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