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