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
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.gui.JvSwingUtils;
48 import jalview.ws.WSMenuEntryProviderI;
49 import jalview.ws.jws2.Jws2Discoverer.Jws2Instance;
50 import jalview.ws.params.ParamDatastoreI;
51 import compbio.data.msa.MsaWS;
52 import compbio.metadata.Option;
53 import compbio.metadata.Preset;
54 import compbio.metadata.PresetManager;
55 import compbio.metadata.RunnerConfig;
56 import compbio.ws.client.Jws2Client;
57 import compbio.ws.client.Services;
60 * discoverer for jws2 services. Follows the lightweight service discoverer
61 * pattern (archetyped by EnfinEnvision2OneWay)
66 public class Jws2Discoverer implements Runnable, WSMenuEntryProviderI
68 private java.beans.PropertyChangeSupport changeSupport = new java.beans.PropertyChangeSupport(
72 * change listeners are notified of "services" property changes
75 * to be added that consumes new services Hashtable object.
77 public void addPropertyChangeListener(
78 java.beans.PropertyChangeListener listener)
80 changeSupport.addPropertyChangeListener(listener);
89 public void removePropertyChangeListener(
90 java.beans.PropertyChangeListener listener)
92 changeSupport.removePropertyChangeListener(listener);
95 boolean running = false, aborted = false;
100 public boolean isAborted()
109 public void setAborted(boolean aborted)
111 this.aborted = aborted;
114 Thread oldthread = null;
118 if (running && oldthread != null && oldthread.isAlive())
129 .debug("Waiting around for old discovery thread to finish.");
130 // wait around until old discoverer dies
132 } catch (Exception e)
136 Cache.log.debug("Old discovery thread has finished.");
139 oldthread = Thread.currentThread();
142 Class foo = getClass().getClassLoader().loadClass(
143 "compbio.ws.client.Jws2Client");
144 } catch (ClassNotFoundException e)
147 .println("Not enabling JABA Webservices : client jar is not available."
148 + "\nPlease check that your webstart JNLP file is up to date!");
152 // reinitialise records of good and bad service URLs
153 if (services != null)
155 services.removeAllElements();
157 if (urlsWithoutServices != null)
159 urlsWithoutServices.removeAllElements();
161 if (invalidServiceUrls != null)
163 invalidServiceUrls.removeAllElements();
166 List<JabaWsServerQuery> qrys = new ArrayList<JabaWsServerQuery>();
167 for (final String jwsservers : getServiceUrls())
169 JabaWsServerQuery squery = new JabaWsServerQuery(this, jwsservers);
171 new Thread(squery).start();
173 boolean finished = false;
179 } catch (Exception e)
183 for (JabaWsServerQuery squery : qrys)
185 finished |= !squery.isRunning();
189 Cache.log.debug("Aborting " + qrys.size()
190 + " JABAWS discovery threads.");
191 for (JabaWsServerQuery squery : qrys)
193 squery.setQuit(true);
196 } while (!aborted && !finished);
201 changeSupport.firePropertyChange("services", new Vector(), services);
206 * record this service endpoint so we can use it
212 synchronized void addService(String jwsservers, Services srv,
215 if (services == null)
217 services = new Vector<Jws2Instance>();
219 System.out.println("Discovered service: " + jwsservers + " "
221 Jws2Instance service = new Jws2Instance(jwsservers, srv.toString(),
224 services.add(service);
225 // retrieve the presets and parameter set and cache now
226 service.getParamStore().getPresets();
227 service.hasParameters();
230 public class Jws2Instance
232 public String hosturl;
234 public String serviceType;
236 public MsaWS service;
238 public Jws2Instance(String hosturl, String serviceType, MsaWS service)
241 this.hosturl = hosturl;
242 this.serviceType = serviceType;
243 this.service = service;
246 PresetManager presets = null;
248 public JabaParamStore paramStore = null;
251 * non thread safe - gets the presets for this service (blocks whilst it
252 * calls the service to get the preset set)
254 * @return service presets or null if exceptions were raised.
256 public PresetManager getPresets()
262 presets = service.getPresets();
263 } catch (Exception ex)
266 .println("Exception when retrieving presets for service "
267 + serviceType + " at " + hosturl);
273 public String getHost()
277 * try { URL serviceurl = new URL(hosturl); if (serviceurl.getPort()!=80)
278 * { return serviceurl.getHost()+":"+serviceurl.getPort(); } return
279 * serviceurl.getHost(); } catch (Exception e) {
280 * System.err.println("Failed to parse service URL '" + hosturl +
281 * "' as a valid URL!"); } return null;
286 * @return short description of what the service will do
288 public String getActionText()
290 return "Align with " + serviceType;
294 * non-thread safe - blocks whilst accessing service to get complete set of
295 * available options and parameters
299 public RunnerConfig getRunnerConfig()
301 return service.getRunnerOptions();
305 protected void finalize() throws Throwable
311 Closeable svc = (Closeable) service;
314 } catch (Exception e)
322 public ParamDatastoreI getParamStore()
324 if (paramStore == null)
328 paramStore = new JabaParamStore(this,
329 (Desktop.instance != null ? Desktop
330 .getUserParameterStore() : null));
331 } catch (Exception ex)
339 public String getUri()
341 // this is only valid for Jaba 1.0 - this formula might have to change!
343 + (hosturl.lastIndexOf("/") == (hosturl.length() - 1) ? ""
344 : "/") + serviceType;
347 private boolean hasParams = false, lookedForParams = false;
349 public boolean hasParameters()
351 if (!lookedForParams)
353 lookedForParams = true;
356 hasParams = (getRunnerConfig().getArguments().size() > 0);
357 } catch (Exception e)
367 * holds list of services.
369 protected Vector<Jws2Instance> services;
371 public void attachWSMenuEntry(JMenu wsmenu, final AlignFrame alignFrame)
373 // dynamically regenerate service list.
374 final JMenu jws2al = wsmenu; // new JMenu("JABAWS Alignment");
375 jws2al.addMenuListener(new MenuListener()
377 // TODO: future: add menu listener to parent menu - so submenus are
378 // populated *before* they are selected.
380 public void menuSelected(MenuEvent e)
382 populateWSMenuEntry(jws2al, alignFrame);
386 public void menuDeselected(MenuEvent e)
388 // TODO Auto-generated method stub
393 public void menuCanceled(MenuEvent e)
395 // TODO Auto-generated method stub
404 private void populateWSMenuEntry(JMenu jws2al, final AlignFrame alignFrame)
406 if (running || services == null || services.size() == 0)
410 boolean byhost = Cache.getDefault("WSMENU_BYHOST", false), bytype = Cache
411 .getDefault("WSMENU_BYTYPE", false);
413 * eventually, JWS2 services will appear under the same align/etc submenus.
414 * for moment we keep them separate.
417 MsaWSClient msacl = new MsaWSClient();
418 Vector hostLabels = new Vector();
420 String lasthost = null;
421 Hashtable<String, ArrayList<Jws2Instance>> hosts = new Hashtable<String, ArrayList<Jws2Instance>>();
423 for (Jws2Instance service : services)
425 ArrayList<Jws2Instance> hostservices = hosts.get(service.getHost());
426 if (hostservices == null)
428 hosts.put(service.getHost(),
429 hostservices = new ArrayList<Jws2Instance>());
431 hostservices.add(service);
433 sorton = hosts.keySet().toArray(new String[1]);
434 String hostlist[] = sorton.clone();
435 jalview.util.QuickSort.sort(sorton, hostlist);
436 for (String host : hostlist)
438 Jws2Instance orderedsvcs[] = hosts.get(host).toArray(
439 new Jws2Instance[1]);
440 String sortbytype[] = new String[orderedsvcs.length];
441 for (int i = 0; i < sortbytype.length; i++)
443 sortbytype[i] = orderedsvcs[i].serviceType;
445 jalview.util.QuickSort.sort(sortbytype, orderedsvcs);
446 for (final Jws2Instance service : orderedsvcs)
449 String type = service.serviceType;
452 atpoint = JvSwingUtils.findOrCreateMenu(atpoint, host);
453 if (atpoint.getToolTipText() == null)
455 atpoint.setToolTipText("Services at " + host);
460 atpoint = JvSwingUtils.findOrCreateMenu(atpoint, type);
461 if (atpoint.getToolTipText() == null)
463 atpoint.setToolTipText(service.getActionText());
467 && !hostLabels.contains(host + service.serviceType
468 + service.getActionText()))
469 // !hostLabels.contains(host + (bytype ?
470 // service.serviceType+service.getActionText() : "")))
472 // add a marker indicating where this service is hosted
473 // relies on services from the same host being listed in a
477 atpoint.addSeparator();
478 if (lasthost == null || !lasthost.equals(host))
480 atpoint.add(hitm = new JMenuItem(host));
481 hitm.setForeground(Color.blue);
482 hitm.addActionListener(new ActionListener()
486 public void actionPerformed(ActionEvent e)
488 Desktop.showUrl(service.getHost());
491 hitm.setToolTipText(JvSwingUtils
492 .wrapTooltip("Opens the JABAWS server's homepage in web browser"));
495 hostLabels.addElement(host + service.serviceType
496 + service.getActionText());
497 // hostLabels.addElement(host + (bytype ?
498 // service.serviceType+service.getActionText() : ""));
500 msacl.attachWSMenuEntry(atpoint, service, alignFrame);
502 * JMenuItem sitem = new JMenuItem(service.serviceType);
503 * sitem.setToolTipText("Hosted at " + service.hosturl);
504 * sitem.addActionListener(new ActionListener() {
506 * @Override public void actionPerformed(ActionEvent e) { AlignmentView
507 * msa = alignFrame.gatherSequencesForAlignment(); MsaWSClient client =
508 * new MsaWSClient(service, "JWS2 Alignment of " +
509 * alignFrame.getTitle(), msa, false, true,
510 * alignFrame.getViewport().getAlignment().getDataset(), alignFrame); }
518 public static void main(String[] args)
520 Thread runner = getDiscoverer().startDiscoverer(
521 new PropertyChangeListener()
524 public void propertyChange(PropertyChangeEvent evt)
526 if (getDiscoverer().services != null)
528 System.out.println("Changesupport: There are now "
529 + getDiscoverer().services.size() + " services");
534 while (runner.isAlive())
539 } catch (InterruptedException e)
546 private static Jws2Discoverer discoverer;
548 public static Jws2Discoverer getDiscoverer()
550 if (discoverer == null)
552 discoverer = new Jws2Discoverer();
557 public boolean hasServices()
559 // TODO Auto-generated method stub
560 return !running && services != null && services.size() > 0;
563 public boolean isRunning()
569 * the jalview .properties entry for JWS2 URLS
571 final static String JWS2HOSTURLS = "JWS2HOSTURLS";
573 public static void setServiceUrls(Vector<String> urls)
577 StringBuffer urlbuffer = new StringBuffer();
579 for (String url : urls)
581 urlbuffer.append(sep);
582 urlbuffer.append(url);
585 Cache.setProperty(JWS2HOSTURLS, urlbuffer.toString());
589 Cache.removeProperty(JWS2HOSTURLS);
593 public static Vector<String> getServiceUrls()
595 String surls = Cache.getDefault(JWS2HOSTURLS,
596 "http://www.compbio.dundee.ac.uk/jabaws");
597 Vector<String> urls = new Vector<String>();
600 StringTokenizer st = new StringTokenizer(surls, ",");
601 while (st.hasMoreElements())
606 java.net.URL u = new java.net.URL(url = st.nextToken());
607 if (!urls.contains(url))
613 jalview.bin.Cache.log.info("Ignoring duplicate url in "
614 + JWS2HOSTURLS + " list");
616 } catch (Exception ex)
618 jalview.bin.Cache.log
619 .warn("Problem whilst trying to make a URL from '"
620 + ((url != null) ? url : "<null>") + "'");
621 jalview.bin.Cache.log
622 .warn("This was probably due to a malformed comma separated list"
625 + " entry of $(HOME)/.jalview_properties)");
626 jalview.bin.Cache.log.debug("Exception was ", ex);
629 } catch (Exception ex)
631 jalview.bin.Cache.log.warn(
632 "Error parsing comma separated list of urls in "
633 + JWS2HOSTURLS + " preference.", ex);
635 if (urls.size() >= 0)
642 public Vector<Jws2Instance> getServices()
644 return (services == null) ? new Vector<Jws2Instance>()
645 : new Vector<Jws2Instance>(services);
649 * test the given URL with the JabaWS test code
654 public static boolean testServiceUrl(URL foo)
658 compbio.ws.client.WSTester.main(new String[]
659 { "-h=" + foo.toString() });
660 } catch (Exception e)
664 } catch (OutOfMemoryError e)
678 * Start a fresh discovery thread and notify the given object when we're
679 * finished. Any known existing threads will be killed before this one is
682 * @param changeSupport2
685 public Thread startDiscoverer(PropertyChangeListener changeSupport2)
691 addPropertyChangeListener(changeSupport2);
692 Thread thr = new Thread(this);
697 Vector<String> invalidServiceUrls = null, urlsWithoutServices = null;
700 * @return the invalidServiceUrls
702 public Vector<String> getInvalidServiceUrls()
704 return invalidServiceUrls;
708 * @return the urlsWithoutServices
710 public Vector<String> getUrlsWithoutServices()
712 return urlsWithoutServices;
716 * add an 'empty' JABA server to the list. Only servers not already in the
717 * 'bad URL' list will be added to this list.
721 public synchronized void addUrlwithnoservices(String jwsservers)
723 if (urlsWithoutServices == null)
725 urlsWithoutServices = new Vector<String>();
728 if ((invalidServiceUrls == null || !invalidServiceUrls
729 .contains(jwsservers))
730 && !urlsWithoutServices.contains(jwsservers))
732 urlsWithoutServices.add(jwsservers);
737 * add a bad URL to the list
741 public synchronized void addInvalidServiceUrl(String jwsservers)
743 if (invalidServiceUrls == null)
745 invalidServiceUrls = new Vector<String>();
747 if (!invalidServiceUrls.contains(jwsservers))
749 invalidServiceUrls.add(jwsservers);
755 * @return a human readable report of any problems with the service URLs used
758 public String getErrorMessages()
760 if (!isRunning() && !isAborted())
762 StringBuffer ermsg = new StringBuffer();
763 boolean list = false;
764 if (getInvalidServiceUrls() != null
765 && getInvalidServiceUrls().size() > 0)
767 ermsg.append("URLs that could not be contacted: \n");
768 for (String svcurl : getInvalidServiceUrls())
775 ermsg.append(svcurl);
777 ermsg.append("\n\n");
780 if (getUrlsWithoutServices() != null
781 && getUrlsWithoutServices().size() > 0)
783 ermsg.append("URLs without any JABA Services : \n");
784 for (String svcurl : getUrlsWithoutServices())
791 ermsg.append(svcurl);
795 if (ermsg.length() > 1)
797 return ermsg.toString();