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;
42 import java.util.StringTokenizer;
43 import java.util.Vector;
45 import javax.swing.JMenu;
46 import javax.swing.JMenuItem;
48 import compbio.ws.client.Services;
51 * discoverer for jws2 services. Follows the lightweight service discoverer
52 * pattern (archetyped by EnfinEnvision2OneWay)
57 public class Jws2Discoverer implements Runnable, WSMenuEntryProviderI
59 private java.beans.PropertyChangeSupport changeSupport = new java.beans.PropertyChangeSupport(
63 * change listeners are notified of "services" property changes
66 * to be added that consumes new services Hashtable object.
68 public void addPropertyChangeListener(
69 java.beans.PropertyChangeListener listener)
71 changeSupport.addPropertyChangeListener(listener);
80 public void removePropertyChangeListener(
81 java.beans.PropertyChangeListener listener)
83 changeSupport.removePropertyChangeListener(listener);
86 boolean running = false, aborted = false;
91 public boolean isAborted()
100 public void setAborted(boolean aborted)
102 this.aborted = aborted;
105 Thread oldthread = null;
110 if (running && oldthread != null && oldthread.isAlive())
121 .debug("Waiting around for old discovery thread to finish.");
122 // wait around until old discoverer dies
124 } catch (Exception e)
128 Cache.log.debug("Old discovery thread has finished.");
132 // first set up exclusion list if needed
133 final Set<String> ignoredServices = new HashSet<String>();
134 for (String ignored:jalview.bin.Cache.getDefault("IGNORED_JABAWS_SERVICETYPES", Services.JpredWS.toString()).split("\\|"))
136 ignoredServices.add(ignored);
140 changeSupport.firePropertyChange("services", services, new Vector());
141 oldthread = Thread.currentThread();
144 Class foo = getClass().getClassLoader().loadClass(
145 "compbio.ws.client.Jws2Client");
146 } catch (ClassNotFoundException e)
149 .println("Not enabling JABA Webservices : client jar is not available."
150 + "\nPlease check that your webstart JNLP file is up to date!");
154 // reinitialise records of good and bad service URLs
155 if (services != null)
157 services.removeAllElements();
159 if (urlsWithoutServices != null)
161 urlsWithoutServices.removeAllElements();
163 if (invalidServiceUrls != null)
165 invalidServiceUrls.removeAllElements();
167 if (validServiceUrls != null)
169 validServiceUrls.removeAllElements();
171 ArrayList<String> svctypes = new ArrayList<String>();
173 List<JabaWsServerQuery> qrys = new ArrayList<JabaWsServerQuery>();
174 for (final String jwsservers : getServiceUrls())
176 JabaWsServerQuery squery = new JabaWsServerQuery(this, jwsservers);
177 if (svctypes.size() == 0)
179 // TODO: remove this ugly hack to get Canonical JABA service ordering
180 // for all possible services
181 for (Services sv : squery.JABAWS2SERVERS)
183 if (!ignoredServices.contains(sv.toString()))
185 svctypes.add(sv.toString());
191 new Thread(squery).start();
193 boolean finished = true;
200 } catch (Exception e)
204 for (JabaWsServerQuery squery : qrys)
206 if (squery.isRunning()){
212 Cache.log.debug("Aborting " + qrys.size()
213 + " JABAWS discovery threads.");
214 for (JabaWsServerQuery squery : qrys)
216 squery.setQuit(true);
219 } while (!aborted && !finished);
222 // resort services according to order found in jabaws service list
223 // also ensure servics for each host are ordered in same way.
225 if (services != null && services.size() > 0)
227 Jws2Instance[] svcs = new Jws2Instance[services.size()];
228 int[] spos = new int[services.size()];
230 Vector svcUrls = getServiceUrls();
231 for (Jws2Instance svc : services)
234 spos[ipos++] = 1000 * svcUrls.indexOf(svc.getHost()) + 1
235 + svctypes.indexOf(svc.serviceType);
237 jalview.util.QuickSort.sort(spos, svcs);
238 services = new Vector<Jws2Instance>();
239 for (Jws2Instance svc : svcs)
241 if (!ignoredServices.contains(svc.serviceType))
250 changeSupport.firePropertyChange("services", new Vector(), services);
254 * record this service endpoint so we can use it
260 synchronized void addService(String jwsservers, Jws2Instance service)
262 if (services == null)
264 services = new Vector<Jws2Instance>();
266 System.out.println("Discovered service: " + jwsservers + " "
267 + service.toString());
268 // Jws2Instance service = new Jws2Instance(jwsservers, srv.toString(),
271 services.add(service);
272 // retrieve the presets and parameter set and cache now
273 ParamDatastoreI pds = service.getParamStore();
278 service.hasParameters();
279 if (validServiceUrls == null)
281 validServiceUrls = new Vector();
283 validServiceUrls.add(jwsservers);
287 * holds list of services.
289 protected Vector<Jws2Instance> services;
292 * attach all available web services to the appropriate submenu in the given
295 public void attachWSMenuEntry(JMenu wsmenu, final AlignFrame alignFrame)
297 // dynamically regenerate service list.
298 populateWSMenuEntry(wsmenu, alignFrame, null);
301 private boolean isRecalculable(String action)
303 return (action != null && action.equalsIgnoreCase("conservation"));
306 private void populateWSMenuEntry(JMenu jws2al,
307 final AlignFrame alignFrame, String typeFilter)
309 if (running || services == null || services.size() == 0)
313 boolean byhost = Cache.getDefault("WSMENU_BYHOST", false), bytype = Cache
314 .getDefault("WSMENU_BYTYPE", false);
316 * eventually, JWS2 services will appear under the same align/etc submenus.
317 * for moment we keep them separate.
320 List<Jws2Instance> enumerableServices = new ArrayList<Jws2Instance>();
321 // jws2al.removeAll();
322 Map<String, Jws2Instance> preferredHosts = new HashMap<String, Jws2Instance>();
323 Map<String, List<Jws2Instance>> alternates = new HashMap<String, List<Jws2Instance>>();
324 for (Jws2Instance service : services.toArray(new Jws2Instance[0]))
326 if (!isRecalculable(service.action))
328 // add 'one shot' services to be displayed using the classic menu
330 enumerableServices.add(service);
334 if (!preferredHosts.containsKey(service.serviceType))
336 Jws2Instance preferredInstance = getPreferredServiceFor(
337 alignFrame, service.serviceType);
338 if (preferredInstance != null)
340 preferredHosts.put(service.serviceType, preferredInstance);
344 preferredHosts.put(service.serviceType, service);
347 List<Jws2Instance> ph = alternates.get(service.serviceType);
348 if (preferredHosts.get(service.serviceType) != service)
352 ph = new ArrayList<Jws2Instance>();
355 alternates.put(service.serviceType, ph);
361 // create GUI element for classic services
362 addEnumeratedServices(jws2al, alignFrame, enumerableServices);
363 // and the instantaneous services
364 for (final Jws2Instance service : preferredHosts.values())
366 atpoint = JvSwingUtils.findOrCreateMenu(jws2al, service.action);
368 if (atpoint.getItemCount() > 1)
370 // previous service of this type already present
371 atpoint.addSeparator();
373 atpoint.add(hitm = new JMenuItem(service.getHost()));
374 hitm.setForeground(Color.blue);
375 hitm.addActionListener(new ActionListener()
379 public void actionPerformed(ActionEvent e)
381 Desktop.showUrl(service.getHost());
384 hitm.setToolTipText(JvSwingUtils
385 .wrapTooltip("Opens the JABAWS server's homepage in web browser"));
387 service.attachWSMenuEntry(atpoint, alignFrame);
388 if (alternates.containsKey(service.serviceType))
390 atpoint.add(hitm = new JMenu("Switch server"));
391 hitm.setToolTipText(JvSwingUtils
392 .wrapTooltip("Choose a server for running this service"));
393 for (final Jws2Instance sv : alternates.get(service.serviceType))
396 hitm.add(itm = new JMenuItem(sv.getHost()));
397 itm.setForeground(Color.blue);
398 itm.addActionListener(new ActionListener()
402 public void actionPerformed(ActionEvent arg0)
404 new Thread(new Runnable()
408 setPreferredServiceFor(alignFrame, sv.serviceType,
410 changeSupport.firePropertyChange("services",
411 new Vector(), services);
419 * hitm.addActionListener(new ActionListener() {
421 * @Override public void actionPerformed(ActionEvent arg0) { new
422 * Thread(new Runnable() {
424 * @Override public void run() { new SetPreferredServer(alignFrame,
425 * service.serviceType, service.action); } }).start(); } });
432 * add services using the Java 2.5/2.6/2.7 system which optionally creates
433 * submenus to index by host and service program type
435 private void addEnumeratedServices(final JMenu jws2al,
436 final AlignFrame alignFrame, List<Jws2Instance> enumerableServices)
438 boolean byhost = Cache.getDefault("WSMENU_BYHOST", false), bytype = Cache
439 .getDefault("WSMENU_BYTYPE", false);
441 * eventually, JWS2 services will appear under the same align/etc submenus.
442 * for moment we keep them separate.
445 MsaWSClient msacl = new MsaWSClient();
446 List<String> hostLabels = new ArrayList<String>();
447 Hashtable<String, String> lasthostFor = new Hashtable<String, String>();
448 Hashtable<String, ArrayList<Jws2Instance>> hosts = new Hashtable<String, ArrayList<Jws2Instance>>();
449 ArrayList<String> hostlist = new ArrayList<String>();
450 for (Jws2Instance service : enumerableServices)
452 ArrayList<Jws2Instance> hostservices = hosts.get(service.getHost());
453 if (hostservices == null)
455 hosts.put(service.getHost(),
456 hostservices = new ArrayList<Jws2Instance>());
457 hostlist.add(service.getHost());
459 hostservices.add(service);
461 // now add hosts in order of the given array
462 for (String host : hostlist)
464 Jws2Instance orderedsvcs[] = hosts.get(host).toArray(
465 new Jws2Instance[1]);
466 String sortbytype[] = new String[orderedsvcs.length];
467 for (int i = 0; i < sortbytype.length; i++)
469 sortbytype[i] = orderedsvcs[i].serviceType;
471 jalview.util.QuickSort.sort(sortbytype, orderedsvcs);
472 for (final Jws2Instance service : orderedsvcs)
474 atpoint = JvSwingUtils.findOrCreateMenu(jws2al, service.action);
475 String type = service.serviceType;
478 atpoint = JvSwingUtils.findOrCreateMenu(atpoint, host);
479 if (atpoint.getToolTipText() == null)
481 atpoint.setToolTipText("Services at " + host);
486 atpoint = JvSwingUtils.findOrCreateMenu(atpoint, type);
487 if (atpoint.getToolTipText() == null)
489 atpoint.setToolTipText(service.getActionText());
493 && !hostLabels.contains(host + service.serviceType
494 + service.getActionText()))
495 // !hostLabels.contains(host + (bytype ?
496 // service.serviceType+service.getActionText() : "")))
498 // add a marker indicating where this service is hosted
499 // relies on services from the same host being listed in a
503 if (hostLabels.contains(host))
505 atpoint.addSeparator();
509 hostLabels.add(host);
511 if (lasthostFor.get(service.action) == null
512 || !lasthostFor.get(service.action).equals(host))
514 atpoint.add(hitm = new JMenuItem(host));
515 hitm.setForeground(Color.blue);
516 hitm.addActionListener(new ActionListener()
520 public void actionPerformed(ActionEvent e)
522 Desktop.showUrl(service.getHost());
525 hitm.setToolTipText(JvSwingUtils
526 .wrapTooltip("Opens the JABAWS server's homepage in web browser"));
527 lasthostFor.put(service.action, host);
529 hostLabels.add(host + service.serviceType
530 + service.getActionText());
533 service.attachWSMenuEntry(atpoint, alignFrame);
538 public static void main(String[] args)
542 testUrls = new Vector<String>();
543 for (String url : args)
549 Thread runner = getDiscoverer().startDiscoverer(
550 new PropertyChangeListener()
553 public void propertyChange(PropertyChangeEvent evt)
555 if (getDiscoverer().services != null)
557 System.out.println("Changesupport: There are now "
558 + getDiscoverer().services.size() + " services");
560 for (Jws2Instance instance : getDiscoverer().services)
562 System.out.println("Service " + i++ + " "
563 + instance.getClass() + "@"
564 + instance.getHost() + ": "
565 + instance.getActionText());
571 while (runner.isAlive())
576 } catch (InterruptedException e)
584 } catch (InterruptedException x)
589 private static Jws2Discoverer discoverer;
591 public static Jws2Discoverer getDiscoverer()
593 if (discoverer == null)
595 discoverer = new Jws2Discoverer();
600 public boolean hasServices()
602 // TODO Auto-generated method stub
603 return !running && services != null && services.size() > 0;
606 public boolean isRunning()
612 * the jalview .properties entry for JWS2 URLS
614 final static String JWS2HOSTURLS = "JWS2HOSTURLS";
616 public static void setServiceUrls(Vector<String> urls)
620 StringBuffer urlbuffer = new StringBuffer();
622 for (String url : urls)
624 urlbuffer.append(sep);
625 urlbuffer.append(url);
628 Cache.setProperty(JWS2HOSTURLS, urlbuffer.toString());
632 Cache.removeProperty(JWS2HOSTURLS);
636 private static Vector<String> testUrls = null;
638 public static Vector<String> getServiceUrls()
640 if (testUrls != null)
642 // return test urls, if there are any, instead of touching cache
645 String surls = Cache.getDefault(JWS2HOSTURLS,
646 "http://www.compbio.dundee.ac.uk/jabaws");
647 Vector<String> urls = new Vector<String>();
650 StringTokenizer st = new StringTokenizer(surls, ",");
651 while (st.hasMoreElements())
656 java.net.URL u = new java.net.URL(url = st.nextToken());
657 if (!urls.contains(url))
663 jalview.bin.Cache.log.info("Ignoring duplicate url in "
664 + JWS2HOSTURLS + " list");
666 } catch (Exception ex)
668 jalview.bin.Cache.log
669 .warn("Problem whilst trying to make a URL from '"
670 + ((url != null) ? url : "<null>") + "'");
671 jalview.bin.Cache.log
672 .warn("This was probably due to a malformed comma separated list"
675 + " entry of $(HOME)/.jalview_properties)");
676 jalview.bin.Cache.log.debug("Exception was ", ex);
679 } catch (Exception ex)
681 jalview.bin.Cache.log.warn(
682 "Error parsing comma separated list of urls in "
683 + JWS2HOSTURLS + " preference.", ex);
685 if (urls.size() >= 0)
692 public Vector<Jws2Instance> getServices()
694 return (services == null) ? new Vector<Jws2Instance>()
695 : new Vector<Jws2Instance>(services);
699 * test the given URL with the JabaWS test code
704 public static boolean testServiceUrl(URL foo)
708 compbio.ws.client.WSTester.main(new String[]
709 { "-h=" + foo.toString() });
710 } catch (Exception e)
714 } catch (OutOfMemoryError e)
728 * Start a fresh discovery thread and notify the given object when we're
729 * finished. Any known existing threads will be killed before this one is
732 * @param changeSupport2
735 public Thread startDiscoverer(PropertyChangeListener changeSupport2)
741 addPropertyChangeListener(changeSupport2);
742 Thread thr = new Thread(this);
747 Vector<String> invalidServiceUrls = null, urlsWithoutServices = null,
748 validServiceUrls = null;
751 * @return the invalidServiceUrls
753 public Vector<String> getInvalidServiceUrls()
755 return invalidServiceUrls;
759 * @return the urlsWithoutServices
761 public Vector<String> getUrlsWithoutServices()
763 return urlsWithoutServices;
767 * add an 'empty' JABA server to the list. Only servers not already in the
768 * 'bad URL' list will be added to this list.
772 public synchronized void addUrlwithnoservices(String jwsservers)
774 if (urlsWithoutServices == null)
776 urlsWithoutServices = new Vector<String>();
779 if ((invalidServiceUrls == null || !invalidServiceUrls
780 .contains(jwsservers))
781 && !urlsWithoutServices.contains(jwsservers))
783 urlsWithoutServices.add(jwsservers);
788 * add a bad URL to the list
792 public synchronized void addInvalidServiceUrl(String jwsservers)
794 if (invalidServiceUrls == null)
796 invalidServiceUrls = new Vector<String>();
798 if (!invalidServiceUrls.contains(jwsservers))
800 invalidServiceUrls.add(jwsservers);
806 * @return a human readable report of any problems with the service URLs used
809 public String getErrorMessages()
811 if (!isRunning() && !isAborted())
813 StringBuffer ermsg = new StringBuffer();
814 boolean list = false;
815 if (getInvalidServiceUrls() != null
816 && getInvalidServiceUrls().size() > 0)
818 ermsg.append("URLs that could not be contacted: \n");
819 for (String svcurl : getInvalidServiceUrls())
826 ermsg.append(svcurl);
828 ermsg.append("\n\n");
831 if (getUrlsWithoutServices() != null
832 && getUrlsWithoutServices().size() > 0)
834 ermsg.append("URLs without any JABA Services : \n");
835 for (String svcurl : getUrlsWithoutServices())
842 ermsg.append(svcurl);
846 if (ermsg.length() > 1)
848 return ermsg.toString();
855 public int getServerStatusFor(String url)
857 if (validServiceUrls != null && validServiceUrls.contains(url))
861 if (urlsWithoutServices != null && urlsWithoutServices.contains(url))
863 if (invalidServiceUrls != null && invalidServiceUrls.contains(url))
871 * pick the user's preferred service based on a set of URLs (jaba server
872 * locations) and service URIs (specifying version and service interface
876 * @return null or best match for given uri/ls.
878 public Jws2Instance getPreferredServiceFor(String[] serviceURLs)
880 HashSet<String> urls = new HashSet<String>();
881 urls.addAll(Arrays.asList(serviceURLs));
882 Jws2Instance match = null;
883 if (services != null)
885 for (Jws2Instance svc : services)
887 if (urls.contains(svc.getServiceTypeURI()))
891 // for moment we always pick service from server ordered first in
892 // user's preferences
895 if (urls.contains(svc.getUri()))
897 // stop and return - we've matched type URI and URI for service
907 Map<String, Map<String, String>> preferredServiceMap = new HashMap<String, Map<String, String>>();;
910 * get current preferred service of the given type, or global default
913 * null or a specific alignFrame
915 * Jws2Instance.serviceType for service
916 * @return null if no service of this type is available, the preferred service
917 * for the serviceType and af if specified and if defined.
919 public Jws2Instance getPreferredServiceFor(AlignFrame af,
922 String serviceurl = null;
923 synchronized (preferredServiceMap)
925 String afid = (af == null) ? "" : af.getViewport().getSequenceSetId();
926 Map<String, String> prefmap = preferredServiceMap.get(afid);
927 if (afid.length() > 0 && prefmap == null)
929 // recover global setting, if any
930 prefmap = preferredServiceMap.get("");
934 serviceurl = prefmap.get(serviceType);
938 Jws2Instance response = null;
939 for (Jws2Instance svc : services)
941 if (svc.serviceType.equals(serviceType))
943 if (serviceurl == null || serviceurl.equals(svc.getHost()))
953 public void setPreferredServiceFor(AlignFrame af, String serviceType,
954 String serviceAction, Jws2Instance selectedServer)
956 String afid = (af == null) ? "" : af.getViewport().getSequenceSetId();
957 if (preferredServiceMap == null)
959 preferredServiceMap = new HashMap<String, Map<String, String>>();
961 Map<String, String> prefmap = preferredServiceMap.get(afid);
964 prefmap = new HashMap<String, String>();
965 preferredServiceMap.put(afid, prefmap);
967 prefmap.put(serviceType, selectedServer.getHost());
968 prefmap.put(serviceAction, selectedServer.getHost());
971 public void setPreferredServiceFor(String serviceType,
972 String serviceAction, Jws2Instance selectedServer)
974 setPreferredServiceFor(null, serviceType, serviceAction, selectedServer);