adca0fa7f9ab490fef4eb97d92c74fb30bfed2fb
[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.jws2.jabaws2.Jws2Instance;
30 import jalview.ws.params.ParamDatastoreI;
31
32 import java.awt.Color;
33 import java.awt.event.ActionEvent;
34 import java.awt.event.ActionListener;
35 import java.beans.PropertyChangeEvent;
36 import java.beans.PropertyChangeListener;
37 import java.beans.PropertyChangeSupport;
38 import java.net.MalformedURLException;
39 import java.net.URL;
40 import java.util.ArrayList;
41 import java.util.Arrays;
42 import java.util.HashMap;
43 import java.util.HashSet;
44 import java.util.Hashtable;
45 import java.util.List;
46 import java.util.Map;
47 import java.util.Set;
48 import java.util.StringTokenizer;
49 import java.util.Vector;
50
51 import javax.swing.JMenu;
52 import javax.swing.JMenuItem;
53
54 import compbio.ws.client.Services;
55
56 /**
57  * discoverer for jws2 services. Follows the lightweight service discoverer
58  * pattern (archetyped by EnfinEnvision2OneWay)
59  * 
60  * @author JimP
61  * 
62  */
63 public class Jws2Discoverer implements Runnable, WSMenuEntryProviderI
64 {
65   public static final String COMPBIO_JABAWS = "http://www.compbio.dundee.ac.uk/jabaws";
66
67   /*
68    * the .jalview_properties entry for JWS2 URLS
69    */
70   private final static String JWS2HOSTURLS = "JWS2HOSTURLS";
71
72   /*
73    * Singleton instance
74    */
75   private static Jws2Discoverer discoverer;
76
77   /*
78    * Override for testing only
79    */
80   private static List<String> testUrls = null;
81
82   // preferred url has precedence over others
83   private String preferredUrl;
84
85   private PropertyChangeSupport changeSupport = new PropertyChangeSupport(
86           this);
87
88   private Vector<String> invalidServiceUrls = null;
89
90   private Vector<String> urlsWithoutServices = null;
91
92   private Vector<String> validServiceUrls = null;
93
94   private volatile boolean running = false;
95
96   private volatile boolean aborted = false;
97
98   private Thread oldthread = null;
99
100   /**
101    * holds list of services.
102    */
103   protected Vector<Jws2Instance> services;
104
105   /**
106    * Private constructor enforces use of singleton via getDiscoverer()
107    */
108   private Jws2Discoverer()
109   {
110   }
111
112   /**
113    * change listeners are notified of "services" property changes
114    * 
115    * @param listener
116    *          to be added that consumes new services Hashtable object.
117    */
118   public void addPropertyChangeListener(
119           java.beans.PropertyChangeListener listener)
120   {
121     changeSupport.addPropertyChangeListener(listener);
122   }
123
124   /**
125    * 
126    * 
127    * @param listener
128    *          to be removed
129    */
130   public void removePropertyChangeListener(
131           java.beans.PropertyChangeListener listener)
132   {
133     changeSupport.removePropertyChangeListener(listener);
134   }
135
136   /**
137    * @return the aborted
138    */
139   public boolean isAborted()
140   {
141     return aborted;
142   }
143
144   /**
145    * @param aborted
146    *          the aborted to set
147    */
148   public void setAborted(boolean aborted)
149   {
150     this.aborted = aborted;
151   }
152
153   @Override
154   public void run()
155   {
156
157     if (running && oldthread != null && oldthread.isAlive())
158     {
159       if (!aborted)
160       {
161         return;
162       }
163       while (running)
164       {
165         try
166         {
167           Cache.log
168                   .debug("Waiting around for old discovery thread to finish.");
169           // wait around until old discoverer dies
170           Thread.sleep(100);
171         } catch (Exception e)
172         {
173         }
174       }
175       Cache.log.debug("Old discovery thread has finished.");
176     }
177     running = true;
178
179     // first set up exclusion list if needed
180     final Set<String> ignoredServices = new HashSet<String>();
181     for (String ignored : Cache.getDefault("IGNORED_JABAWS_SERVICETYPES",
182             "").split("\\|"))
183     {
184       ignoredServices.add(ignored);
185     }
186
187     changeSupport.firePropertyChange("services", services,
188             new Vector<Jws2Instance>());
189     oldthread = Thread.currentThread();
190     try
191     {
192       Class foo = getClass().getClassLoader().loadClass(
193               "compbio.ws.client.Jws2Client");
194     } catch (ClassNotFoundException e)
195     {
196       System.err
197               .println("Not enabling JABA Webservices : client jar is not available."
198                       + "\nPlease check that your webstart JNLP file is up to date!");
199       running = false;
200       return;
201     }
202     // reinitialise records of good and bad service URLs
203     if (services != null)
204     {
205       services.removeAllElements();
206     }
207     if (urlsWithoutServices != null)
208     {
209       urlsWithoutServices.removeAllElements();
210     }
211     if (invalidServiceUrls != null)
212     {
213       invalidServiceUrls.removeAllElements();
214     }
215     if (validServiceUrls != null)
216     {
217       validServiceUrls.removeAllElements();
218     }
219     ArrayList<String> svctypes = new ArrayList<String>();
220
221     List<JabaWsServerQuery> qrys = new ArrayList<JabaWsServerQuery>();
222     for (final String jwsserver : getServiceUrls())
223     {
224       JabaWsServerQuery squery = new JabaWsServerQuery(this, jwsserver);
225       if (svctypes.size() == 0)
226       {
227         // TODO: remove this ugly hack to get Canonical JABA service ordering
228         // for all possible services
229         for (Services sv : squery.JABAWS2SERVERS)
230         {
231           if (!ignoredServices.contains(sv.toString()))
232           {
233             svctypes.add(sv.toString());
234           }
235         }
236
237       }
238       qrys.add(squery);
239       new Thread(squery).start();
240     }
241     boolean finished = true;
242     do
243     {
244       finished = true;
245       try
246       {
247         Thread.sleep(100);
248       } catch (Exception e)
249       {
250       }
251       ;
252       for (JabaWsServerQuery squery : qrys)
253       {
254         if (squery.isRunning())
255         {
256           finished = false;
257         }
258       }
259       if (aborted)
260       {
261         Cache.log.debug("Aborting " + qrys.size()
262                 + " JABAWS discovery threads.");
263         for (JabaWsServerQuery squery : qrys)
264         {
265           squery.setQuit(true);
266         }
267       }
268     } while (!aborted && !finished);
269     if (!aborted)
270     {
271       // resort services according to order found in jabaws service list
272       // also ensure services for each host are ordered in same way.
273
274       if (services != null && services.size() > 0)
275       {
276         Jws2Instance[] svcs = new Jws2Instance[services.size()];
277         int[] spos = new int[services.size()];
278         int ipos = 0;
279         List<String> svcUrls = getServiceUrls();
280         for (Jws2Instance svc : services)
281         {
282           svcs[ipos] = svc;
283           spos[ipos++] = 1000 * svcUrls.indexOf(svc.getHost()) + 1
284                   + svctypes.indexOf(svc.serviceType);
285         }
286         jalview.util.QuickSort.sort(spos, svcs);
287         services = new Vector<Jws2Instance>();
288         for (Jws2Instance svc : svcs)
289         {
290           if (!ignoredServices.contains(svc.serviceType))
291           {
292             services.add(svc);
293           }
294         }
295       }
296     }
297     oldthread = null;
298     running = false;
299     changeSupport.firePropertyChange("services",
300             new Vector<Jws2Instance>(), services);
301   }
302
303   /**
304    * record this service endpoint so we can use it
305    * 
306    * @param jwsservers
307    * @param srv
308    * @param service2
309    */
310   synchronized void addService(String jwsservers, Jws2Instance service)
311   {
312     if (services == null)
313     {
314       services = new Vector<Jws2Instance>();
315     }
316     System.out.println("Discovered service: " + jwsservers + " "
317             + service.toString());
318     // Jws2Instance service = new Jws2Instance(jwsservers, srv.toString(),
319     // service2);
320
321     services.add(service);
322     // retrieve the presets and parameter set and cache now
323     ParamDatastoreI pds = service.getParamStore();
324     if (pds != null)
325     {
326       pds.getPresets();
327     }
328     service.hasParameters();
329     if (validServiceUrls == null)
330     {
331       validServiceUrls = new Vector<String>();
332     }
333     validServiceUrls.add(jwsservers);
334   }
335
336   /**
337    * attach all available web services to the appropriate submenu in the given
338    * JMenu
339    */
340   @Override
341   public void attachWSMenuEntry(JMenu wsmenu, final AlignFrame alignFrame)
342   {
343     // dynamically regenerate service list.
344     populateWSMenuEntry(wsmenu, alignFrame, null);
345   }
346
347   private boolean isRecalculable(String action)
348   {
349     return (action != null && action.equalsIgnoreCase("conservation"));
350   }
351
352   private void populateWSMenuEntry(JMenu jws2al,
353           final AlignFrame alignFrame, String typeFilter)
354   {
355     if (running || services == null || services.size() == 0)
356     {
357       return;
358     }
359
360     /**
361      * eventually, JWS2 services will appear under the same align/etc submenus.
362      * for moment we keep them separate.
363      */
364     JMenu atpoint;
365     List<Jws2Instance> enumerableServices = new ArrayList<Jws2Instance>();
366     // jws2al.removeAll();
367     Map<String, Jws2Instance> preferredHosts = new HashMap<String, Jws2Instance>();
368     Map<String, List<Jws2Instance>> alternates = new HashMap<String, List<Jws2Instance>>();
369     for (Jws2Instance service : services.toArray(new Jws2Instance[0]))
370     {
371       if (!isRecalculable(service.action))
372       {
373         // add 'one shot' services to be displayed using the classic menu
374         // structure
375         enumerableServices.add(service);
376       }
377       else
378       {
379         if (!preferredHosts.containsKey(service.serviceType))
380         {
381           Jws2Instance preferredInstance = getPreferredServiceFor(
382                   alignFrame, service.serviceType);
383           if (preferredInstance != null)
384           {
385             preferredHosts.put(service.serviceType, preferredInstance);
386           }
387           else
388           {
389             preferredHosts.put(service.serviceType, service);
390           }
391         }
392         List<Jws2Instance> ph = alternates.get(service.serviceType);
393         if (preferredHosts.get(service.serviceType) != service)
394         {
395           if (ph == null)
396           {
397             ph = new ArrayList<Jws2Instance>();
398           }
399           ph.add(service);
400           alternates.put(service.serviceType, ph);
401         }
402       }
403
404     }
405
406     // create GUI element for classic services
407     addEnumeratedServices(jws2al, alignFrame, enumerableServices);
408     // and the instantaneous services
409     for (final Jws2Instance service : preferredHosts.values())
410     {
411       atpoint = JvSwingUtils.findOrCreateMenu(jws2al, service.action);
412       JMenuItem hitm;
413       if (atpoint.getItemCount() > 1)
414       {
415         // previous service of this type already present
416         atpoint.addSeparator();
417       }
418       atpoint.add(hitm = new JMenuItem(service.getHost()));
419       hitm.setForeground(Color.blue);
420       hitm.addActionListener(new ActionListener()
421       {
422
423         @Override
424         public void actionPerformed(ActionEvent e)
425         {
426           Desktop.showUrl(service.getHost());
427         }
428       });
429       hitm.setToolTipText(JvSwingUtils.wrapTooltip(false,
430               MessageManager.getString("label.open_jabaws_web_page")));
431
432       service.attachWSMenuEntry(atpoint, alignFrame);
433       if (alternates.containsKey(service.serviceType))
434       {
435         atpoint.add(hitm = new JMenu(MessageManager
436                 .getString("label.switch_server")));
437         hitm.setToolTipText(JvSwingUtils.wrapTooltip(false,
438                 MessageManager.getString("label.choose_jabaws_server")));
439         for (final Jws2Instance sv : alternates.get(service.serviceType))
440         {
441           JMenuItem itm;
442           hitm.add(itm = new JMenuItem(sv.getHost()));
443           itm.setForeground(Color.blue);
444           itm.addActionListener(new ActionListener()
445           {
446
447             @Override
448             public void actionPerformed(ActionEvent arg0)
449             {
450               new Thread(new Runnable()
451               {
452                 @Override
453                 public void run()
454                 {
455                   setPreferredServiceFor(alignFrame, sv.serviceType,
456                           sv.action, sv);
457                   changeSupport.firePropertyChange("services",
458                           new Vector<Jws2Instance>(), services);
459                 };
460               }).start();
461
462             }
463           });
464         }
465       }
466     }
467   }
468
469   /**
470    * add services using the Java 2.5/2.6/2.7 system which optionally creates
471    * submenus to index by host and service program type
472    */
473   private void addEnumeratedServices(final JMenu jws2al,
474           final AlignFrame alignFrame, List<Jws2Instance> enumerableServices)
475   {
476     boolean byhost = Cache.getDefault("WSMENU_BYHOST", false), bytype = Cache
477             .getDefault("WSMENU_BYTYPE", false);
478     /**
479      * eventually, JWS2 services will appear under the same align/etc submenus.
480      * for moment we keep them separate.
481      */
482     JMenu atpoint;
483
484     List<String> hostLabels = new ArrayList<String>();
485     Hashtable<String, String> lasthostFor = new Hashtable<String, String>();
486     Hashtable<String, ArrayList<Jws2Instance>> hosts = new Hashtable<String, ArrayList<Jws2Instance>>();
487     ArrayList<String> hostlist = new ArrayList<String>();
488     for (Jws2Instance service : enumerableServices)
489     {
490       ArrayList<Jws2Instance> hostservices = hosts.get(service.getHost());
491       if (hostservices == null)
492       {
493         hosts.put(service.getHost(),
494                 hostservices = new ArrayList<Jws2Instance>());
495         hostlist.add(service.getHost());
496       }
497       hostservices.add(service);
498     }
499     // now add hosts in order of the given array
500     for (String host : hostlist)
501     {
502       Jws2Instance orderedsvcs[] = hosts.get(host).toArray(
503               new Jws2Instance[1]);
504       String sortbytype[] = new String[orderedsvcs.length];
505       for (int i = 0; i < sortbytype.length; i++)
506       {
507         sortbytype[i] = orderedsvcs[i].serviceType;
508       }
509       jalview.util.QuickSort.sort(sortbytype, orderedsvcs);
510       for (final Jws2Instance service : orderedsvcs)
511       {
512         atpoint = JvSwingUtils.findOrCreateMenu(jws2al, service.action);
513         String type = service.serviceType;
514         if (byhost)
515         {
516           atpoint = JvSwingUtils.findOrCreateMenu(atpoint, host);
517           if (atpoint.getToolTipText() == null)
518           {
519             atpoint.setToolTipText(MessageManager.formatMessage(
520                     "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.wrapTooltip(true,
565                     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               @Override
593               public void propertyChange(PropertyChangeEvent evt)
594               {
595                 if (getDiscoverer().services != null)
596                 {
597                   System.out.println("Changesupport: There are now "
598                           + getDiscoverer().services.size() + " services");
599                   int i = 1;
600                   for (Jws2Instance instance : getDiscoverer().services)
601                   {
602                     System.out.println("Service " + i++ + " "
603                             + instance.getClass() + "@"
604                             + instance.getHost() + ": "
605                             + instance.getActionText());
606                   }
607
608                 }
609               }
610             });
611     while (runner.isAlive())
612     {
613       try
614       {
615         Thread.sleep(50);
616       } catch (InterruptedException e)
617       {
618       }
619       ;
620     }
621     try
622     {
623       Thread.sleep(50);
624     } catch (InterruptedException x)
625     {
626     }
627   }
628
629   /**
630    * Returns the singleton instance of this class.
631    * 
632    * @return
633    */
634   public static Jws2Discoverer getDiscoverer()
635   {
636     if (discoverer == null)
637     {
638       discoverer = new Jws2Discoverer();
639     }
640     return discoverer;
641   }
642
643   public boolean hasServices()
644   {
645     return !running && services != null && services.size() > 0;
646   }
647
648   public boolean isRunning()
649   {
650     return running;
651   }
652
653   public void setServiceUrls(List<String> wsUrls)
654   {
655     if (wsUrls != null && !wsUrls.isEmpty())
656     {
657       StringBuilder urls = new StringBuilder(128);
658       String sep = "";
659       for (String url : wsUrls)
660       {
661         urls.append(sep);
662         urls.append(url);
663         sep = ",";
664       }
665       Cache.setProperty(JWS2HOSTURLS, urls.toString());
666     }
667     else
668     {
669       Cache.removeProperty(JWS2HOSTURLS);
670     }
671   }
672
673   /**
674    * Returns web service URLs, in the order in which they should be tried (or an
675    * empty list).
676    * 
677    * @return
678    */
679   public List<String> getServiceUrls()
680   {
681     if (testUrls != null)
682     {
683       // return test urls, if there are any, instead of touching cache
684       return testUrls;
685     }
686     List<String> urls = new ArrayList<String>();
687
688     if (this.preferredUrl != null)
689     {
690       urls.add(preferredUrl);
691     }
692
693     String surls = Cache.getDefault(JWS2HOSTURLS, COMPBIO_JABAWS);
694     try
695     {
696       StringTokenizer st = new StringTokenizer(surls, ",");
697       while (st.hasMoreElements())
698       {
699         String url = null;
700         try
701         {
702           url = st.nextToken();
703           new URL(url);
704           if (!urls.contains(url))
705           {
706             urls.add(url);
707           }
708           else
709           {
710             Cache.log.warn("Ignoring duplicate url " + url + " in "
711                     + JWS2HOSTURLS + " list");
712           }
713         } catch (MalformedURLException ex)
714         {
715           Cache.log.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("Error parsing comma separated list of urls in "
728               + JWS2HOSTURLS + " preference.", ex);
729     }
730     return urls;
731   }
732
733   public Vector<Jws2Instance> getServices()
734   {
735     return (services == null) ? new Vector<Jws2Instance>()
736             : new Vector<Jws2Instance>(services);
737   }
738
739   /**
740    * test the given URL with the JabaWS test code
741    * 
742    * @param foo
743    * @return
744    */
745   public static boolean testServiceUrl(URL foo)
746   {
747     try
748     {
749       compbio.ws.client.WSTester
750               .main(new String[] { "-h=" + foo.toString() });
751     } catch (Exception e)
752     {
753       e.printStackTrace();
754       return false;
755     } catch (OutOfMemoryError e)
756     {
757       e.printStackTrace();
758       return false;
759     } catch (Error e)
760     {
761       e.printStackTrace();
762       return false;
763     }
764
765     return true;
766   }
767
768   /**
769    * Start a fresh discovery thread and notify the given object when we're
770    * finished. Any known existing threads will be killed before this one is
771    * started.
772    * 
773    * @param changeSupport2
774    * @return new thread
775    */
776   public Thread startDiscoverer(PropertyChangeListener changeSupport2)
777   {
778     if (isRunning())
779     {
780       setAborted(true);
781     }
782     addPropertyChangeListener(changeSupport2);
783     Thread thr = new Thread(this);
784     thr.start();
785     return thr;
786   }
787
788   /**
789    * @return the invalidServiceUrls
790    */
791   public Vector<String> getInvalidServiceUrls()
792   {
793     return invalidServiceUrls;
794   }
795
796   /**
797    * @return the urlsWithoutServices
798    */
799   public Vector<String> getUrlsWithoutServices()
800   {
801     return urlsWithoutServices;
802   }
803
804   /**
805    * add an 'empty' JABA server to the list. Only servers not already in the
806    * 'bad URL' list will be added to this list.
807    * 
808    * @param jwsservers
809    */
810   public synchronized void addUrlwithnoservices(String jwsservers)
811   {
812     if (urlsWithoutServices == null)
813     {
814       urlsWithoutServices = new Vector<String>();
815     }
816
817     if ((invalidServiceUrls == null || !invalidServiceUrls
818             .contains(jwsservers))
819             && !urlsWithoutServices.contains(jwsservers))
820     {
821       urlsWithoutServices.add(jwsservers);
822     }
823   }
824
825   /**
826    * add a bad URL to the list
827    * 
828    * @param jwsservers
829    */
830   public synchronized void addInvalidServiceUrl(String jwsservers)
831   {
832     if (invalidServiceUrls == null)
833     {
834       invalidServiceUrls = new Vector<String>();
835     }
836     if (!invalidServiceUrls.contains(jwsservers))
837     {
838       invalidServiceUrls.add(jwsservers);
839     }
840   }
841
842   /**
843    * 
844    * @return a human readable report of any problems with the service URLs used
845    *         for discovery
846    */
847   public String getErrorMessages()
848   {
849     if (!isRunning() && !isAborted())
850     {
851       StringBuffer ermsg = new StringBuffer();
852       boolean list = false;
853       if (getInvalidServiceUrls() != null
854               && getInvalidServiceUrls().size() > 0)
855       {
856         ermsg.append(MessageManager.getString("warn.urls_not_contacted")
857                 + ": \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(MessageManager.getString("warn.urls_no_jaba") + ": \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 }