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

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

Introduction

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

Prototype

BasicParser

Source Link

Usage

From source file:com.spectralogic.ds3contractcomparator.cli.CLI.java

@SuppressWarnings("deprecation")
private Arguments processArgs(final String[] args) throws ParseException {
    final CommandLineParser parser = new BasicParser();
    final CommandLine cmd = parser.parse(options, args);

    final String oldSpec = cmd.getOptionValue("o");
    final String newSpec = cmd.getOptionValue("n");
    final String outFile = cmd.getOptionValue("d");
    final boolean help = cmd.hasOption("h");
    final boolean properties = cmd.hasOption("properties");
    final boolean annotations = cmd.hasOption("annotations");
    final PrinterType printerType = processPrinterType(cmd);

    final Arguments arguments = new Arguments(oldSpec, newSpec, outFile, help, properties, annotations,
            printerType);//ww w  .ja  v a 2s  .c  o  m

    validateArguments(arguments);

    return arguments;
}

From source file:fr.smartcontext.yatte.context.cli.CLIBasedContextInitializer.java

/**
 * @param parameters/*  w  w  w .  j  a v  a2  s . com*/
 * @param options
 * @return
 * @throws ParseException
 */
protected CommandLine getCmdLine(List<String> parameters, Options options) throws ParseException {
    String[] arguments = parameters.toArray(new String[] {});
    CommandLineParser parser = new BasicParser();
    CommandLine cmdLine = parser.parse(options, arguments);
    return cmdLine;
}

From source file:com.adobe.aem.demomachine.communities.Loader.java

public static void main(String[] args) {

    String hostname = null;//from  ww w.  j  av  a  2 s . co  m
    String port = null;
    String altport = null;
    String csvfile = null;
    String analytics = null;
    String adminPassword = "admin";
    boolean reset = false;
    boolean configure = false;
    boolean minimize = false;
    boolean noenablement = true;
    int maxretries = MAXRETRIES;

    // Command line options for this tool
    Options options = new Options();
    options.addOption("h", true, "Hostname");
    options.addOption("p", true, "Port");
    options.addOption("a", true, "Alternate Port");
    options.addOption("f", true, "CSV file");
    options.addOption("r", false, "Reset");
    options.addOption("u", true, "Admin Password");
    options.addOption("c", false, "Configure");
    options.addOption("m", false, "Minimize");
    options.addOption("e", false, "No Enablement");
    options.addOption("s", true, "Analytics Endpoint");
    options.addOption("t", false, "Analytics");
    options.addOption("w", false, "Retry");
    CommandLineParser parser = new BasicParser();
    try {
        CommandLine cmd = parser.parse(options, args);

        if (cmd.hasOption("h")) {
            hostname = cmd.getOptionValue("h");
        }

        if (cmd.hasOption("p")) {
            port = cmd.getOptionValue("p");
        }

        if (cmd.hasOption("a")) {
            altport = cmd.getOptionValue("a");
        }

        if (cmd.hasOption("f")) {
            csvfile = cmd.getOptionValue("f");
        }

        if (cmd.hasOption("u")) {
            adminPassword = cmd.getOptionValue("u");
        }

        if (cmd.hasOption("t")) {
            if (cmd.hasOption("s")) {
                analytics = cmd.getOptionValue("s");
            }
        }

        if (cmd.hasOption("r")) {
            reset = true;
        }

        if (cmd.hasOption("w")) {
            maxretries = Integer.parseInt(cmd.getOptionValue("w"));
        }

        if (cmd.hasOption("c")) {
            configure = true;
        }

        if (cmd.hasOption("m")) {
            minimize = true;
        }

        if (cmd.hasOption("e")) {
            noenablement = false;
        }

        if (csvfile == null || port == null || hostname == null) {
            System.out.println(
                    "Request parameters: -h hostname -p port -a alternateport -u adminPassword -f path_to_CSV_file -r (true|false, delete content before import) -c (true|false, post additional properties)");
            System.exit(-1);
        }

    } catch (ParseException ex) {

        logger.error(ex.getMessage());

    }

    logger.debug("AEM Demo Loader: Processing file " + csvfile);

    try {

        // Reading and processing the CSV file, stand alone or as part of a ZIP file
        if (csvfile != null && csvfile.toLowerCase().endsWith(".zip")) {

            ZipFile zipFile = new ZipFile(csvfile);
            ZipInputStream stream = new ZipInputStream(new FileInputStream(csvfile));
            ZipEntry zipEntry;
            while ((zipEntry = stream.getNextEntry()) != null) {
                if (!zipEntry.isDirectory() && zipEntry.getName().toLowerCase().endsWith(".csv")) {

                    InputStream is = zipFile.getInputStream(zipEntry);
                    BufferedReader in = new BufferedReader(new InputStreamReader(is, "UTF-8"));
                    processLoading(null, in, hostname, port, altport, adminPassword, analytics, reset,
                            configure, minimize, noenablement, csvfile, maxretries);

                }
            }

            try {
                stream.close();
                zipFile.close();
            } catch (IOException ioex) {
                //omitted.
            }

        } else if (csvfile.toLowerCase().endsWith(".csv")) {

            Reader in = new FileReader(csvfile);
            processLoading(null, in, hostname, port, altport, adminPassword, analytics, reset, configure,
                    minimize, noenablement, csvfile, maxretries);

        }

    } catch (IOException e) {

        logger.error(e.getMessage());

    }

}

