2 * Jalview - A Sequence Alignment Editor and Viewer (Version 2.8.0b1)
3 * Copyright (C) 2014 The Jalview Authors
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/>.
17 * The Jalview Authors are detailed in the 'AUTHORS' file.
19 package jalview.ws.jws2;
21 import jalview.bin.Cache;
22 import jalview.gui.AlignFrame;
23 import jalview.gui.Desktop;
24 import jalview.gui.JvSwingUtils;
25 import jalview.ws.WSMenuEntryProviderI;
26 import jalview.ws.jws2.jabaws2.Jws2Instance;
27 import jalview.ws.params.ParamDatastoreI;
29 import java.awt.Color;
30 import java.awt.event.ActionEvent;
31 import java.awt.event.ActionListener;
32 import java.beans.PropertyChangeEvent;
33 import java.beans.PropertyChangeListener;
35 import java.util.ArrayList;
36 import java.util.Arrays;
37 import java.util.HashMap;
38 import java.util.HashSet;
39 import java.util.Hashtable;
40 import java.util.List;
42 import java.util.StringTokenizer;
43 import java.util.Vector;
45 import javax.swing.JMenu;
46 import javax.swing.JMenuItem;
48 import compbio.ws.client.Services;
51 * discoverer for jws2 services. Follows the lightweight service discoverer
52 * pattern (archetyped by EnfinEnvision2OneWay)
57 public class Jws2Discoverer implements Runnable, WSMenuEntryProviderI
59 private java.beans.PropertyChangeSupport changeSupport = new java.beans.PropertyChangeSupport(
63 * change listeners are notified of "services" property changes
66 * to be added that consumes new services Hashtable object.
68 public void addPropertyChangeListener(
69 java.beans.PropertyChangeListener listener)
71 changeSupport.addPropertyChangeListener(listener);
80 public void removePropertyChangeListener(
81 java.beans.PropertyChangeListener listener)
83 changeSupport.removePropertyChangeListener(listener);
86 boolean running = false, aborted = false;
91 public boolean isAborted()
100 public void setAborted(boolean aborted)
102 this.aborted = aborted;
105 Thread oldthread = null;
109 if (running && oldthread != null && oldthread.isAlive())
120 .debug("Waiting around for old discovery thread to finish.");
121 // wait around until old discoverer dies
123 } catch (Exception e)
127 Cache.log.debug("Old discovery thread has finished.");
130 changeSupport.firePropertyChange("services", services, new Vector());
131 oldthread = Thread.currentThread();
134 Class foo = getClass().getClassLoader().loadClass(
135 "compbio.ws.client.Jws2Client");
136 } catch (ClassNotFoundException e)
139 .println("Not enabling JABA Webservices : client jar is not available."
140 + "\nPlease check that your webstart JNLP file is up to date!");
144 // reinitialise records of good and bad service URLs
145 if (services != null)
147 services.removeAllElements();
149 if (urlsWithoutServices != null)
151 urlsWithoutServices.removeAllElements();
153 if (invalidServiceUrls != null)
155 invalidServiceUrls.removeAllElements();
157 if (validServiceUrls != null)
159 validServiceUrls.removeAllElements();
161 ArrayList<String> svctypes = new ArrayList<String>();
163 List<JabaWsServerQuery> qrys = new ArrayList<JabaWsServerQuery>();
164 for (final String jwsservers : getServiceUrls())
166 JabaWsServerQuery squery = new JabaWsServerQuery(this, jwsservers);
167 if (svctypes.size() == 0)
169 // TODO: remove this ugly hack to get Canonical JABA service ordering
170 // for all possible services
171 for (Services sv : squery.JABAWS2SERVERS)
173 svctypes.add(sv.toString());
178 new Thread(squery).start();
180 boolean finished = true;
187 } catch (Exception e)
191 for (JabaWsServerQuery squery : qrys)
193 finished = finished && !squery.isRunning();
197 Cache.log.debug("Aborting " + qrys.size()
198 + " JABAWS discovery threads.");
199 for (JabaWsServerQuery squery : qrys)
201 squery.setQuit(true);
204 } while (!aborted && !finished);
207 // resort services according to order found in jabaws service list
208 // also ensure servics for each host are ordered in same way.
210 if (services != null && services.size() > 0)
212 Jws2Instance[] svcs = new Jws2Instance[services.size()];
213 int[] spos = new int[services.size()];
215 Vector svcUrls = getServiceUrls();
216 for (Jws2Instance svc : services)
219 spos[ipos++] = 1000 * svcUrls.indexOf(svc.getHost()) + 1
220 + svctypes.indexOf(svc.serviceType);
222 jalview.util.QuickSort.sort(spos, svcs);
223 services = new Vector<Jws2Instance>();
224 for (Jws2Instance svc : svcs)
232 changeSupport.firePropertyChange("services", new Vector(), services);
236 * record this service endpoint so we can use it
242 synchronized void addService(String jwsservers, Jws2Instance service)
244 if (services == null)
246 services = new Vector<Jws2Instance>();
248 System.out.println("Discovered service: " + jwsservers + " "
249 + service.toString());
250 // Jws2Instance service = new Jws2Instance(jwsservers, srv.toString(),
253 services.add(service);
254 // retrieve the presets and parameter set and cache now
255 ParamDatastoreI pds = service.getParamStore();
260 service.hasParameters();
261 if (validServiceUrls == null)
263 validServiceUrls = new Vector();
265 validServiceUrls.add(jwsservers);
269 * holds list of services.
271 protected Vector<Jws2Instance> services;
274 * attach all available web services to the appropriate submenu in the given
277 public void attachWSMenuEntry(JMenu wsmenu, final AlignFrame alignFrame)
279 // dynamically regenerate service list.
280 populateWSMenuEntry(wsmenu, alignFrame, null);
283 private boolean isRecalculable(String action)
285 return (action != null && action.equalsIgnoreCase("conservation"));
288 private void populateWSMenuEntry(JMenu jws2al,
289 final AlignFrame alignFrame, String typeFilter)
291 if (running || services == null || services.size() == 0)
295 boolean byhost = Cache.getDefault("WSMENU_BYHOST", false), bytype = Cache
296 .getDefault("WSMENU_BYTYPE", false);
298 * eventually, JWS2 services will appear under the same align/etc submenus.
299 * for moment we keep them separate.
302 List<Jws2Instance> enumerableServices = new ArrayList<Jws2Instance>();
303 // jws2al.removeAll();
304 Map<String, Jws2Instance> preferredHosts = new HashMap<String, Jws2Instance>();
305 Map<String, List<Jws2Instance>> alternates = new HashMap<String, List<Jws2Instance>>();
306 for (Jws2Instance service : services.toArray(new Jws2Instance[0]))
308 if (!isRecalculable(service.action))
310 // add 'one shot' services to be displayed using the classic menu
312 enumerableServices.add(service);
316 if (!preferredHosts.containsKey(service.serviceType))
318 Jws2Instance preferredInstance = getPreferredServiceFor(
319 alignFrame, service.serviceType);
320 if (preferredInstance != null)
322 preferredHosts.put(service.serviceType, preferredInstance);
326 preferredHosts.put(service.serviceType, service);
329 List<Jws2Instance> ph = alternates.get(service.serviceType);
330 if (preferredHosts.get(service.serviceType) != service)
334 ph = new ArrayList<Jws2Instance>();
337 alternates.put(service.serviceType, ph);
343 // create GUI element for classic services
344 addEnumeratedServices(jws2al, alignFrame, enumerableServices);
345 // and the instantaneous services
346 for (final Jws2Instance service : preferredHosts.values())
348 atpoint = JvSwingUtils.findOrCreateMenu(jws2al, service.action);
350 if (atpoint.getItemCount() > 1)
352 // previous service of this type already present
353 atpoint.addSeparator();
355 atpoint.add(hitm = new JMenuItem(service.getHost()));
356 hitm.setForeground(Color.blue);
357 hitm.addActionListener(new ActionListener()
361 public void actionPerformed(ActionEvent e)
363 Desktop.showUrl(service.getHost());
366 hitm.setToolTipText(JvSwingUtils
367 .wrapTooltip("Opens the JABAWS server's homepage in web browser"));
369 service.attachWSMenuEntry(atpoint, alignFrame);
370 if (alternates.containsKey(service.serviceType))
372 atpoint.add(hitm = new JMenu("Switch server"));
373 hitm.setToolTipText(JvSwingUtils
374 .wrapTooltip("Choose a server for running this service"));
375 for (final Jws2Instance sv : alternates.get(service.serviceType))
378 hitm.add(itm = new JMenuItem(sv.getHost()));
379 itm.setForeground(Color.blue);
380 itm.addActionListener(new ActionListener()
384 public void actionPerformed(ActionEvent arg0)
386 new Thread(new Runnable()
390 setPreferredServiceFor(alignFrame, sv.serviceType,
392 changeSupport.firePropertyChange("services",
393 new Vector(), services);
401 * hitm.addActionListener(new ActionListener() {
403 * @Override public void actionPerformed(ActionEvent arg0) { new
404 * Thread(new Runnable() {
406 * @Override public void run() { new SetPreferredServer(alignFrame,
407 * service.serviceType, service.action); } }).start(); } });
414 * add services using the Java 2.5/2.6/2.7 system which optionally creates
415 * submenus to index by host and service program type
417 private void addEnumeratedServices(final JMenu jws2al,
418 final AlignFrame alignFrame, List<Jws2Instance> enumerableServices)
420 boolean byhost = Cache.getDefault("WSMENU_BYHOST", false), bytype = Cache
421 .getDefault("WSMENU_BYTYPE", false);
423 * eventually, JWS2 services will appear under the same align/etc submenus.
424 * for moment we keep them separate.
427 MsaWSClient msacl = new MsaWSClient();
428 List<String> hostLabels = new ArrayList<String>();
429 Hashtable<String, String> lasthostFor = new Hashtable<String, String>();
430 Hashtable<String, ArrayList<Jws2Instance>> hosts = new Hashtable<String, ArrayList<Jws2Instance>>();
431 ArrayList<String> hostlist = new ArrayList<String>();
432 for (Jws2Instance service : enumerableServices)
434 ArrayList<Jws2Instance> hostservices = hosts.get(service.getHost());
435 if (hostservices == null)
437 hosts.put(service.getHost(),
438 hostservices = new ArrayList<Jws2Instance>());
439 hostlist.add(service.getHost());
441 hostservices.add(service);
443 // now add hosts in order of the given array
444 for (String host : hostlist)
446 Jws2Instance orderedsvcs[] = hosts.get(host).toArray(
447 new Jws2Instance[1]);
448 String sortbytype[] = new String[orderedsvcs.length];
449 for (int i = 0; i < sortbytype.length; i++)
451 sortbytype[i] = orderedsvcs[i].serviceType;
453 jalview.util.QuickSort.sort(sortbytype, orderedsvcs);
454 for (final Jws2Instance service : orderedsvcs)
456 atpoint = JvSwingUtils.findOrCreateMenu(jws2al, service.action);
457 String type = service.serviceType;
460 atpoint = JvSwingUtils.findOrCreateMenu(atpoint, host);
461 if (atpoint.getToolTipText() == null)
463 atpoint.setToolTipText("Services at " + host);
468 atpoint = JvSwingUtils.findOrCreateMenu(atpoint, type);
469 if (atpoint.getToolTipText() == null)
471 atpoint.setToolTipText(service.getActionText());
475 && !hostLabels.contains(host + service.serviceType
476 + service.getActionText()))
477 // !hostLabels.contains(host + (bytype ?
478 // service.serviceType+service.getActionText() : "")))
480 // add a marker indicating where this service is hosted
481 // relies on services from the same host being listed in a
485 if (hostLabels.contains(host))
487 atpoint.addSeparator();
491 hostLabels.add(host);
493 if (lasthostFor.get(service.action) == null
494 || !lasthostFor.get(service.action).equals(host))
496 atpoint.add(hitm = new JMenuItem(host));
497 hitm.setForeground(Color.blue);
498 hitm.addActionListener(new ActionListener()
502 public void actionPerformed(ActionEvent e)
504 Desktop.showUrl(service.getHost());
507 hitm.setToolTipText(JvSwingUtils
508 .wrapTooltip("Opens the JABAWS server's homepage in web browser"));
509 lasthostFor.put(service.action, host);
511 hostLabels.add(host + service.serviceType
512 + service.getActionText());
515 service.attachWSMenuEntry(atpoint, alignFrame);
520 public static void main(String[] args)
524 testUrls = new Vector<String>();
525 for (String url : args)
531 Thread runner = getDiscoverer().startDiscoverer(
532 new PropertyChangeListener()
535 public void propertyChange(PropertyChangeEvent evt)
537 if (getDiscoverer().services != null)
539 System.out.println("Changesupport: There are now "
540 + getDiscoverer().services.size() + " services");
542 for (Jws2Instance instance : getDiscoverer().services)
544 System.out.println("Service " + i++ + " "
545 + instance.getClass() + "@"
546 + instance.getHost() + ": "
547 + instance.getActionText());
553 while (runner.isAlive())
558 } catch (InterruptedException e)
566 } catch (InterruptedException x)
571 private static Jws2Discoverer discoverer;
573 public static Jws2Discoverer getDiscoverer()
575 if (discoverer == null)
577 discoverer = new Jws2Discoverer();
582 public boolean hasServices()
584 // TODO Auto-generated method stub
585 return !running && services != null && services.size() > 0;
588 public boolean isRunning()
594 * the jalview .properties entry for JWS2 URLS
596 final static String JWS2HOSTURLS = "JWS2HOSTURLS";
598 public static void setServiceUrls(Vector<String> urls)
602 StringBuffer urlbuffer = new StringBuffer();
604 for (String url : urls)
606 urlbuffer.append(sep);
607 urlbuffer.append(url);
610 Cache.setProperty(JWS2HOSTURLS, urlbuffer.toString());
614 Cache.removeProperty(JWS2HOSTURLS);
618 private static Vector<String> testUrls = null;
620 public static Vector<String> getServiceUrls()
622 if (testUrls != null)
624 // return test urls, if there are any, instead of touching cache
627 String surls = Cache.getDefault(JWS2HOSTURLS,
628 "http://www.compbio.dundee.ac.uk/jabaws");
629 Vector<String> urls = new Vector<String>();
632 StringTokenizer st = new StringTokenizer(surls, ",");
633 while (st.hasMoreElements())
638 java.net.URL u = new java.net.URL(url = st.nextToken());
639 if (!urls.contains(url))
645 jalview.bin.Cache.log.info("Ignoring duplicate url in "
646 + JWS2HOSTURLS + " list");
648 } catch (Exception ex)
650 jalview.bin.Cache.log
651 .warn("Problem whilst trying to make a URL from '"
652 + ((url != null) ? url : "<null>") + "'");
653 jalview.bin.Cache.log
654 .warn("This was probably due to a malformed comma separated list"
657 + " entry of $(HOME)/.jalview_properties)");
658 jalview.bin.Cache.log.debug("Exception was ", ex);
661 } catch (Exception ex)
663 jalview.bin.Cache.log.warn(
664 "Error parsing comma separated list of urls in "
665 + JWS2HOSTURLS + " preference.", ex);
667 if (urls.size() >= 0)
674 public Vector<Jws2Instance> getServices()
676 return (services == null) ? new Vector<Jws2Instance>()
677 : new Vector<Jws2Instance>(services);
681 * test the given URL with the JabaWS test code
686 public static boolean testServiceUrl(URL foo)
690 compbio.ws.client.WSTester.main(new String[]
691 { "-h=" + foo.toString() });
692 } catch (Exception e)
696 } catch (OutOfMemoryError e)
710 * Start a fresh discovery thread and notify the given object when we're
711 * finished. Any known existing threads will be killed before this one is
714 * @param changeSupport2
717 public Thread startDiscoverer(PropertyChangeListener changeSupport2)
723 addPropertyChangeListener(changeSupport2);
724 Thread thr = new Thread(this);
729 Vector<String> invalidServiceUrls = null, urlsWithoutServices = null,
730 validServiceUrls = null;
733 * @return the invalidServiceUrls
735 public Vector<String> getInvalidServiceUrls()
737 return invalidServiceUrls;
741 * @return the urlsWithoutServices
743 public Vector<String> getUrlsWithoutServices()
745 return urlsWithoutServices;
749 * add an 'empty' JABA server to the list. Only servers not already in the
750 * 'bad URL' list will be added to this list.
754 public synchronized void addUrlwithnoservices(String jwsservers)
756 if (urlsWithoutServices == null)
758 urlsWithoutServices = new Vector<String>();
761 if ((invalidServiceUrls == null || !invalidServiceUrls
762 .contains(jwsservers))
763 && !urlsWithoutServices.contains(jwsservers))
765 urlsWithoutServices.add(jwsservers);
770 * add a bad URL to the list
774 public synchronized void addInvalidServiceUrl(String jwsservers)
776 if (invalidServiceUrls == null)
778 invalidServiceUrls = new Vector<String>();
780 if (!invalidServiceUrls.contains(jwsservers))
782 invalidServiceUrls.add(jwsservers);
788 * @return a human readable report of any problems with the service URLs used
791 public String getErrorMessages()
793 if (!isRunning() && !isAborted())
795 StringBuffer ermsg = new StringBuffer();
796 boolean list = false;
797 if (getInvalidServiceUrls() != null
798 && getInvalidServiceUrls().size() > 0)
800 ermsg.append("URLs that could not be contacted: \n");
801 for (String svcurl : getInvalidServiceUrls())
808 ermsg.append(svcurl);
810 ermsg.append("\n\n");
813 if (getUrlsWithoutServices() != null
814 && getUrlsWithoutServices().size() > 0)
816 ermsg.append("URLs without any JABA Services : \n");
817 for (String svcurl : getUrlsWithoutServices())
824 ermsg.append(svcurl);
828 if (ermsg.length() > 1)
830 return ermsg.toString();
837 public int getServerStatusFor(String url)
839 if (validServiceUrls != null && validServiceUrls.contains(url))
843 if (urlsWithoutServices != null && urlsWithoutServices.contains(url))
845 if (invalidServiceUrls != null && invalidServiceUrls.contains(url))
853 * pick the user's preferred service based on a set of URLs (jaba server
854 * locations) and service URIs (specifying version and service interface
858 * @return null or best match for given uri/ls.
860 public Jws2Instance getPreferredServiceFor(String[] serviceURLs)
862 HashSet<String> urls = new HashSet<String>();
863 urls.addAll(Arrays.asList(serviceURLs));
864 Jws2Instance match = null;
865 if (services != null)
867 for (Jws2Instance svc : services)
869 if (urls.contains(svc.getServiceTypeURI()))
873 // for moment we always pick service from server ordered first in
874 // user's preferences
877 if (urls.contains(svc.getUri()))
879 // stop and return - we've matched type URI and URI for service
889 Map<String, Map<String, String>> preferredServiceMap = new HashMap<String, Map<String, String>>();;
892 * get current preferred service of the given type, or global default
895 * null or a specific alignFrame
897 * Jws2Instance.serviceType for service
898 * @return null if no service of this type is available, the preferred service
899 * for the serviceType and af if specified and if defined.
901 public Jws2Instance getPreferredServiceFor(AlignFrame af,
904 String serviceurl = null;
905 synchronized (preferredServiceMap)
907 String afid = (af == null) ? "" : af.getViewport().getSequenceSetId();
908 Map<String, String> prefmap = preferredServiceMap.get(afid);
909 if (afid.length() > 0 && prefmap == null)
911 // recover global setting, if any
912 prefmap = preferredServiceMap.get("");
916 serviceurl = prefmap.get(serviceType);
920 Jws2Instance response = null;
921 for (Jws2Instance svc : services)
923 if (svc.serviceType.equals(serviceType))
925 if (serviceurl == null || serviceurl.equals(svc.getHost()))
935 public void setPreferredServiceFor(AlignFrame af, String serviceType,
936 String serviceAction, Jws2Instance selectedServer)
938 String afid = (af == null) ? "" : af.getViewport().getSequenceSetId();
939 if (preferredServiceMap == null)
941 preferredServiceMap = new HashMap<String, Map<String, String>>();
943 Map<String, String> prefmap = preferredServiceMap.get(afid);
946 prefmap = new HashMap<String, String>();
947 preferredServiceMap.put(afid, prefmap);
949 prefmap.put(serviceType, selectedServer.getHost());
950 prefmap.put(serviceAction, selectedServer.getHost());
953 public void setPreferredServiceFor(String serviceType,
954 String serviceAction, Jws2Instance selectedServer)
956 setPreferredServiceFor(null, serviceType, serviceAction, selectedServer);