Search in sources :

Example 76 with CommandLineParser

use of org.apache.commons.cli.CommandLineParser in project Cloud9 by lintool.

the class FileMerger method run.

@Override
public /**
   * TODO: add in hadoop configuration
   */
int run(String[] args) throws IOException {
    Options options = new Options();
    options.addOption(HELP_OPTION, false, "print the help message");
    options.addOption(OptionBuilder.withArgName(PATH_INDICATOR).hasArg().withDescription("input file or directory").create(INPUT_OPTION));
    options.addOption(OptionBuilder.withArgName(PATH_INDICATOR).hasArg().withDescription("output file").create(OUTPUT_OPTION));
    options.addOption(OptionBuilder.withArgName(INTEGER_INDICATOR).hasArg().withDescription("number of mappers (default to 0 and hence local merge mode, set to positive value to enable cluster merge mode)").create(MAPPER_OPTION));
    options.addOption(OptionBuilder.withArgName("property=value").hasArgs(2).withValueSeparator().withDescription("assign value for given property").create("D"));
    options.addOption(TEXT_FILE_INPUT_FORMAT, false, "input file in sequence format");
    options.addOption(DELETE_SOURCE_OPTION, false, "delete sources after merging");
    int mapperTasks = 0;
    boolean deleteSource = DELETE_SOURCE;
    boolean textFileFormat = TEXT_FILE_INPUT;
    String inputPath = "";
    String outputPath = "";
    GenericOptionsParser genericOptionsParser = new GenericOptionsParser(args);
    Configuration configuration = genericOptionsParser.getConfiguration();
    CommandLineParser parser = new GnuParser();
    HelpFormatter formatter = new HelpFormatter();
    try {
        CommandLine line = parser.parse(options, args);
        if (line.hasOption(HELP_OPTION)) {
            formatter.printHelp(FileMerger.class.getName(), options);
            System.exit(0);
        }
        if (line.hasOption(INPUT_OPTION)) {
            inputPath = line.getOptionValue(INPUT_OPTION);
        } else {
            throw new ParseException("Parsing failed due to " + INPUT_OPTION + " not initialized...");
        }
        if (line.hasOption(OUTPUT_OPTION)) {
            outputPath = line.getOptionValue(OUTPUT_OPTION);
        } else {
            throw new ParseException("Parsing failed due to " + OUTPUT_OPTION + " not initialized...");
        }
        if (line.hasOption(MAPPER_OPTION)) {
            mapperTasks = Integer.parseInt(line.getOptionValue(MAPPER_OPTION));
            if (mapperTasks <= 0) {
                sLogger.info("Warning: " + MAPPER_OPTION + " is not positive, merge in local model...");
                mapperTasks = 0;
            }
        }
        if (line.hasOption(DELETE_SOURCE_OPTION)) {
            deleteSource = true;
        }
        if (line.hasOption(TEXT_FILE_INPUT_FORMAT)) {
            textFileFormat = true;
        }
    } catch (ParseException pe) {
        System.err.println(pe.getMessage());
        formatter.printHelp(FileMerger.class.getName(), options);
        System.exit(0);
    } catch (NumberFormatException nfe) {
        System.err.println(nfe.getMessage());
        System.exit(0);
    }
    try {
        merge(configuration, inputPath, outputPath, mapperTasks, textFileFormat, deleteSource);
    } catch (InstantiationException ie) {
        ie.printStackTrace();
    } catch (IllegalAccessException iae) {
        iae.printStackTrace();
    }
    return 0;
}
Also used : Options(org.apache.commons.cli.Options) Configuration(org.apache.hadoop.conf.Configuration) GnuParser(org.apache.commons.cli.GnuParser) HelpFormatter(org.apache.commons.cli.HelpFormatter) CommandLine(org.apache.commons.cli.CommandLine) CommandLineParser(org.apache.commons.cli.CommandLineParser) ParseException(org.apache.commons.cli.ParseException) GenericOptionsParser(org.apache.hadoop.util.GenericOptionsParser)

Example 77 with CommandLineParser

use of org.apache.commons.cli.CommandLineParser in project saga by timurstrekalov.

the class Main method main.

