JAL-3070 reorganise prior to refactor
[jalview.git] / src / jalview / ws / jws2 / Jws2Discoverer.java
1 /*
2  * Jalview - A Sequence Alignment Editor and Viewer ($$Version-Rel$$)
3  * Copyright (C) $$Year-Rel$$ The Jalview Authors
4  * 
5  * This file is part of Jalview.
6  * 
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.
11  *  
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.
16  * 
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.
20  */
21 package jalview.ws.jws2;
22
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.api.ServiceWithParameters;
30 import jalview.ws.jws2.jabaws2.Jws2Instance;
31 import jalview.ws.params.ParamDatastoreI;
32
33 import java.awt.Color;
34 import java.awt.event.ActionEvent;
35 import java.awt.event.ActionListener;
36 import java.beans.PropertyChangeEvent;
37 import java.beans.PropertyChangeListener;
38 import java.beans.PropertyChangeSupport;
39 import java.net.MalformedURLException;
40 import java.net.URL;
41 import java.util.ArrayList;
42 import java.util.Arrays;
43 import java.util.HashMap;
44 import java.util.HashSet;
45 import java.util.Hashtable;
46 import java.util.List;
47 import java.util.Map;
48 import java.util.Set;
49 import java.util.StringTokenizer;
50 import java.util.Vector;
51
52 import javax.swing.JMenu;
53 import javax.swing.JMenuItem;
54
55 import compbio.ws.client.Services;
56
57 /**
58  * discoverer for jws2 services. Follows the lightweight service discoverer
59  * pattern (archetyped by EnfinEnvision2OneWay)
60  * 
61  * @author JimP
62  * 
63  */
64 public class Jws2Discoverer implements Runnable, WSMenuEntryProviderI
65 {
66   public static final String COMPBIO_JABAWS = "http://www.compbio.dundee.ac.uk/jabaws";
67
68   /*
69    * the .jalview_properties entry for JWS2 URLS
70    */
71   private final static String JWS2HOSTURLS = "JWS2HOSTURLS";
72
73   /*
74    * Singleton instance
75    */
76   private static Jws2Discoverer discoverer;
77
78   /*
79    * Override for testing only
80    */
81   private static List<String> testUrls = null;
82
83   // preferred url has precedence over others
84   private String preferredUrl;
85
86   private PropertyChangeSupport changeSupport = new PropertyChangeSupport(
87           this);
88
89   private Vector<String> invalidServiceUrls = null;
90
91   private Vector<String> urlsWithoutServices = null;
92
93   private Vector<String> validServiceUrls = null;
94
95   private volatile boolean running = false;
96
97   private volatile boolean aborted = false;
98
99   private Thread oldthread = null;
100
101   /**
102    * holds list of services.
103    */
104   protected Vector<Jws2Instance> services;
105
106   /**
107    * Private constructor enforces use of singleton via getDiscoverer()
108    */
109   private Jws2Discoverer()
110   {
111   }
112
113   /**
114    * change listeners are notified of "services" property changes
115    * 
116    * @param listener
117    *          to be added that consumes new services Hashtable object.
118    */
119   public void addPropertyChangeListener(
120           java.beans.PropertyChangeListener listener)
121   {
122     changeSupport.addPropertyChangeListener(listener);
123   }
124
125   /**
126    * 
127    * 
128    * @param listener
129    *          to be removed
130    */
131   public void removePropertyChangeListener(
132           java.beans.PropertyChangeListener listener)
133   {
134     changeSupport.removePropertyChangeListener(listener);
135   }
136
137   /**
138    * @return the aborted
139    */
140   public boolean isAborted()
141   {
142     return aborted;
143   }
144
145   /**
146    * @param aborted
147    *          the aborted to set
148    */
149   public void setAborted(boolean aborted)
150   {
151     this.aborted = aborted;
152   }
153
154   @Override
155   public void run()
156   {
157
158     if (running && oldthread != null && oldthread.isAlive())
159     {
160       if (!aborted)
161       {
162         return;
163       }
164       while (running)
165       {
166         try
167         {
168           Cache.log.debug(
169                   "Waiting around for old discovery thread to finish.");
170           // wait around until old discoverer dies
171           Thread.sleep(100);
172         } catch (Exception e)
173         {
174         }
175       }
176       aborted = false;
177       Cache.log.debug("Old discovery thread has finished.");
178     }
179     running = true;
180
181     // first set up exclusion list if needed
182     final Set<String> ignoredServices = new HashSet<>();
183     for (String ignored : Cache
184             .getDefault("IGNORED_JABAWS_SERVICETYPES", "").split("\\|"))
185     {
186       ignoredServices.add(ignored);
187     }
188
189     changeSupport.firePropertyChange("services", services,
190             new Vector<Jws2Instance>());
191     oldthread = Thread.currentThread();
192     try
193     {
194       Class foo = getClass().getClassLoader()
195               .loadClass("compbio.ws.client.Jws2Client");
196     } catch (ClassNotFoundException e)
197     {
198       System.err.println(
199               "Not enabling JABA Webservices : client jar is not available."
200                       + "\nPlease check that your webstart JNLP file is up to date!");
201       running = false;
202       return;
203     }
204     // reinitialise records of good and bad service URLs
205     if (services != null)
206     {
207       services.removeAllElements();
208     }
209     if (urlsWithoutServices != null)
210     {
211       urlsWithoutServices.removeAllElements();
212     }
213     if (invalidServiceUrls != null)
214     {
215       invalidServiceUrls.removeAllElements();
216     }
217     if (validServiceUrls != null)
218     {
219       validServiceUrls.removeAllElements();
220     }
221     ArrayList<String> svctypes = new ArrayList<>();
222
223     List<JabaWsServerQuery> qrys = new ArrayList<>();
224     for (final String jwsserver : getServiceUrls())
225     {
226       JabaWsServerQuery squery = new JabaWsServerQuery(this, jwsserver);
227       if (svctypes.size() == 0)
228       {
229         // TODO: remove this ugly hack to get Canonical JABA service ordering
230         // for all possible services
231         for (Services sv : squery.JABAWS2SERVERS)
232         {
233           if (!ignoredServices.contains(sv.toString()))
234           {
235             svctypes.add(sv.toString());
236           }
237         }
238
239       }
240       qrys.add(squery);
241       new Thread(squery).start();
242     }
243     boolean finished = true;
244     do
245     {
246       finished = true;
247       try
248       {
249         Thread.sleep(100);
250       } catch (Exception e)
251       {
252       }
253       ;
254       for (JabaWsServerQuery squery : qrys)
255       {
256         if (squery.isRunning())
257         {
258           finished = false;
259         }
260       }
261       if (aborted)
262       {
263         Cache.log.debug(
264                 "Aborting " + qrys.size() + " JABAWS discovery threads.");
265         for (JabaWsServerQuery squery : qrys)
266         {
267           squery.setQuit(true);
268         }
269       }
270     } while (!aborted && !finished);
271     if (!aborted)
272     {
273       // resort services according to order found in jabaws service list
274       // also ensure services for each host are ordered in same way.
275
276       if (services != null && services.size() > 0)
277       {
278         Jws2Instance[] svcs = new Jws2Instance[services.size()];
279         int[] spos = new int[services.size()];
280         int ipos = 0;
281         List<String> svcUrls = getServiceUrls();
282         for (Jws2Instance svc : services)
283         {
284           svcs[ipos] = svc;
285           spos[ipos++] = 1000 * svcUrls.indexOf(svc.getHostURL()) + 1
286                   + svctypes.indexOf(svc.getName());
287         }
288         jalview.util.QuickSort.sort(spos, svcs);
289         services = new Vector<>();
290         for (Jws2Instance svc : svcs)
291         {
292           if (!ignoredServices.contains(svc.getName()))
293           {
294             services.add(svc);
295           }
296         }
297       }
298     }
299     oldthread = null;
300     running = false;
301     changeSupport.firePropertyChange("services", new Vector<Jws2Instance>(),
302             services);
303   }
304
305   /**
306    * record this service endpoint so we can use it
307    * 
308    * @param jwsservers
309    * @param srv
310    * @param service2
311    */
312   synchronized void addService(String jwsservers, Jws2Instance service)
313   {
314     if (services == null)
315     {
316       services = new Vector<>();
317     }
318     System.out.println(
319             "Discovered service: " + jwsservers + " " + service.toString());
320     // Jws2Instance service = new Jws2Instance(jwsservers, srv.toString(),
321     // service2);
322
323     services.add(service);
324     // retrieve the presets and parameter set and cache now
325     ParamDatastoreI pds = service.getParamStore();
326     if (pds != null)
327     {
328       pds.getPresets();
329     }
330     service.hasParameters();
331     if (validServiceUrls == null)
332     {
333       validServiceUrls = new Vector<>();
334     }
335     validServiceUrls.add(jwsservers);
336   }
337
338   /**
339    * attach all available web services to the appropriate submenu in the given
340    * JMenu
341    */
342   @Override
343   public void attachWSMenuEntry(JMenu wsmenu, final AlignFrame alignFrame)
344   {
345     // dynamically regenerate service list.
346     populateWSMenuEntry(wsmenu, alignFrame, null);
347   }
348
349   private boolean isRecalculable(String action)
350   {
351     return (action != null && action.equalsIgnoreCase("conservation"));
352   }
353
354   private void populateWSMenuEntry(JMenu jws2al,
355           final AlignFrame alignFrame, String typeFilter)
356   {
357     if (running || services == null || services.size() == 0)
358     {
359       return;
360     }
361
362     /**
363      * eventually, JWS2 services will appear under the same align/etc submenus.
364      * for moment we keep them separate.
365      */
366     JMenu atpoint;
367     List<Jws2Instance> enumerableServices = new ArrayList<>();
368     // jws2al.removeAll();
369     Map<String, ServiceWithParameters> preferredHosts = new HashMap<>();
370     Map<String, List<ServiceWithParameters>> alternates = new HashMap<>();
371     for (Jws2Instance service : services.toArray(new Jws2Instance[0]))
372     {
373       // TODO: check this behaves with refactored serviceType to getName
374       if (!isRecalculable(service.getName()))
375       {
376         // add 'one shot' services to be displayed using the classic menu
377         // structure
378         enumerableServices.add(service);
379       }
380       else
381       {
382         if (!preferredHosts.containsKey(service.getName()))
383         {
384           ServiceWithParameters preferredInstance = getPreferredServiceFor(
385                   alignFrame, service.getName());
386           if (preferredInstance != null)
387           {
388             preferredHosts.put(service.getName(), preferredInstance);
389           }
390           else
391           {
392             preferredHosts.put(service.getName(), service);
393           }
394         }
395         List<ServiceWithParameters> ph = alternates.get(service.getName());
396         if (preferredHosts.get(service.getName()) != service)
397         {
398           if (ph == null)
399           {
400             ph = new ArrayList<>();
401           }
402           ph.add(service);
403           alternates.put(service.getName(), ph);
404         }
405       }
406
407     }
408
409     // create GUI element for classic services
410     addEnumeratedServices(jws2al, alignFrame, enumerableServices);
411     // and the instantaneous services
412     for (final ServiceWithParameters service : preferredHosts.values())
413     {
414       atpoint = JvSwingUtils.findOrCreateMenu(jws2al,
415               service.getServiceType());
416       JMenuItem hitm;
417       if (atpoint.getItemCount() > 1)
418       {
419         // previous service of this type already present
420         atpoint.addSeparator();
421       }
422       atpoint.add(hitm = new JMenuItem(service.getHostURL()));
423       hitm.setForeground(Color.blue);
424       hitm.addActionListener(new ActionListener()
425       {
426
427         @Override
428         public void actionPerformed(ActionEvent e)
429         {
430           Desktop.showUrl(service.getHostURL());
431         }
432       });
433       hitm.setToolTipText(JvSwingUtils.wrapTooltip(false,
434               MessageManager.getString("label.open_jabaws_web_page")));
435
436       service.attachWSMenuEntry(atpoint, alignFrame);
437       if (alternates.containsKey(service.getName()))
438       {
439         atpoint.add(hitm = new JMenu(
440                 MessageManager.getString("label.switch_server")));
441         hitm.setToolTipText(JvSwingUtils.wrapTooltip(false,
442                 MessageManager.getString("label.choose_jabaws_server")));
443         for (final ServiceWithParameters sv : alternates.get(service.getName()))
444         {
445           JMenuItem itm;
446           hitm.add(itm = new JMenuItem(sv.getHostURL()));
447           itm.setForeground(Color.blue);
448           itm.addActionListener(new ActionListener()
449           {
450
451             @Override
452             public void actionPerformed(ActionEvent arg0)
453             {
454               new Thread(new Runnable()
455               {
456                 @Override
457                 public void run()
458                 {
459                   setPreferredServiceFor(alignFrame, sv.getName(),
460                           sv.getServiceType(), sv);
461                   changeSupport.firePropertyChange("services",
462                           new Vector<Jws2Instance>(), services);
463                 };
464               }).start();
465
466             }
467           });
468         }
469       }
470     }
471   }
472
473   /**
474    * add services using the Java 2.5/2.6/2.7 system which optionally creates
475    * submenus to index by host and service program type
476    */
477   private void addEnumeratedServices(final JMenu jws2al,
478           final AlignFrame alignFrame,
479           List<Jws2Instance> enumerableServices)
480   {
481     boolean byhost = Cache.getDefault("WSMENU_BYHOST", false),
482             bytype = Cache.getDefault("WSMENU_BYTYPE", false);
483     /**
484      * eventually, JWS2 services will appear under the same align/etc submenus.
485      * for moment we keep them separate.
486      */
487     JMenu atpoint;
488
489     List<String> hostLabels = new ArrayList<>();
490     Hashtable<String, String> lasthostFor = new Hashtable<>();
491     Hashtable<String, ArrayList<Jws2Instance>> hosts = new Hashtable<>();
492     ArrayList<String> hostlist = new ArrayList<>();
493     for (Jws2Instance service : enumerableServices)
494     {
495       ArrayList<Jws2Instance> hostservices = hosts
496               .get(service.getHostURL());
497       if (hostservices == null)
498       {
499         hosts.put(service.getHostURL(),
500                 hostservices = new ArrayList<>());
501         hostlist.add(service.getHostURL());
502       }
503       hostservices.add(service);
504     }
505     // now add hosts in order of the given array
506     for (String host : hostlist)
507     {
508       Jws2Instance orderedsvcs[] = hosts.get(host)
509               .toArray(new Jws2Instance[1]);
510       String sortbytype[] = new String[orderedsvcs.length];
511       for (int i = 0; i < sortbytype.length; i++)
512       {
513         sortbytype[i] = orderedsvcs[i].getName();
514       }
515       jalview.util.QuickSort.sort(sortbytype, orderedsvcs);
516       for (final Jws2Instance service : orderedsvcs)
517       {
518         atpoint = JvSwingUtils.findOrCreateMenu(jws2al,
519                 service.getAction());
520         String type = service.getName();
521         if (byhost)
522         {
523           atpoint = JvSwingUtils.findOrCreateMenu(atpoint, host);
524           if (atpoint.getToolTipText() == null)
525           {
526             atpoint.setToolTipText(MessageManager
527                     .formatMessage("label.services_at", new String[]
528                     { host }));
529           }
530         }
531         if (bytype)
532         {
533           atpoint = JvSwingUtils.findOrCreateMenu(atpoint, type);
534           if (atpoint.getToolTipText() == null)
535           {
536             atpoint.setToolTipText(service.getActionText());
537           }
538         }
539         if (!byhost && !hostLabels.contains(
540                 host + service.getName() + service.getActionText()))
541         // !hostLabels.contains(host + (bytype ?
542         // service.serviceType+service.getActionText() : "")))
543         {
544           // add a marker indicating where this service is hosted
545           // relies on services from the same host being listed in a
546           // contiguous
547           // group
548           JMenuItem hitm;
549           if (hostLabels.contains(host))
550           {
551             atpoint.addSeparator();
552           }
553           else
554           {
555             hostLabels.add(host);
556           }
557           if (lasthostFor.get(service.getAction()) == null
558                   || !lasthostFor.get(service.getAction()).equals(host))
559           {
560             atpoint.add(hitm = new JMenuItem(host));
561             hitm.setForeground(Color.blue);
562             hitm.addActionListener(new ActionListener()
563             {
564
565               @Override
566               public void actionPerformed(ActionEvent e)
567               {
568                 Desktop.showUrl(service.getHostURL());
569               }
570             });
571             hitm.setToolTipText(
572                     JvSwingUtils.wrapTooltip(true, MessageManager
573                             .getString("label.open_jabaws_web_page")));
574             lasthostFor.put(service.getAction(), host);
575           }
576           hostLabels.add(
577                   host + service.getName() + service.getActionText());
578         }
579
580         service.attachWSMenuEntry(atpoint, alignFrame);
581       }
582     }
583   }
584
585   /**
586    * pick the user's preferred service based on a set of URLs (jaba server
587    * locations) and service URIs (specifying version and service interface
588    * class)
589    * 
590    * @param serviceURL
591    * @return null or best match for given uri/ls.
592    */
593   public ServiceWithParameters getPreferredServiceFor(String[] serviceURLs)
594   {
595     HashSet<String> urls = new HashSet<>();
596     urls.addAll(Arrays.asList(serviceURLs));
597     ServiceWithParameters match = null;
598     List<ServiceWithParameters> ourServices = getServices();
599
600     if (ourServices != null)
601     {
602       for (ServiceWithParameters svc : ourServices)
603       {
604         // TODO getNameURI Should return a versioned URI for the service, but
605         // doesn't as of 2.11
606         if (urls.contains(svc.getNameURI()))
607         {
608           if (match == null)
609           {
610             // for moment we always pick service from server ordered first in
611             // user's preferences
612             match = svc;
613           }
614           if (urls.contains(svc.getUri()))
615           {
616             // stop and return - we've matched type URI and URI for service
617             // endpoint
618             return svc;
619           }
620         }
621       }
622     }
623     return match;
624   }
625
626   Map<String, Map<String, String>> preferredServiceMap = new HashMap<>();
627
628   /**
629    * get current preferred endpoint of the given Jabaws service, or global
630    * default
631    * 
632    * @param af
633    *          null or a specific alignFrame
634    * @param serviceName
635    *          Jws2Instance.getName() for service
636    * @return null if no service of this type is available, the preferred service
637    *         for the serviceType and af if specified and if defined.
638    */
639   public ServiceWithParameters getPreferredServiceFor(AlignFrame af,
640           String serviceName)
641   {
642     String serviceurl = null;
643     synchronized (preferredServiceMap)
644     {
645       String afid = (af == null) ? "" : af.getViewport().getSequenceSetId();
646       Map<String, String> prefmap = preferredServiceMap.get(afid);
647       if (afid.length() > 0 && prefmap == null)
648       {
649         // recover global setting, if any
650         prefmap = preferredServiceMap.get("");
651       }
652       if (prefmap != null)
653       {
654         serviceurl = prefmap.get(serviceName);
655       }
656
657     }
658     ServiceWithParameters response = null;
659     for (ServiceWithParameters svc : getServices())
660     {
661       if (svc.getName().equals(serviceName))
662       {
663         if (serviceurl == null || serviceurl.equals(svc.getHostURL()))
664         {
665           response = svc;
666           break;
667         }
668       }
669     }
670     return response;
671   }
672
673   public void setPreferredServiceFor(AlignFrame af, String serviceName,
674           String serviceAction, ServiceWithParameters selectedServer)
675   {
676     // TODO: pull out and generalise for the selectedServer's attributes
677     String afid = (af == null) ? "" : af.getViewport().getSequenceSetId();
678     if (preferredServiceMap == null)
679     {
680       preferredServiceMap = new HashMap<>();
681     }
682     Map<String, String> prefmap = preferredServiceMap.get(afid);
683     if (prefmap == null)
684     {
685       prefmap = new HashMap<>();
686       preferredServiceMap.put(afid, prefmap);
687     }
688     prefmap.put(serviceName, selectedServer.getHostURL());
689     prefmap.put(serviceAction, selectedServer.getHostURL());
690   }
691
692   public void setPreferredServiceFor(String serviceType,
693           String serviceAction, ServiceWithParameters selectedServer)
694   {
695     setPreferredServiceFor(null, serviceType, serviceAction,
696             selectedServer);
697   }
698
699   public static void main(String[] args)
700   {
701     if (args.length > 0)
702     {
703       testUrls = new ArrayList<>();
704       for (String url : args)
705       {
706         testUrls.add(url);
707       }
708       ;
709     }
710     Thread runner = getDiscoverer()
711             .startDiscoverer(new PropertyChangeListener()
712             {
713
714               @Override
715               public void propertyChange(PropertyChangeEvent evt)
716               {
717                 if (getDiscoverer().services != null)
718                 {
719                   System.out.println("Changesupport: There are now "
720                           + getDiscoverer().services.size() + " services");
721                   int i = 1;
722                   for (ServiceWithParameters instance : getDiscoverer().services)
723                   {
724                     System.out.println("Service " + i++ + " "
725                             + instance.getClass() + "@"
726                             + instance.getHostURL()
727                             + ": " + instance.getActionText());
728                   }
729
730                 }
731               }
732             });
733     while (runner.isAlive())
734     {
735       try
736       {
737         Thread.sleep(50);
738       } catch (InterruptedException e)
739       {
740       }
741       ;
742     }
743     try
744     {
745       Thread.sleep(50);
746     } catch (InterruptedException x)
747     {
748     }
749   }
750
751   /**
752    * Returns the singleton instance of this class.
753    * 
754    * @return
755    */
756   public static Jws2Discoverer getDiscoverer()
757   {
758     if (discoverer == null)
759     {
760       discoverer = new Jws2Discoverer();
761     }
762     return discoverer;
763   }
764
765   public boolean hasServices()
766   {
767     return !running && services != null && services.size() > 0;
768   }
769
770   public boolean isRunning()
771   {
772     return running;
773   }
774
775   public void setServiceUrls(List<String> wsUrls)
776   {
777     if (wsUrls != null && !wsUrls.isEmpty())
778     {
779       StringBuilder urls = new StringBuilder(128);
780       String sep = "";
781       for (String url : wsUrls)
782       {
783         urls.append(sep);
784         urls.append(url);
785         sep = ",";
786       }
787       Cache.setProperty(JWS2HOSTURLS, urls.toString());
788     }
789     else
790     {
791       Cache.removeProperty(JWS2HOSTURLS);
792     }
793   }
794
795   /**
796    * Returns web service URLs, in the order in which they should be tried (or an
797    * empty list).
798    * 
799    * @return
800    */
801   public List<String> getServiceUrls()
802   {
803     if (testUrls != null)
804     {
805       // return test urls, if there are any, instead of touching cache
806       return testUrls;
807     }
808     List<String> urls = new ArrayList<>();
809
810     if (this.preferredUrl != null)
811     {
812       urls.add(preferredUrl);
813     }
814
815     String surls = Cache.getDefault(JWS2HOSTURLS, COMPBIO_JABAWS);
816     try
817     {
818       StringTokenizer st = new StringTokenizer(surls, ",");
819       while (st.hasMoreElements())
820       {
821         String url = null;
822         try
823         {
824           url = st.nextToken();
825           new URL(url);
826           if (!urls.contains(url))
827           {
828             urls.add(url);
829           }
830           else
831           {
832             Cache.log.warn("Ignoring duplicate url " + url + " in "
833                     + JWS2HOSTURLS + " list");
834           }
835         } catch (MalformedURLException ex)
836         {
837           Cache.log.warn("Problem whilst trying to make a URL from '"
838                   + ((url != null) ? url : "<null>") + "'");
839           Cache.log.warn(
840                   "This was probably due to a malformed comma separated list"
841                           + " in the " + JWS2HOSTURLS
842                           + " entry of $(HOME)/.jalview_properties)");
843           Cache.log.debug("Exception was ", ex);
844         }
845       }
846     } catch (Exception ex)
847     {
848       Cache.log.warn("Error parsing comma separated list of urls in "
849               + JWS2HOSTURLS + " preference.", ex);
850     }
851     return urls;
852   }
853
854   public Vector<ServiceWithParameters> getServices()
855   {
856     return (services == null) ? new Vector<>()
857             : new Vector<>(services);
858   }
859
860   /**
861    * test the given URL with the JabaWS test code
862    * 
863    * @param foo
864    * @return
865    */
866   public static boolean testServiceUrl(URL foo)
867   {
868     try
869     {
870       compbio.ws.client.WSTester
871               .main(new String[]
872               { "-h=" + foo.toString() });
873     } catch (Exception e)
874     {
875       e.printStackTrace();
876       return false;
877     } catch (OutOfMemoryError e)
878     {
879       e.printStackTrace();
880       return false;
881     } catch (Error e)
882     {
883       e.printStackTrace();
884       return false;
885     }
886
887     return true;
888   }
889
890   public boolean restart()
891   {
892     synchronized (this)
893     {
894       if (running)
895       {
896         aborted = true;
897       }
898       else
899       {
900         running = true;
901       }
902       return aborted;
903     }
904   }
905
906   /**
907    * Start a fresh discovery thread and notify the given object when we're
908    * finished. Any known existing threads will be killed before this one is
909    * started.
910    * 
911    * @param changeSupport2
912    * @return new thread
913    */
914   public Thread startDiscoverer(PropertyChangeListener changeSupport2)
915   {
916     /*    if (restart())
917         {
918           return;
919         }
920         else
921         {
922           Thread thr = new Thread(this);
923           thr.start();
924         }
925        */
926     if (isRunning())
927     {
928       setAborted(true);
929     }
930     addPropertyChangeListener(changeSupport2);
931     Thread thr = new Thread(this);
932     thr.start();
933     return thr;
934   }
935
936   /**
937    * @return the invalidServiceUrls
938    */
939   public Vector<String> getInvalidServiceUrls()
940   {
941     return invalidServiceUrls;
942   }
943
944   /**
945    * @return the urlsWithoutServices
946    */
947   public Vector<String> getUrlsWithoutServices()
948   {
949     return urlsWithoutServices;
950   }
951
952   /**
953    * add an 'empty' JABA server to the list. Only servers not already in the
954    * 'bad URL' list will be added to this list.
955    * 
956    * @param jwsservers
957    */
958   public synchronized void addUrlwithnoservices(String jwsservers)
959   {
960     if (urlsWithoutServices == null)
961     {
962       urlsWithoutServices = new Vector<>();
963     }
964
965     if ((invalidServiceUrls == null
966             || !invalidServiceUrls.contains(jwsservers))
967             && !urlsWithoutServices.contains(jwsservers))
968     {
969       urlsWithoutServices.add(jwsservers);
970     }
971   }
972
973   /**
974    * add a bad URL to the list
975    * 
976    * @param jwsservers
977    */
978   public synchronized void addInvalidServiceUrl(String jwsservers)
979   {
980     if (invalidServiceUrls == null)
981     {
982       invalidServiceUrls = new Vector<>();
983     }
984     if (!invalidServiceUrls.contains(jwsservers))
985     {
986       invalidServiceUrls.add(jwsservers);
987     }
988   }
989
990   /**
991    * 
992    * @return a human readable report of any problems with the service URLs used
993    *         for discovery
994    */
995   public String getErrorMessages()
996   {
997     if (!isRunning() && !isAborted())
998     {
999       StringBuffer ermsg = new StringBuffer();
1000       boolean list = false;
1001       if (getInvalidServiceUrls() != null
1002               && getInvalidServiceUrls().size() > 0)
1003       {
1004         ermsg.append(MessageManager.getString("warn.urls_not_contacted")
1005                 + ": \n");
1006         for (String svcurl : getInvalidServiceUrls())
1007         {
1008           if (list)
1009           {
1010             ermsg.append(", ");
1011           }
1012           list = true;
1013           ermsg.append(svcurl);
1014         }
1015         ermsg.append("\n\n");
1016       }
1017       list = false;
1018       if (getUrlsWithoutServices() != null
1019               && getUrlsWithoutServices().size() > 0)
1020       {
1021         ermsg.append(
1022                 MessageManager.getString("warn.urls_no_jaba") + ": \n");
1023         for (String svcurl : getUrlsWithoutServices())
1024         {
1025           if (list)
1026           {
1027             ermsg.append(", ");
1028           }
1029           list = true;
1030           ermsg.append(svcurl);
1031         }
1032         ermsg.append("\n");
1033       }
1034       if (ermsg.length() > 1)
1035       {
1036         return ermsg.toString();
1037       }
1038
1039     }
1040     return null;
1041   }
1042
1043   public int getServerStatusFor(String url)
1044   {
1045     if (validServiceUrls != null && validServiceUrls.contains(url))
1046     {
1047       return 1;
1048     }
1049     if (urlsWithoutServices != null && urlsWithoutServices.contains(url))
1050     {
1051       return 0;
1052     }
1053     if (invalidServiceUrls != null && invalidServiceUrls.contains(url))
1054     {
1055       return -1;
1056     }
1057     return -2;
1058   }
1059
1060   /**
1061    * Set a URL to try before any others. For use with command-line parameter to
1062    * configure a local Jabaws installation without the need to add to property
1063    * files.
1064    * 
1065    * @param value
1066    * @throws MalformedURLException
1067    */
1068   public void setPreferredUrl(String value) throws MalformedURLException
1069   {
1070     if (value != null && value.trim().length() > 0)
1071     {
1072       new URL(value);
1073       preferredUrl = value;
1074     }
1075   }
1076 }