JAL-3690 separate startup and poll code in SeqAnnotationCalcWorker
[jalview.git] / src / jalview / ws / jws2 / SeqAnnotationServiceCalcWorker.java
index 661bdf7..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,176 +224,124 @@ public class SeqAnnotationServiceCalcWorker extends AlignCalcWorker
 
   private int min_valid_seqs;
 
-  @Override
-  public void run()
+
+  private long progressId = -1;
+  JobStateSummary job = null;
+  WebserviceInfo info = null;
+  List<SequenceI> seqs = null;
+  
+  @Override public void startUp() throws Throwable
   {
-    if (checkDone())
+    if (alignViewport.isClosed())
     {
+      abortAndDestroy();
       return;
     }
     if (!hasService())
     {
-      calcMan.workerComplete(this);
       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");
-        calcMan.workerComplete(this);
-        return;
-      }
-
-      if (guiProgress != null)
-      {
-        guiProgress.setProgressBar(service.getActionText(),
-                progressId = System.currentTimeMillis());
-      }
-      jalview.bin.Cache.log.debug("submitted " + seqs.size()
-              + " sequences to " + service.getActionText());
+    seqs = getInputSequences(
+            alignViewport.getAlignment(),
+            bySequence ? alignViewport.getSelectionGroup() : null);
 
-      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 (seqs == null || !checkValidInputSeqs(seqs))
+    {
+      jalview.bin.Cache.log.debug(
+              "Sequences for analysis service were null or not valid");
+      return;
+    }
 
-                  @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());
-        }
+    if (guiProgress != null)
+    {
+      guiProgress.setProgressBar(service.getActionText(),
+              progressId = System.currentTimeMillis());
+    }
+    jalview.bin.Cache.log.debug("submitted " + seqs.size()
+            + " sequences to " + service.getActionText());
 
-        if (calcMan.isPending(this) && isInteractiveUpdate())
-        {
-          Cache.log.debug("Analysis service job is stale. aborting.");
-          // job has become stale.
-          if (!finished) {
-            finished = true;
-            // cancel this job and yield to the new job
-            try
-            {
-              if (cancellable
-                        && ((CancellableI) annotService).cancel(running))
-              {
-                System.err.println("Cancelled job: " + rslt);
-              }
-              else
+    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()
               {
-                System.err.println("FAILED TO CANCEL job: " + rslt);
-              }
-  
-            } catch (Exception x)
-            {
-  
-            }
-          }
-          rslt = running.getJobHandle();
-          return;
-        }
 
-        // 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
@@ -424,6 +370,24 @@ public class SeqAnnotationServiceCalcWorker extends AlignCalcWorker
         // sequence, excluding regions not annotated due to gapMap/column
         // visibility
 
+        // update calcId if it is not already set on returned annotation
+        if (returnedAnnot != null)
+        {
+          for (AlignmentAnnotation aa : returnedAnnot)
+          {
+            // assume that any CalcIds already set
+            if (getCalcId() != null && aa.getCalcId() == null
+                    || "".equals(aa.getCalcId()))
+            {
+              aa.setCalcId(getCalcId());
+            }
+            // autocalculated annotation are created by interactive alignment
+            // analysis services
+            aa.autoCalculated = service.isAlignmentAnalysis()
+                    && service.isInteractiveUpdate();
+          }
+        }
+
         running.setAnnotation(returnedAnnot);
 
         if (running.hasResults())
@@ -477,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();
-    } finally
+    }
+    
+    return finished;
+  }
+  
+  @Override public void cancel()
+  {
+    cancelCurrentJob();
+  }
+  
+  @Override public void done()
+  {
+    if (ap != null)
     {
-
-      calcMan.workerComplete(this);
-      if (ap != null)
-      {
-        if (guiProgress != null && progressId != -1)
-        {
-          guiProgress.setProgressBar("", progressId);
-        }
-        // TODO: may not need to paintAlignment again !
-        ap.paintAlignment(false, false);
-      }
-      if (msg.length() > 0)
+      if (guiProgress != null && progressId != -1)
       {
-        // 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);
     }
-
   }
 
   /**
@@ -563,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);
       }
@@ -819,7 +751,7 @@ public class SeqAnnotationServiceCalcWorker extends AlignCalcWorker
       for (SequenceI sq : running.getSeqs())
       {
         if (!sq.getFeatures().hasFeatures()
-                && (sq.getDBRefs() == null || sq.getDBRefs().length == 0))
+                && (sq.getDBRefs() == null || sq.getDBRefs().size() == 0))
         {
           continue;
         }
@@ -871,43 +803,6 @@ public class SeqAnnotationServiceCalcWorker extends AlignCalcWorker
     }
   }
 
-  /**
-   * notify manager that we have started, and wait for a free calculation slot
-   * 
-   * @return true if slot is obtained and work still valid, false if another
-   *         thread has done our work for us.
-   */
-  protected boolean checkDone()
-  {
-    calcMan.notifyStart(this);
-    ap.paintAlignment(false, false);
-    while (!calcMan.notifyWorking(this))
-    {
-      if (calcMan.isWorking(this))
-      {
-        return true;
-      }
-      try
-      {
-        if (ap != null)
-        {
-          ap.paintAlignment(false, false);
-        }
-
-        Thread.sleep(200);
-      } catch (Exception ex)
-      {
-        ex.printStackTrace();
-      }
-    }
-    if (alignViewport.isClosed())
-    {
-      abortAndDestroy();
-      return true;
-    }
-    return false;
-  }
-
   protected void updateOurAnnots(List<AlignmentAnnotation> ourAnnot)
   {
     List<AlignmentAnnotation> our = ourAnnots;