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

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

Introduction

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

Prototype

public ParseException(String message) 

Source Link

Document

Construct a new ParseException with the specified detail message.

Usage

From source file:it.crs4.seal.common.SealToolParser.java

/**
 * Parses command line./*  w w w.j  a  v a2 s  .com*/
 *
 * Override this method to implement additional command line options,
 * but do make sure you call this method to parse the default options.
 */
protected CommandLine parseOptions(Configuration conf, String[] args) throws ParseException, IOException {
    myconf = conf;

    setDefaultProperties(conf);

    // load settings from configuration file
    // first, parse the command line (in getRcFile) looking for an option overriding the default seal configuration file
    File configFile = getRcFile(args);
    if (configFile != null)
        loadConfig(conf, configFile);

    // now parse the entire command line using the default hadoop parser.  Now
    // the user can override properties specified in the config file with properties
    // specified on the command line.
    CommandLine line = new GenericOptionsParser(conf, options, args).getCommandLine();
    if (line == null)
        throw new ParseException("Error parsing command line"); // getCommandLine returns an null if there was a parsing error

    ////////////////////// input/output formats //////////////////////
    // set the configuration property.  Then, we'll check the property
    // to ensure it has a valid value, regardless of whether we just set it,
    // so that the check will also be valid if the property is set directly.
    if (line.hasOption(opt_inputFormat.getOpt()))
        myconf.set(INPUT_FORMAT_CONF, line.getOptionValue(opt_inputFormat.getOpt()));

    validateIOFormat(INPUT_FORMAT_CONF, acceptedInputFormats);

    if (line.hasOption(opt_outputFormat.getOpt()))
        myconf.set(OUTPUT_FORMAT_CONF, line.getOptionValue(opt_outputFormat.getOpt()));

    validateIOFormat(OUTPUT_FORMAT_CONF, acceptedOutputFormats);

    if (conf.get(INPUT_FORMAT_ENCODING) != null) {
        String value = conf.get(INPUT_FORMAT_ENCODING);
        if (value.equals("sanger") || value.equals("illumina"))
            conf.set(org.seqdoop.hadoop_bam.FormatConstants.CONF_INPUT_BASE_QUALITY_ENCODING, value);
        else
            throw new ParseException("Invalid " + INPUT_FORMAT_ENCODING + ". Expected 'sanger' or 'illumina'");
    }

    /////////////////////// output compression /////////////////////
    if (line.hasOption(opt_compressOutput.getOpt())) {
        myconf.setBoolean("mapred.output.compress", true);
        String codec = line.getOptionValue(opt_compressOutput.getOpt());
        if (codec != null) {
            String codecClass = "org.apache.hadoop.io.compress.GzipCodec"; // default
            if ("auto".equalsIgnoreCase(codec) || "gzip".equalsIgnoreCase(codec)) {
                // pass.  Already set
            } else if ("bzip2".equalsIgnoreCase(codec))
                codecClass = "org.apache.hadoop.io.compress.BZip2Codec";
            else if ("snappy".equalsIgnoreCase(codec))
                codecClass = "org.apache.hadoop.io.compress.SnappyCodec";
            else {
                throw new ParseException("Unknown codec " + codec
                        + ". Valid values are gzip, bzip2, snappy and auto.\n"
                        + "If you want to use an unsupported codec pass 'auto' and set the property mapred.output.compression.codec directly");
            }

            myconf.set("mapred.output.compression.codec", codecClass);
        }
    }

    ////////////////////// number of reducers //////////////////////
    if (line.hasOption(opt_nReduceTasks.getOpt())) {
        String rString = line.getOptionValue(opt_nReduceTasks.getOpt());
        try {
            int r = Integer.parseInt(rString);
            if (r >= minReduceTasks)
                nReduceTasks = r;
            else
                throw new ParseException("Number of reducers must be greater than or equal to " + minReduceTasks
                        + " (got " + rString + ")");
        } catch (NumberFormatException e) {
            throw new ParseException("Invalid number of reduce tasks '" + rString + "'");
        }
    }

    ////////////////////// positional arguments //////////////////////
    String[] otherArgs = line.getArgs();
    if (otherArgs.length < 2) // require at least two:  one input and one output
        throw new ParseException("You must provide input and output paths");
    else {
        //
        FileSystem fs;
        for (int i = 0; i < otherArgs.length - 1; ++i) {
            Path p = new Path(otherArgs[i]);
            fs = p.getFileSystem(conf);
            p = p.makeQualified(fs);
            FileStatus[] files = fs.globStatus(p);
            if (files != null && files.length > 0) {
                for (FileStatus status : files)
                    inputs.add(status.getPath());
            } else
                throw new ParseException("Input path " + p.toString() + " doesn't exist");
        }
        // now the last one, should be the output path
        outputDir = new Path(otherArgs[otherArgs.length - 1]);
        fs = outputDir.getFileSystem(conf);
        outputDir = outputDir.makeQualified(fs);
        if (fs.exists(outputDir))
            throw new ParseException(
                    "Output path " + outputDir.toString() + " already exists.  Won't overwrite");
    }

    return line;
}

From source file:com.net2plan.cli.tools.CLITrafficDesign.java

