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