Example usage for org.apache.commons.cli PosixParser PosixParser

List of usage examples for org.apache.commons.cli PosixParser PosixParser

Introduction

In this page you can find the example usage for org.apache.commons.cli PosixParser PosixParser.

Prototype

PosixParser

Source Link

Usage

From source file:com.galenframework.actions.GalenActionConfigArguments.java

public static GalenActionConfigArguments parse(String[] args) {
    args = ArgumentsUtils.processSystemProperties(args);

    Options options = new Options();
    options.addOption("g", "global", false, "Flag to create global config in user home directory");

    CommandLineParser parser = new PosixParser();
    CommandLine cmd;/*  ww  w .j  ava  2s.  c o m*/

    try {
        cmd = parser.parse(options, args);
    } catch (MissingArgumentException e) {
        throw new IllegalArgumentException("Missing value for " + e.getOption().getLongOpt(), e);
    } catch (Exception ex) {
        throw new RuntimeException(ex);
    }

    GalenActionConfigArguments configArguments = new GalenActionConfigArguments();
    configArguments.isGlobal = cmd.hasOption("g");
    return configArguments;
}

From source file:lanchon.dexpatcher.Parser.java

public static Configuration parseCommandLine(String[] args) throws ParseException {

    Configuration config = new Configuration();

    Options options = getOptions();//from   www  .  ja  v a2  s  .c o m
    CommandLine cl = new PosixParser().parse(options, args);

    if (cl.hasOption("help")) {
        printUsage();
        return null;
    }

    if (cl.hasOption("version")) {
        System.out.println(Main.getVersion());
        return null;
    }

    @SuppressWarnings("unchecked")
    List<String> files = cl.getArgList();
    if (files.isEmpty())
        throw new ParseException("Missing argument: <source-dex-apk-or-dir>");
    config.sourceFile = files.remove(0);
    config.patchFiles = files;
    config.patchedFile = cl.getOptionValue("output");

    Number apiLevel = (Number) cl.getParsedOptionValue("api-level");
    if (apiLevel != null)
        config.apiLevel = apiLevel.intValue();

    config.multiDex = cl.hasOption("multi-dex");
    if (cl.hasOption("multi-dex-threaded")) {
        config.multiDex = true;
        config.multiDexJobs = 0;
    }
    Number multiDexJobs = (Number) cl.getParsedOptionValue("multi-dex-jobs");
    if (multiDexJobs != null) {
        config.multiDex = true;
        config.multiDexJobs = multiDexJobs.intValue();
    }

    Number maxDexPoolSize = (Number) cl.getParsedOptionValue("max-dex-pool-size");
    if (maxDexPoolSize != null)
        config.maxDexPoolSize = maxDexPoolSize.intValue();

    config.annotationPackage = cl.getOptionValue("annotations", Context.DEFAULT_ANNOTATION_PACKAGE);
    config.dexTagSupported = cl.hasOption("compat-dextag");

    config.logLevel = WARN;
    if (cl.hasOption("quiet"))
        config.logLevel = ERROR;
    if (cl.hasOption("verbose"))
        config.logLevel = INFO;
    if (cl.hasOption("debug"))
        config.logLevel = DEBUG;

    if (cl.hasOption("path"))
        config.sourceCodeRoot = "";
    config.sourceCodeRoot = cl.getOptionValue("path-root", config.sourceCodeRoot);
    config.timingStats = cl.hasOption("stats");

    config.dryRun = cl.hasOption("dry-run");

    return config;

}

From source file:com.opengamma.integration.marketdata.WatchListRecorder.java

/**
 * Main entry point./*from  ww  w  .  j  a v  a2 s . c o  m*/
 * 
 * @param args the arguments
 * @throws Exception if an error occurs
 */
public static void main(final String[] args) throws Exception { // CSIGNORE
    final CommandLineParser parser = new PosixParser();
    final Options options = new Options();
    final Option outputFileOpt = new Option("o", "output", true, "output file");
    outputFileOpt.setRequired(true);
    options.addOption(outputFileOpt);
    final Option urlOpt = new Option("u", "url", true, "server url");
    options.addOption(urlOpt);
    String outputFile = "watchList.txt";
    String url = "http://localhost:8080/jax";
    try {
        final CommandLine cmd = parser.parse(options, args);
        outputFile = cmd.getOptionValue("output");
        url = cmd.getOptionValue("url");
    } catch (final ParseException exp) {
        s_logger.error("Option parsing failed: {}", exp.getMessage());
        System.exit(0);
    }

    final WatchListRecorder recorder = create(URI.create(url), "main", "combined");
    recorder.addWatchScheme(ExternalSchemes.BLOOMBERG_TICKER);
    recorder.addWatchScheme(ExternalSchemes.BLOOMBERG_BUID);
    final PrintWriter pw = new PrintWriter(outputFile);
    recorder.setPrintWriter(pw);
    recorder.run();

    pw.close();
    System.exit(0);
}

From source file:net.schweerelos.parrot.CombinedParrotApp.java

/**
 * @param args//  w  ww. j a  v a2  s.  co m
 */
