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