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.ApplicationSingletonProvider;
25 import jalview.bin.ApplicationSingletonProvider.ApplicationSingletonI;
26 import jalview.gui.AlignFrame;
27 import jalview.gui.Desktop;
28 import jalview.gui.JvSwingUtils;
29 import jalview.util.MessageManager;
30 import jalview.ws.WSMenuEntryProviderI;
31 import jalview.ws.jws2.jabaws2.Jws2Instance;
32 import jalview.ws.params.ParamDatastoreI;
34 import java.awt.Color;
35 import java.awt.event.ActionEvent;
36 import java.awt.event.ActionListener;
37 import java.beans.PropertyChangeEvent;
38 import java.beans.PropertyChangeListener;
39 import java.beans.PropertyChangeSupport;
40 import java.net.MalformedURLException;
42 import java.util.ArrayList;
43 import java.util.Arrays;
44 import java.util.HashMap;
45 import java.util.HashSet;
46 import java.util.Hashtable;
47 import java.util.List;
50 import java.util.StringTokenizer;
51 import java.util.Vector;
53 import javax.swing.JMenu;
54 import javax.swing.JMenuItem;
56 import compbio.ws.client.Services;
59 * discoverer for jws2 services. Follows the lightweight service discoverer
60 * pattern (archetyped by EnfinEnvision2OneWay)
65 public class Jws2Discoverer
66 implements Runnable, WSMenuEntryProviderI, ApplicationSingletonI
70 * Returns the singleton instance of this class.
74 public static Jws2Discoverer getInstance()
76 return (Jws2Discoverer) ApplicationSingletonProvider
77 .getInstance(Jws2Discoverer.class);
81 * Private constructor enforces use of singleton via getDiscoverer()
83 private Jws2Discoverer()
88 public static final String COMPBIO_JABAWS = "http://www.compbio.dundee.ac.uk/jabaws";
91 * the .jalview_properties entry for JWS2 URLS
93 private final static String JWS2HOSTURLS = "JWS2HOSTURLS";
96 * Override for testing only
98 private static List<String> testUrls = null;
100 // preferred url has precedence over others
101 private String preferredUrl;
103 protected PropertyChangeSupport changeSupport = new PropertyChangeSupport(
106 private Vector<String> invalidServiceUrls = null;
108 private Vector<String> urlsWithoutServices = null;
110 private Vector<String> validServiceUrls = null;
112 private volatile boolean running = false;
114 private volatile boolean aborted = false;
116 private Thread oldthread = null;
119 * holds list of services.
121 protected Vector<Jws2Instance> services;
124 * change listeners are notified of "services" property changes
127 * to be added that consumes new services Hashtable object.
129 public void addPropertyChangeListener(
130 java.beans.PropertyChangeListener listener)
132 changeSupport.addPropertyChangeListener(listener);
141 public void removePropertyChangeListener(
142 java.beans.PropertyChangeListener listener)
144 changeSupport.removePropertyChangeListener(listener);
148 * @return the aborted
150 public boolean isAborted()
159 public void setAborted(boolean aborted)
161 this.aborted = aborted;
168 if (running && oldthread != null && oldthread.isAlive())
179 "Waiting around for old discovery thread to finish.");
180 // wait around until old discoverer dies
182 } catch (Exception e)
187 Cache.log.debug("Old discovery thread has finished.");
191 // first set up exclusion list if needed
192 final Set<String> ignoredServices = new HashSet<>();
193 for (String ignored : Cache
194 .getDefault("IGNORED_JABAWS_SERVICETYPES", "").split("\\|"))
196 ignoredServices.add(ignored);
199 changeSupport.firePropertyChange("services", services,
200 new Vector<Jws2Instance>());
201 oldthread = Thread.currentThread();
204 getClass().getClassLoader()
205 .loadClass("compbio.ws.client.Jws2Client");
206 } catch (ClassNotFoundException e)
209 "Not enabling JABA Webservices : client jar is not available."
210 + "\nPlease check that your webstart JNLP file is up to date!");
214 // reinitialise records of good and bad service URLs
215 if (services != null)
217 services.removeAllElements();
219 if (urlsWithoutServices != null)
221 urlsWithoutServices.removeAllElements();
223 if (invalidServiceUrls != null)
225 invalidServiceUrls.removeAllElements();
227 if (validServiceUrls != null)
229 validServiceUrls.removeAllElements();
231 ArrayList<String> svctypes = new ArrayList<>();
233 List<JabaWsServerQuery> qrys = new ArrayList<>();
234 for (final String jwsserver : getServiceUrls())
236 JabaWsServerQuery squery = new JabaWsServerQuery(this, jwsserver);
237 if (svctypes.size() == 0)
239 // TODO: remove this ugly hack to get Canonical JABA service ordering
240 // for all possible services
241 for (Services sv : squery.JABAWS2SERVERS)
243 if (!ignoredServices.contains(sv.toString()))
245 svctypes.add(sv.toString());
251 new Thread(squery).start();
253 boolean finished = true;
260 } catch (Exception e)
263 for (JabaWsServerQuery squery : qrys)
265 if (squery.isRunning())
273 "Aborting " + qrys.size() + " JABAWS discovery threads.");
274 for (JabaWsServerQuery squery : qrys)
276 squery.setQuit(true);
279 } while (!aborted && !finished);
282 // resort services according to order found in jabaws service list
283 // also ensure services for each host are ordered in same way.
285 if (services != null && services.size() > 0)
287 Jws2Instance[] svcs = new Jws2Instance[services.size()];
288 int[] spos = new int[services.size()];
290 List<String> svcUrls = getServiceUrls();
291 for (Jws2Instance svc : services)
294 spos[ipos++] = 1000 * svcUrls.indexOf(svc.getHost()) + 1
295 + svctypes.indexOf(svc.serviceType);
297 jalview.util.QuickSort.sort(spos, svcs);
298 services = new Vector<>();
299 for (Jws2Instance svc : svcs)
301 if (!ignoredServices.contains(svc.serviceType))
310 changeSupport.firePropertyChange("services", new Vector<Jws2Instance>(),
315 * record this service endpoint so we can use it
321 synchronized void addService(String jwsservers, Jws2Instance service)
323 if (services == null)
325 services = new Vector<>();
328 "Discovered service: " + jwsservers + " " + service.toString());
329 // Jws2Instance service = new Jws2Instance(jwsservers, srv.toString(),
332 services.add(service);
333 // retrieve the presets and parameter set and cache now
334 ParamDatastoreI pds = service.getParamStore();
339 service.hasParameters();
340 if (validServiceUrls == null)
342 validServiceUrls = new Vector<>();
344 validServiceUrls.add(jwsservers);
348 * attach all available web services to the appropriate submenu in the given
352 public void attachWSMenuEntry(JMenu wsmenu, final AlignFrame alignFrame)
354 // dynamically regenerate service list.
355 populateWSMenuEntry(wsmenu, alignFrame, null);
358 private boolean isRecalculable(String action)
360 return (action != null && action.equalsIgnoreCase("conservation"));
363 private void populateWSMenuEntry(JMenu jws2al,
364 final AlignFrame alignFrame, String typeFilter)
366 if (running || services == null || services.size() == 0)
372 * eventually, JWS2 services will appear under the same align/etc submenus.
373 * for moment we keep them separate.
376 List<Jws2Instance> enumerableServices = new ArrayList<>();
377 // jws2al.removeAll();
378 Map<String, Jws2Instance> preferredHosts = new HashMap<>();
379 Map<String, List<Jws2Instance>> alternates = new HashMap<>();
380 for (Jws2Instance service : services.toArray(new Jws2Instance[0]))
382 if (!isRecalculable(service.action))
384 // add 'one shot' services to be displayed using the classic menu
386 enumerableServices.add(service);
390 if (!preferredHosts.containsKey(service.serviceType))
392 Jws2Instance preferredInstance = getPreferredServiceFor(
393 alignFrame, service.serviceType);
394 if (preferredInstance != null)
396 preferredHosts.put(service.serviceType, preferredInstance);
400 preferredHosts.put(service.serviceType, service);
403 List<Jws2Instance> ph = alternates.get(service.serviceType);
404 if (preferredHosts.get(service.serviceType) != service)
408 ph = new ArrayList<>();
411 alternates.put(service.serviceType, ph);
417 // create GUI element for classic services
418 addEnumeratedServices(jws2al, alignFrame, enumerableServices);
419 // and the instantaneous services
420 for (final Jws2Instance service : preferredHosts.values())
422 atpoint = JvSwingUtils.findOrCreateMenu(jws2al, service.action);
424 if (atpoint.getItemCount() > 1)
426 // previous service of this type already present
427 atpoint.addSeparator();
429 atpoint.add(hitm = new JMenuItem(service.getHost()));
430 hitm.setForeground(Color.blue);
431 hitm.addActionListener(new ActionListener()
435 public void actionPerformed(ActionEvent e)
437 Desktop.showUrl(service.getHost());
440 hitm.setToolTipText(JvSwingUtils.wrapTooltip(false,
441 MessageManager.getString("label.open_jabaws_web_page")));
443 service.attachWSMenuEntry(atpoint, alignFrame);
444 if (alternates.containsKey(service.serviceType))
446 atpoint.add(hitm = new JMenu(
447 MessageManager.getString("label.switch_server")));
448 hitm.setToolTipText(JvSwingUtils.wrapTooltip(false,
449 MessageManager.getString("label.choose_jabaws_server")));
450 for (final Jws2Instance sv : alternates.get(service.serviceType))
453 hitm.add(itm = new JMenuItem(sv.getHost()));
454 itm.setForeground(Color.blue);
455 itm.addActionListener(new ActionListener()
459 public void actionPerformed(ActionEvent arg0)
461 new Thread(new Runnable()
466 setPreferredServiceFor(alignFrame, sv.serviceType,
468 changeSupport.firePropertyChange("services",
469 new Vector<Jws2Instance>(), services);
481 * add services using the Java 2.5/2.6/2.7 system which optionally creates
482 * submenus to index by host and service program type
484 private void addEnumeratedServices(final JMenu jws2al,
485 final AlignFrame alignFrame,
486 List<Jws2Instance> enumerableServices)
488 boolean byhost = Cache.getDefault("WSMENU_BYHOST", false),
489 bytype = Cache.getDefault("WSMENU_BYTYPE", false);
491 * eventually, JWS2 services will appear under the same align/etc submenus.
492 * for moment we keep them separate.
496 List<String> hostLabels = new ArrayList<>();
497 Hashtable<String, String> lasthostFor = new Hashtable<>();
498 Hashtable<String, ArrayList<Jws2Instance>> hosts = new Hashtable<>();
499 ArrayList<String> hostlist = new ArrayList<>();
500 for (Jws2Instance service : enumerableServices)
502 ArrayList<Jws2Instance> hostservices = hosts.get(service.getHost());
503 if (hostservices == null)
505 hosts.put(service.getHost(),
506 hostservices = new ArrayList<>());
507 hostlist.add(service.getHost());
509 hostservices.add(service);
511 // now add hosts in order of the given array
512 for (String host : hostlist)
514 Jws2Instance orderedsvcs[] = hosts.get(host)
515 .toArray(new Jws2Instance[1]);
516 String sortbytype[] = new String[orderedsvcs.length];
517 for (int i = 0; i < sortbytype.length; i++)
519 sortbytype[i] = orderedsvcs[i].serviceType;
521 jalview.util.QuickSort.sort(sortbytype, orderedsvcs);
522 for (final Jws2Instance service : orderedsvcs)
524 atpoint = JvSwingUtils.findOrCreateMenu(jws2al, service.action);
525 String type = service.serviceType;
528 atpoint = JvSwingUtils.findOrCreateMenu(atpoint, host);
529 if (atpoint.getToolTipText() == null)
531 atpoint.setToolTipText(MessageManager
532 .formatMessage("label.services_at", new String[]
538 atpoint = JvSwingUtils.findOrCreateMenu(atpoint, type);
539 if (atpoint.getToolTipText() == null)
541 atpoint.setToolTipText(service.getActionText());
544 if (!byhost && !hostLabels.contains(
545 host + service.serviceType + service.getActionText()))
546 // !hostLabels.contains(host + (bytype ?
547 // service.serviceType+service.getActionText() : "")))
549 // add a marker indicating where this service is hosted
550 // relies on services from the same host being listed in a
554 if (hostLabels.contains(host))
556 atpoint.addSeparator();
560 hostLabels.add(host);
562 if (lasthostFor.get(service.action) == null
563 || !lasthostFor.get(service.action).equals(host))
565 atpoint.add(hitm = new JMenuItem(host));
566 hitm.setForeground(Color.blue);
567 hitm.addActionListener(new ActionListener()
571 public void actionPerformed(ActionEvent e)
573 Desktop.showUrl(service.getHost());
577 JvSwingUtils.wrapTooltip(true, MessageManager
578 .getString("label.open_jabaws_web_page")));
579 lasthostFor.put(service.action, host);
582 host + service.serviceType + service.getActionText());
585 service.attachWSMenuEntry(atpoint, alignFrame);
595 public static void main(String[] args)
599 testUrls = new ArrayList<>();
600 for (String url : args)
605 Thread runner = getInstance()
606 .startDiscoverer(new PropertyChangeListener()
610 public void propertyChange(PropertyChangeEvent evt)
612 if (getInstance().services != null)
614 System.out.println("Changesupport: There are now "
615 + getInstance().services.size() + " services");
617 for (Jws2Instance instance : getInstance().services)
619 System.out.println("Service " + i++ + " "
620 + instance.getClass() + "@" + instance.getHost()
621 + ": " + instance.getActionText());
627 while (runner.isAlive())
632 } catch (InterruptedException e)
639 } catch (InterruptedException x)
644 public boolean hasServices()
646 return !running && services != null && services.size() > 0;
649 public boolean isRunning()
654 public void setServiceUrls(List<String> wsUrls)
656 if (wsUrls != null && !wsUrls.isEmpty())
658 StringBuilder urls = new StringBuilder(128);
660 for (String url : wsUrls)
666 Cache.setProperty(JWS2HOSTURLS, urls.toString());
670 Cache.removeProperty(JWS2HOSTURLS);
675 * Returns web service URLs, in the order in which they should be tried (or an
680 public List<String> getServiceUrls()
682 if (testUrls != null)
684 // return test urls, if there are any, instead of touching cache
687 List<String> urls = new ArrayList<>();
689 if (this.preferredUrl != null)
691 urls.add(preferredUrl);
694 String surls = Cache.getDefault(JWS2HOSTURLS, COMPBIO_JABAWS);
697 StringTokenizer st = new StringTokenizer(surls, ",");
698 while (st.hasMoreElements())
703 url = st.nextToken();
705 if (!urls.contains(url))
711 Cache.log.warn("Ignoring duplicate url " + url + " in "
712 + JWS2HOSTURLS + " list");
714 } catch (MalformedURLException ex)
716 Cache.log.warn("Problem whilst trying to make a URL from '"
717 + ((url != null) ? url : "<null>") + "'");
719 "This was probably due to a malformed comma separated list"
720 + " in the " + JWS2HOSTURLS
721 + " entry of $(HOME)/.jalview_properties)");
722 Cache.log.debug("Exception was ", ex);
725 } catch (Exception ex)
727 Cache.log.warn("Error parsing comma separated list of urls in "
728 + JWS2HOSTURLS + " preference.", ex);
733 public Vector<Jws2Instance> getServices()
735 return (services == null) ? new Vector<>()
736 : new Vector<>(services);
740 * test the given URL with the JabaWS test code
745 public static boolean testServiceUrl(URL foo)
749 compbio.ws.client.WSTester
751 { "-h=" + foo.toString() });
752 } catch (Exception e)
756 } catch (OutOfMemoryError e)
769 public boolean restart()
786 * Start a fresh discovery thread and notify the given object when we're
787 * finished. Any known existing threads will be killed before this one is
790 * @param changeSupport2
793 public Thread startDiscoverer(PropertyChangeListener changeSupport2)
801 Thread thr = new Thread(this);
809 addPropertyChangeListener(changeSupport2);
810 Thread thr = new Thread(this);
816 * @return the invalidServiceUrls
818 public Vector<String> getInvalidServiceUrls()
820 return invalidServiceUrls;
824 * @return the urlsWithoutServices
826 public Vector<String> getUrlsWithoutServices()
828 return urlsWithoutServices;
832 * add an 'empty' JABA server to the list. Only servers not already in the
833 * 'bad URL' list will be added to this list.
837 public synchronized void addUrlwithnoservices(String jwsservers)
839 if (urlsWithoutServices == null)
841 urlsWithoutServices = new Vector<>();
844 if ((invalidServiceUrls == null
845 || !invalidServiceUrls.contains(jwsservers))
846 && !urlsWithoutServices.contains(jwsservers))
848 urlsWithoutServices.add(jwsservers);
853 * add a bad URL to the list
857 public synchronized void addInvalidServiceUrl(String jwsservers)
859 if (invalidServiceUrls == null)
861 invalidServiceUrls = new Vector<>();
863 if (!invalidServiceUrls.contains(jwsservers))
865 invalidServiceUrls.add(jwsservers);
871 * @return a human readable report of any problems with the service URLs used
874 public String getErrorMessages()
876 if (!isRunning() && !isAborted())
878 StringBuffer ermsg = new StringBuffer();
879 boolean list = false;
880 if (getInvalidServiceUrls() != null
881 && getInvalidServiceUrls().size() > 0)
883 ermsg.append(MessageManager.getString("warn.urls_not_contacted")
885 for (String svcurl : getInvalidServiceUrls())
892 ermsg.append(svcurl);
894 ermsg.append("\n\n");
897 if (getUrlsWithoutServices() != null
898 && getUrlsWithoutServices().size() > 0)
901 MessageManager.getString("warn.urls_no_jaba") + ": \n");
902 for (String svcurl : getUrlsWithoutServices())
909 ermsg.append(svcurl);
913 if (ermsg.length() > 1)
915 return ermsg.toString();
922 public int getServerStatusFor(String url)
924 if (validServiceUrls != null && validServiceUrls.contains(url))
928 if (urlsWithoutServices != null && urlsWithoutServices.contains(url))
932 if (invalidServiceUrls != null && invalidServiceUrls.contains(url))
940 * pick the user's preferred service based on a set of URLs (jaba server
941 * locations) and service URIs (specifying version and service interface
945 * @return null or best match for given uri/ls.
947 public Jws2Instance getPreferredServiceFor(String[] serviceURLs)
949 HashSet<String> urls = new HashSet<>();
950 urls.addAll(Arrays.asList(serviceURLs));
951 Jws2Instance match = null;
952 if (services != null)
954 for (Jws2Instance svc : services)
956 if (urls.contains(svc.getServiceTypeURI()))
960 // for moment we always pick service from server ordered first in
961 // user's preferences
964 if (urls.contains(svc.getUri()))
966 // stop and return - we've matched type URI and URI for service
976 Map<String, Map<String, String>> preferredServiceMap = new HashMap<>();
979 * get current preferred service of the given type, or global default
982 * null or a specific alignFrame
984 * Jws2Instance.serviceType for service
985 * @return null if no service of this type is available, the preferred service
986 * for the serviceType and af if specified and if defined.
988 public Jws2Instance getPreferredServiceFor(AlignFrame af,
991 String serviceurl = null;
992 synchronized (preferredServiceMap)
994 String afid = (af == null) ? "" : af.getViewport().getSequenceSetId();
995 Map<String, String> prefmap = preferredServiceMap.get(afid);
996 if (afid.length() > 0 && prefmap == null)
998 // recover global setting, if any
999 prefmap = preferredServiceMap.get("");
1001 if (prefmap != null)
1003 serviceurl = prefmap.get(serviceType);
1007 Jws2Instance response = null;
1008 for (Jws2Instance svc : services)
1010 if (svc.serviceType.equals(serviceType))
1012 if (serviceurl == null || serviceurl.equals(svc.getHost()))
1022 public void setPreferredServiceFor(AlignFrame af, String serviceType,
1023 String serviceAction, Jws2Instance selectedServer)
1025 String afid = (af == null) ? "" : af.getViewport().getSequenceSetId();
1026 if (preferredServiceMap == null)
1028 preferredServiceMap = new HashMap<>();
1030 Map<String, String> prefmap = preferredServiceMap.get(afid);
1031 if (prefmap == null)
1033 prefmap = new HashMap<>();
1034 preferredServiceMap.put(afid, prefmap);
1036 prefmap.put(serviceType, selectedServer.getHost());
1037 prefmap.put(serviceAction, selectedServer.getHost());
1040 public void setPreferredServiceFor(String serviceType,
1041 String serviceAction, Jws2Instance selectedServer)
1043 setPreferredServiceFor(null, serviceType, serviceAction,
1048 * Set a URL to try before any others. For use with command-line parameter to
1049 * configure a local Jabaws installation without the need to add to property
1053 * @throws MalformedURLException
1055 public void setPreferredUrl(String value) throws MalformedURLException
1057 if (value != null && value.trim().length() > 0)
1060 preferredUrl = value;