@SuppressWarnings("static-access")
public static void main(String[] args) {
    CommandLineParser parser = new PosixParser();
    // create the Options
    Options options = new Options();
    options.addOption(OptionBuilder.withLongOpt("help")
            .withDescription("Shows usage information and quits the program").create("h"));

    options.addOption(
            OptionBuilder.withLongOpt("datafile").withDescription("The file with instances to use (required)")
                    .hasArg().withArgName("file").isRequired().create("f"));

    options.addOption(OptionBuilder.withLongOpt("properties")
            .withDescription("Properties file to use. Default: " + System.getProperty("user.home")
                    + File.separator + ".digital-parrot" + File.separator + "parrot.properties")
            .hasArg().withArgName("prop").create("p"));
    try {
        // parse the command line arguments
        CommandLine line = parser.parse(options, args);

        if (line.hasOption("h")) {
            // this is only executed when all required options are present _and_ the help option is specified!
            printHelp(options);
            return;
        }

        String datafile = line.getOptionValue("f");
        if (!datafile.startsWith("file:") || !datafile.startsWith("http:")) {
            datafile = "file:" + datafile;
        }

        String propertiesPath = System.getProperty("user.home") + File.separator + ".digital-parrot"
                + File.separator + "parrot.properties";
        if (line.hasOption("p")) {
            propertiesPath = line.getOptionValue("p");
        }
        final Properties properties = new Properties();
        File propertiesFile = new File(propertiesPath);
        if (propertiesFile.exists() && propertiesFile.canRead()) {
            try {
                properties.load(new FileReader(propertiesFile));
            } catch (FileNotFoundException e) {
                e.printStackTrace(System.err);
                System.exit(1);
            } catch (IOException e) {
                e.printStackTrace(System.err);
                System.exit(1);
            }
        }

        final String url = datafile; // we need a "final" var for the anonymous class
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                CombinedParrotApp inst = null;
                try {
                    inst = new CombinedParrotApp(properties);
                    inst.loadModel(url);
                } catch (Exception e) {
                    JOptionPane.showMessageDialog(null,
                            "There has been an error while starting the program.\nThe program will exit now.",
                            APP_TITLE + "  Error", JOptionPane.ERROR_MESSAGE);
                    e.printStackTrace(System.err);
                    System.exit(1);
                }
                if (inst != null) {
                    inst.setLocationRelativeTo(null);
                    inst.setVisible(true);
                }
            }
        });
    } catch (ParseException exp) {
        printHelp(options);
    }
}

From source file:de.meldanor.melchatclient.Core.java

public static String[] parseArguments(String[] args) {
    Options options = new Options();
    options.addOption("p", true, "Port");
    options.addOption("h", true, "Host");
    CommandLineParser parser = new PosixParser();
    CommandLine cmd = null;/*from   ww w  .  j  av  a2  s . c  om*/
    String host = null;
    String port = null;

    try {
        cmd = parser.parse(options, args);
        host = cmd.getOptionValue("h");
        port = cmd.getOptionValue('p');
    } catch (ParseException e) {
        System.out.println("Usage: -h HOST -p PORT");
        return null;
    }
    return new String[] { host, port };
}

From source file:com.ggvaidya.TaxRef.Cmdline.CmdController.java

public static void handle(String[] args) {
    Options cmdLineOptions = new Options();
    setupOptions(cmdLineOptions);//from   w w  w. j a va 2 s  .c  om

    // Parse command line options (if possible).
    CommandLineParser parser = new PosixParser();
    CommandLine cmd;
    try {
        cmd = parser.parse(cmdLineOptions, args);
    } catch (ParseException ex) {
        System.err.println("Could not parse command line: " + ex);
        System.exit(1);
        return;
    }

    // --version: report the version and copyright information, then exit.
    if (cmd.hasOption("version")) {
        System.err.println(TaxRef.getName() + "/" + TaxRef.getVersion());
        System.err.println(TaxRef.getDescription());
        System.err.println(TaxRef.getCopyright());
        System.err.println();
        System.exit(0);
    }

    // boolean case_sensitive = (cmd.getOptionValue("case") == null) ? false : true;
    // TODO: actually write code here.

    MainFrame mf = new MainFrame();
    mf.getMainFrame().setVisible(true);
}

From source file:com.milaboratory.mitcr.cli.Main.java

