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:com.xylocore.copybook.generator.CopybookClassGeneratorApplication.java

@Override
protected void processArguments(CommandLine aCommandLine) throws ParseException {
    cliProperties = new HashMap<>();

    checkOption(aCommandLine, "class", EnvironmentConfigurator.CLASS_NAME_KEY);
    checkOption(aCommandLine, "genrootdir", EnvironmentConfigurator.GENERATION_ROOT_DIR_KEY);
    checkOption(aCommandLine, "metafile", EnvironmentConfigurator.METADATA_FILENAME_KEY);
    checkOption(aCommandLine, "implrecname", EnvironmentConfigurator.IMPLICIT_RECORD_NAME_KEY);

    @SuppressWarnings("unchecked")
    List<String> myArgList = aCommandLine.getArgList();

    if (myArgList.size() == 0) {
        throw new ParseException("missing arguments");
    } else if (myArgList.size() > 1) {
        throw new ParseException("too many arguments");
    }//  www.  j av a 2s  .  c om

    cliProperties.put(EnvironmentConfigurator.COPYBOOK_FILENAME_KEY, myArgList.get(0));

    // Use the current working directory for the generation root directory if a generation root
    // directory was not specified
    if (cliProperties.get(EnvironmentConfigurator.GENERATION_ROOT_DIR_KEY) == null) {
        String myCurrentWorkingDirectory = System.getProperty("user.dir");
        cliProperties.put(EnvironmentConfigurator.GENERATION_ROOT_DIR_KEY, myCurrentWorkingDirectory);
    }
}

From source file:edu.ifpb.pos.restletclient.CommandLineApp.java

private static String getUrlType(String type) throws ParseException {
    switch (type) {
    case JSON_PERSON:
        return "http://localhost:8080/app/person";
    case JSON_USER:
        return "http://localhost:8080/app/user";
    default:/*w ww.  jav a  2 s .c  om*/
        throw new ParseException("ERROR: Tipo invlido");
    }
}

From source file:bvt.TestRunner.java

/**
 * Primary entry point for the program.//w  ww  . j a va 2  s  .co  m
 * 
 * @throws Exception
 */
public void run(String[] args) throws Exception {

    // Parse the command line ...
    CommandLine cl = null;
    Options options = getCommandOptions();
    try {
        cl = new BasicParser().parse(options, args);
        if (cl.getOptions().length == 0)
            throw new ParseException("Report format not specified.");
    } catch (ParseException e) {
        System.out.println("");
        System.out.println(e.getMessage());
        System.out.println("");
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp(80, "TestRunner", "", options, "", true);
        System.out.println("");
        System.out.println("Example: TestRunner -h");
        return;
    }

    // Interpret provided values ...
    boolean isBriefRequested = cl.hasOption("b");
    boolean isFullRequested = cl.hasOption("f");
    boolean isHtmlRequested = cl.hasOption("h");
    boolean isXmlRequested = cl.hasOption("x");
    boolean isVerifyRequested = cl.hasOption("v");

    // Launch the requested tests ...
    if (isBriefRequested)
        org.apache.tools.ant.launch.Launcher.main(new String[] { "-buildfile", "TestRunner.xml", "bvt-brief" });
    if (isFullRequested)
        org.apache.tools.ant.launch.Launcher.main(new String[] { "-buildfile", "TestRunner.xml", "bvt-full" });
    if (isHtmlRequested)
        org.apache.tools.ant.launch.Launcher.main(new String[] { "-buildfile", "TestRunner.xml", "bvt-html" });
    if (isXmlRequested)
        org.apache.tools.ant.launch.Launcher.main(new String[] { "-buildfile", "TestRunner.xml", "bvt-xml" });
    if (isVerifyRequested)
        org.apache.tools.ant.launch.Launcher.main(new String[] { "-buildfile", "TestRunner.xml", "verify" });

}

From source file:bachelorthesis.captchabuilder.builder.TextParser.java

/**
 * Parses the string arguments for rendering Text, creates a
 * TextProducer and WordRenderer passes these to the CaptchaBuilder
 *
 * @param buildSequenceOptions the string arguments for adding text
 * @param builder              the CaptchaBuilder Object to be modified
 * <p/>/*from  w w  w .j  a  v a 2  s . com*/
 * @return a modified CaptchaBuilder object
 * <p/>
 * @throws org.apache.commons.cli.ParseException
 * @see CaptchaBuilder
 */