@Override
public void executeFromCommandLine(String[] args) throws ParseException {
    long init = System.nanoTime();

    final CommandLineParser parser = new CommandLineParser();
    final CommandLine cli = parser.parse(OPTIONS, args);

    int numNodes;
    NetPlan netPlan;/*from   w  w  w.  j a  va  2 s .co m*/

    if (cli.hasOption("num-nodes") && cli.hasOption("input-file"))
        throw new ParseException("'num-nodes' and 'input-file' are mutually exclusive");

    if (cli.hasOption("num-nodes")) {
        numNodes = ((Number) cli.getParsedOptionValue("num-nodes")).intValue();
        if (numNodes < 2)
            throw new Net2PlanException("Traffic matrix requires at least 2 nodes");

        netPlan = new NetPlan();
        for (int n = 0; n < numNodes; n++)
            netPlan.addNode(0, 0, null, null);
    } else {
        netPlan = new NetPlan((File) cli.getParsedOptionValue("input-file"));
        numNodes = netPlan.getNumberOfNodes();
    }

    int numMatrices = 1;
    String trafficPattern = null;

    DoubleMatrix2D[] trafficMatrices;
    if (cli.hasOption("variation-pattern")) {
        if (!cli.hasOption("num-matrices"))
            throw new Net2PlanException("'num-matrices' parameters must be specified");

        numMatrices = ((Number) cli.getParsedOptionValue("num-matrices")).intValue();
        if (numMatrices < 1)
            throw new Net2PlanException("Number of traffic matrices must be positive");

        DoubleMatrix2D trafficMatrix = netPlan.getMatrixNode2NodeOfferedTraffic();
        List<DoubleMatrix2D> newMatrices;
        String variationPattern = (String) cli.getParsedOptionValue("variation-pattern");
        switch (variationPattern) {
        case "cagr": {
            double cagr = ((Number) cli.getParsedOptionValue("variation-pattern-cagr")).doubleValue();
            if (cagr <= 0)
                throw new Net2PlanException("Compound annual growth rate must be greater than zero");
            newMatrices = TrafficMatrixGenerationModels.computeMatricesCAGR(trafficMatrix, cagr, numMatrices);

            break;
        }

        case "randomGaussian": {
            double cv = ((Number) cli.getParsedOptionValue("variation-pattern-cv")).doubleValue();
            double maxRelativeVariation = ((Number) cli
                    .getParsedOptionValue("variation-pattern-maxRelativeVariation")).doubleValue();
            if (cv <= 0)
                throw new Net2PlanException("Coefficient of variation must be greater than zero");
            if (maxRelativeVariation <= 0)
                throw new Net2PlanException("Maximum relative variation must be greater than zero");
            newMatrices = TrafficMatrixGenerationModels.computeMatricesRandomGaussianVariation(trafficMatrix,
                    cv, maxRelativeVariation, numMatrices);

            break;
        }

        case "randomUniform": {
            double maxRelativeVariation = ((Number) cli
                    .getParsedOptionValue("variation-pattern-maxRelativeVariation")).doubleValue();
            if (maxRelativeVariation <= 0)
                throw new Net2PlanException("Maximum relative variation must be greater than zero");
            newMatrices = TrafficMatrixGenerationModels.computeMatricesRandomUniformVariation(trafficMatrix,
                    maxRelativeVariation, numMatrices);

            break;
        }

        default:
            throw new RuntimeException("Bad - Unknown variation pattern '" + variationPattern + "'");
        }

        trafficMatrices = new DoubleMatrix2D[numMatrices];
        int i = 0;
        for (DoubleMatrix2D trafficMatrix1 : newMatrices)
            trafficMatrices[i++] = trafficMatrix1;
    } else {
        if (cli.hasOption("traffic-pattern")) {
            trafficPattern = cli.getOptionValue("traffic-pattern");
            if (!TRAFFIC_PATTERNS.containsKey(trafficPattern))
                throw new Net2PlanException("Unknown traffic pattern");

            if (cli.hasOption("num-matrices")) {
                numMatrices = ((Number) cli.getParsedOptionValue("num-matrices")).intValue();
                if (numMatrices < 1)
                    throw new Net2PlanException("Number of traffic matrices must be positive");
            }
        }

        trafficMatrices = new DoubleMatrix2D[numMatrices];
        if (trafficPattern != null) {
            switch (trafficPattern) {
            case "uniform-random-10":
                for (int tmId = 0; tmId < numMatrices; tmId++)
                    trafficMatrices[tmId] = TrafficMatrixGenerationModels.uniformRandom(numNodes, 0, 10);
                break;

            case "uniform-random-100":
                for (int tmId = 0; tmId < numMatrices; tmId++)
                    trafficMatrices[tmId] = TrafficMatrixGenerationModels.uniformRandom(numNodes, 0, 100);
                break;

            case "uniform-random-bimodal-50-50":
                for (int tmId = 0; tmId < numMatrices; tmId++)
                    trafficMatrices[tmId] = TrafficMatrixGenerationModels.bimodalUniformRandom(numNodes, 0.5, 0,
                            100, 0, 10);
                break;

            case "uniform-random-bimodal-25-75":
                for (int tmId = 0; tmId < numMatrices; tmId++)
                    trafficMatrices[tmId] = TrafficMatrixGenerationModels.bimodalUniformRandom(numNodes, 0.25,
                            0, 100, 0, 10);
                break;

            case "population-distance-model":
                double randomFactor = 0;
                double populationOffset = 0;
                double populationPower = 1;
                double distanceOffset = 0;
                double distancePower = 1;
                boolean normalizePopulation = true;
                boolean normalizeDistance = true;

                if (cli.hasOption("random-factor"))
                    randomFactor = ((Number) cli.getParsedOptionValue("random-factor")).doubleValue();
                if (cli.hasOption("population-offset"))
                    populationOffset = ((Number) cli.getParsedOptionValue("population-offset")).doubleValue();
                if (cli.hasOption("population-power"))
                    populationPower = ((Number) cli.getParsedOptionValue("population-power")).doubleValue();
                if (cli.hasOption("distance-offset"))
                    distanceOffset = ((Number) cli.getParsedOptionValue("distance-offset")).doubleValue();
                if (cli.hasOption("distance-power"))
                    distancePower = ((Number) cli.getParsedOptionValue("distance-power")).doubleValue();
                if (cli.hasOption("normalize-population"))
                    normalizePopulation = Boolean.parseBoolean(cli.getOptionValue("normalize-population"));
                if (cli.hasOption("normalize-distance"))
                    normalizeDistance = Boolean.parseBoolean(cli.getOptionValue("normalize-distance"));

                if (!cli.hasOption("level-matrix-file"))
                    throw new Net2PlanException("The level-matrix file is required");
                DoubleMatrix2D levelMatrix = DoubleUtils
                        .read2DMatrixFromFile((File) cli.getParsedOptionValue("level-matrix-file"));

                DoubleMatrix2D distanceMatrix = netPlan.getMatrixNode2NodeEuclideanDistance();
                int[] populationVector = StringUtils
                        .toIntArray(netPlan.getAttributes(netPlan.getNodes(), "population").values(), 0);
                int[] levelVector = StringUtils
                        .toIntArray(netPlan.getAttributes(netPlan.getNodes(), "level").values(), 1);

                for (int tmId = 0; tmId < numMatrices; tmId++)
                    trafficMatrices[tmId] = TrafficMatrixGenerationModels.populationDistanceModel(
                            distanceMatrix, populationVector, levelVector, levelMatrix, randomFactor,
                            populationOffset, populationPower, distanceOffset, distancePower,
                            normalizePopulation, normalizeDistance);

                break;

            case "gravity-model":
                if (cli.hasOption("gravity-model-file")) {
                    File gravityModelFile = (File) cli.getParsedOptionValue("gravity-model-file");
                    DoubleMatrix2D gravityModelMatrix = DoubleUtils.read2DMatrixFromFile(gravityModelFile);

                    if (gravityModelMatrix.rows() != numNodes || gravityModelMatrix.columns() != 2)
                        throw new Net2PlanException(
                                "'gravity-model-file' requires " + numNodes + " rows and two columns");

                    numMatrices = 1;
                    trafficMatrices[0] = TrafficMatrixGenerationModels.gravityModel(
                            gravityModelMatrix.viewColumn(0).toArray(),
                            gravityModelMatrix.viewColumn(1).toArray());
                } else {
                    throw new Net2PlanException("Parameter 'gravity-model-file' should be specified");
                }

                break;

            default:
                throw new RuntimeException("Bad - Unknown traffic pattern '" + trafficPattern + "'");
            }
        } else {
            trafficMatrices[0] = netPlan.getMatrixNode2NodeOfferedTraffic();
        }

        if (cli.hasOption("normalization-pattern")) {
            String normalizationPattern = (String) cli.getParsedOptionValue("normalization-pattern");
            switch (normalizationPattern) {
            case "total-normalization":
            case "row-normalization":
            case "column-normalization":
                if (cli.hasOption("normalization-pattern-file")) {
                    double[] normalizationPatternVector;
                    int patternId;

                    File normalizationPatternFile = (File) cli
                            .getParsedOptionValue("normalization-pattern-file");
                    DoubleMatrix2D normalizationPatternMatrix = DoubleUtils
                            .read2DMatrixFromFile(normalizationPatternFile);
                    if (normalizationPatternMatrix.rows() == 1 && normalizationPatternMatrix.columns() == 1) {
                        patternId = 0;
                        normalizationPatternVector = new double[] { normalizationPatternMatrix.getQuick(0, 0) };
                    } else if (normalizationPatternMatrix.rows() == 1
                            && normalizationPatternMatrix.columns() > 1) {
                        patternId = 1;
                        normalizationPatternVector = normalizationPatternMatrix.viewRow(0).toArray();
                    } else if (normalizationPatternMatrix.rows() > 1
                            && normalizationPatternMatrix.columns() == 1) {
                        patternId = 2;
                        normalizationPatternVector = normalizationPatternMatrix.viewColumn(0).toArray();
                    } else {
                        throw new Net2PlanException(
                                "Bad normalization pattern - Neither a scalar (for total normalization), nor row vector (for row normalization) nor a column vector (for column normalization) was provided");
                    }

                    for (int tmId = 0; tmId < numMatrices; tmId++) {
                        switch (patternId) {
                        case 0:
                            trafficMatrices[tmId] = TrafficMatrixGenerationModels
                                    .normalizationPattern_totalTraffic(trafficMatrices[tmId],
                                            normalizationPatternVector[0]);
                            break;

                        case 1:
                            trafficMatrices[tmId] = TrafficMatrixGenerationModels
                                    .normalizationPattern_incomingTraffic(trafficMatrices[tmId],
                                            normalizationPatternVector);
                            break;

                        case 2:
                            trafficMatrices[tmId] = TrafficMatrixGenerationModels
                                    .normalizationPattern_outgoingTraffic(trafficMatrices[tmId],
                                            normalizationPatternVector);
                            break;

                        default:
                            throw new RuntimeException("Bad");
                        }
                    }
                } else {
                    throw new Net2PlanException("Parameter 'normalization-pattern-file' should be specified");
                }

                break;

            case "max-traffic-estimated-minHop":
                for (int tmId = 0; tmId < numMatrices; tmId++) {
                    netPlan.setTrafficMatrix(trafficMatrices[tmId]);
                    netPlan.setVectorDemandOfferedTraffic(
                            TrafficMatrixGenerationModels.normalizeTraffic_networkCapacity(netPlan));
                    trafficMatrices[tmId] = netPlan.getMatrixNode2NodeOfferedTraffic();
                }
                break;

            case "max-traffic-exact":
                String solverName = Configuration.getOption("defaultILPSolver");
                String solverLibraryName = Configuration.getDefaultSolverLibraryName(solverName);
                //                        if (solverName.equalsIgnoreCase("glpk")) solverLibraryName = Configuration.getOption("glpkSolverLibraryName");
                //                        else if (solverName.equalsIgnoreCase("ipopt")) solverLibraryName = Configuration.getOption("ipoptSolverLibraryName");
                //                        else if (solverName.equalsIgnoreCase("cplex")) solverLibraryName = Configuration.getOption("cplexSolverLibraryName");
                //                        else if (solverName.equalsIgnoreCase("xpress")) solverLibraryName = Configuration.getOption("xpressSolverLicenseFileName");
                //
                for (int tmId = 0; tmId < numMatrices; tmId++) {
                    netPlan.setTrafficMatrix(trafficMatrices[tmId]);
                    netPlan.setVectorDemandOfferedTraffic(TrafficMatrixGenerationModels
                            .normalizeTraffic_linkCapacity_xde(netPlan, solverName, solverLibraryName));
                    trafficMatrices[tmId] = netPlan.getMatrixNode2NodeOfferedTraffic();
                }
                break;

            default:
                throw new RuntimeException(
                        "Bad - Unknown normalization pattern '" + normalizationPattern + "'");
            }
        }
    }

    List<NetPlan> outputDemandSets = new LinkedList<NetPlan>();
    for (int tmId = 0; tmId < numMatrices; tmId++) {
        NetPlan aux = new NetPlan();

        aux.setTrafficMatrix(trafficMatrices[tmId]);
        outputDemandSets.add(aux);

        trafficMatrices[tmId] = null;
    }

    File outputFile = (File) cli.getParsedOptionValue("output-file");

    if (outputDemandSets.size() == 1) {
        outputDemandSets.get(0).saveToFile(outputFile);
    } else {
        String templateFileName = outputFile.getAbsoluteFile().toString();
        if (templateFileName.endsWith(".n2p"))
            templateFileName = templateFileName.substring(0, templateFileName.lastIndexOf('.'));

        ListIterator<NetPlan> netPlanIt = outputDemandSets.listIterator();
        while (netPlanIt.hasNext())
            netPlanIt.next().saveToFile(new File(templateFileName + "_tm" + netPlanIt.nextIndex() + ".n2p"));
    }

    long end = System.nanoTime();

    System.out.println(String.format("%n%nTraffic matrix generation finished successfully in %f seconds",
            (end - init) / 1e9));
}

