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

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

Introduction

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

Prototype

public String toString() 

Source Link

Document

Returns a short description of this throwable.

Usage

From source file:org.polago.deployconf.DeployConfRunner.java

/**
 * Main entry point.//from w  w w . j a  v  a2 s. c o m
 *
 * @param args the runtime program arguments
 */
public static void main(String[] args) {
    Options options = new Options();

    Option help = new Option("h", "help", false, "Display usage information");
    options.addOption(help);

    Option version = new Option("v", "version", false, "Display version information and exit");
    options.addOption(version);

    Option interactive = new Option("i", "interactive", false, "Run in interactive mode");
    options.addOption(interactive);

    Option forceInteractive = new Option("I", "force-interactive", false,
            "Run in interactive mode and configure all tasks");
    options.addOption(forceInteractive);

    Option quiet = new Option("q", "quiet", false, "Suppress most messages");
    options.addOption(quiet);

    Option debug = new Option("d", "debug", false, "Print Debug Information");
    options.addOption(debug);

    boolean debugEnabled = false;

    Option repoDir = new Option("r", "repo", true,
            "Repository directory to use for storing deployment configs");
    options.addOption(repoDir);

    Option configFile = new Option("f", "deployment-config-file", true,
            "File to use for storing the deployment config");
    options.addOption(configFile);

    Option templatePath = new Option("t", "deployment-template-path", true,
            "Path to use for locating the deployment template in the " + "<INPUT> file. Default is '"
                    + DEFAULT_TEMPLATE_PATH + "'");
    options.addOption(templatePath);

    CommandLineParser parser = new DefaultParser();

    try {
        CommandLine cmd = parser.parse(options, args);
        ProjectProperties projectProperties = getProjectProperties();

        if (cmd.hasOption(version.getOpt())) {
            System.out.print(projectProperties.getName());
            System.out.print(" version ");
            System.out.println(projectProperties.getVersion());
            System.out.println(projectProperties.getCopyrightMessage());
            System.exit(0);
        }

        if (cmd.hasOption(help.getOpt())) {
            HelpFormatter formatter = new HelpFormatter();
            formatter.printHelp(projectProperties.getName() + " [OPTION]... <INPUT> <OUTPUT>",
                    projectProperties.getHelpHeader(), options, "");
            System.exit(0);
        }

        if (cmd.hasOption(debug.getOpt())) {
            logger.info("Activating Debug Logging");
            debugEnabled = true;
            setLogConfig("logback-debug.xml");
        } else if (cmd.hasOption(quiet.getOpt())) {
            setLogConfig("logback-quiet.xml");
        }

        RunMode mode = RunMode.NON_INTERACTIVE;
        if (cmd.hasOption(forceInteractive.getOpt())) {
            mode = RunMode.FORCE_INTERACTIVE;
        } else if (cmd.hasOption(interactive.getOpt())) {
            mode = RunMode.INTERACTIVE;
        }

        DeployConfRunner instance = new DeployConfRunner(mode);

        String envRepoDir = instance.getRepositoryDirectoryFromEnvironment();

        if (cmd.hasOption(repoDir.getOpt())) {
            String rd = cmd.getOptionValue(repoDir.getOpt());
            logger.debug("Using repository directory: {}", rd);
            instance.setRepositoryDirectory(rd);
        } else if (envRepoDir != null) {
            logger.debug("Using repository directory from environment {}: {}", ENV_DEPLOYCONF_REPO, envRepoDir);
            instance.setRepositoryDirectory(envRepoDir);
        } else {
            String rd = getDefaultRepository();
            instance.setRepositoryDirectory(rd);
            logger.debug("Using default repository directory: {}", rd);
        }
        Path repo = FileSystems.getDefault().getPath(instance.getRepositoryDirectory());
        if (!Files.exists(repo)) {
            Files.createDirectories(repo);
        } else if (!Files.isDirectory(repo)) {
            logger.error("Specified repository is not a directory: {}", repo);
            System.exit(1);
        }

        instance.setGroupManager(
                new FileSystemConfigGroupManager(Paths.get(instance.getRepositoryDirectory())));

        if (cmd.hasOption(configFile.getOpt())) {
            String f = cmd.getOptionValue(configFile.getOpt());
            logger.debug("Using explicit deployment file: {}", f);
            instance.setDeploymentConfigPath(FileSystems.getDefault().getPath(f));
        }

        if (cmd.hasOption(templatePath.getOpt())) {
            String path = cmd.getOptionValue(templatePath.getOpt());
            logger.debug("Using deployment template path: {}", path);
            instance.setDeploymentTemplatePath(path);
        }

        List<String> argList = cmd.getArgList();
        if (argList.size() != 2) {
            System.out.println("usage: " + projectProperties.getName() + " <INPUT> <OUTPUT>");
            System.exit(1);
        }
        System.exit(instance.run(argList.get(0), argList.get(1)));
    } catch (ParseException e) {
        logger.error("Command Line Parse Error: " + e.getMessage(), e);
        System.exit(1);
    } catch (Exception e) {
        String msg = "Internal Error: " + e.toString();
        if (!debugEnabled) {
            msg += "\n(use the -d option to print stacktraces)";
        }
        logger.error(msg, e);
        System.exit(2);
    }
}

