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