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