JAL-3690 separate startup and poll code in SeqAnnotationCalcWorker
[jalview.git] / src / jalview / ws / jws2 / SeqAnnotationServiceCalcWorker.java
index ae03dfb..53b790d 100644 (file)
@@ -26,6 +26,7 @@ import jalview.analysis.SeqsetUtils;
 import jalview.api.AlignViewportI;
 import jalview.api.AlignmentViewPanel;
 import jalview.api.FeatureColourI;
+import jalview.api.PollableAlignCalcWorkerI;
 import jalview.bin.Cache;
 import jalview.datamodel.AlignmentAnnotation;
 import jalview.datamodel.AlignmentI;
@@ -64,7 +65,7 @@ import java.util.List;
 import java.util.Map;
 
 public class SeqAnnotationServiceCalcWorker extends AlignCalcWorker
-        implements WSAnnotationCalcManagerI
+        implements WSAnnotationCalcManagerI, PollableAlignCalcWorkerI
 {
 
   protected ServiceWithParameters service;
@@ -162,17 +163,11 @@ public class SeqAnnotationServiceCalcWorker extends AlignCalcWorker
     return gapMap;
   }
 
-  public SeqAnnotationServiceCalcWorker(AlignViewportI alignViewport,
-          AlignmentViewPanel alignPanel)
-  {
-    super(alignViewport, alignPanel);
-  }
-
   public SeqAnnotationServiceCalcWorker(ServiceWithParameters service,
           AlignFrame alignFrame,
           WsParamSetI preset, List<ArgumentI> paramset)
   {
-    this(alignFrame.getCurrentView(), alignFrame.alignPanel);
+    super(alignFrame.getCurrentView(), alignFrame.alignPanel);
     // TODO: both these fields needed ?
     this.alignFrame = alignFrame;
     this.guiProgress = alignFrame;
@@ -185,6 +180,7 @@ public class SeqAnnotationServiceCalcWorker extends AlignCalcWorker
               .getEndpoint();
     } catch (ClassCastException cce)
     {
+      annotService = null;
       JvOptionPane.showMessageDialog(Desktop.desktop,
               MessageManager.formatMessage(
                       "label.service_called_is_not_an_annotation_service",
@@ -194,6 +190,7 @@ public class SeqAnnotationServiceCalcWorker extends AlignCalcWorker
               JvOptionPane.WARNING_MESSAGE);
 
     }
+    cancellable = CancellableI.class.isInstance(annotService);
     // configure submission flags
     proteinAllowed = service.isProteinService();
     nucleotidesAllowed = service.isNucleotideService();
@@ -218,7 +215,8 @@ public class SeqAnnotationServiceCalcWorker extends AlignCalcWorker
     return annotService != null;
   }
 
-  protected jalview.ws.api.SequenceAnnotationServiceI annotService = null;
+  protected SequenceAnnotationServiceI annotService;
+  protected final boolean cancellable;
 
   volatile JobId rslt = null;
 
@@ -226,8 +224,13 @@ public class SeqAnnotationServiceCalcWorker extends AlignCalcWorker
 
   private int min_valid_seqs;
 
