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("IGNORED_JABAWS_SERVICETYPES", Services.JpredWS.toString()).split("\\|"))
139 ignoredServices.add(ignored);
143 changeSupport.firePropertyChange("services", services, new Vector());
144 oldthread = Thread.currentThread();
147 Class foo = getClass().getClassLoader().loadClass(
148 "compbio.ws.client.Jws2Client");
149 } catch (ClassNotFoundException e)
152 .println("Not enabling JABA Webservices : client jar is not available."
153 + "\nPlease check that your webstart JNLP file is up to date!");
157 // reinitialise records of good and bad service URLs
158 if (services != null)
160 services.removeAllElements();
162 if (urlsWithoutServices != null)
164 urlsWithoutServices.removeAllElements();
166 if (invalidServiceUrls != null)
168 invalidServiceUrls.removeAllElements();
170 if (validServiceUrls != null)
172 validServiceUrls.removeAllElements();
174 ArrayList<String> svctypes = new ArrayList<String>();
176 List<JabaWsServerQuery> qrys = new ArrayList<JabaWsServerQuery>();
177 for (final String jwsservers : getServiceUrls())
179 JabaWsServerQuery squery = new JabaWsServerQuery(this, jwsservers);
180 if (svctypes.size() == 0)
182 // TODO: remove this ugly hack to get Canonical JABA service ordering
183 // for all possible services
184 for (Services sv : squery.JABAWS2SERVERS)
186 if (!ignoredServices.contains(sv.toString()))
188 svctypes.add(sv.toString());
194 new Thread(squery).start();
196 boolean finished = true;
203 } catch (Exception e)
207 for (JabaWsServerQuery squery : qrys)
209 if (squery.isRunning()){
215 Cache.log.debug("Aborting " + qrys.size()
216 + " JABAWS discovery threads.");
217 for (JabaWsServerQuery squery : qrys)
219 squery.setQuit(true);
222 } while (!aborted && !finished);
225 // resort services according to order found in jabaws service list
226 // also ensure servics for each host are ordered in same way.
228 if (services != null && services.size() > 0)
230 Jws2Instance[] svcs = new Jws2Instance[services.size()];
231 int[] spos = new int[services.size()];
233 Vector svcUrls = getServiceUrls();
234 for (Jws2Instance svc : services)
237 spos[ipos++] = 1000 * svcUrls.indexOf(svc.getHost()) + 1
238 + svctypes.indexOf(svc.serviceType);
240 jalview.util.QuickSort.sort(spos, svcs);
241 services = new Vector<Jws2Instance>();
242 for (Jws2Instance svc : svcs)
244 if (!ignoredServices.contains(svc.serviceType))
253 changeSupport.firePropertyChange("services", new Vector(), services);
257 * record this service endpoint so we can use it
263 synchronized void addService(String jwsservers, Jws2Instance service)
265 if (services == null)
267 services = new Vector<Jws2Instance>();
269 System.out.println("Discovered service: " + jwsservers + " "
270 + service.toString());
271 // Jws2Instance service = new Jws2Instance(jwsservers, srv.toString(),
274 services.add(service);
275 // retrieve the presets and parameter set and cache now
276 ParamDatastoreI pds = service.getParamStore();
281 service.hasParameters();
282 if (validServiceUrls == null)
284 validServiceUrls = new Vector();
286 validServiceUrls.add(jwsservers);
290 * holds list of services.
292 protected Vector<Jws2Instance> services;
295 * attach all available web services to the appropriate submenu in the given
298 public void attachWSMenuEntry(JMenu wsmenu, final AlignFrame alignFrame)
300 // dynamically regenerate service list.
301 populateWSMenuEntry(wsmenu, alignFrame, null);
304 private boolean isRecalculable(String action)
306 return (action != null && action.equalsIgnoreCase("conservation"));
309 private void populateWSMenuEntry(JMenu jws2al,
310 final AlignFrame alignFrame, String typeFilter)
312 if (running || services == null || services.size() == 0)
316 boolean byhost = Cache.getDefault("WSMENU_BYHOST", false), bytype = Cache
317 .getDefault("WSMENU_BYTYPE", false);
319 * eventually, JWS2 services will appear under the same align/etc submenus.
320 * for moment we keep them separate.
323 List<Jws2Instance> enumerableServices = new ArrayList<Jws2Instance>();
324 // jws2al.removeAll();
325 Map<String, Jws2Instance> preferredHosts = new HashMap<String, Jws2Instance>();
326 Map<String, List<Jws2Instance>> alternates = new HashMap<String, List<Jws2Instance>>();
327 for (Jws2Instance service : services.toArray(new Jws2Instance[0]))
329 if (!isRecalculable(service.action))
331 // add 'one shot' services to be displayed using the classic menu
333 enumerableServices.add(service);
337 if (!preferredHosts.containsKey(service.serviceType))
339 Jws2Instance preferredInstance = getPreferredServiceFor(
340 alignFrame, service.serviceType);
341 if (preferredInstance != null)
343 preferredHosts.put(service.serviceType, preferredInstance);
347 preferredHosts.put(service.serviceType, service);
350 List<Jws2Instance> ph = alternates.get(service.serviceType);
351 if (preferredHosts.get(service.serviceType) != service)
355 ph = new ArrayList<Jws2Instance>();
358 alternates.put(service.serviceType, ph);
364 // create GUI element for classic services
365 addEnumeratedServices(jws2al, alignFrame, enumerableServices);
366 // and the instantaneous services
367 for (final Jws2Instance service : preferredHosts.values())
369 atpoint = JvSwingUtils.findOrCreateMenu(jws2al, service.action);
371 if (atpoint.getItemCount() > 1)
373 // previous service of this type already present
374 atpoint.addSeparator();
376 atpoint.add(hitm = new JMenuItem(service.getHost()));
377 hitm.setForeground(Color.blue);
378 hitm.addActionListener(new ActionListener()
382 public void actionPerformed(ActionEvent e)
384 Desktop.showUrl(service.getHost());
387 hitm.setToolTipText(JvSwingUtils
388 .wrapTooltip("Opens the JABAWS server's homepage in web browser"));
390 service.attachWSMenuEntry(atpoint, alignFrame);
391 if (alternates.containsKey(service.serviceType))
393 atpoint.add(hitm = new JMenu("Switch server"));
394 hitm.setToolTipText(JvSwingUtils
395 .wrapTooltip("Choose a server for running this service"));
396 for (final Jws2Instance sv : alternates.get(service.serviceType))
399 hitm.add(itm = new JMenuItem(sv.getHost()));
400 itm.setForeground(Color.blue);
401 itm.addActionListener(new ActionListener()
405 public void actionPerformed(ActionEvent arg0)
407 new Thread(new Runnable()
411 setPreferredServiceFor(alignFrame, sv.serviceType,
413 changeSupport.firePropertyChange("services",
414 new Vector(), services);
422 * hitm.addActionListener(new ActionListener() {
424 * @Override public void actionPerformed(ActionEvent arg0) { new
425 * Thread(new Runnable() {
427 * @Override public void run() { new SetPreferredServer(alignFrame,
428 * service.serviceType, service.action); } }).start(); } });
435 * add services using the Java 2.5/2.6/2.7 system which optionally creates
436 * submenus to index by host and service program type
438 private void addEnumeratedServices(final JMenu jws2al,
439 final AlignFrame alignFrame, List<Jws2Instance> enumerableServices)
441 boolean byhost = Cache.getDefault("WSMENU_BYHOST", false), bytype = Cache
442 .getDefault("WSMENU_BYTYPE", false);
444 * eventually, JWS2 services will appear under the same align/etc submenus.
445 * for moment we keep them separate.
448 MsaWSClient msacl = new MsaWSClient();
449 List<String> hostLabels = new ArrayList<String>();
450 Hashtable<String, String> lasthostFor = new Hashtable<String, String>();
451 Hashtable<String, ArrayList<Jws2Instance>> hosts = new Hashtable<String, ArrayList<Jws2Instance>>();
452 ArrayList<String> hostlist = new ArrayList<String>();
453 for (Jws2Instance service : enumerableServices)
455 ArrayList<Jws2Instance> hostservices = hosts.get(service.getHost());
456 if (hostservices == null)
458 hosts.put(service.getHost(),
459 hostservices = new ArrayList<Jws2Instance>());
460 hostlist.add(service.getHost());
462 hostservices.add(service);
464 // now add hosts in order of the given array
465 for (String host : hostlist)
467 Jws2Instance orderedsvcs[] = hosts.get(host).toArray(
468 new Jws2Instance[1]);
469 String sortbytype[] = new String[orderedsvcs.length];
470 for (int i = 0; i < sortbytype.length; i++)
472 sortbytype[i] = orderedsvcs[i].serviceType;
474 jalview.util.QuickSort.sort(sortbytype, orderedsvcs);
475 for (final Jws2Instance service : orderedsvcs)
477 atpoint = JvSwingUtils.findOrCreateMenu(jws2al, service.action);
478 String type = service.serviceType;
481 atpoint = JvSwingUtils.findOrCreateMenu(atpoint, host);
482 if (atpoint.getToolTipText() == null)
484 atpoint.setToolTipText("Services at " + host);
489 atpoint = JvSwingUtils.findOrCreateMenu(atpoint, type);
490 if (atpoint.getToolTipText() == null)
492 atpoint.setToolTipText(service.getActionText());
496 && !hostLabels.contains(host + service.serviceType
497 + service.getActionText()))
498 // !hostLabels.contains(host + (bytype ?
499 // service.serviceType+service.getActionText() : "")))
501 // add a marker indicating where this service is hosted
502 // relies on services from the same host being listed in a
506 if (hostLabels.contains(host))
508 atpoint.addSeparator();
512 hostLabels.add(host);
514 if (lasthostFor.get(service.action) == null
515 || !lasthostFor.get(service.action).equals(host))
517 atpoint.add(hitm = new JMenuItem(host));
518 hitm.setForeground(Color.blue);
519 hitm.addActionListener(new ActionListener()
523 public void actionPerformed(ActionEvent e)
525 Desktop.showUrl(service.getHost());
528 hitm.setToolTipText(JvSwingUtils
529 .wrapTooltip("Opens the JABAWS server's homepage in web browser"));
530 lasthostFor.put(service.action, host);
532 hostLabels.add(host + service.serviceType
533 + service.getActionText());
536 service.attachWSMenuEntry(atpoint, alignFrame);
541 public static void main(String[] args)
545 testUrls = new Vector<String>();
546 for (String url : args)
552 Thread runner = getDiscoverer().startDiscoverer(
553 new PropertyChangeListener()
556 public void propertyChange(PropertyChangeEvent evt)
558 if (getDiscoverer().services != null)
560 System.out.println("Changesupport: There are now "
561 + getDiscoverer().services.size() + " services");
563 for (Jws2Instance instance : getDiscoverer().services)
565 System.out.println("Service " + i++ + " "
566 + instance.getClass() + "@"
567 + instance.getHost() + ": "
568 + instance.getActionText());
574 while (runner.isAlive())
579 } catch (InterruptedException e)
587 } catch (InterruptedException x)
592 private static Jws2Discoverer discoverer;
594 public static Jws2Discoverer getDiscoverer()
596 if (discoverer == null)
598 discoverer = new Jws2Discoverer();
603 public boolean hasServices()
605 // TODO Auto-generated method stub
606 return !running && services != null && services.size() > 0;
609 public boolean isRunning()
615 * the jalview .properties entry for JWS2 URLS
617 final static String JWS2HOSTURLS = "JWS2HOSTURLS";
619 public static void setServiceUrls(Vector<String> urls)
623 StringBuffer urlbuffer = new StringBuffer();
625 for (String url : urls)
627 urlbuffer.append(sep);
628 urlbuffer.append(url);
631 Cache.setProperty(JWS2HOSTURLS, urlbuffer.toString());
635 Cache.removeProperty(JWS2HOSTURLS);
639 private static Vector<String> testUrls = null;
641 public static Vector<String> getServiceUrls()
643 if (testUrls != null)
645 // return test urls, if there are any, instead of touching cache
648 String surls = Cache.getDefault(JWS2HOSTURLS,
649 "http://www.compbio.dundee.ac.uk/jabaws");
650 Vector<String> urls = new Vector<String>();
653 StringTokenizer st = new StringTokenizer(surls, ",");
654 while (st.hasMoreElements())
659 java.net.URL u = new java.net.URL(url = st.nextToken());
660 if (!urls.contains(url))
666 jalview.bin.Cache.log.info("Ignoring duplicate url in "
667 + JWS2HOSTURLS + " list");
669 } catch (Exception ex)
671 jalview.bin.Cache.log
672 .warn("Problem whilst trying to make a URL from '"
673 + ((url != null) ? url : "<null>") + "'");
674 jalview.bin.Cache.log
675 .warn("This was probably due to a malformed comma separated list"
678 + " entry of $(HOME)/.jalview_properties)");
679 jalview.bin.Cache.log.debug("Exception was ", ex);
682 } catch (Exception ex)
684 jalview.bin.Cache.log.warn(
685 "Error parsing comma separated list of urls in "
686 + JWS2HOSTURLS + " preference.", ex);
688 if (urls.size() >= 0)
695 public Vector<Jws2Instance> getServices()
697 return (services == null) ? new Vector<Jws2Instance>()
698 : new Vector<Jws2Instance>(services);
702 * test the given URL with the JabaWS test code
707 public static boolean testServiceUrl(URL foo)
711 compbio.ws.client.WSTester.main(new String[]
712 { "-h=" + foo.toString() });
713 } catch (Exception e)
717 } catch (OutOfMemoryError e)
731 * Start a fresh discovery thread and notify the given object when we're
732 * finished. Any known existing threads will be killed before this one is
735 * @param changeSupport2
738 public Thread startDiscoverer(PropertyChangeListener changeSupport2)
744 addPropertyChangeListener(changeSupport2);
745 Thread thr = new Thread(this);
750 Vector<String> invalidServiceUrls = null, urlsWithoutServices = null,
751 validServiceUrls = null;
754 * @return the invalidServiceUrls
756 public Vector<String> getInvalidServiceUrls()
758 return invalidServiceUrls;
762 * @return the urlsWithoutServices
764 public Vector<String> getUrlsWithoutServices()
766 return urlsWithoutServices;
770 * add an 'empty' JABA server to the list. Only servers not already in the
771 * 'bad URL' list will be added to this list.
775 public synchronized void addUrlwithnoservices(String jwsservers)
777 if (urlsWithoutServices == null)
779 urlsWithoutServices = new Vector<String>();
782 if ((invalidServiceUrls == null || !invalidServiceUrls
783 .contains(jwsservers))
784 && !urlsWithoutServices.contains(jwsservers))
786 urlsWithoutServices.add(jwsservers);
791 * add a bad URL to the list
795 public synchronized void addInvalidServiceUrl(String jwsservers)
797 if (invalidServiceUrls == null)
799 invalidServiceUrls = new Vector<String>();
801 if (!invalidServiceUrls.contains(jwsservers))
803 invalidServiceUrls.add(jwsservers);
809 * @return a human readable report of any problems with the service URLs used
812 public String getErrorMessages()
814 if (!isRunning() && !isAborted())
816 StringBuffer ermsg = new StringBuffer();
817 boolean list = false;
818 if (getInvalidServiceUrls() != null
819 && getInvalidServiceUrls().size() > 0)
821 ermsg.append("URLs that could not be contacted: \n");
822 for (String svcurl : getInvalidServiceUrls())
829 ermsg.append(svcurl);
831 ermsg.append("\n\n");
834 if (getUrlsWithoutServices() != null
835 && getUrlsWithoutServices().size() > 0)
837 ermsg.append("URLs without any JABA Services : \n");
838 for (String svcurl : getUrlsWithoutServices())
845 ermsg.append(svcurl);
849 if (ermsg.length() > 1)
851 return ermsg.toString();
858 public int getServerStatusFor(String url)
860 if (validServiceUrls != null && validServiceUrls.contains(url))
864 if (urlsWithoutServices != null && urlsWithoutServices.contains(url))
866 if (invalidServiceUrls != null && invalidServiceUrls.contains(url))
874 * pick the user's preferred service based on a set of URLs (jaba server
875 * locations) and service URIs (specifying version and service interface
879 * @return null or best match for given uri/ls.
881 public Jws2Instance getPreferredServiceFor(String[] serviceURLs)
883 HashSet<String> urls = new HashSet<String>();
884 urls.addAll(Arrays.asList(serviceURLs));
885 Jws2Instance match = null;
886 if (services != null)
888 for (Jws2Instance svc : services)
890 if (urls.contains(svc.getServiceTypeURI()))
894 // for moment we always pick service from server ordered first in
895 // user's preferences
898 if (urls.contains(svc.getUri()))
900 // stop and return - we've matched type URI and URI for service
910 Map<String, Map<String, String>> preferredServiceMap = new HashMap<String, Map<String, String>>();;
913 * get current preferred service of the given type, or global default
916 * null or a specific alignFrame
918 * Jws2Instance.serviceType for service
919 * @return null if no service of this type is available, the preferred service
920 * for the serviceType and af if specified and if defined.
922 public Jws2Instance getPreferredServiceFor(AlignFrame af,
925 String serviceurl = null;
926 synchronized (preferredServiceMap)
928 String afid = (af == null) ? "" : af.getViewport().getSequenceSetId();
929 Map<String, String> prefmap = preferredServiceMap.get(afid);
930 if (afid.length() > 0 && prefmap == null)
932 // recover global setting, if any
933 prefmap = preferredServiceMap.get("");
937 serviceurl = prefmap.get(serviceType);
941 Jws2Instance response = null;
942 for (Jws2Instance svc : services)
944 if (svc.serviceType.equals(serviceType))
946 if (serviceurl == null || serviceurl.equals(svc.getHost()))
956 public void setPreferredServiceFor(AlignFrame af, String serviceType,
957 String serviceAction, Jws2Instance selectedServer)
959 String afid = (af == null) ? "" : af.getViewport().getSequenceSetId();
960 if (preferredServiceMap == null)
962 preferredServiceMap = new HashMap<String, Map<String, String>>();
964 Map<String, String> prefmap = preferredServiceMap.get(afid);
967 prefmap = new HashMap<String, String>();
968 preferredServiceMap.put(afid, prefmap);
970 prefmap.put(serviceType, selectedServer.getHost());
971 prefmap.put(serviceAction, selectedServer.getHost());
974 public void setPreferredServiceFor(String serviceType,
975 String serviceAction, Jws2Instance selectedServer)
977 setPreferredServiceFor(null, serviceType, serviceAction, selectedServer);