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