refactored dropFile allowing known information to be passed in if available
[jalview.git] / src / jalview / bin / Jalview.java
1 /*
2  * Jalview - A Sequence Alignment Editor and Viewer (Version 2.6)
3  * Copyright (C) 2010 J Procter, AM Waterhouse, 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.bin;
19
20 import java.io.BufferedReader;
21 import java.io.File;
22 import java.io.FileOutputStream;
23 import java.io.IOException;
24 import java.io.OutputStreamWriter;
25 import java.io.PrintWriter;
26 import java.lang.reflect.Constructor;
27 import java.net.URL;
28 import java.net.URLDecoder;
29 import java.security.AllPermission;
30 import java.security.CodeSource;
31 import java.security.PermissionCollection;
32 import java.security.Permissions;
33 import java.security.Policy;
34 import java.util.*;
35
36 import javax.swing.*;
37
38 import jalview.gui.*;
39 import jalview.util.Platform;
40
41 /**
42  * Main class for Jalview Application <br>
43  * <br>
44  * start with java -Djava.ext.dirs=$PATH_TO_LIB$ jalview.bin.Jalview
45  * 
46  * @author $author$
47  * @version $Revision$
48  */
49 public class Jalview
50 {
51   static
52   {
53     // grab all the rights we can the JVM
54     Policy.setPolicy(new Policy()
55     {
56       public PermissionCollection getPermissions(CodeSource codesource)
57       {
58         Permissions perms = new Permissions();
59         perms.add(new AllPermission());
60         return (perms);
61       }
62
63       public void refresh()
64       {
65       }
66     });
67   }
68
69   /**
70    * main class for Jalview application
71    * 
72    * @param args
73    *          open <em>filename</em>
74    */
75   public static void main(String[] args)
76   {
77     System.out.println("Java version: "
78             + System.getProperty("java.version"));
79     System.out.println(System.getProperty("os.arch") + " "
80             + System.getProperty("os.name") + " "
81             + System.getProperty("os.version"));
82     if (new Platform().isAMac())
83     {
84       System.setProperty("com.apple.mrj.application.apple.menu.about.name",
85               "Jalview");
86       System.setProperty("apple.laf.useScreenMenuBar", "true");
87     }
88
89     ArgsParser aparser = new ArgsParser(args);
90     boolean headless = false;
91
92     if (aparser.contains("help") || aparser.contains("h"))
93     {
94       System.out
95               .println("Usage: jalview -open [FILE] [OUTPUT_FORMAT] [OUTPUT_FILE]\n\n"
96                       + "-nodisplay\tRun Jalview without User Interface.\n"
97                       + "-props FILE\tUse the given Jalview properties file instead of users default.\n"
98                       + "-colour COLOURSCHEME\tThe colourscheme to be applied to the alignment\n"
99                       + "-annotations FILE\tAdd precalculated annotations to the alignment.\n"
100                       + "-tree FILE\tLoad the given newick format tree file onto the alignment\n"
101                       + "-features FILE\tUse the given file to mark features on the alignment.\n"
102                       + "-fasta FILE\tCreate alignment file FILE in Fasta format.\n"
103                       + "-clustal FILE\tCreate alignment file FILE in Clustal format.\n"
104                       + "-pfam FILE\tCreate alignment file FILE in PFAM format.\n"
105                       + "-msf FILE\tCreate alignment file FILE in MSF format.\n"
106                       + "-pileup FILE\tCreate alignment file FILE in Pileup format\n"
107                       + "-pir FILE\tCreate alignment file FILE in PIR format.\n"
108                       + "-blc FILE\tCreate alignment file FILE in BLC format.\n"
109                       + "-jalview FILE\tCreate alignment file FILE in Jalview format.\n"
110                       + "-png FILE\tCreate PNG image FILE from alignment.\n"
111                       + "-imgMap FILE\tCreate HTML file FILE with image map of PNG image.\n"
112                       + "-eps FILE\tCreate EPS file FILE from alignment.\n"
113                       + "-questionnaire URL\tQueries the given URL for information about any Jalview user questionnaires.\n"
114                       + "-noquestionnaire\tTurn off questionnaire check.\n"
115                       + "-nousagestats\tTurn off google analytics tracking for this session.\n"
116                       + "-sortbytree OR -nosortbytree\tEnable or disable sorting of the given alignment by the given tree\n"
117                       // +
118                       // "-setprop PROPERTY=VALUE\tSet the given Jalview property, after all other properties files have been read\n\t (quote the 'PROPERTY=VALUE' pair to ensure spaces are passed in correctly)"
119                       + "-dasserver nickname=URL\tAdd and enable a das server with given nickname\n\t\t\t(alphanumeric or underscores only) for retrieval of features for all alignments.\n"
120                       + "\t\t\tSources that also support the sequence command may be specified by prepending the URL with sequence:\n"
121                       + "\t\t\t e.g. sequence:http://localdas.somewhere.org/das/source)\n"
122                       + "-fetchfrom nickname\tQuery nickname for features for the alignments and display them.\n"
123                       // +
124                       // "-vdoc vamsas-document\tImport vamsas document into new session or join existing session with same URN\n"
125                       // + "-vses vamsas-session\tJoin session with given URN\n"
126                       + "-groovy FILE\tExecute groovy script in FILE, after all other arguments have been processed (if FILE is the text 'STDIN' then the file will be read from STDIN)\n"
127                       + "\n~Read documentation in Application or visit http://www.jalview.org for description of Features and Annotations file~\n\n");
128       System.exit(0);
129     }
130     Cache.loadProperties(aparser.getValue("props")); // must do this before
131     // anything else!
132     String defs = aparser.getValue("setprop");
133     while (defs != null)
134     {
135       int p = defs.indexOf('=');
136       if (p == -1)
137       {
138         System.err.println("Ignoring invalid setprop argument : " + defs);
139       }
140       else
141       {
142         System.out.println("Executing setprop argument: " + defs);
143         // DISABLED FOR SECURITY REASONS
144         // TODO: add a property to allow properties to be overriden by cli args
145         // Cache.setProperty(defs.substring(0,p), defs.substring(p+1));
146       }
147       defs = aparser.getValue("setprop");
148     }
149     if (aparser.contains("nodisplay"))
150     {
151       System.setProperty("java.awt.headless", "true");
152     }
153     if (System.getProperty("java.awt.headless") != null
154             && System.getProperty("java.awt.headless").equals("true"))
155     {
156       headless = true;
157     }
158
159     try
160     {
161       Cache.initLogger();
162     } catch (java.lang.NoClassDefFoundError error)
163     {
164       error.printStackTrace();
165       System.out
166               .println("\nEssential logging libraries not found."
167                       + "\nUse: java -Djava.ext.dirs=$PATH_TO_LIB$ jalview.bin.Jalview");
168       System.exit(0);
169     }
170
171     Desktop desktop = null;
172
173     try
174     {
175       UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
176     } catch (Exception ex)
177     {
178     }
179
180     if (!headless)
181     {
182       desktop = new Desktop();
183       desktop.setInBatchMode(true); // indicate we are starting up
184       desktop.setVisible(true);
185       desktop.startServiceDiscovery();
186       if (!aparser.contains("nousagestats"))
187       {
188         startUsageStats(desktop);
189       }
190       if (!aparser.contains("noquestionnaire"))
191       {
192         String url = aparser.getValue("questionnaire");
193         if (url != null)
194         {
195           // Start the desktop questionnaire prompter with the specified
196           // questionnaire
197           Cache.log.debug("Starting questionnaire url at " + url);
198           desktop.checkForQuestionnaire(url);
199         }
200         else
201         {
202           if (Cache.getProperty("NOQUESTIONNAIRES") == null)
203           {
204             // Start the desktop questionnaire prompter with the specified
205             // questionnaire
206             // String defurl =
207             // "http://anaplog.compbio.dundee.ac.uk/cgi-bin/questionnaire.pl";
208             // //
209             String defurl = "http://www.jalview.org/cgi-bin/questionnaire.pl";
210             Cache.log.debug("Starting questionnaire with default url: "
211                     + defurl);
212             desktop.checkForQuestionnaire(defurl);
213
214           }
215         }
216       }
217     }
218
219     String file = null, protocol = null, format = null, data = null;
220     jalview.io.FileLoader fileLoader = new jalview.io.FileLoader();
221     Vector getFeatures = null; // vector of das source nicknames to fetch
222     // features from
223     // loading is done.
224     String groovyscript = null; // script to execute after all loading is
225     // completed one way or another
226     // extract groovy argument and execute if necessary
227     groovyscript = aparser.getValue("groovy", true);
228     file = aparser.getValue("open", true);
229
230     if (file == null && desktop == null)
231     {
232       System.out.println("No files to open!");
233       System.exit(1);
234     }
235     String vamsasImport = aparser.getValue("vdoc"), vamsasSession = aparser
236             .getValue("vsess");
237     if (vamsasImport != null || vamsasSession != null)
238     {
239       if (desktop == null || headless)
240       {
241         System.out
242                 .println("Headless vamsas sessions not yet supported. Sorry.");
243         System.exit(1);
244       }
245       // if we have a file, start a new session and import it.
246       boolean inSession = false;
247       if (vamsasImport != null)
248       {
249         try
250         {
251           String viprotocol = jalview.io.AppletFormatAdapter.checkProtocol(vamsasImport);
252           if (viprotocol == jalview.io.FormatAdapter.FILE)
253           {
254             inSession = desktop.vamsasImport(new File(vamsasImport));
255           }
256           else if (viprotocol == jalview.io.FormatAdapter.URL)
257           {
258             inSession = desktop.vamsasImport(new URL(vamsasImport));
259           }
260
261         } catch (Exception e)
262         {
263           System.err.println("Exeption when importing " + vamsasImport
264                   + " as a vamsas document.");
265           e.printStackTrace();
266         }
267         if (!inSession)
268         {
269           System.err.println("Failed to import " + vamsasImport
270                   + " as a vamsas document.");
271         }
272         else
273         {
274           System.out.println("Imported Successfully into new session "
275                   + desktop.getVamsasApplication().getCurrentSession());
276         }
277       }
278       if (vamsasSession != null)
279       {
280         if (vamsasImport != null)
281         {
282           // close the newly imported session and import the Jalview specific
283           // remnants into the new session later on.
284           desktop.vamsasStop_actionPerformed(null);
285         }
286         // now join the new session
287         try
288         {
289           if (desktop.joinVamsasSession(vamsasSession))
290           {
291             System.out.println("Successfully joined vamsas session "
292                     + vamsasSession);
293           }
294           else
295           {
296             System.err.println("WARNING: Failed to join vamsas session "
297                     + vamsasSession);
298           }
299         } catch (Exception e)
300         {
301           System.err.println("ERROR: Failed to join vamsas session "
302                   + vamsasSession);
303           e.printStackTrace();
304         }
305         if (vamsasImport != null)
306         {
307           // the Jalview specific remnants can now be imported into the new
308           // session at the user's leisure.
309           Cache.log
310                   .info("Skipping Push for import of data into existing vamsas session."); // TODO:
311           // enable
312           // this
313           // when
314           // debugged
315           // desktop.getVamsasApplication().push_update();
316         }
317       }
318     }
319     // Finally, deal with the remaining input data.
320     if (file != null)
321     {
322       System.out.println("Opening file: " + file);
323
324       if (!file.startsWith("http://"))
325       {
326         if (!(new java.io.File(file)).exists())
327         {
328           System.out.println("Can't find " + file);
329           if (headless)
330           {
331             System.exit(1);
332           }
333         }
334       }
335
336       protocol = jalview.io.AppletFormatAdapter.checkProtocol(file);
337
338       format = new jalview.io.IdentifyFile().Identify(file, protocol);
339
340       AlignFrame af = fileLoader.LoadFileWaitTillLoaded(file, protocol,
341               format);
342       if (af == null)
343       {
344         System.out.println("error");
345         return;
346       }
347
348       data = aparser.getValue("colour", true);
349       if (data != null)
350       {
351         data.replaceAll("%20", " ");
352
353         jalview.schemes.ColourSchemeI cs = jalview.schemes.ColourSchemeProperty
354                 .getColour(af.getViewport().getAlignment(), data);
355
356         if (cs == null)
357         {
358           jalview.schemes.UserColourScheme ucs = new jalview.schemes.UserColourScheme(
359                   "white");
360           ucs.parseAppletParameter(data);
361           cs = ucs;
362         }
363
364         System.out.println("colour is " + data);
365         af.changeColour(cs);
366       }
367
368       // Must maintain ability to use the groups flag
369       data = aparser.getValue("groups", true);
370       if (data != null)
371       {
372         af.parseFeaturesFile(data, jalview.io.AppletFormatAdapter.checkProtocol(data));
373         System.out.println("Added " + data);
374       }
375       data = aparser.getValue("features", true);
376       if (data != null)
377       {
378         af.parseFeaturesFile(data, jalview.io.AppletFormatAdapter.checkProtocol(data));
379         System.out.println("Added " + data);
380       }
381
382       data = aparser.getValue("annotations", true);
383       if (data != null)
384       {
385         af.loadJalviewDataFile(data, null, null, null);
386         System.out.println("Added " + data);
387       }
388       // set or clear the sortbytree flag.
389       if (aparser.contains("sortbytree"))
390       {
391         af.getViewport().setSortByTree(true);
392       }
393       if (aparser.contains("nosortbytree"))
394       {
395         af.getViewport().setSortByTree(false);
396       }
397       data = aparser.getValue("tree", true);
398       if (data != null)
399       {
400         jalview.io.NewickFile fin = null;
401         try
402         {
403           fin = new jalview.io.NewickFile(data, jalview.io.AppletFormatAdapter.checkProtocol(data));
404           if (fin != null)
405           {
406             af.getViewport().setCurrentTree(
407                     af.ShowNewickTree(fin, data).getTree());
408             System.out.println("Added tree " + data);
409           }
410         } catch (IOException ex)
411         {
412           System.err.println("Couldn't add tree " + data);
413           ex.printStackTrace(System.err);
414         }
415       }
416       // TODO - load PDB structure(s) to alignment JAL-629
417       // (associate with identical sequence in alignment, or a specified
418       // sequence)
419
420       getFeatures = checkDasArguments(aparser);
421       if (af != null && getFeatures != null)
422       {
423         FeatureFetcher ff = startFeatureFetching(getFeatures);
424         if (ff != null)
425           while (!ff.allFinished() || af.operationInProgress())
426           {
427             // wait around until fetching is finished.
428             try
429             {
430               Thread.sleep(100);
431             } catch (Exception e)
432             {
433
434             }
435           }
436         getFeatures = null; // have retrieved features - forget them now.
437       }
438       if (groovyscript != null)
439       {
440         // Execute the groovy script after we've done all the rendering stuff
441         // and before any images or figures are generated.
442         if (jalview.bin.Cache.groovyJarsPresent())
443         {
444           System.out.println("Executing script " + groovyscript);
445           executeGroovyScript(groovyscript, desktop);
446         }
447         else
448         {
449           System.err
450                   .println("Sorry. Groovy Support is not available, so ignoring the provided groovy script "
451                           + groovyscript);
452         }
453         groovyscript = null;
454       }
455       String imageName = "unnamed.png";
456       while (aparser.getSize() > 1)
457       {
458         format = aparser.nextValue();
459         file = aparser.nextValue();
460
461         if (format.equalsIgnoreCase("png"))
462         {
463           af.createPNG(new java.io.File(file));
464           imageName = (new java.io.File(file)).getName();
465           System.out.println("Creating PNG image: " + file);
466           continue;
467         }
468         else if (format.equalsIgnoreCase("imgMap"))
469         {
470           af.createImageMap(new java.io.File(file), imageName);
471           System.out.println("Creating image map: " + file);
472           continue;
473         }
474         else if (format.equalsIgnoreCase("eps"))
475         {
476           System.out.println("Creating EPS file: " + file);
477           af.createEPS(new java.io.File(file));
478           continue;
479         }
480
481         if (af.saveAlignment(file, format))
482         {
483           System.out.println("Written alignment in " + format
484                   + " format to " + file);
485         }
486         else
487         {
488           System.out.println("Error writing file " + file + " in " + format
489                   + " format!!");
490         }
491
492       }
493
494       while (aparser.getSize() > 0)
495       {
496         System.out.println("Unknown arg: " + aparser.nextValue());
497       }
498     }
499     AlignFrame startUpAlframe = null;
500     // We'll only open the default file if the desktop is visible.
501     // And the user
502     // ////////////////////
503     if (!headless && file == null && vamsasImport == null
504             && jalview.bin.Cache.getDefault("SHOW_STARTUP_FILE", true))
505     {
506       file = jalview.bin.Cache.getDefault("STARTUP_FILE",
507               "http://www.jalview.org/examples/exampleFile_2_3.jar");
508
509       protocol = "File";
510
511       if (file.indexOf("http:") > -1)
512       {
513         protocol = "URL";
514       }
515
516       if (file.endsWith(".jar"))
517       {
518         format = "Jalview";
519       }
520       else
521       {
522         format = new jalview.io.IdentifyFile().Identify(file, protocol);
523       }
524
525       startUpAlframe = fileLoader.LoadFileWaitTillLoaded(file, protocol,
526               format);
527       getFeatures = checkDasArguments(aparser);
528       // extract groovy arguments before anything else.
529     }
530     // If the user has specified features to be retrieved,
531     // or a groovy script to be executed, do them if they
532     // haven't been done already
533     // fetch features for the default alignment
534     if (getFeatures != null)
535     {
536       if (startUpAlframe != null)
537       {
538         startFeatureFetching(getFeatures);
539       }
540     }
541     // Once all other stuff is done, execute any groovy scripts (in order)
542     if (groovyscript != null)
543     {
544       if (jalview.bin.Cache.groovyJarsPresent())
545       {
546         System.out.println("Executing script " + groovyscript);
547         executeGroovyScript(groovyscript, desktop);
548       }
549       else
550       {
551         System.err
552                 .println("Sorry. Groovy Support is not available, so ignoring the provided groovy script "
553                         + groovyscript);
554       }
555     }
556     // and finally, turn off batch mode indicator - if the desktop still exists
557     if (desktop != null)
558     {
559       desktop.setInBatchMode(false);
560     }
561   }
562
563   private static void startUsageStats(final Desktop desktop)
564   {
565     /**
566      * start a User Config prompt asking if we can log usage statistics.
567      */
568     jalview.gui.PromptUserConfig prompter = new jalview.gui.PromptUserConfig(
569             desktop.desktop,
570             "USAGESTATS",
571             "Jalview Usage Statistics",
572             "Do you want to help make Jalview better by enabling "
573                     + "the collection of usage statistics with Google Analytics ?"
574                     + "\n\n(you can enable or disable usage tracking in the preferences)",
575             new Runnable()
576             {
577               public void run()
578               {
579                 Cache.log
580                         .info("Initialising googletracker for usage stats.");
581                 Cache.initGoogleTracker();
582                 Cache.log.debug("Tracking enabled.");
583               }
584             }, new Runnable()
585             {
586               public void run()
587               {
588                 Cache.log.info("Not enabling Google Tracking.");
589               }
590             }, null, true);
591     SwingUtilities.invokeLater(prompter);
592   }
593
594   /**
595    * Locate the given string as a file and pass it to the groovy interpreter.
596    * 
597    * @param groovyscript
598    *          the script to execute
599    * @param jalviewContext
600    *          the Jalview Desktop object passed in to the groovy binding as the
601    *          'Jalview' object.
602    */
603   private static void executeGroovyScript(String groovyscript,
604           Object jalviewContext)
605   {
606     if (jalviewContext == null)
607     {
608       System.err
609               .println("Sorry. Groovy support is currently only available when running with the Jalview GUI enabled.");
610     }
611     File sfile = null;
612     if (groovyscript.trim().equals("STDIN"))
613     {
614       // read from stdin into a tempfile and execute it
615       try
616       {
617         sfile = File.createTempFile("jalview", "groovy");
618         PrintWriter outfile = new PrintWriter(new OutputStreamWriter(
619                 new FileOutputStream(sfile)));
620         BufferedReader br = new BufferedReader(
621                 new java.io.InputStreamReader(System.in));
622         String line = null;
623         while ((line = br.readLine()) != null)
624         {
625           outfile.write(line + "\n");
626         }
627         br.close();
628         outfile.flush();
629         outfile.close();
630
631       } catch (Exception ex)
632       {
633         System.err.println("Failed to read from STDIN into tempfile "
634                 + ((sfile == null) ? "(tempfile wasn't created)" : sfile
635                         .toString()));
636         ex.printStackTrace();
637         return;
638       }
639     }
640     else
641     {
642       sfile = new File(groovyscript);
643     }
644     if (!sfile.exists())
645     {
646       System.err.println("File '" + groovyscript + "' does not exist.");
647       return;
648     }
649     if (!sfile.canRead())
650     {
651       System.err.println("File '" + groovyscript + "' cannot be read.");
652       return;
653     }
654     if (sfile.length() < 1)
655     {
656       System.err.println("File '" + groovyscript + "' is empty.");
657       return;
658     }
659     boolean success = false;
660     try
661     {
662       /*
663        * The following code performs the GroovyScriptEngine invocation using
664        * reflection, and is equivalent to this fragment from the embedding
665        * groovy documentation on the groovy site: <code> import
666        * groovy.lang.Binding; import groovy.util.GroovyScriptEngine;
667        * 
668        * String[] roots = new String[] { "/my/groovy/script/path" };
669        * GroovyScriptEngine gse = new GroovyScriptEngine(roots); Binding binding
670        * = new Binding(); binding.setVariable("input", "world");
671        * gse.run("hello.groovy", binding); </code>
672        */
673       ClassLoader cl = jalviewContext.getClass().getClassLoader();
674       Class gbindingc = cl.loadClass("groovy.lang.Binding");
675       Constructor gbcons = gbindingc.getConstructor(null);
676       Object gbinding = gbcons.newInstance(null);
677       java.lang.reflect.Method setvar = gbindingc.getMethod("setVariable",
678               new Class[]
679               { String.class, Object.class });
680       setvar.invoke(gbinding, new Object[]
681       { "Jalview", jalviewContext });
682       Class gsec = cl.loadClass("groovy.util.GroovyScriptEngine");
683       Constructor gseccons = gsec.getConstructor(new Class[]
684       { URL[].class }); // String[].class });
685       Object gse = gseccons.newInstance(new Object[]
686       { new URL[]
687       { sfile.toURL() } }); // .toString() } });
688       java.lang.reflect.Method run = gsec.getMethod("run", new Class[]
689       { String.class, gbindingc });
690       run.invoke(gse, new Object[]
691       { sfile.getName(), gbinding });
692       success = true;
693     } catch (Exception e)
694     {
695       System.err.println("Exception Whilst trying to execute file " + sfile
696               + " as a groovy script.");
697       e.printStackTrace(System.err);
698
699     }
700     if (success && groovyscript.equals("STDIN"))
701     {
702       // delete temp file that we made - but only if it was successfully
703       // executed
704       sfile.delete();
705     }
706   }
707
708   /**
709    * Check commandline for any das server definitions or any fetchfrom switches
710    * 
711    * @return vector of DAS source nicknames to retrieve from
712    */
713   private static Vector checkDasArguments(ArgsParser aparser)
714   {
715     Vector source = null;
716     String data;
717     String locsources = Cache.getProperty(Cache.DAS_LOCAL_SOURCE);
718     while ((data = aparser.getValue("dasserver", true)) != null)
719     {
720       String nickname = null;
721       String url = null;
722       boolean seq = false, feat = true;
723       int pos = data.indexOf('=');
724       // determine capabilities
725       if (pos > 0)
726       {
727         nickname = data.substring(0, pos);
728       }
729       url = data.substring(pos + 1);
730       if (url != null
731               && (url.startsWith("http:") || url
732                       .startsWith("sequence:http:")))
733       {
734         if (nickname == null)
735         {
736           nickname = url;
737         }
738         if (locsources == null)
739         {
740           locsources = "";
741         }
742         else
743         {
744           locsources += "\t";
745         }
746         locsources = locsources + nickname + "|" + url;
747         System.err
748                 .println("NOTE! dasserver parameter not yet really supported (got args of "
749                         + nickname + "|" + url);
750         if (source == null)
751         {
752           source = new Vector();
753         }
754         source.addElement(nickname);
755       }
756     } // loop until no more server entries are found.
757     if (locsources != null && locsources.indexOf('|') > -1)
758     {
759       Cache.log.debug("Setting local source list in properties file to:\n"
760               + locsources);
761       Cache.setProperty(Cache.DAS_LOCAL_SOURCE, locsources);
762     }
763     while ((data = aparser.getValue("fetchfrom", true)) != null)
764     {
765       System.out.println("adding source '" + data + "'");
766       if (source == null)
767       {
768         source = new Vector();
769       }
770       source.addElement(data);
771     }
772     return source;
773   }
774
775   /**
776    * start a feature fetcher for every alignment frame
777    * 
778    * @param dasSources
779    */
780   private static FeatureFetcher startFeatureFetching(final Vector dasSources)
781   {
782     FeatureFetcher ff = new FeatureFetcher();
783     AlignFrame afs[] = Desktop.getAlignframes();
784     if (afs == null || afs.length == 0)
785     {
786       return null;
787     }
788     for (int i = 0; i < afs.length; i++)
789     {
790       ff.addFetcher(afs[i], dasSources);
791     }
792     return ff;
793   }
794 }
795
796 /**
797  * Notes: this argParser does not distinguish between parameter switches,
798  * parameter values and argument text. If an argument happens to be identical to
799  * a parameter, it will be taken as such (even though it didn't have a '-'
800  * prefixing it).
801  * 
802  * @author Andrew Waterhouse and JBP documented.
803  * 
804  */
805 class ArgsParser
806 {
807   Vector vargs = null;
808
809   public ArgsParser(String[] args)
810   {
811     vargs = new Vector();
812     for (int i = 0; i < args.length; i++)
813     {
814       String arg = args[i].trim();
815       if (arg.charAt(0) == '-')
816       {
817         arg = arg.substring(1);
818       }
819       vargs.addElement(arg);
820     }
821   }
822
823   /**
824    * check for and remove first occurence of arg+parameter in arglist.
825    * 
826    * @param arg
827    * @return return the argument following the given arg if arg was in list.
828    */
829   public String getValue(String arg)
830   {
831     return getValue(arg, false);
832   }
833
834   public String getValue(String arg, boolean utf8decode)
835   {
836     int index = vargs.indexOf(arg);
837     String dc = null, ret = null;
838     if (index != -1)
839     {
840       ret = vargs.elementAt(index + 1).toString();
841       vargs.removeElementAt(index);
842       vargs.removeElementAt(index);
843       if (utf8decode && ret != null)
844       {
845         try
846         {
847           dc = URLDecoder.decode(ret, "UTF-8");
848           ret = dc;
849         } catch (Exception e)
850         {
851           // TODO: log failure to decode
852         }
853       }
854     }
855     return ret;
856   }
857
858   /**
859    * check for and remove first occurence of arg in arglist.
860    * 
861    * @param arg
862    * @return true if arg was present in argslist.
863    */
864   public boolean contains(String arg)
865   {
866     if (vargs.contains(arg))
867     {
868       vargs.removeElement(arg);
869       return true;
870     }
871     else
872     {
873       return false;
874     }
875   }
876
877   public String nextValue()
878   {
879     return vargs.remove(0).toString();
880   }
881
882   public int getSize()
883   {
884     return vargs.size();
885   }
886
887 }
888
889 /**
890  * keep track of feature fetching tasks.
891  * 
892  * @author JimP
893  * 
894  */
895 class FeatureFetcher
896 {
897   /*
898    * TODO: generalise to track all jalview events to orchestrate batch
899    * processing events.
900    */
901
902   private int queued = 0;
903
904   private int running = 0;
905
906   public FeatureFetcher()
907   {
908
909   }
910
911   public void addFetcher(final AlignFrame af, final Vector dasSources)
912   {
913     final long id = System.currentTimeMillis();
914     queued++;
915     final FeatureFetcher us = this;
916     new Thread(new Runnable()
917     {
918
919       public void run()
920       {
921         synchronized (us)
922         {
923           queued--;
924           running++;
925         }
926
927         af.setProgressBar("DAS features being retrieved...", id);
928         af.featureSettings_actionPerformed(null);
929         af.featureSettings.fetchDasFeatures(dasSources, true);
930         af.setProgressBar(null, id);
931         synchronized (us)
932         {
933           running--;
934         }
935       }
936     }).start();
937   }
938
939   public synchronized boolean allFinished()
940   {
941     return queued == 0 && running == 0;
942   }
943 };