From source file:groovy.ui.GroovyMain.java

/**
 * Process the users request./*  ww w .  j  a  v a2 s  .c o  m*/
 *
 * @param line the parsed command line.
 * @throws ParseException if invalid options are chosen
 */
private static boolean process(CommandLine line) throws ParseException, IOException {
    List args = line.getArgList();

    if (line.hasOption('D')) {
        String[] values = line.getOptionValues('D');

        for (int i = 0; i < values.length; i++) {
            setSystemPropertyFrom(values[i]);
        }
    }

    GroovyMain main = new GroovyMain();

    // 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 = (String) args.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);
    }

    // we use "," as default, because then split will create
    // an empty array if no option is set
    String disabled = line.getOptionValue("disableopt", ",");
    String[] deopts = disabled.split(",");
    for (String deopt_i : deopts) {
        main.conf.getOptimizationOptions().put(deopt_i, false);
    }

    if (line.hasOption("indy")) {
        CompilerConfiguration.DEFAULT.getOptimizationOptions().put("indy", true);
        main.conf.getOptimizationOptions().put("indy", true);
    }

    if (line.hasOption("basescript")) {
        main.conf.setScriptBaseClass(line.getOptionValue("basescript"));
    }

    if (line.hasOption("configscript")) {
        String path = line.getOptionValue("configscript");
        File groovyConfigurator = new File(path);
        Binding binding = new Binding();
        binding.setVariable("configuration", main.conf);

        CompilerConfiguration configuratorConfig = new CompilerConfiguration();
        ImportCustomizer customizer = new ImportCustomizer();
        customizer
                .addStaticStars("org.codehaus.groovy.control.customizers.builder.CompilerCustomizationBuilder");
        configuratorConfig.addCompilationCustomizers(customizer);

        GroovyShell shell = new GroovyShell(binding, configuratorConfig);
        shell.evaluate(groovyConfigurator);
    }

    main.args = args;

    return main.run();
}