public static void main(final String[] args) throws IOException, ParseException {
    logger.debug("Starting...");
    final Option baseDirOpt = new Option("b", "base-dir", true, "Base directory for test search");
    final Option includeOpt = new Option("i", "include", true, "Comma-separated list of Ant-style paths to the tests to run");
    final Option excludeOpt = new Option("e", "exclude", true, "Comma-separated list of Ant-style paths to the tests to exclude from run");
    final Option outputDirOpt = new Option("o", "output-dir", true, "The output directory for coverage reports");
    final Option outputInstrumentedFilesOpt = new Option("f", "output-instrumented-files", false, "Whether to output instrumented files (default is false)");
    final Option noInstrumentPatternOpt = new Option("n", "no-instrument-pattern", true, "Regular expression patterns to match classes to exclude from instrumentation");
    noInstrumentPatternOpt.setArgs(Option.UNLIMITED_VALUES);
    final Option sourcesToPreloadOpt = new Option("p", "preload-sources", true, "Comma-separated list of Ant-style paths to files to preload");
    final Option sourcesToPreloadEncodingOpt = new Option(null, "preload-sources-encoding", true, "Encoding to use when preloading sources");
    final Option threadCountOpt = new Option("t", "thread-count", true, "The maximum number of threads to use (defaults to the number of cores)");
    final Option outputStrategyOpt = new Option("s", "output-strategy", true, "Coverage report output strategy. One of " + Arrays.toString(OutputStrategy.values()));
    final Option includeInlineScriptsOpt = new Option("d", "include-inline-scripts", false, "Whether to include inline scripts into instrumentation by default (default is false)");
    final Option backgroundJavaScriptTimeoutOpt = new Option("j", "background-javascript-timeout", true, "How long to wait for background JavaScript to finish running (in milliseconds, default is 5 minutes)");
    final Option browserVersionOpt = new Option("v", "browser-version", true, "Determines the browser and version profile that HtmlUnit will simulate");
    final Option reportFormatsOpt = new Option(null, "report-formats", true, "A comma-separated list of formats of the reports to be generated. Valid values are: HTML, RAW, CSV, PDF");
    final Option sortByOpt = new Option(null, "sort-by", true, "The column to sort by, one of 'file', 'statements', 'executed' or 'coverage' (default is 'coverage')");
    final Option orderOpt = new Option(null, "order", true, "The order of sorting, one of 'asc' or 'ascending', 'desc' or 'descending' (default is 'ascending')");
    final Option helpOpt = new Option("h", "help", false, "Print this message");
    final Options options = new Options();
    options.addOption(baseDirOpt);
    options.addOption(includeOpt);
    options.addOption(excludeOpt);
    options.addOption(outputDirOpt);
    options.addOption(outputInstrumentedFilesOpt);
    options.addOption(noInstrumentPatternOpt);
    options.addOption(threadCountOpt);
    options.addOption(outputStrategyOpt);
    options.addOption(includeInlineScriptsOpt);
    options.addOption(helpOpt);
    options.addOption(sourcesToPreloadOpt);
    options.addOption(sourcesToPreloadEncodingOpt);
    options.addOption(backgroundJavaScriptTimeoutOpt);
    options.addOption(browserVersionOpt);
    options.addOption(reportFormatsOpt);
    options.addOption(sortByOpt);
    options.addOption(orderOpt);
    logger.debug("Finished configuring options");
    try {
        CommandLineParser parser = new GnuParser();
        CommandLine line = parser.parse(options, args, false);
        logger.debug("Parsed the arguments, take 1");
        baseDirOpt.setRequired(true);
        outputDirOpt.setRequired(true);
        options.addOption(baseDirOpt);
        options.addOption(outputDirOpt);
        if (line.hasOption(helpOpt.getLongOpt())) {
            printHelpAndExit(options);
        }
        parser = new GnuParser();
        line = parser.parse(options, args);
        logger.debug("Parsed the arguments, take 2");
        final String baseDir = line.getOptionValue(baseDirOpt.getLongOpt());
        final String includes = line.getOptionValue(includeOpt.getLongOpt());
        final String excludes = line.getOptionValue(excludeOpt.getLongOpt());
        final File outputDir = new File(line.getOptionValue(outputDirOpt.getLongOpt()));
        final CoverageGenerator gen = CoverageGeneratorFactory.newInstance(baseDir, outputDir);
        final Config config = gen.getConfig();
        config.setIncludes(includes);
        config.setExcludes(excludes);
        if (line.hasOption(outputInstrumentedFilesOpt.getLongOpt())) {
            config.setOutputInstrumentedFiles(true);
        }
        config.setNoInstrumentPatterns(line.getOptionValues(noInstrumentPatternOpt.getLongOpt()));
        config.setSourcesToPreload(line.getOptionValue(sourcesToPreloadOpt.getLongOpt()));
        config.setOutputStrategy(line.getOptionValue(outputStrategyOpt.getLongOpt()));
        final String threadCount = line.getOptionValue(threadCountOpt.getLongOpt());
        if (threadCount != null) {
            try {
                config.setThreadCount(Integer.parseInt(threadCount));
            } catch (final Exception e) {
                System.err.println("Invalid thread count");
                printHelpAndExit(options);
            }
        }
        if (line.hasOption(includeInlineScriptsOpt.getLongOpt())) {
            config.setIncludeInlineScripts(true);
        }
        final String backgroundJavaScriptTimeout = line.getOptionValue(backgroundJavaScriptTimeoutOpt.getLongOpt());
        if (backgroundJavaScriptTimeout != null) {
            try {
                config.setBackgroundJavaScriptTimeout(Long.valueOf(backgroundJavaScriptTimeout));
            } catch (final Exception e) {
                System.err.println("Invalid timeout");
                printHelpAndExit(options);
            }
        }
        config.setBrowserVersion(line.getOptionValue(browserVersionOpt.getLongOpt()));
        config.setReportFormats(line.getOptionValue(reportFormatsOpt.getLongOpt()));
        config.setSortBy(line.getOptionValue(sortByOpt.getLongOpt()));
        config.setOrder(line.getOptionValue(orderOpt.getLongOpt()));
        logger.debug("Configured the coverage generator, running");
        gen.instrumentAndGenerateReports();
    } catch (final MissingOptionException e) {
        System.err.println(e.getMessage());
        printHelpAndExit(options);
    } catch (final UnrecognizedOptionException e) {
        System.err.println(e.getMessage());
        printHelpAndExit(options);
    } catch (final ParseException e) {
        System.err.println(e.getMessage());
        System.exit(1);
    }
}
Also used : Options(org.apache.commons.cli.Options) CoverageGenerator(com.github.timurstrekalov.saga.core.CoverageGenerator) Config(com.github.timurstrekalov.saga.core.cfg.Config) GnuParser(org.apache.commons.cli.GnuParser) UnrecognizedOptionException(org.apache.commons.cli.UnrecognizedOptionException) IOException(java.io.IOException) MissingOptionException(org.apache.commons.cli.MissingOptionException) ParseException(org.apache.commons.cli.ParseException) UnrecognizedOptionException(org.apache.commons.cli.UnrecognizedOptionException) CommandLine(org.apache.commons.cli.CommandLine) Option(org.apache.commons.cli.Option) CommandLineParser(org.apache.commons.cli.CommandLineParser) ParseException(org.apache.commons.cli.ParseException) File(java.io.File) MissingOptionException(org.apache.commons.cli.MissingOptionException)

