JAL-1452 nucleotide/protein default colour; JAL-845 SplitFrame refactor
[jalview.git] / src / jalview / ws / AWSThread.java
1 /*
2  * Jalview - A Sequence Alignment Editor and Viewer (Version 2.8.2)
3  * Copyright (C) 2014 The Jalview Authors
4  * 
5  * This file is part of Jalview.
6  * 
7  * Jalview is free software: you can redistribute it and/or
8  * modify it under the terms of the GNU General Public License 
9  * as published by the Free Software Foundation, either version 3
10  * of the License, or (at your option) any later version.
11  *  
12  * Jalview is distributed in the hope that it will be useful, but 
13  * WITHOUT ANY WARRANTY; without even the implied warranty 
14  * of MERCHANTABILITY or FITNESS FOR A PARTICULAR 
15  * PURPOSE.  See the GNU General Public License for more details.
16  * 
17  * You should have received a copy of the GNU General Public License
18  * along with Jalview.  If not, see <http://www.gnu.org/licenses/>.
19  * The Jalview Authors are detailed in the 'AUTHORS' file.
20  */
21 package jalview.ws;
22
23 import jalview.bin.Cache;
24 import jalview.datamodel.AlignedCodonFrame;
25 import jalview.datamodel.Alignment;
26 import jalview.datamodel.AlignmentI;
27 import jalview.datamodel.AlignmentView;
28 import jalview.datamodel.SequenceI;
29 import jalview.gui.AlignFrame;
30 import jalview.gui.WebserviceInfo;
31 import jalview.util.MessageManager;
32 import jalview.viewmodel.seqfeatures.FeatureRendererSettings;
33
34 import java.util.LinkedHashSet;
35 import java.util.Set;
36
37 public abstract class AWSThread extends Thread
38 {
39
40   /**
41    * view that this job was associated with
42    */
43   protected AlignmentI currentView = null;
44
45   /**
46    * feature settings from view that job was associated with
47    */
48   protected FeatureRendererSettings featureSettings = null;
49
50   /**
51    * metadata about this web service
52    */
53   protected WebserviceInfo wsInfo = null;
54
55   /**
56    * original input data for this job
57    */
58   protected AlignmentView input = null;
59
60   /**
61    * dataset sequence relationships to be propagated onto new results
62    */
63   protected Set<AlignedCodonFrame> codonframe = null;
64
65   /**
66    * are there jobs still running in this thread.
67    */
68   protected boolean jobComplete = false;
69
70   /**
71    * one or more jobs being managed by this thread.
72    */
73   protected AWsJob jobs[] = null;
74
75   /**
76    * full name of service
77    */
78   protected String WebServiceName = null;
79
80   protected char defGapChar = '-';
81
82   /**
83    * header prepended to all output from job
84    */
85   protected String OutputHeader;
86
87   /**
88    * only used when reporting a web service out of memory error - the job ID
89    * will be concatenated to the URL
90    */
91   protected String WsUrl = null;
92
93   private boolean fromSplitFrame;
94
95   /**
96    * generic web service job/subjob poll loop
97    */
98   public void run()
99   {
100     JobStateSummary jstate = null;
101     if (jobs == null)
102     {
103       jobComplete = true;
104     }
105     while (!jobComplete)
106     {
107       jstate = new JobStateSummary();
108       for (int j = 0; j < jobs.length; j++)
109       {
110
111         if (!jobs[j].submitted && jobs[j].hasValidInput())
112         {
113           StartJob(jobs[j]);
114         }
115
116         if (jobs[j].submitted && !jobs[j].subjobComplete)
117         {
118           try
119           {
120             pollJob(jobs[j]);
121             if (!jobs[j].hasResponse())
122             {
123               throw (new Exception(
124                       "Timed out when communicating with server\nTry again later.\n"));
125             }
126             jalview.bin.Cache.log.debug("Job " + j + " Result state "
127                     + jobs[j].getState() + "(ServerError="
128                     + jobs[j].isServerError() + ")");
129           } catch (Exception ex)
130           {
131             // Deal with Transaction exceptions
132             wsInfo.appendProgressText(jobs[j].jobnum, MessageManager
133                     .formatMessage("info.server_exception", new Object[]
134                     { WebServiceName, ex.getMessage() }));
135             // always output the exception's stack trace to the log
136             Cache.log.warn(WebServiceName + " job(" + jobs[j].jobnum
137                     + ") Server exception.");
138             // todo: could limit trace to cause if this is a SOAPFaultException.
139             ex.printStackTrace();
140
141             if (jobs[j].allowedServerExceptions > 0)
142             {
143               jobs[j].allowedServerExceptions--;
144               Cache.log.debug("Sleeping after a server exception.");
145               try
146               {
147                 Thread.sleep(5000);
148               } catch (InterruptedException ex1)
149               {
150               }
151             }
152             else
153             {
154               Cache.log.warn("Dropping job " + j + " " + jobs[j].jobId);
155               jobs[j].subjobComplete = true;
156               wsInfo.setStatus(jobs[j].jobnum,
157                       WebserviceInfo.STATE_STOPPED_SERVERERROR);
158             }
159           } catch (OutOfMemoryError er)
160           {
161             jobComplete = true;
162             jobs[j].subjobComplete = true;
163             jobs[j].clearResponse(); // may contain out of date result data
164             wsInfo.setStatus(jobs[j].jobnum,
165                     WebserviceInfo.STATE_STOPPED_ERROR);
166             Cache.log.error("Out of memory when retrieving Job " + j
167                     + " id:" + WsUrl + "/" + jobs[j].jobId, er);
168             new jalview.gui.OOMWarning("retrieving result for "
169                     + WebServiceName, er);
170             System.gc();
171           }
172         }
173         jstate.updateJobPanelState(wsInfo, OutputHeader, jobs[j]);
174       }
175       // Decide on overall state based on collected jobs[] states
176       updateGlobalStatus(jstate);
177       if (!jobComplete)
178       {
179         try
180         {
181           Thread.sleep(5000);
182         } catch (InterruptedException e)
183         {
184           Cache.log
185                   .debug("Interrupted sleep waiting for next job poll.", e);
186         }
187         // System.out.println("I'm alive "+alTitle);
188       }
189     }
190     if (jobComplete && jobs != null)
191     {
192       parseResult(); // tidy up and make results available to user
193     }
194     else
195     {
196       Cache.log
197               .debug("WebServiceJob poll loop finished with no jobs created.");
198       wsInfo.setStatus(WebserviceInfo.STATE_STOPPED_ERROR);
199       wsInfo.appendProgressText(MessageManager.getString("info.no_jobs_ran"));
200       wsInfo.setFinishedNoResults();
201     }
202   }
203
204   protected void updateGlobalStatus(JobStateSummary jstate)
205   {
206     if (jstate.running > 0)
207     {
208       wsInfo.setStatus(WebserviceInfo.STATE_RUNNING);
209     }
210     else if (jstate.queuing > 0)
211     {
212       wsInfo.setStatus(WebserviceInfo.STATE_QUEUING);
213     }
214     else
215     {
216       jobComplete = true;
217       if (jstate.finished > 0)
218       {
219         wsInfo.setStatus(WebserviceInfo.STATE_STOPPED_OK);
220       }
221       else if (jstate.error > 0)
222       {
223         wsInfo.setStatus(WebserviceInfo.STATE_STOPPED_ERROR);
224       }
225       else if (jstate.serror > 0)
226       {
227         wsInfo.setStatus(WebserviceInfo.STATE_STOPPED_SERVERERROR);
228       }
229     }
230   }
231
232   public AWSThread()
233   {
234     super();
235   }
236
237   public AWSThread(Runnable target)
238   {
239     super(target);
240   }
241
242   public AWSThread(String name)
243   {
244     super(name);
245   }
246
247   public AWSThread(ThreadGroup group, Runnable target)
248   {
249     super(group, target);
250   }
251
252   public AWSThread(ThreadGroup group, String name)
253   {
254     super(group, name);
255   }
256
257   public AWSThread(Runnable target, String name)
258   {
259     super(target, name);
260   }
261
262   public AWSThread(ThreadGroup group, Runnable target, String name)
263   {
264     super(group, target, name);
265   }
266
267   /**
268    * query web service for status of job. on return, job.result must not be null
269    * - if it is then it will be assumed that the job status query timed out and
270    * a server exception will be logged.
271    * 
272    * @param job
273    * @throws Exception
274    *           will be logged as a server exception for this job
275    */
276   public abstract void pollJob(AWsJob job) throws Exception;
277
278   /**
279    * submit job to web service
280    * 
281    * @param job
282    */
283   public abstract void StartJob(AWsJob job);
284
285   /**
286    * process the set of AWsJob objects into a set of results, and tidy up.
287    */
288   public abstract void parseResult();
289
290   /**
291    * helper function to conserve dataset references to sequence objects returned
292    * from web services 1. Propagates AlCodonFrame data from
293    * <code>codonframe</code> to <code>al</code> TODO: refactor to datamodel
294    * 
295    * @param al
296    */
297   public void propagateDatasetMappings(Alignment al)
298   {
299     if (codonframe != null)
300     {
301       SequenceI[] alignment = al.getSequencesArray();
302       for (int sq = 0; sq < alignment.length; sq++)
303       {
304         for (AlignedCodonFrame acf : codonframe)
305         {
306           final SequenceI seq = alignment[sq];
307           if (acf != null && acf.involvesSequence(seq))
308           {
309             al.addCodonFrame(acf);
310             break;
311           }
312         }
313       }
314     }
315   }
316
317   public AWSThread(ThreadGroup group, Runnable target, String name,
318           long stackSize)
319   {
320     super(group, target, name, stackSize);
321   }
322
323   /**
324    * 
325    * @return gap character to use for any alignment generation
326    */
327   public char getGapChar()
328   {
329     return defGapChar;
330   }
331
332   /**
333    * 
334    * @param alignFrame
335    *          reference for copying mappings across
336    * @param wsInfo
337    *          gui attachment point
338    * @param input
339    *          input data for the calculation
340    * @param webServiceName
341    *          name of service
342    * @param wsUrl
343    *          url of the service being invoked
344    */
345   public AWSThread(AlignFrame alignFrame, WebserviceInfo wsinfo,
346           AlignmentView input, String webServiceName, String wsUrl)
347   {
348     this(alignFrame, wsinfo, input, wsUrl);
349     WebServiceName = webServiceName;
350   }
351
352   /**
353    * Extracts additional info from alignment view's context.
354    * 
355    * @param alframe
356    *          - reference for copying mappings and display styles across
357    * @param wsinfo2
358    *          - gui attachment point - may be null
359    * @param alview
360    *          - input data for the calculation
361    * @param wsurl2
362    *          - url of the service being invoked
363    */
364   public AWSThread(AlignFrame alframe, WebserviceInfo wsinfo2,
365           AlignmentView alview, String wsurl2)
366   {
367     super();
368     // this.alignFrame = alframe;
369     this.fromSplitFrame = alframe.getSplitViewContainer() != null;
370     currentView = alframe.getCurrentView().getAlignment();
371     featureSettings = alframe.getFeatureRenderer().getSettings();
372     defGapChar = alframe.getViewport().getGapCharacter();
373     this.wsInfo = wsinfo2;
374     this.input = alview;
375     WsUrl = wsurl2;
376     if (alframe != null)
377     {
378       Set<AlignedCodonFrame> cf = alframe.getViewport().getAlignment()
379               .getCodonFrames();
380       if (cf != null)
381       {
382         codonframe = new LinkedHashSet<AlignedCodonFrame>();
383         codonframe.addAll(cf);
384       }
385     }
386   }
387
388   protected boolean isFromSplitFrame()
389   {
390     return this.fromSplitFrame;
391   }
392 }