From source file:org.servalproject.maps.mapfiletester.MapFileTester.java

/**
 * main method of the main class of the application
 * /*from  w  ww.j av  a 2s .  c  o  m*/
 * @param args an array of command line arguments
 */
public static void main(String[] args) {

    // parse the command line options
    CommandLineParser parser = new PosixParser();
    CommandLine cmd = null;
    try {
        cmd = parser.parse(createOptions(), args);
    } catch (org.apache.commons.cli.ParseException e) {
        // something bad happened so output help message
        printCliHelp("Error in parsing arguments:\n" + e.getMessage());
    }

    /*
     * get and test the command line arguments
     */

    // input path
    String inputPath = cmd.getOptionValue("input");

    if (StringUtils.isEmpty(inputPath)) {
        printCliHelp("Error: the path to the input file / directory is required");
    }

    if (FileUtils.isFileAccessible(inputPath) == false && FileUtils.isDirectoryAccessible(inputPath) == false) {
        printCliHelp("Error: the input file / directory is not accessible");
    }

    File inputFile = new File(inputPath);

    /*
     * output some text
     */
    System.out.println(APP_NAME);
    System.out.println("Version: " + APP_VERSION);
    System.out.println("More info: " + MORE_INFO);
    System.out.println("License info: " + LICENSE_INFO + "\n");

    // inform user of resources we'll be working on
    try {
        if (inputFile.isDirectory()) {
            System.out.println("Processing map files in directory: " + inputFile.getCanonicalPath());

            // test the files in the directory
            FileTester.testFilesInDir(inputFile);

        } else {

            // test the file
            FileTester.testFile(inputFile);
        }
    } catch (IOException e) {
        System.err.println("Unable to access file system resources.\n" + e.toString());
        System.exit(-1);
    }
}

From source file:org.servalproject.maps.osmbboxsplit.OsmBBoxSplit.java

/**
 * main method of the main class of the application
 * /*ww w .  ja  va2  s  .c om*/
 * @param args an array of command line arguments
 */