From source file:com.symbian.utils.cmdline.CmdLine.java

/**
 * Displays tool version./*from  ww w. j a v  a  2  s .  c o m*/
 * 
 * @return 
 * @throws ParseException
 *             if command is not linked to any command set
 */
public String getNameVersionCopyRight() throws ParseException {
    if (iCmdSet == null) {
        throw new ParseException("command not linked to any command set!");
    }

    return iCmdSet.printNameVersionCopyRight();
}

From source file:cmd.ArgumentHandler.java

/**
 * Parses the options in the command line arguments and returns an array of
 * strings corresponding to the filenames given as arguments only
 *
 * @param args//from  www.  ja va2s.  c  o m
 * @throws org.apache.commons.cli.ParseException
 */
@SuppressWarnings("static-access")
public void parseCommandLineOptions(String[] args) throws ParseException {

    options = new Options();

    options.addOption("h", "help", false, "Help page for command usage");

    options.addOption("s", false, "SubStructure detection");

    options.addOption("a", false, "Add Hydrogen");

    options.addOption("x", false, "Match Atom Type");

    options.addOption("r", false, "Remove Hydrogen");

    options.addOption("z", false, "Ring matching");

    options.addOption("b", false, "Match Bond types (Single, Double etc)");

    options.addOption(
            OptionBuilder.hasArg().withDescription("Query filename").withArgName("filepath").create("q"));

    options.addOption(
            OptionBuilder.hasArg().withDescription("Target filename").withArgName("filepath").create("t"));

    options.addOption(OptionBuilder.hasArg().withDescription("Add suffix to the files").withArgName("suffix")
            .create("S"));

    options.addOption("g", false, "create png of the mapping");

    options.addOption(OptionBuilder.hasArg().withDescription("Dimension of the image in pixels")
            .withArgName("WIDTHxHEIGHT").create("d"));

    options.addOption("m", false, "Report all Mappings");

    String filterDescr = "Default: 0, Stereo: 1, " + "Stereo+Fragment: 2, Stereo+Fragment+Energy: 3";
    options.addOption(OptionBuilder.hasArg().withDescription(filterDescr).withArgName("number").create("f"));

    options.addOption("A", false, "Appends output to existing files, else creates new files");

    options.addOption(OptionBuilder.withDescription("Do N-way MCS on the target SD file").create("N"));

    options.addOption(OptionBuilder.hasArg().withDescription("Query type (MOL, SMI, etc)").withArgName("type")
            .create("Q"));

    options.addOption(OptionBuilder.hasArg().withDescription("Target type (MOL, SMI, SMIF, etc)")
            .withArgName("type").create("T"));

    options.addOption(OptionBuilder.hasArg().withDescription("Output the substructure to a file")
            .withArgName("filename").create("o"));

    options.addOption(
            OptionBuilder.hasArg().withDescription("Output type (SMI, MOL)").withArgName("type").create("O"));

    options.addOption(OptionBuilder.hasOptionalArgs(2).withValueSeparator().withDescription("Image options")
            .withArgName("option=value").create("I"));

    PosixParser parser = new PosixParser();
    CommandLine line = parser.parse(options, args, true);

    if (line.hasOption('Q')) {
        queryType = line.getOptionValue("Q");
    } //else {
    //            queryType = "MOL";
    //        } //XXX default type?

    if (line.hasOption('T')) {
        targetType = line.getOptionValue("T");
    } else {
        targetType = "MOL";
    }

    if (line.hasOption('a')) {
        this.setApplyHAdding(true);
    }

    if (line.hasOption('r')) {
        this.setApplyHRemoval(true);
    }

    if (line.hasOption('m')) {
        this.setAllMapping(true);
    }

    if (line.hasOption('s')) {
        this.setSubstructureMode(true);
    }

    if (line.hasOption('g')) {
        this.setImage(true);
    }

    if (line.hasOption('b')) {
        this.setMatchBondType(true);
    }

    if (line.hasOption('z')) {
        this.setMatchRingType(true);
    }

    if (line.hasOption('x')) {
        this.setMatchAtomType(true);
    }

    remainingArgs = line.getArgs();

    if (line.hasOption('h') || line.getOptions().length == 0) {
        //            System.out.println("Hello");
        helpRequested = true;
    }

    if (line.hasOption('S')) {
        String[] suffix_reader = line.getOptionValues('S');
        if (suffix_reader.length < 1) {
            System.out.println("Suffix required!");
            helpRequested = true;
        }
        setSuffix(suffix_reader[0]);
        setApplySuffix(true);
    }

    if (line.hasOption('f')) {
        String[] filters = line.getOptionValues('f');
        if (filters.length < 1) {
            System.out.println("Chemical filter required (Ranges: 0 to 3)!");
            helpRequested = true;
        }
        setChemFilter((int) new Integer(filters[0]));
    }

    if (line.hasOption('q')) {
        queryFilepath = line.getOptionValue('q');
    }

    if (line.hasOption('t')) {
        targetFilepath = line.getOptionValue('t');
    }

    if (line.hasOption("A")) {
        this.setAppendMode(true);
    }

    if (line.hasOption("N")) {
        setNMCS(true);
    }

    if (line.hasOption("o")) {
        outputSubgraph = true;
        outputFilepath = line.getOptionValue("o");
    }

    if (line.hasOption("O")) {
        outputFiletype = line.getOptionValue("O");
    } else {
        outputFiletype = "MOL";
    }

    if (line.hasOption("d")) {
        String dimensionString = line.getOptionValue("d");
        if (dimensionString.contains("x")) {
            String[] parts = dimensionString.split("x");
            try {
                setImageWidth(Integer.parseInt(parts[0]));
                setImageHeight(Integer.parseInt(parts[1]));
                System.out.println("set image dim to " + getImageWidth() + "x" + getImageHeight());
            } catch (NumberFormatException nfe) {
                throw new ParseException("Malformed dimension string " + dimensionString);
            }
        } else {
            throw new ParseException("Malformed dimension string " + dimensionString);
        }
    }

    if (line.hasOption("I")) {
        imageProperties = line.getOptionProperties("I");
        if (imageProperties.isEmpty()) {
            // used just "-I" by itself
            isImageOptionHelp = true;
        }
    }
}

