2 * Jalview - A Sequence Alignment Editor and Viewer (Version 2.8)
3 * Copyright (C) 2012 J Procter, AM Waterhouse, LM Lui, J Engelhardt, G Barton, M Clamp, S Searle
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/>.
18 package jalview.ws.jws2;
20 import jalview.bin.Cache;
21 import jalview.gui.AlignFrame;
22 import jalview.gui.Desktop;
23 import jalview.gui.JvSwingUtils;
24 import jalview.ws.WSMenuEntryProviderI;
25 import jalview.ws.jws2.jabaws2.Jws2Instance;
26 import jalview.ws.params.ParamDatastoreI;
28 import java.awt.Color;
29 import java.awt.event.ActionEvent;
30 import java.awt.event.ActionListener;
31 import java.beans.PropertyChangeEvent;
32 import java.beans.PropertyChangeListener;
34 import java.util.ArrayList;
35 import java.util.Arrays;
36 import java.util.HashMap;
37 import java.util.HashSet;
38 import java.util.Hashtable;
39 import java.util.List;
41 import java.util.StringTokenizer;
42 import java.util.Vector;
44 import javax.swing.JMenu;
45 import javax.swing.JMenuItem;
47 import compbio.ws.client.Services;
50 * discoverer for jws2 services. Follows the lightweight service discoverer
51 * pattern (archetyped by EnfinEnvision2OneWay)
56 public class Jws2Discoverer implements Runnable, WSMenuEntryProviderI
58 private java.beans.PropertyChangeSupport changeSupport = new java.beans.PropertyChangeSupport(
62 * change listeners are notified of "services" property changes
65 * to be added that consumes new services Hashtable object.
67 public void addPropertyChangeListener(
68 java.beans.PropertyChangeListener listener)
70 changeSupport.addPropertyChangeListener(listener);
79 public void removePropertyChangeListener(
80 java.beans.PropertyChangeListener listener)
82 changeSupport.removePropertyChangeListener(listener);
85 boolean running = false, aborted = false;
90 public boolean isAborted()
99 public void setAborted(boolean aborted)
101 this.aborted = aborted;
104 Thread oldthread = null;
108 if (running && oldthread != null && oldthread.isAlive())
119 .debug("Waiting around for old discovery thread to finish.");
120 // wait around until old discoverer dies
122 } catch (Exception e)
126 Cache.log.debug("Old discovery thread has finished.");
129 changeSupport.firePropertyChange("services", services, new Vector());
130 oldthread = Thread.currentThread();
133 Class foo = getClass().getClassLoader().loadClass(
134 "compbio.ws.client.Jws2Client");
135 } catch (ClassNotFoundException e)
138 .println("Not enabling JABA Webservices : client jar is not available."
139 + "\nPlease check that your webstart JNLP file is up to date!");
143 // reinitialise records of good and bad service URLs
144 if (services != null)
146 services.removeAllElements();
148 if (urlsWithoutServices != null)
150 urlsWithoutServices.removeAllElements();
152 if (invalidServiceUrls != null)
154 invalidServiceUrls.removeAllElements();
156 if (validServiceUrls != null)
158 validServiceUrls.removeAllElements();
160 ArrayList<String> svctypes = new ArrayList<String>();
162 List<JabaWsServerQuery> qrys = new ArrayList<JabaWsServerQuery>();
163 for (final String jwsservers : getServiceUrls())
165 JabaWsServerQuery squery = new JabaWsServerQuery(this, jwsservers);
166 if (svctypes.size() == 0)
168 // TODO: remove this ugly hack to get Canonical JABA service ordering
169 // for all possible services
170 for (Services sv : squery.JABAWS2SERVERS)
172 svctypes.add(sv.toString());
177 new Thread(squery).start();
179 boolean finished = true;
186 } catch (Exception e)
190 for (JabaWsServerQuery squery : qrys)
192 if (squery.isRunning()){
198 Cache.log.debug("Aborting " + qrys.size()
199 + " JABAWS discovery threads.");
200 for (JabaWsServerQuery squery : qrys)
202 squery.setQuit(true);
205 } while (!aborted && !finished);
208 // resort services according to order found in jabaws service list
209 // also ensure servics for each host are ordered in same way.
211 if (services != null && services.size() > 0)
213 Jws2Instance[] svcs = new Jws2Instance[services.size()];
214 int[] spos = new int[services.size()];
216 Vector svcUrls = getServiceUrls();
217 for (Jws2Instance svc : services)
220 spos[ipos++] = 1000 * svcUrls.indexOf(svc.getHost()) + 1
221 + svctypes.indexOf(svc.serviceType);
223 jalview.util.QuickSort.sort(spos, svcs);
224 services = new Vector<Jws2Instance>();
225 for (Jws2Instance svc : svcs)
233 changeSupport.firePropertyChange("services", new Vector(), services);
237 * record this service endpoint so we can use it
243 synchronized void addService(String jwsservers, Jws2Instance service)
245 if (services == null)
247 services = new Vector<Jws2Instance>();
249 System.out.println("Discovered service: " + jwsservers + " "
250 + service.toString());
251 // Jws2Instance service = new Jws2Instance(jwsservers, srv.toString(),
254 services.add(service);
255 // retrieve the presets and parameter set and cache now
256 ParamDatastoreI pds = service.getParamStore();
261 service.hasParameters();
262 if (validServiceUrls == null)
264 validServiceUrls = new Vector();
266 validServiceUrls.add(jwsservers);
270 * holds list of services.
272 protected Vector<Jws2Instance> services;
275 * attach all available web services to the appropriate submenu in the given
278 public void attachWSMenuEntry(JMenu wsmenu, final AlignFrame alignFrame)
280 // dynamically regenerate service list.
281 populateWSMenuEntry(wsmenu, alignFrame, null);
284 private boolean isRecalculable(String action)
286 return (action != null && action.equalsIgnoreCase("conservation"));
289 private void populateWSMenuEntry(JMenu jws2al,
290 final AlignFrame alignFrame, String typeFilter)
292 if (running || services == null || services.size() == 0)
296 boolean byhost = Cache.getDefault("WSMENU_BYHOST", false), bytype = Cache
297 .getDefault("WSMENU_BYTYPE", false);
299 * eventually, JWS2 services will appear under the same align/etc submenus.
300 * for moment we keep them separate.
303 List<Jws2Instance> enumerableServices = new ArrayList<Jws2Instance>();
304 // jws2al.removeAll();
305 Map<String, Jws2Instance> preferredHosts = new HashMap<String, Jws2Instance>();
306 Map<String, List<Jws2Instance>> alternates = new HashMap<String, List<Jws2Instance>>();
307 for (Jws2Instance service : services.toArray(new Jws2Instance[0]))
309 if (!isRecalculable(service.action))
311 // add 'one shot' services to be displayed using the classic menu
313 enumerableServices.add(service);
317 if (!preferredHosts.containsKey(service.serviceType))
319 Jws2Instance preferredInstance = getPreferredServiceFor(
320 alignFrame, service.serviceType);
321 if (preferredInstance != null)
323 preferredHosts.put(service.serviceType, preferredInstance);
327 preferredHosts.put(service.serviceType, service);
330 List<Jws2Instance> ph = alternates.get(service.serviceType);
331 if (preferredHosts.get(service.serviceType) != service)
335 ph = new ArrayList<Jws2Instance>();
338 alternates.put(service.serviceType, ph);
344 // create GUI element for classic services
345 addEnumeratedServices(jws2al, alignFrame, enumerableServices);
346 // and the instantaneous services
347 for (final Jws2Instance service : preferredHosts.values())
349 atpoint = JvSwingUtils.findOrCreateMenu(jws2al, service.action);
351 if (atpoint.getItemCount() > 1)
353 // previous service of this type already present
354 atpoint.addSeparator();
356 atpoint.add(hitm = new JMenuItem(service.getHost()));
357 hitm.setForeground(Color.blue);
358 hitm.addActionListener(new ActionListener()
362 public void actionPerformed(ActionEvent e)
364 Desktop.showUrl(service.getHost());
367 hitm.setToolTipText(JvSwingUtils
368 .wrapTooltip("Opens the JABAWS server's homepage in web browser"));
370 service.attachWSMenuEntry(atpoint, alignFrame);
371 if (alternates.containsKey(service.serviceType))
373 atpoint.add(hitm = new JMenu("Switch server"));
374 hitm.setToolTipText(JvSwingUtils
375 .wrapTooltip("Choose a server for running this service"));
376 for (final Jws2Instance sv : alternates.get(service.serviceType))
379 hitm.add(itm = new JMenuItem(sv.getHost()));
380 itm.setForeground(Color.blue);
381 itm.addActionListener(new ActionListener()
385 public void actionPerformed(ActionEvent arg0)
387 new Thread(new Runnable()
391 setPreferredServiceFor(alignFrame, sv.serviceType,
393 changeSupport.firePropertyChange("services",
394 new Vector(), services);
402 * hitm.addActionListener(new ActionListener() {
404 * @Override public void actionPerformed(ActionEvent arg0) { new
405 * Thread(new Runnable() {
407 * @Override public void run() { new SetPreferredServer(alignFrame,
408 * service.serviceType, service.action); } }).start(); } });
415 * add services using the Java 2.5/2.6/2.7 system which optionally creates
416 * submenus to index by host and service program type
418 private void addEnumeratedServices(final JMenu jws2al,
419 final AlignFrame alignFrame, List<Jws2Instance> enumerableServices)
421 boolean byhost = Cache.getDefault("WSMENU_BYHOST", false), bytype = Cache
422 .getDefault("WSMENU_BYTYPE", false);
424 * eventually, JWS2 services will appear under the same align/etc submenus.
425 * for moment we keep them separate.
428 MsaWSClient msacl = new MsaWSClient();
429 List<String> hostLabels = new ArrayList<String>();
430 Hashtable<String, String> lasthostFor = new Hashtable<String, String>();
431 Hashtable<String, ArrayList<Jws2Instance>> hosts = new Hashtable<String, ArrayList<Jws2Instance>>();
432 ArrayList<String> hostlist = new ArrayList<String>();
433 for (Jws2Instance service : enumerableServices)
435 ArrayList<Jws2Instance> hostservices = hosts.get(service.getHost());
436 if (hostservices == null)
438 hosts.put(service.getHost(),
439 hostservices = new ArrayList<Jws2Instance>());
440 hostlist.add(service.getHost());
442 hostservices.add(service);
444 // now add hosts in order of the given array
445 for (String host : hostlist)
447 Jws2Instance orderedsvcs[] = hosts.get(host).toArray(
448 new Jws2Instance[1]);
449 String sortbytype[] = new String[orderedsvcs.length];
450 for (int i = 0; i < sortbytype.length; i++)
452 sortbytype[i] = orderedsvcs[i].serviceType;
454 jalview.util.QuickSort.sort(sortbytype, orderedsvcs);
455 for (final Jws2Instance service : orderedsvcs)
457 atpoint = JvSwingUtils.findOrCreateMenu(jws2al, service.action);
458 String type = service.serviceType;
461 atpoint = JvSwingUtils.findOrCreateMenu(atpoint, host);
462 if (atpoint.getToolTipText() == null)
464 atpoint.setToolTipText("Services at " + host);
469 atpoint = JvSwingUtils.findOrCreateMenu(atpoint, type);
470 if (atpoint.getToolTipText() == null)
472 atpoint.setToolTipText(service.getActionText());
476 && !hostLabels.contains(host + service.serviceType
477 + service.getActionText()))
478 // !hostLabels.contains(host + (bytype ?
479 // service.serviceType+service.getActionText() : "")))
481 // add a marker indicating where this service is hosted
482 // relies on services from the same host being listed in a
486 if (hostLabels.contains(host))
488 atpoint.addSeparator();
492 hostLabels.add(host);
494 if (lasthostFor.get(service.action) == null
495 || !lasthostFor.get(service.action).equals(host))
497 atpoint.add(hitm = new JMenuItem(host));
498 hitm.setForeground(Color.blue);
499 hitm.addActionListener(new ActionListener()
503 public void actionPerformed(ActionEvent e)
505 Desktop.showUrl(service.getHost());
508 hitm.setToolTipText(JvSwingUtils
509 .wrapTooltip("Opens the JABAWS server's homepage in web browser"));
510 lasthostFor.put(service.action, host);
512 hostLabels.add(host + service.serviceType
513 + service.getActionText());
516 service.attachWSMenuEntry(atpoint, alignFrame);
521 public static void main(String[] args)
525 testUrls = new Vector<String>();
526 for (String url : args)
532 Thread runner = getDiscoverer().startDiscoverer(
533 new PropertyChangeListener()
536 public void propertyChange(PropertyChangeEvent evt)
538 if (getDiscoverer().services != null)
540 System.out.println("Changesupport: There are now "
541 + getDiscoverer().services.size() + " services");
543 for (Jws2Instance instance : getDiscoverer().services)
545 System.out.println("Service " + i++ + " "
546 + instance.getClass() + "@"
547 + instance.getHost() + ": "
548 + instance.getActionText());
554 while (runner.isAlive())
559 } catch (InterruptedException e)
567 } catch (InterruptedException x)
572 private static Jws2Discoverer discoverer;
574 public static Jws2Discoverer getDiscoverer()
576 if (discoverer == null)
578 discoverer = new Jws2Discoverer();
583 public boolean hasServices()
585 // TODO Auto-generated method stub
586 return !running && services != null && services.size() > 0;
589 public boolean isRunning()
595 * the jalview .properties entry for JWS2 URLS
597 final static String JWS2HOSTURLS = "JWS2HOSTURLS";
599 public static void setServiceUrls(Vector<String> urls)
603 StringBuffer urlbuffer = new StringBuffer();
605 for (String url : urls)
607 urlbuffer.append(sep);
608 urlbuffer.append(url);
611 Cache.setProperty(JWS2HOSTURLS, urlbuffer.toString());
615 Cache.removeProperty(JWS2HOSTURLS);
619 private static Vector<String> testUrls = null;
621 public static Vector<String> getServiceUrls()
623 if (testUrls != null)
625 // return test urls, if there are any, instead of touching cache
628 String surls = Cache.getDefault(JWS2HOSTURLS,
629 "http://www.compbio.dundee.ac.uk/jabaws");
630 Vector<String> urls = new Vector<String>();
633 StringTokenizer st = new StringTokenizer(surls, ",");
634 while (st.hasMoreElements())
639 java.net.URL u = new java.net.URL(url = st.nextToken());
640 if (!urls.contains(url))
646 jalview.bin.Cache.log.info("Ignoring duplicate url in "
647 + JWS2HOSTURLS + " list");
649 } catch (Exception ex)
651 jalview.bin.Cache.log
652 .warn("Problem whilst trying to make a URL from '"
653 + ((url != null) ? url : "<null>") + "'");
654 jalview.bin.Cache.log
655 .warn("This was probably due to a malformed comma separated list"
658 + " entry of $(HOME)/.jalview_properties)");
659 jalview.bin.Cache.log.debug("Exception was ", ex);
662 } catch (Exception ex)
664 jalview.bin.Cache.log.warn(
665 "Error parsing comma separated list of urls in "
666 + JWS2HOSTURLS + " preference.", ex);
668 if (urls.size() >= 0)
675 public Vector<Jws2Instance> getServices()
677 return (services == null) ? new Vector<Jws2Instance>()
678 : new Vector<Jws2Instance>(services);
682 * test the given URL with the JabaWS test code
687 public static boolean testServiceUrl(URL foo)
691 compbio.ws.client.WSTester.main(new String[]
692 { "-h=" + foo.toString() });
693 } catch (Exception e)
697 } catch (OutOfMemoryError e)
711 * Start a fresh discovery thread and notify the given object when we're
712 * finished. Any known existing threads will be killed before this one is
715 * @param changeSupport2
718 public Thread startDiscoverer(PropertyChangeListener changeSupport2)
724 addPropertyChangeListener(changeSupport2);
725 Thread thr = new Thread(this);
730 Vector<String> invalidServiceUrls = null, urlsWithoutServices = null,
731 validServiceUrls = null;
734 * @return the invalidServiceUrls
736 public Vector<String> getInvalidServiceUrls()
738 return invalidServiceUrls;
742 * @return the urlsWithoutServices
744 public Vector<String> getUrlsWithoutServices()
746 return urlsWithoutServices;
750 * add an 'empty' JABA server to the list. Only servers not already in the
751 * 'bad URL' list will be added to this list.
755 public synchronized void addUrlwithnoservices(String jwsservers)
757 if (urlsWithoutServices == null)
759 urlsWithoutServices = new Vector<String>();
762 if ((invalidServiceUrls == null || !invalidServiceUrls
763 .contains(jwsservers))
764 && !urlsWithoutServices.contains(jwsservers))
766 urlsWithoutServices.add(jwsservers);
771 * add a bad URL to the list
775 public synchronized void addInvalidServiceUrl(String jwsservers)
777 if (invalidServiceUrls == null)
779 invalidServiceUrls = new Vector<String>();
781 if (!invalidServiceUrls.contains(jwsservers))
783 invalidServiceUrls.add(jwsservers);
789 * @return a human readable report of any problems with the service URLs used
792 public String getErrorMessages()
794 if (!isRunning() && !isAborted())
796 StringBuffer ermsg = new StringBuffer();
797 boolean list = false;
798 if (getInvalidServiceUrls() != null
799 && getInvalidServiceUrls().size() > 0)
801 ermsg.append("URLs that could not be contacted: \n");
802 for (String svcurl : getInvalidServiceUrls())
809 ermsg.append(svcurl);
811 ermsg.append("\n\n");
814 if (getUrlsWithoutServices() != null
815 && getUrlsWithoutServices().size() > 0)
817 ermsg.append("URLs without any JABA Services : \n");
818 for (String svcurl : getUrlsWithoutServices())
825 ermsg.append(svcurl);
829 if (ermsg.length() > 1)
831 return ermsg.toString();
838 public int getServerStatusFor(String url)
840 if (validServiceUrls != null && validServiceUrls.contains(url))
844 if (urlsWithoutServices != null && urlsWithoutServices.contains(url))
846 if (invalidServiceUrls != null && invalidServiceUrls.contains(url))
854 * pick the user's preferred service based on a set of URLs (jaba server
855 * locations) and service URIs (specifying version and service interface
859 * @return null or best match for given uri/ls.
861 public Jws2Instance getPreferredServiceFor(String[] serviceURLs)
863 HashSet<String> urls = new HashSet<String>();
864 urls.addAll(Arrays.asList(serviceURLs));
865 Jws2Instance match = null;
866 if (services != null)
868 for (Jws2Instance svc : services)
870 if (urls.contains(svc.getServiceTypeURI()))
874 // for moment we always pick service from server ordered first in
875 // user's preferences
878 if (urls.contains(svc.getUri()))
880 // stop and return - we've matched type URI and URI for service
890 Map<String, Map<String, String>> preferredServiceMap = new HashMap<String, Map<String, String>>();;
893 * get current preferred service of the given type, or global default
896 * null or a specific alignFrame
898 * Jws2Instance.serviceType for service
899 * @return null if no service of this type is available, the preferred service
900 * for the serviceType and af if specified and if defined.
902 public Jws2Instance getPreferredServiceFor(AlignFrame af,
905 String serviceurl = null;
906 synchronized (preferredServiceMap)
908 String afid = (af == null) ? "" : af.getViewport().getSequenceSetId();
909 Map<String, String> prefmap = preferredServiceMap.get(afid);
910 if (afid.length() > 0 && prefmap == null)
912 // recover global setting, if any
913 prefmap = preferredServiceMap.get("");
917 serviceurl = prefmap.get(serviceType);
921 Jws2Instance response = null;
922 for (Jws2Instance svc : services)
924 if (svc.serviceType.equals(serviceType))
926 if (serviceurl == null || serviceurl.equals(svc.getHost()))
936 public void setPreferredServiceFor(AlignFrame af, String serviceType,
937 String serviceAction, Jws2Instance selectedServer)
939 String afid = (af == null) ? "" : af.getViewport().getSequenceSetId();
940 if (preferredServiceMap == null)
942 preferredServiceMap = new HashMap<String, Map<String, String>>();
944 Map<String, String> prefmap = preferredServiceMap.get(afid);
947 prefmap = new HashMap<String, String>();
948 preferredServiceMap.put(afid, prefmap);
950 prefmap.put(serviceType, selectedServer.getHost());
951 prefmap.put(serviceAction, selectedServer.getHost());
954 public void setPreferredServiceFor(String serviceType,
955 String serviceAction, Jws2Instance selectedServer)
957 setPreferredServiceFor(null, serviceType, serviceAction, selectedServer);