public static void main(String[] args) {

    // parse the command line options
    CommandLineParser parser = new PosixParser();
    CommandLine cmd = null;
    try {
        cmd = parser.parse(createOptions(), args);
    } catch (org.apache.commons.cli.ParseException e) {
        // something bad happened so output help message
        printCliHelp("Error in parsing arguments:\n" + e.getMessage());
    }

    /*
     * get and test the command line arguments
     */

    // input path
    String inputPath = cmd.getOptionValue("input");

    if (StringUtils.isEmpty(inputPath)) {
        printCliHelp("Error: the path to the input file / directory is required");
    }

    if (FileUtils.isFileAccessible(inputPath) == false && FileUtils.isDirectoryAccessible(inputPath) == false) {
        printCliHelp("Error: the input file / directory is not accessible");
    }

    File inputFile = new File(inputPath);

    // minimum file size
    String inputSize = cmd.getOptionValue("minsize");
    int minFileSize = MIN_FILE_SIZE;

    if (StringUtils.isEmpty(inputSize) == false) {
        try {
            minFileSize = Integer.parseInt(inputSize);
        } catch (NumberFormatException e) {
            printCliHelp("Error: the minimum file size must be a valid integer");
        }
    }

    // arbitrary file size in attempt to stop invalid data and 
    // unnecessarily processing small files
    if (minFileSize < 10) {
        printCliHelp("Error: the minimum file size must be greater than 10");
    }

    // output path && template file

    File outputDir = null;
    String scriptContents = null;

    String outputPath = cmd.getOptionValue("output");
    String templatePath = cmd.getOptionValue("template");

    if (StringUtils.isEmpty(outputPath) == false) {
        if (FileUtils.isDirectoryAccessible(outputPath) == false) {
            printCliHelp("Error: the output directory is not accessible");
        }

        if (StringUtils.isEmpty(templatePath)) {
            printCliHelp("Error: the template must be specified when the output pararameter used");
        }

        if (FileUtils.isFileAccessible(templatePath) == false) {
            printCliHelp("Error: the osmosis script template file is not accesible");
        }

        outputDir = new File(outputPath);

        // read the contents of the template file
        try {
            scriptContents = org.apache.commons.io.FileUtils.readFileToString(new File(templatePath));
        } catch (IOException e1) {
            System.err.println("ERROR: unable to read the template file");
            System.exit(-1);
        }
    }

    // ignore list path
    ignoreList = new ArrayList<String>();

    String ignorePath = cmd.getOptionValue("ignore");

    if (StringUtils.isEmpty(ignorePath) == false) {

        if (FileUtils.isFileAccessible(ignorePath) == false) {
            printCliHelp("Error: the ignore list file is not accessible");
        }

        // read the contents of the ignore list file
        try {
            ignoreList = (ArrayList<String>) org.apache.commons.io.FileUtils.readLines(new File(ignorePath));

            // strip out any comment lines
            for (int i = 0; i < ignoreList.size(); i++) {
                if (ignoreList.get(i).startsWith("#")) {
                    ignoreList.remove(i);
                    i--;
                }
            }
        } catch (IOException e) {
            System.err.println("ERROR: unable to read the ignore list file");
            System.exit(-1);
        }

    }

    /*
     * output some text
     */
    System.out.println(APP_NAME);
    System.out.println("Version: " + APP_VERSION);
    System.out.println("More info: " + MORE_INFO);
    System.out.println("License info: " + LICENSE_INFO + "\n");

    // inform user of resources we'll be working on
    try {
        if (inputFile.isDirectory()) {
            System.out.println("Processing OSM PBF files in directory: " + inputFile.getCanonicalPath());

            // test the files in the directory
            BBoxSplit.readFilesInDir(inputFile, outputDir, scriptContents, minFileSize);

        } else {

            // test the file
            BBoxSplit.readFile(inputFile, outputDir, scriptContents, minFileSize);
        }
    } catch (IOException e) {
        System.err.println("Unable to access file system resources.\n" + e.toString());
        System.exit(-1);
    }
}

From source file:org.servalproject.maps.osmpbfmetadata.OsmPbfMetadata.java

/**
 * main method of the main class of the application
 * /*from w w  w  . java  2  s  .  com*/
 * @param args an array of command line arguments
 */
