2 * Jalview - A Sequence Alignment Editor and Viewer ($$Version-Rel$$)
3 * Copyright (C) $$Year-Rel$$ 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
10 * of the License, or (at your option) any later version.
12 * Jalview is distributed in the hope that it will be useful, but
13 * WITHOUT ANY WARRANTY; without even the implied warranty
14 * of MERCHANTABILITY or FITNESS FOR A PARTICULAR
15 * PURPOSE. See the GNU General Public License for more details.
17 * You should have received a copy of the GNU General Public License
18 * along with Jalview. If not, see <http://www.gnu.org/licenses/>.
19 * The Jalview Authors are detailed in the 'AUTHORS' file.
21 package jalview.ws.jws2;
23 import jalview.bin.Cache;
24 import jalview.gui.AlignFrame;
25 import jalview.gui.Desktop;
26 import jalview.gui.JvSwingUtils;
27 import jalview.util.MessageManager;
28 import jalview.ws.WSMenuEntryProviderI;
29 import jalview.ws.jws2.jabaws2.Jws2Instance;
30 import jalview.ws.params.ParamDatastoreI;
32 import java.awt.Color;
33 import java.awt.event.ActionEvent;
34 import java.awt.event.ActionListener;
35 import java.beans.PropertyChangeEvent;
36 import java.beans.PropertyChangeListener;
37 import java.beans.PropertyChangeSupport;
38 import java.net.MalformedURLException;
40 import java.util.ArrayList;
41 import java.util.Arrays;
42 import java.util.HashMap;
43 import java.util.HashSet;
44 import java.util.Hashtable;
45 import java.util.List;
48 import java.util.StringTokenizer;
49 import java.util.Vector;
51 import javax.swing.JMenu;
52 import javax.swing.JMenuItem;
54 import compbio.ws.client.Services;
57 * discoverer for jws2 services. Follows the lightweight service discoverer
58 * pattern (archetyped by EnfinEnvision2OneWay)
63 public class Jws2Discoverer implements Runnable, WSMenuEntryProviderI
65 public static final String COMPBIO_JABAWS = "http://www.compbio.dundee.ac.uk/jabaws";
68 * the .jalview_properties entry for JWS2 URLS
70 private final static String JWS2HOSTURLS = "JWS2HOSTURLS";
75 private static Jws2Discoverer discoverer;
78 * Override for testing only
80 private static List<String> testUrls = null;
82 // preferred url has precedence over others
83 private String preferredUrl;
85 private PropertyChangeSupport changeSupport = new PropertyChangeSupport(
88 private Vector<String> invalidServiceUrls = null;
90 private Vector<String> urlsWithoutServices = null;
92 private Vector<String> validServiceUrls = null;
94 private volatile boolean running = false;
96 private volatile boolean aborted = false;
98 private Thread oldthread = null;
101 * holds list of services.
103 protected Vector<Jws2Instance> services;
106 * Private constructor enforces use of singleton via getDiscoverer()
108 private Jws2Discoverer()
113 * change listeners are notified of "services" property changes
116 * to be added that consumes new services Hashtable object.
118 public void addPropertyChangeListener(
119 java.beans.PropertyChangeListener listener)
121 changeSupport.addPropertyChangeListener(listener);
130 public void removePropertyChangeListener(
131 java.beans.PropertyChangeListener listener)
133 changeSupport.removePropertyChangeListener(listener);
137 * @return the aborted
139 public boolean isAborted()
148 public void setAborted(boolean aborted)
150 this.aborted = aborted;
157 if (running && oldthread != null && oldthread.isAlive())
168 "Waiting around for old discovery thread to finish.");
169 // wait around until old discoverer dies
171 } catch (Exception e)
176 Cache.log.debug("Old discovery thread has finished.");
180 // first set up exclusion list if needed
181 final Set<String> ignoredServices = new HashSet<>();
182 for (String ignored : Cache
183 .getDefault("IGNORED_JABAWS_SERVICETYPES", "").split("\\|"))
185 ignoredServices.add(ignored);
188 changeSupport.firePropertyChange("services", services,
189 new Vector<Jws2Instance>());
190 oldthread = Thread.currentThread();
193 Class foo = getClass().getClassLoader()
194 .loadClass("compbio.ws.client.Jws2Client");
195 } catch (ClassNotFoundException e)
198 "Not enabling JABA Webservices : client jar is not available."
199 + "\nPlease check that your webstart JNLP file is up to date!");
203 // reinitialise records of good and bad service URLs
204 if (services != null)
206 services.removeAllElements();
208 if (urlsWithoutServices != null)
210 urlsWithoutServices.removeAllElements();
212 if (invalidServiceUrls != null)
214 invalidServiceUrls.removeAllElements();
216 if (validServiceUrls != null)
218 validServiceUrls.removeAllElements();
220 ArrayList<String> svctypes = new ArrayList<>();
222 List<JabaWsServerQuery> qrys = new ArrayList<>();
223 for (final String jwsserver : getServiceUrls())
225 JabaWsServerQuery squery = new JabaWsServerQuery(this, jwsserver);
226 if (svctypes.size() == 0)
228 // TODO: remove this ugly hack to get Canonical JABA service ordering
229 // for all possible services
230 for (Services sv : squery.JABAWS2SERVERS)
232 if (!ignoredServices.contains(sv.toString()))
234 svctypes.add(sv.toString());
240 new Thread(squery).start();
242 boolean finished = true;
249 } catch (Exception e)
252 for (JabaWsServerQuery squery : qrys)
254 if (squery.isRunning())
262 "Aborting " + qrys.size() + " JABAWS discovery threads.");
263 for (JabaWsServerQuery squery : qrys)
265 squery.setQuit(true);
268 } while (!aborted && !finished);
271 // resort services according to order found in jabaws service list
272 // also ensure services for each host are ordered in same way.
274 if (services != null && services.size() > 0)
276 Jws2Instance[] svcs = new Jws2Instance[services.size()];
277 int[] spos = new int[services.size()];
279 List<String> svcUrls = getServiceUrls();
280 for (Jws2Instance svc : services)
283 spos[ipos++] = 1000 * svcUrls.indexOf(svc.getHost()) + 1
284 + svctypes.indexOf(svc.serviceType);
286 jalview.util.QuickSort.sort(spos, svcs);
287 services = new Vector<>();
288 for (Jws2Instance svc : svcs)
290 if (!ignoredServices.contains(svc.serviceType))
299 changeSupport.firePropertyChange("services", new Vector<Jws2Instance>(),
304 * record this service endpoint so we can use it
310 synchronized void addService(String jwsservers, Jws2Instance service)
312 if (services == null)
314 services = new Vector<>();
317 "Discovered service: " + jwsservers + " " + service.toString());
318 // Jws2Instance service = new Jws2Instance(jwsservers, srv.toString(),
321 services.add(service);
322 // retrieve the presets and parameter set and cache now
323 ParamDatastoreI pds = service.getParamStore();
328 service.hasParameters();
329 if (validServiceUrls == null)
331 validServiceUrls = new Vector<>();
333 validServiceUrls.add(jwsservers);
337 * attach all available web services to the appropriate submenu in the given
341 public void attachWSMenuEntry(JMenu wsmenu, final AlignFrame alignFrame)
343 // dynamically regenerate service list.
344 populateWSMenuEntry(wsmenu, alignFrame, null);
347 private boolean isRecalculable(String action)
349 return (action != null && action.equalsIgnoreCase("conservation"));
352 private void populateWSMenuEntry(JMenu jws2al,
353 final AlignFrame alignFrame, String typeFilter)
355 if (running || services == null || services.size() == 0)
361 * eventually, JWS2 services will appear under the same align/etc submenus.
362 * for moment we keep them separate.
365 List<Jws2Instance> enumerableServices = new ArrayList<>();
366 // jws2al.removeAll();
367 Map<String, Jws2Instance> preferredHosts = new HashMap<>();
368 Map<String, List<Jws2Instance>> alternates = new HashMap<>();
369 for (Jws2Instance service : services.toArray(new Jws2Instance[0]))
371 if (!isRecalculable(service.action))
373 // add 'one shot' services to be displayed using the classic menu
375 enumerableServices.add(service);
379 if (!preferredHosts.containsKey(service.serviceType))
381 Jws2Instance preferredInstance = getPreferredServiceFor(
382 alignFrame, service.serviceType);
383 if (preferredInstance != null)
385 preferredHosts.put(service.serviceType, preferredInstance);
389 preferredHosts.put(service.serviceType, service);
392 List<Jws2Instance> ph = alternates.get(service.serviceType);
393 if (preferredHosts.get(service.serviceType) != service)
397 ph = new ArrayList<>();
400 alternates.put(service.serviceType, ph);
406 // create GUI element for classic services
407 addEnumeratedServices(jws2al, alignFrame, enumerableServices);
408 // and the instantaneous services
409 for (final Jws2Instance service : preferredHosts.values())
411 atpoint = JvSwingUtils.findOrCreateMenu(jws2al, service.action);
413 if (atpoint.getItemCount() > 1)
415 // previous service of this type already present
416 atpoint.addSeparator();
418 atpoint.add(hitm = new JMenuItem(service.getHost()));
419 hitm.setForeground(Color.blue);
420 hitm.addActionListener(new ActionListener()
424 public void actionPerformed(ActionEvent e)
426 Desktop.showUrl(service.getHost());
429 hitm.setToolTipText(JvSwingUtils.wrapTooltip(false,
430 MessageManager.getString("label.open_jabaws_web_page")));
432 service.attachWSMenuEntry(atpoint, alignFrame);
433 if (alternates.containsKey(service.serviceType))
435 atpoint.add(hitm = new JMenu(
436 MessageManager.getString("label.switch_server")));
437 hitm.setToolTipText(JvSwingUtils.wrapTooltip(false,
438 MessageManager.getString("label.choose_jabaws_server")));
439 for (final Jws2Instance sv : alternates.get(service.serviceType))
442 hitm.add(itm = new JMenuItem(sv.getHost()));
443 itm.setForeground(Color.blue);
444 itm.addActionListener(new ActionListener()
448 public void actionPerformed(ActionEvent arg0)
450 new Thread(new Runnable()
455 setPreferredServiceFor(alignFrame, sv.serviceType,
457 changeSupport.firePropertyChange("services",
458 new Vector<Jws2Instance>(), services);
470 * add services using the Java 2.5/2.6/2.7 system which optionally creates
471 * submenus to index by host and service program type
473 private void addEnumeratedServices(final JMenu jws2al,
474 final AlignFrame alignFrame,
475 List<Jws2Instance> enumerableServices)
477 boolean byhost = Cache.getDefault("WSMENU_BYHOST", false),
478 bytype = Cache.getDefault("WSMENU_BYTYPE", false);
480 * eventually, JWS2 services will appear under the same align/etc submenus.
481 * for moment we keep them separate.
485 List<String> hostLabels = new ArrayList<>();
486 Hashtable<String, String> lasthostFor = new Hashtable<>();
487 Hashtable<String, ArrayList<Jws2Instance>> hosts = new Hashtable<>();
488 ArrayList<String> hostlist = new ArrayList<>();
489 for (Jws2Instance service : enumerableServices)
491 ArrayList<Jws2Instance> hostservices = hosts.get(service.getHost());
492 if (hostservices == null)
494 hosts.put(service.getHost(),
495 hostservices = new ArrayList<>());
496 hostlist.add(service.getHost());
498 hostservices.add(service);
500 // now add hosts in order of the given array
501 for (String host : hostlist)
503 Jws2Instance orderedsvcs[] = hosts.get(host)
504 .toArray(new Jws2Instance[1]);
505 String sortbytype[] = new String[orderedsvcs.length];
506 for (int i = 0; i < sortbytype.length; i++)
508 sortbytype[i] = orderedsvcs[i].serviceType;
510 jalview.util.QuickSort.sort(sortbytype, orderedsvcs);
511 for (final Jws2Instance service : orderedsvcs)
513 atpoint = JvSwingUtils.findOrCreateMenu(jws2al, service.action);
514 String type = service.serviceType;
517 atpoint = JvSwingUtils.findOrCreateMenu(atpoint, host);
518 if (atpoint.getToolTipText() == null)
520 atpoint.setToolTipText(MessageManager
521 .formatMessage("label.services_at", new String[]
527 atpoint = JvSwingUtils.findOrCreateMenu(atpoint, type);
528 if (atpoint.getToolTipText() == null)
530 atpoint.setToolTipText(service.getActionText());
533 if (!byhost && !hostLabels.contains(
534 host + service.serviceType + service.getActionText()))
535 // !hostLabels.contains(host + (bytype ?
536 // service.serviceType+service.getActionText() : "")))
538 // add a marker indicating where this service is hosted
539 // relies on services from the same host being listed in a
543 if (hostLabels.contains(host))
545 atpoint.addSeparator();
549 hostLabels.add(host);
551 if (lasthostFor.get(service.action) == null
552 || !lasthostFor.get(service.action).equals(host))
554 atpoint.add(hitm = new JMenuItem(host));
555 hitm.setForeground(Color.blue);
556 hitm.addActionListener(new ActionListener()
560 public void actionPerformed(ActionEvent e)
562 Desktop.showUrl(service.getHost());
566 JvSwingUtils.wrapTooltip(true, MessageManager
567 .getString("label.open_jabaws_web_page")));
568 lasthostFor.put(service.action, host);
571 host + service.serviceType + service.getActionText());
574 service.attachWSMenuEntry(atpoint, alignFrame);
584 public static void main(String[] args)
588 testUrls = new ArrayList<>();
589 for (String url : args)
594 Thread runner = getDiscoverer()
595 .startDiscoverer(new PropertyChangeListener()
599 public void propertyChange(PropertyChangeEvent evt)
601 if (getDiscoverer().services != null)
603 System.out.println("Changesupport: There are now "
604 + getDiscoverer().services.size() + " services");
606 for (Jws2Instance instance : getDiscoverer().services)
608 System.out.println("Service " + i++ + " "
609 + instance.getClass() + "@" + instance.getHost()
610 + ": " + instance.getActionText());
616 while (runner.isAlive())
621 } catch (InterruptedException e)
628 } catch (InterruptedException x)
634 * Returns the singleton instance of this class.
638 public static Jws2Discoverer getDiscoverer()
640 if (discoverer == null)
642 discoverer = new Jws2Discoverer();
647 public boolean hasServices()
649 return !running && services != null && services.size() > 0;
652 public boolean isRunning()
657 public void setServiceUrls(List<String> wsUrls)
659 if (wsUrls != null && !wsUrls.isEmpty())
661 StringBuilder urls = new StringBuilder(128);
663 for (String url : wsUrls)
669 Cache.setProperty(JWS2HOSTURLS, urls.toString());
673 Cache.removeProperty(JWS2HOSTURLS);
678 * Returns web service URLs, in the order in which they should be tried (or an
683 public List<String> getServiceUrls()
685 if (testUrls != null)
687 // return test urls, if there are any, instead of touching cache
690 List<String> urls = new ArrayList<>();
692 if (this.preferredUrl != null)
694 urls.add(preferredUrl);
697 String surls = Cache.getDefault(JWS2HOSTURLS, COMPBIO_JABAWS);
700 StringTokenizer st = new StringTokenizer(surls, ",");
701 while (st.hasMoreElements())
706 url = st.nextToken();
708 if (!urls.contains(url))
714 Cache.log.warn("Ignoring duplicate url " + url + " in "
715 + JWS2HOSTURLS + " list");
717 } catch (MalformedURLException ex)
719 Cache.log.warn("Problem whilst trying to make a URL from '"
720 + ((url != null) ? url : "<null>") + "'");
722 "This was probably due to a malformed comma separated list"
723 + " in the " + JWS2HOSTURLS
724 + " entry of $(HOME)/.jalview_properties)");
725 Cache.log.debug("Exception was ", ex);
728 } catch (Exception ex)
730 Cache.log.warn("Error parsing comma separated list of urls in "
731 + JWS2HOSTURLS + " preference.", ex);
736 public Vector<Jws2Instance> getServices()
738 return (services == null) ? new Vector<>()
739 : new Vector<>(services);
743 * test the given URL with the JabaWS test code
748 public static boolean testServiceUrl(URL foo)
752 compbio.ws.client.WSTester
754 { "-h=" + foo.toString() });
755 } catch (Exception e)
759 } catch (OutOfMemoryError e)
772 public boolean restart()
789 * Start a fresh discovery thread and notify the given object when we're
790 * finished. Any known existing threads will be killed before this one is
793 * @param changeSupport2
796 public Thread startDiscoverer(PropertyChangeListener changeSupport2)
804 Thread thr = new Thread(this);
812 addPropertyChangeListener(changeSupport2);
813 Thread thr = new Thread(this);
819 * @return the invalidServiceUrls
821 public Vector<String> getInvalidServiceUrls()
823 return invalidServiceUrls;
827 * @return the urlsWithoutServices
829 public Vector<String> getUrlsWithoutServices()
831 return urlsWithoutServices;
835 * add an 'empty' JABA server to the list. Only servers not already in the
836 * 'bad URL' list will be added to this list.
840 public synchronized void addUrlwithnoservices(String jwsservers)
842 if (urlsWithoutServices == null)
844 urlsWithoutServices = new Vector<>();
847 if ((invalidServiceUrls == null
848 || !invalidServiceUrls.contains(jwsservers))
849 && !urlsWithoutServices.contains(jwsservers))
851 urlsWithoutServices.add(jwsservers);
856 * add a bad URL to the list
860 public synchronized void addInvalidServiceUrl(String jwsservers)
862 if (invalidServiceUrls == null)
864 invalidServiceUrls = new Vector<>();
866 if (!invalidServiceUrls.contains(jwsservers))
868 invalidServiceUrls.add(jwsservers);
874 * @return a human readable report of any problems with the service URLs used
877 public String getErrorMessages()
879 if (!isRunning() && !isAborted())
881 StringBuffer ermsg = new StringBuffer();
882 boolean list = false;
883 if (getInvalidServiceUrls() != null
884 && getInvalidServiceUrls().size() > 0)
886 ermsg.append(MessageManager.getString("warn.urls_not_contacted")
888 for (String svcurl : getInvalidServiceUrls())
895 ermsg.append(svcurl);
897 ermsg.append("\n\n");
900 if (getUrlsWithoutServices() != null
901 && getUrlsWithoutServices().size() > 0)
904 MessageManager.getString("warn.urls_no_jaba") + ": \n");
905 for (String svcurl : getUrlsWithoutServices())
912 ermsg.append(svcurl);
916 if (ermsg.length() > 1)
918 return ermsg.toString();
925 public int getServerStatusFor(String url)
927 if (validServiceUrls != null && validServiceUrls.contains(url))
931 if (urlsWithoutServices != null && urlsWithoutServices.contains(url))
935 if (invalidServiceUrls != null && invalidServiceUrls.contains(url))
943 * pick the user's preferred service based on a set of URLs (jaba server
944 * locations) and service URIs (specifying version and service interface
948 * @return null or best match for given uri/ls.
950 public Jws2Instance getPreferredServiceFor(String[] serviceURLs)
952 HashSet<String> urls = new HashSet<>();
953 urls.addAll(Arrays.asList(serviceURLs));
954 Jws2Instance match = null;
955 if (services != null)
957 for (Jws2Instance svc : services)
959 if (urls.contains(svc.getServiceTypeURI()))
963 // for moment we always pick service from server ordered first in
964 // user's preferences
967 if (urls.contains(svc.getUri()))
969 // stop and return - we've matched type URI and URI for service
979 Map<String, Map<String, String>> preferredServiceMap = new HashMap<>();
982 * get current preferred service of the given type, or global default
985 * null or a specific alignFrame
987 * Jws2Instance.serviceType for service
988 * @return null if no service of this type is available, the preferred service
989 * for the serviceType and af if specified and if defined.
991 public Jws2Instance getPreferredServiceFor(AlignFrame af,
994 String serviceurl = null;
995 synchronized (preferredServiceMap)
997 String afid = (af == null) ? "" : af.getViewport().getSequenceSetId();
998 Map<String, String> prefmap = preferredServiceMap.get(afid);
999 if (afid.length() > 0 && prefmap == null)
1001 // recover global setting, if any
1002 prefmap = preferredServiceMap.get("");
1004 if (prefmap != null)
1006 serviceurl = prefmap.get(serviceType);
1010 Jws2Instance response = null;
1011 for (Jws2Instance svc : services)
1013 if (svc.serviceType.equals(serviceType))
1015 if (serviceurl == null || serviceurl.equals(svc.getHost()))
1025 public void setPreferredServiceFor(AlignFrame af, String serviceType,
1026 String serviceAction, Jws2Instance selectedServer)
1028 String afid = (af == null) ? "" : af.getViewport().getSequenceSetId();
1029 if (preferredServiceMap == null)
1031 preferredServiceMap = new HashMap<>();
1033 Map<String, String> prefmap = preferredServiceMap.get(afid);
1034 if (prefmap == null)
1036 prefmap = new HashMap<>();
1037 preferredServiceMap.put(afid, prefmap);
1039 prefmap.put(serviceType, selectedServer.getHost());
1040 prefmap.put(serviceAction, selectedServer.getHost());
1043 public void setPreferredServiceFor(String serviceType,
1044 String serviceAction, Jws2Instance selectedServer)
1046 setPreferredServiceFor(null, serviceType, serviceAction,
1051 * Set a URL to try before any others. For use with command-line parameter to
1052 * configure a local Jabaws installation without the need to add to property
1056 * @throws MalformedURLException
1058 public void setPreferredUrl(String value) throws MalformedURLException
1060 if (value != null && value.trim().length() > 0)
1063 preferredUrl = value;