public static CaptchaBuilder parse(String[] buildSequenceOptions, CaptchaBuilder builder)
        throws ParseException {

    for (String textOptionArg : buildSequenceOptions) {
        if (!textOptionArg.isEmpty()) {
            try {
                String[] optionArgs = textOptionArg.split(CaptchaConstants.buildSequencelvl3Delim);
                TextOptions textOptionType = TextOptions.valueOf(optionArgs[0]);
                String[] textOptions = Arrays.copyOfRange(optionArgs, 1, optionArgs.length);

                parseTextOption(textOptionType, textOptions, builder);
            } catch (IllegalArgumentException e) {
                throw new ParseException(e.getMessage());
            }

        }
    }

    //return builder.addText(textProducerBuilder.create(), wordRendererBuilder.create());
    builder.addBuildSequence(textProducerBuilder);
    builder.addBuildSequence(wordRendererBuilder);
    return builder;
}

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

/**
 * Retrieves the <code>org.apache.commons.cli.CommandLine</code> object
 * that parses the command line. Use this to customize the command line.
 * // w w w .j  a  v  a  2s  .  com
 * @return Command Line
 * @throws ParseException
 *             If the commandline is invalid.
 */
public CommandLine getCommandLine() throws ParseException {
    if (iCommandLine == null) {
        throw new ParseException("NULL pointer exception at constructor of Commandline.");
    }
    return iCommandLine;
}

From source file:com.example.cloud.iot.examples.DeviceRegistryExampleOptions.java

/** Construct an DeviceRegistryExampleOptions class from command line flags. */
public static DeviceRegistryExampleOptions fromFlags(String[] args) {
    Options options = new Options();
    // Required arguments
    options.addOption(Option.builder().type(String.class).longOpt("pubsub_topic").hasArg()
            .desc("Pub/Sub topic to create registry in.").required().build());
    options.addOption(Option.builder().type(String.class).longOpt("command").hasArg()
            .desc("Command to run:" + "\n\tcreate-iot-topic" // TODO: Descriptions or too verbose?
                    + "\n\tcreate-rsa" + "\n\tcreate-es" + "\n\tcreate-unauth" + "\n\tcreate-registry"
                    + "\n\tdelete-device" + "\n\tdelete-registry" + "\n\tget-device" + "\n\tget-device-state"
                    + "\n\tget-registry" + "\n\tlist-devices" + "\n\tlist-registries" + "\n\tpatch-device-es"
                    + "\n\tpatch-device-rsa")
            .required().build());//  w ww.  ja  v  a  2 s. c o  m

    // Optional arguments.
    options.addOption(Option.builder().type(String.class).longOpt("ec_public_key_file").hasArg()
            .desc("Path to ES256 public key file.").build());
    options.addOption(Option.builder().type(String.class).longOpt("rsa_certificate_file").hasArg()
            .desc("Path to RS256 certificate file.").build());
    options.addOption(Option.builder().type(String.class).longOpt("cloud_region").hasArg()
            .desc("GCP cloud region.").build());
    options.addOption(Option.builder().type(String.class).longOpt("project_id").hasArg()
            .desc("GCP cloud project name.").build());
    options.addOption(Option.builder().type(String.class).longOpt("registry_name").hasArg()
            .desc("Name for your Device Registry.").build());
    options.addOption(Option.builder().type(String.class).longOpt("device_id").hasArg()
            .desc("Name for your Device.").build());

    CommandLineParser parser = new DefaultParser();
    CommandLine commandLine;
    try {
        commandLine = parser.parse(options, args);
        DeviceRegistryExampleOptions res = new DeviceRegistryExampleOptions();

        res.command = commandLine.getOptionValue("command");

        if (res.command.equals("help") || res.command.equals("")) {
            throw new ParseException("Invalid command, showing help.");
        }

        if (commandLine.hasOption("project_id")) {
            res.projectId = commandLine.getOptionValue("project_id");
        } else {
            try {
                res.projectId = System.getenv("GOOGLE_CLOUD_PROJECT");
            } catch (NullPointerException npe) {
                res.projectId = System.getenv("GCLOUD_PROJECT");
            }
        }

        if (commandLine.hasOption("pubsub_topic")) {
            res.pubsubTopic = commandLine.getOptionValue("pubsub_topic");
        } else {
            // TODO: Get from environment variable
        }

        if (commandLine.hasOption("ec_public_key_file")) {
            res.ecPublicKeyFile = commandLine.getOptionValue("ec_public_key_file");
        }
        if (commandLine.hasOption("rsa_certificate_file")) {
            res.rsaCertificateFile = commandLine.getOptionValue("rsa_certificate_file");
        }
        if (commandLine.hasOption("cloud_region")) {
            res.cloudRegion = commandLine.getOptionValue("cloud_region");
        }
        if (commandLine.hasOption("registry_name")) {
            res.registryName = commandLine.getOptionValue("registry_name");
        }
        if (commandLine.hasOption("device_id")) {
            res.deviceId = commandLine.getOptionValue("device_id");
        }
        return res;
    } catch (ParseException e) {
        String header = "Cloud IoT Core Commandline Example (Device / Registry management): \n\n";
        String footer = "\nhttps://cloud.google.com/iot-core";

        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("DeviceRegistryExample", header, options, footer, true);

        System.err.println(e.getMessage());
        return null;
    }
}

