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 * Returns the singleton instance of this class.
82 public static Jws2Discoverer getInstance()
84 if (discoverer == null)
86 discoverer = new Jws2Discoverer();
92 * Override for testing only
94 private static List<String> testUrls = null;
96 // preferred url has precedence over others
97 private String preferredUrl;
99 private PropertyChangeSupport changeSupport = new PropertyChangeSupport(
102 private Vector<String> invalidServiceUrls = null;
104 private Vector<String> urlsWithoutServices = null;
106 private Vector<String> validServiceUrls = null;
108 private volatile boolean running = false;
110 private volatile boolean aborted = false;
112 private Thread oldthread = null;
115 * holds list of services.
117 protected Vector<Jws2Instance> services;
120 * Private constructor enforces use of singleton via getDiscoverer()
122 private Jws2Discoverer()
127 * change listeners are notified of "services" property changes
130 * to be added that consumes new services Hashtable object.
132 public void addPropertyChangeListener(
133 java.beans.PropertyChangeListener listener)
135 changeSupport.addPropertyChangeListener(listener);
144 public void removePropertyChangeListener(
145 java.beans.PropertyChangeListener listener)
147 changeSupport.removePropertyChangeListener(listener);
151 * @return the aborted
153 public boolean isAborted()
162 public void setAborted(boolean aborted)
164 this.aborted = aborted;
171 if (running && oldthread != null && oldthread.isAlive())
182 "Waiting around for old discovery thread to finish.");
183 // wait around until old discoverer dies
185 } catch (Exception e)
190 Cache.log.debug("Old discovery thread has finished.");
194 // first set up exclusion list if needed
195 final Set<String> ignoredServices = new HashSet<>();
196 for (String ignored : Cache
197 .getDefault("IGNORED_JABAWS_SERVICETYPES", "").split("\\|"))
199 ignoredServices.add(ignored);
202 changeSupport.firePropertyChange("services", services,
203 new Vector<Jws2Instance>());
204 oldthread = Thread.currentThread();
207 Class foo = getClass().getClassLoader()
208 .loadClass("compbio.ws.client.Jws2Client");
209 } catch (ClassNotFoundException e)
212 "Not enabling JABA Webservices : client jar is not available."
213 + "\nPlease check that your webstart JNLP file is up to date!");
217 // reinitialise records of good and bad service URLs
218 if (services != null)
220 services.removeAllElements();
222 if (urlsWithoutServices != null)
224 urlsWithoutServices.removeAllElements();
226 if (invalidServiceUrls != null)
228 invalidServiceUrls.removeAllElements();
230 if (validServiceUrls != null)
232 validServiceUrls.removeAllElements();
234 ArrayList<String> svctypes = new ArrayList<>();
236 List<JabaWsServerQuery> qrys = new ArrayList<>();
237 for (final String jwsserver : getServiceUrls())
239 JabaWsServerQuery squery = new JabaWsServerQuery(this, jwsserver);
240 if (svctypes.size() == 0)
242 // TODO: remove this ugly hack to get Canonical JABA service ordering
243 // for all possible services
244 for (Services sv : squery.JABAWS2SERVERS)
246 if (!ignoredServices.contains(sv.toString()))
248 svctypes.add(sv.toString());
254 new Thread(squery).start();
256 boolean finished = true;
263 } catch (Exception e)
266 for (JabaWsServerQuery squery : qrys)
268 if (squery.isRunning())
276 "Aborting " + qrys.size() + " JABAWS discovery threads.");
277 for (JabaWsServerQuery squery : qrys)
279 squery.setQuit(true);
282 } while (!aborted && !finished);
285 // resort services according to order found in jabaws service list
286 // also ensure services for each host are ordered in same way.
288 if (services != null && services.size() > 0)
290 Jws2Instance[] svcs = new Jws2Instance[services.size()];
291 int[] spos = new int[services.size()];
293 List<String> svcUrls = getServiceUrls();
294 for (Jws2Instance svc : services)
297 spos[ipos++] = 1000 * svcUrls.indexOf(svc.getHost()) + 1
298 + svctypes.indexOf(svc.serviceType);
300 jalview.util.QuickSort.sort(spos, svcs);
301 services = new Vector<>();
302 for (Jws2Instance svc : svcs)
304 if (!ignoredServices.contains(svc.serviceType))
313 changeSupport.firePropertyChange("services", new Vector<Jws2Instance>(),
318 * record this service endpoint so we can use it
324 synchronized void addService(String jwsservers, Jws2Instance service)
326 if (services == null)
328 services = new Vector<>();
331 "Discovered service: " + jwsservers + " " + service.toString());
332 // Jws2Instance service = new Jws2Instance(jwsservers, srv.toString(),
335 services.add(service);
336 // retrieve the presets and parameter set and cache now
337 ParamDatastoreI pds = service.getParamStore();
342 service.hasParameters();
343 if (validServiceUrls == null)
345 validServiceUrls = new Vector<>();
347 validServiceUrls.add(jwsservers);
351 * attach all available web services to the appropriate submenu in the given
355 public void attachWSMenuEntry(JMenu wsmenu, final AlignFrame alignFrame)
357 // dynamically regenerate service list.
358 populateWSMenuEntry(wsmenu, alignFrame, null);
361 private boolean isRecalculable(String action)
363 return (action != null && action.equalsIgnoreCase("conservation"));
366 private void populateWSMenuEntry(JMenu jws2al,
367 final AlignFrame alignFrame, String typeFilter)
369 if (running || services == null || services.size() == 0)
375 * eventually, JWS2 services will appear under the same align/etc submenus.
376 * for moment we keep them separate.
379 List<Jws2Instance> enumerableServices = new ArrayList<>();
380 // jws2al.removeAll();
381 Map<String, Jws2Instance> preferredHosts = new HashMap<>();
382 Map<String, List<Jws2Instance>> alternates = new HashMap<>();
383 for (Jws2Instance service : services.toArray(new Jws2Instance[0]))
385 if (!isRecalculable(service.action))
387 // add 'one shot' services to be displayed using the classic menu
389 enumerableServices.add(service);
393 if (!preferredHosts.containsKey(service.serviceType))
395 Jws2Instance preferredInstance = getPreferredServiceFor(
396 alignFrame, service.serviceType);
397 if (preferredInstance != null)
399 preferredHosts.put(service.serviceType, preferredInstance);
403 preferredHosts.put(service.serviceType, service);
406 List<Jws2Instance> ph = alternates.get(service.serviceType);
407 if (preferredHosts.get(service.serviceType) != service)
411 ph = new ArrayList<>();
414 alternates.put(service.serviceType, ph);
420 // create GUI element for classic services
421 addEnumeratedServices(jws2al, alignFrame, enumerableServices);
422 // and the instantaneous services
423 for (final Jws2Instance service : preferredHosts.values())
425 atpoint = JvSwingUtils.findOrCreateMenu(jws2al, service.action);
427 if (atpoint.getItemCount() > 1)
429 // previous service of this type already present
430 atpoint.addSeparator();
432 atpoint.add(hitm = new JMenuItem(service.getHost()));
433 hitm.setForeground(Color.blue);
434 hitm.addActionListener(new ActionListener()
438 public void actionPerformed(ActionEvent e)
440 Desktop.showUrl(service.getHost());
443 hitm.setToolTipText(JvSwingUtils.wrapTooltip(false,
444 MessageManager.getString("label.open_jabaws_web_page")));
446 service.attachWSMenuEntry(atpoint, alignFrame);
447 if (alternates.containsKey(service.serviceType))
449 atpoint.add(hitm = new JMenu(
450 MessageManager.getString("label.switch_server")));
451 hitm.setToolTipText(JvSwingUtils.wrapTooltip(false,
452 MessageManager.getString("label.choose_jabaws_server")));
453 for (final Jws2Instance sv : alternates.get(service.serviceType))
456 hitm.add(itm = new JMenuItem(sv.getHost()));
457 itm.setForeground(Color.blue);
458 itm.addActionListener(new ActionListener()
462 public void actionPerformed(ActionEvent arg0)
464 new Thread(new Runnable()
469 setPreferredServiceFor(alignFrame, sv.serviceType,
471 changeSupport.firePropertyChange("services",
472 new Vector<Jws2Instance>(), services);
484 * add services using the Java 2.5/2.6/2.7 system which optionally creates
485 * submenus to index by host and service program type
487 private void addEnumeratedServices(final JMenu jws2al,
488 final AlignFrame alignFrame,
489 List<Jws2Instance> enumerableServices)
491 boolean byhost = Cache.getDefault("WSMENU_BYHOST", false),
492 bytype = Cache.getDefault("WSMENU_BYTYPE", false);
494 * eventually, JWS2 services will appear under the same align/etc submenus.
495 * for moment we keep them separate.
499 List<String> hostLabels = new ArrayList<>();
500 Hashtable<String, String> lasthostFor = new Hashtable<>();
501 Hashtable<String, ArrayList<Jws2Instance>> hosts = new Hashtable<>();
502 ArrayList<String> hostlist = new ArrayList<>();
503 for (Jws2Instance service : enumerableServices)
505 ArrayList<Jws2Instance> hostservices = hosts.get(service.getHost());
506 if (hostservices == null)
508 hosts.put(service.getHost(),
509 hostservices = new ArrayList<>());
510 hostlist.add(service.getHost());
512 hostservices.add(service);
514 // now add hosts in order of the given array
515 for (String host : hostlist)
517 Jws2Instance orderedsvcs[] = hosts.get(host)
518 .toArray(new Jws2Instance[1]);
519 String sortbytype[] = new String[orderedsvcs.length];
520 for (int i = 0; i < sortbytype.length; i++)
522 sortbytype[i] = orderedsvcs[i].serviceType;
524 jalview.util.QuickSort.sort(sortbytype, orderedsvcs);
525 for (final Jws2Instance service : orderedsvcs)
527 atpoint = JvSwingUtils.findOrCreateMenu(jws2al, service.action);
528 String type = service.serviceType;
531 atpoint = JvSwingUtils.findOrCreateMenu(atpoint, host);
532 if (atpoint.getToolTipText() == null)
534 atpoint.setToolTipText(MessageManager
535 .formatMessage("label.services_at", new String[]
541 atpoint = JvSwingUtils.findOrCreateMenu(atpoint, type);
542 if (atpoint.getToolTipText() == null)
544 atpoint.setToolTipText(service.getActionText());
547 if (!byhost && !hostLabels.contains(
548 host + service.serviceType + service.getActionText()))
549 // !hostLabels.contains(host + (bytype ?
550 // service.serviceType+service.getActionText() : "")))
552 // add a marker indicating where this service is hosted
553 // relies on services from the same host being listed in a
557 if (hostLabels.contains(host))
559 atpoint.addSeparator();
563 hostLabels.add(host);
565 if (lasthostFor.get(service.action) == null
566 || !lasthostFor.get(service.action).equals(host))
568 atpoint.add(hitm = new JMenuItem(host));
569 hitm.setForeground(Color.blue);
570 hitm.addActionListener(new ActionListener()
574 public void actionPerformed(ActionEvent e)
576 Desktop.showUrl(service.getHost());
580 JvSwingUtils.wrapTooltip(true, MessageManager
581 .getString("label.open_jabaws_web_page")));
582 lasthostFor.put(service.action, host);
585 host + service.serviceType + service.getActionText());
588 service.attachWSMenuEntry(atpoint, alignFrame);
598 public static void main(String[] args)
602 testUrls = new ArrayList<>();
603 for (String url : args)
608 Thread runner = getInstance()
609 .startDiscoverer(new PropertyChangeListener()
613 public void propertyChange(PropertyChangeEvent evt)
615 if (getInstance().services != null)
617 System.out.println("Changesupport: There are now "
618 + getInstance().services.size() + " services");
620 for (Jws2Instance instance : getInstance().services)
622 System.out.println("Service " + i++ + " "
623 + instance.getClass() + "@" + instance.getHost()
624 + ": " + instance.getActionText());
630 while (runner.isAlive())
635 } catch (InterruptedException e)
642 } catch (InterruptedException x)
648 public boolean hasServices()
650 return !running && services != null && services.size() > 0;
653 public boolean isRunning()
658 public void setServiceUrls(List<String> wsUrls)
660 if (wsUrls != null && !wsUrls.isEmpty())
662 StringBuilder urls = new StringBuilder(128);
664 for (String url : wsUrls)
670 Cache.setProperty(JWS2HOSTURLS, urls.toString());
674 Cache.removeProperty(JWS2HOSTURLS);
679 * Returns web service URLs, in the order in which they should be tried (or an
684 public List<String> getServiceUrls()
686 if (testUrls != null)
688 // return test urls, if there are any, instead of touching cache
691 List<String> urls = new ArrayList<>();
693 if (this.preferredUrl != null)
695 urls.add(preferredUrl);
698 String surls = Cache.getDefault(JWS2HOSTURLS, COMPBIO_JABAWS);
701 StringTokenizer st = new StringTokenizer(surls, ",");
702 while (st.hasMoreElements())
707 url = st.nextToken();
709 if (!urls.contains(url))
715 Cache.log.warn("Ignoring duplicate url " + url + " in "
716 + JWS2HOSTURLS + " list");
718 } catch (MalformedURLException ex)
720 Cache.log.warn("Problem whilst trying to make a URL from '"
721 + ((url != null) ? url : "<null>") + "'");
723 "This was probably due to a malformed comma separated list"
724 + " in the " + JWS2HOSTURLS
725 + " entry of $(HOME)/.jalview_properties)");
726 Cache.log.debug("Exception was ", ex);
729 } catch (Exception ex)
731 Cache.log.warn("Error parsing comma separated list of urls in "
732 + JWS2HOSTURLS + " preference.", ex);
737 public Vector<Jws2Instance> getServices()
739 return (services == null) ? new Vector<>()
740 : new Vector<>(services);
744 * test the given URL with the JabaWS test code
749 public static boolean testServiceUrl(URL foo)
753 compbio.ws.client.WSTester
755 { "-h=" + foo.toString() });
756 } catch (Exception e)
760 } catch (OutOfMemoryError e)
773 public boolean restart()
790 * Start a fresh discovery thread and notify the given object when we're
791 * finished. Any known existing threads will be killed before this one is
794 * @param changeSupport2
797 public Thread startDiscoverer(PropertyChangeListener changeSupport2)
805 Thread thr = new Thread(this);
813 addPropertyChangeListener(changeSupport2);
814 Thread thr = new Thread(this);
820 * @return the invalidServiceUrls
822 public Vector<String> getInvalidServiceUrls()
824 return invalidServiceUrls;
828 * @return the urlsWithoutServices
830 public Vector<String> getUrlsWithoutServices()
832 return urlsWithoutServices;
836 * add an 'empty' JABA server to the list. Only servers not already in the
837 * 'bad URL' list will be added to this list.
841 public synchronized void addUrlwithnoservices(String jwsservers)
843 if (urlsWithoutServices == null)
845 urlsWithoutServices = new Vector<>();
848 if ((invalidServiceUrls == null
849 || !invalidServiceUrls.contains(jwsservers))
850 && !urlsWithoutServices.contains(jwsservers))
852 urlsWithoutServices.add(jwsservers);
857 * add a bad URL to the list
861 public synchronized void addInvalidServiceUrl(String jwsservers)
863 if (invalidServiceUrls == null)
865 invalidServiceUrls = new Vector<>();
867 if (!invalidServiceUrls.contains(jwsservers))
869 invalidServiceUrls.add(jwsservers);
875 * @return a human readable report of any problems with the service URLs used
878 public String getErrorMessages()
880 if (!isRunning() && !isAborted())
882 StringBuffer ermsg = new StringBuffer();
883 boolean list = false;
884 if (getInvalidServiceUrls() != null
885 && getInvalidServiceUrls().size() > 0)
887 ermsg.append(MessageManager.getString("warn.urls_not_contacted")
889 for (String svcurl : getInvalidServiceUrls())
896 ermsg.append(svcurl);
898 ermsg.append("\n\n");
901 if (getUrlsWithoutServices() != null
902 && getUrlsWithoutServices().size() > 0)
905 MessageManager.getString("warn.urls_no_jaba") + ": \n");
906 for (String svcurl : getUrlsWithoutServices())
913 ermsg.append(svcurl);
917 if (ermsg.length() > 1)
919 return ermsg.toString();
926 public int getServerStatusFor(String url)
928 if (validServiceUrls != null && validServiceUrls.contains(url))
932 if (urlsWithoutServices != null && urlsWithoutServices.contains(url))
936 if (invalidServiceUrls != null && invalidServiceUrls.contains(url))
944 * pick the user's preferred service based on a set of URLs (jaba server
945 * locations) and service URIs (specifying version and service interface
949 * @return null or best match for given uri/ls.
951 public Jws2Instance getPreferredServiceFor(String[] serviceURLs)
953 HashSet<String> urls = new HashSet<>();
954 urls.addAll(Arrays.asList(serviceURLs));
955 Jws2Instance match = null;
956 if (services != null)
958 for (Jws2Instance svc : services)
960 if (urls.contains(svc.getServiceTypeURI()))
964 // for moment we always pick service from server ordered first in
965 // user's preferences
968 if (urls.contains(svc.getUri()))
970 // stop and return - we've matched type URI and URI for service
980 Map<String, Map<String, String>> preferredServiceMap = new HashMap<>();
983 * get current preferred service of the given type, or global default
986 * null or a specific alignFrame
988 * Jws2Instance.serviceType for service
989 * @return null if no service of this type is available, the preferred service
990 * for the serviceType and af if specified and if defined.
992 public Jws2Instance getPreferredServiceFor(AlignFrame af,
995 String serviceurl = null;
996 synchronized (preferredServiceMap)
998 String afid = (af == null) ? "" : af.getViewport().getSequenceSetId();
999 Map<String, String> prefmap = preferredServiceMap.get(afid);
1000 if (afid.length() > 0 && prefmap == null)
1002 // recover global setting, if any
1003 prefmap = preferredServiceMap.get("");
1005 if (prefmap != null)
1007 serviceurl = prefmap.get(serviceType);
1011 Jws2Instance response = null;
1012 for (Jws2Instance svc : services)
1014 if (svc.serviceType.equals(serviceType))
1016 if (serviceurl == null || serviceurl.equals(svc.getHost()))
1026 public void setPreferredServiceFor(AlignFrame af, String serviceType,
1027 String serviceAction, Jws2Instance selectedServer)
1029 String afid = (af == null) ? "" : af.getViewport().getSequenceSetId();
1030 if (preferredServiceMap == null)
1032 preferredServiceMap = new HashMap<>();
1034 Map<String, String> prefmap = preferredServiceMap.get(afid);
1035 if (prefmap == null)
1037 prefmap = new HashMap<>();
1038 preferredServiceMap.put(afid, prefmap);
1040 prefmap.put(serviceType, selectedServer.getHost());
1041 prefmap.put(serviceAction, selectedServer.getHost());
1044 public void setPreferredServiceFor(String serviceType,
1045 String serviceAction, Jws2Instance selectedServer)
1047 setPreferredServiceFor(null, serviceType, serviceAction,
1052 * Set a URL to try before any others. For use with command-line parameter to
1053 * configure a local Jabaws installation without the need to add to property
1057 * @throws MalformedURLException
1059 public void setPreferredUrl(String value) throws MalformedURLException
1061 if (value != null && value.trim().length() > 0)
1064 preferredUrl = value;