2 * Jalview - A Sequence Alignment Editor and Viewer (Version 2.8.2)
3 * Copyright (C) 2014 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;
38 import java.util.ArrayList;
39 import java.util.Arrays;
40 import java.util.HashMap;
41 import java.util.HashSet;
42 import java.util.Hashtable;
43 import java.util.List;
46 import java.util.StringTokenizer;
47 import java.util.Vector;
49 import javax.swing.JMenu;
50 import javax.swing.JMenuItem;
52 import compbio.ws.client.Services;
55 * discoverer for jws2 services. Follows the lightweight service discoverer
56 * pattern (archetyped by EnfinEnvision2OneWay)
61 public class Jws2Discoverer implements Runnable, WSMenuEntryProviderI
63 private java.beans.PropertyChangeSupport changeSupport = new java.beans.PropertyChangeSupport(
67 * change listeners are notified of "services" property changes
70 * to be added that consumes new services Hashtable object.
72 public void addPropertyChangeListener(
73 java.beans.PropertyChangeListener listener)
75 changeSupport.addPropertyChangeListener(listener);
84 public void removePropertyChangeListener(
85 java.beans.PropertyChangeListener listener)
87 changeSupport.removePropertyChangeListener(listener);
90 boolean running = false, aborted = false;
95 public boolean isAborted()
104 public void setAborted(boolean aborted)
106 this.aborted = aborted;
109 Thread oldthread = null;
114 if (running && oldthread != null && oldthread.isAlive())
125 .debug("Waiting around for old discovery thread to finish.");
126 // wait around until old discoverer dies
128 } catch (Exception e)
132 Cache.log.debug("Old discovery thread has finished.");
136 // first set up exclusion list if needed
137 final Set<String> ignoredServices = new HashSet<String>();
138 for (String ignored : jalview.bin.Cache.getDefault(
139 "IGNORED_JABAWS_SERVICETYPES", "")
142 ignoredServices.add(ignored);
145 changeSupport.firePropertyChange("services", services, new Vector());
146 oldthread = Thread.currentThread();
149 Class foo = getClass().getClassLoader().loadClass(
150 "compbio.ws.client.Jws2Client");
151 } catch (ClassNotFoundException e)
154 .println("Not enabling JABA Webservices : client jar is not available."
155 + "\nPlease check that your webstart JNLP file is up to date!");
159 // reinitialise records of good and bad service URLs
160 if (services != null)
162 services.removeAllElements();
164 if (urlsWithoutServices != null)
166 urlsWithoutServices.removeAllElements();
168 if (invalidServiceUrls != null)
170 invalidServiceUrls.removeAllElements();
172 if (validServiceUrls != null)
174 validServiceUrls.removeAllElements();
176 ArrayList<String> svctypes = new ArrayList<String>();
178 List<JabaWsServerQuery> qrys = new ArrayList<JabaWsServerQuery>();
179 for (final String jwsservers : getServiceUrls())
181 JabaWsServerQuery squery = new JabaWsServerQuery(this, jwsservers);
182 if (svctypes.size() == 0)
184 // TODO: remove this ugly hack to get Canonical JABA service ordering
185 // for all possible services
186 for (Services sv : squery.JABAWS2SERVERS)
188 if (!ignoredServices.contains(sv.toString()))
190 svctypes.add(sv.toString());
196 new Thread(squery).start();
198 boolean finished = true;
205 } catch (Exception e)
209 for (JabaWsServerQuery squery : qrys)
211 if (squery.isRunning())
218 Cache.log.debug("Aborting " + qrys.size()
219 + " JABAWS discovery threads.");
220 for (JabaWsServerQuery squery : qrys)
222 squery.setQuit(true);
225 } while (!aborted && !finished);
228 // resort services according to order found in jabaws service list
229 // also ensure servics for each host are ordered in same way.
231 if (services != null && services.size() > 0)
233 Jws2Instance[] svcs = new Jws2Instance[services.size()];
234 int[] spos = new int[services.size()];
236 Vector svcUrls = getServiceUrls();
237 for (Jws2Instance svc : services)
240 spos[ipos++] = 1000 * svcUrls.indexOf(svc.getHost()) + 1
241 + svctypes.indexOf(svc.serviceType);
243 jalview.util.QuickSort.sort(spos, svcs);
244 services = new Vector<Jws2Instance>();
245 for (Jws2Instance svc : svcs)
247 if (!ignoredServices.contains(svc.serviceType))
256 changeSupport.firePropertyChange("services", new Vector(), services);
260 * record this service endpoint so we can use it
266 synchronized void addService(String jwsservers, Jws2Instance service)
268 if (services == null)
270 services = new Vector<Jws2Instance>();
272 System.out.println("Discovered service: " + jwsservers + " "
273 + service.toString());
274 // Jws2Instance service = new Jws2Instance(jwsservers, srv.toString(),
277 services.add(service);
278 // retrieve the presets and parameter set and cache now
279 ParamDatastoreI pds = service.getParamStore();
284 service.hasParameters();
285 if (validServiceUrls == null)
287 validServiceUrls = new Vector();
289 validServiceUrls.add(jwsservers);
293 * holds list of services.
295 protected Vector<Jws2Instance> services;
298 * attach all available web services to the appropriate submenu in the given
301 public void attachWSMenuEntry(JMenu wsmenu, final AlignFrame alignFrame)
303 // dynamically regenerate service list.
304 populateWSMenuEntry(wsmenu, alignFrame, null);
307 private boolean isRecalculable(String action)
309 return (action != null && action.equalsIgnoreCase("conservation"));
312 private void populateWSMenuEntry(JMenu jws2al,
313 final AlignFrame alignFrame, String typeFilter)
315 if (running || services == null || services.size() == 0)
319 boolean byhost = Cache.getDefault("WSMENU_BYHOST", false), bytype = Cache
320 .getDefault("WSMENU_BYTYPE", false);
322 * eventually, JWS2 services will appear under the same align/etc submenus.
323 * for moment we keep them separate.
326 List<Jws2Instance> enumerableServices = new ArrayList<Jws2Instance>();
327 // jws2al.removeAll();
328 Map<String, Jws2Instance> preferredHosts = new HashMap<String, Jws2Instance>();
329 Map<String, List<Jws2Instance>> alternates = new HashMap<String, List<Jws2Instance>>();
330 for (Jws2Instance service : services.toArray(new Jws2Instance[0]))
332 if (!isRecalculable(service.action))
334 // add 'one shot' services to be displayed using the classic menu
336 enumerableServices.add(service);
340 if (!preferredHosts.containsKey(service.serviceType))
342 Jws2Instance preferredInstance = getPreferredServiceFor(
343 alignFrame, service.serviceType);
344 if (preferredInstance != null)
346 preferredHosts.put(service.serviceType, preferredInstance);
350 preferredHosts.put(service.serviceType, service);
353 List<Jws2Instance> ph = alternates.get(service.serviceType);
354 if (preferredHosts.get(service.serviceType) != service)
358 ph = new ArrayList<Jws2Instance>();
361 alternates.put(service.serviceType, ph);
367 // create GUI element for classic services
368 addEnumeratedServices(jws2al, alignFrame, enumerableServices);
369 // and the instantaneous services
370 for (final Jws2Instance service : preferredHosts.values())
372 atpoint = JvSwingUtils.findOrCreateMenu(jws2al, service.action);
374 if (atpoint.getItemCount() > 1)
376 // previous service of this type already present
377 atpoint.addSeparator();
379 atpoint.add(hitm = new JMenuItem(service.getHost()));
380 hitm.setForeground(Color.blue);
381 hitm.addActionListener(new ActionListener()
385 public void actionPerformed(ActionEvent e)
387 Desktop.showUrl(service.getHost());
390 hitm.setToolTipText(JvSwingUtils
391 .wrapTooltip(false, MessageManager.getString("label.open_jabaws_web_page ")));
393 service.attachWSMenuEntry(atpoint, alignFrame);
394 if (alternates.containsKey(service.serviceType))
396 atpoint.add(hitm = new JMenu(MessageManager.getString("label.switch_server")));
397 hitm.setToolTipText(JvSwingUtils
398 .wrapTooltip(false, MessageManager.getString("label.choose_jabaws_server")));
399 for (final Jws2Instance sv : alternates.get(service.serviceType))
402 hitm.add(itm = new JMenuItem(sv.getHost()));
403 itm.setForeground(Color.blue);
404 itm.addActionListener(new ActionListener()
408 public void actionPerformed(ActionEvent arg0)
410 new Thread(new Runnable()
414 setPreferredServiceFor(alignFrame, sv.serviceType,
416 changeSupport.firePropertyChange("services",
417 new Vector(), services);
425 * hitm.addActionListener(new ActionListener() {
427 * @Override public void actionPerformed(ActionEvent arg0) { new
428 * Thread(new Runnable() {
430 * @Override public void run() { new SetPreferredServer(alignFrame,
431 * service.serviceType, service.action); } }).start(); } });
438 * add services using the Java 2.5/2.6/2.7 system which optionally creates
439 * submenus to index by host and service program type
441 private void addEnumeratedServices(final JMenu jws2al,
442 final AlignFrame alignFrame, List<Jws2Instance> enumerableServices)
444 boolean byhost = Cache.getDefault("WSMENU_BYHOST", false), bytype = Cache
445 .getDefault("WSMENU_BYTYPE", false);
447 * eventually, JWS2 services will appear under the same align/etc submenus.
448 * for moment we keep them separate.
451 MsaWSClient msacl = new MsaWSClient();
452 List<String> hostLabels = new ArrayList<String>();
453 Hashtable<String, String> lasthostFor = new Hashtable<String, String>();
454 Hashtable<String, ArrayList<Jws2Instance>> hosts = new Hashtable<String, ArrayList<Jws2Instance>>();
455 ArrayList<String> hostlist = new ArrayList<String>();
456 for (Jws2Instance service : enumerableServices)
458 ArrayList<Jws2Instance> hostservices = hosts.get(service.getHost());
459 if (hostservices == null)
461 hosts.put(service.getHost(),
462 hostservices = new ArrayList<Jws2Instance>());
463 hostlist.add(service.getHost());
465 hostservices.add(service);
467 // now add hosts in order of the given array
468 for (String host : hostlist)
470 Jws2Instance orderedsvcs[] = hosts.get(host).toArray(
471 new Jws2Instance[1]);
472 String sortbytype[] = new String[orderedsvcs.length];
473 for (int i = 0; i < sortbytype.length; i++)
475 sortbytype[i] = orderedsvcs[i].serviceType;
477 jalview.util.QuickSort.sort(sortbytype, orderedsvcs);
478 for (final Jws2Instance service : orderedsvcs)
480 atpoint = JvSwingUtils.findOrCreateMenu(jws2al, service.action);
481 String type = service.serviceType;
484 atpoint = JvSwingUtils.findOrCreateMenu(atpoint, host);
485 if (atpoint.getToolTipText() == null)
487 atpoint.setToolTipText(MessageManager.formatMessage("label.services_at", new String[]{host}));
492 atpoint = JvSwingUtils.findOrCreateMenu(atpoint, type);
493 if (atpoint.getToolTipText() == null)
495 atpoint.setToolTipText(service.getActionText());
499 && !hostLabels.contains(host + service.serviceType
500 + service.getActionText()))
501 // !hostLabels.contains(host + (bytype ?
502 // service.serviceType+service.getActionText() : "")))
504 // add a marker indicating where this service is hosted
505 // relies on services from the same host being listed in a
509 if (hostLabels.contains(host))
511 atpoint.addSeparator();
515 hostLabels.add(host);
517 if (lasthostFor.get(service.action) == null
518 || !lasthostFor.get(service.action).equals(host))
520 atpoint.add(hitm = new JMenuItem(host));
521 hitm.setForeground(Color.blue);
522 hitm.addActionListener(new ActionListener()
526 public void actionPerformed(ActionEvent e)
528 Desktop.showUrl(service.getHost());
531 hitm.setToolTipText(JvSwingUtils
532 .wrapTooltip(true, MessageManager.getString("label.open_jabaws_web_page")));
533 lasthostFor.put(service.action, host);
535 hostLabels.add(host + service.serviceType
536 + service.getActionText());
539 service.attachWSMenuEntry(atpoint, alignFrame);
544 public static void main(String[] args)
548 testUrls = new Vector<String>();
549 for (String url : args)
555 Thread runner = getDiscoverer().startDiscoverer(
556 new PropertyChangeListener()
559 public void propertyChange(PropertyChangeEvent evt)
561 if (getDiscoverer().services != null)
563 System.out.println("Changesupport: There are now "
564 + getDiscoverer().services.size() + " services");
566 for (Jws2Instance instance : getDiscoverer().services)
568 System.out.println("Service " + i++ + " "
569 + instance.getClass() + "@"
570 + instance.getHost() + ": "
571 + instance.getActionText());
577 while (runner.isAlive())
582 } catch (InterruptedException e)
590 } catch (InterruptedException x)
595 private static Jws2Discoverer discoverer;
597 public static Jws2Discoverer getDiscoverer()
599 if (discoverer == null)
601 discoverer = new Jws2Discoverer();
606 public boolean hasServices()
608 // TODO Auto-generated method stub
609 return !running && services != null && services.size() > 0;
612 public boolean isRunning()
618 * the jalview .properties entry for JWS2 URLS
620 final static String JWS2HOSTURLS = "JWS2HOSTURLS";
622 public static void setServiceUrls(Vector<String> urls)
626 StringBuffer urlbuffer = new StringBuffer();
628 for (String url : urls)
630 urlbuffer.append(sep);
631 urlbuffer.append(url);
634 Cache.setProperty(JWS2HOSTURLS, urlbuffer.toString());
638 Cache.removeProperty(JWS2HOSTURLS);
642 private static Vector<String> testUrls = null;
644 public static Vector<String> getServiceUrls()
646 if (testUrls != null)
648 // return test urls, if there are any, instead of touching cache
651 String surls = Cache.getDefault(JWS2HOSTURLS,
652 "http://www.compbio.dundee.ac.uk/jabaws");
653 Vector<String> urls = new Vector<String>();
656 StringTokenizer st = new StringTokenizer(surls, ",");
657 while (st.hasMoreElements())
662 java.net.URL u = new java.net.URL(url = st.nextToken());
663 if (!urls.contains(url))
669 jalview.bin.Cache.log.info("Ignoring duplicate url in "
670 + JWS2HOSTURLS + " list");
672 } catch (Exception ex)
674 jalview.bin.Cache.log
675 .warn("Problem whilst trying to make a URL from '"
676 + ((url != null) ? url : "<null>") + "'");
677 jalview.bin.Cache.log
678 .warn("This was probably due to a malformed comma separated list"
681 + " entry of $(HOME)/.jalview_properties)");
682 jalview.bin.Cache.log.debug("Exception was ", ex);
685 } catch (Exception ex)
687 jalview.bin.Cache.log.warn(
688 "Error parsing comma separated list of urls in "
689 + JWS2HOSTURLS + " preference.", ex);
691 if (urls.size() >= 0)
698 public Vector<Jws2Instance> getServices()
700 return (services == null) ? new Vector<Jws2Instance>()
701 : new Vector<Jws2Instance>(services);
705 * test the given URL with the JabaWS test code
710 public static boolean testServiceUrl(URL foo)
714 compbio.ws.client.WSTester.main(new String[]
715 { "-h=" + foo.toString() });
716 } catch (Exception e)
720 } catch (OutOfMemoryError e)
734 * Start a fresh discovery thread and notify the given object when we're
735 * finished. Any known existing threads will be killed before this one is
738 * @param changeSupport2
741 public Thread startDiscoverer(PropertyChangeListener changeSupport2)
747 addPropertyChangeListener(changeSupport2);
748 Thread thr = new Thread(this);
753 Vector<String> invalidServiceUrls = null, urlsWithoutServices = null,
754 validServiceUrls = null;
757 * @return the invalidServiceUrls
759 public Vector<String> getInvalidServiceUrls()
761 return invalidServiceUrls;
765 * @return the urlsWithoutServices
767 public Vector<String> getUrlsWithoutServices()
769 return urlsWithoutServices;
773 * add an 'empty' JABA server to the list. Only servers not already in the
774 * 'bad URL' list will be added to this list.
778 public synchronized void addUrlwithnoservices(String jwsservers)
780 if (urlsWithoutServices == null)
782 urlsWithoutServices = new Vector<String>();
785 if ((invalidServiceUrls == null || !invalidServiceUrls
786 .contains(jwsservers))
787 && !urlsWithoutServices.contains(jwsservers))
789 urlsWithoutServices.add(jwsservers);
794 * add a bad URL to the list
798 public synchronized void addInvalidServiceUrl(String jwsservers)
800 if (invalidServiceUrls == null)
802 invalidServiceUrls = new Vector<String>();
804 if (!invalidServiceUrls.contains(jwsservers))
806 invalidServiceUrls.add(jwsservers);
812 * @return a human readable report of any problems with the service URLs used
815 public String getErrorMessages()
817 if (!isRunning() && !isAborted())
819 StringBuffer ermsg = new StringBuffer();
820 boolean list = false;
821 if (getInvalidServiceUrls() != null
822 && getInvalidServiceUrls().size() > 0)
824 ermsg.append("URLs that could not be contacted: \n");
825 for (String svcurl : getInvalidServiceUrls())
832 ermsg.append(svcurl);
834 ermsg.append("\n\n");
837 if (getUrlsWithoutServices() != null
838 && getUrlsWithoutServices().size() > 0)
840 ermsg.append("URLs without any JABA Services : \n");
841 for (String svcurl : getUrlsWithoutServices())
848 ermsg.append(svcurl);
852 if (ermsg.length() > 1)
854 return ermsg.toString();
861 public int getServerStatusFor(String url)
863 if (validServiceUrls != null && validServiceUrls.contains(url))
867 if (urlsWithoutServices != null && urlsWithoutServices.contains(url))
869 if (invalidServiceUrls != null && invalidServiceUrls.contains(url))
877 * pick the user's preferred service based on a set of URLs (jaba server
878 * locations) and service URIs (specifying version and service interface
882 * @return null or best match for given uri/ls.
884 public Jws2Instance getPreferredServiceFor(String[] serviceURLs)
886 HashSet<String> urls = new HashSet<String>();
887 urls.addAll(Arrays.asList(serviceURLs));
888 Jws2Instance match = null;
889 if (services != null)
891 for (Jws2Instance svc : services)
893 if (urls.contains(svc.getServiceTypeURI()))
897 // for moment we always pick service from server ordered first in
898 // user's preferences
901 if (urls.contains(svc.getUri()))
903 // stop and return - we've matched type URI and URI for service
913 Map<String, Map<String, String>> preferredServiceMap = new HashMap<String, Map<String, String>>();;
916 * get current preferred service of the given type, or global default
919 * null or a specific alignFrame
921 * Jws2Instance.serviceType for service
922 * @return null if no service of this type is available, the preferred service
923 * for the serviceType and af if specified and if defined.
925 public Jws2Instance getPreferredServiceFor(AlignFrame af,
928 String serviceurl = null;
929 synchronized (preferredServiceMap)
931 String afid = (af == null) ? "" : af.getViewport().getSequenceSetId();
932 Map<String, String> prefmap = preferredServiceMap.get(afid);
933 if (afid.length() > 0 && prefmap == null)
935 // recover global setting, if any
936 prefmap = preferredServiceMap.get("");
940 serviceurl = prefmap.get(serviceType);
944 Jws2Instance response = null;
945 for (Jws2Instance svc : services)
947 if (svc.serviceType.equals(serviceType))
949 if (serviceurl == null || serviceurl.equals(svc.getHost()))
959 public void setPreferredServiceFor(AlignFrame af, String serviceType,
960 String serviceAction, Jws2Instance selectedServer)
962 String afid = (af == null) ? "" : af.getViewport().getSequenceSetId();
963 if (preferredServiceMap == null)
965 preferredServiceMap = new HashMap<String, Map<String, String>>();
967 Map<String, String> prefmap = preferredServiceMap.get(afid);
970 prefmap = new HashMap<String, String>();
971 preferredServiceMap.put(afid, prefmap);
973 prefmap.put(serviceType, selectedServer.getHost());
974 prefmap.put(serviceAction, selectedServer.getHost());
977 public void setPreferredServiceFor(String serviceType,
978 String serviceAction, Jws2Instance selectedServer)
980 setPreferredServiceFor(null, serviceType, serviceAction, selectedServer);