public static void main(String[] args) {

    // parse the command line options
    CommandLineParser parser = new PosixParser();
    CommandLine cmd = null;
    try {
        cmd = parser.parse(createOptions(), args);
    } catch (org.apache.commons.cli.ParseException e) {
        // something bad happened so output help message
        printCliHelp("Error in parsing arguments:\n" + e.getMessage());
    }

    /*
     * get and test the command line arguments
     */

    // input path
    String inputPath = cmd.getOptionValue("input");

    if (StringUtils.isEmpty(inputPath)) {
        printCliHelp("Error: the path to the input file / directory is required");
    }

    if (FileUtils.isFileAccessible(inputPath) == false && FileUtils.isDirectoryAccessible(inputPath) == false) {
        printCliHelp("Error: the input file / directory is not accessible");
    }

    File inputFile = new File(inputPath);

    /*
     * output some text
     */
    System.out.println(APP_NAME);
    System.out.println("Version: " + APP_VERSION);
    System.out.println("More info: " + MORE_INFO);
    System.out.println("License info: " + LICENSE_INFO + "\n");

    // inform user of resources we'll be working on
    try {
        if (inputFile.isDirectory()) {
            System.out.println("Processing OSM PBF files in directory: " + inputFile.getCanonicalPath());

            // test the files in the directory
            OsmPbfReader.readFilesInDir(inputFile);

        } else {

            // test the file
            OsmPbfReader.readFile(inputFile);
        }
    } catch (IOException e) {
        System.err.println("Unable to access file system resources.\n" + e.toString());
        System.exit(-1);
    }

}

From source file:org.springframework.ldap.odm.tools.SchemaToJava.java

public static void main(String[] argv) {
    CommandLineParser parser = new PosixParser();
    CommandLine cmd = null;//from w ww  . j  a  v a  2s .  c  om

    // Parse out the command line options
    try {
        cmd = parser.parse(DEFAULT_OPTIONS, argv);
    } catch (ParseException e) {
        error(e.toString());
    }

    // If the help flag is specified ignore other flags, print a usage message and exit
    if (cmd.hasOption(Flag.HELP.getShort())) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp(120, SchemaToJava.class.getSimpleName(), null, DEFAULT_OPTIONS, null, true);
        System.exit(0);
    }

    // Class name flag
    String className = cmd.getOptionValue(Flag.CLASS.getShort());
    if (className == null) {
        error("You must specify the name of a Java class to create");
    }

    // Package name flag
    String packageName = cmd.getOptionValue(Flag.PACKAGE.getShort());
    if (packageName == null) {
        error("You must specifiy a package name");
    }

    // Output base directory 
    String outputDir = cmd.getOptionValue(Flag.OUTPUT_DIR.getShort(), ".");
    File outputFile = null;
    try {
        outputFile = makeOutputFile(outputDir, packageName, className);
    } catch (IOException e) {
        error(e.toString());
    }

    // Get the flags we need to bind to the directory
    String url = cmd.getOptionValue(Flag.URL.getShort(), DEFAULT_URL);
    String user = cmd.getOptionValue(Flag.USERNAME.getShort());
    String pass = cmd.getOptionValue(Flag.PASSWORD.getShort());

    // Parse out object classes
    String objectClassesFlag = cmd.getOptionValue(Flag.OBJECTCLASS.getShort());
    if (objectClassesFlag == null) {
        error("You must specificy a package name");
    }
    Set<String> objectClasses = parseObjectClassesFlag(objectClassesFlag);
    if (objectClasses.size() == 0) {
        error("You must specificy a package name");
    }

    // Look for the optional syntax to Java class mapping file
    String syntaxMapFileName = cmd.getOptionValue(Flag.SYNTAX_MAP.getShort(), null);
    SyntaxToJavaClass syntaxToJavaClass = new SyntaxToJavaClass(new HashMap<String, String>());
    if (syntaxMapFileName != null) {
        File syntaxMapFile = new File(syntaxMapFileName);
        if (syntaxMapFile.canRead()) {
            try {
                syntaxToJavaClass = new SyntaxToJavaClass(readSyntaxMap(syntaxMapFile));
            } catch (IOException e) {
                error(String.format("Error reading syntax map file %1$s - %2$s",
                        syntaxMapFile.getAbsolutePath(), e.toString()));
            }
        } else {
            error(String.format("Cannot read syntax map file %s$1", syntaxMapFile.getAbsolutePath()));
        }
    }

    // Read binary mapping file
    URL binarySetUrl = DEFAULT_LOADER_CLASS.getResource(BINARY_FILE);
    if (binarySetUrl == null) {
        error(String.format("Can't locatate binary mappings file %1$s", BINARY_FILE));
    }
    File binarySetFile = new File(binarySetUrl.getFile());
    if (!binarySetFile.canRead()) {
        error(String.format("Can't read from binary mappings file %1$s", BINARY_FILE));
    }
    Set<String> binarySet = null;
    try {
        binarySet = readBinarySet(binarySetFile);
    } catch (IOException e) {
        error(String.format("Error reading binary set file %1$s - %2$s", binarySetFile.getAbsolutePath(), e));
    }

    // Read schema from the directory
    ObjectSchema schema = null;
    try {
        schema = readSchema(url, user, pass, syntaxToJavaClass, binarySet, objectClasses);
    } catch (NamingException ne) {
        error(String.format("Error processing schema - %1$s", ne));
    } catch (ClassNotFoundException cnfe) {
        error(String.format("Error processing schema - %1$s", cnfe));
    }

    // Work out what imports we need
    Set<SyntaxToJavaClass.ClassInfo> imports = new HashSet<SyntaxToJavaClass.ClassInfo>();
    for (AttributeSchema attributeSchema : schema.getMay()) {
        SyntaxToJavaClass.ClassInfo classInfo = syntaxToJavaClass.getClassInfo(attributeSchema.getSyntax());
        if (classInfo != null) {
            String classPackageName = classInfo.getPackageName();
            if (classPackageName != null && classPackageName.length() > 0) {
                imports.add(classInfo);
            }
        }
    }

    // Create the Java code
    try {
        createCode(packageName, className, schema, imports, outputFile);
    } catch (TemplateException te) {
        error(String.format("Error generating code - %1$s", te.toString()));
    } catch (IOException ioe) {
        error(String.format("Error generatign code - %1$s", ioe.toString()));
    }
}