From source file:it.crs4.seal.read_sort.ReadSortOptionParser.java

@Override
protected CommandLine parseOptions(Configuration conf, String[] args) throws IOException, ParseException {
    CommandLine line = super.parseOptions(conf, args);

    /********* distributed reference and annotations *********/
    if (line.hasOption(distReference.getOpt())) {
        // Distribute the reference archive, and create a // symlink "reference" to the directory
        Path optPath = new Path(line.getOptionValue(distReference.getOpt()));
        optPath = optPath.makeQualified(optPath.getFileSystem(conf));
        Path cachePath = new Path(optPath.toString() + "#reference");
        conf.set("mapred.cache.archives", cachePath.toString());
        conf.set("mapred.create.symlink", "yes");

        if (line.hasOption(ann.getOpt()))
            conf.set(ReadSort.REF_ANN_PROP_NAME, "reference/" + line.getOptionValue(ann.getOpt()));
        else/*from   w w w  . j a va 2s  . c o m*/
            throw new ParseException(
                    "You must specify the name of the annotation file within the distributed reference archive with -"
                            + ann.getOpt());
    } else if (line.hasOption(ann.getOpt())) {
        // direct access to the reference annotation
        conf.set(ReadSort.REF_ANN_PROP_NAME, line.getOptionValue(ann.getOpt()));
    } else
        throw new ParseException("You must provide the path the reference annotation file (<ref>.ann)");

    conf.set(ClusterUtils.NUM_RED_TASKS_PROPERTY, String.valueOf(getNReduceTasks()));
    return line;
}

From source file:com.soteradefense.dga.DGACommandLineUtil.java

public static DGAConfiguration parseCommandLine(String[] args, Options options) throws ParseException {
    CommandLineParser parser = new GnuParser();
    CommandLine cmd = parser.parse(options, args);
    if (cmd.hasOption("h")) {
        printUsageAndExit(options);//from   www.  j  av a 2s  .c  o  m
    }

    DGAConfiguration dgaConf = new DGAConfiguration();

    if (cmd.hasOption("q")) {
        dgaConf.setGiraphProperty("-q", "");
    }

    if (cmd.hasOption("w")) {
        dgaConf.setGiraphProperty("-w", cmd.getOptionValue("w"));
    }

    if (cmd.hasOption("yj")) {
        dgaConf.setGiraphProperty("-yj", cmd.getOptionValue("yj"));
    }

    if (cmd.hasOption("yh")) {
        dgaConf.setGiraphProperty("-yh", cmd.getOptionValue("yh"));
    }

    if (cmd.hasOption("ca")) {
        String[] customArguments = cmd.getOptionValues("ca");
        for (String customArgument : customArguments) {
            int indexOfEquals = customArgument.indexOf("=");
            if (indexOfEquals == -1)
                throw new ParseException(
                        "The custom argument " + customArgument + " does not follow the form -ca key=value");
            String key = customArgument.substring(0, indexOfEquals);
            String value = customArgument.substring(indexOfEquals + 1);
            if (characterMap.containsKey(value)) {
                value = String.valueOf(characterMap.get(value));
            }
            dgaConf.setCustomProperty(key, value);
        }
    }

    if (cmd.hasOption("D")) {
        String[] systemProperty = cmd.getOptionValues("D");
        for (String sysProp : systemProperty) {
            int indexOfEquals = sysProp.indexOf("=");
            if (indexOfEquals == -1)
                throw new ParseException(
                        "The systemProperty " + sysProp + " does not follow the form -D key=value");
            String key = sysProp.substring(0, indexOfEquals);
            String value = sysProp.substring(indexOfEquals + 1);
            dgaConf.setSystemProperty(key, value);
        }
    }

    return dgaConf;
}

