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