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