public static void main(String[] args) {
    int o = 0;//from  w w w.j a  v  a  2 s. c  o m

    BuildInformation buildInformation = BuildInformationProvider.get();

    final boolean isProduction = "default".equals(buildInformation.scmBranch); // buildInformation.version != null && buildInformation.version.lastIndexOf("SNAPSHOT") < 0;

    orderingMap.put(PARAMETERS_SET_OPTION, o++);
    orderingMap.put(SPECIES_OPTION, o++);
    orderingMap.put(GENE_OPTION, o++);
    orderingMap.put(ERROR_CORECTION_LEVEL_OPTION, o++);
    orderingMap.put(QUALITY_THRESHOLD_OPTION, o++);
    orderingMap.put(AVERAGE_QUALITY_OPTION, o++);
    orderingMap.put(LQ_OPTION, o++);
    orderingMap.put(CLUSTERIZATION_OPTION, o++);
    orderingMap.put(INCLUDE_CYS_PHE_OPTION, o++);
    orderingMap.put(LIMIT_OPTION, o++);
    orderingMap.put(EXPORT_OPTION, o++);
    orderingMap.put(REPORT_OPTION, o++);
    orderingMap.put(REPORTING_LEVEL_OPTION, o++);
    orderingMap.put(PHRED33_OPTION, o++);
    orderingMap.put(PHRED64_OPTION, o++);
    orderingMap.put(THREADS_OPTION, o++);
    orderingMap.put(COMPRESSED_OPTION, o++);
    orderingMap.put(PRINT_HELP_OPTION, o++);
    orderingMap.put(PRINT_VERSION_OPTION, o++);
    orderingMap.put(PRINT_DEBUG_OPTION, o++);

    options.addOption(OptionBuilder.withArgName("preset name").hasArg()
            .withDescription("preset of pipeline parameters to use").create(PARAMETERS_SET_OPTION));

    options.addOption(OptionBuilder.withArgName("species").hasArg()
            .withDescription("overrides species ['hs' for Homo sapiens, 'mm' for us Mus musculus] "
                    + "(default for built-in presets is 'hs')")
            .create(SPECIES_OPTION));

    options.addOption(OptionBuilder.withArgName("gene").hasArg()
            .withDescription("overrides gene: TRB or TRA (default value for built-in parameter sets is TRB)")
            .create(GENE_OPTION));

    options.addOption(OptionBuilder.withArgName("0|1|2").hasArg()
            .withDescription(
                    "overrides error correction level (0 = don't correct errors, 1 = correct sequenecing "
                            + "errors only (see -" + QUALITY_THRESHOLD_OPTION + " and -" + LQ_OPTION
                            + " options for details), " + "2 = also correct PCR errors (see -"
                            + CLUSTERIZATION_OPTION + " option)")
            .create(ERROR_CORECTION_LEVEL_OPTION));

    options.addOption(OptionBuilder.withArgName("value").hasArg().withDescription(
            "overrides quality threshold value for segment alignment and bad quality sequences "
                    + "correction algorithms. 0 tells the program not to process quality information. (default is 25)")
            .create(QUALITY_THRESHOLD_OPTION));

    if (!isProduction)
        options.addOption(OptionBuilder.hasArg(false)
                .withDescription("use this option to output average instead of "
                        + "maximal, quality for CDR3 nucleotide sequences. (Experimental option, use with caution.)")
                .create(AVERAGE_QUALITY_OPTION));

    options.addOption(OptionBuilder.withArgName("map | drop").hasArg()
            .withDescription("overrides low quality CDR3s processing strategy (drop = filter off, "
                    + "map = map onto clonotypes created from the high quality CDR3s). This option makes no difference if "
                    + "quality threshold (-" + QUALITY_THRESHOLD_OPTION
                    + " option) is set to 0, or error correction " + "level (-" + ERROR_CORECTION_LEVEL_OPTION
                    + ") is 0.")
            .create(LQ_OPTION));

    options.addOption(OptionBuilder.withArgName("smd | ete").hasArg()
            .withDescription("overrides the PCR error correction algorithm: smd = \"save my diversity\", "
                    + "ete = \"eliminate these errors\". Default value for built-in parameters is ete.")
            .create(CLUSTERIZATION_OPTION));

    options.addOption(OptionBuilder.withArgName("0|1").hasArg()
            .withDescription("overrides weather include bounding Cys & Phe into CDR3 sequence")
            .create(INCLUDE_CYS_PHE_OPTION));

    options.addOption(
            OptionBuilder.withArgName("# of reads").hasArg()
                    .withDescription("limits the number of input sequencing reads, use this parameter to "
                            + "normalize several datasets or to have a glance at the data")
                    .create(LIMIT_OPTION));

    options.addOption(OptionBuilder.withArgName("new name").hasArg()
            .withDescription("use this option to export presets to a local xml files").create(EXPORT_OPTION));

    options.addOption(OptionBuilder.withArgName("file name").hasArg()
            .withDescription("use this option to write analysis report (summary) to file")
            .create(REPORT_OPTION));

    options.addOption(OptionBuilder.withArgName("1|2|3").hasArg(true)
            .withDescription("output detalization level (1 = simple, 2 = medium, 3 = full, this format "
                    + "could be deserialized using mitcr API). Affects only tab-delimited output. Default value is 3.")
            .create(REPORTING_LEVEL_OPTION));

    options.addOption(OptionBuilder.hasArg(false).withDescription(
            "add this option if input file is in old illumina format with 64 byte offset for quality "
                    + "string (MiTCR will try to automatically detect file format if one of the \"-phredXX\" options is not provided)")
            .create(PHRED64_OPTION));

    options.addOption(OptionBuilder.hasArg(false)
            .withDescription("add this option if input file is in Phred+33 format for quality values "
                    + "(MiTCR will try to automatically detect file format if one of the \"-phredXX\" options is not provided)")
            .create(PHRED33_OPTION));

    options.addOption(OptionBuilder.withArgName("threads").hasArg()
            .withDescription(
                    "specifies the number of CDR3 extraction threads (default = number of available CPU cores)")
            .create(THREADS_OPTION));

    if (!isProduction)
        options.addOption(OptionBuilder.hasArg(false)
                .withDescription("use compressed data structures for storing individual "
                        + "clone segments statistics (from which arises the clone segment information). This option reduces required "
                        + "amount of memory, but introduces small stochastic errors into the algorithm which determines clone "
                        + "segments. (Experimental option, use with caution.)")
                .create(COMPRESSED_OPTION));

    options.addOption(
            OptionBuilder.hasArg(false).withDescription("print this message").create(PRINT_HELP_OPTION));

    options.addOption(OptionBuilder.hasArg(false).withDescription("print version information")
            .create(PRINT_VERSION_OPTION));

    options.addOption(OptionBuilder.hasArg(false)
            .withDescription("print additional information about analysis process").create(PRINT_DEBUG_OPTION));

    PosixParser parser = new PosixParser();

    try {
        long input_limit = -1;
        int threads = Runtime.getRuntime().availableProcessors();
        int reporting_level = 3;
        int ec_level = 2;

        CommandLine cl = parser.parse(options, args, true);
        if (cl.hasOption(PRINT_HELP_OPTION)) {
            printHelp();
            return;
        }

        boolean averageQuality = cl.hasOption(AVERAGE_QUALITY_OPTION),
                compressedAggregators = cl.hasOption(COMPRESSED_OPTION);

        if (cl.hasOption(PRINT_VERSION_OPTION)) {
            System.out.println("MiTCR by MiLaboratory, version: " + buildInformation.version);
            System.out.println("Branch: " + buildInformation.scmBranch);
            System.out.println("Built: " + buildInformation.buildDate + ", " + buildInformation.jdk + " JDK, "
                    + "build machine: " + buildInformation.builtBy);
            System.out.println("SCM changeset: " + buildInformation.scmChangeset + " ("
                    + buildInformation.scmDate.replace("\"", "") + ")");
            return;
        }

        //Normal execution

        String paramName = cl.getOptionValue(PARAMETERS_SET_OPTION);

        if (paramName == null) {
            err.println("No parameters set is specified.");
            return;
        }

        Parameters params = ParametersIO.getParameters(paramName);

        if (params == null) {
            err.println("No parameters set found with name '" + paramName + "'.");
            return;
        }

        String value;

        if ((value = cl.getOptionValue(THREADS_OPTION)) != null)
            threads = Integer.decode(value);

        if ((value = cl.getOptionValue(REPORTING_LEVEL_OPTION)) != null)
            reporting_level = Integer.decode(value);

        if ((value = cl.getOptionValue(LIMIT_OPTION)) != null)
            input_limit = Long.decode(value);

        if ((value = cl.getOptionValue(GENE_OPTION)) != null)
            params.setGene(Gene.fromXML(value));

        if ((value = cl.getOptionValue(SPECIES_OPTION)) != null)
            params.setSpecies(Species.getFromShortName(value));

        if ((value = cl.getOptionValue(INCLUDE_CYS_PHE_OPTION)) != null) {
            if (value.equals("1"))
                params.getCDR3ExtractorParameters().setIncludeCysPhe(true);
            else if (value.equals("0"))
                params.getCDR3ExtractorParameters().setIncludeCysPhe(false);
            else {
                err.println("Illegal value for -" + INCLUDE_CYS_PHE_OPTION + " parameter.");
                return;
            }
        }

        if ((value = cl.getOptionValue(ERROR_CORECTION_LEVEL_OPTION)) != null) {
            int v = Integer.decode(value);
            ec_level = v;
            if (v == 0) {
                params.setCloneGeneratorParameters(new BasicCloneGeneratorParameters());
                params.setClusterizationType(CloneClusterizationType.None);
            } else if (v == 1) {
                params.setCloneGeneratorParameters(new LQMappingCloneGeneratorParameters());
                params.setClusterizationType(CloneClusterizationType.None);
            } else if (v == 2) {
                params.setCloneGeneratorParameters(new LQMappingCloneGeneratorParameters());
                params.setClusterizationType(CloneClusterizationType.OneMismatch, .1f);
            } else
                throw new RuntimeException("This (" + v + ") error correction level is not supported.");
        }

        if ((value = cl.getOptionValue(QUALITY_THRESHOLD_OPTION)) != null) {
            int v = Integer.decode(value);
            if (v == 0)
                params.setQualityInterpretationStrategy(new DummyQualityInterpretationStrategy());
            else
                params.setQualityInterpretationStrategy(new IlluminaQualityInterpretationStrategy((byte) v));
        }

        if ((value = cl.getOptionValue(LQ_OPTION)) != null)
            if (ec_level > 0)
                switch (value) {
                case "map":
                    params.setCloneGeneratorParameters(new LQMappingCloneGeneratorParameters(
                            ((BasicCloneGeneratorParameters) params.getCloneGeneratorParameters())
                                    .getSegmentInformationAggregationFactor(),
                            3, true));
                    break;
                case "drop":
                    params.setCloneGeneratorParameters(new LQFilteringOffCloneGeneratorParameters(
                            ((BasicCloneGeneratorParameters) params.getCloneGeneratorParameters())
                                    .getSegmentInformationAggregationFactor()));
                    break;
                default:
                    throw new RuntimeException("Wrong value for -" + LQ_OPTION + " option.");
                }

        if ((value = cl.getOptionValue(CLUSTERIZATION_OPTION)) != null)
            if (ec_level > 1) // == 2
                switch (value) {
                case "smd":
                    params.setClusterizationType(CloneClusterizationType.V2D1J2T3Explicit);
                    break;
                case "ete":
                    params.setClusterizationType(CloneClusterizationType.OneMismatch);
                    break;
                default:
                    throw new RuntimeException("Wrong value for -" + CLUSTERIZATION_OPTION + " option.");
                }

        ((BasicCloneGeneratorParameters) params.getCloneGeneratorParameters())
                .setAccumulatorType(AccumulatorType.get(compressedAggregators, averageQuality));

        if ((value = cl.getOptionValue(EXPORT_OPTION)) != null) {
            //Exporting parameters
            ParametersIO.exportParameters(params, value);
            return;
        }

        String[] offArgs = cl.getArgs();

        if (offArgs.length == 0) {
            err.println("Input file not specified.");
            return;
        } else if (offArgs.length == 1) {
            err.println("Output file not specified.");
            return;
        } else if (offArgs.length > 2) {
            err.println("Unrecognized argument.");
            return;
        }

        String inputFileName = offArgs[0];
        String outputFileName = offArgs[1];

        File input = new File(inputFileName);

        if (!input.exists()) {
            err.println("Input file not found.");
            return;
        }

        //TODO This also done inside SFastqReader constructor
        CompressionType compressionType = CompressionType.None;
        if (inputFileName.endsWith(".gz"))
            compressionType = CompressionType.GZIP;

        QualityFormat format = null; // If variable remains null file format will be detected automatically
        if (cl.hasOption(PHRED33_OPTION))
            format = QualityFormat.Phred33;
        if (cl.hasOption(PHRED64_OPTION))
            if (format == null)
                format = QualityFormat.Phred64;
            else {
                err.println(
                        "Options: -" + PHRED33_OPTION + " and -" + PHRED64_OPTION + " are mutually exclusive");
                return;
            }

        SFastqReader reads = format == null ? new SFastqReader(input, compressionType)
                : new SFastqReader(input, format, compressionType);

        OutputPort<SSequencingRead> inputToPipeline = reads;
        if (input_limit >= 0)
            inputToPipeline = new CountLimitingOutputPort<>(inputToPipeline, input_limit);

        SegmentLibrary library = DefaultSegmentLibrary.load();

        AnalysisStatisticsAggregator statisticsAggregator = new AnalysisStatisticsAggregator();

        FullPipeline pipeline = new FullPipeline(inputToPipeline, params, false, library);
        pipeline.setThreads(threads);
        pipeline.setAnalysisListener(statisticsAggregator);

        new Thread(new SmartProgressReporter(pipeline, err)).start(); // Printing status to the standard error stream

        pipeline.run();

        if (cl.hasOption(PRINT_DEBUG_OPTION)) {
            err.println("Memory = " + (Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory()));
            err.println("Clusterization: " + pipeline.getQC().getReadsClusterized() + "% of reads, "
                    + pipeline.getQC().getClonesClusterized() + " % clones");
        }

        CloneSetClustered cloneSet = pipeline.getResult();

        if ((value = cl.getOptionValue(REPORT_OPTION)) != null) {
            File file = new File(value);
            TablePrintStreamAdapter table;
            if (file.exists())
                table = new TablePrintStreamAdapter(new FileOutputStream(file, true));
            else {
                table = new TablePrintStreamAdapter(file);
                ReportExporter.printHeader(table);
            }
            //CloneSetQualityControl qc = new CloneSetQualityControl(library, params.getSpecies(), params.getGene(), cloneSet);
            ReportExporter.printRow(table, inputFileName, outputFileName, pipeline.getQC(),
                    statisticsAggregator);
            table.close();
        }

        if (outputFileName.endsWith(".cls"))
            ClsExporter.export(pipeline, outputFileName.replace(".cls", "") + " " + new Date().toString(),
                    input.getName(), outputFileName);
        else {
            //Dry run
            if (outputFileName.startsWith("-"))
                return;

            ExportDetalizationLevel detalization = ExportDetalizationLevel.fromLevel(reporting_level);

            CompressionType compressionType1 = CompressionType.None;
            if (outputFileName.endsWith(".gz"))
                compressionType1 = CompressionType.GZIP;
            CloneSetIO.exportCloneSet(outputFileName, cloneSet, detalization, params, input.getAbsolutePath(),
                    compressionType1);
        }
    } catch (ParseException | RuntimeException | IOException e) {
        err.println("Error occurred in the analysis pipeline.");
        err.println();
        e.printStackTrace();
        //printHelp();
    }
}

