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.");
129 changeSupport.firePropertyChange("services", services, new Vector());
130 oldthread = Thread.currentThread();
133 Class foo = getClass().getClassLoader().loadClass(
134 "compbio.ws.client.Jws2Client");
135 } catch (ClassNotFoundException e)
138 .println("Not enabling JABA Webservices : client jar is not available."
139 + "\nPlease check that your webstart JNLP file is up to date!");
143 // reinitialise records of good and bad service URLs
144 if (services != null)
146 services.removeAllElements();
148 if (urlsWithoutServices != null)
150 urlsWithoutServices.removeAllElements();
152 if (invalidServiceUrls != null)
154 invalidServiceUrls.removeAllElements();
156 if (validServiceUrls != null)
158 validServiceUrls.removeAllElements();
160 ArrayList<String> svctypes = new ArrayList<String>();
162 List<JabaWsServerQuery> qrys = new ArrayList<JabaWsServerQuery>();
163 for (final String jwsservers : getServiceUrls())
165 JabaWsServerQuery squery = new JabaWsServerQuery(this, jwsservers);
166 if (svctypes.size() == 0)
168 // TODO: remove this ugly hack to get Canonical JABA service ordering
169 // for all possible services
170 for (Services sv : squery.JABAWS2SERVERS)
172 svctypes.add(sv.toString());
177 new Thread(squery).start();
179 boolean finished = true;
186 } catch (Exception e)
190 for (JabaWsServerQuery squery : qrys)
192 finished = finished && !squery.isRunning();
196 Cache.log.debug("Aborting " + qrys.size()
197 + " JABAWS discovery threads.");
198 for (JabaWsServerQuery squery : qrys)
200 squery.setQuit(true);
203 } while (!aborted && !finished);
206 // resort services according to order found in jabaws service list
207 // also ensure servics for each host are ordered in same way.
209 if (services != null && services.size() > 0)
211 Jws2Instance[] svcs = new Jws2Instance[services.size()];
212 int[] spos = new int[services.size()];
214 Vector svcUrls = getServiceUrls();
215 for (Jws2Instance svc : services)
218 spos[ipos++] = 1000 * svcUrls.indexOf(svc.getHost()) + 1
219 + svctypes.indexOf(svc.serviceType);
221 jalview.util.QuickSort.sort(spos, svcs);
222 services = new Vector<Jws2Instance>();
223 for (Jws2Instance svc : svcs)
231 changeSupport.firePropertyChange("services", new Vector(), services);
235 * record this service endpoint so we can use it
241 synchronized void addService(String jwsservers, Jws2Instance service)
243 if (services == null)
245 services = new Vector<Jws2Instance>();
247 System.out.println("Discovered service: " + jwsservers + " "
248 + service.toString());
249 // Jws2Instance service = new Jws2Instance(jwsservers, srv.toString(),
252 services.add(service);
253 // retrieve the presets and parameter set and cache now
254 ParamDatastoreI pds = service.getParamStore();
259 service.hasParameters();
260 if (validServiceUrls == null)
262 validServiceUrls = new Vector();
264 validServiceUrls.add(jwsservers);
268 * holds list of services.
270 protected Vector<Jws2Instance> services;
273 * attach all available web services to the appropriate submenu in the given
276 public void attachWSMenuEntry(JMenu wsmenu, final AlignFrame alignFrame)
278 // dynamically regenerate service list.
279 populateWSMenuEntry(wsmenu, alignFrame, null);
282 private boolean isRecalculable(String action)
284 return (action != null && action.equalsIgnoreCase("conservation"));
287 private void populateWSMenuEntry(JMenu jws2al,
288 final AlignFrame alignFrame, String typeFilter)
290 if (running || services == null || services.size() == 0)
294 boolean byhost = Cache.getDefault("WSMENU_BYHOST", false), bytype = Cache
295 .getDefault("WSMENU_BYTYPE", false);
297 * eventually, JWS2 services will appear under the same align/etc submenus.
298 * for moment we keep them separate.
301 List<Jws2Instance> enumerableServices = new ArrayList<Jws2Instance>();
302 // jws2al.removeAll();
303 Map<String, Jws2Instance> preferredHosts = new HashMap<String, Jws2Instance>();
304 Map<String, List<Jws2Instance>> alternates = new HashMap<String, List<Jws2Instance>>();
305 for (Jws2Instance service : services.toArray(new Jws2Instance[0]))
307 if (!isRecalculable(service.action))
309 // add 'one shot' services to be displayed using the classic menu
311 enumerableServices.add(service);
315 if (!preferredHosts.containsKey(service.serviceType))
317 Jws2Instance preferredInstance = getPreferredServiceFor(
318 alignFrame, service.serviceType);
319 if (preferredInstance != null)
321 preferredHosts.put(service.serviceType, preferredInstance);
325 preferredHosts.put(service.serviceType, service);
328 List<Jws2Instance> ph = alternates.get(service.serviceType);
329 if (preferredHosts.get(service.serviceType) != service)
333 ph = new ArrayList<Jws2Instance>();
336 alternates.put(service.serviceType, ph);
342 // create GUI element for classic services
343 addEnumeratedServices(jws2al, alignFrame, enumerableServices);
344 // and the instantaneous services
345 for (final Jws2Instance service : preferredHosts.values())
347 atpoint = JvSwingUtils.findOrCreateMenu(jws2al, service.action);
349 if (atpoint.getItemCount() > 1)
351 // previous service of this type already present
352 atpoint.addSeparator();
354 atpoint.add(hitm = new JMenuItem(service.getHost()));
355 hitm.setForeground(Color.blue);
356 hitm.addActionListener(new ActionListener()
360 public void actionPerformed(ActionEvent e)
362 Desktop.showUrl(service.getHost());
365 hitm.setToolTipText(JvSwingUtils
366 .wrapTooltip("Opens the JABAWS server's homepage in web browser"));
368 service.attachWSMenuEntry(atpoint, alignFrame);
369 if (alternates.containsKey(service.serviceType))
371 atpoint.add(hitm = new JMenu("Switch server"));
372 hitm.setToolTipText(JvSwingUtils
373 .wrapTooltip("Choose a server for running this service"));
374 for (final Jws2Instance sv : alternates.get(service.serviceType))
377 hitm.add(itm = new JMenuItem(sv.getHost()));
378 itm.setForeground(Color.blue);
379 itm.addActionListener(new ActionListener()
383 public void actionPerformed(ActionEvent arg0)
385 new Thread(new Runnable()
389 setPreferredServiceFor(alignFrame, sv.serviceType,
391 changeSupport.firePropertyChange("services",
392 new Vector(), services);
400 * hitm.addActionListener(new ActionListener() {
402 * @Override public void actionPerformed(ActionEvent arg0) { new
403 * Thread(new Runnable() {
405 * @Override public void run() { new SetPreferredServer(alignFrame,
406 * service.serviceType, service.action); } }).start(); } });
413 * add services using the Java 2.5/2.6/2.7 system which optionally creates
414 * submenus to index by host and service program type
416 private void addEnumeratedServices(final JMenu jws2al,
417 final AlignFrame alignFrame, List<Jws2Instance> enumerableServices)
419 boolean byhost = Cache.getDefault("WSMENU_BYHOST", false), bytype = Cache
420 .getDefault("WSMENU_BYTYPE", false);
422 * eventually, JWS2 services will appear under the same align/etc submenus.
423 * for moment we keep them separate.
426 MsaWSClient msacl = new MsaWSClient();
427 List<String> hostLabels = new ArrayList<String>();
428 Hashtable<String, String> lasthostFor = new Hashtable<String, String>();
429 Hashtable<String, ArrayList<Jws2Instance>> hosts = new Hashtable<String, ArrayList<Jws2Instance>>();
430 ArrayList<String> hostlist = new ArrayList<String>();
431 for (Jws2Instance service : enumerableServices)
433 ArrayList<Jws2Instance> hostservices = hosts.get(service.getHost());
434 if (hostservices == null)
436 hosts.put(service.getHost(),
437 hostservices = new ArrayList<Jws2Instance>());
438 hostlist.add(service.getHost());
440 hostservices.add(service);
442 // now add hosts in order of the given array
443 for (String host : hostlist)
445 Jws2Instance orderedsvcs[] = hosts.get(host).toArray(
446 new Jws2Instance[1]);
447 String sortbytype[] = new String[orderedsvcs.length];
448 for (int i = 0; i < sortbytype.length; i++)
450 sortbytype[i] = orderedsvcs[i].serviceType;
452 jalview.util.QuickSort.sort(sortbytype, orderedsvcs);
453 for (final Jws2Instance service : orderedsvcs)
455 atpoint = JvSwingUtils.findOrCreateMenu(jws2al, service.action);
456 String type = service.serviceType;
459 atpoint = JvSwingUtils.findOrCreateMenu(atpoint, host);
460 if (atpoint.getToolTipText() == null)
462 atpoint.setToolTipText("Services at " + host);
467 atpoint = JvSwingUtils.findOrCreateMenu(atpoint, type);
468 if (atpoint.getToolTipText() == null)
470 atpoint.setToolTipText(service.getActionText());
474 && !hostLabels.contains(host + service.serviceType
475 + service.getActionText()))
476 // !hostLabels.contains(host + (bytype ?
477 // service.serviceType+service.getActionText() : "")))
479 // add a marker indicating where this service is hosted
480 // relies on services from the same host being listed in a
484 if (hostLabels.contains(host))
486 atpoint.addSeparator();
490 hostLabels.add(host);
492 if (lasthostFor.get(service.action) == null
493 || !lasthostFor.get(service.action).equals(host))
495 atpoint.add(hitm = new JMenuItem(host));
496 hitm.setForeground(Color.blue);
497 hitm.addActionListener(new ActionListener()
501 public void actionPerformed(ActionEvent e)
503 Desktop.showUrl(service.getHost());
506 hitm.setToolTipText(JvSwingUtils
507 .wrapTooltip("Opens the JABAWS server's homepage in web browser"));
508 lasthostFor.put(service.action, host);
510 hostLabels.add(host + service.serviceType
511 + service.getActionText());
514 service.attachWSMenuEntry(atpoint, alignFrame);
519 public static void main(String[] args)
523 testUrls = new Vector<String>();
524 for (String url : args)
530 Thread runner = getDiscoverer().startDiscoverer(
531 new PropertyChangeListener()
534 public void propertyChange(PropertyChangeEvent evt)
536 if (getDiscoverer().services != null)
538 System.out.println("Changesupport: There are now "
539 + getDiscoverer().services.size() + " services");
541 for (Jws2Instance instance : getDiscoverer().services)
543 System.out.println("Service " + i++ + " "
544 + instance.getClass() + "@"
545 + instance.getHost() + ": "
546 + instance.getActionText());
552 while (runner.isAlive())
557 } catch (InterruptedException e)
565 } catch (InterruptedException x)
570 private static Jws2Discoverer discoverer;
572 public static Jws2Discoverer getDiscoverer()
574 if (discoverer == null)
576 discoverer = new Jws2Discoverer();
581 public boolean hasServices()
583 // TODO Auto-generated method stub
584 return !running && services != null && services.size() > 0;
587 public boolean isRunning()
593 * the jalview .properties entry for JWS2 URLS
595 final static String JWS2HOSTURLS = "JWS2HOSTURLS";
597 public static void setServiceUrls(Vector<String> urls)
601 StringBuffer urlbuffer = new StringBuffer();
603 for (String url : urls)
605 urlbuffer.append(sep);
606 urlbuffer.append(url);
609 Cache.setProperty(JWS2HOSTURLS, urlbuffer.toString());
613 Cache.removeProperty(JWS2HOSTURLS);
617 private static Vector<String> testUrls = null;
619 public static Vector<String> getServiceUrls()
621 if (testUrls != null)
623 // return test urls, if there are any, instead of touching cache
626 String surls = Cache.getDefault(JWS2HOSTURLS,
627 "http://www.compbio.dundee.ac.uk/jabaws");
628 Vector<String> urls = new Vector<String>();
631 StringTokenizer st = new StringTokenizer(surls, ",");
632 while (st.hasMoreElements())
637 java.net.URL u = new java.net.URL(url = st.nextToken());
638 if (!urls.contains(url))
644 jalview.bin.Cache.log.info("Ignoring duplicate url in "
645 + JWS2HOSTURLS + " list");
647 } catch (Exception ex)
649 jalview.bin.Cache.log
650 .warn("Problem whilst trying to make a URL from '"
651 + ((url != null) ? url : "<null>") + "'");
652 jalview.bin.Cache.log
653 .warn("This was probably due to a malformed comma separated list"
656 + " entry of $(HOME)/.jalview_properties)");
657 jalview.bin.Cache.log.debug("Exception was ", ex);
660 } catch (Exception ex)
662 jalview.bin.Cache.log.warn(
663 "Error parsing comma separated list of urls in "
664 + JWS2HOSTURLS + " preference.", ex);
666 if (urls.size() >= 0)
673 public Vector<Jws2Instance> getServices()
675 return (services == null) ? new Vector<Jws2Instance>()
676 : new Vector<Jws2Instance>(services);
680 * test the given URL with the JabaWS test code
685 public static boolean testServiceUrl(URL foo)
689 compbio.ws.client.WSTester.main(new String[]
690 { "-h=" + foo.toString() });
691 } catch (Exception e)
695 } catch (OutOfMemoryError e)
709 * Start a fresh discovery thread and notify the given object when we're
710 * finished. Any known existing threads will be killed before this one is
713 * @param changeSupport2
716 public Thread startDiscoverer(PropertyChangeListener changeSupport2)
722 addPropertyChangeListener(changeSupport2);
723 Thread thr = new Thread(this);
728 Vector<String> invalidServiceUrls = null, urlsWithoutServices = null,
729 validServiceUrls = null;
732 * @return the invalidServiceUrls
734 public Vector<String> getInvalidServiceUrls()
736 return invalidServiceUrls;
740 * @return the urlsWithoutServices
742 public Vector<String> getUrlsWithoutServices()
744 return urlsWithoutServices;
748 * add an 'empty' JABA server to the list. Only servers not already in the
749 * 'bad URL' list will be added to this list.
753 public synchronized void addUrlwithnoservices(String jwsservers)
755 if (urlsWithoutServices == null)
757 urlsWithoutServices = new Vector<String>();
760 if ((invalidServiceUrls == null || !invalidServiceUrls
761 .contains(jwsservers))
762 && !urlsWithoutServices.contains(jwsservers))
764 urlsWithoutServices.add(jwsservers);
769 * add a bad URL to the list
773 public synchronized void addInvalidServiceUrl(String jwsservers)
775 if (invalidServiceUrls == null)
777 invalidServiceUrls = new Vector<String>();
779 if (!invalidServiceUrls.contains(jwsservers))
781 invalidServiceUrls.add(jwsservers);
787 * @return a human readable report of any problems with the service URLs used
790 public String getErrorMessages()
792 if (!isRunning() && !isAborted())
794 StringBuffer ermsg = new StringBuffer();
795 boolean list = false;
796 if (getInvalidServiceUrls() != null
797 && getInvalidServiceUrls().size() > 0)
799 ermsg.append("URLs that could not be contacted: \n");
800 for (String svcurl : getInvalidServiceUrls())
807 ermsg.append(svcurl);
809 ermsg.append("\n\n");
812 if (getUrlsWithoutServices() != null
813 && getUrlsWithoutServices().size() > 0)
815 ermsg.append("URLs without any JABA Services : \n");
816 for (String svcurl : getUrlsWithoutServices())
823 ermsg.append(svcurl);
827 if (ermsg.length() > 1)
829 return ermsg.toString();
836 public int getServerStatusFor(String url)
838 if (validServiceUrls != null && validServiceUrls.contains(url))
842 if (urlsWithoutServices != null && urlsWithoutServices.contains(url))
844 if (invalidServiceUrls != null && invalidServiceUrls.contains(url))
852 * pick the user's preferred service based on a set of URLs (jaba server
853 * locations) and service URIs (specifying version and service interface
857 * @return null or best match for given uri/ls.
859 public Jws2Instance getPreferredServiceFor(String[] serviceURLs)
861 HashSet<String> urls = new HashSet<String>();
862 urls.addAll(Arrays.asList(serviceURLs));
863 Jws2Instance match = null;
864 if (services != null)
866 for (Jws2Instance svc : services)
868 if (urls.contains(svc.getServiceTypeURI()))
872 // for moment we always pick service from server ordered first in
873 // user's preferences
876 if (urls.contains(svc.getUri()))
878 // stop and return - we've matched type URI and URI for service
888 Map<String, Map<String, String>> preferredServiceMap = new HashMap<String, Map<String, String>>();;
891 * get current preferred service of the given type, or global default
894 * null or a specific alignFrame
896 * Jws2Instance.serviceType for service
897 * @return null if no service of this type is available, the preferred service
898 * for the serviceType and af if specified and if defined.
900 public Jws2Instance getPreferredServiceFor(AlignFrame af,
903 String serviceurl = null;
904 synchronized (preferredServiceMap)
906 String afid = (af == null) ? "" : af.getViewport().getSequenceSetId();
907 Map<String, String> prefmap = preferredServiceMap.get(afid);
908 if (afid.length() > 0 && prefmap == null)
910 // recover global setting, if any
911 prefmap = preferredServiceMap.get("");
915 serviceurl = prefmap.get(serviceType);
919 Jws2Instance response = null;
920 for (Jws2Instance svc : services)
922 if (svc.serviceType.equals(serviceType))
924 if (serviceurl == null || serviceurl.equals(svc.getHost()))
934 public void setPreferredServiceFor(AlignFrame af, String serviceType,
935 String serviceAction, Jws2Instance selectedServer)
937 String afid = (af == null) ? "" : af.getViewport().getSequenceSetId();
938 if (preferredServiceMap == null)
940 preferredServiceMap = new HashMap<String, Map<String, String>>();
942 Map<String, String> prefmap = preferredServiceMap.get(afid);
945 prefmap = new HashMap<String, String>();
946 preferredServiceMap.put(afid, prefmap);
948 prefmap.put(serviceType, selectedServer.getHost());
949 prefmap.put(serviceAction, selectedServer.getHost());
952 public void setPreferredServiceFor(String serviceType,
953 String serviceAction, Jws2Instance selectedServer)
955 setPreferredServiceFor(null, serviceType, serviceAction, selectedServer);