JAL-1731 fix JPred4 citation in legacy client code
[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         {
198             new ServiceHandle(
199                     "MsaWS",
200                     "Edgar, Robert C. (2004), MUSCLE: multiple sequence alignment "
201                             + "with high accuracy and high throughput, Nucleic Acids Research 32(5), 1792-97.",
202                     "http://www.compbio.dundee.ac.uk/JalviewWS/services/MuscleWS",
203                     MessageManager.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.getString("label.mafft_multiple_sequence_alignment")),
211             new ServiceHandle(
212                     "MsaWS",
213                     "Thompson, J.D., Higgins, D.G. and Gibson, T.J. (1994) CLUSTAL W: improving the sensitivity of progressive multiple"
214                             + " sequence alignment through sequence weighting, position specific gap penalties and weight matrix choice."
215                             + " Nucleic Acids Research, 22 4673-4680",
216                     "http://www.compbio.dundee.ac.uk/JalviewWS/services/ClustalWS",
217                     MessageManager.getString("label.clustalw_multiple_sequence_alignment")),
218             new ServiceHandle(
219                     "SecStrPred",
220                     "Drozdetskiy A, Cole C, Procter J & Barton GJ. (2015)\nJPred4: a protein secondary structure prediction server"
221                             + "\nNucleic Acids Research, Web Server issue (first published 15th April 2015)"
222                             + "\ndoi://10.1093/nar/gkv332",
223                     "http://www.compbio.dundee.ac.uk/JalviewWS/services/jpred",
224                     "JNet Secondary Structure Prediction") };
225         services = new Hashtable();
226         serviceList = new Vector();
227         buildServiceLists(defServices, serviceList, services);
228       }
229
230     } catch (Exception e)
231     {
232       System.err
233               .println("jalview.rootRegistry is not a proper url!\nWas set to "
234                       + RootServiceURL + "\n" + e);
235     }
236
237   }
238
239   // TODO: JBPNote : make this discover more services based on list of
240   // discovery service urls, break cyclic references to the same url and
241   // duplicate service entries (same endpoint *and* same interface)
242   private ServiceHandle[] getServices(java.net.URL location)
243   {
244     ServiceHandles shs = null;
245     try
246     {
247       jalview.bin.Cache.log.debug("Discovering services using " + location);
248       shs = locateWebService(location).getServices();
249     } catch (org.apache.axis.AxisFault f)
250     {
251       // JBPNote - should do this a better way!
252       if (f.getFaultReason().indexOf("(407)") > -1)
253       {
254         if (jalview.gui.Desktop.desktop != null)
255         {
256           JOptionPane
257                   .showMessageDialog(
258                           jalview.gui.Desktop.desktop,
259                           MessageManager.getString("label.set_proxy_settings"),
260                           MessageManager.getString("label.proxy_authorization_failed"),
261                           JOptionPane.WARNING_MESSAGE);
262         }
263       }
264       else
265       {
266         jalview.bin.Cache.log.warn("No Discovery service at " + location);
267         jalview.bin.Cache.log.debug("Axis Fault", f);
268       }
269     } catch (Exception e)
270     {
271       jalview.bin.Cache.log.warn("No Discovery service at " + location);
272       jalview.bin.Cache.log.debug("Discovery Service General Exception", e);
273     }
274     if ((shs != null) && shs.getServices().length > 0)
275     {
276       return shs.getServices();
277     }
278     return null;
279   }
280
281   /**
282    * Adds a list of services to the service catalog and categorised catalog
283    * returns true if ServiceURLList was modified with a new DiscoveryService URL
284    * 
285    * @param sh
286    *          ServiceHandle[]
287    * @param cat
288    *          Vector
289    * @param sscat
290    *          Hashtable
291    * @return boolean
292    */
293   static private boolean buildServiceLists(ServiceHandle[] sh, Vector cat,
294           Hashtable sscat)
295   {
296     boolean seenNewDiscovery = false;
297     for (int i = 0, j = sh.length; i < j; i++)
298     {
299       if (!cat.contains(sh[i]))
300       {
301         jalview.bin.Cache.log.debug("A " + sh[i].getAbstractName()
302                 + " service called " + sh[i].getName() + " exists at "
303                 + sh[i].getEndpointURL() + "\n");
304         if (!sscat.containsKey(sh[i].getAbstractName()))
305         {
306           sscat.put(sh[i].getAbstractName(), cat = new Vector());
307         }
308         else
309         {
310           cat = (Vector) sscat.get(sh[i].getAbstractName());
311         }
312         cat.add(sh[i]);
313         if (sh[i].getAbstractName().equals("Registry"))
314         {
315           for (int s = 0, sUrls = ServiceURLList.size(); s < sUrls; s++)
316           {
317             java.net.URL disc_serv = null;
318             try
319             {
320               disc_serv = new java.net.URL(sh[i].getEndpointURL());
321               if (!ServiceURLList.contains(disc_serv))
322               {
323                 jalview.bin.Cache.log
324                         .debug("Adding new discovery service at "
325                                 + disc_serv);
326                 ServiceURLList.add(disc_serv);
327                 seenNewDiscovery = true;
328               }
329             } catch (Exception e)
330             {
331               jalview.bin.Cache.log.debug(
332                       "Ignoring bad discovery service URL "
333                               + sh[i].getEndpointURL(), e);
334             }
335           }
336         }
337       }
338     }
339     return seenNewDiscovery;
340   }
341
342   public void discoverServices()
343   {
344     Hashtable sscat = new Hashtable();
345     Vector cat = new Vector();
346     ServiceHandle sh[] = null;
347     int s_url = 0;
348     if (ServiceURLList == null)
349     {
350       jalview.bin.Cache.log
351               .debug("No service endpoints to use for service discovery.");
352       return;
353     }
354     while (s_url < ServiceURLList.size())
355     {
356       if ((sh = getServices((java.net.URL) ServiceURLList.get(s_url))) != null)
357       {
358
359         buildServiceLists(sh, cat, sscat);
360       }
361       else
362       {
363         jalview.bin.Cache.log
364                 .warn("No services at "
365                         + (ServiceURLList.get(s_url))
366                         + " - check DISCOVERY_URLS property in .jalview_properties");
367       }
368       s_url++;
369     }
370     // TODO: decide on correct semantics for services list - PropertyChange
371     // provides a way of passing the new object around
372     // so no need to access original discovery thread.
373     // Curent decision is to change properties then notify listeners with old
374     // and new values.
375     Hashtable oldServices = services;
376     // Vector oldServicelist = serviceList;
377     services = sscat;
378     serviceList = cat;
379     changeSupport.firePropertyChange("services", oldServices, services);
380   }
381
382   /**
383    * creates a new thread to call discoverServices()
384    */
385   public void run()
386   {
387     final Discoverer discoverer = this;
388     Thread discoverThread = new Thread()
389     {
390       public void run()
391       {
392         discoverer.doDiscovery();
393         discoverer.discoverServices();
394       }
395     };
396     discoverThread.start();
397   }
398
399   /**
400    * binding service abstract name to handler class
401    */
402   private static Hashtable serviceClientBindings;
403
404   public static WS1Client getServiceClient(ServiceHandle sh)
405   {
406     if (serviceClientBindings == null)
407     {
408       // get a list from Config or create below
409       serviceClientBindings = new Hashtable();
410       serviceClientBindings.put("MsaWS", new MsaWSClient());
411       serviceClientBindings.put("SecStrPred", new JPredClient());
412       serviceClientBindings.put("SeqSearch", new SeqSearchWSClient());
413     }
414     WS1Client instance = (WS1Client) serviceClientBindings.get(sh
415             .getAbstractName());
416     if (instance == null)
417     {
418       System.err
419               .println("WARNING - POSSIBLE IMPLEMENTATION ERROR - cannot find WSClient implementation for "
420                       + sh.getAbstractName());
421     }
422     else
423     {
424       instance.serviceHandle = sh;
425     }
426     return instance;
427   }
428   /**
429    * notes on discovery service 1. need to allow multiple discovery source urls.
430    * 2. user interface to add/control list of urls in preferences notes on
431    * wsclient discovery 1. need a classpath property with list of additional
432    * plugin directories 2. optional config to cite specific bindings between
433    * class name and Abstract service name. 3. precedence for automatic discovery
434    * by using getAbstractName for WSClient - user added plugins override default
435    * plugins ? notes on wsclient gui code for gui attachment now moved to
436    * wsclient implementation. Needs more abstraction but approach seems to work.
437    * is it possible to 'generalise' the data retrieval calls further ? current
438    * methods are very specific (gatherForMSA or gatherForSeqOrMsaSecStrPred),
439    * new methods for conservation (group or alignment), treecalc (aligned
440    * profile), seqannot (sequences selected from dataset, annotation back to
441    * dataset).
442    * 
443    */
444 }