2 * Jalview - A Sequence Alignment Editor and Viewer (Version 2.7)
3 * Copyright (C) 2011 J Procter, AM Waterhouse, J Engelhardt, LM Lui, 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.HashSet;
36 import java.util.Hashtable;
37 import java.util.List;
38 import java.util.StringTokenizer;
39 import java.util.Vector;
41 import javax.swing.JMenu;
42 import javax.swing.JMenuItem;
44 import compbio.ws.client.Services;
47 * discoverer for jws2 services. Follows the lightweight service discoverer
48 * pattern (archetyped by EnfinEnvision2OneWay)
53 public class Jws2Discoverer implements Runnable, WSMenuEntryProviderI
55 private java.beans.PropertyChangeSupport changeSupport = new java.beans.PropertyChangeSupport(
59 * change listeners are notified of "services" property changes
62 * to be added that consumes new services Hashtable object.
64 public void addPropertyChangeListener(
65 java.beans.PropertyChangeListener listener)
67 changeSupport.addPropertyChangeListener(listener);
76 public void removePropertyChangeListener(
77 java.beans.PropertyChangeListener listener)
79 changeSupport.removePropertyChangeListener(listener);
82 boolean running = false, aborted = false;
87 public boolean isAborted()
96 public void setAborted(boolean aborted)
98 this.aborted = aborted;
101 Thread oldthread = null;
105 if (running && oldthread != null && oldthread.isAlive())
116 .debug("Waiting around for old discovery thread to finish.");
117 // wait around until old discoverer dies
119 } catch (Exception e)
123 Cache.log.debug("Old discovery thread has finished.");
126 changeSupport.firePropertyChange("services", services, new Vector());
127 oldthread = Thread.currentThread();
130 Class foo = getClass().getClassLoader().loadClass(
131 "compbio.ws.client.Jws2Client");
132 } catch (ClassNotFoundException e)
135 .println("Not enabling JABA Webservices : client jar is not available."
136 + "\nPlease check that your webstart JNLP file is up to date!");
140 // reinitialise records of good and bad service URLs
141 if (services != null)
143 services.removeAllElements();
145 if (urlsWithoutServices != null)
147 urlsWithoutServices.removeAllElements();
149 if (invalidServiceUrls != null)
151 invalidServiceUrls.removeAllElements();
153 if (validServiceUrls != null)
155 validServiceUrls.removeAllElements();
157 ArrayList<String> svctypes=new ArrayList<String>();
159 List<JabaWsServerQuery> qrys = new ArrayList<JabaWsServerQuery>();
160 for (final String jwsservers : getServiceUrls())
162 JabaWsServerQuery squery = new JabaWsServerQuery(this, jwsservers);
163 if (svctypes.size()==0)
165 // TODO: remove this ugly hack to get Canonical JABA service ordering for all possible services
166 for (Services sv:squery.JABAWS2SERVERS)
168 svctypes.add(sv.toString());
173 new Thread(squery).start();
175 boolean finished = true;
182 } catch (Exception e)
186 for (JabaWsServerQuery squery : qrys)
188 finished = finished && !squery.isRunning();
192 Cache.log.debug("Aborting " + qrys.size()
193 + " JABAWS discovery threads.");
194 for (JabaWsServerQuery squery : qrys)
196 squery.setQuit(true);
199 } while (!aborted && !finished);
202 // resort services according to order found in jabaws service list
203 // also ensure servics for each host are ordered in same way.
205 if (services!=null && services.size()>0)
207 Jws2Instance[] svcs=new Jws2Instance[services.size()];
208 int[] spos=new int[services.size()];
210 Vector svcUrls = getServiceUrls();
211 for (Jws2Instance svc:services)
214 spos[ipos++]=1000*svcUrls.indexOf(svc.getHost()) + 1+svctypes.indexOf(svc.serviceType);
216 jalview.util.QuickSort.sort(spos, svcs);
217 services=new Vector<Jws2Instance>();
218 for (Jws2Instance svc:svcs) {
225 changeSupport.firePropertyChange("services", new Vector(), services);
229 * record this service endpoint so we can use it
235 synchronized void addService(String jwsservers, Jws2Instance service)
237 if (services == null)
239 services = new Vector<Jws2Instance>();
241 System.out.println("Discovered service: " + jwsservers + " "
242 + service.toString());
243 // Jws2Instance service = new Jws2Instance(jwsservers, srv.toString(),
246 services.add(service);
247 // retrieve the presets and parameter set and cache now
248 service.getParamStore().getPresets();
249 service.hasParameters();
250 if (validServiceUrls==null)
252 validServiceUrls=new Vector();
254 validServiceUrls.add(jwsservers);
258 * holds list of services.
260 protected Vector<Jws2Instance> services;
262 * attach all available web services to the appropriate submenu in the given JMenu
264 public void attachWSMenuEntry(JMenu wsmenu, final AlignFrame alignFrame)
266 // dynamically regenerate service list.
267 populateWSMenuEntry(wsmenu, alignFrame, null);
270 private void populateWSMenuEntry(JMenu jws2al, final AlignFrame alignFrame, String typeFilter)
272 if (running || services == null || services.size() == 0)
276 boolean byhost = Cache.getDefault("WSMENU_BYHOST", false), bytype = Cache
277 .getDefault("WSMENU_BYTYPE", false);
279 * eventually, JWS2 services will appear under the same align/etc submenus.
280 * for moment we keep them separate.
283 MsaWSClient msacl = new MsaWSClient();
284 Vector hostLabels = new Vector();
285 //jws2al.removeAll();
286 Hashtable<String,String> lasthostFor = new Hashtable<String,String>();
287 Hashtable<String, ArrayList<Jws2Instance>> hosts = new Hashtable<String, ArrayList<Jws2Instance>>();
288 ArrayList<String> hostlist=new ArrayList<String>();
289 for (Jws2Instance service : services)
291 ArrayList<Jws2Instance> hostservices = hosts.get(service.getHost());
292 if (hostservices == null)
294 hosts.put(service.getHost(),
295 hostservices = new ArrayList<Jws2Instance>());
296 hostlist.add(service.getHost());
298 hostservices.add(service);
300 // now add hosts in order of the given array
301 for (String host : hostlist)
303 Jws2Instance orderedsvcs[] = hosts.get(host).toArray(
304 new Jws2Instance[1]);
305 String sortbytype[] = new String[orderedsvcs.length];
306 for (int i = 0; i < sortbytype.length; i++)
308 sortbytype[i] = orderedsvcs[i].serviceType;
310 jalview.util.QuickSort.sort(sortbytype, orderedsvcs);
311 for (final Jws2Instance service : orderedsvcs)
313 atpoint = JvSwingUtils.findOrCreateMenu(jws2al,service.action);
314 String type = service.serviceType;
317 atpoint = JvSwingUtils.findOrCreateMenu(atpoint, host);
318 if (atpoint.getToolTipText() == null)
320 atpoint.setToolTipText("Services at " + host);
325 atpoint = JvSwingUtils.findOrCreateMenu(atpoint, type);
326 if (atpoint.getToolTipText() == null)
328 atpoint.setToolTipText(service.getActionText());
332 && !hostLabels.contains(host + service.serviceType
333 + service.getActionText()))
334 // !hostLabels.contains(host + (bytype ?
335 // service.serviceType+service.getActionText() : "")))
337 // add a marker indicating where this service is hosted
338 // relies on services from the same host being listed in a
342 atpoint.addSeparator();
343 if (lasthostFor.get(service.action) == null || !lasthostFor.get(service.action).equals(host))
345 atpoint.add(hitm = new JMenuItem(host));
346 hitm.setForeground(Color.blue);
347 hitm.addActionListener(new ActionListener()
351 public void actionPerformed(ActionEvent e)
353 Desktop.showUrl(service.getHost());
356 hitm.setToolTipText(JvSwingUtils
357 .wrapTooltip("Opens the JABAWS server's homepage in web browser"));
358 lasthostFor.put(service.action,host);
360 hostLabels.addElement(host + service.serviceType
361 + service.getActionText());
362 // hostLabels.addElement(host + (bytype ?
363 // service.serviceType+service.getActionText() : ""));
366 service.attachWSMenuEntry(atpoint, alignFrame);
368 * JMenuItem sitem = new JMenuItem(service.serviceType);
369 * sitem.setToolTipText("Hosted at " + service.hosturl);
370 * sitem.addActionListener(new ActionListener() {
372 * @Override public void actionPerformed(ActionEvent e) { AlignmentView
373 * msa = alignFrame.gatherSequencesForAlignment(); MsaWSClient client =
374 * new MsaWSClient(service, "JWS2 Alignment of " +
375 * alignFrame.getTitle(), msa, false, true,
376 * alignFrame.getViewport().getAlignment().getDataset(), alignFrame); }
384 public static void main(String[] args)
388 testUrls = new Vector<String>();
389 for (String url:args)
394 Thread runner = getDiscoverer().startDiscoverer(
395 new PropertyChangeListener()
398 public void propertyChange(PropertyChangeEvent evt)
400 if (getDiscoverer().services != null)
402 System.out.println("Changesupport: There are now "
403 + getDiscoverer().services.size() + " services");
405 for (Jws2Instance instance:getDiscoverer().services)
407 System.out.println("Service "+i+++" "+instance.getClass()+"@"+instance.getHost()+": "+instance.getActionText());
413 while (runner.isAlive())
418 } catch (InterruptedException e)
425 } catch (InterruptedException x) {}
428 private static Jws2Discoverer discoverer;
430 public static Jws2Discoverer getDiscoverer()
432 if (discoverer == null)
434 discoverer = new Jws2Discoverer();
439 public boolean hasServices()
441 // TODO Auto-generated method stub
442 return !running && services != null && services.size() > 0;
445 public boolean isRunning()
451 * the jalview .properties entry for JWS2 URLS
453 final static String JWS2HOSTURLS = "JWS2HOSTURLS";
455 public static void setServiceUrls(Vector<String> urls)
459 StringBuffer urlbuffer = new StringBuffer();
461 for (String url : urls)
463 urlbuffer.append(sep);
464 urlbuffer.append(url);
467 Cache.setProperty(JWS2HOSTURLS, urlbuffer.toString());
471 Cache.removeProperty(JWS2HOSTURLS);
475 private static Vector<String> testUrls=null;
476 public static Vector<String> getServiceUrls()
480 // return test urls, if there are any, instead of touching cache
483 String surls = Cache.getDefault(JWS2HOSTURLS,
484 "http://www.compbio.dundee.ac.uk/jabaws");
485 Vector<String> urls = new Vector<String>();
488 StringTokenizer st = new StringTokenizer(surls, ",");
489 while (st.hasMoreElements())
494 java.net.URL u = new java.net.URL(url = st.nextToken());
495 if (!urls.contains(url))
501 jalview.bin.Cache.log.info("Ignoring duplicate url in "
502 + JWS2HOSTURLS + " list");
504 } catch (Exception ex)
506 jalview.bin.Cache.log
507 .warn("Problem whilst trying to make a URL from '"
508 + ((url != null) ? url : "<null>") + "'");
509 jalview.bin.Cache.log
510 .warn("This was probably due to a malformed comma separated list"
513 + " entry of $(HOME)/.jalview_properties)");
514 jalview.bin.Cache.log.debug("Exception was ", ex);
517 } catch (Exception ex)
519 jalview.bin.Cache.log.warn(
520 "Error parsing comma separated list of urls in "
521 + JWS2HOSTURLS + " preference.", ex);
523 if (urls.size() >= 0)
530 public Vector<Jws2Instance> getServices()
532 return (services == null) ? new Vector<Jws2Instance>()
533 : new Vector<Jws2Instance>(services);
537 * test the given URL with the JabaWS test code
542 public static boolean testServiceUrl(URL foo)
546 compbio.ws.client.WSTester.main(new String[]
547 { "-h=" + foo.toString() });
548 } catch (Exception e)
552 } catch (OutOfMemoryError e)
566 * Start a fresh discovery thread and notify the given object when we're
567 * finished. Any known existing threads will be killed before this one is
570 * @param changeSupport2
573 public Thread startDiscoverer(PropertyChangeListener changeSupport2)
579 addPropertyChangeListener(changeSupport2);
580 Thread thr = new Thread(this);
585 Vector<String> invalidServiceUrls = null, urlsWithoutServices = null, validServiceUrls=null;
588 * @return the invalidServiceUrls
590 public Vector<String> getInvalidServiceUrls()
592 return invalidServiceUrls;
596 * @return the urlsWithoutServices
598 public Vector<String> getUrlsWithoutServices()
600 return urlsWithoutServices;
604 * add an 'empty' JABA server to the list. Only servers not already in the
605 * 'bad URL' list will be added to this list.
609 public synchronized void addUrlwithnoservices(String jwsservers)
611 if (urlsWithoutServices == null)
613 urlsWithoutServices = new Vector<String>();
616 if ((invalidServiceUrls == null || !invalidServiceUrls
617 .contains(jwsservers))
618 && !urlsWithoutServices.contains(jwsservers))
620 urlsWithoutServices.add(jwsservers);
625 * add a bad URL to the list
629 public synchronized void addInvalidServiceUrl(String jwsservers)
631 if (invalidServiceUrls == null)
633 invalidServiceUrls = new Vector<String>();
635 if (!invalidServiceUrls.contains(jwsservers))
637 invalidServiceUrls.add(jwsservers);
643 * @return a human readable report of any problems with the service URLs used
646 public String getErrorMessages()
648 if (!isRunning() && !isAborted())
650 StringBuffer ermsg = new StringBuffer();
651 boolean list = false;
652 if (getInvalidServiceUrls() != null
653 && getInvalidServiceUrls().size() > 0)
655 ermsg.append("URLs that could not be contacted: \n");
656 for (String svcurl : getInvalidServiceUrls())
663 ermsg.append(svcurl);
665 ermsg.append("\n\n");
668 if (getUrlsWithoutServices() != null
669 && getUrlsWithoutServices().size() > 0)
671 ermsg.append("URLs without any JABA Services : \n");
672 for (String svcurl : getUrlsWithoutServices())
679 ermsg.append(svcurl);
683 if (ermsg.length() > 1)
685 return ermsg.toString();
692 public int getServerStatusFor(String url)
694 if (validServiceUrls!=null && validServiceUrls.contains(url))
698 if (urlsWithoutServices!=null && urlsWithoutServices.contains(url))
700 if (invalidServiceUrls!=null && invalidServiceUrls.contains(url))
708 * pick the user's preferred service based on a set of URLs (jaba server locations) and service URIs (specifying version and service interface class)
711 * @return null or best match for given uri/ls.
713 public Jws2Instance getPreferredServiceFor(String[] serviceURLs)
715 HashSet<String> urls=new HashSet<String>();
716 urls.addAll(Arrays.asList(serviceURLs));
717 Jws2Instance match=null;
718 for (Jws2Instance svc:services)
720 if (urls.contains(svc.getServiceTypeURI()))
723 // for moment we always pick service from server ordered first in user's preferences
726 if (urls.contains(svc.getUri()))
728 // stop and return - we've matched type URI and URI for service endpoint