Example 78 with CommandLineParser

use of org.apache.commons.cli.CommandLineParser in project solo by b3log.

the class Starter method main.

/**
     * Main.
     *
     * @param args the specified arguments
     * @throws java.lang.Exception if start failed
     */
public static void main(final String[] args) throws Exception {
    final Logger logger = Logger.getLogger(Starter.class);
    final Options options = new Options();
    final Option listenPortOpt = Option.builder("lp").longOpt("listen_port").argName("LISTEN_PORT").hasArg().desc("listen port, default is 8080").build();
    options.addOption(listenPortOpt);
    final Option serverSchemeOpt = Option.builder("ss").longOpt("server_scheme").argName("SERVER_SCHEME").hasArg().desc("browser visit protocol, default is http").build();
    options.addOption(serverSchemeOpt);
    final Option serverHostOpt = Option.builder("sh").longOpt("server_host").argName("SERVER_HOST").hasArg().desc("browser visit domain name, default is localhost").build();
    options.addOption(serverHostOpt);
    final Option serverPortOpt = Option.builder("sp").longOpt("server_port").argName("SERVER_PORT").hasArg().desc("browser visit port, default is 8080").build();
    options.addOption(serverPortOpt);
    final Option staticServerSchemeOpt = Option.builder("sss").longOpt("static_server_scheme").argName("STATIC_SERVER_SCHEME").hasArg().desc("browser visit static resource protocol, default is http").build();
    options.addOption(staticServerSchemeOpt);
    final Option staticServerHostOpt = Option.builder("ssh").longOpt("static_server_host").argName("STATIC_SERVER_HOST").hasArg().desc("browser visit static resource domain name, default is localhost").build();
    options.addOption(staticServerHostOpt);
    final Option staticServerPortOpt = Option.builder("ssp").longOpt("static_server_port").argName("STATIC_SERVER_PORT").hasArg().desc("browser visit static resource port, default is 8080").build();
    options.addOption(staticServerPortOpt);
    final Option runtimeModeOpt = Option.builder("rm").longOpt("runtime_mode").argName("RUNTIME_MODE").hasArg().desc("runtime mode (DEVELOPMENT/PRODUCTION), default is DEVELOPMENT").build();
    options.addOption(runtimeModeOpt);
    options.addOption("h", "help", false, "print help for the command");
    final HelpFormatter helpFormatter = new HelpFormatter();
    final CommandLineParser commandLineParser = new DefaultParser();
    CommandLine commandLine;
    final boolean isWindows = System.getProperty("os.name").toLowerCase().contains("windows");
    final String cmdSyntax = isWindows ? "java -cp WEB-INF/lib/*;WEB-INF/classes org.b3log.solo.Starter" : "java -cp WEB-INF/lib/*:WEB-INF/classes org.b3log.solo.Starter";
    final String header = "\nSolo is a blogging system written in Java, feel free to create your or your team own blog.\nSolo 是一个用 Java 实现的博客系统,为你或你的团队创建个博客吧。\n\n";
    final String footer = "\nReport bugs or request features please visit our project website: https://github.com/b3log/solo\n\n";
    try {
        commandLine = commandLineParser.parse(options, args);
    } catch (final ParseException e) {
        helpFormatter.printHelp(cmdSyntax, header, options, footer, true);
        return;
    }
    if (commandLine.hasOption("h")) {
        helpFormatter.printHelp(cmdSyntax, header, options, footer, true);
        return;
    }
    String portArg = commandLine.getOptionValue("listen_port");
    if (!Strings.isNumeric(portArg)) {
        portArg = "8080";
    }
    String serverScheme = commandLine.getOptionValue("server_scheme");
    Latkes.setServerScheme(serverScheme);
    String serverHost = commandLine.getOptionValue("server_host");
    Latkes.setServerHost(serverHost);
    String serverPort = commandLine.getOptionValue("server_port");
    Latkes.setServerPort(serverPort);
    String staticServerScheme = commandLine.getOptionValue("static_server_scheme");
    Latkes.setStaticServerScheme(staticServerScheme);
    String staticServerHost = commandLine.getOptionValue("static_server_host");
    Latkes.setStaticServerHost(staticServerHost);
    String staticServerPort = commandLine.getOptionValue("static_server_port");
    Latkes.setStaticServerPort(staticServerPort);
    String runtimeMode = commandLine.getOptionValue("runtime_mode");
    if (null != runtimeMode) {
        Latkes.setRuntimeMode(RuntimeMode.valueOf(runtimeMode));
    }
    // For Latke IoC 
    Latkes.setScanPath("org.b3log.solo");
    logger.info("Standalone mode, see [https://github.com/b3log/solo/wiki/standalone_mode] for more details.");
    Latkes.initRuntimeEnv();
    // POM structure in dev env
    String webappDirLocation = "src/main/webapp/";
    final File file = new File(webappDirLocation);
    if (!file.exists()) {
        // production environment
        webappDirLocation = ".";
    }
    final int port = Integer.valueOf(portArg);
    final Server server = new Server(port);
    final WebAppContext root = new WebAppContext();
    // Use parent class loader
    root.setParentLoaderPriority(true);
    root.setContextPath("/");
    root.setDescriptor(webappDirLocation + "/WEB-INF/web.xml");
    root.setResourceBase(webappDirLocation);
    server.setHandler(root);
    try {
        server.start();
    } catch (final Exception e) {
        logger.log(Level.ERROR, "Server start failed", e);
        System.exit(-1);
    }
    serverScheme = Latkes.getServerScheme();
    serverHost = Latkes.getServerHost();
    serverPort = Latkes.getServerPort();
    final String contextPath = Latkes.getContextPath();
    try {
        Desktop.getDesktop().browse(new URI(serverScheme + "://" + serverHost + ":" + serverPort + contextPath));
    } catch (final Throwable e) {
    // Ignored
    }
    server.join();
}
Also used : Options(org.apache.commons.cli.Options) Server(org.eclipse.jetty.server.Server) Logger(org.b3log.latke.logging.Logger) URI(java.net.URI) ParseException(org.apache.commons.cli.ParseException) HelpFormatter(org.apache.commons.cli.HelpFormatter) WebAppContext(org.eclipse.jetty.webapp.WebAppContext) CommandLine(org.apache.commons.cli.CommandLine) Option(org.apache.commons.cli.Option) CommandLineParser(org.apache.commons.cli.CommandLineParser) ParseException(org.apache.commons.cli.ParseException) File(java.io.File) DefaultParser(org.apache.commons.cli.DefaultParser)

