2 * Jalview - A Sequence Alignment Editor and Viewer (Version 2.8.1)
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 of the License, or (at your option) any later version.
11 * Jalview is distributed in the hope that it will be useful, but
12 * WITHOUT ANY WARRANTY; without even the implied warranty
13 * of MERCHANTABILITY or FITNESS FOR A PARTICULAR
14 * PURPOSE. See the GNU General Public License for more details.
16 * You should have received a copy of the GNU General Public License along with Jalview. If not, see <http://www.gnu.org/licenses/>.
17 * The Jalview Authors are detailed in the 'AUTHORS' file.
19 package jalview.ws.jws2;
21 import jalview.bin.Cache;
22 import jalview.gui.AlignFrame;
23 import jalview.gui.Desktop;
24 import jalview.gui.JvSwingUtils;
25 import jalview.ws.WSMenuEntryProviderI;
26 import jalview.ws.jws2.jabaws2.Jws2Instance;
27 import jalview.ws.params.ParamDatastoreI;
29 import java.awt.Color;
30 import java.awt.event.ActionEvent;
31 import java.awt.event.ActionListener;
32 import java.beans.PropertyChangeEvent;
33 import java.beans.PropertyChangeListener;
35 import java.util.ArrayList;
36 import java.util.Arrays;
37 import java.util.HashMap;
38 import java.util.HashSet;
39 import java.util.Hashtable;
40 import java.util.List;
43 import java.util.StringTokenizer;
44 import java.util.Vector;
46 import javax.swing.JMenu;
47 import javax.swing.JMenuItem;
49 import compbio.ws.client.Services;
52 * discoverer for jws2 services. Follows the lightweight service discoverer
53 * pattern (archetyped by EnfinEnvision2OneWay)
58 public class Jws2Discoverer implements Runnable, WSMenuEntryProviderI
60 private java.beans.PropertyChangeSupport changeSupport = new java.beans.PropertyChangeSupport(
64 * change listeners are notified of "services" property changes
67 * to be added that consumes new services Hashtable object.
69 public void addPropertyChangeListener(
70 java.beans.PropertyChangeListener listener)
72 changeSupport.addPropertyChangeListener(listener);
81 public void removePropertyChangeListener(
82 java.beans.PropertyChangeListener listener)
84 changeSupport.removePropertyChangeListener(listener);
87 boolean running = false, aborted = false;
92 public boolean isAborted()
101 public void setAborted(boolean aborted)
103 this.aborted = aborted;
106 Thread oldthread = null;
111 if (running && oldthread != null && oldthread.isAlive())
122 .debug("Waiting around for old discovery thread to finish.");
123 // wait around until old discoverer dies
125 } catch (Exception e)
129 Cache.log.debug("Old discovery thread has finished.");
133 // first set up exclusion list if needed
134 final Set<String> ignoredServices = new HashSet<String>();
135 for (String ignored:jalview.bin.Cache.getDefault("IGNORED_JABAWS_SERVICETYPES", Services.JpredWS.toString()).split("\\|"))
137 ignoredServices.add(ignored);
141 changeSupport.firePropertyChange("services", services, new Vector());
142 oldthread = Thread.currentThread();
145 Class foo = getClass().getClassLoader().loadClass(
146 "compbio.ws.client.Jws2Client");
147 } catch (ClassNotFoundException e)
150 .println("Not enabling JABA Webservices : client jar is not available."
151 + "\nPlease check that your webstart JNLP file is up to date!");
155 // reinitialise records of good and bad service URLs
156 if (services != null)
158 services.removeAllElements();
160 if (urlsWithoutServices != null)
162 urlsWithoutServices.removeAllElements();
164 if (invalidServiceUrls != null)
166 invalidServiceUrls.removeAllElements();
168 if (validServiceUrls != null)
170 validServiceUrls.removeAllElements();
172 ArrayList<String> svctypes = new ArrayList<String>();
174 List<JabaWsServerQuery> qrys = new ArrayList<JabaWsServerQuery>();
175 for (final String jwsservers : getServiceUrls())
177 JabaWsServerQuery squery = new JabaWsServerQuery(this, jwsservers);
178 if (svctypes.size() == 0)
180 // TODO: remove this ugly hack to get Canonical JABA service ordering
181 // for all possible services
182 for (Services sv : squery.JABAWS2SERVERS)
184 if (!ignoredServices.contains(sv.toString()))
186 svctypes.add(sv.toString());
192 new Thread(squery).start();
194 boolean finished = true;
201 } catch (Exception e)
205 for (JabaWsServerQuery squery : qrys)
207 if (squery.isRunning()){
213 Cache.log.debug("Aborting " + qrys.size()
214 + " JABAWS discovery threads.");
215 for (JabaWsServerQuery squery : qrys)
217 squery.setQuit(true);
220 } while (!aborted && !finished);
223 // resort services according to order found in jabaws service list
224 // also ensure servics for each host are ordered in same way.
226 if (services != null && services.size() > 0)
228 Jws2Instance[] svcs = new Jws2Instance[services.size()];
229 int[] spos = new int[services.size()];
231 Vector svcUrls = getServiceUrls();
232 for (Jws2Instance svc : services)
235 spos[ipos++] = 1000 * svcUrls.indexOf(svc.getHost()) + 1
236 + svctypes.indexOf(svc.serviceType);
238 jalview.util.QuickSort.sort(spos, svcs);
239 services = new Vector<Jws2Instance>();
240 for (Jws2Instance svc : svcs)
242 if (!ignoredServices.contains(svc.serviceType))
251 changeSupport.firePropertyChange("services", new Vector(), services);
255 * record this service endpoint so we can use it
261 synchronized void addService(String jwsservers, Jws2Instance service)
263 if (services == null)
265 services = new Vector<Jws2Instance>();
267 System.out.println("Discovered service: " + jwsservers + " "
268 + service.toString());
269 // Jws2Instance service = new Jws2Instance(jwsservers, srv.toString(),
272 services.add(service);
273 // retrieve the presets and parameter set and cache now
274 ParamDatastoreI pds = service.getParamStore();
279 service.hasParameters();
280 if (validServiceUrls == null)
282 validServiceUrls = new Vector();
284 validServiceUrls.add(jwsservers);
288 * holds list of services.
290 protected Vector<Jws2Instance> services;
293 * attach all available web services to the appropriate submenu in the given
296 public void attachWSMenuEntry(JMenu wsmenu, final AlignFrame alignFrame)
298 // dynamically regenerate service list.
299 populateWSMenuEntry(wsmenu, alignFrame, null);
302 private boolean isRecalculable(String action)
304 return (action != null && action.equalsIgnoreCase("conservation"));
307 private void populateWSMenuEntry(JMenu jws2al,
308 final AlignFrame alignFrame, String typeFilter)
310 if (running || services == null || services.size() == 0)
314 boolean byhost = Cache.getDefault("WSMENU_BYHOST", false), bytype = Cache
315 .getDefault("WSMENU_BYTYPE", false);
317 * eventually, JWS2 services will appear under the same align/etc submenus.
318 * for moment we keep them separate.
321 List<Jws2Instance> enumerableServices = new ArrayList<Jws2Instance>();
322 // jws2al.removeAll();
323 Map<String, Jws2Instance> preferredHosts = new HashMap<String, Jws2Instance>();
324 Map<String, List<Jws2Instance>> alternates = new HashMap<String, List<Jws2Instance>>();
325 for (Jws2Instance service : services.toArray(new Jws2Instance[0]))
327 if (!isRecalculable(service.action))
329 // add 'one shot' services to be displayed using the classic menu
331 enumerableServices.add(service);
335 if (!preferredHosts.containsKey(service.serviceType))
337 Jws2Instance preferredInstance = getPreferredServiceFor(
338 alignFrame, service.serviceType);
339 if (preferredInstance != null)
341 preferredHosts.put(service.serviceType, preferredInstance);
345 preferredHosts.put(service.serviceType, service);
348 List<Jws2Instance> ph = alternates.get(service.serviceType);
349 if (preferredHosts.get(service.serviceType) != service)
353 ph = new ArrayList<Jws2Instance>();
356 alternates.put(service.serviceType, ph);
362 // create GUI element for classic services
363 addEnumeratedServices(jws2al, alignFrame, enumerableServices);
364 // and the instantaneous services
365 for (final Jws2Instance service : preferredHosts.values())
367 atpoint = JvSwingUtils.findOrCreateMenu(jws2al, service.action);
369 if (atpoint.getItemCount() > 1)
371 // previous service of this type already present
372 atpoint.addSeparator();
374 atpoint.add(hitm = new JMenuItem(service.getHost()));
375 hitm.setForeground(Color.blue);
376 hitm.addActionListener(new ActionListener()
380 public void actionPerformed(ActionEvent e)
382 Desktop.showUrl(service.getHost());
385 hitm.setToolTipText(JvSwingUtils
386 .wrapTooltip("Opens the JABAWS server's homepage in web browser"));
388 service.attachWSMenuEntry(atpoint, alignFrame);
389 if (alternates.containsKey(service.serviceType))
391 atpoint.add(hitm = new JMenu("Switch server"));
392 hitm.setToolTipText(JvSwingUtils
393 .wrapTooltip("Choose a server for running this service"));
394 for (final Jws2Instance sv : alternates.get(service.serviceType))
397 hitm.add(itm = new JMenuItem(sv.getHost()));
398 itm.setForeground(Color.blue);
399 itm.addActionListener(new ActionListener()
403 public void actionPerformed(ActionEvent arg0)
405 new Thread(new Runnable()
409 setPreferredServiceFor(alignFrame, sv.serviceType,
411 changeSupport.firePropertyChange("services",
412 new Vector(), services);
420 * hitm.addActionListener(new ActionListener() {
422 * @Override public void actionPerformed(ActionEvent arg0) { new
423 * Thread(new Runnable() {
425 * @Override public void run() { new SetPreferredServer(alignFrame,
426 * service.serviceType, service.action); } }).start(); } });
433 * add services using the Java 2.5/2.6/2.7 system which optionally creates
434 * submenus to index by host and service program type
436 private void addEnumeratedServices(final JMenu jws2al,
437 final AlignFrame alignFrame, List<Jws2Instance> enumerableServices)
439 boolean byhost = Cache.getDefault("WSMENU_BYHOST", false), bytype = Cache
440 .getDefault("WSMENU_BYTYPE", false);
442 * eventually, JWS2 services will appear under the same align/etc submenus.
443 * for moment we keep them separate.
446 MsaWSClient msacl = new MsaWSClient();
447 List<String> hostLabels = new ArrayList<String>();
448 Hashtable<String, String> lasthostFor = new Hashtable<String, String>();
449 Hashtable<String, ArrayList<Jws2Instance>> hosts = new Hashtable<String, ArrayList<Jws2Instance>>();
450 ArrayList<String> hostlist = new ArrayList<String>();
451 for (Jws2Instance service : enumerableServices)
453 ArrayList<Jws2Instance> hostservices = hosts.get(service.getHost());
454 if (hostservices == null)
456 hosts.put(service.getHost(),
457 hostservices = new ArrayList<Jws2Instance>());
458 hostlist.add(service.getHost());
460 hostservices.add(service);
462 // now add hosts in order of the given array
463 for (String host : hostlist)
465 Jws2Instance orderedsvcs[] = hosts.get(host).toArray(
466 new Jws2Instance[1]);
467 String sortbytype[] = new String[orderedsvcs.length];
468 for (int i = 0; i < sortbytype.length; i++)
470 sortbytype[i] = orderedsvcs[i].serviceType;
472 jalview.util.QuickSort.sort(sortbytype, orderedsvcs);
473 for (final Jws2Instance service : orderedsvcs)
475 atpoint = JvSwingUtils.findOrCreateMenu(jws2al, service.action);
476 String type = service.serviceType;
479 atpoint = JvSwingUtils.findOrCreateMenu(atpoint, host);
480 if (atpoint.getToolTipText() == null)
482 atpoint.setToolTipText("Services at " + host);
487 atpoint = JvSwingUtils.findOrCreateMenu(atpoint, type);
488 if (atpoint.getToolTipText() == null)
490 atpoint.setToolTipText(service.getActionText());
494 && !hostLabels.contains(host + service.serviceType
495 + service.getActionText()))
496 // !hostLabels.contains(host + (bytype ?
497 // service.serviceType+service.getActionText() : "")))
499 // add a marker indicating where this service is hosted
500 // relies on services from the same host being listed in a
504 if (hostLabels.contains(host))
506 atpoint.addSeparator();
510 hostLabels.add(host);
512 if (lasthostFor.get(service.action) == null
513 || !lasthostFor.get(service.action).equals(host))
515 atpoint.add(hitm = new JMenuItem(host));
516 hitm.setForeground(Color.blue);
517 hitm.addActionListener(new ActionListener()
521 public void actionPerformed(ActionEvent e)
523 Desktop.showUrl(service.getHost());
526 hitm.setToolTipText(JvSwingUtils
527 .wrapTooltip("Opens the JABAWS server's homepage in web browser"));
528 lasthostFor.put(service.action, host);
530 hostLabels.add(host + service.serviceType
531 + service.getActionText());
534 service.attachWSMenuEntry(atpoint, alignFrame);
539 public static void main(String[] args)
543 testUrls = new Vector<String>();
544 for (String url : args)
550 Thread runner = getDiscoverer().startDiscoverer(
551 new PropertyChangeListener()
554 public void propertyChange(PropertyChangeEvent evt)
556 if (getDiscoverer().services != null)
558 System.out.println("Changesupport: There are now "
559 + getDiscoverer().services.size() + " services");
561 for (Jws2Instance instance : getDiscoverer().services)
563 System.out.println("Service " + i++ + " "
564 + instance.getClass() + "@"
565 + instance.getHost() + ": "
566 + instance.getActionText());
572 while (runner.isAlive())
577 } catch (InterruptedException e)
585 } catch (InterruptedException x)
590 private static Jws2Discoverer discoverer;
592 public static Jws2Discoverer getDiscoverer()
594 if (discoverer == null)
596 discoverer = new Jws2Discoverer();
601 public boolean hasServices()
603 // TODO Auto-generated method stub
604 return !running && services != null && services.size() > 0;
607 public boolean isRunning()
613 * the jalview .properties entry for JWS2 URLS
615 final static String JWS2HOSTURLS = "JWS2HOSTURLS";
617 public static void setServiceUrls(Vector<String> urls)
621 StringBuffer urlbuffer = new StringBuffer();
623 for (String url : urls)
625 urlbuffer.append(sep);
626 urlbuffer.append(url);
629 Cache.setProperty(JWS2HOSTURLS, urlbuffer.toString());
633 Cache.removeProperty(JWS2HOSTURLS);
637 private static Vector<String> testUrls = null;
639 public static Vector<String> getServiceUrls()
641 if (testUrls != null)
643 // return test urls, if there are any, instead of touching cache
646 String surls = Cache.getDefault(JWS2HOSTURLS,
647 "http://www.compbio.dundee.ac.uk/jabaws");
648 Vector<String> urls = new Vector<String>();
651 StringTokenizer st = new StringTokenizer(surls, ",");
652 while (st.hasMoreElements())
657 java.net.URL u = new java.net.URL(url = st.nextToken());
658 if (!urls.contains(url))
664 jalview.bin.Cache.log.info("Ignoring duplicate url in "
665 + JWS2HOSTURLS + " list");
667 } catch (Exception ex)
669 jalview.bin.Cache.log
670 .warn("Problem whilst trying to make a URL from '"
671 + ((url != null) ? url : "<null>") + "'");
672 jalview.bin.Cache.log
673 .warn("This was probably due to a malformed comma separated list"
676 + " entry of $(HOME)/.jalview_properties)");
677 jalview.bin.Cache.log.debug("Exception was ", ex);
680 } catch (Exception ex)
682 jalview.bin.Cache.log.warn(
683 "Error parsing comma separated list of urls in "
684 + JWS2HOSTURLS + " preference.", ex);
686 if (urls.size() >= 0)
693 public Vector<Jws2Instance> getServices()
695 return (services == null) ? new Vector<Jws2Instance>()
696 : new Vector<Jws2Instance>(services);
700 * test the given URL with the JabaWS test code
705 public static boolean testServiceUrl(URL foo)
709 compbio.ws.client.WSTester.main(new String[]
710 { "-h=" + foo.toString() });
711 } catch (Exception e)
715 } catch (OutOfMemoryError e)
729 * Start a fresh discovery thread and notify the given object when we're
730 * finished. Any known existing threads will be killed before this one is
733 * @param changeSupport2
736 public Thread startDiscoverer(PropertyChangeListener changeSupport2)
742 addPropertyChangeListener(changeSupport2);
743 Thread thr = new Thread(this);
748 Vector<String> invalidServiceUrls = null, urlsWithoutServices = null,
749 validServiceUrls = null;
752 * @return the invalidServiceUrls
754 public Vector<String> getInvalidServiceUrls()
756 return invalidServiceUrls;
760 * @return the urlsWithoutServices
762 public Vector<String> getUrlsWithoutServices()
764 return urlsWithoutServices;
768 * add an 'empty' JABA server to the list. Only servers not already in the
769 * 'bad URL' list will be added to this list.
773 public synchronized void addUrlwithnoservices(String jwsservers)
775 if (urlsWithoutServices == null)
777 urlsWithoutServices = new Vector<String>();
780 if ((invalidServiceUrls == null || !invalidServiceUrls
781 .contains(jwsservers))
782 && !urlsWithoutServices.contains(jwsservers))
784 urlsWithoutServices.add(jwsservers);
789 * add a bad URL to the list
793 public synchronized void addInvalidServiceUrl(String jwsservers)
795 if (invalidServiceUrls == null)
797 invalidServiceUrls = new Vector<String>();
799 if (!invalidServiceUrls.contains(jwsservers))
801 invalidServiceUrls.add(jwsservers);
807 * @return a human readable report of any problems with the service URLs used
810 public String getErrorMessages()
812 if (!isRunning() && !isAborted())
814 StringBuffer ermsg = new StringBuffer();
815 boolean list = false;
816 if (getInvalidServiceUrls() != null
817 && getInvalidServiceUrls().size() > 0)
819 ermsg.append("URLs that could not be contacted: \n");
820 for (String svcurl : getInvalidServiceUrls())
827 ermsg.append(svcurl);
829 ermsg.append("\n\n");
832 if (getUrlsWithoutServices() != null
833 && getUrlsWithoutServices().size() > 0)
835 ermsg.append("URLs without any JABA Services : \n");
836 for (String svcurl : getUrlsWithoutServices())
843 ermsg.append(svcurl);
847 if (ermsg.length() > 1)
849 return ermsg.toString();
856 public int getServerStatusFor(String url)
858 if (validServiceUrls != null && validServiceUrls.contains(url))
862 if (urlsWithoutServices != null && urlsWithoutServices.contains(url))
864 if (invalidServiceUrls != null && invalidServiceUrls.contains(url))
872 * pick the user's preferred service based on a set of URLs (jaba server
873 * locations) and service URIs (specifying version and service interface
877 * @return null or best match for given uri/ls.
879 public Jws2Instance getPreferredServiceFor(String[] serviceURLs)
881 HashSet<String> urls = new HashSet<String>();
882 urls.addAll(Arrays.asList(serviceURLs));
883 Jws2Instance match = null;
884 if (services != null)
886 for (Jws2Instance svc : services)
888 if (urls.contains(svc.getServiceTypeURI()))
892 // for moment we always pick service from server ordered first in
893 // user's preferences
896 if (urls.contains(svc.getUri()))
898 // stop and return - we've matched type URI and URI for service
908 Map<String, Map<String, String>> preferredServiceMap = new HashMap<String, Map<String, String>>();;
911 * get current preferred service of the given type, or global default
914 * null or a specific alignFrame
916 * Jws2Instance.serviceType for service
917 * @return null if no service of this type is available, the preferred service
918 * for the serviceType and af if specified and if defined.
920 public Jws2Instance getPreferredServiceFor(AlignFrame af,
923 String serviceurl = null;
924 synchronized (preferredServiceMap)
926 String afid = (af == null) ? "" : af.getViewport().getSequenceSetId();
927 Map<String, String> prefmap = preferredServiceMap.get(afid);
928 if (afid.length() > 0 && prefmap == null)
930 // recover global setting, if any
931 prefmap = preferredServiceMap.get("");
935 serviceurl = prefmap.get(serviceType);
939 Jws2Instance response = null;
940 for (Jws2Instance svc : services)
942 if (svc.serviceType.equals(serviceType))
944 if (serviceurl == null || serviceurl.equals(svc.getHost()))
954 public void setPreferredServiceFor(AlignFrame af, String serviceType,
955 String serviceAction, Jws2Instance selectedServer)
957 String afid = (af == null) ? "" : af.getViewport().getSequenceSetId();
958 if (preferredServiceMap == null)
960 preferredServiceMap = new HashMap<String, Map<String, String>>();
962 Map<String, String> prefmap = preferredServiceMap.get(afid);
965 prefmap = new HashMap<String, String>();
966 preferredServiceMap.put(afid, prefmap);
968 prefmap.put(serviceType, selectedServer.getHost());
969 prefmap.put(serviceAction, selectedServer.getHost());
972 public void setPreferredServiceFor(String serviceType,
973 String serviceAction, Jws2Instance selectedServer)
975 setPreferredServiceFor(null, serviceType, serviceAction, selectedServer);