From source file:com.asakusafw.testdata.generator.excel.Main.java

static int start(String... args) {
    assert args != null;
    GenerateTask task;/*from  w w w.  ja v a 2  s  . c  o m*/
    try {
        CommandLineParser parser = new BasicParser();
        CommandLine cmd = parser.parse(OPTIONS, args);
        TemplateGenerator generator = getGenerator(cmd);
        DmdlSourceRepository repository = getRepository(cmd);
        ClassLoader classLoader = getClassLoader(cmd);
        task = new GenerateTask(generator, repository, classLoader);
    } catch (Exception e) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.setWidth(Integer.MAX_VALUE);
        formatter.printHelp(MessageFormat.format("java -classpath ... {0}", //$NON-NLS-1$
                Main.class.getName()), OPTIONS, true);
        System.out.printf(Messages.getString("Main.helpFormatHead"), OPT_FORMAT.getOpt()); //$NON-NLS-1$
        System.out.printf(" %8s - %s%n", WorkbookFormat.DATA, //$NON-NLS-1$
                Messages.getString("Main.helpFormatData")); //$NON-NLS-1$
        System.out.printf(" %8s - %s%n", WorkbookFormat.RULE, //$NON-NLS-1$
                Messages.getString("Main.helpFormatRule")); //$NON-NLS-1$
        System.out.printf(" %8s - %s%n", WorkbookFormat.INOUT, //$NON-NLS-1$
                Messages.getString("Main.helpFormatInout")); //$NON-NLS-1$
        System.out.printf(" %8s - %s%n", WorkbookFormat.INSPECT, //$NON-NLS-1$
                Messages.getString("Main.helpFormatInspect")); //$NON-NLS-1$
        System.out.printf(" %8s - %s%n", WorkbookFormat.ALL, //$NON-NLS-1$
                Messages.getString("Main.helpFormatAll")); //$NON-NLS-1$
        System.out.printf(" %8s - %s%n", WorkbookFormat.DATAX, //$NON-NLS-1$
                Messages.getString("Main.helpFormatDataX")); //$NON-NLS-1$
        System.out.printf(" %8s - %s%n", WorkbookFormat.RULEX, //$NON-NLS-1$
                Messages.getString("Main.helpFormatRuleX")); //$NON-NLS-1$
        System.out.printf(" %8s - %s%n", WorkbookFormat.INOUTX, //$NON-NLS-1$
                Messages.getString("Main.helpFormatInoutX")); //$NON-NLS-1$
        System.out.printf(" %8s - %s%n", WorkbookFormat.INSPECTX, //$NON-NLS-1$
                Messages.getString("Main.helpFormatInspectX")); //$NON-NLS-1$
        System.out.printf(" %8s - %s%n", WorkbookFormat.ALLX, //$NON-NLS-1$
                Messages.getString("Main.helpFormatAllX")); //$NON-NLS-1$
        e.printStackTrace(System.out);
        return 1;
    }
    try {
        task.process();
    } catch (IOException e) {
        e.printStackTrace(System.out);
        return 1;
    }
    return 0;
}

