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;
27 import java.awt.Color;
28 import java.awt.event.ActionEvent;
29 import java.awt.event.ActionListener;
30 import java.beans.PropertyChangeEvent;
31 import java.beans.PropertyChangeListener;
33 import java.util.ArrayList;
34 import java.util.Arrays;
35 import java.util.HashMap;
36 import java.util.HashSet;
37 import java.util.Hashtable;
38 import java.util.List;
40 import java.util.StringTokenizer;
41 import java.util.Vector;
43 import javax.swing.JMenu;
44 import javax.swing.JMenuItem;
46 import compbio.ws.client.Services;
49 * discoverer for jws2 services. Follows the lightweight service discoverer
50 * pattern (archetyped by EnfinEnvision2OneWay)
55 public class Jws2Discoverer implements Runnable, WSMenuEntryProviderI
57 private java.beans.PropertyChangeSupport changeSupport = new java.beans.PropertyChangeSupport(
61 * change listeners are notified of "services" property changes
64 * to be added that consumes new services Hashtable object.
66 public void addPropertyChangeListener(
67 java.beans.PropertyChangeListener listener)
69 changeSupport.addPropertyChangeListener(listener);
78 public void removePropertyChangeListener(
79 java.beans.PropertyChangeListener listener)
81 changeSupport.removePropertyChangeListener(listener);
84 boolean running = false, aborted = false;
89 public boolean isAborted()
98 public void setAborted(boolean aborted)
100 this.aborted = aborted;
103 Thread oldthread = null;
107 if (running && oldthread != null && oldthread.isAlive())
118 .debug("Waiting around for old discovery thread to finish.");
119 // wait around until old discoverer dies
121 } catch (Exception e)
125 Cache.log.debug("Old discovery thread has finished.");
128 changeSupport.firePropertyChange("services", services, new Vector());
129 oldthread = Thread.currentThread();
132 Class foo = getClass().getClassLoader().loadClass(
133 "compbio.ws.client.Jws2Client");
134 } catch (ClassNotFoundException e)
137 .println("Not enabling JABA Webservices : client jar is not available."
138 + "\nPlease check that your webstart JNLP file is up to date!");
142 // reinitialise records of good and bad service URLs
143 if (services != null)
145 services.removeAllElements();
147 if (urlsWithoutServices != null)
149 urlsWithoutServices.removeAllElements();
151 if (invalidServiceUrls != null)
153 invalidServiceUrls.removeAllElements();
155 if (validServiceUrls != null)
157 validServiceUrls.removeAllElements();
159 ArrayList<String> svctypes = new ArrayList<String>();
161 List<JabaWsServerQuery> qrys = new ArrayList<JabaWsServerQuery>();
162 for (final String jwsservers : getServiceUrls())
164 JabaWsServerQuery squery = new JabaWsServerQuery(this, jwsservers);
165 if (svctypes.size() == 0)
167 // TODO: remove this ugly hack to get Canonical JABA service ordering
168 // for all possible services
169 for (Services sv : squery.JABAWS2SERVERS)
171 svctypes.add(sv.toString());
176 new Thread(squery).start();
178 boolean finished = true;
185 } catch (Exception e)
189 for (JabaWsServerQuery squery : qrys)
191 finished = finished && !squery.isRunning();
195 Cache.log.debug("Aborting " + qrys.size()
196 + " JABAWS discovery threads.");
197 for (JabaWsServerQuery squery : qrys)
199 squery.setQuit(true);
202 } while (!aborted && !finished);
205 // resort services according to order found in jabaws service list
206 // also ensure servics for each host are ordered in same way.
208 if (services != null && services.size() > 0)
210 Jws2Instance[] svcs = new Jws2Instance[services.size()];
211 int[] spos = new int[services.size()];
213 Vector svcUrls = getServiceUrls();
214 for (Jws2Instance svc : services)
217 spos[ipos++] = 1000 * svcUrls.indexOf(svc.getHost()) + 1
218 + svctypes.indexOf(svc.serviceType);
220 jalview.util.QuickSort.sort(spos, svcs);
221 services = new Vector<Jws2Instance>();
222 for (Jws2Instance svc : svcs)
230 changeSupport.firePropertyChange("services", new Vector(), services);
234 * record this service endpoint so we can use it
240 synchronized void addService(String jwsservers, Jws2Instance service)
242 if (services == null)
244 services = new Vector<Jws2Instance>();
246 System.out.println("Discovered service: " + jwsservers + " "
247 + service.toString());
248 // Jws2Instance service = new Jws2Instance(jwsservers, srv.toString(),
251 services.add(service);
252 // retrieve the presets and parameter set and cache now
253 ParamDataStoreI pds = service.getParamStore();
258 service.hasParameters();
259 if (validServiceUrls == null)
261 validServiceUrls = new Vector();
263 validServiceUrls.add(jwsservers);
267 * holds list of services.
269 protected Vector<Jws2Instance> services;
272 * attach all available web services to the appropriate submenu in the given
275 public void attachWSMenuEntry(JMenu wsmenu, final AlignFrame alignFrame)
277 // dynamically regenerate service list.
278 populateWSMenuEntry(wsmenu, alignFrame, null);
281 private boolean isRecalculable(String action)
283 return (action != null && action.equalsIgnoreCase("conservation"));
286 private void populateWSMenuEntry(JMenu jws2al,
287 final AlignFrame alignFrame, String typeFilter)
289 if (running || services == null || services.size() == 0)
293 boolean byhost = Cache.getDefault("WSMENU_BYHOST", false), bytype = Cache
294 .getDefault("WSMENU_BYTYPE", false);
296 * eventually, JWS2 services will appear under the same align/etc submenus.
297 * for moment we keep them separate.
300 List<Jws2Instance> enumerableServices = new ArrayList<Jws2Instance>();
301 // jws2al.removeAll();
302 Map<String, Jws2Instance> preferredHosts = new HashMap<String, Jws2Instance>();
303 Map<String, List<Jws2Instance>> alternates = new HashMap<String, List<Jws2Instance>>();
304 for (Jws2Instance service : services.toArray(new Jws2Instance[0]))
306 if (!isRecalculable(service.action))
308 // add 'one shot' services to be displayed using the classic menu
310 enumerableServices.add(service);
314 if (!preferredHosts.containsKey(service.serviceType))
316 Jws2Instance preferredInstance = getPreferredServiceFor(
317 alignFrame, service.serviceType);
318 if (preferredInstance != null)
320 preferredHosts.put(service.serviceType, preferredInstance);
324 preferredHosts.put(service.serviceType, service);
327 List<Jws2Instance> ph = alternates.get(service.serviceType);
328 if (preferredHosts.get(service.serviceType) != service)
332 ph = new ArrayList<Jws2Instance>();
335 alternates.put(service.serviceType, ph);
341 // create GUI element for classic services
342 addEnumeratedServices(jws2al, alignFrame, enumerableServices);
343 // and the instantaneous services
344 for (final Jws2Instance service : preferredHosts.values())
346 atpoint = JvSwingUtils.findOrCreateMenu(jws2al, service.action);
348 if (atpoint.getItemCount() > 1)
350 // previous service of this type already present
351 atpoint.addSeparator();
353 atpoint.add(hitm = new JMenuItem(service.getHost()));
354 hitm.setForeground(Color.blue);
355 hitm.addActionListener(new ActionListener()
359 public void actionPerformed(ActionEvent e)
361 Desktop.showUrl(service.getHost());
364 hitm.setToolTipText(JvSwingUtils
365 .wrapTooltip("Opens the JABAWS server's homepage in web browser"));
367 service.attachWSMenuEntry(atpoint, alignFrame);
368 if (alternates.containsKey(service.serviceType))
370 atpoint.add(hitm = new JMenu("Switch server"));
371 hitm.setToolTipText(JvSwingUtils
372 .wrapTooltip("Choose a server for running this service"));
373 for (final Jws2Instance sv : alternates.get(service.serviceType))
376 hitm.add(itm = new JMenuItem(sv.getHost()));
377 itm.setForeground(Color.blue);
378 itm.addActionListener(new ActionListener()
382 public void actionPerformed(ActionEvent arg0)
384 new Thread(new Runnable()
388 setPreferredServiceFor(alignFrame, sv.serviceType,
390 changeSupport.firePropertyChange("services",
391 new Vector(), services);
399 * hitm.addActionListener(new ActionListener() {
401 * @Override public void actionPerformed(ActionEvent arg0) { new
402 * Thread(new Runnable() {
404 * @Override public void run() { new SetPreferredServer(alignFrame,
405 * service.serviceType, service.action); } }).start(); } });
412 * add services using the Java 2.5/2.6/2.7 system which optionally creates
413 * submenus to index by host and service program type
415 private void addEnumeratedServices(final JMenu jws2al,
416 final AlignFrame alignFrame, List<Jws2Instance> enumerableServices)
418 boolean byhost = Cache.getDefault("WSMENU_BYHOST", false), bytype = Cache
419 .getDefault("WSMENU_BYTYPE", false);
421 * eventually, JWS2 services will appear under the same align/etc submenus.
422 * for moment we keep them separate.
425 MsaWSClient msacl = new MsaWSClient();
426 List<String> hostLabels = new ArrayList<String>();
427 Hashtable<String, String> lasthostFor = new Hashtable<String, String>();
428 Hashtable<String, ArrayList<Jws2Instance>> hosts = new Hashtable<String, ArrayList<Jws2Instance>>();
429 ArrayList<String> hostlist = new ArrayList<String>();
430 for (Jws2Instance service : enumerableServices)
432 ArrayList<Jws2Instance> hostservices = hosts.get(service.getHost());
433 if (hostservices == null)
435 hosts.put(service.getHost(),
436 hostservices = new ArrayList<Jws2Instance>());
437 hostlist.add(service.getHost());
439 hostservices.add(service);
441 // now add hosts in order of the given array
442 for (String host : hostlist)
444 Jws2Instance orderedsvcs[] = hosts.get(host).toArray(
445 new Jws2Instance[1]);
446 String sortbytype[] = new String[orderedsvcs.length];
447 for (int i = 0; i < sortbytype.length; i++)
449 sortbytype[i] = orderedsvcs[i].serviceType;
451 jalview.util.QuickSort.sort(sortbytype, orderedsvcs);
452 for (final Jws2Instance service : orderedsvcs)
454 atpoint = JvSwingUtils.findOrCreateMenu(jws2al, service.action);
455 String type = service.serviceType;
458 atpoint = JvSwingUtils.findOrCreateMenu(atpoint, host);
459 if (atpoint.getToolTipText() == null)
461 atpoint.setToolTipText("Services at " + host);
466 atpoint = JvSwingUtils.findOrCreateMenu(atpoint, type);
467 if (atpoint.getToolTipText() == null)
469 atpoint.setToolTipText(service.getActionText());
473 && !hostLabels.contains(host + service.serviceType
474 + service.getActionText()))
475 // !hostLabels.contains(host + (bytype ?
476 // service.serviceType+service.getActionText() : "")))
478 // add a marker indicating where this service is hosted
479 // relies on services from the same host being listed in a
483 if (hostLabels.contains(host))
485 atpoint.addSeparator();
489 hostLabels.add(host);
491 if (lasthostFor.get(service.action) == null
492 || !lasthostFor.get(service.action).equals(host))
494 atpoint.add(hitm = new JMenuItem(host));
495 hitm.setForeground(Color.blue);
496 hitm.addActionListener(new ActionListener()
500 public void actionPerformed(ActionEvent e)
502 Desktop.showUrl(service.getHost());
505 hitm.setToolTipText(JvSwingUtils
506 .wrapTooltip("Opens the JABAWS server's homepage in web browser"));
507 lasthostFor.put(service.action, host);
509 hostLabels.add(host + service.serviceType
510 + service.getActionText());
513 service.attachWSMenuEntry(atpoint, alignFrame);
518 public static void main(String[] args)
522 testUrls = new Vector<String>();
523 for (String url : args)
529 Thread runner = getDiscoverer().startDiscoverer(
530 new PropertyChangeListener()
533 public void propertyChange(PropertyChangeEvent evt)
535 if (getDiscoverer().services != null)
537 System.out.println("Changesupport: There are now "
538 + getDiscoverer().services.size() + " services");
540 for (Jws2Instance instance : getDiscoverer().services)
542 System.out.println("Service " + i++ + " "
543 + instance.getClass() + "@"
544 + instance.getHost() + ": "
545 + instance.getActionText());
551 while (runner.isAlive())
556 } catch (InterruptedException e)
564 } catch (InterruptedException x)
569 private static Jws2Discoverer discoverer;
571 public static Jws2Discoverer getDiscoverer()
573 if (discoverer == null)
575 discoverer = new Jws2Discoverer();
580 public boolean hasServices()
582 // TODO Auto-generated method stub
583 return !running && services != null && services.size() > 0;
586 public boolean isRunning()
592 * the jalview .properties entry for JWS2 URLS
594 final static String JWS2HOSTURLS = "JWS2HOSTURLS";
596 public static void setServiceUrls(Vector<String> urls)
600 StringBuffer urlbuffer = new StringBuffer();
602 for (String url : urls)
604 urlbuffer.append(sep);
605 urlbuffer.append(url);
608 Cache.setProperty(JWS2HOSTURLS, urlbuffer.toString());
612 Cache.removeProperty(JWS2HOSTURLS);
616 private static Vector<String> testUrls = null;
618 public static Vector<String> getServiceUrls()
620 if (testUrls != null)
622 // return test urls, if there are any, instead of touching cache
625 String surls = Cache.getDefault(JWS2HOSTURLS,
626 "http://www.compbio.dundee.ac.uk/jabaws");
627 Vector<String> urls = new Vector<String>();
630 StringTokenizer st = new StringTokenizer(surls, ",");
631 while (st.hasMoreElements())
636 java.net.URL u = new java.net.URL(url = st.nextToken());
637 if (!urls.contains(url))
643 jalview.bin.Cache.log.info("Ignoring duplicate url in "
644 + JWS2HOSTURLS + " list");
646 } catch (Exception ex)
648 jalview.bin.Cache.log
649 .warn("Problem whilst trying to make a URL from '"
650 + ((url != null) ? url : "<null>") + "'");
651 jalview.bin.Cache.log
652 .warn("This was probably due to a malformed comma separated list"
655 + " entry of $(HOME)/.jalview_properties)");
656 jalview.bin.Cache.log.debug("Exception was ", ex);
659 } catch (Exception ex)
661 jalview.bin.Cache.log.warn(
662 "Error parsing comma separated list of urls in "
663 + JWS2HOSTURLS + " preference.", ex);
665 if (urls.size() >= 0)
672 public Vector<Jws2Instance> getServices()
674 return (services == null) ? new Vector<Jws2Instance>()
675 : new Vector<Jws2Instance>(services);
679 * test the given URL with the JabaWS test code
684 public static boolean testServiceUrl(URL foo)
688 compbio.ws.client.WSTester.main(new String[]
689 { "-h=" + foo.toString() });
690 } catch (Exception e)
694 } catch (OutOfMemoryError e)
708 * Start a fresh discovery thread and notify the given object when we're
709 * finished. Any known existing threads will be killed before this one is
712 * @param changeSupport2
715 public Thread startDiscoverer(PropertyChangeListener changeSupport2)
721 addPropertyChangeListener(changeSupport2);
722 Thread thr = new Thread(this);
727 Vector<String> invalidServiceUrls = null, urlsWithoutServices = null,
728 validServiceUrls = null;
731 * @return the invalidServiceUrls
733 public Vector<String> getInvalidServiceUrls()
735 return invalidServiceUrls;
739 * @return the urlsWithoutServices
741 public Vector<String> getUrlsWithoutServices()
743 return urlsWithoutServices;
747 * add an 'empty' JABA server to the list. Only servers not already in the
748 * 'bad URL' list will be added to this list.
752 public synchronized void addUrlwithnoservices(String jwsservers)
754 if (urlsWithoutServices == null)
756 urlsWithoutServices = new Vector<String>();
759 if ((invalidServiceUrls == null || !invalidServiceUrls
760 .contains(jwsservers))
761 && !urlsWithoutServices.contains(jwsservers))
763 urlsWithoutServices.add(jwsservers);
768 * add a bad URL to the list
772 public synchronized void addInvalidServiceUrl(String jwsservers)
774 if (invalidServiceUrls == null)
776 invalidServiceUrls = new Vector<String>();
778 if (!invalidServiceUrls.contains(jwsservers))
780 invalidServiceUrls.add(jwsservers);
786 * @return a human readable report of any problems with the service URLs used
789 public String getErrorMessages()
791 if (!isRunning() && !isAborted())
793 StringBuffer ermsg = new StringBuffer();
794 boolean list = false;
795 if (getInvalidServiceUrls() != null
796 && getInvalidServiceUrls().size() > 0)
798 ermsg.append("URLs that could not be contacted: \n");
799 for (String svcurl : getInvalidServiceUrls())
806 ermsg.append(svcurl);
808 ermsg.append("\n\n");
811 if (getUrlsWithoutServices() != null
812 && getUrlsWithoutServices().size() > 0)
814 ermsg.append("URLs without any JABA Services : \n");
815 for (String svcurl : getUrlsWithoutServices())
822 ermsg.append(svcurl);
826 if (ermsg.length() > 1)
828 return ermsg.toString();
835 public int getServerStatusFor(String url)
837 if (validServiceUrls != null && validServiceUrls.contains(url))
841 if (urlsWithoutServices != null && urlsWithoutServices.contains(url))
843 if (invalidServiceUrls != null && invalidServiceUrls.contains(url))
851 * pick the user's preferred service based on a set of URLs (jaba server
852 * locations) and service URIs (specifying version and service interface
856 * @return null or best match for given uri/ls.
858 public Jws2Instance getPreferredServiceFor(String[] serviceURLs)
860 HashSet<String> urls = new HashSet<String>();
861 urls.addAll(Arrays.asList(serviceURLs));
862 Jws2Instance match = null;
863 if (services != null)
865 for (Jws2Instance svc : services)
867 if (urls.contains(svc.getServiceTypeURI()))
871 // for moment we always pick service from server ordered first in
872 // user's preferences
875 if (urls.contains(svc.getUri()))
877 // stop and return - we've matched type URI and URI for service
887 Map<String, Map<String, String>> preferredServiceMap = new HashMap<String, Map<String, String>>();;
890 * get current preferred service of the given type, or global default
893 * null or a specific alignFrame
895 * Jws2Instance.serviceType for service
896 * @return null if no service of this type is available, the preferred service
897 * for the serviceType and af if specified and if defined.
899 public Jws2Instance getPreferredServiceFor(AlignFrame af,
902 String serviceurl = null;
903 synchronized (preferredServiceMap)
905 String afid = (af == null) ? "" : af.getViewport().getSequenceSetId();
906 Map<String, String> prefmap = preferredServiceMap.get(afid);
907 if (afid.length() > 0 && prefmap == null)
909 // recover global setting, if any
910 prefmap = preferredServiceMap.get("");
914 serviceurl = prefmap.get(serviceType);
918 Jws2Instance response = null;
919 for (Jws2Instance svc : services)
921 if (svc.serviceType.equals(serviceType))
923 if (serviceurl == null || serviceurl.equals(svc.getHost()))
933 public void setPreferredServiceFor(AlignFrame af, String serviceType,
934 String serviceAction, Jws2Instance selectedServer)
936 String afid = (af == null) ? "" : af.getViewport().getSequenceSetId();
937 if (preferredServiceMap == null)
939 preferredServiceMap = new HashMap<String, Map<String, String>>();
941 Map<String, String> prefmap = preferredServiceMap.get(afid);
944 prefmap = new HashMap<String, String>();
945 preferredServiceMap.put(afid, prefmap);
947 prefmap.put(serviceType, selectedServer.getHost());
948 prefmap.put(serviceAction, selectedServer.getHost());
951 public void setPreferredServiceFor(String serviceType,
952 String serviceAction, Jws2Instance selectedServer)
954 setPreferredServiceFor(null, serviceType, serviceAction, selectedServer);