Example 79 with CommandLineParser

use of org.apache.commons.cli.CommandLineParser in project groovy-core by groovy.

the class Java2GroovyMain method main.

public static void main(String[] args) {
    try {
        Options options = new Options();
        CommandLineParser cliParser = new GroovyInternalPosixParser();
        CommandLine cli = cliParser.parse(options, args);
        String[] filenames = cli.getArgs();
        if (filenames.length == 0) {
            System.err.println("Needs at least one filename");
        }
        Java2GroovyProcessor.processFiles(Arrays.asList(filenames));
    } catch (Throwable t) {
        t.printStackTrace();
    }
}
Also used : Options(org.apache.commons.cli.Options) CommandLine(org.apache.commons.cli.CommandLine) CommandLineParser(org.apache.commons.cli.CommandLineParser) GroovyInternalPosixParser(org.apache.commons.cli.GroovyInternalPosixParser)

Example 80 with CommandLineParser

use of org.apache.commons.cli.CommandLineParser in project groovy-core by groovy.

the class Groovyc method runCompiler.

private void runCompiler(String[] commandLine) {
    // hand crank it so we can add our own compiler configuration
    try {
        Options options = FileSystemCompiler.createCompilationOptions();
        CommandLineParser cliParser = new GroovyInternalPosixParser();
        CommandLine cli;
        cli = cliParser.parse(options, commandLine);
        configuration = FileSystemCompiler.generateCompilerConfigurationFromOptions(cli);
        configuration.setScriptExtensions(getScriptExtensions());
        String tmpExtension = getScriptExtension();
        if (tmpExtension.startsWith("*."))
            tmpExtension = tmpExtension.substring(1);
        configuration.setDefaultScriptExtension(tmpExtension);
        // Load the file name list
        String[] filenames = FileSystemCompiler.generateFileNamesFromOptions(cli);
        boolean fileNameErrors = filenames == null;
        fileNameErrors = fileNameErrors && !FileSystemCompiler.validateFiles(filenames);
        if (targetBytecode != null) {
            configuration.setTargetBytecode(targetBytecode);
        }
        if (!fileNameErrors) {
            FileSystemCompiler.doCompilation(configuration, makeCompileUnit(), filenames, forceLookupUnnamedFiles);
        }
    } catch (Exception re) {
        Throwable t = re;
        if ((re.getClass() == RuntimeException.class) && (re.getCause() != null)) {
            // unwrap to the real exception
            t = re.getCause();
        }
        StringWriter writer = new StringWriter();
        new ErrorReporter(t, false).write(new PrintWriter(writer));
        String message = writer.toString();
        taskSuccess = false;
        if (errorProperty != null) {
            getProject().setNewProperty(errorProperty, "true");
        }
        if (failOnError) {
            log.error(message);
            throw new BuildException("Compilation Failed", t, getLocation());
        } else {
            log.error(message);
        }
    }
}
Also used : Options(org.apache.commons.cli.Options) GroovyInternalPosixParser(org.apache.commons.cli.GroovyInternalPosixParser) MalformedURLException(java.net.MalformedURLException) IOException(java.io.IOException) BuildException(org.apache.tools.ant.BuildException) CommandLine(org.apache.commons.cli.CommandLine) ErrorReporter(org.codehaus.groovy.tools.ErrorReporter) StringWriter(java.io.StringWriter) CommandLineParser(org.apache.commons.cli.CommandLineParser) BuildException(org.apache.tools.ant.BuildException) PrintWriter(java.io.PrintWriter)

Aggregations

CommandLineParser (org.apache.commons.cli.CommandLineParser)265 CommandLine (org.apache.commons.cli.CommandLine)246 Options (org.apache.commons.cli.Options)206 ParseException (org.apache.commons.cli.ParseException)186 GnuParser (org.apache.commons.cli.GnuParser)158 HelpFormatter (org.apache.commons.cli.HelpFormatter)111 PosixParser (org.apache.commons.cli.PosixParser)61 Option (org.apache.commons.cli.Option)52 IOException (java.io.IOException)48 Path (org.apache.hadoop.fs.Path)42 File (java.io.File)41 DefaultParser (org.apache.commons.cli.DefaultParser)29 Job (org.apache.hadoop.mapreduce.Job)27 Configuration (org.apache.hadoop.conf.Configuration)19 FileInputStream (java.io.FileInputStream)16 Properties (java.util.Properties)15 ArrayList (java.util.ArrayList)14 BasicParser (org.apache.commons.cli.BasicParser)14 FileSystem (org.apache.hadoop.fs.FileSystem)12 URI (java.net.URI)10