Merge branch 'improvement/JAL-4111_suffixed_DEVELOP_channels' into development/Releas...
[jalview.git] / src / jalview / ws / jws2 / Jws2Discoverer.java
index d11174e..56a4b77 100644 (file)
 package jalview.ws.jws2;
 
 import jalview.bin.Cache;
+import jalview.bin.Console;
+import jalview.bin.ApplicationSingletonProvider;
+import jalview.bin.ApplicationSingletonProvider.ApplicationSingletonI;
 import jalview.gui.AlignFrame;
 import jalview.util.MessageManager;
-import jalview.ws.WSMenuEntryProviderI;
+import jalview.ws.ServiceChangeListener;
+import jalview.ws.WSDiscovererI;
 import jalview.ws.api.ServiceWithParameters;
 import jalview.ws.jws2.jabaws2.Jws2Instance;
 import jalview.ws.params.ParamDatastoreI;
@@ -34,11 +38,17 @@ import java.beans.PropertyChangeSupport;
 import java.net.MalformedURLException;
 import java.net.URL;
 import java.util.ArrayList;
+import java.util.Collections;
 import java.util.HashSet;
 import java.util.List;
 import java.util.Set;
 import java.util.StringTokenizer;
 import java.util.Vector;
+import java.util.concurrent.CompletableFuture;
+import java.util.concurrent.CopyOnWriteArraySet;
+import java.util.concurrent.ExecutionException;
+import java.util.concurrent.Future;
+import java.util.concurrent.FutureTask;
 
 import javax.swing.JMenu;
 
@@ -51,8 +61,18 @@ import compbio.ws.client.Services;
  * @author JimP
  * 
  */
