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