From source file:com.progressiveaccess.cmlspeech.base.Cli.java

/**
 * Parses the command line arguments.//from ww w  .j a  v a  2  s  .  com
 *
 * @param args
 *          The command line argument list.
 */
private static void parse(final String[] args) {
    final Options options = new Options();
    // Basic Options
    options.addOption("help", false, "Print this message");
    options.addOption("d", "debug", false, "Debug mode");
    options.addOption("v", "verbose", false, "Verbose mode");
    // File Handling
    // options.addOption("i", "input", true, "Input File");
    options.addOption("o", "output", true, "Output file addition");
    options.addOption("l", "log", true, "Log File");
    options.addOption("x", "error", true, "Debug File");
    // Processing Options
    options.addOption("c", "cml", false, "Also write a CML file without annotations: adds -simple to name");
    options.addOption("a", "ann", false, "Include annotations in CML output");
    options.addOption("ao", "annonly", false, "Annotations only output. Omits the original CML output");
    options.addOption("r", "descr", false, "Include speech descriptions in CML output");
    options.addOption("nonih", "nonih", false, "Do not use the NIH naming service");
    options.addOption("s", "subrings", false, "Do not compute subrings");
    options.addOption("sssr", "sssr", false, "Do not use SSSR method for sub-ring computation");
    options.addOption("vis", "visualize", false, "Visualize the abstraction graph");
    options.addOption("vr", "vis_recursive", false, "Visualize sub graphs recursively");
    options.addOption("vb", "vis_bw", false, "Visualize graph black and white; default colour");
    options.addOption("vs", "vis_short", false, "Visualize bonds short");
    options.addOption("sf", "structuralformula", false, "Print the structural formula");
    options.addOption("sub", "subscript", false, "Use subscripts with structural formula");
    options.addOption("m", "molcom", true, "Comparison heuristics for molecules given as a comma"
            + "separated list. Currently available heuristics:" + " type, weight, size");

    final CommandLineParser parser = new BasicParser();
    try {
        Cli.cl = parser.parse(options, args);
    } catch (final ParseException e) {
        usage(options, 1);
    }
    if (Cli.cl.hasOption("help")) {
        usage(options, 0);
    }

    for (int i = 0; i < Cli.cl.getArgList().size(); i++) {
        final String fileName = Cli.cl.getArgList().get(i).toString();
        final File file = new File(fileName);
        if (file.exists() && !file.isDirectory()) {
            Cli.files.add(fileName);
        } else {
            Cli.warning(fileName);
        }
    }

}

From source file:com.twitter.distributedlog.service.MonitorServiceApp.java

private void run() {
    try {//from  ww w  .j a  va2s . co m
        logger.info("Running monitor service.");
        BasicParser parser = new BasicParser();
        CommandLine cmdline = parser.parse(options, args);
        runCmd(cmdline);
    } catch (ParseException pe) {
        printUsage();
        Runtime.getRuntime().exit(-1);
    } catch (IOException ie) {
        logger.error("Failed to start monitor service : ", ie);
        Runtime.getRuntime().exit(-1);
    }
}

From source file:it.infodreams.syncpath.commands.Commander.java

