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