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 service.getParamStore().getPresets();
254 service.hasParameters();
255 if (validServiceUrls == null)
257 validServiceUrls = new Vector();
259 validServiceUrls.add(jwsservers);
263 * holds list of services.
265 protected Vector<Jws2Instance> services;
268 * attach all available web services to the appropriate submenu in the given
271 public void attachWSMenuEntry(JMenu wsmenu, final AlignFrame alignFrame)
273 // dynamically regenerate service list.
274 populateWSMenuEntry(wsmenu, alignFrame, null);
277 private boolean isRecalculable(String action)
279 return (action != null && action.equalsIgnoreCase("conservation"));
282 private void populateWSMenuEntry(JMenu jws2al,
283 final AlignFrame alignFrame, String typeFilter)
285 if (running || services == null || services.size() == 0)
289 boolean byhost = Cache.getDefault("WSMENU_BYHOST", false), bytype = Cache
290 .getDefault("WSMENU_BYTYPE", false);
292 * eventually, JWS2 services will appear under the same align/etc submenus.
293 * for moment we keep them separate.
296 List<Jws2Instance> enumerableServices = new ArrayList<Jws2Instance>();
297 // jws2al.removeAll();
298 Map<String, Jws2Instance> preferredHosts = new HashMap<String, Jws2Instance>();
299 Map<String, List<Jws2Instance>> alternates = new HashMap<String, List<Jws2Instance>>();
300 for (Jws2Instance service : services.toArray(new Jws2Instance[0]))
302 if (!isRecalculable(service.action))
304 // add 'one shot' services to be displayed using the classic menu
306 enumerableServices.add(service);
310 if (!preferredHosts.containsKey(service.serviceType))
312 Jws2Instance preferredInstance = getPreferredServiceFor(
313 alignFrame, service.serviceType);
314 if (preferredInstance != null)
316 preferredHosts.put(service.serviceType, preferredInstance);
320 preferredHosts.put(service.serviceType, service);
323 List<Jws2Instance> ph = alternates.get(service.serviceType);
324 if (preferredHosts.get(service.serviceType) != service)
328 ph = new ArrayList<Jws2Instance>();
331 alternates.put(service.serviceType, ph);
337 // create GUI element for classic services
338 addEnumeratedServices(jws2al, alignFrame, enumerableServices);
339 // and the instantaneous services
340 for (final Jws2Instance service : preferredHosts.values())
342 atpoint = JvSwingUtils.findOrCreateMenu(jws2al, service.action);
344 if (atpoint.getItemCount() > 1)
346 // previous service of this type already present
347 atpoint.addSeparator();
349 atpoint.add(hitm = new JMenuItem(service.getHost()));
350 hitm.setForeground(Color.blue);
351 hitm.addActionListener(new ActionListener()
355 public void actionPerformed(ActionEvent e)
357 Desktop.showUrl(service.getHost());
360 hitm.setToolTipText(JvSwingUtils
361 .wrapTooltip("Opens the JABAWS server's homepage in web browser"));
363 service.attachWSMenuEntry(atpoint, alignFrame);
364 if (alternates.containsKey(service.serviceType))
366 atpoint.add(hitm = new JMenu("Switch server"));
367 hitm.setToolTipText(JvSwingUtils
368 .wrapTooltip("Choose a server for running this service"));
369 for (final Jws2Instance sv : alternates.get(service.serviceType))
372 hitm.add(itm = new JMenuItem(sv.getHost()));
373 itm.setForeground(Color.blue);
374 itm.addActionListener(new ActionListener()
378 public void actionPerformed(ActionEvent arg0)
380 new Thread(new Runnable()
384 setPreferredServiceFor(alignFrame, sv.serviceType,
386 changeSupport.firePropertyChange("services",
387 new Vector(), services);
395 * hitm.addActionListener(new ActionListener() {
397 * @Override public void actionPerformed(ActionEvent arg0) { new
398 * Thread(new Runnable() {
400 * @Override public void run() { new SetPreferredServer(alignFrame,
401 * service.serviceType, service.action); } }).start(); } });
408 * add services using the Java 2.5/2.6/2.7 system which optionally creates
409 * submenus to index by host and service program type
411 private void addEnumeratedServices(final JMenu jws2al,
412 final AlignFrame alignFrame, List<Jws2Instance> enumerableServices)
414 boolean byhost = Cache.getDefault("WSMENU_BYHOST", false), bytype = Cache
415 .getDefault("WSMENU_BYTYPE", false);
417 * eventually, JWS2 services will appear under the same align/etc submenus.
418 * for moment we keep them separate.
421 MsaWSClient msacl = new MsaWSClient();
422 List<String> hostLabels = new ArrayList<String>();
423 Hashtable<String, String> lasthostFor = new Hashtable<String, String>();
424 Hashtable<String, ArrayList<Jws2Instance>> hosts = new Hashtable<String, ArrayList<Jws2Instance>>();
425 ArrayList<String> hostlist = new ArrayList<String>();
426 for (Jws2Instance service : enumerableServices)
428 ArrayList<Jws2Instance> hostservices = hosts.get(service.getHost());
429 if (hostservices == null)
431 hosts.put(service.getHost(),
432 hostservices = new ArrayList<Jws2Instance>());
433 hostlist.add(service.getHost());
435 hostservices.add(service);
437 // now add hosts in order of the given array
438 for (String host : hostlist)
440 Jws2Instance orderedsvcs[] = hosts.get(host).toArray(
441 new Jws2Instance[1]);
442 String sortbytype[] = new String[orderedsvcs.length];
443 for (int i = 0; i < sortbytype.length; i++)
445 sortbytype[i] = orderedsvcs[i].serviceType;
447 jalview.util.QuickSort.sort(sortbytype, orderedsvcs);
448 for (final Jws2Instance service : orderedsvcs)
450 atpoint = JvSwingUtils.findOrCreateMenu(jws2al, service.action);
451 String type = service.serviceType;
454 atpoint = JvSwingUtils.findOrCreateMenu(atpoint, host);
455 if (atpoint.getToolTipText() == null)
457 atpoint.setToolTipText("Services at " + host);
462 atpoint = JvSwingUtils.findOrCreateMenu(atpoint, type);
463 if (atpoint.getToolTipText() == null)
465 atpoint.setToolTipText(service.getActionText());
469 && !hostLabels.contains(host + service.serviceType
470 + service.getActionText()))
471 // !hostLabels.contains(host + (bytype ?
472 // service.serviceType+service.getActionText() : "")))
474 // add a marker indicating where this service is hosted
475 // relies on services from the same host being listed in a
479 if (hostLabels.contains(host))
481 atpoint.addSeparator();
485 hostLabels.add(host);
487 if (lasthostFor.get(service.action) == null
488 || !lasthostFor.get(service.action).equals(host))
490 atpoint.add(hitm = new JMenuItem(host));
491 hitm.setForeground(Color.blue);
492 hitm.addActionListener(new ActionListener()
496 public void actionPerformed(ActionEvent e)
498 Desktop.showUrl(service.getHost());
501 hitm.setToolTipText(JvSwingUtils
502 .wrapTooltip("Opens the JABAWS server's homepage in web browser"));
503 lasthostFor.put(service.action, host);
505 hostLabels.add(host + service.serviceType
506 + service.getActionText());
509 service.attachWSMenuEntry(atpoint, alignFrame);
514 public static void main(String[] args)
518 testUrls = new Vector<String>();
519 for (String url : args)
525 Thread runner = getDiscoverer().startDiscoverer(
526 new PropertyChangeListener()
529 public void propertyChange(PropertyChangeEvent evt)
531 if (getDiscoverer().services != null)
533 System.out.println("Changesupport: There are now "
534 + getDiscoverer().services.size() + " services");
536 for (Jws2Instance instance : getDiscoverer().services)
538 System.out.println("Service " + i++ + " "
539 + instance.getClass() + "@"
540 + instance.getHost() + ": "
541 + instance.getActionText());
547 while (runner.isAlive())
552 } catch (InterruptedException e)
560 } catch (InterruptedException x)
565 private static Jws2Discoverer discoverer;
567 public static Jws2Discoverer getDiscoverer()
569 if (discoverer == null)
571 discoverer = new Jws2Discoverer();
576 public boolean hasServices()
578 // TODO Auto-generated method stub
579 return !running && services != null && services.size() > 0;
582 public boolean isRunning()
588 * the jalview .properties entry for JWS2 URLS
590 final static String JWS2HOSTURLS = "JWS2HOSTURLS";
592 public static void setServiceUrls(Vector<String> urls)
596 StringBuffer urlbuffer = new StringBuffer();
598 for (String url : urls)
600 urlbuffer.append(sep);
601 urlbuffer.append(url);
604 Cache.setProperty(JWS2HOSTURLS, urlbuffer.toString());
608 Cache.removeProperty(JWS2HOSTURLS);
612 private static Vector<String> testUrls = null;
614 public static Vector<String> getServiceUrls()
616 if (testUrls != null)
618 // return test urls, if there are any, instead of touching cache
621 String surls = Cache.getDefault(JWS2HOSTURLS,
622 "http://www.compbio.dundee.ac.uk/jabaws");
623 Vector<String> urls = new Vector<String>();
626 StringTokenizer st = new StringTokenizer(surls, ",");
627 while (st.hasMoreElements())
632 java.net.URL u = new java.net.URL(url = st.nextToken());
633 if (!urls.contains(url))
639 jalview.bin.Cache.log.info("Ignoring duplicate url in "
640 + JWS2HOSTURLS + " list");
642 } catch (Exception ex)
644 jalview.bin.Cache.log
645 .warn("Problem whilst trying to make a URL from '"
646 + ((url != null) ? url : "<null>") + "'");
647 jalview.bin.Cache.log
648 .warn("This was probably due to a malformed comma separated list"
651 + " entry of $(HOME)/.jalview_properties)");
652 jalview.bin.Cache.log.debug("Exception was ", ex);
655 } catch (Exception ex)
657 jalview.bin.Cache.log.warn(
658 "Error parsing comma separated list of urls in "
659 + JWS2HOSTURLS + " preference.", ex);
661 if (urls.size() >= 0)
668 public Vector<Jws2Instance> getServices()
670 return (services == null) ? new Vector<Jws2Instance>()
671 : new Vector<Jws2Instance>(services);
675 * test the given URL with the JabaWS test code
680 public static boolean testServiceUrl(URL foo)
684 compbio.ws.client.WSTester.main(new String[]
685 { "-h=" + foo.toString() });
686 } catch (Exception e)
690 } catch (OutOfMemoryError e)
704 * Start a fresh discovery thread and notify the given object when we're
705 * finished. Any known existing threads will be killed before this one is
708 * @param changeSupport2
711 public Thread startDiscoverer(PropertyChangeListener changeSupport2)
717 addPropertyChangeListener(changeSupport2);
718 Thread thr = new Thread(this);
723 Vector<String> invalidServiceUrls = null, urlsWithoutServices = null,
724 validServiceUrls = null;
727 * @return the invalidServiceUrls
729 public Vector<String> getInvalidServiceUrls()
731 return invalidServiceUrls;
735 * @return the urlsWithoutServices
737 public Vector<String> getUrlsWithoutServices()
739 return urlsWithoutServices;
743 * add an 'empty' JABA server to the list. Only servers not already in the
744 * 'bad URL' list will be added to this list.
748 public synchronized void addUrlwithnoservices(String jwsservers)
750 if (urlsWithoutServices == null)
752 urlsWithoutServices = new Vector<String>();
755 if ((invalidServiceUrls == null || !invalidServiceUrls
756 .contains(jwsservers))
757 && !urlsWithoutServices.contains(jwsservers))
759 urlsWithoutServices.add(jwsservers);
764 * add a bad URL to the list
768 public synchronized void addInvalidServiceUrl(String jwsservers)
770 if (invalidServiceUrls == null)
772 invalidServiceUrls = new Vector<String>();
774 if (!invalidServiceUrls.contains(jwsservers))
776 invalidServiceUrls.add(jwsservers);
782 * @return a human readable report of any problems with the service URLs used
785 public String getErrorMessages()
787 if (!isRunning() && !isAborted())
789 StringBuffer ermsg = new StringBuffer();
790 boolean list = false;
791 if (getInvalidServiceUrls() != null
792 && getInvalidServiceUrls().size() > 0)
794 ermsg.append("URLs that could not be contacted: \n");
795 for (String svcurl : getInvalidServiceUrls())
802 ermsg.append(svcurl);
804 ermsg.append("\n\n");
807 if (getUrlsWithoutServices() != null
808 && getUrlsWithoutServices().size() > 0)
810 ermsg.append("URLs without any JABA Services : \n");
811 for (String svcurl : getUrlsWithoutServices())
818 ermsg.append(svcurl);
822 if (ermsg.length() > 1)
824 return ermsg.toString();
831 public int getServerStatusFor(String url)
833 if (validServiceUrls != null && validServiceUrls.contains(url))
837 if (urlsWithoutServices != null && urlsWithoutServices.contains(url))
839 if (invalidServiceUrls != null && invalidServiceUrls.contains(url))
847 * pick the user's preferred service based on a set of URLs (jaba server
848 * locations) and service URIs (specifying version and service interface
852 * @return null or best match for given uri/ls.
854 public Jws2Instance getPreferredServiceFor(String[] serviceURLs)
856 HashSet<String> urls = new HashSet<String>();
857 urls.addAll(Arrays.asList(serviceURLs));
858 Jws2Instance match = null;
859 if (services != null)
861 for (Jws2Instance svc : services)
863 if (urls.contains(svc.getServiceTypeURI()))
867 // for moment we always pick service from server ordered first in
868 // user's preferences
871 if (urls.contains(svc.getUri()))
873 // stop and return - we've matched type URI and URI for service
883 Map<String, Map<String, String>> preferredServiceMap = new HashMap<String, Map<String, String>>();;
886 * get current preferred service of the given type, or global default
889 * null or a specific alignFrame
891 * Jws2Instance.serviceType for service
892 * @return null if no service of this type is available, the preferred service
893 * for the serviceType and af if specified and if defined.
895 public Jws2Instance getPreferredServiceFor(AlignFrame af,
898 String serviceurl = null;
899 synchronized (preferredServiceMap)
901 String afid = (af == null) ? "" : af.getViewport().getSequenceSetId();
902 Map<String, String> prefmap = preferredServiceMap.get(afid);
903 if (afid.length() > 0 && prefmap == null)
905 // recover global setting, if any
906 prefmap = preferredServiceMap.get("");
910 serviceurl = prefmap.get(serviceType);
914 Jws2Instance response = null;
915 for (Jws2Instance svc : services)
917 if (svc.serviceType.equals(serviceType))
919 if (serviceurl == null || serviceurl.equals(svc.getHost()))
929 public void setPreferredServiceFor(AlignFrame af, String serviceType,
930 String serviceAction, Jws2Instance selectedServer)
932 String afid = (af == null) ? "" : af.getViewport().getSequenceSetId();
933 if (preferredServiceMap == null)
935 preferredServiceMap = new HashMap<String, Map<String, String>>();
937 Map<String, String> prefmap = preferredServiceMap.get(afid);
940 prefmap = new HashMap<String, String>();
941 preferredServiceMap.put(afid, prefmap);
943 prefmap.put(serviceType, selectedServer.getHost());
944 prefmap.put(serviceAction, selectedServer.getHost());
947 public void setPreferredServiceFor(String serviceType,
948 String serviceAction, Jws2Instance selectedServer)
950 setPreferredServiceFor(null, serviceType, serviceAction, selectedServer);