Merge branch 'mmw/JAL-4199-web-services-testing' into development/Release_2_12_Branch
[jalview.git] / src / jalview / ws / slivkaws / SlivkaWSInstance.java
1 package jalview.ws.slivkaws;
2
3 import java.io.ByteArrayInputStream;
4 import java.io.ByteArrayOutputStream;
5 import java.io.IOError;
6 import java.io.IOException;
7 import java.io.InputStream;
8 import java.util.Arrays;
9 import java.util.EnumMap;
10 import java.util.HashSet;
11 import java.util.List;
12 import java.util.Set;
13
14 import jalview.datamodel.AlignmentI;
15 import jalview.datamodel.SequenceI;
16 import jalview.gui.WebserviceInfo;
17 import jalview.io.DataSourceType;
18 import jalview.io.FileFormat;
19 import jalview.io.FormatAdapter;
20 import jalview.ws.api.JalviewServiceEndpointProviderI;
21 import jalview.ws.api.JalviewWebServiceI;
22 import jalview.ws.api.JobId;
23 import jalview.ws.api.ServiceWithParameters;
24 import jalview.ws.gui.WsJob;
25 import jalview.ws.params.ArgumentI;
26 import jalview.ws.params.ParamDatastoreI;
27 import jalview.ws.params.ParamManager;
28 import jalview.ws.params.WsParamSetI;
29 import javajs.http.ClientProtocolException;
30
31 import java.util.Collection;
32 import uk.ac.dundee.compbio.slivkaclient.Job;
33 import uk.ac.dundee.compbio.slivkaclient.RequestValues;
34 import uk.ac.dundee.compbio.slivkaclient.Parameter;
35 import uk.ac.dundee.compbio.slivkaclient.RemoteFile;
36 import uk.ac.dundee.compbio.slivkaclient.SlivkaClient;
37 import uk.ac.dundee.compbio.slivkaclient.SlivkaService;
38
39 public abstract class SlivkaWSInstance extends ServiceWithParameters
40     implements JalviewServiceEndpointProviderI, JalviewWebServiceI
41 {
42   protected final SlivkaClient client;
43
44   protected final SlivkaService service;
45
46   protected SlivkaDatastore store = null;
47
48   protected static final EnumMap<Job.Status, WsJob.JobState> stateMap = new EnumMap<>(Job.Status.class);
49   {
50     stateMap.put(Job.Status.PENDING, WsJob.JobState.QUEUED);
51     stateMap.put(Job.Status.REJECTED, WsJob.JobState.INVALID);
52     stateMap.put(Job.Status.ACCEPTED, WsJob.JobState.QUEUED);
53     stateMap.put(Job.Status.QUEUED, WsJob.JobState.QUEUED);
54     stateMap.put(Job.Status.RUNNING, WsJob.JobState.RUNNING);
55     stateMap.put(Job.Status.COMPLETED, WsJob.JobState.FINISHED);
56     stateMap.put(Job.Status.INTERRUPTED, WsJob.JobState.CANCELLED);
57     stateMap.put(Job.Status.DELETED, WsJob.JobState.CANCELLED);
58     stateMap.put(Job.Status.FAILED, WsJob.JobState.FAILED);
59     stateMap.put(Job.Status.ERROR, WsJob.JobState.SERVERERROR);
60     stateMap.put(Job.Status.UNKNOWN, WsJob.JobState.UNKNOWN);
61   }
62   protected final Set<WsJob.JobState> failedStates = new HashSet<>(Arrays.asList(
63       WsJob.JobState.INVALID, WsJob.JobState.BROKEN, WsJob.JobState.FAILED,
64       WsJob.JobState.SERVERERROR, WsJob.JobState.CANCELLED
65   ));
66
67   public SlivkaWSInstance(SlivkaClient client, SlivkaService service, String action)
68   {
69     super(action, action, service.getName(), "Slivka", client.getUrl().toString());
70     this.client = client;
71     this.service = service;
72   }
73
74   protected final JobId submit(List<SequenceI> sequences,
75           WsParamSetI preset, List<ArgumentI> args) throws Throwable
76   {
77     var parameters = service.getParameters();
78     var request = new RequestValues();
79     for (Parameter param : parameters)
80     {
81       if (param instanceof Parameter.FileParameter)
82       {
83         FormatAdapter fa = new FormatAdapter();
84         fa.setNewlineString("\r\n");
85         Parameter.FileParameter fileParam = (Parameter.FileParameter) param;
86         FileFormat format;
87         switch (fileParam.getMediaType())
88         {
89         case "application/pfam":
90           format = FileFormat.Pfam;
91           break;
92         case "application/stockholm":
93           format = FileFormat.Stockholm;
94           break;
95         default:
96         case "application/fasta":
97           format = FileFormat.Fasta;
98           break;
99         }
100         
101         // we avoid any use of Jalview's user facing export routines here
102         
103         InputStream stream = new ByteArrayInputStream(format.getWriter(null)
104                 .print(sequences.toArray(new SequenceI[0]), false)
105                 .getBytes());
106         request.addFile(param.getId(), stream);
107       }
108     }
109     if (args != null)
110     {
111       for (ArgumentI arg : args)
112       {
113         // multiple choice field names are name$number to avoid duplications
114         // the number is stripped here
115         String paramId = arg.getName().split("\\$", 2)[0];
116         Parameter param = service.getParameter(paramId);
117         if (param instanceof Parameter.FlagParameter) {
118           if (arg.getValue() != null && !arg.getValue().isBlank())
119             request.addData(paramId, true);
120           else
121             request.addData(paramId, false);
122         }
123         else
124         {
125           request.addData(paramId, arg.getValue());
126         }
127       }
128     }
129     var jobId = client.submitJob(service, request);
130     return new JobId(service.getName(), service.getName(), jobId);
131   }
132
133   @Override
134   public final void updateStatus(WsJob job)
135   {
136     try
137     {
138       job.setState(stateMap.get(client.fetchJobStatus(job.getJobId())));
139     } catch (IOException e)
140     {
141       throw new IOError(e);
142     }
143   }
144
145   @Override
146   public final boolean updateJobProgress(WsJob job) throws IOException
147   {      
148     Collection<RemoteFile> files = client.fetchFilesList(job.getJobId());
149     RemoteFile logFile=null;
150     for (RemoteFile f : files)
151     {
152       if (f.getLabel().equals("log"))
153       {
154         logFile = f; break;
155       }
156     }
157
158     boolean newContent = false;
159     if (logFile!=null)
160     {
161       ByteArrayOutputStream output = new ByteArrayOutputStream();
162       client.writeFileTo(logFile, output);
163       if (output.size() > job.getNextChunk())
164       {
165         newContent = true;
166         job.setStatus(output.toString("UTF-8"));
167         job.setnextChunk(output.size());
168       }
169     }
170     if (failedStates.contains(job.getJobState()))
171     {
172       
173       RemoteFile errLogFile = null;
174       for (RemoteFile f : files)
175       {
176         if (f.getLabel().equals("error-log"))
177         {
178           errLogFile = f;
179           break;
180         }
181       }
182
183       if (errLogFile!=null)
184       {
185         ByteArrayOutputStream output = new ByteArrayOutputStream();
186         client.writeFileTo(errLogFile, output);
187         if (output.size() > 0)
188         {
189           newContent = true;
190           job.setStatus(job.getStatus() + "\n" + output.toString("UTF-8"));
191         }
192       }
193     }
194     return newContent;
195   }
196
197   @Override
198   public final boolean handleSubmitError(Throwable _lex, WsJob j, WebserviceInfo wsInfo)
199   {
200     if (_lex instanceof ClientProtocolException)
201     {
202       j.setState(WsJob.JobState.INVALID);
203       j.setStatus(_lex.getMessage());
204       return true;
205     }
206     return false;
207   }
208
209   @Override
210   public final boolean handleCollectionException(Exception e, WsJob msjob, WebserviceInfo wsInfo)
211   {
212     // TODO
213     return false;
214   }
215
216   final SlivkaService getService()
217   {
218     return service;
219   }
220
221   @Override
222   public final Object getEndpoint()
223   {
224     return this;
225   }
226
227   @Override
228   public final void initParamStore(ParamManager userParameterStore)
229   {
230     if (store == null)
231     {
232       store = new SlivkaDatastore(service);
233     }
234   }
235
236   @Override
237   public boolean hasParameters()
238   {
239     return true;
240   }
241
242   @Override
243   public final ParamDatastoreI getParamStore()
244   {
245     if (store == null)
246     {
247       initParamStore(null);
248     }
249     return store;
250   }
251   
252   public static AlignmentI readAlignment(RemoteFile f) throws IOException
253   {
254     final var mimetype = f.getMediaType();
255     FileFormat format;
256     if (mimetype.equals("application/clustal"))
257       format = FileFormat.Clustal;
258     else if (mimetype.equals("application/fasta"))
259       format = FileFormat.Fasta;
260     else
261       return null;
262     return new FormatAdapter().readFile(f.getContentUrl().toString(),
263         DataSourceType.URL, format);
264   }
265
266 }