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