From source file:com.cloudera.learnavro.test.GenerateTestAvro.java

/**
 *///  w  w w  .j a  va  2 s  .c om
public static void main(String argv[]) throws IOException, InstantiationException {
    CommandLine cmd = null;
    Options options = new Options();
    options.addOption("?", false, "Help for command-line");
    options.addOption("n", true, "# tuples to emit per file");

    try {
        CommandLineParser parser = new PosixParser();
        cmd = parser.parse(options, argv);
    } catch (ParseException pe) {
        HelpFormatter fmt = new HelpFormatter();
        fmt.printHelp("GenerateTestAvro", options, true);
        System.exit(-1);
    }

    if (cmd.hasOption("?")) {
        HelpFormatter fmt = new HelpFormatter();
        fmt.printHelp("GenerateTestAvro", options, true);
        System.exit(0);
    }

    int numToEmit = 100;
    if (cmd.hasOption("n")) {
        try {
            numToEmit = Integer.parseInt(cmd.getOptionValue("n"));
        } catch (NumberFormatException nfe) {
            nfe.printStackTrace();
        }
    }

    String[] argArray = cmd.getArgs();
    if (argArray.length == 0) {
        HelpFormatter fmt = new HelpFormatter();
        fmt.printHelp("GenerateTestAvro", options, true);
        System.exit(0);
    }
    File outputDir = new File(argArray[0]).getCanonicalFile();

    GenerateTestAvro gta = new GenerateTestAvro();
    gta.generateData(outputDir, numToEmit);
}