public void parseArgs(String[] args) {
    CommandLineParser parser = new BasicParser();
    Packager packager = new Packager();

    try {/*  w  w w.  j a v a2s. c  om*/
        CommandLine line = parser.parse(options, args);

        if (line.hasOption("split-size")) {
            long size = 0;

            if (line.hasOption("split-size")) {
                size = Long.parseLong(line.getOptionValue("split-size"));
            } else {
                ErrorManager.getInstance().error("Value expected for parameter 'split-size'",
                        ErrorLevel.SEVERE);
            }

            packager.setPackageSplitSize(size);
        }

        if (line.hasOption("verbose")) {
            LogManager.getInstance().setVerbosityLevel(LogManager.LOG_LEVEL_2);
        }

        if (line.hasOption("help") || args.length == 0) {
            HelpFormatter formatter = new HelpFormatter();
            formatter.printHelp("SyncPath", options);
        } else if (line.hasOption("scan")) {

            String path = null;
            String reportFileName = null;

            if (line.hasOption("source-path")) {
                path = line.getOptionValue("source-path");
            } else {
                ErrorManager.getInstance().error(
                        "Parameter '--scan' needs a source path to perform its operation", ErrorLevel.SEVERE);
            }

            if (line.hasOption("report")) {
                reportFileName = line.getOptionValue("report");
            } else {
                ErrorManager.getInstance().error(
                        "Parameter '--scan' needs a report filename to perform its operation",
                        ErrorLevel.SEVERE);
            }

            packager.scanPath(path, reportFileName);

        } else if (line.hasOption("pack")) {

            String sourcePath = null;
            String destPath = null;
            String reportFileName = null;

            if (line.hasOption("source-path")) {
                sourcePath = line.getOptionValue("source-path");
            } else {
                ErrorManager.getInstance().error(
                        "Parameter '--pack' needs a source path to perform its operation", ErrorLevel.SEVERE);
            }

            if (line.hasOption("dest-path")) {
                destPath = line.getOptionValue("dest-path");
            } else {
                ErrorManager.getInstance().error(
                        "Parameter '--pack' needs a source path to perform its operation", ErrorLevel.SEVERE);
            }

            if (line.hasOption("report")) {
                reportFileName = line.getOptionValue("report");
            } else {
                ErrorManager.getInstance().error(
                        "Parameter '--pack' needs a report filename to perform its operation",
                        ErrorLevel.SEVERE);
            }

            Report report;

            try {
                report = Report.loadFromFile(reportFileName);
                packager.packFiles(report, sourcePath, destPath);
            } catch (FileNotFoundException ex) {
                ErrorManager.getInstance().error(ex.getMessage(), ErrorLevel.SEVERE);
            }

        } else if (line.hasOption("unpack")) {

        }
    } catch (ParseException ex) {
        ErrorManager.getInstance().error(ex.getMessage(), ErrorLevel.SEVERE);
    }
}

From source file:br.usp.poli.lta.cereda.macro.util.CLIParser.java

/**
 * Realiza a anlise dos argumentos de linha de comando e retorna um par
 * contendo o texto a ser expandido e o arquivo de sada.
 * @return Um par contendo o texto a ser expandido e o arquivo de sada.
 * @throws IOException Um dos arquivos de entrada no existe.
 *//*from   w  w  w  .  j av  a2s.co m*/