From source file:lcmc.ArgumentParser.java

public void parseOptionsAndReturnAutoArguments(String[] args) {
    final Options options = new Options();

    options.addOption("h", HELP_OP, false, "print this help");
    options.addOption(null, KEEP_HELPER_OP, false, "do not overwrite the lcmc-gui-helper program");
    options.addOption(null, RO_OP, false, "read only mode");
    options.addOption(null, OP_OP, false, "operator mode");
    options.addOption(null, ADMIN_OP, false, "administrator mode");
    options.addOption(null, OP_MODE_OP, true, "operating mode. <arg> can be:\n" + "ro - read only\n"
            + "op - operator\n" + "admin - administrator");
    options.addOption(null, NOLRM_OP, false, "do not show removed resources from LRM.");
    options.addOption("v", VERSION_OP, false, "print version");
    options.addOption(null, AUTO_OP, true, "ADVANCED USE: for testing");
    options.addOption(null, PCMKTEST_OP, true, "ADVANCED USE: for testing");
    options.addOption(null, DRBDTEST_OP, true, "ADVANCED USE: for testing");
    options.addOption(null, VMTEST_OP, true, "ADVANCED USE: for testing");
    options.addOption(null, GUITEST_OP, true, "ADVANCED USE: for testing");
    options.addOption(null, NO_UPGRADE_CHECK_OP, false, "disable upgrade check");
    options.addOption(null, NO_PLUGIN_CHECK_OP, false,
            "disable plugin check, DEPRECATED: there are no plugins");
    options.addOption(null, TIGHTVNC_OP, false, "enable tight vnc viewer");
    options.addOption(null, ULTRAVNC_OP, false, "enable ultra vnc viewer");
    options.addOption(null, REALVNC_OP, false, "enable real vnc viewer");
    options.addOption(null, BIGDRBDCONF_OP, false,
            "create one big drbd.conf, instead of many" + " files in drbd.d/ directory");
    options.addOption(null, STAGING_DRBD_OP, false, "enable more DRBD installation options");
    options.addOption(null, STAGING_PACEMAKER_OP, false, "enable more Pacemaker installation options");
    options.addOption(null, VNC_PORT_OFFSET_OP, true, "offset for port forwarding");
    options.addOption(null, SLOW_OP, false, "specify this if you have slow computer");
    options.addOption(null, RESTORE_MOUSE_OP, false, "ADVANCED USE: for testing");
    options.addOption(null, SCALE_OP, true, "scale fonts and sizes of elements in percent (100)");
    options.addOption(null, ID_DSA_OP, true, "location of id_dsa file ($HOME/.ssh/id_dsa)");
    options.addOption(null, ID_RSA_OP, true, "location of id_rsa file ($HOME/.ssh/id_rsa)");
    options.addOption(null, KNOWN_HOSTS_OP, true, "location of known_hosts file ($HOME/.ssh/known_hosts)");
    options.addOption(null, OUT_OP, true, "where to redirect the standard out");
    options.addOption(null, DEBUG_OP, true, "debug level, 0 - none, 3 - all");
    options.addOption("c", CLUSTER_OP, true, "define a cluster");
    final Option hostOp = new Option("h", HOST_OP, true, "define a cluster, used with --cluster option");
    hostOp.setArgs(10000);/*ww w. ja  v  a 2s  . c o m*/
    options.addOption(hostOp);
    options.addOption(null, SUDO_OP, false, "whether to use sudo, used with --cluster option");
    options.addOption(null, USER_OP, true, "user to use with sudo, used with --cluster option");
    options.addOption(null, PORT_OP, true, "ssh port, used with --cluster option");
    options.addOption(null, ADVANCED_OP, false, "start in an advanced mode");
    options.addOption(null, ONE_HOST_CLUSTER_OP, false, "allow one host cluster");
    options.addOption(null, NO_PASSPHRASE_OP, false, "try no passphrase first");
    options.addOption(null, EMBED_OP, false, "embed applet in the browser");
    options.addOption(null, NO_EMBED_OP, false, "don't embed applet in the browser");
    options.addOption(null, CMD_LOG_OP, false, "Log executed commands to the lcmc.log on the servers");
    options.addOption(null, CHECK_SWING_OP, false, "ADVANCED USE: for testing");
    final CommandLineParser parser = new PosixParser();
    String autoArgs = null;
    try {
        final CommandLine cmd = parser.parse(options, args);
        if (cmd.hasOption(OUT_OP)) {
            final String out = cmd.getOptionValue(OUT_OP);
            if (out != null) {
                try {
                    System.setOut(new PrintStream(new FileOutputStream(out)));
                } catch (final FileNotFoundException e) {
                    System.exit(2);
                }
            }
        }
        if (cmd.hasOption(DEBUG_OP)) {
            final String level = cmd.getOptionValue(DEBUG_OP);
            if (level != null && lcmc.common.domain.util.Tools.isNumber(level)) {
                LoggerFactory.setDebugLevel(Integer.parseInt(level));
            } else {
                throw new ParseException("cannot parse debug level: " + level);
            }
        }
        boolean tightvnc = cmd.hasOption(TIGHTVNC_OP);
        boolean ultravnc = cmd.hasOption(ULTRAVNC_OP);
        final boolean realvnc = cmd.hasOption(REALVNC_OP);
        if (!tightvnc && !ultravnc && !realvnc) {
            if (lcmc.common.domain.util.Tools.isLinux()) {
                tightvnc = true;
            } else {
                tightvnc = true;
                ultravnc = true;
            }
        }
        final boolean advanced = cmd.hasOption(ADVANCED_OP);
        access.setAdvancedMode(advanced);
        application.setUseTightvnc(tightvnc);
        application.setUseUltravnc(ultravnc);
        application.setUseRealvnc(realvnc);

        application.setUpgradeCheckEnabled(!cmd.hasOption(NO_UPGRADE_CHECK_OP));
        application.setBigDRBDConf(cmd.hasOption(BIGDRBDCONF_OP));
        application.setStagingDrbd(cmd.hasOption(STAGING_DRBD_OP));
        application.setStagingPacemaker(cmd.hasOption(STAGING_PACEMAKER_OP));
        application.setHideLRM(cmd.hasOption(NOLRM_OP));
        application.setKeepHelper(cmd.hasOption(KEEP_HELPER_OP));
        application.setOneHostCluster(cmd.hasOption(ONE_HOST_CLUSTER_OP));
        application.setNoPassphrase(cmd.hasOption(NO_PASSPHRASE_OP));
        if (cmd.hasOption(EMBED_OP)) {
            application.setEmbedApplet(true);
        }
        if (cmd.hasOption(NO_EMBED_OP)) {
            application.setEmbedApplet(false);
        }
        if (cmd.hasOption(CMD_LOG_OP)) {
            application.setCmdLog(true);
        }
        if (cmd.hasOption(CHECK_SWING_OP)) {
            swingUtils.setCheckSwing(true);
        }
        final String pwd = System.getProperty("user.home");
        final String scaleOp = cmd.getOptionValue(SCALE_OP, "100");
        try {
            final int scale = Integer.parseInt(scaleOp);
            application.setScale(scale);
            application.resizeFonts(scale);
        } catch (final NumberFormatException e) {
            LOG.appWarning("initApp: cannot parse scale: " + scaleOp);
        }

        final String idDsaPath = cmd.getOptionValue(ID_DSA_OP, pwd + "/.ssh/id_dsa");
        final String idRsaPath = cmd.getOptionValue(ID_RSA_OP, pwd + "/.ssh/id_rsa");
        final String knownHostsPath = cmd.getOptionValue(KNOWN_HOSTS_OP, pwd + "/.ssh/known_hosts");
        application.setIdDSAPath(idDsaPath);
        application.setIdRSAPath(idRsaPath);
        application.setKnownHostPath(knownHostsPath);

        final String opMode = cmd.getOptionValue(OP_MODE_OP);
        autoArgs = cmd.getOptionValue(AUTO_OP);
        if (cmd.hasOption(HELP_OP)) {
            final HelpFormatter formatter = new HelpFormatter();
            formatter.printHelp("java -jar LCMC.jar [OPTIONS]", options);
            System.exit(0);
        }
        if (cmd.hasOption(VERSION_OP)) {
            System.out.println("LINUX CLUSTER MANAGEMENT CONSOLE " + lcmc.common.domain.util.Tools.getRelease()
                    + " by Rasto Levrinc");
            System.exit(0);
        }
        if (cmd.hasOption("ro") || "ro".equals(opMode)) {
            access.setAccessType(AccessMode.RO);
            access.setMaxAccessType(AccessMode.RO);
        } else if (cmd.hasOption("op") || "op".equals(opMode)) {
            access.setAccessType(AccessMode.OP);
            access.setMaxAccessType(AccessMode.OP);
        } else if (cmd.hasOption("admin") || "admin".equals(opMode)) {
            access.setAccessType(AccessMode.ADMIN);
            access.setMaxAccessType(AccessMode.ADMIN);
        } else if (opMode != null) {
            LOG.appWarning("initApp: unknown operating mode: " + opMode);
        }
        float fps = MainData.DEFAULT_ANIM_FPS;
        if (cmd.hasOption(SLOW_OP)) {
            fps /= 2;
        }
        if (cmd.hasOption(RESTORE_MOUSE_OP)) {
            /* restore mouse if it is stuck in pressed state, during
            * robot tests. */
            roboTest.restoreMouse();
        }
        final String vncPortOffsetString = cmd.getOptionValue(VNC_PORT_OFFSET_OP);
        if (vncPortOffsetString != null && lcmc.common.domain.util.Tools.isNumber(vncPortOffsetString)) {
            application.setVncPortOffset(Integer.parseInt(vncPortOffsetString));
        }
        mainData.setAnimFPS(fps);
        if (cmd.hasOption(CLUSTER_OP) || cmd.hasOption(HOST_OP)) {
            parseClusterOptionsAndCreateClusterButton(cmd);
        }
    } catch (final ParseException exp) {
        System.out.println("ERROR: " + exp.getMessage());
        System.exit(1);
    }
    LOG.debug1("initApp: max mem: " + Runtime.getRuntime().maxMemory() / 1024 / 1024 + 'm');
    if (autoArgs != null) {
        parseAutoArgs(autoArgs);
    }
}

