2 * Jalview - A Sequence Alignment Editor and Viewer (Version 2.6)
3 * Copyright (C) 2010 J Procter, AM Waterhouse, G Barton, M Clamp, S Searle
5 * This file is part of Jalview.
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.
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.
16 * You should have received a copy of the GNU General Public License along with Jalview. If not, see <http://www.gnu.org/licenses/>.
18 package jalview.ws.jws2;
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.io.Closeable;
26 import java.net.ConnectException;
28 import java.util.ArrayList;
29 import java.util.HashSet;
30 import java.util.Hashtable;
31 import java.util.List;
32 import java.util.StringTokenizer;
33 import java.util.Vector;
35 import javax.swing.JMenu;
36 import javax.swing.JMenuItem;
37 import javax.swing.event.MenuEvent;
38 import javax.swing.event.MenuListener;
40 import org.apache.log4j.Level;
42 import jalview.bin.Cache;
43 import jalview.datamodel.AlignmentView;
44 import jalview.gui.AlignFrame;
45 import jalview.gui.Desktop;
46 import jalview.gui.JalviewChangeSupport;
47 import jalview.ws.WSMenuEntryProviderI;
48 import jalview.ws.params.ParamDatastoreI;
49 import compbio.data.msa.MsaWS;
50 import compbio.metadata.Option;
51 import compbio.metadata.Preset;
52 import compbio.metadata.PresetManager;
53 import compbio.metadata.RunnerConfig;
54 import compbio.ws.client.Jws2Client;
55 import compbio.ws.client.Services;
58 * discoverer for jws2 services. Follows the lightweight service discoverer
59 * pattern (archetyped by EnfinEnvision2OneWay)
64 public class Jws2Discoverer implements Runnable, WSMenuEntryProviderI
66 private java.beans.PropertyChangeSupport changeSupport = new java.beans.PropertyChangeSupport(
70 * change listeners are notified of "services" property changes
73 * to be added that consumes new services Hashtable object.
75 public void addPropertyChangeListener(
76 java.beans.PropertyChangeListener listener)
78 changeSupport.addPropertyChangeListener(listener);
87 public void removePropertyChangeListener(
88 java.beans.PropertyChangeListener listener)
90 changeSupport.removePropertyChangeListener(listener);
93 boolean running = false, aborted = false;
99 public void setAborted(boolean aborted)
101 this.aborted = aborted;
104 Thread oldthread = null;
108 if (running && oldthread != null && oldthread.isAlive())
119 .debug("Waiting around for old discovery thread to finish.");
120 // wait around until old discoverer dies
122 } catch (Exception e)
126 Cache.log.debug("Old discovery thread has finished.");
129 oldthread = Thread.currentThread();
132 Class foo = getClass().getClassLoader().loadClass(
133 "compbio.ws.client.Jws2Client");
134 } catch (ClassNotFoundException e)
137 .println("Not enabling Jalview Webservices version 2: client jar is not available."
138 + "\nPlease check that your webstart JNLP file is up to date!");
142 if (services != null)
144 services.removeAllElements();
146 List<JabaWsServerQuery> qrys = new ArrayList<JabaWsServerQuery>();
147 for (final String jwsservers : getServiceUrls())
149 JabaWsServerQuery squery = new JabaWsServerQuery(this, jwsservers);
151 new Thread(squery).start();
153 boolean finished = false;
159 } catch (Exception e)
163 for (JabaWsServerQuery squery : qrys)
165 finished |= !squery.isRunning();
169 Cache.log.debug("Aborting " + qrys.size()
170 + " JABAWS discovery threads.");
171 for (JabaWsServerQuery squery : qrys)
173 squery.setQuit(true);
176 } while (!aborted && !finished);
181 changeSupport.firePropertyChange("services", new Vector(), services);
186 * record this service endpoint so we can use it
192 synchronized void addService(String jwsservers, Services srv,
195 if (services == null)
197 services = new Vector<Jws2Instance>();
199 System.out.println("Discovered service: " + jwsservers + " "
201 Jws2Instance service = new Jws2Instance(jwsservers, srv.toString(),
204 services.add(service);
205 // retrieve the presets and parameter set and cache now
206 service.getParamStore().getPresets();
207 service.hasParameters();
210 public class Jws2Instance
212 public String hosturl;
214 public String serviceType;
216 public MsaWS service;
218 public Jws2Instance(String hosturl, String serviceType, MsaWS service)
221 this.hosturl = hosturl;
222 this.serviceType = serviceType;
223 this.service = service;
226 PresetManager presets = null;
228 public JabaParamStore paramStore = null;
231 * non thread safe - gets the presets for this service (blocks whilst it
232 * calls the service to get the preset set)
234 * @return service presets or null if exceptions were raised.
236 public PresetManager getPresets()
242 presets = service.getPresets();
243 } catch (Exception ex)
246 .println("Exception when retrieving presets for service "
247 + serviceType + " at " + hosturl);
253 public String getHost()
257 * try { URL serviceurl = new URL(hosturl); if (serviceurl.getPort()!=80)
258 * { return serviceurl.getHost()+":"+serviceurl.getPort(); } return
259 * serviceurl.getHost(); } catch (Exception e) {
260 * System.err.println("Failed to parse service URL '" + hosturl +
261 * "' as a valid URL!"); } return null;
266 * @return short description of what the service will do
268 public String getActionText()
270 return "Align with " + serviceType;
274 * non-thread safe - blocks whilst accessing service to get complete set of
275 * available options and parameters
279 public RunnerConfig getRunnerConfig()
281 return service.getRunnerOptions();
285 protected void finalize() throws Throwable
291 Closeable svc = (Closeable) service;
294 } catch (Exception e)
302 public ParamDatastoreI getParamStore()
304 if (paramStore == null)
308 paramStore = new JabaParamStore(this,
309 (Desktop.instance != null ? Desktop
310 .getUserParameterStore() : null));
311 } catch (Exception ex)
319 public String getUri()
321 // this is only valid for Jaba 1.0 - this formula might have to change!
323 + (hosturl.lastIndexOf("/") == (hosturl.length() - 1) ? "/"
327 private boolean hasParams = false, lookedForParams = false;
329 public boolean hasParameters()
331 if (!lookedForParams)
333 lookedForParams = true;
336 hasParams = (getRunnerConfig().getArguments().size() > 0);
337 } catch (Exception e)
347 * holds list of services.
349 protected Vector<Jws2Instance> services;
352 * find or add a submenu with the given title in the given menu
356 * @return the new or existing submenu
358 private JMenu findOrCreateMenu(JMenu menu, String submenu)
360 JMenu submenuinstance = null;
361 for (int i = 0, iSize = menu.getMenuComponentCount(); i < iSize; i++)
363 if (menu.getMenuComponent(i) instanceof JMenu
364 && ((JMenu) menu.getMenuComponent(i)).getText().equals(
367 submenuinstance = (JMenu) menu.getMenuComponent(i);
370 if (submenuinstance == null)
372 submenuinstance = new JMenu(submenu);
373 menu.add(submenuinstance);
375 return submenuinstance;
379 public void attachWSMenuEntry(JMenu wsmenu, final AlignFrame alignFrame)
381 // dynamically regenerate service list.
382 final JMenu jws2al = new JMenu("JABAWS Alignment");
383 jws2al.addMenuListener(new MenuListener()
385 // TODO: future: add menu listener to parent menu - so submenus are
386 // populated *before* they are selected.
388 public void menuSelected(MenuEvent e)
390 populateWSMenuEntry(jws2al, alignFrame);
394 public void menuDeselected(MenuEvent e)
396 // TODO Auto-generated method stub
401 public void menuCanceled(MenuEvent e)
403 // TODO Auto-generated method stub
412 private void populateWSMenuEntry(JMenu jws2al, final AlignFrame alignFrame)
414 if (running || services == null || services.size() == 0)
418 boolean byhost = Cache.getDefault("WSMENU_BYHOST", true), bytype = Cache
419 .getDefault("WSMENU_BYTYPE", true);
421 * eventually, JWS2 services will appear under the same align/etc submenus.
422 * for moment we keep them separate.
425 MsaWSClient msacl = new MsaWSClient();
426 Vector hostLabels = new Vector();
428 String lasthost = null;
429 for (final Jws2Instance service : services)
432 String host = service.getHost();
433 String type = service.serviceType;
436 atpoint = findOrCreateMenu(atpoint, host);
437 if (atpoint.getToolTipText() == null)
439 atpoint.setToolTipText("Services at " + host);
444 atpoint = findOrCreateMenu(atpoint, type);
445 if (atpoint.getToolTipText() == null)
447 atpoint.setToolTipText(service.getActionText());
451 && !hostLabels.contains(host + service.serviceType
452 + service.getActionText()))
453 // !hostLabels.contains(host + (bytype ?
454 // service.serviceType+service.getActionText() : "")))
456 // add a marker indicating where this service is hosted
457 // relies on services from the same host being listed in a contiguous
460 atpoint.addSeparator();
461 if (lasthost == null || !lasthost.equals(host))
463 atpoint.add(hitm = new JMenuItem(host));
464 hitm.setForeground(Color.blue);
467 hostLabels.addElement(host + service.serviceType
468 + service.getActionText());
469 // hostLabels.addElement(host + (bytype ?
470 // service.serviceType+service.getActionText() : ""));
472 msacl.attachWSMenuEntry(atpoint, service, alignFrame);
474 * JMenuItem sitem = new JMenuItem(service.serviceType);
475 * sitem.setToolTipText("Hosted at " + service.hosturl);
476 * sitem.addActionListener(new ActionListener() {
478 * @Override public void actionPerformed(ActionEvent e) { AlignmentView
479 * msa = alignFrame.gatherSequencesForAlignment(); MsaWSClient client =
480 * new MsaWSClient(service, "JWS2 Alignment of " + alignFrame.getTitle(),
481 * msa, false, true, alignFrame.getViewport().getAlignment().getDataset(),
487 public static void main(String[] args)
489 Thread runner = getDiscoverer().startDiscoverer(new PropertyChangeListener()
492 public void propertyChange(PropertyChangeEvent evt)
494 if (getDiscoverer().services!=null)
495 {System.out.println("Changesupport: There are now "
496 + getDiscoverer().services.size() + " services");
501 while (runner.isAlive())
506 } catch (InterruptedException e)
513 private static Jws2Discoverer discoverer;
515 public static Jws2Discoverer getDiscoverer()
517 if (discoverer == null)
519 discoverer = new Jws2Discoverer();
524 public boolean hasServices()
526 // TODO Auto-generated method stub
527 return !running && services != null && services.size() > 0;
530 public boolean isRunning()
536 * the jalview .properties entry for JWS2 URLS
538 final static String JWS2HOSTURLS = "JWS2HOSTURLS";
540 public static void setServiceUrls(Vector<String> urls)
544 StringBuffer urlbuffer = new StringBuffer();
546 for (String url : urls)
548 urlbuffer.append(sep);
549 urlbuffer.append(url);
552 Cache.setProperty(JWS2HOSTURLS, urlbuffer.toString());
556 Cache.removeProperty(JWS2HOSTURLS);
560 public static Vector<String> getServiceUrls()
562 String surls = Cache.getDefault(JWS2HOSTURLS,
563 "http://www.compbio.dundee.ac.uk/jabaws");
564 Vector<String> urls = new Vector<String>();
567 StringTokenizer st = new StringTokenizer(surls, ",");
568 while (st.hasMoreElements())
573 java.net.URL u = new java.net.URL(url = st.nextToken());
574 if (!urls.contains(url))
580 jalview.bin.Cache.log.info("Ignoring duplicate url in "
581 + JWS2HOSTURLS + " list");
583 } catch (Exception ex)
585 jalview.bin.Cache.log
586 .warn("Problem whilst trying to make a URL from '"
587 + ((url != null) ? url : "<null>") + "'");
588 jalview.bin.Cache.log
589 .warn("This was probably due to a malformed comma separated list"
592 + " entry of $(HOME)/.jalview_properties)");
593 jalview.bin.Cache.log.debug("Exception was ", ex);
596 } catch (Exception ex)
598 jalview.bin.Cache.log.warn(
599 "Error parsing comma separated list of urls in "
600 + JWS2HOSTURLS + " preference.", ex);
602 if (urls.size() >= 0)
609 public Vector<Jws2Instance> getServices()
611 return (services == null) ? new Vector<Jws2Instance>()
612 : new Vector<Jws2Instance>(services);
616 * test the given URL with the JabaWS test code
621 public static boolean testServiceUrl(URL foo)
625 compbio.ws.client.WSTester.main(new String[]
626 { "-h=" + foo.toString() });
627 } catch (Exception e)
630 } catch (OutOfMemoryError e)
641 * Start a fresh discovery thread and notify the given object when we're finished. Any known existing threads will be killed before this one is started.
642 * @param changeSupport2
645 public Thread startDiscoverer(PropertyChangeListener changeSupport2)
651 addPropertyChangeListener(changeSupport2);
652 Thread thr = new Thread(this);