public Pair<String, File> parse() throws IOException {

    // opo de entrada
    Option input = OptionBuilder.withLongOpt("input").hasArgs().withArgName("lista de arquivos")
            .withDescription("arquivos de entrada").create("i");

    // opo de sada
    Option output = OptionBuilder.withLongOpt("output").hasArg().withArgName("arquivo")
            .withDescription("arquivo de sada").create("o");

    // opo do editor embutido
    Option ui = OptionBuilder.withLongOpt("editor").withDescription("editor grfico").create("e");

    Options options = new Options();
    options.addOption(input);
    options.addOption(output);
    options.addOption(ui);

    try {

        // parsing dos argumentos
        Parser parser = new BasicParser();
        CommandLine line = parser.parse(options, arguments);

        // verifica se  uma chamada ao editor e retorna em caso positivo
        if (line.hasOption("e")) {
            editor = true;
            return null;
        }

        // se no  uma chamada ao editor de macros,  necessrio verificar
        // se existe um arquivo de entrada
        if (!line.hasOption("i")) {
            throw new ParseException("");
        }

        // existem argumentos restantes, o que representa situao de erro
        if (!line.getArgList().isEmpty()) {
            throw new ParseException("");
        }

        String text = "";
        File out = line.hasOption("output") ? new File(line.getOptionValue("output")) : null;

        if (out == null) {
            logger.info("A sada ser gerada no terminal.");
        } else {
            logger.info("A sada ser gerada no arquivo '{}'.", out.getName());
        }

        // faz a leitura de todos os arquivos e concatena seu contedo em
        // uma varivel
        logger.info("Iniciando a leitura dos arquivos de entrada.");
        String[] files = line.getOptionValues("input");
        for (String file : files) {
            logger.info("Lendo arquivo '{}'.", file);
            text = text.concat(FileUtils.readFileToString(new File(file), Charset.forName("UTF-8")));
        }

        // retorna o par da varivel contendo o texto de todos os arquivos
        // e a referncia ao arquivo de sada (podendo este ser nulo)
        return new Pair<>(text, out);

    } catch (ParseException exception) {

        // imprime a ajuda
        HelpFormatter help = new HelpFormatter();
        help.printHelp("expander ( --editor | --input <lista de arquivos>" + " [ --output <arquivo> ] )",
                options);
    }

    // retorna um valor invlido indicando para no prosseguir com o
    // processo de expanso
    return null;

}

From source file:com.lcdfx.pipoint.PiPoint.java

public PiPoint(String[] args) {

    this.addWindowListener(new WindowAdapter() {
        @Override//  w  w w . j a  v a2s .com
        public void windowClosing(WindowEvent ev) {
            shutDown();
        }
    });

    // add logging
    logger = Logger.getLogger(this.getClass().getName());
    logger.log(Level.INFO,
            "PiPoint version " + PiPoint.class.getPackage().getImplementationVersion() + " running under "
                    + System.getProperty("java.vm.name") + " v" + System.getProperty("java.vm.version"));

    // get command line options
    CommandLineParser parser = new BasicParser();
    Map<String, String> cmdOptions = new HashMap<String, String>();
    Options options = new Options();
    options.addOption(new Option("f", "fullscreen", false, "fullscreen mode (no cursor)"));
    CommandLine cmd = null;
    try {
        cmd = parser.parse(options, args);
        for (Option option : cmd.getOptions()) {
            cmdOptions.put(option.getOpt(), option.getValue());
        }
    } catch (ParseException e) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("java -jar pipoint.jar", options);
        System.exit(0);
    }

    if (cmd.hasOption("f")) {
        setUndecorated(true);
        BufferedImage cursorImg = new BufferedImage(16, 16, BufferedImage.TYPE_INT_ARGB);
        Cursor blankCursor = Toolkit.getDefaultToolkit().createCustomCursor(cursorImg, new Point(0, 0),
                "blank cursor");
        getContentPane().setCursor(blankCursor);
    }

    // instantiate the RendererManager
    mgr = new DlnaRendererManager(this);
    mgr.refreshDevices();

    nowPlayingPanel = new NowPlayingPanel(this);
    mgr.getRenderer().addListener(nowPlayingPanel);
    devicePanel = new DevicePanel(this);

    this.getContentPane().setPreferredSize(new Dimension(DISPLAY_WIDTH, DISPLAY_HEIGHT));
    this.getContentPane().add(devicePanel);
}

From source file:gov.nih.nci.caintegrator.heatmap.invokeCBS2HeatMap.java

