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.ws.WSMenuEntryProviderI;
28 import jalview.ws.jws2.jabaws2.Jws2Instance;
29 import jalview.ws.params.ParamDatastoreI;
31 import java.awt.Color;
32 import java.awt.event.ActionEvent;
33 import java.awt.event.ActionListener;
34 import java.beans.PropertyChangeEvent;
35 import java.beans.PropertyChangeListener;
37 import java.util.ArrayList;
38 import java.util.Arrays;
39 import java.util.HashMap;
40 import java.util.HashSet;
41 import java.util.Hashtable;
42 import java.util.List;
45 import java.util.StringTokenizer;
46 import java.util.Vector;
48 import javax.swing.JMenu;
49 import javax.swing.JMenuItem;
51 import compbio.ws.client.Services;
54 * discoverer for jws2 services. Follows the lightweight service discoverer
55 * pattern (archetyped by EnfinEnvision2OneWay)
60 public class Jws2Discoverer implements Runnable, WSMenuEntryProviderI
62 private java.beans.PropertyChangeSupport changeSupport = new java.beans.PropertyChangeSupport(
66 * change listeners are notified of "services" property changes
69 * to be added that consumes new services Hashtable object.
71 public void addPropertyChangeListener(
72 java.beans.PropertyChangeListener listener)
74 changeSupport.addPropertyChangeListener(listener);
83 public void removePropertyChangeListener(
84 java.beans.PropertyChangeListener listener)
86 changeSupport.removePropertyChangeListener(listener);
89 boolean running = false, aborted = false;
94 public boolean isAborted()
103 public void setAborted(boolean aborted)
105 this.aborted = aborted;
108 Thread oldthread = null;
113 if (running && oldthread != null && oldthread.isAlive())
124 .debug("Waiting around for old discovery thread to finish.");
125 // wait around until old discoverer dies
127 } catch (Exception e)
131 Cache.log.debug("Old discovery thread has finished.");
135 // first set up exclusion list if needed
136 final Set<String> ignoredServices = new HashSet<String>();
137 for (String ignored : jalview.bin.Cache.getDefault(
138 "IGNORED_JABAWS_SERVICETYPES", Services.JpredWS.toString())
141 ignoredServices.add(ignored);
144 changeSupport.firePropertyChange("services", services, new Vector());
145 oldthread = Thread.currentThread();
148 Class foo = getClass().getClassLoader().loadClass(
149 "compbio.ws.client.Jws2Client");
150 } catch (ClassNotFoundException e)
153 .println("Not enabling JABA Webservices : client jar is not available."
154 + "\nPlease check that your webstart JNLP file is up to date!");
158 // reinitialise records of good and bad service URLs
159 if (services != null)
161 services.removeAllElements();
163 if (urlsWithoutServices != null)
165 urlsWithoutServices.removeAllElements();
167 if (invalidServiceUrls != null)
169 invalidServiceUrls.removeAllElements();
171 if (validServiceUrls != null)
173 validServiceUrls.removeAllElements();
175 ArrayList<String> svctypes = new ArrayList<String>();
177 List<JabaWsServerQuery> qrys = new ArrayList<JabaWsServerQuery>();
178 for (final String jwsservers : getServiceUrls())
180 JabaWsServerQuery squery = new JabaWsServerQuery(this, jwsservers);
181 if (svctypes.size() == 0)
183 // TODO: remove this ugly hack to get Canonical JABA service ordering
184 // for all possible services
185 for (Services sv : squery.JABAWS2SERVERS)
187 if (!ignoredServices.contains(sv.toString()))
189 svctypes.add(sv.toString());
195 new Thread(squery).start();
197 boolean finished = true;
204 } catch (Exception e)
208 for (JabaWsServerQuery squery : qrys)
210 if (squery.isRunning())
217 Cache.log.debug("Aborting " + qrys.size()
218 + " JABAWS discovery threads.");
219 for (JabaWsServerQuery squery : qrys)
221 squery.setQuit(true);
224 } while (!aborted && !finished);
227 // resort services according to order found in jabaws service list
228 // also ensure servics for each host are ordered in same way.
230 if (services != null && services.size() > 0)
232 Jws2Instance[] svcs = new Jws2Instance[services.size()];
233 int[] spos = new int[services.size()];
235 Vector svcUrls = getServiceUrls();
236 for (Jws2Instance svc : services)
239 spos[ipos++] = 1000 * svcUrls.indexOf(svc.getHost()) + 1
240 + svctypes.indexOf(svc.serviceType);
242 jalview.util.QuickSort.sort(spos, svcs);
243 services = new Vector<Jws2Instance>();
244 for (Jws2Instance svc : svcs)
246 if (!ignoredServices.contains(svc.serviceType))
255 changeSupport.firePropertyChange("services", new Vector(), services);
259 * record this service endpoint so we can use it
265 synchronized void addService(String jwsservers, Jws2Instance service)
267 if (services == null)
269 services = new Vector<Jws2Instance>();
271 System.out.println("Discovered service: " + jwsservers + " "
272 + service.toString());
273 // Jws2Instance service = new Jws2Instance(jwsservers, srv.toString(),
276 services.add(service);
277 // retrieve the presets and parameter set and cache now
278 ParamDatastoreI pds = service.getParamStore();
283 service.hasParameters();
284 if (validServiceUrls == null)
286 validServiceUrls = new Vector();
288 validServiceUrls.add(jwsservers);
292 * holds list of services.
294 protected Vector<Jws2Instance> services;
297 * attach all available web services to the appropriate submenu in the given
300 public void attachWSMenuEntry(JMenu wsmenu, final AlignFrame alignFrame)
302 // dynamically regenerate service list.
303 populateWSMenuEntry(wsmenu, alignFrame, null);
306 private boolean isRecalculable(String action)
308 return (action != null && action.equalsIgnoreCase("conservation"));
311 private void populateWSMenuEntry(JMenu jws2al,
312 final AlignFrame alignFrame, String typeFilter)
314 if (running || services == null || services.size() == 0)
318 boolean byhost = Cache.getDefault("WSMENU_BYHOST", false), bytype = Cache
319 .getDefault("WSMENU_BYTYPE", false);
321 * eventually, JWS2 services will appear under the same align/etc submenus.
322 * for moment we keep them separate.
325 List<Jws2Instance> enumerableServices = new ArrayList<Jws2Instance>();
326 // jws2al.removeAll();
327 Map<String, Jws2Instance> preferredHosts = new HashMap<String, Jws2Instance>();
328 Map<String, List<Jws2Instance>> alternates = new HashMap<String, List<Jws2Instance>>();
329 for (Jws2Instance service : services.toArray(new Jws2Instance[0]))
331 if (!isRecalculable(service.action))
333 // add 'one shot' services to be displayed using the classic menu
335 enumerableServices.add(service);
339 if (!preferredHosts.containsKey(service.serviceType))
341 Jws2Instance preferredInstance = getPreferredServiceFor(
342 alignFrame, service.serviceType);
343 if (preferredInstance != null)
345 preferredHosts.put(service.serviceType, preferredInstance);
349 preferredHosts.put(service.serviceType, service);
352 List<Jws2Instance> ph = alternates.get(service.serviceType);
353 if (preferredHosts.get(service.serviceType) != service)
357 ph = new ArrayList<Jws2Instance>();
360 alternates.put(service.serviceType, ph);
366 // create GUI element for classic services
367 addEnumeratedServices(jws2al, alignFrame, enumerableServices);
368 // and the instantaneous services
369 for (final Jws2Instance service : preferredHosts.values())
371 atpoint = JvSwingUtils.findOrCreateMenu(jws2al, service.action);
373 if (atpoint.getItemCount() > 1)
375 // previous service of this type already present
376 atpoint.addSeparator();
378 atpoint.add(hitm = new JMenuItem(service.getHost()));
379 hitm.setForeground(Color.blue);
380 hitm.addActionListener(new ActionListener()
384 public void actionPerformed(ActionEvent e)
386 Desktop.showUrl(service.getHost());
389 hitm.setToolTipText(JvSwingUtils
390 .wrapTooltip("Opens the JABAWS server's homepage in web browser"));
392 service.attachWSMenuEntry(atpoint, alignFrame);
393 if (alternates.containsKey(service.serviceType))
395 atpoint.add(hitm = new JMenu("Switch server"));
396 hitm.setToolTipText(JvSwingUtils
397 .wrapTooltip("Choose a server for running this service"));
398 for (final Jws2Instance sv : alternates.get(service.serviceType))
401 hitm.add(itm = new JMenuItem(sv.getHost()));
402 itm.setForeground(Color.blue);
403 itm.addActionListener(new ActionListener()
407 public void actionPerformed(ActionEvent arg0)
409 new Thread(new Runnable()
413 setPreferredServiceFor(alignFrame, sv.serviceType,
415 changeSupport.firePropertyChange("services",
416 new Vector(), services);
424 * hitm.addActionListener(new ActionListener() {
426 * @Override public void actionPerformed(ActionEvent arg0) { new
427 * Thread(new Runnable() {
429 * @Override public void run() { new SetPreferredServer(alignFrame,
430 * service.serviceType, service.action); } }).start(); } });
437 * add services using the Java 2.5/2.6/2.7 system which optionally creates
438 * submenus to index by host and service program type
440 private void addEnumeratedServices(final JMenu jws2al,
441 final AlignFrame alignFrame, List<Jws2Instance> enumerableServices)
443 boolean byhost = Cache.getDefault("WSMENU_BYHOST", false), bytype = Cache
444 .getDefault("WSMENU_BYTYPE", false);
446 * eventually, JWS2 services will appear under the same align/etc submenus.
447 * for moment we keep them separate.
450 MsaWSClient msacl = new MsaWSClient();
451 List<String> hostLabels = new ArrayList<String>();
452 Hashtable<String, String> lasthostFor = new Hashtable<String, String>();
453 Hashtable<String, ArrayList<Jws2Instance>> hosts = new Hashtable<String, ArrayList<Jws2Instance>>();
454 ArrayList<String> hostlist = new ArrayList<String>();
455 for (Jws2Instance service : enumerableServices)
457 ArrayList<Jws2Instance> hostservices = hosts.get(service.getHost());
458 if (hostservices == null)
460 hosts.put(service.getHost(),
461 hostservices = new ArrayList<Jws2Instance>());
462 hostlist.add(service.getHost());
464 hostservices.add(service);
466 // now add hosts in order of the given array
467 for (String host : hostlist)
469 Jws2Instance orderedsvcs[] = hosts.get(host).toArray(
470 new Jws2Instance[1]);
471 String sortbytype[] = new String[orderedsvcs.length];
472 for (int i = 0; i < sortbytype.length; i++)
474 sortbytype[i] = orderedsvcs[i].serviceType;
476 jalview.util.QuickSort.sort(sortbytype, orderedsvcs);
477 for (final Jws2Instance service : orderedsvcs)
479 atpoint = JvSwingUtils.findOrCreateMenu(jws2al, service.action);
480 String type = service.serviceType;
483 atpoint = JvSwingUtils.findOrCreateMenu(atpoint, host);
484 if (atpoint.getToolTipText() == null)
486 atpoint.setToolTipText("Services at " + host);
491 atpoint = JvSwingUtils.findOrCreateMenu(atpoint, type);
492 if (atpoint.getToolTipText() == null)
494 atpoint.setToolTipText(service.getActionText());
498 && !hostLabels.contains(host + service.serviceType
499 + service.getActionText()))
500 // !hostLabels.contains(host + (bytype ?
501 // service.serviceType+service.getActionText() : "")))
503 // add a marker indicating where this service is hosted
504 // relies on services from the same host being listed in a
508 if (hostLabels.contains(host))
510 atpoint.addSeparator();
514 hostLabels.add(host);
516 if (lasthostFor.get(service.action) == null
517 || !lasthostFor.get(service.action).equals(host))
519 atpoint.add(hitm = new JMenuItem(host));
520 hitm.setForeground(Color.blue);
521 hitm.addActionListener(new ActionListener()
525 public void actionPerformed(ActionEvent e)
527 Desktop.showUrl(service.getHost());
530 hitm.setToolTipText(JvSwingUtils
531 .wrapTooltip("Opens the JABAWS server's homepage in web browser"));
532 lasthostFor.put(service.action, host);
534 hostLabels.add(host + service.serviceType
535 + service.getActionText());
538 service.attachWSMenuEntry(atpoint, alignFrame);
543 public static void main(String[] args)
547 testUrls = new Vector<String>();
548 for (String url : args)
554 Thread runner = getDiscoverer().startDiscoverer(
555 new PropertyChangeListener()
558 public void propertyChange(PropertyChangeEvent evt)
560 if (getDiscoverer().services != null)
562 System.out.println("Changesupport: There are now "
563 + getDiscoverer().services.size() + " services");
565 for (Jws2Instance instance : getDiscoverer().services)
567 System.out.println("Service " + i++ + " "
568 + instance.getClass() + "@"
569 + instance.getHost() + ": "
570 + instance.getActionText());
576 while (runner.isAlive())
581 } catch (InterruptedException e)
589 } catch (InterruptedException x)
594 private static Jws2Discoverer discoverer;
596 public static Jws2Discoverer getDiscoverer()
598 if (discoverer == null)
600 discoverer = new Jws2Discoverer();
605 public boolean hasServices()
607 // TODO Auto-generated method stub
608 return !running && services != null && services.size() > 0;
611 public boolean isRunning()
617 * the jalview .properties entry for JWS2 URLS
619 final static String JWS2HOSTURLS = "JWS2HOSTURLS";
621 public static void setServiceUrls(Vector<String> urls)
625 StringBuffer urlbuffer = new StringBuffer();
627 for (String url : urls)
629 urlbuffer.append(sep);
630 urlbuffer.append(url);
633 Cache.setProperty(JWS2HOSTURLS, urlbuffer.toString());
637 Cache.removeProperty(JWS2HOSTURLS);
641 private static Vector<String> testUrls = null;
643 public static Vector<String> getServiceUrls()
645 if (testUrls != null)
647 // return test urls, if there are any, instead of touching cache
650 String surls = Cache.getDefault(JWS2HOSTURLS,
651 "http://www.compbio.dundee.ac.uk/jabaws");
652 Vector<String> urls = new Vector<String>();
655 StringTokenizer st = new StringTokenizer(surls, ",");
656 while (st.hasMoreElements())
661 java.net.URL u = new java.net.URL(url = st.nextToken());
662 if (!urls.contains(url))
668 jalview.bin.Cache.log.info("Ignoring duplicate url in "
669 + JWS2HOSTURLS + " list");
671 } catch (Exception ex)
673 jalview.bin.Cache.log
674 .warn("Problem whilst trying to make a URL from '"
675 + ((url != null) ? url : "<null>") + "'");
676 jalview.bin.Cache.log
677 .warn("This was probably due to a malformed comma separated list"
680 + " entry of $(HOME)/.jalview_properties)");
681 jalview.bin.Cache.log.debug("Exception was ", ex);
684 } catch (Exception ex)
686 jalview.bin.Cache.log.warn(
687 "Error parsing comma separated list of urls in "
688 + JWS2HOSTURLS + " preference.", ex);
690 if (urls.size() >= 0)
697 public Vector<Jws2Instance> getServices()
699 return (services == null) ? new Vector<Jws2Instance>()
700 : new Vector<Jws2Instance>(services);
704 * test the given URL with the JabaWS test code
709 public static boolean testServiceUrl(URL foo)
713 compbio.ws.client.WSTester.main(new String[]
714 { "-h=" + foo.toString() });
715 } catch (Exception e)
719 } catch (OutOfMemoryError e)
733 * Start a fresh discovery thread and notify the given object when we're
734 * finished. Any known existing threads will be killed before this one is
737 * @param changeSupport2
740 public Thread startDiscoverer(PropertyChangeListener changeSupport2)
746 addPropertyChangeListener(changeSupport2);
747 Thread thr = new Thread(this);
752 Vector<String> invalidServiceUrls = null, urlsWithoutServices = null,
753 validServiceUrls = null;
756 * @return the invalidServiceUrls
758 public Vector<String> getInvalidServiceUrls()
760 return invalidServiceUrls;
764 * @return the urlsWithoutServices
766 public Vector<String> getUrlsWithoutServices()
768 return urlsWithoutServices;
772 * add an 'empty' JABA server to the list. Only servers not already in the
773 * 'bad URL' list will be added to this list.
777 public synchronized void addUrlwithnoservices(String jwsservers)
779 if (urlsWithoutServices == null)
781 urlsWithoutServices = new Vector<String>();
784 if ((invalidServiceUrls == null || !invalidServiceUrls
785 .contains(jwsservers))
786 && !urlsWithoutServices.contains(jwsservers))
788 urlsWithoutServices.add(jwsservers);
793 * add a bad URL to the list
797 public synchronized void addInvalidServiceUrl(String jwsservers)
799 if (invalidServiceUrls == null)
801 invalidServiceUrls = new Vector<String>();
803 if (!invalidServiceUrls.contains(jwsservers))
805 invalidServiceUrls.add(jwsservers);
811 * @return a human readable report of any problems with the service URLs used
814 public String getErrorMessages()
816 if (!isRunning() && !isAborted())
818 StringBuffer ermsg = new StringBuffer();
819 boolean list = false;
820 if (getInvalidServiceUrls() != null
821 && getInvalidServiceUrls().size() > 0)
823 ermsg.append("URLs that could not be contacted: \n");
824 for (String svcurl : getInvalidServiceUrls())
831 ermsg.append(svcurl);
833 ermsg.append("\n\n");
836 if (getUrlsWithoutServices() != null
837 && getUrlsWithoutServices().size() > 0)
839 ermsg.append("URLs without any JABA Services : \n");
840 for (String svcurl : getUrlsWithoutServices())
847 ermsg.append(svcurl);
851 if (ermsg.length() > 1)
853 return ermsg.toString();
860 public int getServerStatusFor(String url)
862 if (validServiceUrls != null && validServiceUrls.contains(url))
866 if (urlsWithoutServices != null && urlsWithoutServices.contains(url))
868 if (invalidServiceUrls != null && invalidServiceUrls.contains(url))
876 * pick the user's preferred service based on a set of URLs (jaba server
877 * locations) and service URIs (specifying version and service interface
881 * @return null or best match for given uri/ls.
883 public Jws2Instance getPreferredServiceFor(String[] serviceURLs)
885 HashSet<String> urls = new HashSet<String>();
886 urls.addAll(Arrays.asList(serviceURLs));
887 Jws2Instance match = null;
888 if (services != null)
890 for (Jws2Instance svc : services)
892 if (urls.contains(svc.getServiceTypeURI()))
896 // for moment we always pick service from server ordered first in
897 // user's preferences
900 if (urls.contains(svc.getUri()))
902 // stop and return - we've matched type URI and URI for service
912 Map<String, Map<String, String>> preferredServiceMap = new HashMap<String, Map<String, String>>();;
915 * get current preferred service of the given type, or global default
918 * null or a specific alignFrame
920 * Jws2Instance.serviceType for service
921 * @return null if no service of this type is available, the preferred service
922 * for the serviceType and af if specified and if defined.
924 public Jws2Instance getPreferredServiceFor(AlignFrame af,
927 String serviceurl = null;
928 synchronized (preferredServiceMap)
930 String afid = (af == null) ? "" : af.getViewport().getSequenceSetId();
931 Map<String, String> prefmap = preferredServiceMap.get(afid);
932 if (afid.length() > 0 && prefmap == null)
934 // recover global setting, if any
935 prefmap = preferredServiceMap.get("");
939 serviceurl = prefmap.get(serviceType);
943 Jws2Instance response = null;
944 for (Jws2Instance svc : services)
946 if (svc.serviceType.equals(serviceType))
948 if (serviceurl == null || serviceurl.equals(svc.getHost()))
958 public void setPreferredServiceFor(AlignFrame af, String serviceType,
959 String serviceAction, Jws2Instance selectedServer)
961 String afid = (af == null) ? "" : af.getViewport().getSequenceSetId();
962 if (preferredServiceMap == null)
964 preferredServiceMap = new HashMap<String, Map<String, String>>();
966 Map<String, String> prefmap = preferredServiceMap.get(afid);
969 prefmap = new HashMap<String, String>();
970 preferredServiceMap.put(afid, prefmap);
972 prefmap.put(serviceType, selectedServer.getHost());
973 prefmap.put(serviceAction, selectedServer.getHost());
976 public void setPreferredServiceFor(String serviceType,
977 String serviceAction, Jws2Instance selectedServer)
979 setPreferredServiceFor(null, serviceType, serviceAction, selectedServer);