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