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