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