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