-public class Jws2Discoverer implements Runnable, WSMenuEntryProviderI
+public class Jws2Discoverer implements WSDiscovererI, Runnable, ApplicationSingletonI
 {
+  /**
+   * Returns the singleton instance of this class.
+   * 
+   * @return
+   */
+  public static Jws2Discoverer getInstance()
+  {
+    return (Jws2Discoverer) ApplicationSingletonProvider
+            .getInstance(Jws2Discoverer.class);
+  }
   public static final String COMPBIO_JABAWS = "http://www.compbio.dundee.ac.uk/jabaws";
 
   /*
@@ -61,20 +81,15 @@ public class Jws2Discoverer implements Runnable, WSMenuEntryProviderI
   private final static String JWS2HOSTURLS = "JWS2HOSTURLS";
 
   /*
-   * Singleton instance
-   */
-  private static Jws2Discoverer discoverer;
-
-  /*
    * Override for testing only
    */
-  private static List<String> testUrls = null;
+  private List<String> testUrls = null;
 
   // preferred url has precedence over others
   private String preferredUrl;
 
-  private PropertyChangeSupport changeSupport = new PropertyChangeSupport(
-          this);
+  
+  private Set<ServiceChangeListener> serviceListeners = new CopyOnWriteArraySet<>();
 
   private Vector<String> invalidServiceUrls = null;
 
@@ -86,7 +101,8 @@ public class Jws2Discoverer implements Runnable, WSMenuEntryProviderI
 
   private volatile boolean aborted = false;
 
-  private Thread oldthread = null;
+  
+  private volatile Thread oldthread = null;
 
   /**
    * holds list of services.
@@ -100,28 +116,24 @@ public class Jws2Discoverer implements Runnable, WSMenuEntryProviderI
   {
   }
 
-  /**
-   * change listeners are notified of "services" property changes
-   * 
-   * @param listener
-   *          to be added that consumes new services Hashtable object.
-   */
-  public void addPropertyChangeListener(
-          java.beans.PropertyChangeListener listener)
+  @Override
+  public void addServiceChangeListener(ServiceChangeListener listener)
   {
-    changeSupport.addPropertyChangeListener(listener);
+    serviceListeners.add(listener);
   }
 
-  /**
-   * 
-   * 
-   * @param listener
-   *          to be removed
-   */
-  public void removePropertyChangeListener(
-          java.beans.PropertyChangeListener listener)
+  @Override
+  public void removeServiceChangeListener(ServiceChangeListener listener)
+  {
+    serviceListeners.remove(listener);
+  }
+
+  private void notifyServiceListeners(List<? extends ServiceWithParameters> services) 
   {
-    changeSupport.removePropertyChangeListener(listener);
+    if (services == null) services = this.services;
+    for (var listener : serviceListeners) {
+      listener.servicesChanged(this, services);
+    }
   }
 
   /**
@@ -155,7 +167,7 @@ public class Jws2Discoverer implements Runnable, WSMenuEntryProviderI
       {
         try
         {
-          Cache.log.debug(
+          Console.debug(
                   "Waiting around for old discovery thread to finish.");
           // wait around until old discoverer dies
           Thread.sleep(100);
@@ -164,7 +176,7 @@ public class Jws2Discoverer implements Runnable, WSMenuEntryProviderI
         }
       }
       aborted = false;
-      Cache.log.debug("Old discovery thread has finished.");
+      Console.debug("Old discovery thread has finished.");
     }
     running = true;
 
@@ -176,13 +188,11 @@ public class Jws2Discoverer implements Runnable, WSMenuEntryProviderI
       ignoredServices.add(ignored);
     }
 
-    changeSupport.firePropertyChange("services", services,
-            new Vector<Jws2Instance>());
+    notifyServiceListeners(Collections.emptyList());
     oldthread = Thread.currentThread();
     try
     {
-      Class foo = getClass().getClassLoader()
-              .loadClass("compbio.ws.client.Jws2Client");
+      getClass().getClassLoader().loadClass("compbio.ws.client.Jws2Client");
     } catch (ClassNotFoundException e)
     {
       System.err.println(
@@ -240,7 +250,6 @@ public class Jws2Discoverer implements Runnable, WSMenuEntryProviderI
       } catch (Exception e)
       {
       }
-      ;
       for (JabaWsServerQuery squery : qrys)
       {
         if (squery.isRunning())
@@ -250,7 +259,7 @@ public class Jws2Discoverer implements Runnable, WSMenuEntryProviderI
       }
       if (aborted)
       {
-        Cache.log.debug(
+        Console.debug(
                 "Aborting " + qrys.size() + " JABAWS discovery threads.");
         for (JabaWsServerQuery squery : qrys)
         {
@@ -288,8 +297,7 @@ public class Jws2Discoverer implements Runnable, WSMenuEntryProviderI
     }
     oldthread = null;
     running = false;
-    changeSupport.firePropertyChange("services", new Vector<Jws2Instance>(),
-            services);
+    notifyServiceListeners(services);
   }
 
   /**
@@ -326,72 +334,43 @@ public class Jws2Discoverer implements Runnable, WSMenuEntryProviderI
   }
 
   /**
-   * attach all available web services to the appropriate submenu in the given
-   * JMenu
+   * 
+   * @param args
+   * @j2sIgnore
    */
-  @Override
-  public void attachWSMenuEntry(JMenu wsmenu, final AlignFrame alignFrame)
-  {
-    if (running || services == null || services.size() == 0)
-    {
-      return;
-    }
-    // dynamically regenerate service list.
-    populateWSMenuEntry(wsmenu, alignFrame, null);
-  }
-
-  private void populateWSMenuEntry(JMenu jws2al,
-          final AlignFrame alignFrame, String typeFilter)
-  {
-    PreferredServiceRegistry.getRegistry().populateWSMenuEntry(
-            getServices(),
-            changeSupport, jws2al,
-            alignFrame, typeFilter);
-  }
-
   public static void main(String[] args)
   {
+    Jws2Discoverer instance = getInstance();
     if (args.length > 0)
     {
-      testUrls = new ArrayList<>();
+      instance.testUrls = new ArrayList<>();
       for (String url : args)
       {
-        testUrls.add(url);
+        instance.testUrls.add(url);
       }
-      ;
-    }
-    Thread runner = getDiscoverer()
-            .startDiscoverer(new PropertyChangeListener()
-            {
-
-              @Override
-              public void propertyChange(PropertyChangeEvent evt)
-              {
-                if (getDiscoverer().services != null)
-                {
-                  System.out.println("Changesupport: There are now "
-                          + getDiscoverer().services.size() + " services");
-                  int i = 1;
-                  for (ServiceWithParameters instance : getDiscoverer().services)
-                  {
-                    System.out.println("Service " + i++ + " "
-                            + instance.getClass() + "@"
-                            + instance.getHostURL()
-                            + ": " + instance.getActionText());
-                  }
-
-                }
-              }
-            });
-    while (runner.isAlive())
-    {
-      try
-      {
-        Thread.sleep(50);
-      } catch (InterruptedException e)
+    }
+    var discoverer = getInstance();
+    discoverer.addServiceChangeListener((_discoverer, _services) -> {
+      if (discoverer.services != null)
       {
+        System.out.println("Changesupport: There are now "
+                + discoverer.services.size() + " services");
+        int i = 1;
+        for (ServiceWithParameters s_instance : discoverer.services)
+        {
+          System.out.println(
+                  "Service " + i++ + " " + s_instance.getClass()
+                          + "@" + s_instance.getHostURL() + ": "
+                          + s_instance.getActionText());
+        }
+
       }
-      ;
+    });
+    try
+    {
+      discoverer.startDiscoverer().get();
+    } catch (InterruptedException | ExecutionException e)
+    {
     }
     try
     {
@@ -401,30 +380,20 @@ public class Jws2Discoverer implements Runnable, WSMenuEntryProviderI
     }
   }
 
-  /**
-   * Returns the singleton instance of this class.
-   * 
-   * @return
-   */
-  public static Jws2Discoverer getDiscoverer()
-  {
-    if (discoverer == null)
-    {
-      discoverer = new Jws2Discoverer();
-    }
-    return discoverer;
-  }
 
+  @Override
   public boolean hasServices()
   {
     return !running && services != null && services.size() > 0;
   }
 
+  @Override
   public boolean isRunning()
   {
     return running;
   }
 
+  @Override
   public void setServiceUrls(List<String> wsUrls)
   {
     if (wsUrls != null && !wsUrls.isEmpty())
@@ -451,6 +420,7 @@ public class Jws2Discoverer implements Runnable, WSMenuEntryProviderI
    * 
    * @return
    */
+  @Override
   public List<String> getServiceUrls()
   {
     if (testUrls != null)
@@ -482,32 +452,32 @@ public class Jws2Discoverer implements Runnable, WSMenuEntryProviderI
           }
           else
           {
-            Cache.log.warn("Ignoring duplicate url " + url + " in "
+            Console.warn("Ignoring duplicate url " + url + " in "
                     + JWS2HOSTURLS + " list");
           }
         } catch (MalformedURLException ex)
         {
-          Cache.log.warn("Problem whilst trying to make a URL from '"
+          Console.warn("Problem whilst trying to make a URL from '"
                   + ((url != null) ? url : "<null>") + "'");
-          Cache.log.warn(
+          Console.warn(
                   "This was probably due to a malformed comma separated list"
                           + " in the " + JWS2HOSTURLS
                           + " entry of $(HOME)/.jalview_properties)");
-          Cache.log.debug("Exception was ", ex);
+          Console.debug("Exception was ", ex);
         }
       }
     } catch (Exception ex)
     {
-      Cache.log.warn("Error parsing comma separated list of urls in "
+      Console.warn("Error parsing comma separated list of urls in "
               + JWS2HOSTURLS + " preference.", ex);
     }
     return urls;
   }
 
+  @Override
   public Vector<ServiceWithParameters> getServices()
   {
-    return (services == null) ? new Vector<>()
-            : new Vector<>(services);
+    return (services == null) ? new Vector<>() : new Vector<>(services);
   }
 
   /**
@@ -516,7 +486,8 @@ public class Jws2Discoverer implements Runnable, WSMenuEntryProviderI
    * @param foo
    * @return
    */
-  public static boolean testServiceUrl(URL foo)
+  @Override
+  public boolean testServiceUrl(URL foo)
   {
     try
     {
@@ -564,7 +535,8 @@ public class Jws2Discoverer implements Runnable, WSMenuEntryProviderI
    * @param changeSupport2
    * @return new thread
    */
-  public Thread startDiscoverer(PropertyChangeListener changeSupport2)
+  @Override
+  public CompletableFuture<WSDiscovererI> startDiscoverer()
   {
     /*    if (restart())
         {
@@ -580,10 +552,12 @@ public class Jws2Discoverer implements Runnable, WSMenuEntryProviderI
     {
       setAborted(true);
     }
-    addPropertyChangeListener(changeSupport2);
-    Thread thr = new Thread(this);
-    thr.start();
-    return thr;
+    CompletableFuture<WSDiscovererI> task = CompletableFuture
+            .supplyAsync(() -> {
+              run();
+              return Jws2Discoverer.this;
+            });
+    return task;
   }
 
   /**
@@ -645,6 +619,7 @@ public class Jws2Discoverer implements Runnable, WSMenuEntryProviderI
    * @return a human readable report of any problems with the service URLs used
    *         for discovery
    */
+  @Override
   public String getErrorMessages()
   {
     if (!isRunning() && !isAborted())
@@ -693,21 +668,22 @@ public class Jws2Discoverer implements Runnable, WSMenuEntryProviderI
     return null;
   }
 
+  @Override
   public int getServerStatusFor(String url)
   {
     if (validServiceUrls != null && validServiceUrls.contains(url))
     {
-      return 1;
+      return STATUS_OK;
     }
     if (urlsWithoutServices != null && urlsWithoutServices.contains(url))
     {
-      return 0;
+      return STATUS_NO_SERVICES;
     }
     if (invalidServiceUrls != null && invalidServiceUrls.contains(url))
     {
-      return -1;
+      return STATUS_INVALID;
     }
-    return -2;
+    return STATUS_UNKNOWN;
   }
 
   /**