8907b581a93b513708a9e3b6e633c18a46b187a9
[jalview.git] / src / jalview / ws / jws2 / Jws2Discoverer.java
1 /*
2  * Jalview - A Sequence Alignment Editor and Viewer (Version 2.7)
3  * Copyright (C) 2011 J Procter, AM Waterhouse, J Engelhardt, LM Lui, 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.jws2;
19
20 import java.awt.Color;
21 import java.awt.event.ActionEvent;
22 import java.awt.event.ActionListener;
23 import java.beans.PropertyChangeEvent;
24 import java.beans.PropertyChangeListener;
25 import java.net.ConnectException;
26 import java.net.URL;
27 import java.util.ArrayList;
28 import java.util.HashSet;
29 import java.util.Hashtable;
30 import java.util.List;
31 import java.util.StringTokenizer;
32 import java.util.Vector;
33
34 import javax.swing.JMenu;
35 import javax.swing.JMenuItem;
36 import javax.swing.event.MenuEvent;
37 import javax.swing.event.MenuListener;
38
39 import org.apache.log4j.Level;
40
41 import jalview.bin.Cache;
42 import jalview.datamodel.AlignmentView;
43 import jalview.gui.AlignFrame;
44 import jalview.gui.Desktop;
45 import jalview.gui.JalviewChangeSupport;
46 import jalview.gui.JvSwingUtils;
47 import jalview.ws.WSMenuEntryProviderI;
48 import jalview.ws.jws2.jabaws2.Jws2Instance;
49 import compbio.data.msa.JABAService;
50 import compbio.metadata.Option;
51 import compbio.metadata.Preset;
52 import compbio.ws.client.Jws2Client;
53 import compbio.ws.client.Services;
54
55 /**
56  * discoverer for jws2 services. Follows the lightweight service discoverer
57  * pattern (archetyped by EnfinEnvision2OneWay)
58  * 
59  * @author JimP
60  * 
61  */
62 public class Jws2Discoverer implements Runnable, WSMenuEntryProviderI
63 {
64   private java.beans.PropertyChangeSupport changeSupport = new java.beans.PropertyChangeSupport(
65           this);
66
67   /**
68    * change listeners are notified of "services" property changes
69    * 
70    * @param listener
71    *          to be added that consumes new services Hashtable object.
72    */
73   public void addPropertyChangeListener(
74           java.beans.PropertyChangeListener listener)
75   {
76     changeSupport.addPropertyChangeListener(listener);
77   }
78
79   /**
80    * 
81    * 
82    * @param listener
83    *          to be removed
84    */
85   public void removePropertyChangeListener(
86           java.beans.PropertyChangeListener listener)
87   {
88     changeSupport.removePropertyChangeListener(listener);
89   }
90
91   boolean running = false, aborted = false;
92
93   /**
94    * @return the aborted
95    */
96   public boolean isAborted()
97   {
98     return aborted;
99   }
100
101   /**
102    * @param aborted
103    *          the aborted to set
104    */
105   public void setAborted(boolean aborted)
106   {
107     this.aborted = aborted;
108   }
109
110   Thread oldthread = null;
111
112   public void run()
113   {
114     if (running && oldthread != null && oldthread.isAlive())
115     {
116       if (!aborted)
117       {
118         return;
119       }
120       while (running)
121       {
122         try
123         {
124           Cache.log
125                   .debug("Waiting around for old discovery thread to finish.");
126           // wait around until old discoverer dies
127           Thread.sleep(100);
128         } catch (Exception e)
129         {
130         }
131       }
132       Cache.log.debug("Old discovery thread has finished.");
133     }
134     running = true;
135     oldthread = Thread.currentThread();
136     try
137     {
138       Class foo = getClass().getClassLoader().loadClass(
139               "compbio.ws.client.Jws2Client");
140     } catch (ClassNotFoundException e)
141     {
142       System.err
143               .println("Not enabling JABA Webservices : client jar is not available."
144                       + "\nPlease check that your webstart JNLP file is up to date!");
145       running = false;
146       return;
147     }
148     // reinitialise records of good and bad service URLs
149     if (services != null)
150     {
151       services.removeAllElements();
152     }
153     if (urlsWithoutServices != null)
154     {
155       urlsWithoutServices.removeAllElements();
156     }
157     if (invalidServiceUrls != null)
158     {
159       invalidServiceUrls.removeAllElements();
160     }
161
162     List<JabaWsServerQuery> qrys = new ArrayList<JabaWsServerQuery>();
163     for (final String jwsservers : getServiceUrls())
164     {
165       JabaWsServerQuery squery = new JabaWsServerQuery(this, jwsservers);
166       qrys.add(squery);
167       new Thread(squery).start();
168     }
169     boolean finished = false;
170     do
171     {
172       try
173       {
174         Thread.sleep(100);
175       } catch (Exception e)
176       {
177       }
178       ;
179       for (JabaWsServerQuery squery : qrys)
180       {
181         finished |= !squery.isRunning();
182       }
183       if (aborted)
184       {
185         Cache.log.debug("Aborting " + qrys.size()
186                 + " JABAWS discovery threads.");
187         for (JabaWsServerQuery squery : qrys)
188         {
189           squery.setQuit(true);
190         }
191       }
192     } while (!aborted && !finished);
193     oldthread = null;
194     running = false;
195     if (!aborted)
196     {
197       changeSupport.firePropertyChange("services", new Vector(), services);
198     }
199   }
200
201   /**
202    * record this service endpoint so we can use it
203    * 
204    * @param jwsservers
205    * @param srv
206    * @param service2
207    */
208   synchronized void addService(String jwsservers, Services srv,
209           MsaWS service2)
210   {
211     if (services == null)
212     {
213       services = new Vector<Jws2Instance>();
214     }
215     System.out.println("Discovered service: " + jwsservers + " "
216             + srv.toString());
217     Jws2Instance service = new Jws2Instance(jwsservers, srv.toString(),
218             service2);
219
220     services.add(service);
221     // retrieve the presets and parameter set and cache now
222     service.getParamStore().getPresets();
223     service.hasParameters();
224   }
225
226   /**
227    * holds list of services.
228    */
229   protected Vector<Jws2Instance> services;
230
231   public void attachWSMenuEntry(JMenu wsmenu, final AlignFrame alignFrame)
232   {
233     // dynamically regenerate service list.
234     final JMenu jws2al = wsmenu; // new JMenu("JABAWS Alignment");
235     jws2al.addMenuListener(new MenuListener()
236     {
237       // TODO: future: add menu listener to parent menu - so submenus are
238       // populated *before* they are selected.
239       @Override
240       public void menuSelected(MenuEvent e)
241       {
242         populateWSMenuEntry(jws2al, alignFrame);
243       }
244
245       @Override
246       public void menuDeselected(MenuEvent e)
247       {
248         // TODO Auto-generated method stub
249
250       }
251
252       @Override
253       public void menuCanceled(MenuEvent e)
254       {
255         // TODO Auto-generated method stub
256
257       }
258
259     });
260     wsmenu.add(jws2al);
261
262   }
263
264   private void populateWSMenuEntry(JMenu jws2al, final AlignFrame alignFrame)
265   {
266     if (running || services == null || services.size() == 0)
267     {
268       return;
269     }
270     boolean byhost = Cache.getDefault("WSMENU_BYHOST", false), bytype = Cache
271             .getDefault("WSMENU_BYTYPE", false);
272     /**
273      * eventually, JWS2 services will appear under the same align/etc submenus.
274      * for moment we keep them separate.
275      */
276     JMenu atpoint;
277     MsaWSClient msacl = new MsaWSClient();
278     Vector hostLabels = new Vector();
279     jws2al.removeAll();
280     String lasthost = null;
281     Hashtable<String, ArrayList<Jws2Instance>> hosts = new Hashtable<String, ArrayList<Jws2Instance>>();
282     String[] sorton;
283     for (Jws2Instance service : services)
284     {
285       ArrayList<Jws2Instance> hostservices = hosts.get(service.getHost());
286       if (hostservices == null)
287       {
288         hosts.put(service.getHost(),
289                 hostservices = new ArrayList<Jws2Instance>());
290       }
291       hostservices.add(service);
292     }
293     sorton = hosts.keySet().toArray(new String[1]);
294     String hostlist[] = sorton.clone();
295     jalview.util.QuickSort.sort(sorton, hostlist);
296     for (String host : hostlist)
297     {
298       Jws2Instance orderedsvcs[] = hosts.get(host).toArray(
299               new Jws2Instance[1]);
300       String sortbytype[] = new String[orderedsvcs.length];
301       for (int i = 0; i < sortbytype.length; i++)
302       {
303         sortbytype[i] = orderedsvcs[i].serviceType;
304       }
305       jalview.util.QuickSort.sort(sortbytype, orderedsvcs);
306       for (final Jws2Instance service : orderedsvcs)
307       {
308         atpoint = jws2al;
309         String type = service.serviceType;
310         if (byhost)
311         {
312           atpoint = JvSwingUtils.findOrCreateMenu(atpoint, host);
313           if (atpoint.getToolTipText() == null)
314           {
315             atpoint.setToolTipText("Services at " + host);
316           }
317         }
318         if (bytype)
319         {
320           atpoint = JvSwingUtils.findOrCreateMenu(atpoint, type);
321           if (atpoint.getToolTipText() == null)
322           {
323             atpoint.setToolTipText(service.getActionText());
324           }
325         }
326         if (!byhost
327                 && !hostLabels.contains(host + service.serviceType
328                         + service.getActionText()))
329         // !hostLabels.contains(host + (bytype ?
330         // service.serviceType+service.getActionText() : "")))
331         {
332           // add a marker indicating where this service is hosted
333           // relies on services from the same host being listed in a
334           // contiguous
335           // group
336           JMenuItem hitm;
337           atpoint.addSeparator();
338           if (lasthost == null || !lasthost.equals(host))
339           {
340             atpoint.add(hitm = new JMenuItem(host));
341             hitm.setForeground(Color.blue);
342             hitm.addActionListener(new ActionListener()
343             {
344
345               @Override
346               public void actionPerformed(ActionEvent e)
347               {
348                 Desktop.showUrl(service.getHost());
349               }
350             });
351             hitm.setToolTipText(JvSwingUtils
352                     .wrapTooltip("Opens the JABAWS server's homepage in web browser"));
353             lasthost = host;
354           }
355           hostLabels.addElement(host + service.serviceType
356                   + service.getActionText());
357           // hostLabels.addElement(host + (bytype ?
358           // service.serviceType+service.getActionText() : ""));
359         }
360         msacl.attachWSMenuEntry(atpoint, service, alignFrame);
361         /*
362          * JMenuItem sitem = new JMenuItem(service.serviceType);
363          * sitem.setToolTipText("Hosted at " + service.hosturl);
364          * sitem.addActionListener(new ActionListener() {
365          * 
366          * @Override public void actionPerformed(ActionEvent e) { AlignmentView
367          * msa = alignFrame.gatherSequencesForAlignment(); MsaWSClient client =
368          * new MsaWSClient(service, "JWS2 Alignment of " +
369          * alignFrame.getTitle(), msa, false, true,
370          * alignFrame.getViewport().getAlignment().getDataset(), alignFrame); }
371          * });
372          */
373       }
374     }
375
376   }
377
378   public static void main(String[] args)
379   {
380     Thread runner = getDiscoverer().startDiscoverer(
381             new PropertyChangeListener()
382             {
383
384               public void propertyChange(PropertyChangeEvent evt)
385               {
386                 if (getDiscoverer().services != null)
387                 {
388                   System.out.println("Changesupport: There are now "
389                           + getDiscoverer().services.size() + " services");
390
391                 }
392               }
393             });
394     while (runner.isAlive())
395     {
396       try
397       {
398         Thread.sleep(50);
399       } catch (InterruptedException e)
400       {
401       }
402       ;
403     }
404   }
405
406   private static Jws2Discoverer discoverer;
407
408   public static Jws2Discoverer getDiscoverer()
409   {
410     if (discoverer == null)
411     {
412       discoverer = new Jws2Discoverer();
413     }
414     return discoverer;
415   }
416
417   public boolean hasServices()
418   {
419     // TODO Auto-generated method stub
420     return !running && services != null && services.size() > 0;
421   }
422
423   public boolean isRunning()
424   {
425     return running;
426   }
427
428   /**
429    * the jalview .properties entry for JWS2 URLS
430    */
431   final static String JWS2HOSTURLS = "JWS2HOSTURLS";
432
433   public static void setServiceUrls(Vector<String> urls)
434   {
435     if (urls != null)
436     {
437       StringBuffer urlbuffer = new StringBuffer();
438       String sep = "";
439       for (String url : urls)
440       {
441         urlbuffer.append(sep);
442         urlbuffer.append(url);
443         sep = ",";
444       }
445       Cache.setProperty(JWS2HOSTURLS, urlbuffer.toString());
446     }
447     else
448     {
449       Cache.removeProperty(JWS2HOSTURLS);
450     }
451   }
452
453   public static Vector<String> getServiceUrls()
454   {
455     String surls = Cache.getDefault(JWS2HOSTURLS,
456             "http://www.compbio.dundee.ac.uk/jabaws");
457     Vector<String> urls = new Vector<String>();
458     try
459     {
460       StringTokenizer st = new StringTokenizer(surls, ",");
461       while (st.hasMoreElements())
462       {
463         String url = null;
464         try
465         {
466           java.net.URL u = new java.net.URL(url = st.nextToken());
467           if (!urls.contains(url))
468           {
469             urls.add(url);
470           }
471           else
472           {
473             jalview.bin.Cache.log.info("Ignoring duplicate url in "
474                     + JWS2HOSTURLS + " list");
475           }
476         } catch (Exception ex)
477         {
478           jalview.bin.Cache.log
479                   .warn("Problem whilst trying to make a URL from '"
480                           + ((url != null) ? url : "<null>") + "'");
481           jalview.bin.Cache.log
482                   .warn("This was probably due to a malformed comma separated list"
483                           + " in the "
484                           + JWS2HOSTURLS
485                           + " entry of $(HOME)/.jalview_properties)");
486           jalview.bin.Cache.log.debug("Exception was ", ex);
487         }
488       }
489     } catch (Exception ex)
490     {
491       jalview.bin.Cache.log.warn(
492               "Error parsing comma separated list of urls in "
493                       + JWS2HOSTURLS + " preference.", ex);
494     }
495     if (urls.size() >= 0)
496     {
497       return urls;
498     }
499     return null;
500   }
501
502   public Vector<Jws2Instance> getServices()
503   {
504     return (services == null) ? new Vector<Jws2Instance>()
505             : new Vector<Jws2Instance>(services);
506   }
507
508   /**
509    * test the given URL with the JabaWS test code
510    * 
511    * @param foo
512    * @return
513    */
514   public static boolean testServiceUrl(URL foo)
515   {
516     try
517     {
518       compbio.ws.client.WSTester.main(new String[]
519       { "-h=" + foo.toString() });
520     } catch (Exception e)
521     {
522       e.printStackTrace();
523       return false;
524     } catch (OutOfMemoryError e)
525     {
526       e.printStackTrace();
527       return false;
528     } catch (Error e)
529     {
530       e.printStackTrace();
531       return false;
532     }
533
534     return true;
535   }
536
537   /**
538    * Start a fresh discovery thread and notify the given object when we're
539    * finished. Any known existing threads will be killed before this one is
540    * started.
541    * 
542    * @param changeSupport2
543    * @return new thread
544    */
545   public Thread startDiscoverer(PropertyChangeListener changeSupport2)
546   {
547     if (isRunning())
548     {
549       setAborted(true);
550     }
551     addPropertyChangeListener(changeSupport2);
552     Thread thr = new Thread(this);
553     thr.start();
554     return thr;
555   }
556
557   Vector<String> invalidServiceUrls = null, urlsWithoutServices = null;
558
559   /**
560    * @return the invalidServiceUrls
561    */
562   public Vector<String> getInvalidServiceUrls()
563   {
564     return invalidServiceUrls;
565   }
566
567   /**
568    * @return the urlsWithoutServices
569    */
570   public Vector<String> getUrlsWithoutServices()
571   {
572     return urlsWithoutServices;
573   }
574
575   /**
576    * add an 'empty' JABA server to the list. Only servers not already in the
577    * 'bad URL' list will be added to this list.
578    * 
579    * @param jwsservers
580    */
581   public synchronized void addUrlwithnoservices(String jwsservers)
582   {
583     if (urlsWithoutServices == null)
584     {
585       urlsWithoutServices = new Vector<String>();
586     }
587
588     if ((invalidServiceUrls == null || !invalidServiceUrls
589             .contains(jwsservers))
590             && !urlsWithoutServices.contains(jwsservers))
591     {
592       urlsWithoutServices.add(jwsservers);
593     }
594   }
595
596   /**
597    * add a bad URL to the list
598    * 
599    * @param jwsservers
600    */
601   public synchronized void addInvalidServiceUrl(String jwsservers)
602   {
603     if (invalidServiceUrls == null)
604     {
605       invalidServiceUrls = new Vector<String>();
606     }
607     if (!invalidServiceUrls.contains(jwsservers))
608     {
609       invalidServiceUrls.add(jwsservers);
610     }
611   }
612
613   /**
614    * 
615    * @return a human readable report of any problems with the service URLs used
616    *         for discovery
617    */
618   public String getErrorMessages()
619   {
620     if (!isRunning() && !isAborted())
621     {
622       StringBuffer ermsg = new StringBuffer();
623       boolean list = false;
624       if (getInvalidServiceUrls() != null
625               && getInvalidServiceUrls().size() > 0)
626       {
627         ermsg.append("URLs that could not be contacted: \n");
628         for (String svcurl : getInvalidServiceUrls())
629         {
630           if (list)
631           {
632             ermsg.append(", ");
633           }
634           list = true;
635           ermsg.append(svcurl);
636         }
637         ermsg.append("\n\n");
638       }
639       list = false;
640       if (getUrlsWithoutServices() != null
641               && getUrlsWithoutServices().size() > 0)
642       {
643         ermsg.append("URLs without any JABA Services : \n");
644         for (String svcurl : getUrlsWithoutServices())
645         {
646           if (list)
647           {
648             ermsg.append(", ");
649           }
650           list = true;
651           ermsg.append(svcurl);
652         }
653         ermsg.append("\n");
654       }
655       if (ermsg.length() > 1)
656       {
657         return ermsg.toString();
658       }
659
660     }
661     return null;
662   }
663
664 }