header updated
[jalview.git] / src / jalview / ws / WSThread.java
1 /*
2  * Jalview - A Sequence Alignment Editor and Viewer
3  * Copyright (C) 2006 AM Waterhouse, J Procter, G Barton, M Clamp, S Searle
4  *
5  * This program is free software; you can redistribute it and/or
6  * modify it under the terms of the GNU General Public License
7  * as published by the Free Software Foundation; either version 2
8  * of the License, or (at your option) any later version.
9  *
10  * This program is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13  * GNU General Public License for more details.
14  *
15  * You should have received a copy of the GNU General Public License
16  * along with this program; if not, write to the Free Software
17  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA
18  */
19  package jalview.ws;
20
21 import jalview.gui.AlignFrame;
22 import jalview.gui.WebserviceInfo;
23 import jalview.datamodel.AlignmentView;
24 import jalview.gui.Desktop;
25 import javax.swing.JOptionPane;
26 import jalview.bin.Cache;
27
28 public abstract class WSThread extends Thread
29 {
30     /**
31      * Generic properties for Web Service Client threads.
32      */
33     AlignFrame alignFrame=null;
34   WebserviceInfo wsInfo = null;
35   AlignmentView input=null;
36   boolean jobComplete = false;
37   abstract class WSJob {
38       /**
39        * Generic properties for an individual job within a Web Service Client thread
40        */
41     int jobnum = 0; // WebServiceInfo pane for this job
42     String jobId; // ws job ticket
43     boolean cancelled = false;
44     int allowedServerExceptions = 3; // job dies if too many exceptions.
45     boolean submitted = false;
46     boolean subjobComplete = false;
47     /**
48      *
49      * @return true if job has completed and valid results are available
50      */
51     abstract boolean hasResults();
52     /**
53      *
54      * @return boolean true if job can be submitted.
55      */
56     abstract boolean hasValidInput();
57     vamsas.objects.simple.Result result;
58   }
59   class JobStateSummary {
60     int running = 0;
61     int queuing = 0;
62     int finished = 0;
63     int error = 0;
64     int serror = 0;
65     int cancelled = 0;
66     int results = 0;
67     void updateJobPanelState(WebserviceInfo wsInfo, String OutputHeader,
68                              WSJob j)
69     {
70       if (j.result != null)
71       {
72         String progheader = "";
73         // Parse state of job[j]
74         if (j.result.isRunning())
75         {
76           running++;
77           wsInfo.setStatus(j.jobnum, WebserviceInfo.STATE_RUNNING);
78         }
79         else if (j.result.isQueued())
80         {
81           queuing++;
82           wsInfo.setStatus(j.jobnum, WebserviceInfo.STATE_QUEUING);
83         }
84         else if (j.result.isFinished())
85         {
86           finished++;
87           j.subjobComplete = true;
88           if (j.hasResults())
89             results++;
90           wsInfo.setStatus(j.jobnum, WebserviceInfo.STATE_STOPPED_OK);
91         }
92         else if (j.result.isFailed())
93         {
94           progheader += "Job failed.\n";
95           j.subjobComplete = true;
96           wsInfo.setStatus(j.jobnum, WebserviceInfo.STATE_STOPPED_ERROR);
97           error++;
98         }
99         else if (j.result.isServerError())
100         {
101           serror++;
102           j.subjobComplete = true;
103           wsInfo.setStatus(j.jobnum,
104                            WebserviceInfo.STATE_STOPPED_SERVERERROR);
105         }
106         else if (j.result.isBroken() || j.result.isFailed())
107         {
108           error++;
109           j.subjobComplete = true;
110           wsInfo.setStatus(j.jobnum, WebserviceInfo.STATE_STOPPED_ERROR);
111         }
112         // and pass on any sub-job messages to the user
113         wsInfo.setProgressText(j.jobnum, OutputHeader);
114         wsInfo.appendProgressText(j.jobnum, progheader);
115         if (j.result.getStatus() != null)
116         {
117           wsInfo.appendProgressText(j.jobnum, j.result.getStatus());
118         }
119       }
120       else
121       {
122         if (j.submitted && j.subjobComplete)
123         {
124           if (j.allowedServerExceptions == 0)
125           {
126             serror++;
127           }
128           else if (j.result == null)
129           {
130             error++;
131           }
132         }
133       }
134     }
135   }
136
137   WSJob jobs[] = null;
138   String WebServiceName = null;
139   String OutputHeader;
140   String WsUrl = null;
141   abstract void pollJob(WSJob job) throws Exception;
142   public void run()
143   {
144   JobStateSummary jstate=null;
145   if (jobs==null)
146     jobComplete=true;
147   while (!jobComplete)
148   {
149     jstate = new JobStateSummary();
150     for (int j = 0; j < jobs.length; j++)
151     {
152
153       if (!jobs[j].submitted && jobs[j].hasValidInput())
154       {
155         StartJob(jobs[j]);
156       }
157
158       if (jobs[j].submitted && !jobs[j].subjobComplete)
159       {
160         try
161         {
162           pollJob(jobs[j]);
163           if (jobs[j].result == null)
164           {
165             throw (new Exception(
166                 "Timed out when communicating with server\nTry again later.\n"));
167           }
168           jalview.bin.Cache.log.debug("Job " + j + " Result state " +
169                                       jobs[j].result.getState()
170                                       + "(ServerError=" +
171                                       jobs[j].result.isServerError() + ")");
172         }
173         catch (Exception ex)
174         {
175           // Deal with Transaction exceptions
176           wsInfo.appendProgressText(jobs[j].jobnum, "\n" + WebServiceName
177                                     + " Server exception!\n" + ex.getMessage());
178           Cache.log.warn(WebServiceName + " job(" + jobs[j].jobnum
179                          + ") Server exception: " + ex.getMessage());
180
181           if (jobs[j].allowedServerExceptions > 0)
182           {
183             jobs[j].allowedServerExceptions--;
184             Cache.log.debug("Sleeping after a server exception.");
185             try
186             {
187               Thread.sleep(5000);
188             }
189             catch (InterruptedException ex1)
190             {
191             }
192           }
193           else
194           {
195             Cache.log.warn("Dropping job " + j + " " + jobs[j].jobId);
196             jobs[j].subjobComplete = true;
197             wsInfo.setStatus(jobs[j].jobnum,
198                              WebserviceInfo.STATE_STOPPED_SERVERERROR);
199           }
200         }
201         catch (OutOfMemoryError er)
202         {
203           jobComplete = true;
204           jobs[j].subjobComplete = true;
205           jobs[j].result = null; // may contain out of date result object
206           wsInfo.setStatus(jobs[j].jobnum,
207                            WebserviceInfo.STATE_STOPPED_ERROR);
208           JOptionPane
209               .showInternalMessageDialog(
210                   Desktop.desktop,
211                   "Out of memory handling result for job !!"
212                   +
213               "\nSee help files for increasing Java Virtual Machine memory.",
214                   "Out of memory", JOptionPane.WARNING_MESSAGE);
215           Cache.log.error("Out of memory when retrieving Job " + j + " id:" +
216                           WsUrl + "/" + jobs[j].jobId, er);
217           System.gc();
218         }
219       }
220       jstate.updateJobPanelState(wsInfo, OutputHeader, jobs[j]);
221     }
222     // Decide on overall state based on collected jobs[] states
223     if (jstate.running > 0)
224     {
225       wsInfo.setStatus(WebserviceInfo.STATE_RUNNING);
226     }
227     else if (jstate.queuing > 0)
228     {
229       wsInfo.setStatus(WebserviceInfo.STATE_QUEUING);
230     }
231     else
232     {
233       jobComplete = true;
234       if (jstate.finished > 0)
235       {
236         wsInfo.setStatus(WebserviceInfo.STATE_STOPPED_OK);
237       }
238       else if (jstate.error > 0)
239       {
240         wsInfo.setStatus(WebserviceInfo.STATE_STOPPED_ERROR);
241       }
242       else if (jstate.serror > 0)
243       {
244         wsInfo.setStatus(WebserviceInfo.STATE_STOPPED_SERVERERROR);
245       }
246     }
247     if (!jobComplete)
248     {
249       try
250       {
251         Thread.sleep(5000);
252       }
253       catch (InterruptedException e)
254       {
255         Cache.log.debug("Interrupted sleep waiting for next job poll.", e);
256       }
257       // System.out.println("I'm alive "+alTitle);
258     }
259   }
260   if (jobComplete && jobs!=null)
261   {
262     parseResult(); // tidy up and make results available to user
263   } else {
264     Cache.log.debug("WebServiceJob poll loop finished with no jobs created.");
265   }
266 }
267 abstract void StartJob(WSJob job);
268 abstract void parseResult();
269 }