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