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