From source file:org.wikidata.wdtk.client.ClientConfiguration.java

/**
 * This function interprets the arguments of the main function. By doing
 * this it will set flags for the dump generation. See in the help text for
 * more specific information about the options.
 * //from  w w w .j av  a2s  .  com
 * @param args
 *            array of arguments from the main function.
 * @return list of {@link DumpProcessingOutputAction}
 */
private List<DumpProcessingAction> handleArguments(String[] args) {
    CommandLine cmd;
    CommandLineParser parser = new GnuParser();

    try {
        cmd = parser.parse(options, args);
    } catch (ParseException e) {
        logger.error("Failed to parse arguments: " + e.getMessage());
        return Collections.<DumpProcessingAction>emptyList();
    }

    // Stop processing if a help text is to be printed:
    if ((cmd.hasOption(CMD_OPTION_HELP)) || (args.length == 0)) {
        return Collections.<DumpProcessingAction>emptyList();
    }

    List<DumpProcessingAction> configuration = new ArrayList<>();

    handleGlobalArguments(cmd);

    if (cmd.hasOption(CMD_OPTION_ACTION)) {
        DumpProcessingAction action = handleActionArguments(cmd);
        if (action != null) {
            configuration.add(action);
        }
    }

    if (cmd.hasOption(CMD_OPTION_CONFIG_FILE)) {
        try {
            List<DumpProcessingAction> configFile = readConfigFile(cmd.getOptionValue(CMD_OPTION_CONFIG_FILE));
            configuration.addAll(configFile);
        } catch (IOException e) {
            logger.error("Failed to read configuration file \"" + cmd.getOptionValue(CMD_OPTION_CONFIG_FILE)
                    + "\": " + e.toString());
        }

    }

    return configuration;

}

From source file:speedith.Main.java

/**
 * The main entry point to Speedith. <p>Parses the arguments and starts
 * Speedith either in interactive or batch mode.</p>
 *
 * @param args the Command line arguments to Speedith.
 *//*w w w  .j a va 2 s  .c o  m*/
