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.Console;
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";
76 private static Jws2Discoverer discoverer;
79 * Override for testing only
81 private static List<String> testUrls = null;
83 // preferred url has precedence over others
84 private String preferredUrl;
86 private PropertyChangeSupport changeSupport = new PropertyChangeSupport(
89 private Vector<String> invalidServiceUrls = null;
91 private Vector<String> urlsWithoutServices = null;
93 private Vector<String> validServiceUrls = null;
95 private volatile boolean running = false;
97 private volatile boolean aborted = false;
99 private Thread oldthread = null;
102 * holds list of services.
104 protected Vector<Jws2Instance> services;
107 * Private constructor enforces use of singleton via getDiscoverer()
109 private Jws2Discoverer()
114 * change listeners are notified of "services" property changes
117 * to be added that consumes new services Hashtable object.
119 public void addPropertyChangeListener(
120 java.beans.PropertyChangeListener listener)
122 changeSupport.addPropertyChangeListener(listener);
131 public void removePropertyChangeListener(
132 java.beans.PropertyChangeListener listener)
134 changeSupport.removePropertyChangeListener(listener);
138 * @return the aborted
140 public boolean isAborted()
149 public void setAborted(boolean aborted)
151 this.aborted = aborted;
158 if (running && oldthread != null && oldthread.isAlive())
169 "Waiting around for old discovery thread to finish.");
170 // wait around until old discoverer dies
172 } catch (Exception e)
177 Console.debug("Old discovery thread has finished.");
181 // first set up exclusion list if needed
182 final Set<String> ignoredServices = new HashSet<>();
183 for (String ignored : Cache
184 .getDefault("IGNORED_JABAWS_SERVICETYPES", "").split("\\|"))
186 ignoredServices.add(ignored);
189 changeSupport.firePropertyChange("services", services,
190 new Vector<Jws2Instance>());
191 oldthread = Thread.currentThread();
194 Class foo = getClass().getClassLoader()
195 .loadClass("compbio.ws.client.Jws2Client");
196 } catch (ClassNotFoundException e)
199 "Not enabling JABA Webservices : client jar is not available."
200 + "\nPlease check that your webstart JNLP file is up to date!");
204 // reinitialise records of good and bad service URLs
205 if (services != null)
207 services.removeAllElements();
209 if (urlsWithoutServices != null)
211 urlsWithoutServices.removeAllElements();
213 if (invalidServiceUrls != null)
215 invalidServiceUrls.removeAllElements();
217 if (validServiceUrls != null)
219 validServiceUrls.removeAllElements();
221 ArrayList<String> svctypes = new ArrayList<>();
223 List<JabaWsServerQuery> qrys = new ArrayList<>();
224 for (final String jwsserver : getServiceUrls())
226 JabaWsServerQuery squery = new JabaWsServerQuery(this, jwsserver);
227 if (svctypes.size() == 0)
229 // TODO: remove this ugly hack to get Canonical JABA service ordering
230 // for all possible services
231 for (Services sv : squery.JABAWS2SERVERS)
233 if (!ignoredServices.contains(sv.toString()))
235 svctypes.add(sv.toString());
241 new Thread(squery).start();
243 boolean finished = true;
250 } catch (Exception e)
253 for (JabaWsServerQuery squery : qrys)
255 if (squery.isRunning())
263 "Aborting " + qrys.size() + " JABAWS discovery threads.");
264 for (JabaWsServerQuery squery : qrys)
266 squery.setQuit(true);
269 } while (!aborted && !finished);
272 // resort services according to order found in jabaws service list
273 // also ensure services for each host are ordered in same way.
275 if (services != null && services.size() > 0)
277 Jws2Instance[] svcs = new Jws2Instance[services.size()];
278 int[] spos = new int[services.size()];
280 List<String> svcUrls = getServiceUrls();
281 for (Jws2Instance svc : services)
284 spos[ipos++] = 1000 * svcUrls.indexOf(svc.getHost()) + 1
285 + svctypes.indexOf(svc.serviceType);
287 jalview.util.QuickSort.sort(spos, svcs);
288 services = new Vector<>();
289 for (Jws2Instance svc : svcs)
291 if (!ignoredServices.contains(svc.serviceType))
300 changeSupport.firePropertyChange("services", new Vector<Jws2Instance>(),
305 * record this service endpoint so we can use it
311 synchronized void addService(String jwsservers, Jws2Instance service)
313 if (services == null)
315 services = new Vector<>();
318 "Discovered service: " + jwsservers + " " + service.toString());
319 // Jws2Instance service = new Jws2Instance(jwsservers, srv.toString(),
322 services.add(service);
323 // retrieve the presets and parameter set and cache now
324 ParamDatastoreI pds = service.getParamStore();
329 service.hasParameters();
330 if (validServiceUrls == null)
332 validServiceUrls = new Vector<>();
334 validServiceUrls.add(jwsservers);
338 * attach all available web services to the appropriate submenu in the given
342 public void attachWSMenuEntry(JMenu wsmenu, final AlignFrame alignFrame)
344 // dynamically regenerate service list.
345 populateWSMenuEntry(wsmenu, alignFrame, null);
348 private boolean isRecalculable(String action)
350 return (action != null && action.equalsIgnoreCase("conservation"));
353 private void populateWSMenuEntry(JMenu jws2al,
354 final AlignFrame alignFrame, String typeFilter)
356 if (running || services == null || services.size() == 0)
362 * eventually, JWS2 services will appear under the same align/etc submenus.
363 * for moment we keep them separate.
366 List<Jws2Instance> enumerableServices = new ArrayList<>();
367 // jws2al.removeAll();
368 Map<String, Jws2Instance> preferredHosts = new HashMap<>();
369 Map<String, List<Jws2Instance>> alternates = new HashMap<>();
370 for (Jws2Instance service : services.toArray(new Jws2Instance[0]))
372 if (!isRecalculable(service.action))
374 // add 'one shot' services to be displayed using the classic menu
376 enumerableServices.add(service);
380 if (!preferredHosts.containsKey(service.serviceType))
382 Jws2Instance preferredInstance = getPreferredServiceFor(
383 alignFrame, service.serviceType);
384 if (preferredInstance != null)
386 preferredHosts.put(service.serviceType, preferredInstance);
390 preferredHosts.put(service.serviceType, service);
393 List<Jws2Instance> ph = alternates.get(service.serviceType);
394 if (preferredHosts.get(service.serviceType) != service)
398 ph = new ArrayList<>();
401 alternates.put(service.serviceType, ph);
407 // create GUI element for classic services
408 addEnumeratedServices(jws2al, alignFrame, enumerableServices);
409 // and the instantaneous services
410 for (final Jws2Instance service : preferredHosts.values())
412 atpoint = JvSwingUtils.findOrCreateMenu(jws2al, service.action);
414 if (atpoint.getItemCount() > 1)
416 // previous service of this type already present
417 atpoint.addSeparator();
419 atpoint.add(hitm = new JMenuItem(service.getHost()));
420 hitm.setForeground(Color.blue);
421 hitm.addActionListener(new ActionListener()
425 public void actionPerformed(ActionEvent e)
427 Desktop.showUrl(service.getHost());
430 hitm.setToolTipText(JvSwingUtils.wrapTooltip(false,
431 MessageManager.getString("label.open_jabaws_web_page")));
433 service.attachWSMenuEntry(atpoint, alignFrame);
434 if (alternates.containsKey(service.serviceType))
436 atpoint.add(hitm = new JMenu(
437 MessageManager.getString("label.switch_server")));
438 hitm.setToolTipText(JvSwingUtils.wrapTooltip(false,
439 MessageManager.getString("label.choose_jabaws_server")));
440 for (final Jws2Instance sv : alternates.get(service.serviceType))
443 hitm.add(itm = new JMenuItem(sv.getHost()));
444 itm.setForeground(Color.blue);
445 itm.addActionListener(new ActionListener()
449 public void actionPerformed(ActionEvent arg0)
451 new Thread(new Runnable()
456 setPreferredServiceFor(alignFrame, sv.serviceType,
458 changeSupport.firePropertyChange("services",
459 new Vector<Jws2Instance>(), services);
471 * add services using the Java 2.5/2.6/2.7 system which optionally creates
472 * submenus to index by host and service program type
474 private void addEnumeratedServices(final JMenu jws2al,
475 final AlignFrame alignFrame,
476 List<Jws2Instance> enumerableServices)
478 boolean byhost = Cache.getDefault("WSMENU_BYHOST", false),
479 bytype = Cache.getDefault("WSMENU_BYTYPE", false);
481 * eventually, JWS2 services will appear under the same align/etc submenus.
482 * for moment we keep them separate.
486 List<String> hostLabels = new ArrayList<>();
487 Hashtable<String, String> lasthostFor = new Hashtable<>();
488 Hashtable<String, ArrayList<Jws2Instance>> hosts = new Hashtable<>();
489 ArrayList<String> hostlist = new ArrayList<>();
490 for (Jws2Instance service : enumerableServices)
492 ArrayList<Jws2Instance> hostservices = hosts.get(service.getHost());
493 if (hostservices == null)
495 hosts.put(service.getHost(), 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 Console.warn("Ignoring duplicate url " + url + " in "
715 + JWS2HOSTURLS + " list");
717 } catch (MalformedURLException ex)
719 Console.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 Console.debug("Exception was ", ex);
728 } catch (Exception ex)
730 Console.warn("Error parsing comma separated list of urls in "
731 + JWS2HOSTURLS + " preference.", ex);
736 public Vector<Jws2Instance> getServices()
738 return (services == null) ? new Vector<>() : new Vector<>(services);
742 * test the given URL with the JabaWS test code
747 public static boolean testServiceUrl(URL foo)
751 compbio.ws.client.WSTester
753 { "-h=" + foo.toString() });
754 } catch (Exception e)
758 } catch (OutOfMemoryError e)
771 public boolean restart()
788 * Start a fresh discovery thread and notify the given object when we're
789 * finished. Any known existing threads will be killed before this one is
792 * @param changeSupport2
795 public Thread startDiscoverer(PropertyChangeListener changeSupport2)
803 Thread thr = new Thread(this);
811 addPropertyChangeListener(changeSupport2);
812 Thread thr = new Thread(this);
818 * @return the invalidServiceUrls
820 public Vector<String> getInvalidServiceUrls()
822 return invalidServiceUrls;
826 * @return the urlsWithoutServices
828 public Vector<String> getUrlsWithoutServices()
830 return urlsWithoutServices;
834 * add an 'empty' JABA server to the list. Only servers not already in the
835 * 'bad URL' list will be added to this list.
839 public synchronized void addUrlwithnoservices(String jwsservers)
841 if (urlsWithoutServices == null)
843 urlsWithoutServices = new Vector<>();
846 if ((invalidServiceUrls == null
847 || !invalidServiceUrls.contains(jwsservers))
848 && !urlsWithoutServices.contains(jwsservers))
850 urlsWithoutServices.add(jwsservers);
855 * add a bad URL to the list
859 public synchronized void addInvalidServiceUrl(String jwsservers)
861 if (invalidServiceUrls == null)
863 invalidServiceUrls = new Vector<>();
865 if (!invalidServiceUrls.contains(jwsservers))
867 invalidServiceUrls.add(jwsservers);
873 * @return a human readable report of any problems with the service URLs used
876 public String getErrorMessages()
878 if (!isRunning() && !isAborted())
880 StringBuffer ermsg = new StringBuffer();
881 boolean list = false;
882 if (getInvalidServiceUrls() != null
883 && getInvalidServiceUrls().size() > 0)
885 ermsg.append(MessageManager.getString("warn.urls_not_contacted")
887 for (String svcurl : getInvalidServiceUrls())
894 ermsg.append(svcurl);
896 ermsg.append("\n\n");
899 if (getUrlsWithoutServices() != null
900 && getUrlsWithoutServices().size() > 0)
903 MessageManager.getString("warn.urls_no_jaba") + ": \n");
904 for (String svcurl : getUrlsWithoutServices())
911 ermsg.append(svcurl);
915 if (ermsg.length() > 1)
917 return ermsg.toString();
924 public int getServerStatusFor(String url)
926 if (validServiceUrls != null && validServiceUrls.contains(url))
930 if (urlsWithoutServices != null && urlsWithoutServices.contains(url))
934 if (invalidServiceUrls != null && invalidServiceUrls.contains(url))
942 * pick the user's preferred service based on a set of URLs (jaba server
943 * locations) and service URIs (specifying version and service interface
947 * @return null or best match for given uri/ls.
949 public Jws2Instance getPreferredServiceFor(String[] serviceURLs)
951 HashSet<String> urls = new HashSet<>();
952 urls.addAll(Arrays.asList(serviceURLs));
953 Jws2Instance match = null;
954 if (services != null)
956 for (Jws2Instance svc : services)
958 if (urls.contains(svc.getServiceTypeURI()))
962 // for moment we always pick service from server ordered first in
963 // user's preferences
966 if (urls.contains(svc.getUri()))
968 // stop and return - we've matched type URI and URI for service
978 Map<String, Map<String, String>> preferredServiceMap = new HashMap<>();
981 * get current preferred service of the given type, or global default
984 * null or a specific alignFrame
986 * Jws2Instance.serviceType for service
987 * @return null if no service of this type is available, the preferred service
988 * for the serviceType and af if specified and if defined.
990 public Jws2Instance getPreferredServiceFor(AlignFrame af,
993 String serviceurl = null;
994 synchronized (preferredServiceMap)
996 String afid = (af == null) ? "" : af.getViewport().getSequenceSetId();
997 Map<String, String> prefmap = preferredServiceMap.get(afid);
998 if (afid.length() > 0 && prefmap == null)
1000 // recover global setting, if any
1001 prefmap = preferredServiceMap.get("");
1003 if (prefmap != null)
1005 serviceurl = prefmap.get(serviceType);
1009 Jws2Instance response = null;
1010 for (Jws2Instance svc : services)
1012 if (svc.serviceType.equals(serviceType))
1014 if (serviceurl == null || serviceurl.equals(svc.getHost()))
1024 public void setPreferredServiceFor(AlignFrame af, String serviceType,
1025 String serviceAction, Jws2Instance selectedServer)
1027 String afid = (af == null) ? "" : af.getViewport().getSequenceSetId();
1028 if (preferredServiceMap == null)
1030 preferredServiceMap = new HashMap<>();
1032 Map<String, String> prefmap = preferredServiceMap.get(afid);
1033 if (prefmap == null)
1035 prefmap = new HashMap<>();
1036 preferredServiceMap.put(afid, prefmap);
1038 prefmap.put(serviceType, selectedServer.getHost());
1039 prefmap.put(serviceAction, selectedServer.getHost());
1042 public void setPreferredServiceFor(String serviceType,
1043 String serviceAction, Jws2Instance selectedServer)
1045 setPreferredServiceFor(null, serviceType, serviceAction,
1050 * Set a URL to try before any others. For use with command-line parameter to
1051 * configure a local Jabaws installation without the need to add to property
1055 * @throws MalformedURLException
1057 public void setPreferredUrl(String value) throws MalformedURLException
1059 if (value != null && value.trim().length() > 0)
1062 preferredUrl = value;