From source file:com.cws.esolutions.security.main.PasswordUtility.java

public static void main(final String[] args) {
    final String methodName = PasswordUtility.CNAME + "#main(final String[] args)";

    if (DEBUG) {/*  w w  w .  j a v a 2s.com*/
        DEBUGGER.debug("Value: {}", methodName);
    }

    if (args.length == 0) {
        HelpFormatter usage = new HelpFormatter();
        usage.printHelp(PasswordUtility.CNAME, options, true);

        System.exit(1);
    }

    BufferedReader bReader = null;
    BufferedWriter bWriter = null;

    try {
        // load service config first !!
        SecurityServiceInitializer.initializeService(PasswordUtility.SEC_CONFIG, PasswordUtility.LOG_CONFIG,
                false);

        if (DEBUG) {
            DEBUGGER.debug("Options options: {}", options);

            for (String arg : args) {
                DEBUGGER.debug("Value: {}", arg);
            }
        }

        CommandLineParser parser = new PosixParser();
        CommandLine commandLine = parser.parse(options, args);

        if (DEBUG) {
            DEBUGGER.debug("CommandLineParser parser: {}", parser);
            DEBUGGER.debug("CommandLine commandLine: {}", commandLine);
            DEBUGGER.debug("CommandLine commandLine.getOptions(): {}", (Object[]) commandLine.getOptions());
            DEBUGGER.debug("CommandLine commandLine.getArgList(): {}", commandLine.getArgList());
        }

        final SecurityConfigurationData secConfigData = PasswordUtility.svcBean.getConfigData();
        final SecurityConfig secConfig = secConfigData.getSecurityConfig();
        final PasswordRepositoryConfig repoConfig = secConfigData.getPasswordRepo();
        final SystemConfig systemConfig = secConfigData.getSystemConfig();

        if (DEBUG) {
            DEBUGGER.debug("SecurityConfigurationData secConfig: {}", secConfigData);
            DEBUGGER.debug("SecurityConfig secConfig: {}", secConfig);
            DEBUGGER.debug("RepositoryConfig secConfig: {}", repoConfig);
            DEBUGGER.debug("SystemConfig systemConfig: {}", systemConfig);
        }

        if (commandLine.hasOption("encrypt")) {
            if ((StringUtils.isBlank(repoConfig.getPasswordFile()))
                    || (StringUtils.isBlank(repoConfig.getSaltFile()))) {
                System.err.println("The password/salt files are not configured. Entries will not be stored!");
            }

            File passwordFile = FileUtils.getFile(repoConfig.getPasswordFile());
            File saltFile = FileUtils.getFile(repoConfig.getSaltFile());

            if (DEBUG) {
                DEBUGGER.debug("File passwordFile: {}", passwordFile);
                DEBUGGER.debug("File saltFile: {}", saltFile);
            }

            final String entryName = commandLine.getOptionValue("entry");
            final String username = commandLine.getOptionValue("username");
            final String password = commandLine.getOptionValue("password");
            final String salt = RandomStringUtils.randomAlphanumeric(secConfig.getSaltLength());

            if (DEBUG) {
                DEBUGGER.debug("String entryName: {}", entryName);
                DEBUGGER.debug("String username: {}", username);
                DEBUGGER.debug("String password: {}", password);
                DEBUGGER.debug("String salt: {}", salt);
            }

            final String encodedSalt = PasswordUtils.base64Encode(salt);
            final String encodedUserName = PasswordUtils.base64Encode(username);
            final String encryptedPassword = PasswordUtils.encryptText(password, salt,
                    secConfig.getSecretAlgorithm(), secConfig.getIterations(), secConfig.getKeyBits(),
                    secConfig.getEncryptionAlgorithm(), secConfig.getEncryptionInstance(),
                    systemConfig.getEncoding());
            final String encodedPassword = PasswordUtils.base64Encode(encryptedPassword);

            if (DEBUG) {
                DEBUGGER.debug("String encodedSalt: {}", encodedSalt);
                DEBUGGER.debug("String encodedUserName: {}", encodedUserName);
                DEBUGGER.debug("String encodedPassword: {}", encodedPassword);
            }

            if (commandLine.hasOption("store")) {
                try {
                    new File(passwordFile.getParent()).mkdirs();
                    new File(saltFile.getParent()).mkdirs();

                    boolean saltFileExists = (saltFile.exists()) ? true : saltFile.createNewFile();

                    if (DEBUG) {
                        DEBUGGER.debug("saltFileExists: {}", saltFileExists);
                    }

                    // write the salt out first
                    if (!(saltFileExists)) {
                        throw new IOException("Unable to create salt file");
                    }

                    boolean passwordFileExists = (passwordFile.exists()) ? true : passwordFile.createNewFile();

                    if (!(passwordFileExists)) {
                        throw new IOException("Unable to create password file");
                    }

                    if (commandLine.hasOption("replace")) {
                        File[] files = new File[] { saltFile, passwordFile };

                        if (DEBUG) {
                            DEBUGGER.debug("File[] files: {}", (Object) files);
                        }

                        for (File file : files) {
                            if (DEBUG) {
                                DEBUGGER.debug("File: {}", file);
                            }

                            String currentLine = null;
                            File tmpFile = new File(FileUtils.getTempDirectory() + "/" + "tmpFile");

                            if (DEBUG) {
                                DEBUGGER.debug("File tmpFile: {}", tmpFile);
                            }

                            bReader = new BufferedReader(new FileReader(file));
                            bWriter = new BufferedWriter(new FileWriter(tmpFile));

                            while ((currentLine = bReader.readLine()) != null) {
                                if (!(StringUtils.equals(currentLine.trim().split(",")[0], entryName))) {
                                    bWriter.write(currentLine + System.getProperty("line.separator"));
                                    bWriter.flush();
                                }
                            }

                            bWriter.close();

                            FileUtils.deleteQuietly(file);
                            FileUtils.copyFile(tmpFile, file);
                            FileUtils.deleteQuietly(tmpFile);
                        }
                    }

                    FileUtils.writeStringToFile(saltFile, entryName + "," + encodedUserName + "," + encodedSalt
                            + System.getProperty("line.separator"), true);
                    FileUtils.writeStringToFile(passwordFile, entryName + "," + encodedUserName + ","
                            + encodedPassword + System.getProperty("line.separator"), true);
                } catch (IOException iox) {
                    ERROR_RECORDER.error(iox.getMessage(), iox);
                }
            }

            System.out.println("Entry Name " + entryName + " stored.");
        }

        if (commandLine.hasOption("decrypt")) {
            String saltEntryName = null;
            String saltEntryValue = null;
            String decryptedPassword = null;
            String passwordEntryName = null;

            if ((StringUtils.isEmpty(commandLine.getOptionValue("entry"))
                    && (StringUtils.isEmpty(commandLine.getOptionValue("username"))))) {
                throw new ParseException("No entry or username was provided to decrypt.");
            }

            if (StringUtils.isEmpty(commandLine.getOptionValue("username"))) {
                throw new ParseException("no entry provided to decrypt");
            }

            String entryName = commandLine.getOptionValue("entry");
            String username = commandLine.getOptionValue("username");

            if (DEBUG) {
                DEBUGGER.debug("String entryName: {}", entryName);
                DEBUGGER.debug("String username: {}", username);
            }

            File passwordFile = FileUtils.getFile(repoConfig.getPasswordFile());
            File saltFile = FileUtils.getFile(repoConfig.getSaltFile());

            if (DEBUG) {
                DEBUGGER.debug("File passwordFile: {}", passwordFile);
                DEBUGGER.debug("File saltFile: {}", saltFile);
            }

            if ((!(saltFile.canRead())) || (!(passwordFile.canRead()))) {
                throw new IOException(
                        "Unable to read configured password/salt file. Please check configuration and/or permissions.");
            }

            for (String lineEntry : FileUtils.readLines(saltFile, systemConfig.getEncoding())) {
                saltEntryName = lineEntry.split(",")[0];

                if (DEBUG) {
                    DEBUGGER.debug("String saltEntryName: {}", saltEntryName);
                }

                if (StringUtils.equals(saltEntryName, entryName)) {
                    saltEntryValue = PasswordUtils.base64Decode(lineEntry.split(",")[2]);

                    break;
                }
            }

            if (StringUtils.isEmpty(saltEntryValue)) {
                throw new SecurityException("No entries were found that matched the provided information");
            }

            for (String lineEntry : FileUtils.readLines(passwordFile, systemConfig.getEncoding())) {
                passwordEntryName = lineEntry.split(",")[0];

                if (DEBUG) {
                    DEBUGGER.debug("String passwordEntryName: {}", passwordEntryName);
                }

                if (StringUtils.equals(passwordEntryName, saltEntryName)) {
                    String decodedPassword = PasswordUtils.base64Decode(lineEntry.split(",")[2]);

                    decryptedPassword = PasswordUtils.decryptText(decodedPassword, saltEntryValue,
                            secConfig.getSecretAlgorithm(), secConfig.getIterations(), secConfig.getKeyBits(),
                            secConfig.getEncryptionAlgorithm(), secConfig.getEncryptionInstance(),
                            systemConfig.getEncoding());

                    break;
                }
            }

            if (StringUtils.isEmpty(decryptedPassword)) {
                throw new SecurityException("No entries were found that matched the provided information");
            }

            System.out.println(decryptedPassword);
        } else if (commandLine.hasOption("encode")) {
            System.out.println(PasswordUtils.base64Encode((String) commandLine.getArgList().get(0)));
        } else if (commandLine.hasOption("decode")) {
            System.out.println(PasswordUtils.base64Decode((String) commandLine.getArgList().get(0)));
        }
    } catch (IOException iox) {
        ERROR_RECORDER.error(iox.getMessage(), iox);

        System.err.println("An error occurred during processing: " + iox.getMessage());
        System.exit(1);
    } catch (ParseException px) {
        ERROR_RECORDER.error(px.getMessage(), px);

        System.err.println("An error occurred during processing: " + px.getMessage());
        System.exit(1);
    } catch (SecurityException sx) {
        ERROR_RECORDER.error(sx.getMessage(), sx);

        System.err.println("An error occurred during processing: " + sx.getMessage());
        System.exit(1);
    } catch (SecurityServiceException ssx) {
        ERROR_RECORDER.error(ssx.getMessage(), ssx);
        System.exit(1);
    } finally {
        try {
            if (bReader != null) {
                bReader.close();
            }

            if (bWriter != null) {
                bReader.close();
            }
        } catch (IOException iox) {
        }
    }

    System.exit(0);
}

From source file:com.cloudera.csd.tools.codahale.AbstractCodahaleFixtureGenerator.java

public AbstractCodahaleFixtureGenerator(String[] args, Options options) throws Exception {
    Preconditions.checkNotNull(args);/*from  w w  w  . j a va  2s . c o  m*/
    Preconditions.checkNotNull(options);

    CommandLineParser parser = new DefaultParser();
    try {
        CommandLine cmdLine = parser.parse(options, args);
        if (!cmdLine.getArgList().isEmpty()) {
            throw new ParseException("Unexpected extra arguments: " + cmdLine.getArgList());
        }
        config = new MapConfiguration(Maps.<String, Object>newHashMap());
        for (Option option : cmdLine.getOptions()) {
            config.addProperty(option.getLongOpt(), option.getValue());
        }
    } catch (ParseException ex) {
        IOUtils.write("Error: " + ex.getMessage() + "\n", System.err);
        printUsageMessage(System.err, options);
        throw ex;
    }
}