613c702c70883398de442b8395b8b30831d84de9
[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.JobRequest;
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 JobRequest();
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 job = service.submitJob(request);
130     return new JobId(service.getName(), service.getName(), job.getId());
131   }
132
133   @Override
134   public final void updateStatus(WsJob job)
135   {
136     try
137     {
138       var slivkaJob = client.getJob(job.getJobId());
139       job.setState(stateMap.get(slivkaJob.getStatus()));
140     } catch (IOException e)
141     {
142       throw new IOError(e);
143     }
144   }
145
146   @Override
147   public final boolean updateJobProgress(WsJob job) throws IOException
148   {      
149     var slivkaJob = client.getJob(job.getJobId());
150     Collection<RemoteFile> files = slivkaJob.getResults();
151     RemoteFile logFile=null;
152     for (RemoteFile f : files)
153     {
154       if (f.getLabel().equals("log"))
155       {
156         logFile = f; break;
157       }
158     }
159
160     boolean newContent = false;
161     if (logFile!=null)
162     {
163       ByteArrayOutputStream output = new ByteArrayOutputStream();
164       logFile.writeTo(output);
165       if (output.size() > job.getNextChunk())
166       {
167         newContent = true;
168         job.setStatus(output.toString("UTF-8"));
169         job.setnextChunk(output.size());
170       }
171     }
172     if (failedStates.contains(job.getJobState()))
173     {
174       
175       RemoteFile errLogFile = null;
176       for (RemoteFile f : files)
177       {
178         if (f.getLabel().equals("error-log"))
179         {
180           errLogFile = f;
181           break;
182         }
183       }
184
185       if (errLogFile!=null)
186       {
187         ByteArrayOutputStream output = new ByteArrayOutputStream();
188         errLogFile.writeTo(output);
189         if (output.size() > 0)
190         {
191           newContent = true;
192           job.setStatus(job.getStatus() + "\n" + output.toString("UTF-8"));
193         }
194       }
195     }
196     return newContent;
197   }
198
199   @Override
200   public final boolean handleSubmitError(Throwable _lex, WsJob j, WebserviceInfo wsInfo)
201   {
202     if (_lex instanceof ClientProtocolException)
203     {
204       j.setState(WsJob.JobState.INVALID);
205       j.setStatus(_lex.getMessage());
206       return true;
207     }
208     return false;
209   }
210
211   @Override
212   public final boolean handleCollectionException(Exception e, WsJob msjob, WebserviceInfo wsInfo)
213   {
214     // TODO
215     return false;
216   }
217
218   final SlivkaService getService()
219   {
220     return service;
221   }
222
223   @Override
224   public final Object getEndpoint()
225   {
226     return this;
227   }
228
229   @Override
230   public final void initParamStore(ParamManager userParameterStore)
231   {
232     if (store == null)
233     {
234       store = new SlivkaDatastore(service);
235     }
236   }
237
238   @Override
239   public boolean hasParameters()
240   {
241     return true;
242   }
243
244   @Override
245   public final ParamDatastoreI getParamStore()
246   {
247     if (store == null)
248     {
249       initParamStore(null);
250     }
251     return store;
252   }
253   
254   public static AlignmentI readAlignment(RemoteFile f) throws IOException
255   {
256     final var mimetype = f.getMediaType();
257     FileFormat format;
258     if (mimetype.equals("application/clustal"))
259       format = FileFormat.Clustal;
260     else if (mimetype.equals("application/fasta"))
261       format = FileFormat.Fasta;
262     else
263       return null;
264     return new FormatAdapter().readFile(f.getContentUrl().toString(),
265         DataSourceType.URL, format);
266   }
267
268 }