2 * Jalview - A Sequence Alignment Editor and Viewer ($$Version-Rel$$)
3 * Copyright (C) $$Year-Rel$$ 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.util.MessageManager;
28 import jalview.ws.WSMenuEntryProviderI;
29 import jalview.ws.jws2.jabaws2.Jws2Instance;
30 import jalview.ws.params.ParamDatastoreI;
32 import java.awt.Color;
33 import java.awt.event.ActionEvent;
34 import java.awt.event.ActionListener;
35 import java.beans.PropertyChangeEvent;
36 import java.beans.PropertyChangeListener;
37 import java.beans.PropertyChangeSupport;
38 import java.net.MalformedURLException;
40 import java.util.ArrayList;
41 import java.util.Arrays;
42 import java.util.HashMap;
43 import java.util.HashSet;
44 import java.util.Hashtable;
45 import java.util.List;
48 import java.util.StringTokenizer;
49 import java.util.Vector;
51 import javax.swing.JMenu;
52 import javax.swing.JMenuItem;
54 import compbio.ws.client.Services;
57 * discoverer for jws2 services. Follows the lightweight service discoverer
58 * pattern (archetyped by EnfinEnvision2OneWay)
63 public class Jws2Discoverer implements Runnable, WSMenuEntryProviderI
65 public static final String COMPBIO_JABAWS = "http://www.compbio.dundee.ac.uk/jabaws";
68 * the .jalview_properties entry for JWS2 URLS
70 final static String JWS2HOSTURLS = "JWS2HOSTURLS";
75 private static Jws2Discoverer discoverer;
78 * Override for testing only
80 private static List<String> testUrls = null;
82 // preferred url has precedence over others
83 private String preferredUrl;
85 private PropertyChangeSupport changeSupport = new PropertyChangeSupport(
88 Vector<String> invalidServiceUrls = null, urlsWithoutServices = null,
89 validServiceUrls = null;
91 boolean running = false, aborted = false;
93 Thread oldthread = null;
96 * holds list of services.
98 protected Vector<Jws2Instance> services;
101 * Private constructor enforces use of singleton via getDiscoverer()
103 private Jws2Discoverer()
108 * change listeners are notified of "services" property changes
111 * to be added that consumes new services Hashtable object.
113 public void addPropertyChangeListener(
114 java.beans.PropertyChangeListener listener)
116 changeSupport.addPropertyChangeListener(listener);
125 public void removePropertyChangeListener(
126 java.beans.PropertyChangeListener listener)
128 changeSupport.removePropertyChangeListener(listener);
132 * @return the aborted
134 public boolean isAborted()
143 public void setAborted(boolean aborted)
145 this.aborted = aborted;
152 if (running && oldthread != null && oldthread.isAlive())
163 .debug("Waiting around for old discovery thread to finish.");
164 // wait around until old discoverer dies
166 } catch (Exception e)
170 Cache.log.debug("Old discovery thread has finished.");
174 // first set up exclusion list if needed
175 final Set<String> ignoredServices = new HashSet<String>();
176 for (String ignored : Cache.getDefault("IGNORED_JABAWS_SERVICETYPES",
179 ignoredServices.add(ignored);
182 changeSupport.firePropertyChange("services", services, new Vector());
183 oldthread = Thread.currentThread();
186 Class foo = getClass().getClassLoader().loadClass(
187 "compbio.ws.client.Jws2Client");
188 } catch (ClassNotFoundException e)
191 .println("Not enabling JABA Webservices : client jar is not available."
192 + "\nPlease check that your webstart JNLP file is up to date!");
196 // reinitialise records of good and bad service URLs
197 if (services != null)
199 services.removeAllElements();
201 if (urlsWithoutServices != null)
203 urlsWithoutServices.removeAllElements();
205 if (invalidServiceUrls != null)
207 invalidServiceUrls.removeAllElements();
209 if (validServiceUrls != null)
211 validServiceUrls.removeAllElements();
213 ArrayList<String> svctypes = new ArrayList<String>();
215 List<JabaWsServerQuery> qrys = new ArrayList<JabaWsServerQuery>();
216 for (final String jwsserver : getServiceUrls())
218 JabaWsServerQuery squery = new JabaWsServerQuery(this, jwsserver);
219 if (svctypes.size() == 0)
221 // TODO: remove this ugly hack to get Canonical JABA service ordering
222 // for all possible services
223 for (Services sv : squery.JABAWS2SERVERS)
225 if (!ignoredServices.contains(sv.toString()))
227 svctypes.add(sv.toString());
233 new Thread(squery).start();
235 boolean finished = true;
242 } catch (Exception e)
246 for (JabaWsServerQuery squery : qrys)
248 if (squery.isRunning())
255 Cache.log.debug("Aborting " + qrys.size()
256 + " JABAWS discovery threads.");
257 for (JabaWsServerQuery squery : qrys)
259 squery.setQuit(true);
262 } while (!aborted && !finished);
265 // resort services according to order found in jabaws service list
266 // also ensure servics for each host are ordered in same way.
268 if (services != null && services.size() > 0)
270 Jws2Instance[] svcs = new Jws2Instance[services.size()];
271 int[] spos = new int[services.size()];
273 List<String> svcUrls = getServiceUrls();
274 for (Jws2Instance svc : services)
277 spos[ipos++] = 1000 * svcUrls.indexOf(svc.getHost()) + 1
278 + svctypes.indexOf(svc.serviceType);
280 jalview.util.QuickSort.sort(spos, svcs);
281 services = new Vector<Jws2Instance>();
282 for (Jws2Instance svc : svcs)
284 if (!ignoredServices.contains(svc.serviceType))
293 changeSupport.firePropertyChange("services", new Vector(), services);
297 * record this service endpoint so we can use it
303 synchronized void addService(String jwsservers, Jws2Instance service)
305 if (services == null)
307 services = new Vector<Jws2Instance>();
309 System.out.println("Discovered service: " + jwsservers + " "
310 + service.toString());
311 // Jws2Instance service = new Jws2Instance(jwsservers, srv.toString(),
314 services.add(service);
315 // retrieve the presets and parameter set and cache now
316 ParamDatastoreI pds = service.getParamStore();
321 service.hasParameters();
322 if (validServiceUrls == null)
324 validServiceUrls = new Vector();
326 validServiceUrls.add(jwsservers);
330 * attach all available web services to the appropriate submenu in the given
333 public void attachWSMenuEntry(JMenu wsmenu, final AlignFrame alignFrame)
335 // dynamically regenerate service list.
336 populateWSMenuEntry(wsmenu, alignFrame, null);
339 private boolean isRecalculable(String action)
341 return (action != null && action.equalsIgnoreCase("conservation"));
344 private void populateWSMenuEntry(JMenu jws2al,
345 final AlignFrame alignFrame, String typeFilter)
347 if (running || services == null || services.size() == 0)
351 boolean byhost = Cache.getDefault("WSMENU_BYHOST", false), bytype = Cache
352 .getDefault("WSMENU_BYTYPE", false);
354 * eventually, JWS2 services will appear under the same align/etc submenus.
355 * for moment we keep them separate.
358 List<Jws2Instance> enumerableServices = new ArrayList<Jws2Instance>();
359 // jws2al.removeAll();
360 Map<String, Jws2Instance> preferredHosts = new HashMap<String, Jws2Instance>();
361 Map<String, List<Jws2Instance>> alternates = new HashMap<String, List<Jws2Instance>>();
362 for (Jws2Instance service : services.toArray(new Jws2Instance[0]))
364 if (!isRecalculable(service.action))
366 // add 'one shot' services to be displayed using the classic menu
368 enumerableServices.add(service);
372 if (!preferredHosts.containsKey(service.serviceType))
374 Jws2Instance preferredInstance = getPreferredServiceFor(
375 alignFrame, service.serviceType);
376 if (preferredInstance != null)
378 preferredHosts.put(service.serviceType, preferredInstance);
382 preferredHosts.put(service.serviceType, service);
385 List<Jws2Instance> ph = alternates.get(service.serviceType);
386 if (preferredHosts.get(service.serviceType) != service)
390 ph = new ArrayList<Jws2Instance>();
393 alternates.put(service.serviceType, ph);
399 // create GUI element for classic services
400 addEnumeratedServices(jws2al, alignFrame, enumerableServices);
401 // and the instantaneous services
402 for (final Jws2Instance service : preferredHosts.values())
404 atpoint = JvSwingUtils.findOrCreateMenu(jws2al, service.action);
406 if (atpoint.getItemCount() > 1)
408 // previous service of this type already present
409 atpoint.addSeparator();
411 atpoint.add(hitm = new JMenuItem(service.getHost()));
412 hitm.setForeground(Color.blue);
413 hitm.addActionListener(new ActionListener()
417 public void actionPerformed(ActionEvent e)
419 Desktop.showUrl(service.getHost());
422 hitm.setToolTipText(JvSwingUtils.wrapTooltip(false,
423 MessageManager.getString("label.open_jabaws_web_page")));
425 service.attachWSMenuEntry(atpoint, alignFrame);
426 if (alternates.containsKey(service.serviceType))
428 atpoint.add(hitm = new JMenu(MessageManager
429 .getString("label.switch_server")));
430 hitm.setToolTipText(JvSwingUtils.wrapTooltip(false,
431 MessageManager.getString("label.choose_jabaws_server")));
432 for (final Jws2Instance sv : alternates.get(service.serviceType))
435 hitm.add(itm = new JMenuItem(sv.getHost()));
436 itm.setForeground(Color.blue);
437 itm.addActionListener(new ActionListener()
441 public void actionPerformed(ActionEvent arg0)
443 new Thread(new Runnable()
447 setPreferredServiceFor(alignFrame, sv.serviceType,
449 changeSupport.firePropertyChange("services",
450 new Vector(), services);
458 * hitm.addActionListener(new ActionListener() {
460 * @Override public void actionPerformed(ActionEvent arg0) { new
461 * Thread(new Runnable() {
463 * @Override public void run() { new SetPreferredServer(alignFrame,
464 * service.serviceType, service.action); } }).start(); } });
471 * add services using the Java 2.5/2.6/2.7 system which optionally creates
472 * submenus to index by host and service program type
474 private void addEnumeratedServices(final JMenu jws2al,
475 final AlignFrame alignFrame, List<Jws2Instance> enumerableServices)
477 boolean byhost = Cache.getDefault("WSMENU_BYHOST", false), bytype = Cache
478 .getDefault("WSMENU_BYTYPE", false);
480 * eventually, JWS2 services will appear under the same align/etc submenus.
481 * for moment we keep them separate.
484 MsaWSClient msacl = new MsaWSClient();
485 List<String> hostLabels = new ArrayList<String>();
486 Hashtable<String, String> lasthostFor = new Hashtable<String, String>();
487 Hashtable<String, ArrayList<Jws2Instance>> hosts = new Hashtable<String, ArrayList<Jws2Instance>>();
488 ArrayList<String> hostlist = new ArrayList<String>();
489 for (Jws2Instance service : enumerableServices)
491 ArrayList<Jws2Instance> hostservices = hosts.get(service.getHost());
492 if (hostservices == null)
494 hosts.put(service.getHost(),
495 hostservices = new ArrayList<Jws2Instance>());
496 hostlist.add(service.getHost());
498 hostservices.add(service);
500 // now add hosts in order of the given array
501 for (String host : hostlist)
503 Jws2Instance orderedsvcs[] = hosts.get(host).toArray(
504 new Jws2Instance[1]);
505 String sortbytype[] = new String[orderedsvcs.length];
506 for (int i = 0; i < sortbytype.length; i++)
508 sortbytype[i] = orderedsvcs[i].serviceType;
510 jalview.util.QuickSort.sort(sortbytype, orderedsvcs);
511 for (final Jws2Instance service : orderedsvcs)
513 atpoint = JvSwingUtils.findOrCreateMenu(jws2al, service.action);
514 String type = service.serviceType;
517 atpoint = JvSwingUtils.findOrCreateMenu(atpoint, host);
518 if (atpoint.getToolTipText() == null)
520 atpoint.setToolTipText(MessageManager.formatMessage(
521 "label.services_at", new String[] { host }));
526 atpoint = JvSwingUtils.findOrCreateMenu(atpoint, type);
527 if (atpoint.getToolTipText() == null)
529 atpoint.setToolTipText(service.getActionText());
533 && !hostLabels.contains(host + service.serviceType
534 + service.getActionText()))
535 // !hostLabels.contains(host + (bytype ?
536 // service.serviceType+service.getActionText() : "")))
538 // add a marker indicating where this service is hosted
539 // relies on services from the same host being listed in a
543 if (hostLabels.contains(host))
545 atpoint.addSeparator();
549 hostLabels.add(host);
551 if (lasthostFor.get(service.action) == null
552 || !lasthostFor.get(service.action).equals(host))
554 atpoint.add(hitm = new JMenuItem(host));
555 hitm.setForeground(Color.blue);
556 hitm.addActionListener(new ActionListener()
560 public void actionPerformed(ActionEvent e)
562 Desktop.showUrl(service.getHost());
565 hitm.setToolTipText(JvSwingUtils.wrapTooltip(true,
566 MessageManager.getString("label.open_jabaws_web_page")));
567 lasthostFor.put(service.action, host);
569 hostLabels.add(host + service.serviceType
570 + service.getActionText());
573 service.attachWSMenuEntry(atpoint, alignFrame);
578 public static void main(String[] args)
582 testUrls = new ArrayList<String>();
583 for (String url : args)
589 Thread runner = getDiscoverer().startDiscoverer(
590 new PropertyChangeListener()
593 public void propertyChange(PropertyChangeEvent evt)
595 if (getDiscoverer().services != null)
597 System.out.println("Changesupport: There are now "
598 + getDiscoverer().services.size() + " services");
600 for (Jws2Instance instance : getDiscoverer().services)
602 System.out.println("Service " + i++ + " "
603 + instance.getClass() + "@"
604 + instance.getHost() + ": "
605 + instance.getActionText());
611 while (runner.isAlive())
616 } catch (InterruptedException e)
624 } catch (InterruptedException x)
630 * Returns the singleton instance of this class.
634 public static Jws2Discoverer getDiscoverer()
636 if (discoverer == null)
638 discoverer = new Jws2Discoverer();
643 public boolean hasServices()
645 return !running && services != null && services.size() > 0;
648 public boolean isRunning()
653 public void setServiceUrls(List<String> wsUrls)
655 if (wsUrls != null && !wsUrls.isEmpty())
657 StringBuilder urls = new StringBuilder(128);
659 for (String url : wsUrls)
665 Cache.setProperty(JWS2HOSTURLS, urls.toString());
669 Cache.removeProperty(JWS2HOSTURLS);
674 * Returns web service URLs, in the order in which they should be tried (or an
679 public List<String> getServiceUrls()
681 if (testUrls != null)
683 // return test urls, if there are any, instead of touching cache
686 List<String> urls = new ArrayList<String>();
688 if (this.preferredUrl != null)
690 urls.add(preferredUrl);
693 String surls = Cache.getDefault(JWS2HOSTURLS, COMPBIO_JABAWS);
696 StringTokenizer st = new StringTokenizer(surls, ",");
697 while (st.hasMoreElements())
702 url = st.nextToken();
704 if (!urls.contains(url))
710 Cache.log.warn("Ignoring duplicate url " + url + " in "
711 + JWS2HOSTURLS + " list");
713 } catch (MalformedURLException ex)
715 Cache.log.warn("Problem whilst trying to make a URL from '"
716 + ((url != null) ? url : "<null>") + "'");
718 .warn("This was probably due to a malformed comma separated list"
721 + " entry of $(HOME)/.jalview_properties)");
722 Cache.log.debug("Exception was ", ex);
725 } catch (Exception ex)
727 Cache.log.warn("Error parsing comma separated list of urls in "
728 + JWS2HOSTURLS + " preference.", ex);
733 public Vector<Jws2Instance> getServices()
735 return (services == null) ? new Vector<Jws2Instance>()
736 : new Vector<Jws2Instance>(services);
740 * test the given URL with the JabaWS test code
745 public static boolean testServiceUrl(URL foo)
749 compbio.ws.client.WSTester
750 .main(new String[] { "-h=" + foo.toString() });
751 } catch (Exception e)
755 } catch (OutOfMemoryError e)
769 * Start a fresh discovery thread and notify the given object when we're
770 * finished. Any known existing threads will be killed before this one is
773 * @param changeSupport2
776 public Thread startDiscoverer(PropertyChangeListener changeSupport2)
782 addPropertyChangeListener(changeSupport2);
783 Thread thr = new Thread(this);
789 * @return the invalidServiceUrls
791 public Vector<String> getInvalidServiceUrls()
793 return invalidServiceUrls;
797 * @return the urlsWithoutServices
799 public Vector<String> getUrlsWithoutServices()
801 return urlsWithoutServices;
805 * add an 'empty' JABA server to the list. Only servers not already in the
806 * 'bad URL' list will be added to this list.
810 public synchronized void addUrlwithnoservices(String jwsservers)
812 if (urlsWithoutServices == null)
814 urlsWithoutServices = new Vector<String>();
817 if ((invalidServiceUrls == null || !invalidServiceUrls
818 .contains(jwsservers))
819 && !urlsWithoutServices.contains(jwsservers))
821 urlsWithoutServices.add(jwsservers);
826 * add a bad URL to the list
830 public synchronized void addInvalidServiceUrl(String jwsservers)
832 if (invalidServiceUrls == null)
834 invalidServiceUrls = new Vector<String>();
836 if (!invalidServiceUrls.contains(jwsservers))
838 invalidServiceUrls.add(jwsservers);
844 * @return a human readable report of any problems with the service URLs used
847 public String getErrorMessages()
849 if (!isRunning() && !isAborted())
851 StringBuffer ermsg = new StringBuffer();
852 boolean list = false;
853 if (getInvalidServiceUrls() != null
854 && getInvalidServiceUrls().size() > 0)
856 ermsg.append(MessageManager.getString("warn.urls_not_contacted")
858 for (String svcurl : getInvalidServiceUrls())
865 ermsg.append(svcurl);
867 ermsg.append("\n\n");
870 if (getUrlsWithoutServices() != null
871 && getUrlsWithoutServices().size() > 0)
873 ermsg.append(MessageManager.getString("warn.urls_no_jaba") + ": \n");
874 for (String svcurl : getUrlsWithoutServices())
881 ermsg.append(svcurl);
885 if (ermsg.length() > 1)
887 return ermsg.toString();
894 public int getServerStatusFor(String url)
896 if (validServiceUrls != null && validServiceUrls.contains(url))
900 if (urlsWithoutServices != null && urlsWithoutServices.contains(url))
904 if (invalidServiceUrls != null && invalidServiceUrls.contains(url))
912 * pick the user's preferred service based on a set of URLs (jaba server
913 * locations) and service URIs (specifying version and service interface
917 * @return null or best match for given uri/ls.
919 public Jws2Instance getPreferredServiceFor(String[] serviceURLs)
921 HashSet<String> urls = new HashSet<String>();
922 urls.addAll(Arrays.asList(serviceURLs));
923 Jws2Instance match = null;
924 if (services != null)
926 for (Jws2Instance svc : services)
928 if (urls.contains(svc.getServiceTypeURI()))
932 // for moment we always pick service from server ordered first in
933 // user's preferences
936 if (urls.contains(svc.getUri()))
938 // stop and return - we've matched type URI and URI for service
948 Map<String, Map<String, String>> preferredServiceMap = new HashMap<String, Map<String, String>>();;
951 * get current preferred service of the given type, or global default
954 * null or a specific alignFrame
956 * Jws2Instance.serviceType for service
957 * @return null if no service of this type is available, the preferred service
958 * for the serviceType and af if specified and if defined.
960 public Jws2Instance getPreferredServiceFor(AlignFrame af,
963 String serviceurl = null;
964 synchronized (preferredServiceMap)
966 String afid = (af == null) ? "" : af.getViewport().getSequenceSetId();
967 Map<String, String> prefmap = preferredServiceMap.get(afid);
968 if (afid.length() > 0 && prefmap == null)
970 // recover global setting, if any
971 prefmap = preferredServiceMap.get("");
975 serviceurl = prefmap.get(serviceType);
979 Jws2Instance response = null;
980 for (Jws2Instance svc : services)
982 if (svc.serviceType.equals(serviceType))
984 if (serviceurl == null || serviceurl.equals(svc.getHost()))
994 public void setPreferredServiceFor(AlignFrame af, String serviceType,
995 String serviceAction, Jws2Instance selectedServer)
997 String afid = (af == null) ? "" : af.getViewport().getSequenceSetId();
998 if (preferredServiceMap == null)
1000 preferredServiceMap = new HashMap<String, Map<String, String>>();
1002 Map<String, String> prefmap = preferredServiceMap.get(afid);
1003 if (prefmap == null)
1005 prefmap = new HashMap<String, String>();
1006 preferredServiceMap.put(afid, prefmap);
1008 prefmap.put(serviceType, selectedServer.getHost());
1009 prefmap.put(serviceAction, selectedServer.getHost());
1012 public void setPreferredServiceFor(String serviceType,
1013 String serviceAction, Jws2Instance selectedServer)
1015 setPreferredServiceFor(null, serviceType, serviceAction, selectedServer);
1019 * Set a URL to try before any others. For use with command-line parameter to
1020 * configure a local Jabaws installation without the need to add to property
1024 * @throws MalformedURLException
1026 public void setPreferredUrl(String value) throws MalformedURLException
1028 if (value != null && value.trim().length() > 0)
1031 preferredUrl = value;