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.bin.Jalview;
25 import jalview.gui.AlignFrame;
26 import jalview.gui.Desktop;
27 import jalview.gui.JvSwingUtils;
28 import jalview.util.MessageManager;
29 import jalview.ws.WSMenuEntryProviderI;
30 import jalview.ws.jws2.jabaws2.Jws2Instance;
31 import jalview.ws.params.ParamDatastoreI;
33 import java.awt.Color;
34 import java.awt.event.ActionEvent;
35 import java.awt.event.ActionListener;
36 import java.beans.PropertyChangeEvent;
37 import java.beans.PropertyChangeListener;
38 import java.beans.PropertyChangeSupport;
39 import java.net.MalformedURLException;
41 import java.util.ArrayList;
42 import java.util.Arrays;
43 import java.util.HashMap;
44 import java.util.HashSet;
45 import java.util.Hashtable;
46 import java.util.List;
49 import java.util.StringTokenizer;
50 import java.util.Vector;
52 import javax.swing.JMenu;
53 import javax.swing.JMenuItem;
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 public static final String COMPBIO_JABAWS = "http://www.compbio.dundee.ac.uk/jabaws";
69 * the .jalview_properties entry for JWS2 URLS
71 private final static String JWS2HOSTURLS = "JWS2HOSTURLS";
74 * Override for testing only
76 private static List<String> testUrls = null;
78 // preferred url has precedence over others
79 private String preferredUrl;
81 protected PropertyChangeSupport changeSupport = new PropertyChangeSupport(
84 private Vector<String> invalidServiceUrls = null;
86 private Vector<String> urlsWithoutServices = null;
88 private Vector<String> validServiceUrls = null;
90 private volatile boolean running = false;
92 private volatile boolean aborted = false;
94 private Thread oldthread = null;
97 * holds list of services.
99 protected Vector<Jws2Instance> services;
102 * Private constructor enforces use of singleton via getDiscoverer()
104 private Jws2Discoverer()
109 * change listeners are notified of "services" property changes
112 * to be added that consumes new services Hashtable object.
114 public void addPropertyChangeListener(
115 java.beans.PropertyChangeListener listener)
117 changeSupport.addPropertyChangeListener(listener);
126 public void removePropertyChangeListener(
127 java.beans.PropertyChangeListener listener)
129 changeSupport.removePropertyChangeListener(listener);
133 * @return the aborted
135 public boolean isAborted()
144 public void setAborted(boolean aborted)
146 this.aborted = aborted;
153 if (running && oldthread != null && oldthread.isAlive())
164 "Waiting around for old discovery thread to finish.");
165 // wait around until old discoverer dies
167 } catch (Exception e)
172 Cache.log.debug("Old discovery thread has finished.");
176 // first set up exclusion list if needed
177 final Set<String> ignoredServices = new HashSet<>();
178 for (String ignored : Cache
179 .getDefault("IGNORED_JABAWS_SERVICETYPES", "").split("\\|"))
181 ignoredServices.add(ignored);
184 changeSupport.firePropertyChange("services", services,
185 new Vector<Jws2Instance>());
186 oldthread = Thread.currentThread();
189 getClass().getClassLoader()
190 .loadClass("compbio.ws.client.Jws2Client");
191 } catch (ClassNotFoundException e)
194 "Not enabling JABA Webservices : client jar is not available."
195 + "\nPlease check that your webstart JNLP file is up to date!");
199 // reinitialise records of good and bad service URLs
200 if (services != null)
202 services.removeAllElements();
204 if (urlsWithoutServices != null)
206 urlsWithoutServices.removeAllElements();
208 if (invalidServiceUrls != null)
210 invalidServiceUrls.removeAllElements();
212 if (validServiceUrls != null)
214 validServiceUrls.removeAllElements();
216 ArrayList<String> svctypes = new ArrayList<>();
218 List<JabaWsServerQuery> qrys = new ArrayList<>();
219 for (final String jwsserver : getServiceUrls())
221 JabaWsServerQuery squery = new JabaWsServerQuery(this, jwsserver);
222 if (svctypes.size() == 0)
224 // TODO: remove this ugly hack to get Canonical JABA service ordering
225 // for all possible services
226 for (Services sv : squery.JABAWS2SERVERS)
228 if (!ignoredServices.contains(sv.toString()))
230 svctypes.add(sv.toString());
236 new Thread(squery).start();
238 boolean finished = true;
245 } catch (Exception e)
248 for (JabaWsServerQuery squery : qrys)
250 if (squery.isRunning())
258 "Aborting " + qrys.size() + " JABAWS discovery threads.");
259 for (JabaWsServerQuery squery : qrys)
261 squery.setQuit(true);
264 } while (!aborted && !finished);
267 // resort services according to order found in jabaws service list
268 // also ensure services for each host are ordered in same way.
270 if (services != null && services.size() > 0)
272 Jws2Instance[] svcs = new Jws2Instance[services.size()];
273 int[] spos = new int[services.size()];
275 List<String> svcUrls = getServiceUrls();
276 for (Jws2Instance svc : services)
279 spos[ipos++] = 1000 * svcUrls.indexOf(svc.getHost()) + 1
280 + svctypes.indexOf(svc.serviceType);
282 jalview.util.QuickSort.sort(spos, svcs);
283 services = new Vector<>();
284 for (Jws2Instance svc : svcs)
286 if (!ignoredServices.contains(svc.serviceType))
295 changeSupport.firePropertyChange("services", new Vector<Jws2Instance>(),
300 * record this service endpoint so we can use it
306 synchronized void addService(String jwsservers, Jws2Instance service)
308 if (services == null)
310 services = new Vector<>();
313 "Discovered service: " + jwsservers + " " + service.toString());
314 // Jws2Instance service = new Jws2Instance(jwsservers, srv.toString(),
317 services.add(service);
318 // retrieve the presets and parameter set and cache now
319 ParamDatastoreI pds = service.getParamStore();
324 service.hasParameters();
325 if (validServiceUrls == null)
327 validServiceUrls = new Vector<>();
329 validServiceUrls.add(jwsservers);
333 * attach all available web services to the appropriate submenu in the given
337 public void attachWSMenuEntry(JMenu wsmenu, final AlignFrame alignFrame)
339 // dynamically regenerate service list.
340 populateWSMenuEntry(wsmenu, alignFrame, null);
343 private boolean isRecalculable(String action)
345 return (action != null && action.equalsIgnoreCase("conservation"));
348 private void populateWSMenuEntry(JMenu jws2al,
349 final AlignFrame alignFrame, String typeFilter)
351 if (running || services == null || services.size() == 0)
357 * eventually, JWS2 services will appear under the same align/etc submenus.
358 * for moment we keep them separate.
361 List<Jws2Instance> enumerableServices = new ArrayList<>();
362 // jws2al.removeAll();
363 Map<String, Jws2Instance> preferredHosts = new HashMap<>();
364 Map<String, List<Jws2Instance>> alternates = new HashMap<>();
365 for (Jws2Instance service : services.toArray(new Jws2Instance[0]))
367 if (!isRecalculable(service.action))
369 // add 'one shot' services to be displayed using the classic menu
371 enumerableServices.add(service);
375 if (!preferredHosts.containsKey(service.serviceType))
377 Jws2Instance preferredInstance = getPreferredServiceFor(
378 alignFrame, service.serviceType);
379 if (preferredInstance != null)
381 preferredHosts.put(service.serviceType, preferredInstance);
385 preferredHosts.put(service.serviceType, service);
388 List<Jws2Instance> ph = alternates.get(service.serviceType);
389 if (preferredHosts.get(service.serviceType) != service)
393 ph = new ArrayList<>();
396 alternates.put(service.serviceType, ph);
402 // create GUI element for classic services
403 addEnumeratedServices(jws2al, alignFrame, enumerableServices);
404 // and the instantaneous services
405 for (final Jws2Instance service : preferredHosts.values())
407 atpoint = JvSwingUtils.findOrCreateMenu(jws2al, service.action);
409 if (atpoint.getItemCount() > 1)
411 // previous service of this type already present
412 atpoint.addSeparator();
414 atpoint.add(hitm = new JMenuItem(service.getHost()));
415 hitm.setForeground(Color.blue);
416 hitm.addActionListener(new ActionListener()
420 public void actionPerformed(ActionEvent e)
422 Desktop.showUrl(service.getHost());
425 hitm.setToolTipText(JvSwingUtils.wrapTooltip(false,
426 MessageManager.getString("label.open_jabaws_web_page")));
428 service.attachWSMenuEntry(atpoint, alignFrame);
429 if (alternates.containsKey(service.serviceType))
431 atpoint.add(hitm = new JMenu(
432 MessageManager.getString("label.switch_server")));
433 hitm.setToolTipText(JvSwingUtils.wrapTooltip(false,
434 MessageManager.getString("label.choose_jabaws_server")));
435 for (final Jws2Instance sv : alternates.get(service.serviceType))
438 hitm.add(itm = new JMenuItem(sv.getHost()));
439 itm.setForeground(Color.blue);
440 itm.addActionListener(new ActionListener()
444 public void actionPerformed(ActionEvent arg0)
446 new Thread(new Runnable()
451 setPreferredServiceFor(alignFrame, sv.serviceType,
453 changeSupport.firePropertyChange("services",
454 new Vector<Jws2Instance>(), services);
466 * add services using the Java 2.5/2.6/2.7 system which optionally creates
467 * submenus to index by host and service program type
469 private void addEnumeratedServices(final JMenu jws2al,
470 final AlignFrame alignFrame,
471 List<Jws2Instance> enumerableServices)
473 boolean byhost = Cache.getDefault("WSMENU_BYHOST", false),
474 bytype = Cache.getDefault("WSMENU_BYTYPE", false);
476 * eventually, JWS2 services will appear under the same align/etc submenus.
477 * for moment we keep them separate.
481 List<String> hostLabels = new ArrayList<>();
482 Hashtable<String, String> lasthostFor = new Hashtable<>();
483 Hashtable<String, ArrayList<Jws2Instance>> hosts = new Hashtable<>();
484 ArrayList<String> hostlist = new ArrayList<>();
485 for (Jws2Instance service : enumerableServices)
487 ArrayList<Jws2Instance> hostservices = hosts.get(service.getHost());
488 if (hostservices == null)
490 hosts.put(service.getHost(),
491 hostservices = new ArrayList<>());
492 hostlist.add(service.getHost());
494 hostservices.add(service);
496 // now add hosts in order of the given array
497 for (String host : hostlist)
499 Jws2Instance orderedsvcs[] = hosts.get(host)
500 .toArray(new Jws2Instance[1]);
501 String sortbytype[] = new String[orderedsvcs.length];
502 for (int i = 0; i < sortbytype.length; i++)
504 sortbytype[i] = orderedsvcs[i].serviceType;
506 jalview.util.QuickSort.sort(sortbytype, orderedsvcs);
507 for (final Jws2Instance service : orderedsvcs)
509 atpoint = JvSwingUtils.findOrCreateMenu(jws2al, service.action);
510 String type = service.serviceType;
513 atpoint = JvSwingUtils.findOrCreateMenu(atpoint, host);
514 if (atpoint.getToolTipText() == null)
516 atpoint.setToolTipText(MessageManager
517 .formatMessage("label.services_at", new String[]
523 atpoint = JvSwingUtils.findOrCreateMenu(atpoint, type);
524 if (atpoint.getToolTipText() == null)
526 atpoint.setToolTipText(service.getActionText());
529 if (!byhost && !hostLabels.contains(
530 host + service.serviceType + service.getActionText()))
531 // !hostLabels.contains(host + (bytype ?
532 // service.serviceType+service.getActionText() : "")))
534 // add a marker indicating where this service is hosted
535 // relies on services from the same host being listed in a
539 if (hostLabels.contains(host))
541 atpoint.addSeparator();
545 hostLabels.add(host);
547 if (lasthostFor.get(service.action) == null
548 || !lasthostFor.get(service.action).equals(host))
550 atpoint.add(hitm = new JMenuItem(host));
551 hitm.setForeground(Color.blue);
552 hitm.addActionListener(new ActionListener()
556 public void actionPerformed(ActionEvent e)
558 Desktop.showUrl(service.getHost());
562 JvSwingUtils.wrapTooltip(true, MessageManager
563 .getString("label.open_jabaws_web_page")));
564 lasthostFor.put(service.action, host);
567 host + service.serviceType + service.getActionText());
570 service.attachWSMenuEntry(atpoint, alignFrame);
580 public static void main(String[] args)
584 testUrls = new ArrayList<>();
585 for (String url : args)
590 Thread runner = getDiscoverer()
591 .startDiscoverer(new PropertyChangeListener()
595 public void propertyChange(PropertyChangeEvent evt)
597 if (getDiscoverer().services != null)
599 System.out.println("Changesupport: There are now "
600 + getDiscoverer().services.size() + " services");
602 for (Jws2Instance instance : getDiscoverer().services)
604 System.out.println("Service " + i++ + " "
605 + instance.getClass() + "@" + instance.getHost()
606 + ": " + instance.getActionText());
612 while (runner.isAlive())
617 } catch (InterruptedException e)
624 } catch (InterruptedException x)
630 * Returns the singleton instance of this class.
634 public static Jws2Discoverer getDiscoverer()
636 Jalview j = Jalview.getInstance();
637 return (j.j2s2discoverer == null
638 ? j.j2s2discoverer = new Jws2Discoverer()
642 public boolean hasServices()
644 return !running && services != null && services.size() > 0;
647 public boolean isRunning()
652 public void setServiceUrls(List<String> wsUrls)
654 if (wsUrls != null && !wsUrls.isEmpty())
656 StringBuilder urls = new StringBuilder(128);
658 for (String url : wsUrls)
664 Cache.setProperty(JWS2HOSTURLS, urls.toString());
668 Cache.removeProperty(JWS2HOSTURLS);
673 * Returns web service URLs, in the order in which they should be tried (or an
678 public List<String> getServiceUrls()
680 if (testUrls != null)
682 // return test urls, if there are any, instead of touching cache
685 List<String> urls = new ArrayList<>();
687 if (this.preferredUrl != null)
689 urls.add(preferredUrl);
692 String surls = Cache.getDefault(JWS2HOSTURLS, COMPBIO_JABAWS);
695 StringTokenizer st = new StringTokenizer(surls, ",");
696 while (st.hasMoreElements())
701 url = st.nextToken();
703 if (!urls.contains(url))
709 Cache.log.warn("Ignoring duplicate url " + url + " in "
710 + JWS2HOSTURLS + " list");
712 } catch (MalformedURLException ex)
714 Cache.log.warn("Problem whilst trying to make a URL from '"
715 + ((url != null) ? url : "<null>") + "'");
717 "This was probably due to a malformed comma separated list"
718 + " in the " + JWS2HOSTURLS
719 + " entry of $(HOME)/.jalview_properties)");
720 Cache.log.debug("Exception was ", ex);
723 } catch (Exception ex)
725 Cache.log.warn("Error parsing comma separated list of urls in "
726 + JWS2HOSTURLS + " preference.", ex);
731 public Vector<Jws2Instance> getServices()
733 return (services == null) ? new Vector<>()
734 : new Vector<>(services);
738 * test the given URL with the JabaWS test code
743 public static boolean testServiceUrl(URL foo)
747 compbio.ws.client.WSTester
749 { "-h=" + foo.toString() });
750 } catch (Exception e)
754 } catch (OutOfMemoryError e)
767 public boolean restart()
784 * Start a fresh discovery thread and notify the given object when we're
785 * finished. Any known existing threads will be killed before this one is
788 * @param changeSupport2
791 public Thread startDiscoverer(PropertyChangeListener changeSupport2)
799 Thread thr = new Thread(this);
807 addPropertyChangeListener(changeSupport2);
808 Thread thr = new Thread(this);
814 * @return the invalidServiceUrls
816 public Vector<String> getInvalidServiceUrls()
818 return invalidServiceUrls;
822 * @return the urlsWithoutServices
824 public Vector<String> getUrlsWithoutServices()
826 return urlsWithoutServices;
830 * add an 'empty' JABA server to the list. Only servers not already in the
831 * 'bad URL' list will be added to this list.
835 public synchronized void addUrlwithnoservices(String jwsservers)
837 if (urlsWithoutServices == null)
839 urlsWithoutServices = new Vector<>();
842 if ((invalidServiceUrls == null
843 || !invalidServiceUrls.contains(jwsservers))
844 && !urlsWithoutServices.contains(jwsservers))
846 urlsWithoutServices.add(jwsservers);
851 * add a bad URL to the list
855 public synchronized void addInvalidServiceUrl(String jwsservers)
857 if (invalidServiceUrls == null)
859 invalidServiceUrls = new Vector<>();
861 if (!invalidServiceUrls.contains(jwsservers))
863 invalidServiceUrls.add(jwsservers);
869 * @return a human readable report of any problems with the service URLs used
872 public String getErrorMessages()
874 if (!isRunning() && !isAborted())
876 StringBuffer ermsg = new StringBuffer();
877 boolean list = false;
878 if (getInvalidServiceUrls() != null
879 && getInvalidServiceUrls().size() > 0)
881 ermsg.append(MessageManager.getString("warn.urls_not_contacted")
883 for (String svcurl : getInvalidServiceUrls())
890 ermsg.append(svcurl);
892 ermsg.append("\n\n");
895 if (getUrlsWithoutServices() != null
896 && getUrlsWithoutServices().size() > 0)
899 MessageManager.getString("warn.urls_no_jaba") + ": \n");
900 for (String svcurl : getUrlsWithoutServices())
907 ermsg.append(svcurl);
911 if (ermsg.length() > 1)
913 return ermsg.toString();
920 public int getServerStatusFor(String url)
922 if (validServiceUrls != null && validServiceUrls.contains(url))
926 if (urlsWithoutServices != null && urlsWithoutServices.contains(url))
930 if (invalidServiceUrls != null && invalidServiceUrls.contains(url))
938 * pick the user's preferred service based on a set of URLs (jaba server
939 * locations) and service URIs (specifying version and service interface
943 * @return null or best match for given uri/ls.
945 public Jws2Instance getPreferredServiceFor(String[] serviceURLs)
947 HashSet<String> urls = new HashSet<>();
948 urls.addAll(Arrays.asList(serviceURLs));
949 Jws2Instance match = null;
950 if (services != null)
952 for (Jws2Instance svc : services)
954 if (urls.contains(svc.getServiceTypeURI()))
958 // for moment we always pick service from server ordered first in
959 // user's preferences
962 if (urls.contains(svc.getUri()))
964 // stop and return - we've matched type URI and URI for service
974 Map<String, Map<String, String>> preferredServiceMap = new HashMap<>();
977 * get current preferred service of the given type, or global default
980 * null or a specific alignFrame
982 * Jws2Instance.serviceType for service
983 * @return null if no service of this type is available, the preferred service
984 * for the serviceType and af if specified and if defined.
986 public Jws2Instance getPreferredServiceFor(AlignFrame af,
989 String serviceurl = null;
990 synchronized (preferredServiceMap)
992 String afid = (af == null) ? "" : af.getViewport().getSequenceSetId();
993 Map<String, String> prefmap = preferredServiceMap.get(afid);
994 if (afid.length() > 0 && prefmap == null)
996 // recover global setting, if any
997 prefmap = preferredServiceMap.get("");
1001 serviceurl = prefmap.get(serviceType);
1005 Jws2Instance response = null;
1006 for (Jws2Instance svc : services)
1008 if (svc.serviceType.equals(serviceType))
1010 if (serviceurl == null || serviceurl.equals(svc.getHost()))
1020 public void setPreferredServiceFor(AlignFrame af, String serviceType,
1021 String serviceAction, Jws2Instance selectedServer)
1023 String afid = (af == null) ? "" : af.getViewport().getSequenceSetId();
1024 if (preferredServiceMap == null)
1026 preferredServiceMap = new HashMap<>();
1028 Map<String, String> prefmap = preferredServiceMap.get(afid);
1029 if (prefmap == null)
1031 prefmap = new HashMap<>();
1032 preferredServiceMap.put(afid, prefmap);
1034 prefmap.put(serviceType, selectedServer.getHost());
1035 prefmap.put(serviceAction, selectedServer.getHost());
1038 public void setPreferredServiceFor(String serviceType,
1039 String serviceAction, Jws2Instance selectedServer)
1041 setPreferredServiceFor(null, serviceType, serviceAction,
1046 * Set a URL to try before any others. For use with command-line parameter to
1047 * configure a local Jabaws installation without the need to add to property
1051 * @throws MalformedURLException
1053 public void setPreferredUrl(String value) throws MalformedURLException
1055 if (value != null && value.trim().length() > 0)
1058 preferredUrl = value;