public static void ReadOptions(String[] args, HeatMapArgs hma) {
    try {//w ww.  j  a  va 2s  .  c om
        Options opt = new Options();

        opt.addOption("h", false, "Print help for this application");
        opt.addOption("big_bins", true, "name of big bin definition file");
        opt.addOption("small_bins", true, "name of small bin definition file");
        opt.addOption("seg", true, "name of file containing segmented copy number data");
        opt.addOption("samples", true, "name of file specifying samples to include");
        opt.addOption("genomeout", true, "name of genome matrix output file");
        opt.addOption("geneout", true, "name of gene matrix output file");
        opt.addOption("title", true, "title for output heatmap");
        opt.addOption("genes", true, "name of RefSeq gene flat file");
        opt.addOption("gender", true, "name of file mapping patients to gender");
        opt.addOption("protocol", true, "matched or unmatched");
        opt.addOption("scale", true,
                "comma-separated list of real positive numbers for interval upperbounds (default is '0.5,1.5,2.5,3.5,4.5')");
        opt.addOption("minseg", true, "minimum segment length to consider (default = 500)");
        opt.addOption("platform", true, "name of platform");
        opt.addOption("submitter", true, "name of center that submitted the data");
        opt.addOption("contact", true, "contact: name of NCI contact person for this heatmap");
        opt.addOption("cnv_track", true, "name of file with cnv track info");
        opt.addOption("project", true, "project: name of project");
        opt.addOption("base", true, "assumed base (can be float) for log ratio values (defaults to 2)");

        BasicParser parser = new BasicParser();
        CommandLine cl = parser.parse(opt, args);

        if (cl.hasOption("h")) {
            HelpFormatter f = new HelpFormatter();
            f.printHelp("OptionsTip", opt);
            System.exit(0);
        } else {
            if (cl.hasOption("small_bins")) {
                hma.setSmallBinFile(cl.getOptionValue("small_bins"));
            }
            if (cl.hasOption("big_bins")) {
                hma.setBigBinFile(cl.getOptionValue("big_bins"));
            }
            if (cl.hasOption("seg")) {
                hma.setSegmentFile(cl.getOptionValue("seg"));
            }
            if (cl.hasOption("samples")) {
                hma.setSampleFile(cl.getOptionValue("samples"));
            }
            if (cl.hasOption("genomeout")) {
                hma.setGenomeOutFile(cl.getOptionValue("genomeout"));
            }
            if (cl.hasOption("geneout")) {
                hma.setGeneOutFile(cl.getOptionValue("geneout"));
            }
            if (cl.hasOption("title")) {
                hma.setTitle(cl.getOptionValue("title"));
            }
            if (cl.hasOption("genes")) {
                hma.setRefGenesFile(cl.getOptionValue("genes"));
            }
            if (cl.hasOption("gender")) {
                hma.setGenderFile(cl.getOptionValue("gender"));
            }
            if (cl.hasOption("protocol")) {
                hma.setProtocol(cl.getOptionValue("protocol"));
            }
            if (cl.hasOption("scale")) {
                hma.setScale(cl.getOptionValue("scale"));
            }
            if (cl.hasOption("minseg")) {
                hma.setMinSegLength(Integer.parseInt(cl.getOptionValue("minseg")));
            }
            if (cl.hasOption("platform")) {
                hma.setPlatform(cl.getOptionValue("platform"));
            }
            if (cl.hasOption("submitter")) {
                hma.setSubmitter(cl.getOptionValue("submitter"));
            }
            if (cl.hasOption("contact")) {
                hma.setContact(cl.getOptionValue("contact"));
            }
            if (cl.hasOption("cnv_track")) {
                hma.setCnvTrack(cl.getOptionValue("cnv_track"));
            }
            if (cl.hasOption("project")) {
                hma.setProject(cl.getOptionValue("project"));
            }
            if (cl.hasOption("base")) {
                hma.setBase(Integer.parseInt(cl.getOptionValue("base")));
            }
        }
    } catch (ParseException e) {
        e.printStackTrace();
    }
}