From source file:gr.seab.r2rml.beans.MainParser.java

public static void runParcer(String[] args) {
    Calendar c0 = Calendar.getInstance();
    long t0 = c0.getTimeInMillis();

    CommandLineParser cmdParser = new PosixParser();

    Options cmdOptions = new Options();
    cmdOptions.addOption("p", "properties", true,
            "define the properties file. Example: r2rml-parser -p r2rml.properties");
    cmdOptions.addOption("h", "print help", false, "help");

    String propertiesFile = "r2rml.properties";

    try {//from   w w  w . j av a 2 s .  c o  m
        if (StringUtils.isNotEmpty(propertiesFile)) {
            properties.load(new FileInputStream(propertiesFile));
            log.info("Loaded properties from " + propertiesFile);
            if (args != null && args.length > 0 && args[0].equals("fixProperty")) {
                properties = fixProperty(properties);
            }
        }
    } catch (FileNotFoundException e) {
        //e.printStackTrace();
        String err = "Properties file not found (" + propertiesFile + ").";
        log.error(err);
        throw new RuntimeException(err);
        //System.exit(0);
    } catch (IOException e) {
        //e.printStackTrace();
        String err = "Error reading properties file (" + propertiesFile + ").";
        log.error(err);
        throw new RuntimeException(err);
        //System.exit(0);
    }

    ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("app-context.xml");

    Database db = (Database) context.getBean("db");
    db.setProperties(properties);

    Parser parser = (Parser) context.getBean("parser");
    parser.setProperties(properties);

    MappingDocument mappingDocument = parser.parse();

    mappingDocument.getTimestamps().add(t0); //0 Started
    mappingDocument.getTimestamps().add(Calendar.getInstance().getTimeInMillis()); //1 Finished parsing. Starting generating result model.

    Generator generator = (Generator) context.getBean("generator");
    generator.setProperties(properties);
    generator.setResultModel(parser.getResultModel());

    //Actually do the output
    generator.createTriples(mappingDocument);

    context.close();
    Calendar c1 = Calendar.getInstance();
    long t1 = c1.getTimeInMillis();
    log.info("Finished in " + (t1 - t0) + " milliseconds. Done.");
    mappingDocument.getTimestamps().add(Calendar.getInstance().getTimeInMillis()); //5 Finished.
    //log.info("5 Finished.");

    //output the result
    for (int i = 0; i < mappingDocument.getTimestamps().size(); i++) {
        if (i > 0) {
            long l = (mappingDocument.getTimestamps().get(i).longValue()
                    - mappingDocument.getTimestamps().get(i - 1).longValue());
            //System.out.println(l);
            log.info(String.valueOf(l));
        }
    }
    log.info("Parse. Generate in memory. Dump to disk/database. Log. - Alltogether in "
            + String.valueOf(mappingDocument.getTimestamps().get(5).longValue()
                    - mappingDocument.getTimestamps().get(0).longValue())
            + " msec.");
    log.info("Done.");
    System.out.println("Done.");
}