public static void main(String[] args) {
    CliOptions clargs = new CliOptions();
    try {
        clargs.parse(args);
        // Did the user specify any of the 'print help' options? If so, just
        // print the info and exit.
        // Otherwise startup Speedith.
        if (clargs.isHelp()) {
            clargs.printHelp();
        } else if (clargs.isListOutputFormats()) {
            printKnownFormats();
        } else if (clargs.isListInferenceRules()) {
            printKnownInferenceRules();
        } else if (clargs.isBatchMode()) {
            // ---- Starting up Speedith
            // Did the user provide a spider diagram to Speedith?
            String formula = clargs.getSpiderDiagram();
            SpiderDiagram readSpiderDiagram = (formula == null) ? null
                    : SpiderDiagramsReader.readSpiderDiagram(formula);
            // Did the user specify an output format?
            String outputFormat = clargs.getOutputFormat();
            // Now print out the formula in the specified format
            if (readSpiderDiagram != null) {
                // Get the inference rule (and all of its possible arguments):
                String ir = clargs.getInferenceRule();
                if (ir == null || ir.isEmpty()) {
                    throw new IllegalArgumentException(i18n("APP_NO_INFERENCE_RULE"));
                }

                String spider = clargs.getSpider();
                int subDiagramIndex = clargs.getSubDiagramIndex();
                Region region = clargs.getRegion();
                InferenceRule<? extends RuleArg> inferenceRule = InferenceRules.getInferenceRule(ir);

                if (inferenceRule == null) {
                    throw new IllegalArgumentException(i18n("APP_UNKNOWN_INFERENCE_RULE"));
                }

                RuleArg ruleArg;
                if (subDiagramIndex >= 0) {
                    if (!Strings.isNullOrEmpty(spider)) {
                        if (region != null) {
                            ruleArg = new SpiderRegionArg(0, subDiagramIndex, spider, region);
                        } else {
                            ruleArg = new SpiderArg(0, subDiagramIndex, spider);
                        }
                    } else {
                        ruleArg = new SubDiagramIndexArg(0, subDiagramIndex);
                    }
                } else {
                    throw new IllegalArgumentException(i18n("MAIN_SUBDIAGRAM_INDEX_NEGATIVE"));
                }
                RuleApplicationResult subGoals = inferenceRule.apply(ruleArg,
                        new Goals(Arrays.asList(readSpiderDiagram)));

                if (subGoals != null && subGoals.getGoals() != null
                        && subGoals.getGoals().getGoalsCount() > 0) {
                    readSpiderDiagram = subGoals.getGoals().getGoalAt(0);
                    SDExporter exporter = SDExporting.getExporter(outputFormat,
                            clargs.getOutputFormatArguments());
                    if (exporter == null) {
                        throw new IllegalArgumentException(i18n("APP_UNKNOWN_EXPORTER"));
                    } else {
                        exporter.exportTo(readSpiderDiagram, System.out);
                    }
                }
                System.out.println();
            }
        } else {
            // We are not running in the batch mode. Ignore all arguments
            // and show the main form.
            SpeedithMainForm.main(args);
        }
    } catch (ParseException ex) {
        // Report why the parsing of the command line arguments failed and 
        // print the help message (both to the error output).
        log(Level.SEVERE, i18n("ERR_CLI_PARSE_FAILED", ex.getLocalizedMessage()), ex);
        System.err.println(i18n("ERR_CLI_PARSE_FAILED", ex.getLocalizedMessage()));
        clargs.printHelp(System.err);
        System.exit(1);
    } catch (ReadingException rex) {
        // The spider diagram formula could not be read successfully.
        log(Level.SEVERE, i18n("ERR_READING_FORMULA", rex.getLocalizedMessage()), rex);
        System.out.println(i18n("ERR_READING_FORMULA", rex.getLocalizedMessage()));
        System.exit(1);
    } catch (Exception ex) {
        log(Level.SEVERE, ex.getLocalizedMessage(), ex);
        System.out.println(ex.toString());
        System.exit(1);
    }
}