Merge branch 'Jalview-JS/develop.JAL-3446.ctrlDown' into
[jalview.git] / src / jalview / ws / jws1 / Discoverer.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.jws1;
22
23 import jalview.bin.ApplicationSingletonProvider;
24 import jalview.bin.ApplicationSingletonProvider.ApplicationSingletonI;
25 import jalview.gui.AlignmentPanel;
26 import jalview.gui.JvOptionPane;
27 import jalview.util.MessageManager;
28
29 import java.net.URL;
30 import java.util.Hashtable;
31 import java.util.List;
32 import java.util.StringTokenizer;
33 import java.util.Vector;
34
35 import ext.vamsas.IRegistry;
36 import ext.vamsas.IRegistryServiceLocator;
37 import ext.vamsas.RegistryServiceSoapBindingStub;
38 import ext.vamsas.ServiceHandle;
39 import ext.vamsas.ServiceHandles;
40
41 public class Discoverer implements Runnable, ApplicationSingletonI
42 {
43
44   public static Discoverer getInstance()
45   {
46     return (Discoverer) ApplicationSingletonProvider.getInstance(Discoverer.class);
47   }
48
49   private Discoverer()
50   {
51     // use getInstance()
52   }
53
54   ext.vamsas.IRegistry registry; // the root registry service.
55
56   private java.beans.PropertyChangeSupport changeSupport = new java.beans.PropertyChangeSupport(
57           this);
58
59   /**
60    * change listeners are notified of "services" property changes
61    * 
62    * @param listener
63    *          to be added that consumes new services Hashtable object.
64    */
65   public void addPropertyChangeListener(
66           java.beans.PropertyChangeListener listener)
67   {
68     changeSupport.addPropertyChangeListener(listener);
69   }
70
71   /**
72    * 
73    * 
74    * @param listener
75    *          to be removed
76    */
77   public void removePropertyChangeListener(
78           java.beans.PropertyChangeListener listener)
79   {
80     changeSupport.removePropertyChangeListener(listener);
81   }
82
83   /**
84    * Property change listener firing routine
85    * 
86    * @param prop
87    *          services
88    * @param oldvalue
89    *          old services hash
90    * @param newvalue
91    *          new services hash
92    */
93   public void firePropertyChange(String prop, Object oldvalue,
94           Object newvalue)
95   {
96     changeSupport.firePropertyChange(prop, oldvalue, newvalue);
97   }
98
99   /**
100    * Initializes the server field with a valid service implementation.
101    * 
102    * @return true if service was located.
103    */
104   private IRegistry locateWebService(java.net.URL WsURL)
105   {
106     IRegistryServiceLocator loc = new IRegistryServiceLocator(); // Default
107     IRegistry server = null;
108     try
109     {
110       server = loc.getRegistryService(WsURL);
111       ((RegistryServiceSoapBindingStub) server).setTimeout(60000); // One
112       // minute
113       // timeout
114     } catch (Exception ex)
115     {
116       jalview.bin.Cache.log.error(
117               "Serious!  Service location failed\nfor URL :" + WsURL + "\n",
118               ex);
119
120       return null;
121     }
122
123     loc.getEngine().setOption("axis", "1");
124
125     return server;
126   }
127
128   private java.net.URL RootServiceURL = null;
129
130   private Vector<URL> ServiceURLList = null;
131
132   public Vector<URL> getServiceURLList() {
133     return ServiceURLList;
134   }
135   
136   private boolean reallyDiscoverServices = true;
137
138   private java.util.Hashtable<String, Vector<ServiceHandle>> services = null;
139   // stored by
140   // abstractServiceType
141   // string
142
143   public java.util.Vector<ServiceHandle> serviceList = null;
144
145   private Vector<URL> getDiscoveryURLS()
146   {
147     Vector<URL> urls = new Vector<>();
148     String RootServiceURLs = jalview.bin.Cache.getDefault("DISCOVERY_URLS",
149             "http://www.compbio.dundee.ac.uk/JalviewWS/services/ServiceRegistry");
150
151     try
152     {
153       StringTokenizer st = new StringTokenizer(RootServiceURLs, ",");
154       while (st.hasMoreElements())
155       {
156         String url = null;
157         try
158         {
159           java.net.URL u = new java.net.URL(url = st.nextToken());
160           if (!urls.contains(u))
161           {
162             urls.add(u);
163           }
164           else
165           {
166             jalview.bin.Cache.log
167                     .info("Ignoring duplicate url in DISCOVERY_URLS list");
168           }
169         } catch (Exception ex)
170         {
171           jalview.bin.Cache.log
172                   .warn("Problem whilst trying to make a URL from '"
173                           + ((url != null) ? url : "<null>") + "'");
174           jalview.bin.Cache.log.warn(
175                   "This was probably due to a malformed comma separated list"
176                           + " in the DISCOVERY_URLS entry of $(HOME)/.jalview_properties)");
177           jalview.bin.Cache.log.debug("Exception was ", ex);
178         }
179       }
180     } catch (Exception ex)
181     {
182       jalview.bin.Cache.log.warn(
183               "Error parsing comma separated list of urls in DISCOVERY_URLS.",
184               ex);
185     }
186     if (urls.size() > 0)
187     {
188       return urls;
189     }
190     return null;
191   }
192
193   /**
194    * fetch new services or reset to hardwired defaults depending on preferences.
195    */
196   static public void doDiscovery()
197   {
198     getInstance().discovery();
199   }
200
201   private void discovery()
202   {
203     jalview.bin.Cache.log
204             .debug("(Re)-Initialising the discovery URL list.");
205     try
206     {
207       Discoverer d = getInstance();
208       reallyDiscoverServices = jalview.bin.Cache
209               .getDefault("DISCOVERY_START", false);
210       if (reallyDiscoverServices)
211       {
212         ServiceURLList = getDiscoveryURLS();
213       }
214       else
215       {
216         jalview.bin.Cache.log.debug("Setting default services");
217         services = new Hashtable<>();
218         // Muscle, Clustal and JPred.
219         ServiceHandle[] defServices = { new ServiceHandle("MsaWS",
220                 "Edgar, Robert C. (2004), MUSCLE: multiple sequence alignment "
221                         + "with high accuracy and high throughput, Nucleic Acids Research 32(5), 1792-97.",
222                 "http://www.compbio.dundee.ac.uk/JalviewWS/services/MuscleWS",
223                 MessageManager.getString(
224                         "label.muscle_multiple_protein_sequence_alignment")),
225             new ServiceHandle("MsaWS",
226                     "Katoh, K., K. Kuma, K., Toh, H.,  and Miyata, T. (2005) "
227                             + "\"MAFFT version 5: improvement in accuracy of multiple sequence alignment.\""
228                             + " Nucleic Acids Research, 33 511-518",
229                     "http://www.compbio.dundee.ac.uk/JalviewWS/services/MafftWS",
230                     MessageManager.getString(
231                             "label.mafft_multiple_sequence_alignment")),
232             new ServiceHandle("MsaWS",
233                     "Thompson, J.D., Higgins, D.G. and Gibson, T.J. (1994) CLUSTAL W: improving the sensitivity of progressive multiple"
234                             + " sequence alignment through sequence weighting, position specific gap penalties and weight matrix choice."
235                             + " Nucleic Acids Research, 22 4673-4680",
236                     "http://www.compbio.dundee.ac.uk/JalviewWS/services/ClustalWS",
237                     MessageManager.getString(
238                             "label.clustalw_multiple_sequence_alignment")),
239             new ServiceHandle("SecStrPred",
240                     "Drozdetskiy A, Cole C, Procter J & Barton GJ. (2015)\nJPred4: a protein secondary structure prediction server"
241                             + "\nNucleic Acids Research, Web Server issue (first published 15th April 2015)"
242                             + "\ndoi://10.1093/nar/gkv332",
243                     "http://www.compbio.dundee.ac.uk/JalviewWS/services/jpred",
244                     "JPred Secondary Structure Prediction") };
245         services = new Hashtable<>();
246         serviceList = new Vector<>();
247         buildServiceLists(defServices, serviceList, services);
248       }
249
250     } catch (Exception e)
251     {
252       System.err.println(
253               "jalview.rootRegistry is not a proper url!\nWas set to "
254                       + RootServiceURL + "\n" + e);
255     }
256
257   }
258
259   // TODO: JBPNote : make this discover more services based on list of
260   // discovery service urls, break cyclic references to the same url and
261   // duplicate service entries (same endpoint *and* same interface)
262   private ServiceHandle[] getServices(java.net.URL location)
263   {
264     ServiceHandles shs = null;
265     try
266     {
267       jalview.bin.Cache.log.debug("Discovering services using " + location);
268       shs = locateWebService(location).getServices();
269     } catch (org.apache.axis.AxisFault f)
270     {
271       // JBPNote - should do this a better way!
272       if (f.getFaultReason().indexOf("(407)") > -1)
273       {
274         if (jalview.gui.Desktop.getDesktopPane() != null)
275         {
276           JvOptionPane.showMessageDialog(jalview.gui.Desktop.getDesktopPane(),
277                   MessageManager.getString("label.set_proxy_settings"),
278                   MessageManager
279                           .getString("label.proxy_authorization_failed"),
280                   JvOptionPane.WARNING_MESSAGE);
281         }
282       }
283       else
284       {
285         jalview.bin.Cache.log.warn("No Discovery service at " + location);
286         jalview.bin.Cache.log.debug("Axis Fault", f);
287       }
288     } catch (Exception e)
289     {
290       jalview.bin.Cache.log.warn("No Discovery service at " + location);
291       jalview.bin.Cache.log.debug("Discovery Service General Exception", e);
292     }
293     if ((shs != null) && shs.getServices().length > 0)
294     {
295       return shs.getServices();
296     }
297     return null;
298   }
299
300   /**
301    * Adds a list of services to the service catalog and categorised catalog
302    * returns true if ServiceURLList was modified with a new DiscoveryService URL
303    * 
304    * @param sh
305    *          ServiceHandle[]
306    * @param cat
307    *          Vector
308    * @param sscat
309    *          Hashtable
310    * @return boolean
311    */
312   private boolean buildServiceLists(ServiceHandle[] sh,
313           Vector<ServiceHandle> cat,
314           Hashtable<String, Vector<ServiceHandle>> sscat)
315   {
316     boolean seenNewDiscovery = false;
317     for (int i = 0, j = sh.length; i < j; i++)
318     {
319       if (!cat.contains(sh[i]))
320       {
321         jalview.bin.Cache.log.debug("A " + sh[i].getAbstractName()
322                 + " service called " + sh[i].getName() + " exists at "
323                 + sh[i].getEndpointURL() + "\n");
324         if (!sscat.containsKey(sh[i].getAbstractName()))
325         {
326           sscat.put(sh[i].getAbstractName(), cat = new Vector<>());
327         }
328         else
329         {
330           cat = sscat.get(sh[i].getAbstractName());
331         }
332         cat.add(sh[i]);
333         if (sh[i].getAbstractName().equals("Registry"))
334         {
335           for (int s = 0, sUrls = ServiceURLList.size(); s < sUrls; s++)
336           {
337             java.net.URL disc_serv = null;
338             try
339             {
340               disc_serv = new java.net.URL(sh[i].getEndpointURL());
341               if (!ServiceURLList.contains(disc_serv))
342               {
343                 jalview.bin.Cache.log.debug(
344                         "Adding new discovery service at " + disc_serv);
345                 ServiceURLList.add(disc_serv);
346                 seenNewDiscovery = true;
347               }
348             } catch (Exception e)
349             {
350               jalview.bin.Cache.log
351                       .debug("Ignoring bad discovery service URL "
352                               + sh[i].getEndpointURL(), e);
353             }
354           }
355         }
356       }
357     }
358     return seenNewDiscovery;
359   }
360
361   public void discoverServices()
362   {
363     Hashtable<String, Vector<ServiceHandle>> sscat = new Hashtable<>();
364     Vector<ServiceHandle> cat = new Vector<>();
365     ServiceHandle sh[] = null;
366     int s_url = 0;
367     if (ServiceURLList == null)
368     {
369       jalview.bin.Cache.log
370               .debug("No service endpoints to use for service discovery.");
371       return;
372     }
373     while (s_url < ServiceURLList.size())
374     {
375       if ((sh = getServices(
376               ServiceURLList.get(s_url))) != null)
377       {
378
379         buildServiceLists(sh, cat, sscat);
380       }
381       else
382       {
383         jalview.bin.Cache.log.warn("No services at "
384                 + (ServiceURLList.get(s_url))
385                 + " - check DISCOVERY_URLS property in .jalview_properties");
386       }
387       s_url++;
388     }
389     // TODO: decide on correct semantics for services list - PropertyChange
390     // provides a way of passing the new object around
391     // so no need to access original discovery thread.
392     // Curent decision is to change properties then notify listeners with old
393     // and new values.
394     Hashtable<String, Vector<ServiceHandle>> oldServices = services;
395     // Vector oldServicelist = serviceList;
396     services = sscat;
397     serviceList = cat;
398     changeSupport.firePropertyChange("services", oldServices, services);
399   }
400
401   /**
402    * creates a new thread to call discoverServices()
403    */
404   @Override
405   public void run()
406   {
407     final Discoverer discoverer = this;
408     Thread discoverThread = new Thread()
409     {
410       @Override
411       public void run()
412       {
413         Discoverer.doDiscovery();
414         discoverer.discoverServices();
415       }
416     };
417     discoverThread.start();
418   }
419
420   /**
421    * binding service abstract name to handler class
422    */
423   private Hashtable<String, WS1Client> serviceClientBindings;
424
425   public static WS1Client getServiceClient(ServiceHandle sh)
426   {
427     return getInstance().getClient(sh);
428   }
429   
430   /**
431    * notes on discovery service 1. need to allow multiple discovery source urls.
432    * 2. user interface to add/control list of urls in preferences notes on
433    * wsclient discovery 1. need a classpath property with list of additional
434    * plugin directories 2. optional config to cite specific bindings between
435    * class name and Abstract service name. 3. precedence for automatic discovery
436    * by using getAbstractName for WSClient - user added plugins override default
437    * plugins ? notes on wsclient gui code for gui attachment now moved to
438    * wsclient implementation. Needs more abstraction but approach seems to work.
439    * is it possible to 'generalise' the data retrieval calls further ? current
440    * methods are very specific (gatherForMSA or gatherForSeqOrMsaSecStrPred),
441    * new methods for conservation (group or alignment), treecalc (aligned
442    * profile), seqannot (sequences selected from dataset, annotation back to
443    * dataset).
444    * 
445    */
446
447   private WS1Client getClient(ServiceHandle sh)
448   {
449     if (serviceClientBindings == null)
450     {
451       // get a list from Config or create below
452       serviceClientBindings = new Hashtable<>();
453       serviceClientBindings.put("MsaWS", new MsaWSClient());
454       serviceClientBindings.put("SecStrPred", new JPredClient());
455       serviceClientBindings.put("SeqSearch", new SeqSearchWSClient());
456     }
457     WS1Client instance = serviceClientBindings
458             .get(sh.getAbstractName());
459     if (instance == null)
460     {
461       System.err.println(
462               "WARNING - POSSIBLE IMPLEMENTATION ERROR - cannot find WSClient implementation for "
463                       + sh.getAbstractName());
464     }
465     else
466     {
467       instance.serviceHandle = sh;
468     }
469     return instance;
470   }
471
472   public static Hashtable<String, Vector<ServiceHandle>> getServices()
473   {
474     return getInstance().services;
475   }
476 }