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.");
131 changeSupport.firePropertyChange("services", services, new Vector());
132 oldthread = Thread.currentThread();
135 Class foo = getClass().getClassLoader().loadClass(
136 "compbio.ws.client.Jws2Client");
137 } catch (ClassNotFoundException e)
140 .println("Not enabling JABA Webservices : client jar is not available."
141 + "\nPlease check that your webstart JNLP file is up to date!");
145 // reinitialise records of good and bad service URLs
146 if (services != null)
148 services.removeAllElements();
150 if (urlsWithoutServices != null)
152 urlsWithoutServices.removeAllElements();
154 if (invalidServiceUrls != null)
156 invalidServiceUrls.removeAllElements();
158 if (validServiceUrls != null)
160 validServiceUrls.removeAllElements();
162 ArrayList<String> svctypes = new ArrayList<String>();
164 List<JabaWsServerQuery> qrys = new ArrayList<JabaWsServerQuery>();
165 for (final String jwsservers : getServiceUrls())
167 JabaWsServerQuery squery = new JabaWsServerQuery(this, jwsservers);
168 if (svctypes.size() == 0)
170 // TODO: remove this ugly hack to get Canonical JABA service ordering
171 // for all possible services
172 for (Services sv : squery.JABAWS2SERVERS)
174 svctypes.add(sv.toString());
179 new Thread(squery).start();
181 boolean finished = true;
188 } catch (Exception e)
192 for (JabaWsServerQuery squery : qrys)
194 if (squery.isRunning()){
200 Cache.log.debug("Aborting " + qrys.size()
201 + " JABAWS discovery threads.");
202 for (JabaWsServerQuery squery : qrys)
204 squery.setQuit(true);
207 } while (!aborted && !finished);
210 // resort services according to order found in jabaws service list
211 // also ensure servics for each host are ordered in same way.
213 if (services != null && services.size() > 0)
215 Jws2Instance[] svcs = new Jws2Instance[services.size()];
216 int[] spos = new int[services.size()];
218 Vector svcUrls = getServiceUrls();
219 for (Jws2Instance svc : services)
222 spos[ipos++] = 1000 * svcUrls.indexOf(svc.getHost()) + 1
223 + svctypes.indexOf(svc.serviceType);
225 jalview.util.QuickSort.sort(spos, svcs);
226 services = new Vector<Jws2Instance>();
227 for (Jws2Instance svc : svcs)
235 changeSupport.firePropertyChange("services", new Vector(), services);
239 * record this service endpoint so we can use it
245 synchronized void addService(String jwsservers, Jws2Instance service)
247 if (services == null)
249 services = new Vector<Jws2Instance>();
251 System.out.println("Discovered service: " + jwsservers + " "
252 + service.toString());
253 // Jws2Instance service = new Jws2Instance(jwsservers, srv.toString(),
256 services.add(service);
257 // retrieve the presets and parameter set and cache now
258 ParamDatastoreI pds = service.getParamStore();
263 service.hasParameters();
264 if (validServiceUrls == null)
266 validServiceUrls = new Vector();
268 validServiceUrls.add(jwsservers);
272 * holds list of services.
274 protected Vector<Jws2Instance> services;
277 * attach all available web services to the appropriate submenu in the given
280 public void attachWSMenuEntry(JMenu wsmenu, final AlignFrame alignFrame)
282 // dynamically regenerate service list.
283 populateWSMenuEntry(wsmenu, alignFrame, null);
286 private boolean isRecalculable(String action)
288 return (action != null && action.equalsIgnoreCase("conservation"));
291 private void populateWSMenuEntry(JMenu jws2al,
292 final AlignFrame alignFrame, String typeFilter)
294 if (running || services == null || services.size() == 0)
298 boolean byhost = Cache.getDefault("WSMENU_BYHOST", false), bytype = Cache
299 .getDefault("WSMENU_BYTYPE", false);
301 * eventually, JWS2 services will appear under the same align/etc submenus.
302 * for moment we keep them separate.
305 List<Jws2Instance> enumerableServices = new ArrayList<Jws2Instance>();
306 // jws2al.removeAll();
307 Map<String, Jws2Instance> preferredHosts = new HashMap<String, Jws2Instance>();
308 Map<String, List<Jws2Instance>> alternates = new HashMap<String, List<Jws2Instance>>();
309 for (Jws2Instance service : services.toArray(new Jws2Instance[0]))
311 if (!isRecalculable(service.action))
313 // add 'one shot' services to be displayed using the classic menu
315 enumerableServices.add(service);
319 if (!preferredHosts.containsKey(service.serviceType))
321 Jws2Instance preferredInstance = getPreferredServiceFor(
322 alignFrame, service.serviceType);
323 if (preferredInstance != null)
325 preferredHosts.put(service.serviceType, preferredInstance);
329 preferredHosts.put(service.serviceType, service);
332 List<Jws2Instance> ph = alternates.get(service.serviceType);
333 if (preferredHosts.get(service.serviceType) != service)
337 ph = new ArrayList<Jws2Instance>();
340 alternates.put(service.serviceType, ph);
346 // create GUI element for classic services
347 addEnumeratedServices(jws2al, alignFrame, enumerableServices);
348 // and the instantaneous services
349 for (final Jws2Instance service : preferredHosts.values())
351 atpoint = JvSwingUtils.findOrCreateMenu(jws2al, service.action);
353 if (atpoint.getItemCount() > 1)
355 // previous service of this type already present
356 atpoint.addSeparator();
358 atpoint.add(hitm = new JMenuItem(service.getHost()));
359 hitm.setForeground(Color.blue);
360 hitm.addActionListener(new ActionListener()
364 public void actionPerformed(ActionEvent e)
366 Desktop.showUrl(service.getHost());
369 hitm.setToolTipText(JvSwingUtils
370 .wrapTooltip("Opens the JABAWS server's homepage in web browser"));
372 service.attachWSMenuEntry(atpoint, alignFrame);
373 if (alternates.containsKey(service.serviceType))
375 atpoint.add(hitm = new JMenu("Switch server"));
376 hitm.setToolTipText(JvSwingUtils
377 .wrapTooltip("Choose a server for running this service"));
378 for (final Jws2Instance sv : alternates.get(service.serviceType))
381 hitm.add(itm = new JMenuItem(sv.getHost()));
382 itm.setForeground(Color.blue);
383 itm.addActionListener(new ActionListener()
387 public void actionPerformed(ActionEvent arg0)
389 new Thread(new Runnable()
393 setPreferredServiceFor(alignFrame, sv.serviceType,
395 changeSupport.firePropertyChange("services",
396 new Vector(), services);
404 * hitm.addActionListener(new ActionListener() {
406 * @Override public void actionPerformed(ActionEvent arg0) { new
407 * Thread(new Runnable() {
409 * @Override public void run() { new SetPreferredServer(alignFrame,
410 * service.serviceType, service.action); } }).start(); } });
417 * add services using the Java 2.5/2.6/2.7 system which optionally creates
418 * submenus to index by host and service program type
420 private void addEnumeratedServices(final JMenu jws2al,
421 final AlignFrame alignFrame, List<Jws2Instance> enumerableServices)
423 boolean byhost = Cache.getDefault("WSMENU_BYHOST", false), bytype = Cache
424 .getDefault("WSMENU_BYTYPE", false);
426 * eventually, JWS2 services will appear under the same align/etc submenus.
427 * for moment we keep them separate.
430 MsaWSClient msacl = new MsaWSClient();
431 List<String> hostLabels = new ArrayList<String>();
432 Hashtable<String, String> lasthostFor = new Hashtable<String, String>();
433 Hashtable<String, ArrayList<Jws2Instance>> hosts = new Hashtable<String, ArrayList<Jws2Instance>>();
434 ArrayList<String> hostlist = new ArrayList<String>();
435 for (Jws2Instance service : enumerableServices)
437 ArrayList<Jws2Instance> hostservices = hosts.get(service.getHost());
438 if (hostservices == null)
440 hosts.put(service.getHost(),
441 hostservices = new ArrayList<Jws2Instance>());
442 hostlist.add(service.getHost());
444 hostservices.add(service);
446 // now add hosts in order of the given array
447 for (String host : hostlist)
449 Jws2Instance orderedsvcs[] = hosts.get(host).toArray(
450 new Jws2Instance[1]);
451 String sortbytype[] = new String[orderedsvcs.length];
452 for (int i = 0; i < sortbytype.length; i++)
454 sortbytype[i] = orderedsvcs[i].serviceType;
456 jalview.util.QuickSort.sort(sortbytype, orderedsvcs);
457 for (final Jws2Instance service : orderedsvcs)
459 atpoint = JvSwingUtils.findOrCreateMenu(jws2al, service.action);
460 String type = service.serviceType;
463 atpoint = JvSwingUtils.findOrCreateMenu(atpoint, host);
464 if (atpoint.getToolTipText() == null)
466 atpoint.setToolTipText("Services at " + host);
471 atpoint = JvSwingUtils.findOrCreateMenu(atpoint, type);
472 if (atpoint.getToolTipText() == null)
474 atpoint.setToolTipText(service.getActionText());
478 && !hostLabels.contains(host + service.serviceType
479 + service.getActionText()))
480 // !hostLabels.contains(host + (bytype ?
481 // service.serviceType+service.getActionText() : "")))
483 // add a marker indicating where this service is hosted
484 // relies on services from the same host being listed in a
488 if (hostLabels.contains(host))
490 atpoint.addSeparator();
494 hostLabels.add(host);
496 if (lasthostFor.get(service.action) == null
497 || !lasthostFor.get(service.action).equals(host))
499 atpoint.add(hitm = new JMenuItem(host));
500 hitm.setForeground(Color.blue);
501 hitm.addActionListener(new ActionListener()
505 public void actionPerformed(ActionEvent e)
507 Desktop.showUrl(service.getHost());
510 hitm.setToolTipText(JvSwingUtils
511 .wrapTooltip("Opens the JABAWS server's homepage in web browser"));
512 lasthostFor.put(service.action, host);
514 hostLabels.add(host + service.serviceType
515 + service.getActionText());
518 service.attachWSMenuEntry(atpoint, alignFrame);
523 public static void main(String[] args)
527 testUrls = new Vector<String>();
528 for (String url : args)
534 Thread runner = getDiscoverer().startDiscoverer(
535 new PropertyChangeListener()
538 public void propertyChange(PropertyChangeEvent evt)
540 if (getDiscoverer().services != null)
542 System.out.println("Changesupport: There are now "
543 + getDiscoverer().services.size() + " services");
545 for (Jws2Instance instance : getDiscoverer().services)
547 System.out.println("Service " + i++ + " "
548 + instance.getClass() + "@"
549 + instance.getHost() + ": "
550 + instance.getActionText());
556 while (runner.isAlive())
561 } catch (InterruptedException e)
569 } catch (InterruptedException x)
574 private static Jws2Discoverer discoverer;
576 public static Jws2Discoverer getDiscoverer()
578 if (discoverer == null)
580 discoverer = new Jws2Discoverer();
585 public boolean hasServices()
587 // TODO Auto-generated method stub
588 return !running && services != null && services.size() > 0;
591 public boolean isRunning()
597 * the jalview .properties entry for JWS2 URLS
599 final static String JWS2HOSTURLS = "JWS2HOSTURLS";
601 public static void setServiceUrls(Vector<String> urls)
605 StringBuffer urlbuffer = new StringBuffer();
607 for (String url : urls)
609 urlbuffer.append(sep);
610 urlbuffer.append(url);
613 Cache.setProperty(JWS2HOSTURLS, urlbuffer.toString());
617 Cache.removeProperty(JWS2HOSTURLS);
621 private static Vector<String> testUrls = null;
623 public static Vector<String> getServiceUrls()
625 if (testUrls != null)
627 // return test urls, if there are any, instead of touching cache
630 String surls = Cache.getDefault(JWS2HOSTURLS,
631 "http://www.compbio.dundee.ac.uk/jabaws");
632 Vector<String> urls = new Vector<String>();
635 StringTokenizer st = new StringTokenizer(surls, ",");
636 while (st.hasMoreElements())
641 java.net.URL u = new java.net.URL(url = st.nextToken());
642 if (!urls.contains(url))
648 jalview.bin.Cache.log.info("Ignoring duplicate url in "
649 + JWS2HOSTURLS + " list");
651 } catch (Exception ex)
653 jalview.bin.Cache.log
654 .warn("Problem whilst trying to make a URL from '"
655 + ((url != null) ? url : "<null>") + "'");
656 jalview.bin.Cache.log
657 .warn("This was probably due to a malformed comma separated list"
660 + " entry of $(HOME)/.jalview_properties)");
661 jalview.bin.Cache.log.debug("Exception was ", ex);
664 } catch (Exception ex)
666 jalview.bin.Cache.log.warn(
667 "Error parsing comma separated list of urls in "
668 + JWS2HOSTURLS + " preference.", ex);
670 if (urls.size() >= 0)
677 public Vector<Jws2Instance> getServices()
679 return (services == null) ? new Vector<Jws2Instance>()
680 : new Vector<Jws2Instance>(services);
684 * test the given URL with the JabaWS test code
689 public static boolean testServiceUrl(URL foo)
693 compbio.ws.client.WSTester.main(new String[]
694 { "-h=" + foo.toString() });
695 } catch (Exception e)
699 } catch (OutOfMemoryError e)
713 * Start a fresh discovery thread and notify the given object when we're
714 * finished. Any known existing threads will be killed before this one is
717 * @param changeSupport2
720 public Thread startDiscoverer(PropertyChangeListener changeSupport2)
726 addPropertyChangeListener(changeSupport2);
727 Thread thr = new Thread(this);
732 Vector<String> invalidServiceUrls = null, urlsWithoutServices = null,
733 validServiceUrls = null;
736 * @return the invalidServiceUrls
738 public Vector<String> getInvalidServiceUrls()
740 return invalidServiceUrls;
744 * @return the urlsWithoutServices
746 public Vector<String> getUrlsWithoutServices()
748 return urlsWithoutServices;
752 * add an 'empty' JABA server to the list. Only servers not already in the
753 * 'bad URL' list will be added to this list.
757 public synchronized void addUrlwithnoservices(String jwsservers)
759 if (urlsWithoutServices == null)
761 urlsWithoutServices = new Vector<String>();
764 if ((invalidServiceUrls == null || !invalidServiceUrls
765 .contains(jwsservers))
766 && !urlsWithoutServices.contains(jwsservers))
768 urlsWithoutServices.add(jwsservers);
773 * add a bad URL to the list
777 public synchronized void addInvalidServiceUrl(String jwsservers)
779 if (invalidServiceUrls == null)
781 invalidServiceUrls = new Vector<String>();
783 if (!invalidServiceUrls.contains(jwsservers))
785 invalidServiceUrls.add(jwsservers);
791 * @return a human readable report of any problems with the service URLs used
794 public String getErrorMessages()
796 if (!isRunning() && !isAborted())
798 StringBuffer ermsg = new StringBuffer();
799 boolean list = false;
800 if (getInvalidServiceUrls() != null
801 && getInvalidServiceUrls().size() > 0)
803 ermsg.append("URLs that could not be contacted: \n");
804 for (String svcurl : getInvalidServiceUrls())
811 ermsg.append(svcurl);
813 ermsg.append("\n\n");
816 if (getUrlsWithoutServices() != null
817 && getUrlsWithoutServices().size() > 0)
819 ermsg.append("URLs without any JABA Services : \n");
820 for (String svcurl : getUrlsWithoutServices())
827 ermsg.append(svcurl);
831 if (ermsg.length() > 1)
833 return ermsg.toString();
840 public int getServerStatusFor(String url)
842 if (validServiceUrls != null && validServiceUrls.contains(url))
846 if (urlsWithoutServices != null && urlsWithoutServices.contains(url))
848 if (invalidServiceUrls != null && invalidServiceUrls.contains(url))
856 * pick the user's preferred service based on a set of URLs (jaba server
857 * locations) and service URIs (specifying version and service interface
861 * @return null or best match for given uri/ls.
863 public Jws2Instance getPreferredServiceFor(String[] serviceURLs)
865 HashSet<String> urls = new HashSet<String>();
866 urls.addAll(Arrays.asList(serviceURLs));
867 Jws2Instance match = null;
868 if (services != null)
870 for (Jws2Instance svc : services)
872 if (urls.contains(svc.getServiceTypeURI()))
876 // for moment we always pick service from server ordered first in
877 // user's preferences
880 if (urls.contains(svc.getUri()))
882 // stop and return - we've matched type URI and URI for service
892 Map<String, Map<String, String>> preferredServiceMap = new HashMap<String, Map<String, String>>();;
895 * get current preferred service of the given type, or global default
898 * null or a specific alignFrame
900 * Jws2Instance.serviceType for service
901 * @return null if no service of this type is available, the preferred service
902 * for the serviceType and af if specified and if defined.
904 public Jws2Instance getPreferredServiceFor(AlignFrame af,
907 String serviceurl = null;
908 synchronized (preferredServiceMap)
910 String afid = (af == null) ? "" : af.getViewport().getSequenceSetId();
911 Map<String, String> prefmap = preferredServiceMap.get(afid);
912 if (afid.length() > 0 && prefmap == null)
914 // recover global setting, if any
915 prefmap = preferredServiceMap.get("");
919 serviceurl = prefmap.get(serviceType);
923 Jws2Instance response = null;
924 for (Jws2Instance svc : services)
926 if (svc.serviceType.equals(serviceType))
928 if (serviceurl == null || serviceurl.equals(svc.getHost()))
938 public void setPreferredServiceFor(AlignFrame af, String serviceType,
939 String serviceAction, Jws2Instance selectedServer)
941 String afid = (af == null) ? "" : af.getViewport().getSequenceSetId();
942 if (preferredServiceMap == null)
944 preferredServiceMap = new HashMap<String, Map<String, String>>();
946 Map<String, String> prefmap = preferredServiceMap.get(afid);
949 prefmap = new HashMap<String, String>();
950 preferredServiceMap.put(afid, prefmap);
952 prefmap.put(serviceType, selectedServer.getHost());
953 prefmap.put(serviceAction, selectedServer.getHost());
956 public void setPreferredServiceFor(String serviceType,
957 String serviceAction, Jws2Instance selectedServer)
959 setPreferredServiceFor(null, serviceType, serviceAction, selectedServer);