From source file:edu.stanford.muse.launcher.Main.java

public static void main(String args[]) throws Exception {

    // set javawebstart.version to a dummy value if not already set (might happen when running with java -jar from cmd line)
    // exit.jsp doesn't allow us to showdown unless this prop is set
    if (System.getProperty("javawebstart.version") == null)
        System.setProperty("javawebstart.version", "UNKNOWN");

    final int TIMEOUT_SECS = 60;
    if (args.length > 0) {
        out.print(args.length + " argument(s): ");
        for (int i = 0; i < args.length; i++)
            out.print(args[i] + " ");
        out.println();/* w w w .  j  ava  2  s.  c o m*/
    }

    Options options = getOpt();
    CommandLineParser parser = new PosixParser();
    CommandLine cmd = parser.parse(options, args);
    if (cmd.hasOption("help")) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("Muse batch mode", options);
        return;
    }

    boolean debug = false;
    if (cmd.hasOption("debug")) {
        URL url = ClassLoader.getSystemResource("log4j.properties.debug");
        out.println("Loading logging configuration from url: " + url);
        PropertyConfigurator.configure(url);
        debug = true;
    } else if (cmd.hasOption("debug-address-book")) {
        URL url = ClassLoader.getSystemResource("log4j.properties.debug.ab");
        out.println("Loading logging configuration from url: " + url);
        PropertyConfigurator.configure(url);
        debug = false;
    } else if (cmd.hasOption("debug-groups")) {
        URL url = ClassLoader.getSystemResource("log4j.properties.debug.groups");
        out.println("Loading logging configuration from url: " + url);
        PropertyConfigurator.configure(url);
        debug = false;
    }

    if (cmd.hasOption("no-browser-open"))
        browserOpen = false;

    if (cmd.hasOption("port")) {
        String portStr = cmd.getOptionValue('p');
        try {
            PORT = Integer.parseInt(portStr);
            String mesg = " Running on port: " + PORT;
            out.println(mesg);
        } catch (NumberFormatException nfe) {
            out.println("invalid port number " + portStr);
        }
    }

    if (cmd.hasOption("start-page"))
        startPage = cmd.getOptionValue("start-page");
    if (cmd.hasOption("base-dir"))
        baseDir = cmd.getOptionValue("base-dir");
    if (cmd.hasOption("search-mode"))
        searchMode = true;
    if (cmd.hasOption("amuse-mode"))
        amuseMode = true;

    System.setSecurityManager(null); // this is important
    WebAppContext webapp0 = null; // deployWarAt("root.war", "/"); // for redirecting
    String path = "/muse";
    WebAppContext webapp1 = deployWarAt("muse.war", path);
    if (webapp1 == null) {
        System.err.println("Aborting... no webapp");
        return;
    }

    // if in any debug mode, turn blurring off
    if (debug)
        webapp1.setAttribute("noblur", true);

    // we set this and its read by JSPHelper within the webapp 
    System.setProperty("muse.container", "jetty");

    // need to copy crossdomain.xml file for
    String tmp = System.getProperty("java.io.tmpdir");
    final URL url = Main.class.getClassLoader().getResource("crossdomain.xml");
    try {
        InputStream is = url.openStream();
        String file = tmp + File.separatorChar + "crossdomain.xml";
        copy_stream_to_file(is, file);
    } catch (Exception e) {
        System.err.println("Aborting..." + e);
        return;
    }
    server = new Server(PORT);
    ResourceHandler resource_handler = new ResourceHandler();
    //        resource_handler.setWelcomeFiles(new String[]{ "index.html" });
    resource_handler.setResourceBase(tmp);

    // set the header buffer size in the connectors, default is a ridiculous 4K, which causes failures any time there is
    // is a large request, such as selecting a few hundred folders. (even for posts!)
    // usually there is only one SocketConnector, so we just put the setHeaderBufferSize in a loop.
    Connector conns[] = server.getConnectors();
    for (Connector conn : conns) {
        int NEW_BUFSIZE = 1000000;
        // out.println ("Connector " + conn + " buffer size is " + conn.getHeaderBufferSize() + " setting to " + NEW_BUFSIZE);
        conn.setHeaderBufferSize(NEW_BUFSIZE);
    }

    BASE_URL = "http://localhost:" + PORT + path;
    String MUSE_CHECK_URL = BASE_URL + "/js/muse.js"; // for quick check of existing muse or successful start up. BASE_URL may take some time to run and may not always be available now that we set dirAllowed to false and public mode does not serve /muse.
    String debugFile = tmp + File.separatorChar + "debug.txt";

    HandlerList hl = new HandlerList();
    if (webapp0 != null)
        hl.setHandlers(new Handler[] { webapp1, webapp0, resource_handler });
    else
        hl.setHandlers(new Handler[] { webapp1, resource_handler });
    out.println("Starting up Muse on the local computer at " + BASE_URL + ", "
            + formatDateLong(new GregorianCalendar()));
    out.println("***For troubleshooting information, see this file: " + debugFile + "***\n");
    out.println("Current directory = " + System.getProperty("user.dir") + ", home directory = "
            + System.getProperty("user.home"));
    out.println("Memory status at the beginning: " + getMemoryStats());
    if (Runtime.getRuntime().maxMemory() / MB < 512)
        aggressiveWarn(
                "You are probably running Muse without enough memory. \nIf you launched Muse from the command line, you can increase memory with an option like java -Xmx1g",
                2000);
    server.setHandler(hl);

    // handle frequent error of user trying to launch another server when its already on
    // server.start() usually takes a few seconds to return
    // after that it takes a few seconds for the webapp to deploy
    // ignore any exceptions along the way and assume not if we can't prove it is alive
    boolean urlAlive = false;
    try {
        urlAlive = isURLAlive(MUSE_CHECK_URL);
    } catch (Exception e) {
        out.println("Exception: e");
        e.printStackTrace(out);
    }

    boolean disableStart = false;
    if (urlAlive) {
        out.println("Oh! Muse is already running at the URL: " + BASE_URL + ", will have to kill it!");
        killRunningServer(BASE_URL);
        Thread.sleep(3000);
        try {
            urlAlive = isURLAlive(MUSE_CHECK_URL);
        } catch (Exception e) {
            out.println("Exception: e");
            e.printStackTrace(out);
        }
        if (!urlAlive)
            out.println("Good. Kill succeeded, will restart");
        else {
            String message = "Previously running Muse still alive despite attempt to kill it, disabling fresh restart!\n";
            message += "If you just want to use the previous instance of Muse, please go to http://localhost:9099/muse\n";
            message += "\nTo kill this instance, please go to your computer's task manager and kill running java or javaw processes.\nThen try launching Muse again.\n";
            aggressiveWarn(message, 2000);
            return;
        }
    }
    //        else
    //          out.println ("Muse not already alive at URL: ..." + URL);

    if (!disableStart) {
        out.println("Starting Muse at URL: ..." + BASE_URL);
        try {
            server.start();
        } catch (BindException be) {
            out.println("port busy, but webapp not alive: " + BASE_URL + "\n" + be);
            throw new RuntimeException("Error: Port in use (Please kill Muse if its already running!)\n" + be);
        }
    }

    //      webapp1.start(); -- not needed
    PrintStream debugOut1 = System.err;
    try {
        File f = new File(debugFile);
        if (f.exists())
            f.delete(); // particular problem on windows :-(
        debugOut1 = new PrintStream(new FileOutputStream(debugFile), false, "UTF-8");
    } catch (IOException ioe) {
        System.err.println("Warning: failed to delete debug file " + debugFile + " : " + ioe);
    }

    final PrintStream debugOut = debugOut1;

    Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() {
        public void run() {
            try {
                server.stop();
                server.destroy();
                debugOut.close();
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }));

    //        InfoFrame frame = new InfoFrame();
    //        frame.doShow();

    boolean success = waitTillPageAlive(MUSE_CHECK_URL, TIMEOUT_SECS);
    //        frame.updateText ("Opening a browser window");

    if (success) {
        // best effort to start shutdown thread
        //           out.println ("Starting Muse shutdown listener at port " + JettyShutdownThread.SHUTDOWN_PORT);

        try {
            int shutdownPort = PORT + 1; // shut down port is arbitrarily set to port + 1. it is ASSUMED to be free. 

            new JettyShutdownThread(server, shutdownPort).start();
            out.println("Listening for Muse shutdown message on port " + shutdownPort);
        } catch (Exception e) {
            out.println(
                    "Unable to start shutdown listener, you will have to stop the server manually using Cmd-Q on Mac OS or kill javaw processes on Windows");
        }

        try {
            setupSystemTrayIcon();
        } catch (Exception e) {
            out.println("Unable to setup system tray icon: " + e);
            e.printStackTrace(out);
        }

        // open browser window
        if (browserOpen) {
            preferredBrowser = null;
            // launch a browser here
            try {

                String link;
                if (System.getProperty("muse.mode.public") != null)
                    link = "http://localhost:" + PORT + "/muse/archives/";
                else
                    link = "http://localhost:" + PORT + "/muse/index.jsp";

                if (searchMode) {
                    String u = "http://localhost:" + PORT + "/muse/search";
                    out.println("Launching URL in browser: " + u);
                    link += "?mode=search";
                } else if (amuseMode) {
                    String u = "http://localhost:" + PORT + "/muse/amuse.jsp";
                    out.println("Launching URL in browser: " + u);
                    link = u;
                } else if (startPage != null) {
                    // startPage has to be absolute
                    link = "http://localhost:" + PORT + "/muse/" + startPage;
                }

                if (baseDir != null)
                    link = link + "?cacheDir=" + baseDir; // typically this is used when starting from command line. note: still using name, cacheDir

                out.println("Launching URL in browser: " + link);
                launchBrowser(link);

            } catch (Exception e) {
                out.println(
                        "Warning: Unable to launch browser due to exception (use the -n option to prevent Muse from trying to launch a browser):");
                e.printStackTrace(out);
            }
        }

        if (!cmd.hasOption("no-shutdown")) {
            // arrange to kill Muse after a period of time, we don't want the server to run forever

            // i clearly have too much time on my hands right now...
            long secs = KILL_AFTER_MILLIS / 1000;
            long hh = secs / 3600;
            long mm = (secs % 3600) / 60;
            long ss = secs % (60);
            out.print("Muse will shut down automatically after ");
            if (hh != 0)
                out.print(hh + " hours ");
            if (mm != 0 || (hh != 0 && ss != 0))
                out.print(mm + " minutes");
            if (ss != 0)
                out.print(ss + " seconds");
            out.println();

            Timer timer = new Timer();
            TimerTask tt = new ShutdownTimerTask();
            timer.schedule(tt, KILL_AFTER_MILLIS);
        }
    } else {
        out.println("\n\n\nSORRY!!! UNABLE TO DEPLOY WEBAPP, EXITING\n\n\n");
        //          frame.updateText("Sorry, looks like we are having trouble starting the jetty server\n");
    }

    savedSystemOut = out;
    savedSystemErr = System.err;
    System.setOut(debugOut);
    System.setErr(debugOut);
}