Revert "JAL-2799 all tabs now get mouse listeners and Jalview switches tree view"
[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.Console;
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    * Singleton instance
75    */
76   private static Jws2Discoverer discoverer;
77
78   /*
79    * Override for testing only
80    */
81   private static List<String> testUrls = null;
82
83   // preferred url has precedence over others
84   private String preferredUrl;
85
86   private PropertyChangeSupport changeSupport = new PropertyChangeSupport(
87           this);
88
89   private Vector<String> invalidServiceUrls = null;
90
91   private Vector<String> urlsWithoutServices = null;
92
93   private Vector<String> validServiceUrls = null;
94
95   private volatile boolean running = false;
96
97   private volatile boolean aborted = false;
98
99   private Thread oldthread = null;
100
101   /**
102    * holds list of services.
103    */
104   protected Vector<Jws2Instance> services;
105
106   /**
107    * Private constructor enforces use of singleton via getDiscoverer()
108    */
109   private Jws2Discoverer()
110   {
111   }
112
113   /**
114    * change listeners are notified of "services" property changes
115    * 
116    * @param listener
117    *          to be added that consumes new services Hashtable object.
118    */
119   public void addPropertyChangeListener(
120           java.beans.PropertyChangeListener listener)
121   {
122     changeSupport.addPropertyChangeListener(listener);
123   }
124
125   /**
126    * 
127    * 
128    * @param listener
129    *          to be removed
130    */
131   public void removePropertyChangeListener(
132           java.beans.PropertyChangeListener listener)
133   {
134     changeSupport.removePropertyChangeListener(listener);
135   }
136
137   /**
138    * @return the aborted
139    */
140   public boolean isAborted()
141   {
142     return aborted;
143   }
144
145   /**
146    * @param aborted
147    *          the aborted to set
148    */
149   public void setAborted(boolean aborted)
150   {
151     this.aborted = aborted;
152   }
153
154   @Override
155   public void run()
156   {
157
158     if (running && oldthread != null && oldthread.isAlive())
159     {
160       if (!aborted)
161       {
162         return;
163       }
164       while (running)
165       {
166         try
167         {
168           Console.debug(
169                   "Waiting around for old discovery thread to finish.");
170           // wait around until old discoverer dies
171           Thread.sleep(100);
172         } catch (Exception e)
173         {
174         }
175       }
176       aborted = false;
177       Console.debug("Old discovery thread has finished.");
178     }
179     running = true;
180
181     // first set up exclusion list if needed
182     final Set<String> ignoredServices = new HashSet<>();
183     for (String ignored : Cache
184             .getDefault("IGNORED_JABAWS_SERVICETYPES", "").split("\\|"))
185     {
186       ignoredServices.add(ignored);
187     }
188
189     changeSupport.firePropertyChange("services", services,
190             new Vector<Jws2Instance>());
191     oldthread = Thread.currentThread();
192     try
193     {
194       Class foo = getClass().getClassLoader()
195               .loadClass("compbio.ws.client.Jws2Client");
196     } catch (ClassNotFoundException e)
197     {
198       System.err.println(
199               "Not enabling JABA Webservices : client jar is not available."
200                       + "\nPlease check that your webstart JNLP file is up to date!");
201       running = false;
202       return;
203     }
204     // reinitialise records of good and bad service URLs
205     if (services != null)
206     {
207       services.removeAllElements();
208     }
209     if (urlsWithoutServices != null)
210     {
211       urlsWithoutServices.removeAllElements();
212     }
213     if (invalidServiceUrls != null)
214     {
215       invalidServiceUrls.removeAllElements();
216     }
217     if (validServiceUrls != null)
218     {
219       validServiceUrls.removeAllElements();
220     }
221     ArrayList<String> svctypes = new ArrayList<>();
222
223     List<JabaWsServerQuery> qrys = new ArrayList<>();
224     for (final String jwsserver : getServiceUrls())
225     {
226       JabaWsServerQuery squery = new JabaWsServerQuery(this, jwsserver);
227       if (svctypes.size() == 0)
228       {
229         // TODO: remove this ugly hack to get Canonical JABA service ordering
230         // for all possible services
231         for (Services sv : squery.JABAWS2SERVERS)
232         {
233           if (!ignoredServices.contains(sv.toString()))
234           {
235             svctypes.add(sv.toString());
236           }
237         }
238
239       }
240       qrys.add(squery);
241       new Thread(squery, "JabaQueryThread").start();
242     }
243     boolean finished = true;
244     do
245     {
246       finished = true;
247       try
248       {
249         Thread.sleep(100);
250       } catch (Exception e)
251       {
252       }
253       for (JabaWsServerQuery squery : qrys)
254       {
255         if (squery.isRunning())
256         {
257           finished = false;
258         }
259       }
260       if (aborted)
261       {
262         Console.debug(
263                 "Aborting " + qrys.size() + " 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<>();
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", new Vector<Jws2Instance>(),
301             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<>();
316     }
317     System.out.println(
318             "Discovered service: " + jwsservers + " " + 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<>();
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<>();
367     // jws2al.removeAll();
368     Map<String, Jws2Instance> preferredHosts = new HashMap<>();
369     Map<String, List<Jws2Instance>> alternates = new HashMap<>();
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<>();
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(
437                 MessageManager.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               }, "LoadPreferredServiceThread").start();
462             }
463           });
464         }
465       }
466     }
467   }
468
469   /**
470    * add services using the Java 2.5/2.6/2.7 system which optionally creates
471    * submenus to index by host and service program type
472    */
473   private void addEnumeratedServices(final JMenu jws2al,
474           final AlignFrame alignFrame,
475           List<Jws2Instance> enumerableServices)
476   {
477     boolean byhost = Cache.getDefault("WSMENU_BYHOST", false),
478             bytype = Cache.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<>();
486     Hashtable<String, String> lasthostFor = new Hashtable<>();
487     Hashtable<String, ArrayList<Jws2Instance>> hosts = new Hashtable<>();
488     ArrayList<String> hostlist = new ArrayList<>();
489     for (Jws2Instance service : enumerableServices)
490     {
491       ArrayList<Jws2Instance> hostservices = hosts.get(service.getHost());
492       if (hostservices == null)
493       {
494         hosts.put(service.getHost(), hostservices = new ArrayList<>());
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)
503               .toArray(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
520                     .formatMessage("label.services_at", new String[]
521                     { 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 && !hostLabels.contains(
533                 host + service.serviceType + service.getActionText()))
534         // !hostLabels.contains(host + (bytype ?
535         // service.serviceType+service.getActionText() : "")))
536         {
537           // add a marker indicating where this service is hosted
538           // relies on services from the same host being listed in a
539           // contiguous
540           // group
541           JMenuItem hitm;
542           if (hostLabels.contains(host))
543           {
544             atpoint.addSeparator();
545           }
546           else
547           {
548             hostLabels.add(host);
549           }
550           if (lasthostFor.get(service.action) == null
551                   || !lasthostFor.get(service.action).equals(host))
552           {
553             atpoint.add(hitm = new JMenuItem(host));
554             hitm.setForeground(Color.blue);
555             hitm.addActionListener(new ActionListener()
556             {
557
558               @Override
559               public void actionPerformed(ActionEvent e)
560               {
561                 Desktop.showUrl(service.getHost());
562               }
563             });
564             hitm.setToolTipText(
565                     JvSwingUtils.wrapTooltip(true, MessageManager
566                             .getString("label.open_jabaws_web_page")));
567             lasthostFor.put(service.action, host);
568           }
569           hostLabels.add(
570                   host + service.serviceType + service.getActionText());
571         }
572
573         service.attachWSMenuEntry(atpoint, alignFrame);
574       }
575     }
576   }
577
578   /**
579    * 
580    * @param args
581    * @j2sIgnore
582    */
583   public static void main(String[] args)
584   {
585     if (args.length > 0)
586     {
587       testUrls = new ArrayList<>();
588       for (String url : args)
589       {
590         testUrls.add(url);
591       }
592     }
593     Thread runner = getDiscoverer()
594             .startDiscoverer(new PropertyChangeListener()
595             {
596
597               @Override
598               public void propertyChange(PropertyChangeEvent evt)
599               {
600                 if (getDiscoverer().services != null)
601                 {
602                   System.out.println("Changesupport: There are now "
603                           + getDiscoverer().services.size() + " services");
604                   int i = 1;
605                   for (Jws2Instance instance : getDiscoverer().services)
606                   {
607                     System.out.println("Service " + i++ + " "
608                             + instance.getClass() + "@" + instance.getHost()
609                             + ": " + instance.getActionText());
610                   }
611
612                 }
613               }
614             });
615     while (runner.isAlive())
616     {
617       try
618       {
619         Thread.sleep(50);
620       } catch (InterruptedException e)
621       {
622       }
623     }
624     try
625     {
626       Thread.sleep(50);
627     } catch (InterruptedException x)
628     {
629     }
630   }
631
632   /**
633    * Returns the singleton instance of this class.
634    * 
635    * @return
636    */
637   public static Jws2Discoverer getDiscoverer()
638   {
639     if (discoverer == null)
640     {
641       discoverer = new Jws2Discoverer();
642     }
643     return discoverer;
644   }
645
646   public boolean hasServices()
647   {
648     return !running && services != null && services.size() > 0;
649   }
650
651   public boolean isRunning()
652   {
653     return running;
654   }
655
656   public void setServiceUrls(List<String> wsUrls)
657   {
658     if (wsUrls != null && !wsUrls.isEmpty())
659     {
660       StringBuilder urls = new StringBuilder(128);
661       String sep = "";
662       for (String url : wsUrls)
663       {
664         urls.append(sep);
665         urls.append(url);
666         sep = ",";
667       }
668       Cache.setProperty(JWS2HOSTURLS, urls.toString());
669     }
670     else
671     {
672       Cache.removeProperty(JWS2HOSTURLS);
673     }
674   }
675
676   /**
677    * Returns web service URLs, in the order in which they should be tried (or an
678    * empty list).
679    * 
680    * @return
681    */
682   public List<String> getServiceUrls()
683   {
684     if (testUrls != null)
685     {
686       // return test urls, if there are any, instead of touching cache
687       return testUrls;
688     }
689     List<String> urls = new ArrayList<>();
690
691     if (this.preferredUrl != null)
692     {
693       urls.add(preferredUrl);
694     }
695
696     String surls = Cache.getDefault(JWS2HOSTURLS, COMPBIO_JABAWS);
697     try
698     {
699       StringTokenizer st = new StringTokenizer(surls, ",");
700       while (st.hasMoreElements())
701       {
702         String url = null;
703         try
704         {
705           url = st.nextToken();
706           new URL(url);
707           if (!urls.contains(url))
708           {
709             urls.add(url);
710           }
711           else
712           {
713             Console.warn("Ignoring duplicate url " + url + " in "
714                     + JWS2HOSTURLS + " list");
715           }
716         } catch (MalformedURLException ex)
717         {
718           Console.warn("Problem whilst trying to make a URL from '"
719                   + ((url != null) ? url : "<null>") + "'");
720           Console.warn(
721                   "This was probably due to a malformed comma separated list"
722                           + " in the " + JWS2HOSTURLS
723                           + " entry of $(HOME)/.jalview_properties)");
724           Console.debug("Exception was ", ex);
725         }
726       }
727     } catch (Exception ex)
728     {
729       Console.warn("Error parsing comma separated list of urls in "
730               + JWS2HOSTURLS + " preference.", ex);
731     }
732     return urls;
733   }
734
735   public Vector<Jws2Instance> getServices()
736   {
737     return (services == null) ? new Vector<Jws2Instance>()
738             : new Vector<>(services);
739   }
740
741   /**
742    * test the given URL with the JabaWS test code
743    * 
744    * @param foo
745    * @return
746    */
747   public static boolean testServiceUrl(URL foo)
748   {
749     try
750     {
751       compbio.ws.client.WSTester
752               .main(new String[]
753               { "-h=" + foo.toString() });
754     } catch (Exception e)
755     {
756       e.printStackTrace();
757       return false;
758     } catch (OutOfMemoryError e)
759     {
760       e.printStackTrace();
761       return false;
762     } catch (Error e)
763     {
764       e.printStackTrace();
765       return false;
766     }
767
768     return true;
769   }
770
771   public boolean restart()
772   {
773     synchronized (this)
774     {
775       if (running)
776       {
777         aborted = true;
778       }
779       else
780       {
781         running = true;
782       }
783       return aborted;
784     }
785   }
786
787   /**
788    * Start a fresh discovery thread and notify the given object when we're
789    * finished. Any known existing threads will be killed before this one is
790    * started.
791    * 
792    * @param changeSupport2
793    * @return new thread
794    */
795   public Thread startDiscoverer(PropertyChangeListener changeSupport2)
796   {
797     /*    if (restart())
798         {
799           return;
800         }
801         else
802         {
803           Thread thr = new Thread(this);
804           thr.start();
805         }
806        */
807     if (isRunning())
808     {
809       setAborted(true);
810     }
811     addPropertyChangeListener(changeSupport2);
812     Thread thr = new Thread(this);
813     thr.start();
814     return thr;
815   }
816
817   /**
818    * @return the invalidServiceUrls
819    */
820   public Vector<String> getInvalidServiceUrls()
821   {
822     return invalidServiceUrls;
823   }
824
825   /**
826    * @return the urlsWithoutServices
827    */
828   public Vector<String> getUrlsWithoutServices()
829   {
830     return urlsWithoutServices;
831   }
832
833   /**
834    * add an 'empty' JABA server to the list. Only servers not already in the
835    * 'bad URL' list will be added to this list.
836    * 
837    * @param jwsservers
838    */
839   public synchronized void addUrlwithnoservices(String jwsservers)
840   {
841     if (urlsWithoutServices == null)
842     {
843       urlsWithoutServices = new Vector<>();
844     }
845
846     if ((invalidServiceUrls == null
847             || !invalidServiceUrls.contains(jwsservers))
848             && !urlsWithoutServices.contains(jwsservers))
849     {
850       urlsWithoutServices.add(jwsservers);
851     }
852   }
853
854   /**
855    * add a bad URL to the list
856    * 
857    * @param jwsservers
858    */
859   public synchronized void addInvalidServiceUrl(String jwsservers)
860   {
861     if (invalidServiceUrls == null)
862     {
863       invalidServiceUrls = new Vector<>();
864     }
865     if (!invalidServiceUrls.contains(jwsservers))
866     {
867       invalidServiceUrls.add(jwsservers);
868     }
869   }
870
871   /**
872    * 
873    * @return a human readable report of any problems with the service URLs used
874    *         for discovery
875    */
876   public String getErrorMessages()
877   {
878     if (!isRunning() && !isAborted())
879     {
880       StringBuffer ermsg = new StringBuffer();
881       boolean list = false;
882       if (getInvalidServiceUrls() != null
883               && getInvalidServiceUrls().size() > 0)
884       {
885         ermsg.append(MessageManager.getString("warn.urls_not_contacted")
886                 + ": \n");
887         for (String svcurl : getInvalidServiceUrls())
888         {
889           if (list)
890           {
891             ermsg.append(", ");
892           }
893           list = true;
894           ermsg.append(svcurl);
895         }
896         ermsg.append("\n\n");
897       }
898       list = false;
899       if (getUrlsWithoutServices() != null
900               && getUrlsWithoutServices().size() > 0)
901       {
902         ermsg.append(
903                 MessageManager.getString("warn.urls_no_jaba") + ": \n");
904         for (String svcurl : getUrlsWithoutServices())
905         {
906           if (list)
907           {
908             ermsg.append(", ");
909           }
910           list = true;
911           ermsg.append(svcurl);
912         }
913         ermsg.append("\n");
914       }
915       if (ermsg.length() > 1)
916       {
917         return ermsg.toString();
918       }
919
920     }
921     return null;
922   }
923
924   public int getServerStatusFor(String url)
925   {
926     if (validServiceUrls != null && validServiceUrls.contains(url))
927     {
928       return 1;
929     }
930     if (urlsWithoutServices != null && urlsWithoutServices.contains(url))
931     {
932       return 0;
933     }
934     if (invalidServiceUrls != null && invalidServiceUrls.contains(url))
935     {
936       return -1;
937     }
938     return -2;
939   }
940
941   /**
942    * pick the user's preferred service based on a set of URLs (jaba server
943    * locations) and service URIs (specifying version and service interface
944    * class)
945    * 
946    * @param serviceURL
947    * @return null or best match for given uri/ls.
948    */
949   public Jws2Instance getPreferredServiceFor(String[] serviceURLs)
950   {
951     HashSet<String> urls = new HashSet<>();
952     urls.addAll(Arrays.asList(serviceURLs));
953     Jws2Instance match = null;
954     if (services != null)
955     {
956       for (Jws2Instance svc : services)
957       {
958         if (urls.contains(svc.getServiceTypeURI()))
959         {
960           if (match == null)
961           {
962             // for moment we always pick service from server ordered first in
963             // user's preferences
964             match = svc;
965           }
966           if (urls.contains(svc.getUri()))
967           {
968             // stop and return - we've matched type URI and URI for service
969             // endpoint
970             return svc;
971           }
972         }
973       }
974     }
975     return match;
976   }
977
978   Map<String, Map<String, String>> preferredServiceMap = new HashMap<>();
979
980   /**
981    * get current preferred service of the given type, or global default
982    * 
983    * @param af
984    *          null or a specific alignFrame
985    * @param serviceType
986    *          Jws2Instance.serviceType for service
987    * @return null if no service of this type is available, the preferred service
988    *         for the serviceType and af if specified and if defined.
989    */
990   public Jws2Instance getPreferredServiceFor(AlignFrame af,
991           String serviceType)
992   {
993     String serviceurl = null;
994     synchronized (preferredServiceMap)
995     {
996       String afid = (af == null) ? "" : af.getViewport().getSequenceSetId();
997       Map<String, String> prefmap = preferredServiceMap.get(afid);
998       if (afid.length() > 0 && prefmap == null)
999       {
1000         // recover global setting, if any
1001         prefmap = preferredServiceMap.get("");
1002       }
1003       if (prefmap != null)
1004       {
1005         serviceurl = prefmap.get(serviceType);
1006       }
1007
1008     }
1009     Jws2Instance response = null;
1010     for (Jws2Instance svc : services)
1011     {
1012       if (svc.serviceType.equals(serviceType))
1013       {
1014         if (serviceurl == null || serviceurl.equals(svc.getHost()))
1015         {
1016           response = svc;
1017           break;
1018         }
1019       }
1020     }
1021     return response;
1022   }
1023
1024   public void setPreferredServiceFor(AlignFrame af, String serviceType,
1025           String serviceAction, Jws2Instance selectedServer)
1026   {
1027     String afid = (af == null) ? "" : af.getViewport().getSequenceSetId();
1028     if (preferredServiceMap == null)
1029     {
1030       preferredServiceMap = new HashMap<>();
1031     }
1032     Map<String, String> prefmap = preferredServiceMap.get(afid);
1033     if (prefmap == null)
1034     {
1035       prefmap = new HashMap<>();
1036       preferredServiceMap.put(afid, prefmap);
1037     }
1038     prefmap.put(serviceType, selectedServer.getHost());
1039     prefmap.put(serviceAction, selectedServer.getHost());
1040   }
1041
1042   public void setPreferredServiceFor(String serviceType,
1043           String serviceAction, Jws2Instance selectedServer)
1044   {
1045     setPreferredServiceFor(null, serviceType, serviceAction,
1046             selectedServer);
1047   }
1048
1049   /**
1050    * Set a URL to try before any others. For use with command-line parameter to
1051    * configure a local Jabaws installation without the need to add to property
1052    * files.
1053    * 
1054    * @param value
1055    * @throws MalformedURLException
1056    */
1057   public void setPreferredUrl(String value) throws MalformedURLException
1058   {
1059     if (value != null && value.trim().length() > 0)
1060     {
1061       new URL(value);
1062       preferredUrl = value;
1063     }
1064   }
1065 }