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