From source file:bdsup2sub.cli.CommandLineParser.java

private void parseDelayOption(CommandLine line) throws ParseException {
    if (line.hasOption(DELAY)) {
        String value = line.getOptionValue(DELAY);
        try {//from   w w w .j a va  2s. c om
            delay = Optional.of(Double.parseDouble(value.trim()));
        } catch (NumberFormatException ex) {
            throw new ParseException("Illegal delay value: " + value);
        }
    }
}

From source file:groovyx.groovyserv.GroovyMain2.java

/**
 * Process the users request./*from  w  w w .  j av  a 2  s.c o m*/
 *
 * @param line the parsed command line.
 * @throws ParseException if invalid options are chosen
 */
private static boolean process(CommandLine line, String classpath) throws ParseException, IOException { // for GroovyServ
    List args = line.getArgList();

    if (line.hasOption('D')) {
        String[] values = line.getOptionValues('D');

        for (int i = 0; i < values.length; i++) {
            setSystemPropertyFrom(values[i]);
        }
    }

    GroovyMain2 main = new GroovyMain2();

    // 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 = (String) args.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);
    }

    // we use "," as default, because then split will create
    // an empty array if no option is set
    String disabled = line.getOptionValue("disableopt", ",");
    String[] deopts = disabled.split(",");
    for (String deopt_i : deopts) {
        main.conf.getOptimizationOptions().put(deopt_i, false);
    }

    if (line.hasOption("indy")) {
        CompilerConfiguration.DEFAULT.getOptimizationOptions().put("indy", true);
        main.conf.getOptimizationOptions().put("indy", true);
    }

    if (line.hasOption("basescript")) {
        main.conf.setScriptBaseClass(line.getOptionValue("basescript"));
    }

    if (line.hasOption("configscript")) {
        String path = line.getOptionValue("configscript");
        File groovyConfigurator = new File(path);
        Binding binding = new Binding();
        binding.setVariable("configuration", main.conf);

        CompilerConfiguration configuratorConfig = new CompilerConfiguration();
        ImportCustomizer customizer = new ImportCustomizer();
        customizer
                .addStaticStars("org.codehaus.groovy.control.customizers.builder.CompilerCustomizationBuilder");
        configuratorConfig.addCompilationCustomizers(customizer);

        GroovyShell shell = new GroovyShell(binding, configuratorConfig);
        shell.evaluate(groovyConfigurator);
    }

    main.args = args;

    // for GroovyServ: classpath is given by GroovyInvokeHandler
    if (classpath != null) {
        main.conf.setClasspath(classpath);
    }

    return main.run();
}

