layout the menu with a minimum number of host labels
[jalview.git] / src / jalview / ws / jws2 / Jws2Discoverer.java
1 package jalview.ws.jws2;
2
3 import java.awt.Color;
4 import java.awt.event.ActionEvent;
5 import java.awt.event.ActionListener;
6 import java.beans.PropertyChangeEvent;
7 import java.beans.PropertyChangeListener;
8 import java.io.Closeable;
9 import java.net.ConnectException;
10 import java.net.URL;
11 import java.util.HashSet;
12 import java.util.Hashtable;
13 import java.util.StringTokenizer;
14 import java.util.Vector;
15
16 import javax.swing.JMenu;
17 import javax.swing.JMenuItem;
18 import javax.swing.event.MenuEvent;
19 import javax.swing.event.MenuListener;
20
21 import org.apache.log4j.Level;
22
23 import jalview.bin.Cache;
24 import jalview.datamodel.AlignmentView;
25 import jalview.gui.AlignFrame;
26 import jalview.gui.Desktop;
27 import jalview.ws.WSMenuEntryProviderI;
28 import jalview.ws.params.ParamDatastoreI;
29 import compbio.data.msa.MsaWS;
30 import compbio.metadata.Option;
31 import compbio.metadata.Preset;
32 import compbio.metadata.PresetManager;
33 import compbio.metadata.RunnerConfig;
34 import compbio.ws.client.Jws2Client;
35 import compbio.ws.client.Services;
36
37 /**
38  * discoverer for jws2 services. Follows the lightweight service discoverer
39  * pattern (archetyped by EnfinEnvision2OneWay)
40  * 
41  * @author JimP
42  * 
43  */
44 public class Jws2Discoverer implements Runnable, WSMenuEntryProviderI
45 {
46   private java.beans.PropertyChangeSupport changeSupport = new java.beans.PropertyChangeSupport(
47           this);
48
49   /**
50    * change listeners are notified of "services" property changes
51    * 
52    * @param listener
53    *          to be added that consumes new services Hashtable object.
54    */
55   public void addPropertyChangeListener(
56           java.beans.PropertyChangeListener listener)
57   {
58     changeSupport.addPropertyChangeListener(listener);
59   }
60
61   /**
62    * 
63    * 
64    * @param listener
65    *          to be removed
66    */
67   public void removePropertyChangeListener(
68           java.beans.PropertyChangeListener listener)
69   {
70     changeSupport.removePropertyChangeListener(listener);
71   }
72
73   boolean running = false;
74
75   Thread oldthread = null;
76
77   public void run()
78   {
79     if (running && oldthread != null && oldthread.isAlive())
80     {
81       return;
82     }
83     running = true;
84     oldthread = Thread.currentThread();
85     try
86     {
87       Class foo = getClass().getClassLoader().loadClass(
88               "compbio.ws.client.Jws2Client");
89     } catch (ClassNotFoundException e)
90     {
91       System.err
92               .println("Not enabling Jalview Webservices version 2: client jar is not available."
93                       + "\nPlease check that your webstart JNLP file is up to date!");
94       running = false;
95       return;
96     }
97     if (services != null)
98     {
99       services.removeAllElements();
100     }
101     for (String jwsservers : getServiceUrls())
102     {
103       try
104       {
105         if (Jws2Client.validURL(jwsservers))
106         {
107           // look for services
108           for (Services srv : Services.values())
109           {
110             MsaWS service = null;
111             try
112             {
113               service = Jws2Client.connect(jwsservers, srv);
114             } catch (Exception e)
115             {
116               System.err.println("Jws2 Discoverer: Problem on "
117                       + jwsservers + " with service " + srv + ":\n"
118                       + e.getMessage());
119               if (!(e instanceof javax.xml.ws.WebServiceException))
120               {
121                 e.printStackTrace();
122               }
123             }
124             ;
125             if (service != null)
126             {
127               addService(jwsservers, srv, service);
128             }
129           }
130
131         }
132         else
133         {
134           Cache.log.info("Ignoring invalid Jws2 service url " + jwsservers);
135         }
136       } catch (Exception e)
137       {
138         e.printStackTrace();
139         Cache.log.warn("Exception when discovering Jws2 services.", e);
140       } catch (Error e)
141       {
142         Cache.log.error("Exception when discovering Jws2 services.", e);
143       }
144     }
145     oldthread = null;
146     running = false;
147     changeSupport.firePropertyChange("services", new Vector(), services);
148   }
149
150   /**
151    * record this service endpoint so we can use it
152    * 
153    * @param jwsservers
154    * @param srv
155    * @param service2
156    */
157   private void addService(String jwsservers, Services srv, MsaWS service2)
158   {
159     if (services == null)
160     {
161       services = new Vector<Jws2Instance>();
162     }
163     System.out.println("Discovered service: " + jwsservers + " "
164             + srv.toString());
165     Jws2Instance service = new Jws2Instance(jwsservers, srv.toString(), service2);
166
167     services.add(service);
168     service.getParamStore();
169   }
170
171   public class Jws2Instance
172   {
173     public String hosturl;
174
175     public String serviceType;
176
177     public MsaWS service;
178
179     public Jws2Instance(String hosturl, String serviceType, MsaWS service)
180     {
181       super();
182       this.hosturl = hosturl;
183       this.serviceType = serviceType;
184       this.service = service;
185     }
186
187     PresetManager presets = null;
188
189     public JabaParamStore paramStore = null;
190
191     /**
192      * non thread safe - gets the presets for this service (blocks whilst it
193      * calls the service to get the preset set)
194      * 
195      * @return service presets or null if exceptions were raised.
196      */
197     public PresetManager getPresets()
198     {
199       if (presets == null)
200       {
201         try
202         {
203           presets = service.getPresets();
204         } catch (Exception ex)
205         {
206           System.err
207                   .println("Exception when retrieving presets for service "
208                           + serviceType + " at " + hosturl);
209         }
210       }
211       return presets;
212     }
213
214     public String getHost()
215     {
216       return hosturl;
217       /*
218        * try { URL serviceurl = new URL(hosturl); if (serviceurl.getPort()!=80)
219        * { return serviceurl.getHost()+":"+serviceurl.getPort(); } return
220        * serviceurl.getHost(); } catch (Exception e) {
221        * System.err.println("Failed to parse service URL '" + hosturl +
222        * "' as a valid URL!"); } return null;
223        */
224     }
225
226     /**
227      * @return short description of what the service will do
228      */
229     public String getActionText()
230     {
231       return "Align with " + serviceType;
232     }
233
234     /**
235      * non-thread safe - blocks whilst accessing service to get complete set of
236      * available options and parameters
237      * 
238      * @return
239      */
240     public RunnerConfig getRunnerConfig()
241     {
242       return service.getRunnerOptions();
243     }
244
245     @Override
246     protected void finalize() throws Throwable
247     {
248       if (service != null)
249       {
250         try
251         {
252           Closeable svc = (Closeable) service;
253           service = null;
254           svc.close();
255         } catch (Exception e)
256         {
257         }
258         ;
259       }
260       super.finalize();
261     }
262
263     public ParamDatastoreI getParamStore()
264     {
265       if (paramStore == null)
266       {
267         try
268         {
269           paramStore = new JabaParamStore(this,
270                   (Desktop.instance != null ? Desktop
271                           .getUserParameterStore() : null));
272         } catch (Exception ex)
273         {
274         }
275
276       }
277       return paramStore;
278     }
279
280     public String getUri()
281     {
282       // this is only valid for Jaba 1.0 - this formula might have to change!
283       return hosturl+(hosturl.lastIndexOf("/")==(hosturl.length()-1) ? "/" : "") +serviceType;
284     }
285     private boolean hasParams=false,lookedForParams=false;
286     public boolean hasParameters()
287     {
288       if (!lookedForParams)
289       {
290         lookedForParams=true;
291       try
292       {
293         hasParams = (getRunnerConfig().getArguments().size() > 0);
294       } catch (Exception e)
295       {
296
297       }
298       }
299       return hasParams;
300     }
301   };
302
303   /**
304    * holds list of services.
305    */
306   protected Vector<Jws2Instance> services;
307
308   /**
309    * find or add a submenu with the given title in the given menu
310    * 
311    * @param menu
312    * @param submenu
313    * @return the new or existing submenu
314    */
315   private JMenu findOrCreateMenu(JMenu menu, String submenu)
316   {
317     JMenu submenuinstance = null;
318     for (int i = 0, iSize = menu.getMenuComponentCount(); i < iSize; i++)
319     {
320       if (menu.getMenuComponent(i) instanceof JMenu
321               && ((JMenu) menu.getMenuComponent(i)).getText().equals(
322                       submenu))
323       {
324         submenuinstance = (JMenu) menu.getMenuComponent(i);
325       }
326     }
327     if (submenuinstance == null)
328     {
329       submenuinstance = new JMenu(submenu);
330       menu.add(submenuinstance);
331     }
332     return submenuinstance;
333
334   }
335
336   public void attachWSMenuEntry(JMenu wsmenu, final AlignFrame alignFrame)
337   {
338     // dynamically regenerate service list.
339     final JMenu jws2al = new JMenu("JABAWS Alignment");
340     jws2al.addMenuListener(new MenuListener()
341     {
342       // TODO: future: add menu listener to parent menu - so submenus are
343       // populated *before* they are selected.
344       @Override
345       public void menuSelected(MenuEvent e)
346       {
347         populateWSMenuEntry(jws2al, alignFrame);
348       }
349
350       @Override
351       public void menuDeselected(MenuEvent e)
352       {
353         // TODO Auto-generated method stub
354
355       }
356
357       @Override
358       public void menuCanceled(MenuEvent e)
359       {
360         // TODO Auto-generated method stub
361
362       }
363
364     });
365     wsmenu.add(jws2al);
366     
367   }
368
369   private void populateWSMenuEntry(JMenu jws2al, final AlignFrame alignFrame)
370   {
371     if (running || services == null || services.size() == 0)
372     {
373       return;
374     }
375     boolean byhost = Cache.getDefault("WSMENU_BYHOST", true), bytype = Cache
376             .getDefault("WSMENU_BYTYPE", true);
377     /**
378      * eventually, JWS2 services will appear under the same align/etc submenus.
379      * for moment we keep them separate.
380      */
381     JMenu atpoint;
382     MsaWSClient msacl = new MsaWSClient();
383     Vector hostLabels = new Vector();
384     jws2al.removeAll();
385     String lasthost=null;
386     for (final Jws2Instance service : services)
387     {
388       atpoint = jws2al;
389       String host = service.getHost();
390       String type = service.serviceType;
391       if (byhost)
392       {
393         atpoint = findOrCreateMenu(atpoint, host);
394         if (atpoint.getToolTipText() == null)
395         {
396           atpoint.setToolTipText("Services at " + host);
397         }
398       }
399       if (bytype)
400       {
401         atpoint = findOrCreateMenu(atpoint, type);
402         if (atpoint.getToolTipText() == null)
403         {
404           atpoint.setToolTipText(service.getActionText());
405         }
406       }
407       if (!byhost && !hostLabels.contains(host + service.serviceType+service.getActionText()))
408               //!hostLabels.contains(host + (bytype ? service.serviceType+service.getActionText() : "")))
409       {
410         // add a marker indicating where this service is hosted
411         // relies on services from the same host being listed in a contiguous
412         // group
413         JMenuItem hitm;
414         atpoint.addSeparator();
415         if (lasthost==null || !lasthost.equals(host))
416         {
417           atpoint.add(hitm = new JMenuItem(host));
418           hitm.setForeground(Color.blue);
419           lasthost = host;
420         }
421         hostLabels.addElement(host + service.serviceType+service.getActionText() );
422         // hostLabels.addElement(host + (bytype ? service.serviceType+service.getActionText() : ""));
423       }
424       msacl.attachWSMenuEntry(atpoint, service, alignFrame);
425       /*
426        * JMenuItem sitem = new JMenuItem(service.serviceType);
427        * sitem.setToolTipText("Hosted at " + service.hosturl);
428        * sitem.addActionListener(new ActionListener() {
429        * 
430        * @Override public void actionPerformed(ActionEvent e) { AlignmentView
431        * msa = alignFrame.gatherSequencesForAlignment(); MsaWSClient client =
432        * new MsaWSClient(service, "JWS2 Alignment of " + alignFrame.getTitle(),
433        * msa, false, true, alignFrame.getViewport().getAlignment().getDataset(),
434        * alignFrame); } });
435        */
436     }
437   }
438
439   public static void main(String[] args)
440   {
441     Thread runner = new Thread(getDiscoverer());
442     getDiscoverer().addPropertyChangeListener(new PropertyChangeListener()
443     {
444
445       public void propertyChange(PropertyChangeEvent evt)
446       {
447         System.out.println("Changesupport: There are now "
448                 + getDiscoverer().services.size() + " services");
449       }
450     });
451     runner.start();
452     while (runner.isAlive())
453     {
454       try
455       {
456         Thread.sleep(50);
457       } catch (InterruptedException e)
458       {
459       }
460       ;
461     }
462   }
463
464   private static Jws2Discoverer discoverer;
465
466   public static Jws2Discoverer getDiscoverer()
467   {
468     if (discoverer == null)
469     {
470       discoverer = new Jws2Discoverer();
471     }
472     return discoverer;
473   }
474
475   public boolean hasServices()
476   {
477     // TODO Auto-generated method stub
478     return !running && services != null && services.size() > 0;
479   }
480
481   public boolean isRunning()
482   {
483     return running;
484   }
485
486   /**
487    * the jalview .properties entry for JWS2 URLS
488    */
489   final static String JWS2HOSTURLS = "JWS2HOSTURLS";
490
491   public static void setServiceUrls(Vector<String> urls)
492   {
493     if (urls != null)
494     {
495       StringBuffer urlbuffer = new StringBuffer();
496       String sep = "";
497       for (String url : urls)
498       {
499         urlbuffer.append(sep);
500         urlbuffer.append(url);
501         sep = ",";
502       }
503       Cache.setProperty(JWS2HOSTURLS, urlbuffer.toString());
504     }
505     else
506     {
507       Cache.removeProperty(JWS2HOSTURLS);
508     }
509   }
510
511   public static Vector<String> getServiceUrls()
512   {
513     String surls = Cache.getDefault(JWS2HOSTURLS,
514             "http://www.compbio.dundee.ac.uk/jabaws");
515     Vector<String> urls = new Vector<String>();
516     try
517     {
518       StringTokenizer st = new StringTokenizer(surls, ",");
519       while (st.hasMoreElements())
520       {
521         String url = null;
522         try
523         {
524           java.net.URL u = new java.net.URL(url = st.nextToken());
525           if (!urls.contains(url))
526           {
527             urls.add(url);
528           }
529           else
530           {
531             jalview.bin.Cache.log.info("Ignoring duplicate url in "
532                     + JWS2HOSTURLS + " list");
533           }
534         } catch (Exception ex)
535         {
536           jalview.bin.Cache.log
537                   .warn("Problem whilst trying to make a URL from '"
538                           + ((url != null) ? url : "<null>") + "'");
539           jalview.bin.Cache.log
540                   .warn("This was probably due to a malformed comma separated list"
541                           + " in the "
542                           + JWS2HOSTURLS
543                           + " entry of $(HOME)/.jalview_properties)");
544           jalview.bin.Cache.log.debug("Exception was ", ex);
545         }
546       }
547     } catch (Exception ex)
548     {
549       jalview.bin.Cache.log.warn(
550               "Error parsing comma separated list of urls in "
551                       + JWS2HOSTURLS + " preference.", ex);
552     }
553     if (urls.size() >= 0)
554     {
555       return urls;
556     }
557     return null;
558   }
559
560   public Vector<Jws2Instance> getServices()
561   {
562     return (services == null) ? new Vector<Jws2Instance>()
563             : new Vector<Jws2Instance>(services);
564   }
565
566   /**
567    * test the given URL with the JabaWS test code
568    * 
569    * @param foo
570    * @return
571    */
572   public static boolean testServiceUrl(URL foo)
573   {
574     try
575     {
576       compbio.ws.client.WSTester.main(new String[]
577       { "-h=" + foo.toString() });
578     } catch (Exception e)
579     {
580       return false;
581     } catch (OutOfMemoryError e)
582     {
583       return false;
584     } catch (Error e)
585     {
586       return false;
587     }
588     return true;
589   }
590
591 }