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