refer to local default setting for proxy when connecting to
[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, new Object[] {desktop,af});
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               jalview.bin.Cache.getDefault("www.jalview.org", "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, new Object[] { desktop, startUpAlframe});
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       Class[] bspec;
674       Object[] binding;
675       int blen=((jalviewContext[0]==null) ? 0 : 1) + ((jalviewContext[1]==null) ? 0 : 1);
676       String cnames[] = new String[] { "Jalview", "currentAlFrame"};
677       bspec=new Class[blen*2];
678       binding=new Object[blen*2];
679       blen=0;
680       ClassLoader cl=null;
681       for (int jc=0;jc<jalviewContext.length;jc++)
682       {
683         if (jalviewContext[jc]!=null) { 
684           if (cl==null)
685           {
686                   cl = jalviewContext[jc].getClass().getClassLoader();
687           }
688                 bspec[blen*2] = String.class;
689           bspec[blen*2+1] = Object.class;
690           binding[blen*2]=cnames[jc];
691           binding[blen*2+1]=jalviewContext[jc];
692           blen++;
693         }
694       }
695       Class gbindingc = cl.loadClass("groovy.lang.Binding");
696       Constructor gbcons = gbindingc.getConstructor(null);
697       Object gbinding = gbcons.newInstance(null);
698       
699       java.lang.reflect.Method setvar = gbindingc.getMethod("setVariable",
700               bspec);
701       
702       setvar.invoke(gbinding, binding);
703       Class gsec = cl.loadClass("groovy.util.GroovyScriptEngine");
704       Constructor gseccons = gsec.getConstructor(new Class[]
705       { URL[].class }); // String[].class });
706       Object gse = gseccons.newInstance(new Object[]
707       { new URL[]
708       { sfile.toURL() } }); // .toString() } });
709       java.lang.reflect.Method run = gsec.getMethod("run", new Class[]
710       { String.class, gbindingc });
711       run.invoke(gse, new Object[]
712       { sfile.getName(), gbinding });
713       success = true;
714     } catch (Exception e)
715     {
716       System.err.println("Exception Whilst trying to execute file " + sfile
717               + " as a groovy script.");
718       e.printStackTrace(System.err);
719
720     }
721     if (success && groovyscript.equals("STDIN"))
722     {
723       // delete temp file that we made - but only if it was successfully
724       // executed
725       sfile.delete();
726     }
727   }
728
729   /**
730    * Check commandline for any das server definitions or any fetchfrom switches
731    * 
732    * @return vector of DAS source nicknames to retrieve from
733    */
734   private static Vector checkDasArguments(ArgsParser aparser)
735   {
736     Vector source = null;
737     String data;
738     String locsources = Cache.getProperty(Cache.DAS_LOCAL_SOURCE);
739     while ((data = aparser.getValue("dasserver", true)) != null)
740     {
741       String nickname = null;
742       String url = null;
743       boolean seq = false, feat = true;
744       int pos = data.indexOf('=');
745       // determine capabilities
746       if (pos > 0)
747       {
748         nickname = data.substring(0, pos);
749       }
750       url = data.substring(pos + 1);
751       if (url != null
752               && (url.startsWith("http:") || url
753                       .startsWith("sequence:http:")))
754       {
755         if (nickname == null)
756         {
757           nickname = url;
758         }
759         if (locsources == null)
760         {
761           locsources = "";
762         }
763         else
764         {
765           locsources += "\t";
766         }
767         locsources = locsources + nickname + "|" + url;
768         System.err
769                 .println("NOTE! dasserver parameter not yet really supported (got args of "
770                         + nickname + "|" + url);
771         if (source == null)
772         {
773           source = new Vector();
774         }
775         source.addElement(nickname);
776       }
777     } // loop until no more server entries are found.
778     if (locsources != null && locsources.indexOf('|') > -1)
779     {
780       Cache.log.debug("Setting local source list in properties file to:\n"
781               + locsources);
782       Cache.setProperty(Cache.DAS_LOCAL_SOURCE, locsources);
783     }
784     while ((data = aparser.getValue("fetchfrom", true)) != null)
785     {
786       System.out.println("adding source '" + data + "'");
787       if (source == null)
788       {
789         source = new Vector();
790       }
791       source.addElement(data);
792     }
793     return source;
794   }
795
796   /**
797    * start a feature fetcher for every alignment frame
798    * 
799    * @param dasSources
800    */
801   private static FeatureFetcher startFeatureFetching(final Vector dasSources)
802   {
803     FeatureFetcher ff = new FeatureFetcher();
804     AlignFrame afs[] = Desktop.getAlignframes();
805     if (afs == null || afs.length == 0)
806     {
807       return null;
808     }
809     for (int i = 0; i < afs.length; i++)
810     {
811       ff.addFetcher(afs[i], dasSources);
812     }
813     return ff;
814   }
815 }
816
817 /**
818  * Notes: this argParser does not distinguish between parameter switches,
819  * parameter values and argument text. If an argument happens to be identical to
820  * a parameter, it will be taken as such (even though it didn't have a '-'
821  * prefixing it).
822  * 
823  * @author Andrew Waterhouse and JBP documented.
824  * 
825  */
826 class ArgsParser
827 {
828   Vector vargs = null;
829
830   public ArgsParser(String[] args)
831   {
832     vargs = new Vector();
833     for (int i = 0; i < args.length; i++)
834     {
835       String arg = args[i].trim();
836       if (arg.charAt(0) == '-')
837       {
838         arg = arg.substring(1);
839       }
840       vargs.addElement(arg);
841     }
842   }
843
844   /**
845    * check for and remove first occurence of arg+parameter in arglist.
846    * 
847    * @param arg
848    * @return return the argument following the given arg if arg was in list.
849    */
850   public String getValue(String arg)
851   {
852     return getValue(arg, false);
853   }
854
855   public String getValue(String arg, boolean utf8decode)
856   {
857     int index = vargs.indexOf(arg);
858     String dc = null, ret = null;
859     if (index != -1)
860     {
861       ret = vargs.elementAt(index + 1).toString();
862       vargs.removeElementAt(index);
863       vargs.removeElementAt(index);
864       if (utf8decode && ret != null)
865       {
866         try
867         {
868           dc = URLDecoder.decode(ret, "UTF-8");
869           ret = dc;
870         } catch (Exception e)
871         {
872           // TODO: log failure to decode
873         }
874       }
875     }
876     return ret;
877   }
878
879   /**
880    * check for and remove first occurence of arg in arglist.
881    * 
882    * @param arg
883    * @return true if arg was present in argslist.
884    */
885   public boolean contains(String arg)
886   {
887     if (vargs.contains(arg))
888     {
889       vargs.removeElement(arg);
890       return true;
891     }
892     else
893     {
894       return false;
895     }
896   }
897
898   public String nextValue()
899   {
900     return vargs.remove(0).toString();
901   }
902
903   public int getSize()
904   {
905     return vargs.size();
906   }
907
908 }
909
910 /**
911  * keep track of feature fetching tasks.
912  * 
913  * @author JimP
914  * 
915  */
916 class FeatureFetcher
917 {
918   /*
919    * TODO: generalise to track all jalview events to orchestrate batch
920    * processing events.
921    */
922
923   private int queued = 0;
924
925   private int running = 0;
926
927   public FeatureFetcher()
928   {
929
930   }
931
932   public void addFetcher(final AlignFrame af, final Vector dasSources)
933   {
934     final long id = System.currentTimeMillis();
935     queued++;
936     final FeatureFetcher us = this;
937     new Thread(new Runnable()
938     {
939
940       public void run()
941       {
942         synchronized (us)
943         {
944           queued--;
945           running++;
946         }
947
948         af.setProgressBar("DAS features being retrieved...", id);
949         af.featureSettings_actionPerformed(null);
950         af.featureSettings.fetchDasFeatures(dasSources, true);
951         af.setProgressBar(null, id);
952         synchronized (us)
953         {
954           running--;
955         }
956       }
957     }).start();
958   }
959
960   public synchronized boolean allFinished()
961   {
962     return queued == 0 && running == 0;
963   }
964 };