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