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