Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
  /*
   * Copyright 2003-2007 the original author or authors.
   *
   * Licensed under the Apache License, Version 2.0 (the "License");
   * you may not use this file except in compliance with the License.
   * You may obtain a copy of the License at
   *
   *     http://www.apache.org/licenses/LICENSE-2.0
   *
  * Unless required by applicable law or agreed to in writing, software
  * distributed under the License is distributed on an "AS IS" BASIS,
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  * See the License for the specific language governing permissions and
  * limitations under the License.
  */
 package groovy.ui;
 
 
 import java.io.*;
 import java.util.List;
 
 import  org.apache.commons.cli.CommandLine;
 import  org.apache.commons.cli.CommandLineParser;
 import  org.apache.commons.cli.HelpFormatter;
 import  org.apache.commons.cli.OptionBuilder;
 import  org.apache.commons.cli.Options;
 import  org.apache.commons.cli.ParseException;
 import  org.apache.commons.cli.PosixParser;
A Command line to execute groovy.

Author(s):
Jeremy Rayner
Yuri Schimke
Version:
$Revision: 12135 $
 
 public class GroovyMain {
 
     // arguments to the script
     private List args;
 
     // is this a file on disk
     private boolean isScriptFile;
 
     // filename or content of script
     private String script;
 
     // process args as input files
     private boolean processFiles;
 
     // edit input files in place
     private boolean editFiles;
 
     // automatically output the result of each script
     private boolean autoOutput;
 
     // automatically split each line using the splitpattern
     private boolean autoSplit;
 
     // The pattern used to split the current line
     private String splitPattern = " ";
 
     // process sockets
     private boolean processSockets;
 
     // port to listen on when processing sockets
     private int port;
 
     // backup input files with extension
     private String backupExtension;
 
     // do you want full stack traces in script exceptions?
     private boolean debug = false;
 
     // Compiler configuration, used to set the encodings of the scripts/classes
     private CompilerConfiguration conf = new CompilerConfiguration(System.getProperties());

    
Main CLI interface.

Parameters:
args all command line args.
 
     public static void main(String args[]) {
         processArgs(args.);
     }
 
     // package-level visibility for testing purposes (just usage/errors at this stage)
     // TODO: should we have an 'err' printstream too for ParseException?
     static void processArgs(String[] argsfinal PrintStream out) {
         Options options = buildOptions();
 
        try {
            CommandLine cmd = parseCommandLine(optionsargs);
            if (cmd.hasOption('h')) {
                printHelp(outoptions);
            } else if (cmd.hasOption('v')) {
                String version = InvokerHelper.getVersion();
                out.println("Groovy Version: " + version + " JVM: " + System.getProperty("java.version"));
            } else {
                // If we fail, then exit with an error so scripting frameworks can catch it
                // TODO: pass printstream(s) down through process
                if (!process(cmd)) {
                    System.exit(1);
                }
            }
        } catch (ParseException pe) {
            out.println("error: " + pe.getMessage());
            printHelp(outoptions);
        }
    }
    private static void printHelp(PrintStream out, Options options) {
        HelpFormatter formatter = new HelpFormatter();
        PrintWriter pw = new PrintWriter(out);
        formatter.printHelp(
            pw,
            80,
            "groovy [options] [args]",
            "options:",
            options,
            2,
            4,
            null// footer
            false);
       
        pw.flush();
    }

    
Parse the command line.

Parameters:
options the options parser.
args the command line args.
Returns:
parsed command line.
Throws:
ParseException if there was a problem.
    private static CommandLine parseCommandLine(Options optionsString[] argsthrows ParseException {
        CommandLineParser parser = new PosixParser();
        return parser.parse(optionsargstrue);
    }

    
Build the options parser. Has to be synchronized because of the way Options are constructed.

Returns:
an options parser.
    private static synchronized Options buildOptions() {
        Options options = new Options();
        options.addOption(
            OptionBuilder.withLongOpt("define").
                withDescription("define a system property").
                hasArg(true).
                withArgName("name=value").
                create('D')
        );
        options.addOption(
            OptionBuilder.hasArg(false)
            .withDescription("usage information")
            .withLongOpt("help")
            .create('h'));
        options.addOption(
            OptionBuilder.hasArg(false)
            .withDescription("debug mode will print out full stack traces")
            .withLongOpt("debug")
            .create('d'));
        options.addOption(
            OptionBuilder.hasArg(false)
            .withDescription("display the Groovy and JVM versions")
            .withLongOpt("version")
            .create('v'));
        options.addOption(
            OptionBuilder.withArgName("charset")
            .hasArg()
            .withDescription("specify the encoding of the files")
            .withLongOpt("encoding")
            .create('c'));
        options.addOption(
            OptionBuilder.withArgName("script")
            .hasArg()
            .withDescription("specify a command line script")
            .create('e'));
        options.addOption(
            OptionBuilder.withArgName("extension")
            .hasOptionalArg()
            .withDescription("modify files in place; create backup if extension is given (e.g. \'.bak\')")
            .create('i'));
        options.addOption(
            OptionBuilder.hasArg(false)
            .withDescription("process files line by line using implicit 'line' variable")
            .create('n'));
        options.addOption(
            OptionBuilder.hasArg(false)
            .withDescription("process files line by line and print result (see also -n)")
            .create('p'));
        options.addOption(
            OptionBuilder.withArgName("port")
            .hasOptionalArg()
            .withDescription("listen on a port and process inbound lines")
            .create('l'));
        options.addOption(
            OptionBuilder.withArgName("splitPattern")
            .hasOptionalArg()
            .withDescription("split lines using splitPattern (default '\\s') using implicit 'split' variable")
            .withLongOpt("autosplit")
            .create('a'));
        return options;
    }
    private static void setSystemPropertyFrom(final String nameValue) {
        if(nameValue==nullthrow new IllegalArgumentException("argument should not be null");
        String namevalue;
        int i = nameValue.indexOf("=");
        if (i == -1) {
            name = nameValue;
            value = ..toString();
        }
        else {
            name = nameValue.substring(0, i);
            value = nameValue.substring(i + 1, nameValue.length());
        }
        name = name.trim();
        System.setProperty(namevalue);
    }

    
Process the users request.

Parameters:
line the parsed command line.
Throws:
ParseException if invalid options are chosen
    private static boolean process(CommandLine linethrows ParseException {
        GroovyMain main = new GroovyMain();
        List args = line.getArgList();
        
        if (line.hasOption('D')) {
            String[] values = line.getOptionValues('D');
            for (int i=0; i<values.lengthi++) {
                setSystemPropertyFrom(values[i]);
            }
        }
        // add the ability to parse scripts with a specified encoding
        main.conf.setSourceEncoding(line.getOptionValue('c',main.conf.getSourceEncoding()));
        main.isScriptFile = !line.hasOption('e');
        main.debug = line.hasOption('d');
        main.conf.setDebug(main.debug);
        main.processFiles = line.hasOption('p') || line.hasOption('n');
        main.autoOutput = line.hasOption('p');
        main.editFiles = line.hasOption('i');
        if (main.editFiles) {
            main.backupExtension = line.getOptionValue('i');
        }
        main.autoSplit = line.hasOption('a');
        String sp = line.getOptionValue('a');
        if (sp != null)
            main.splitPattern = sp;
        if (main.isScriptFile) {
            if (args.isEmpty())
                throw new ParseException("neither -e or filename provided");
            main.script = (Stringargs.remove(0);
            if (main.script.endsWith(".java"))
                throw new ParseException("error: cannot compile file with .java extension: " + main.script);
        } else {
            main.script = line.getOptionValue('e');
        }
        main.processSockets = line.hasOption('l');
        if (main.processSockets) {
            String p = line.getOptionValue('l'"1960"); // default port to listen to
            main.port = Integer.parseInt(p);
        }
        main.args = args;
        return main.run();
    }


    
Run the script.
    private boolean run() {
        try {
            if () {
                processSockets();
            } else if () {
                processFiles();
            } else {
                processOnce();
            }
            return true;
        } catch (CompilationFailedException e) {
            ..println(e);
            return false;
        } catch (Throwable e) {
            if (e instanceof InvokerInvocationException) {
                InvokerInvocationException iie = (InvokerInvocationExceptione;
                e = iie.getCause();
            }
            ..println("Caught: " + e);
            if () {
                e.printStackTrace();
            } else {
                StackTraceElement[] stackTrace = e.getStackTrace();
                for (int i = 0; i < stackTrace.lengthi++) {
                    StackTraceElement element = stackTrace[i];
                    String fileName = element.getFileName();
                    if (fileName!=null && !fileName.endsWith(".java")) {
                        ..println("\tat " + element);
                    }
                }
            }
            return false;
        }
    }

    
Process Sockets.
    private void processSockets() throws CompilationFailedExceptionIOException {
        GroovyShell groovy = new GroovyShell();
        //check the script is currently valid before starting a server against the script
        if () {
            groovy.parse(new FileInputStream(huntForTheScriptFile()));
        } else {
            groovy.parse();
        }
        new GroovySocketServer(groovy);
    }

    
Hunt for the script file, doesn't bother if it is named precisely. Tries in this order: - actual supplied name - name.groovy - name.gvy - name.gy - name.gsh
    public File huntForTheScriptFile(String input) {
        String scriptFileName = input.trim();
        File scriptFile = new File(scriptFileName);
        String[] standardExtensions = {".groovy",".gvy",".gy",".gsh"};
        int i = 0;
        while (i < standardExtensions.length && !scriptFile.exists()) {
            scriptFile = new File(scriptFileName + standardExtensions[i]);
            i++;
        }
        // if we still haven't found the file, point back to the originally specified filename
        if (!scriptFile.exists()) {
            scriptFile = new File(scriptFileName);
        }
        return scriptFile;
    }

    
Process the input files.
    private void processFiles() throws CompilationFailedExceptionIOException {
        GroovyShell groovy = new GroovyShell();
        Script s;
        if () {
            s = groovy.parse(huntForTheScriptFile());
        } else {
            s = groovy.parse("main");
        }
        if (.isEmpty()) {
            BufferedReader reader = new BufferedReader(new InputStreamReader(.));
            PrintWriter writer = new PrintWriter(.);
            try {
                processReader(sreaderwriter);
            } finally {
                reader.close();
                writer.close();
            }
        } else {
            Iterator i = .iterator();
            while (i.hasNext()) {
                String filename = (Stringi.next();
                File file = huntForTheScriptFile(filename);
                processFile(sfile);
            }
        }
    }

    
Process a single input file.

Parameters:
s the script to execute.
file the input file.
    private void processFile(Script sFile filethrows IOException {
        if (!file.exists())
            throw new FileNotFoundException(file.getName());
        if (!) {
            BufferedReader reader = new BufferedReader(new FileReader(file));
            try {
                PrintWriter writer = new PrintWriter(.);
                processReader(sreaderwriter);
                writer.flush();
            } finally {
                reader.close();
            }
        } else {
            File backup;
            if ( == null) {
                backup = File.createTempFile("groovy_"".tmp");
                backup.deleteOnExit();
            } else {
                backup = new File(file.getPath() + );
            }
            backup.delete();
            if (!file.renameTo(backup))
                throw new IOException("unable to rename " + file + " to " + backup);
            BufferedReader reader = new BufferedReader(new FileReader(backup));
            try {
                PrintWriter writer = new PrintWriter(new FileWriter(file));
                try {
                    processReader(sreaderwriter);
                } finally {
                    writer.close();
                }
            } finally {
                reader.close();
            }
        }
    }

    
Process a script against a single input file.

Parameters:
s script to execute.
reader input file.
pw output sink.
    private void processReader(Script sBufferedReader readerPrintWriter pwthrows IOException {
        String line;
        String lineCountName = "count";
        s.setProperty(lineCountName.);
        String autoSplitName = "split";
        s.setProperty("out"pw);
        while ((line = reader.readLine()) != null) {
            s.setProperty("line"line);
            s.setProperty(lineCountName, ((BigInteger)s.getProperty(lineCountName)).add(.));
            if() {
                s.setProperty(autoSplitNameline.split());
            }
            Object o = s.run();
            if ( && o != null) {
                pw.println(o);
            }
        }
    }
    
    
Process the standard, single script with args.
    private void processOnce() throws CompilationFailedExceptionIOException {
        GroovyShell groovy = new GroovyShell();
        if () {
            groovy.run(huntForTheScriptFile(), );
        }
        else {
            groovy.run("script_from_command_line");
        }
    }
New to GrepCode? Check out our FAQ X