From source file:com.databasepreservation.cli.CLI.java

/**
 * Parses the argument list and creates new import and export modules
 *
 * @param args/*from  w ww  .  j a  v a2 s.  c o m*/
 *          The command line arguments
 * @throws ParseException
 *           If the arguments could not be parsed or are invalid
 */
private void parse(List<String> args) throws ParseException, LicenseNotAcceptedException {
    DatabaseModuleFactoriesPair databaseModuleFactoriesPair = getModuleFactories(args);

    try {
        importModuleName = databaseModuleFactoriesPair.getImportModuleFactory().getModuleName();
        exportModuleName = databaseModuleFactoriesPair.getExportModuleFactory().getModuleName();
        DatabaseModuleFactoriesArguments databaseModuleFactoriesArguments = getModuleArguments(
                databaseModuleFactoriesPair, args);

        if (forceDisableEncryption) {
            // inject disable encryption for import module
            for (Parameter parameter : databaseModuleFactoriesPair.getImportModuleFactory()
                    .getImportModuleParameters().getParameters()) {
                if (parameter.longName().equalsIgnoreCase("disable-encryption")) {
                    if (!databaseModuleFactoriesArguments.getImportModuleArguments().containsKey(parameter)) {
                        databaseModuleFactoriesArguments.getImportModuleArguments().put(parameter, "true");
                    }
                    break;
                }
            }

            // inject disable encryption for export module
            for (Parameter parameter : databaseModuleFactoriesPair.getExportModuleFactory()
                    .getExportModuleParameters().getParameters()) {
                if (parameter.longName().equalsIgnoreCase("disable-encryption")) {
                    if (!databaseModuleFactoriesArguments.getExportModuleArguments().containsKey(parameter)) {
                        databaseModuleFactoriesArguments.getExportModuleArguments().put(parameter, "true");
                    }
                    break;
                }
            }
        }

        // set import and export modules
        importModule = databaseModuleFactoriesPair.getImportModuleFactory()
                .buildImportModule(databaseModuleFactoriesArguments.getImportModuleArguments());
        exportModule = databaseModuleFactoriesPair.getExportModuleFactory()
                .buildExportModule(databaseModuleFactoriesArguments.getExportModuleArguments());
    } catch (OperationNotSupportedException e) {
        LOGGER.debug("OperationNotSupportedException", e);
        throw new ParseException("Module does not support the requested mode.");
    }
}

From source file:com.symbian.driver.remoting.cmdline.RunremoteCmdLine.java

/**
 * Implements additional constraints on switches.
 * /*  w w w  .ja  v a  2s  .  c  o  m*/
 * @param aCommandLine
 *            {@inheritDoc}
 * @throws ParseException
 *             {@inheritDoc}
 */
public void checkAdditionalConstraints(final CommandLine aCommandLine) throws ParseException {
    if (aCommandLine.hasOption("m")) {
        String lMode = aCommandLine.getOptionValue("m");
        if (!lMode.equalsIgnoreCase("sync") && !lMode.equalsIgnoreCase("async")) {
            throw new ParseException("Synchrinization should be either sync or async.");
        }
    }
}