-  @Override
-  public void run() throws Exception
+
+  private long progressId = -1;
+  JobStateSummary job = null;
+  WebserviceInfo info = null;
+  List<SequenceI> seqs = null;
+  
+  @Override public void startUp() throws Throwable
   {
     if (alignViewport.isClosed())
     {
@@ -239,134 +242,106 @@ public class SeqAnnotationServiceCalcWorker extends AlignCalcWorker
       return;
     }
 
-    long progressId = -1;
-
-    int serverErrorsLeft = 3;
-    final boolean cancellable = CancellableI.class
-            .isAssignableFrom(annotService.getClass());
     StringBuffer msg = new StringBuffer();
-    JobStateSummary job = new JobStateSummary();
-    WebserviceInfo info = new WebserviceInfo("foo", "bar", false);
-    try
-    {
-      List<SequenceI> seqs = getInputSequences(
-              alignViewport.getAlignment(),
-              bySequence ? alignViewport.getSelectionGroup() : null);
+    job = new JobStateSummary();
+    info = new WebserviceInfo("foo", "bar", false);
 
-      if (seqs == null || !checkValidInputSeqs(seqs))
-      {
-        jalview.bin.Cache.log.debug(
-                "Sequences for analysis service were null or not valid");
-        return;
-      }
+    seqs = getInputSequences(
+            alignViewport.getAlignment(),
+            bySequence ? alignViewport.getSelectionGroup() : null);
 
-      if (guiProgress != null)
-      {
-        guiProgress.setProgressBar(service.getActionText(),
-                progressId = System.currentTimeMillis());
-      }
-      jalview.bin.Cache.log.debug("submitted " + seqs.size()
-              + " sequences to " + service.getActionText());
+    if (seqs == null || !checkValidInputSeqs(seqs))
+    {
+      jalview.bin.Cache.log.debug(
+              "Sequences for analysis service were null or not valid");
+      return;
+    }
 
-      rslt = annotService.submitToService(seqs, getPreset(),
-              getArguments());
-      if (rslt == null)
-      {
-        return;
-      }
-      // TODO: handle job submission error reporting here.
-      Cache.log.debug("Service " + service.getUri() + "\nSubmitted job ID: "
-              + rslt);
-      ;
-      // ///
-      // otherwise, construct WsJob and any UI handlers
-      running = new AnnotationWsJob();
-      running.setJobHandle(rslt);
-      running.setSeqNames(seqNames);
-      running.setStartPos(start);
-      running.setSeqs(seqs);
-      job.updateJobPanelState(info, "", running);
-      if (guiProgress != null)
-      {
-        guiProgress.registerHandler(progressId,
-                new IProgressIndicatorHandler()
-                {
+    if (guiProgress != null)
+    {
+      guiProgress.setProgressBar(service.getActionText(),
+              progressId = System.currentTimeMillis());
+    }
+    jalview.bin.Cache.log.debug("submitted " + seqs.size()
+            + " sequences to " + service.getActionText());
 
-                  @Override
-                  public boolean cancelActivity(long id)
-                  {
-                    ((CancellableI) annotService).cancel(running);
-                    return true;
-                  }
-
-                  @Override
-                  public boolean canCancel()
-                  {
-                    return cancellable;
-                  }
-                });
-      }
-      
-      // ///
-      // and poll for updates until job finishes, fails or becomes stale
-      
-      boolean finished = false;
-      do
-      {
-        Cache.log.debug("Updating status for annotation service.");
-        annotService.updateStatus(running);
-        job.updateJobPanelState(info, "", running);
-        if (running.isSubjobComplete())
-        {
-          Cache.log.debug(
-                  "Finished polling analysis service job: status reported is "
-                          + running.getState());
-          finished = true;
-        }
-        else
-        {
-          Cache.log.debug("Status now " + running.getState());
-        }
+    rslt = annotService.submitToService(seqs, getPreset(),
+            getArguments());
+    if (rslt == null)
+    {
+      return;
+    }
+    // TODO: handle job submission error reporting here.
+    Cache.log.debug("Service " + service.getUri() + "\nSubmitted job ID: "
+            + rslt);
+    ;
+    // ///
+    // otherwise, construct WsJob and any UI handlers
+    running = new AnnotationWsJob();
+    running.setJobHandle(rslt);
+    running.setSeqNames(seqNames);
+    running.setStartPos(start);
+    running.setSeqs(seqs);
+    job.updateJobPanelState(info, "", running);
+    if (guiProgress != null)
+    {
+      guiProgress.registerHandler(progressId,
+              new IProgressIndicatorHandler()
+              {
 
-        // pull any stats - some services need to flush log output before
-        // results are available
-        Cache.log.debug("Updating progress log for annotation service.");
+                @Override
+                public boolean cancelActivity(long id)
+                {
+                  calcMan.cancelWorker(SeqAnnotationServiceCalcWorker.this);
+                  return true;
+                }
 
-        try
-        {
-          annotService.updateJobProgress(running);
-        } catch (Throwable thr)
-        {
-          Cache.log.debug("Ignoring exception during progress update.",
-                  thr);
-        }
-        Cache.log.trace("Result of poll: " + running.getStatus());
+                @Override
+                public boolean canCancel()
+                {
+                  return cancellable;
+                }
+              });
+    }
+  }
+  
+  @Override public boolean poll() throws Throwable
+  {
+    boolean finished = false;
+    
+    Cache.log.debug("Updating status for annotation service.");
+    annotService.updateStatus(running);
+    job.updateJobPanelState(info, "", running);
+    if (running.isSubjobComplete())
+    {
+      Cache.log.debug(
+              "Finished polling analysis service job: status reported is "
+                      + running.getState());
+      finished = true;
+    }
+    else
+    {
+      Cache.log.debug("Status now " + running.getState());
+    }
 
-        if (!finished && !running.isFailed())
-        {
-          try
-          {
-            Cache.log.debug("Analysis service job thread sleeping.");
-            Thread.sleep(200);
-            Cache.log.debug("Analysis service job thread woke.");
-          } catch (InterruptedException x)
-          {
-          }
-          ;
-        }
-      } while (!finished);
+    // pull any stats - some services need to flush log output before
+    // results are available
+    Cache.log.debug("Updating progress log for annotation service.");
 
+    try
+    {
+      annotService.updateJobProgress(running);
+    } catch (Throwable thr)
+    {
+      Cache.log.debug("Ignoring exception during progress update.",
+              thr);
+    }
+    Cache.log.trace("Result of poll: " + running.getStatus());
+    
+    
+    if (finished)
+    {
       Cache.log.debug("Job poll loop exited. Job is " + running.getState());
-      // TODO: need to poll/retry
-      if (serverErrorsLeft > 0)
-      {
-        try
-        {
-          Thread.sleep(200);
-        } catch (InterruptedException x)
-        {
-        }
-      }
       if (running.isFinished())
       {
         // expect there to be results to collect
@@ -466,60 +441,28 @@ public class SeqAnnotationServiceCalcWorker extends AlignCalcWorker
         }
       }
       Cache.log.debug("Annotation Service Worker thread finished.");
-    }
-// TODO: use service specitic exception handlers
-//    catch (JobSubmissionException x)
-//    {
-//
-//      System.err.println(
-//              "submission error with " + getServiceActionText() + " :");
-//      x.printStackTrace();
-//      calcMan.disableWorker(this);
-//    } catch (ResultNotAvailableException x)
-//    {
-//      System.err.println("collection error:\nJob ID: " + rslt);
-//      x.printStackTrace();
-//      calcMan.disableWorker(this);
-//
-//    } catch (OutOfMemoryError error)
-//    {
-//      calcMan.disableWorker(this);
-//
-//      ap.raiseOOMWarning(getServiceActionText(), error);
-//    } 
-    catch (Throwable x)
-    {
-      calcMan.disableWorker(this);
 
-      System.err
-              .println("Blacklisting worker due to unexpected exception:");
-      x.printStackTrace();
-      throw new Exception(x);
-    } finally
+    }
+    
+    return finished;
+  }
+  
+  @Override public void cancel()
+  {
+    cancelCurrentJob();
+  }
+  
+  @Override public void done()
+  {
+    if (ap != null)
     {
-
-      if (ap != null)
+      if (guiProgress != null && progressId != -1)
       {
-        if (guiProgress != null && progressId != -1)
-        {
-          guiProgress.setProgressBar("", progressId);
-        }
-        // TODO: may not need to paintAlignment again !
-        ap.paintAlignment(false, false);
-      }
-      if (msg.length() > 0)
-      {
-        // TODO: stash message somewhere in annotation or alignment view.
-        // code below shows result in a text box popup
-        /*
-         * jalview.gui.CutAndPasteTransfer cap = new
-         * jalview.gui.CutAndPasteTransfer(); cap.setText(msg.toString());
-         * jalview.gui.Desktop.addInternalFrame(cap,
-         * "Job Status for "+getServiceActionText(), 600, 400);
-         */
+        guiProgress.removeProgressBar(progressId);
       }
+      // TODO: may not need to paintAlignment again !
+      ap.paintAlignment(false, false);
     }
-
   }
 
   /**
@@ -552,7 +495,7 @@ public class SeqAnnotationServiceCalcWorker extends AlignCalcWorker
     try
     {
       String id = running.getJobId();
-      if (((CancellableI) annotService).cancel(running))
+      if (cancellable && ((CancellableI) annotService).cancel(running))
       {
         System.err.println("Cancelled job " + id);
       }