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

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

Introduction

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

Prototype

public void printStackTrace() 

Source Link

Document

Prints this throwable and its backtrace to the standard error stream.

Usage

From source file:org.jhub1.agent.run.cli.ParamsMain.java

public void parse(String[] args) {
    try {//w ww. ja  v a 2 s.  c om
        initParser(args);
    } catch (ParseException e) {
        System.out.println("\n************************");
        System.out.println("The parameter(s) not recognized or other parsing problem!");
        System.out.println("************************");
        e.printStackTrace();
    }
    /*      if (cmdMain.hasOption("p")) {
             String provide = cmdMain.getOptionValue("p");
             if (StringUtils.isNotBlank(provide)) {
    if (provide.equalsIgnoreCase(SAMPLE_FILE)) {
       getRemainingParams(SAMPLE_FILE, args);
    } else if (provide.equalsIgnoreCase(SAMPLE_UDP)) {
       getRemainingParams(SAMPLE_UDP, args);
    }
             }
          }*/
}

From source file:org.kaazing.gateway.server.GatewayCommandLineProcessor.java

private void launchGateway(String[] args, Properties properties) {
    CommandLine cmd = null;/*from ww  w .j  av  a 2  s.  c om*/
    Options options = createOptions();

    try {
        Parser parser = new PosixParser();
        cmd = parser.parse(options, args);
    } catch (ParseException ex) {
        printCliHelp("There was a problem with a command-line argument:\n" + ex.getMessage(), options, cmd);
        return;
    }

    String[] nonProcessedArgs = cmd.getArgs();
    if (nonProcessedArgs != null && nonProcessedArgs.length > 0) {
        System.out.println("There was a problem with the command-line arguments.");
        System.out.println("One or more unknown arguments were not processed:");
        for (String nonProcessedArg : nonProcessedArgs) {
            System.out.println("   " + nonProcessedArg);
        }
        printCliHelp(null, options, cmd);
        return;
    }

    if (cmd.hasOption(HELP_ARG)) {
        printCliHelp(null, options, cmd);
        return;
    }

    // get the various options
    String config = cmd.getOptionValue(CONFIG_ARG);
    if (config != null) {
        properties.setProperty(Gateway.GATEWAY_CONFIG_PROPERTY, config);
    }

    // Because Gateway already has checking for defaults (and they default
    // to directories under $GATEWAY_HOME), we don't actually have to do anything
    // here (we do in the InstalledLinux case.)
    final Gateway gateway = GatewayFactory.createGateway();
    gateway.setProperties(properties);

    Runtime.getRuntime().addShutdownHook(new Thread() {
        @Override
        public void run() {
            try {
                gateway.destroy();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    });

    try {
        gateway.launch();
    } catch (Exception ex) {
        // Log the exception then exit. It's possible log4j won't be initialized by the time
        // the exception occurred, so log and print stacktrace (to System.err)
        LOGGER.error("Gateway failed to launch", ex);
        ex.printStackTrace();
        System.exit(-1);
    }
}

From source file:org.kaazing.gateway.server.GatewayCommandProcessor.java

public void launchGateway(String[] args, Properties properties) {
    CommandLine cmd = null;/*from ww  w  . j a  v a2s  .  c  om*/
    Options options = createOptions();

    try {
        Parser parser = new PosixParser();
        cmd = parser.parse(options, args);
    } catch (ParseException ex) {
        printCliHelp("There was a problem with a command-line argument:\n" + ex.getMessage(), options);
        return;
    }

    String[] nonProcessedArgs = cmd.getArgs();
    if (nonProcessedArgs != null && nonProcessedArgs.length > 0) {
        System.out.println("There was a problem with the command-line arguments.");
        System.out.println("One or more unknown arguments were not processed:");
        for (String nonProcessedArg : nonProcessedArgs) {
            System.out.println("   " + nonProcessedArg);
        }
        printCliHelp(null, options);
        return;
    }

    if (cmd.hasOption("help")) {
        printCliHelp(null, options);
        return;
    }

    // get the various options
    String config = cmd.getOptionValue("config");
    if (config != null) {
        properties.setProperty(Gateway.GATEWAY_CONFIG_PROPERTY, config);
    }

    // Because Gateway already has checking for defaults (and they default
    // to directories under $GATEWAY_HOME), we don't actually have to do anything
    // here (we do in the InstalledLinux case.)
    final Gateway gateway = GatewayFactory.createGateway();
    gateway.setProperties(properties);

    Runtime.getRuntime().addShutdownHook(new Thread() {
        public void run() {
            try {
                gateway.destroy();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    });

    try {
        gateway.launch();
    } catch (Exception ex) {
        // Log the exception then exit.  It's possible log4j won't be initialized by the time
        // the exception occurred, so log and print stacktrace (to System.err)
        LOGGER.error("Gateway failed to launch", ex);
        ex.printStackTrace();
        System.exit(-1);
    }
}

From source file:org.kie.workbench.common.services.backend.compiler.MavenParameterTest.java

@Test
public void cliParameters() {
    String settingsXml = "src/test/settings.xml";
    File file = new File(settingsXml);
    String settingPath = "-s" + file.getAbsolutePath();

    for (int i = 0; i < 50; i++) {
        new Thread(() -> {
            final CLIManager manager = new CLIManager();

            final String[] values = new String[] { "compile", settingPath,
                    "-Dcompilation.ID=eb678741-0b34-409f-903e-addc083ab2aa", "dependency:build-classpath",
                    "-Dmdep.outputFile=module.cpath" };

            try {
                final CommandLine commandLine = manager.parse(values);
                System.out.println(commandLine.getArgList());
                assertThat(commandLine.getArgs().length).isEqualTo(2);
            } catch (ParseException e) {
                e.printStackTrace();
            }//from ww w.j a  va 2s.  c  o m
        }).start();
    }
}

From source file:org.lab41.graphlab.twill.Main.java

public static void main(String[] args) {
    CommandLineParser parser = new GnuParser();

    Options options = new Options();

    options.addOption("h", "help", false, "print this message");
    options.addOption("i", "instances", true, "number of instances");
    options.addOption("t", "threads", true, "number of threads");
    options.addOption("debug", false, "enable debugging");

    int instanceCount = 1;
    int virtualCores = 1;
    boolean debug = false;

    try {/* w ww . j av a  2  s . c  o m*/
        CommandLine line = parser.parse(options, args, true);

        if (line.hasOption("help")) {
            printHelp(options);
            System.exit(0);
        }

        if (line.hasOption("instances")) {
            String option = line.getOptionValue("instances");
            instanceCount = Integer.parseInt(option);
        }

        if (line.hasOption("threads")) {
            String option = line.getOptionValue("threads");
            virtualCores = Integer.parseInt(option);
        }

        if (line.hasOption("debug")) {
            debug = true;
        }

        args = line.getArgs();

    } catch (ParseException e) {
        System.out.println("error: " + e);
        System.exit(1);
    }

    if (args.length != 5) {
        printHelp(options);
        System.exit(1);
    }

    String zkStr = args[0];
    GraphLabRunnable.Arguments arguments = GraphLabRunnable.Arguments
            .fromArray(Arrays.copyOfRange(args, 1, args.length));

    final TwillRunnerService twillRunner = new YarnTwillRunnerService(new YarnConfiguration(), zkStr);
    twillRunner.startAndWait();

    ResourceSpecification resources = ResourceSpecification.Builder.with().setVirtualCores(virtualCores)
            .setMemory(512, ResourceSpecification.SizeUnit.MEGA).setInstances(instanceCount).build();

    String runnableName = "GraphLabRunnable";

    TwillPreparer preparer = twillRunner.prepare(new GraphLabRunnable(), resources)
            .withArguments(runnableName, arguments.toArray())
            .addLogHandler(new PrinterLogHandler(new PrintWriter(System.out, true)));

    if (debug) {
        preparer.enableDebugging(true);
    }

    final TwillController controller = preparer.start();

    Runtime.getRuntime().addShutdownHook(new Thread() {
        @Override
        public void run() {
            LOG.debug("shutting down");
            controller.stopAndWait();
            twillRunner.stopAndWait();
        }
    });

    try {
        /*
        // Try to catch the debug port.
        if (debug) {
        waitForDebugPort(controller, runnableName, 300);
        }
        */

        Services.getCompletionFuture(controller).get();
    } catch (InterruptedException | ExecutionException e) {
        e.printStackTrace();
    }

    LOG.debug("after shutting down");
}

From source file:org.LexGrid.LexBIG.admin.LoadManifest.java

/**
 * Primary entry point for the program.//from w w w.  j ava  2s.  c  om
 * 
 * @throws Exception
 */
public void run(String[] args) throws Exception {
    synchronized (ResourceManager.instance()) {

        // Parse the command line ...
        CommandLine cl = null;
        Options options = getCommandOptions();
        try {
            cl = new BasicParser().parse(options, args);
        } catch (ParseException e) {
            Util.displayCommandOptions("LoadManifest", options,
                    "\n LoadManifest -u \"urn:oid:2.16.840.1.113883.3.26.1.1\" -v \"05.09e\" -mf \"file://path//to//manifest.xml\""
                            + "\n LoadManifest -mf \"file://path//to//manifest.xml\"",
                    e);
            Util.displayMessage(Util.getPromptForSchemeHelp());
            return;
        }

        // Interpret provided values ...
        String urn = cl.getOptionValue("u");
        String ver = cl.getOptionValue("v");

        String manifest = cl.getOptionValue("mf");
        manifest = manifest.trim();

        try {
            getReader(new File(manifest).toURI());
        } catch (Exception e) {
            Util.displayMessage("Supplied manifest file is invalid or do not exist.");
            return;
        }

        CodingSchemeSummary css = null;

        // Find in list of registered vocabularies ...
        if (urn != null && ver != null) {
            urn = urn.trim();
            ver = ver.trim();

            LexBIGService lbs = LexBIGServiceImpl.defaultInstance();
            Enumeration<? extends CodingSchemeRendering> schemes = lbs.getSupportedCodingSchemes()
                    .enumerateCodingSchemeRendering();
            while (schemes.hasMoreElements() && css == null) {
                CodingSchemeSummary summary = schemes.nextElement().getCodingSchemeSummary();
                if (urn.equalsIgnoreCase(summary.getCodingSchemeURI())
                        && ver.equalsIgnoreCase(summary.getRepresentsVersion()))
                    css = summary;
            }
        }

        // Found it? If not, prompt...
        if (css == null) {
            if (urn != null || ver != null) {
                Util.displayMessage("No matching coding scheme was found for the given URN or version.");
                Util.displayMessage("");
            }
            css = Util.promptForCodeSystem();
            if (css == null)
                return;
        }

        LexBIGServiceManager lbsm = LexBIGServiceImpl.defaultInstance().getServiceManager(new Object());

        MetaData_Loader mdLoader = (MetaData_Loader) lbsm.getLoader(METADATALOADER);
        AbsoluteCodingSchemeVersionReference codingSchemeURNVersion = new AbsoluteCodingSchemeVersionReference();
        codingSchemeURNVersion.setCodingSchemeURN(css.getCodingSchemeURI());
        codingSchemeURNVersion.setCodingSchemeVersion(css.getRepresentsVersion());

        try {
            mdLoader.loadLexGridManifest(new File(manifest).toURI(), codingSchemeURNVersion, false, true);
            Util.displayMessage("Manifest data applied successfully on the codingscheme.");
        } catch (LBException e) {
            Util.displayMessage("Load failed: " + e.getMessage());
            e.printStackTrace();
        }

    }
}

From source file:org.lilyproject.runtime.cli.LilyRuntimeCli.java

private void run(String[] args) throws Exception {
    // Forward JDK logging to SLF4J
    LogManager.getLogManager().reset();
    LogManager.getLogManager().getLogger("").addHandler(new SLF4JBridgeHandler());
    LogManager.getLogManager().getLogger("").setLevel(Level.ALL);

    Options cliOptions = new Options();

    Option confDirsOption = OptionBuilder.withArgName("confdir").hasArg()
            .withDescription("The Lily runtime configuration directory. Can be multiple paths separated by "
                    + File.pathSeparator)
            .withLongOpt("confdir").create('c');
    cliOptions.addOption(confDirsOption);

    Option repositoryLocationOption = OptionBuilder.withArgName("maven-repo-path").hasArg()
            .withDescription(//from  ww  w  .jav  a 2  s  .  c  om
                    "Location of the (Maven-style) artifact repository. Use comma-separated entries to "
                            + "specify multiple locations which will be searched in the order as specified.")
            .withLongOpt("repository").create('r');
    cliOptions.addOption(repositoryLocationOption);

    Option disabledModulesOption = OptionBuilder.withArgName("mod-id1,mod-id2,...").hasArg()
            .withDescription("Comma-separated list of modules that should be disabled.")
            .withLongOpt("disable-modules").create('i');
    cliOptions.addOption(disabledModulesOption);

    Option disableClassSharingOption = OptionBuilder
            .withDescription("Disable optional sharing of classes between modules")
            .withLongOpt("disable-class-sharing").create('d');
    cliOptions.addOption(disableClassSharingOption);

    Option consoleLoggingOption = OptionBuilder.withArgName("loglevel").hasArg()
            .withDescription("Enable logging to console for the root log category with specified loglevel "
                    + "(debug, info, warn, error)")
            .withLongOpt("console-logging").create('l');
    cliOptions.addOption(consoleLoggingOption);

    Option consoleLogCatOption = OptionBuilder.withArgName("logcategory").hasArg()
            .withDescription("Enable console logging only for this category")
            .withLongOpt("console-log-category").create('m');
    cliOptions.addOption(consoleLogCatOption);

    Option logConfigurationOption = OptionBuilder.withArgName("config").hasArg()
            .withDescription("Log4j configuration file (properties or .xml)").withLongOpt("log-configuration")
            .create("o");
    cliOptions.addOption(logConfigurationOption);

    Option classLoadingLoggingOption = OptionBuilder
            .withDescription("Print information about the classloader setup (at startup).")
            .withLongOpt("classloader-log").create("z");
    cliOptions.addOption(classLoadingLoggingOption);

    Option verboseOption = OptionBuilder.withDescription("Prints lots of information.").withLongOpt("verbose")
            .create("v");
    cliOptions.addOption(verboseOption);

    Option quietOption = OptionBuilder.withDescription("Suppress normal output.").withLongOpt("quiet")
            .create("q");
    cliOptions.addOption(quietOption);

    Option sourceLocationsOption = OptionBuilder.withArgName("sourcelocationfile").hasArg()
            .withDescription(
                    "Path to property file containing alternate source location directory for artifacts.")
            .withLongOpt("source-locations").create("s");
    cliOptions.addOption(sourceLocationsOption);

    Option modeOption = OptionBuilder.withArgName("modename").hasArg()
            .withDescription("The runtime mode: prototype, production").withLongOpt("runtime-mode").create("p");
    cliOptions.addOption(modeOption);

    Option versionOption = OptionBuilder.withDescription(
            "Don't start the service, only dump the version info string for the module defined with -Dlilyruntime.info.module")
            .withLongOpt("version").create("V");
    cliOptions.addOption(versionOption);

    Option helpOption = new Option("h", "help", false, "Shows help");
    cliOptions.addOption(helpOption);

    CommandLineParser parser = new PosixParser();
    CommandLine cmd = null;
    boolean showHelp = false;
    try {
        cmd = parser.parse(cliOptions, args);
    } catch (ParseException e) {
        showHelp = true;
    }

    if (showHelp || cmd.hasOption(helpOption.getOpt())) {
        printHelp(cliOptions);
        System.exit(1);
    }

    Logging.setupLogging(cmd.hasOption(verboseOption.getOpt()), cmd.hasOption(quietOption.getOpt()),
            cmd.hasOption(classLoadingLoggingOption.getOpt()),
            cmd.getOptionValue(logConfigurationOption.getOpt()),
            cmd.getOptionValue(consoleLoggingOption.getOpt()),
            cmd.getOptionValue(consoleLogCatOption.getOpt()));

    try {
        Logging.registerLog4jMBeans();
    } catch (JMException e) {
        infolog.error("Unable to register log4j JMX control", e);
    }

    infolog.info("Starting the Lily Runtime.");

    List<File> confDirs = new ArrayList<File>();

    if (!cmd.hasOption(confDirsOption.getOpt())) {
        File confDir = new File(DEFAULT_CONF_DIR).getAbsoluteFile();
        if (!confDir.exists()) {
            System.out.println("Default configuration directory " + DEFAULT_CONF_DIR
                    + " not found in current directory: " + confDir.getAbsolutePath());
            System.out
                    .println("To specify another location, use the -" + confDirsOption.getOpt() + " argument");
            System.exit(1);
        }
        confDirs.add(confDir);
    } else {
        String confPathArg = cmd.getOptionValue(confDirsOption.getOpt());
        String[] confPaths = confPathArg.split(File.pathSeparator);
        for (String confPath : confPaths) {
            confPath = confPath.trim();
            if (confPath.length() == 0) {
                continue;
            }
            File confDir = new File(confPath);
            if (!confDir.exists()) {
                System.out.println(
                        "Specified configuration directory does not exist: " + confDir.getAbsolutePath());
                System.exit(1);
            }
            confDirs.add(confDir);
        }
    }

    ArtifactRepository artifactRepository;

    if (cmd.hasOption(repositoryLocationOption.getOpt())) {
        artifactRepository = new ChainedMaven2StyleArtifactRepository(
                cmd.getOptionValue(repositoryLocationOption.getOpt()));
    } else {
        File maven2Repository = findLocalMavenRepository();
        infolog.info("Using local Maven repository at " + maven2Repository.getAbsolutePath());
        artifactRepository = new Maven2StyleArtifactRepository(maven2Repository);
    }

    Set<String> disabledModuleIds = getDisabledModuleIds(cmd.getOptionValue(disabledModulesOption.getOpt()));

    SourceLocations sourceLocations;
    if (cmd.hasOption(sourceLocationsOption.getOpt())) {
        File file = new File(cmd.getOptionValue(sourceLocationsOption.getOpt())).getAbsoluteFile();
        if (!file.exists()) {
            System.out.println(
                    "The specified source locations property file does not exist: " + file.getAbsolutePath());
            System.exit(1);
        }

        InputStream is = null;
        try {
            is = new FileInputStream(file);
            sourceLocations = new SourceLocations(is, file.getParent());
        } catch (Throwable t) {
            throw new LilyRTException("Problem reading source locations property file.", t);
        } finally {
            IOUtils.closeQuietly(is);
        }
    } else {
        sourceLocations = new SourceLocations();
    }

    LilyRuntimeSettings settings = new LilyRuntimeSettings();
    settings.setConfManager(new ConfManagerImpl(confDirs));
    settings.setDisabledModuleIds(disabledModuleIds);
    settings.setRepository(artifactRepository);
    settings.setSourceLocations(sourceLocations);
    settings.setEnableArtifactSharing(!cmd.hasOption(disableClassSharingOption.getOpt()));

    LilyRuntime runtime = new LilyRuntime(settings);

    if (cmd.hasOption(modeOption.getOpt())) {
        String optionValue = cmd.getOptionValue(modeOption.getOpt());
        Mode mode = Mode.byName(optionValue);
        runtime.setMode(mode);
    }

    if (cmd.hasOption(versionOption.getOpt())) {
        System.out.println(runtime.buildModel().moduleInfo(System.getProperty("lilyruntime.info.module")));
        System.exit(0);
    }

    try {
        runtime.start();
        Runtime.getRuntime().addShutdownHook(new Thread(new ShutdownHandler(runtime)));
        printStartedMessage();
    } catch (Throwable e) {
        e.printStackTrace();
        System.err.println("Startup failed. Will try to shutdown and exit.");
        try {
            runtime.stop();
        } finally {
            System.exit(1);
        }
    }

}

From source file:org.mili.tools.jsql.JSql.java

/**
 * @param args//  w  w  w .j a v  a 2 s  .  c  om
 */
public static void main(String[] args) {
    Options options = new Options();
    options.addOption("help", false, "print this message.");
    options.addOption("version", false, "print version.");
    options.addOption("profile", true, "the database profile.");
    CommandLineParser parser = new PosixParser();
    CommandLine cmd = null;
    try {
        cmd = parser.parse(options, args);
    } catch (ParseException e) {
        e.printStackTrace();
        System.exit(1);
    }
    if (cmd.hasOption("help")) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp(JSql.class.getName(), options);
        return;
    } else if (cmd.hasOption("version")) {
        System.out.println("1.0");
        return;
    }
    String profile = "";
    if (cmd.hasOption("profile")) {
        profile = cmd.getOptionValue("profile");
    } else {
        throw new IllegalArgumentException("No profile given !");
    }
    JSql sql = new JSql(profile);
    try {
        sql.start();
    } catch (Exception e) {
        System.out.println(new File("").getAbsolutePath());
        e.printStackTrace();
        System.exit(1);
    } finally {
        try {
            sql.stop();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}

From source file:org.mitre.scap.xccdf.XCCDFInterpreter.java

/**
 * @param args the command line arguments
 *///from  w  ww  .  ja v  a2  s .  c  om
public static void main(String[] args) throws IOException, XmlException, URISyntaxException {
    XCCDFInterpreter.generateExecutionTimeStr();
    BuildProperties buildProperties = BuildProperties.getInstance();

    //System.out.println();
    //System.out.println( buildProperties.getApplicationName()+" v"+ buildProperties.getApplicationVersion()+" build "+buildProperties.getApplicationBuild());
    //System.out.println("--------------------");
    //outputOsProperties();
    //System.out.println("--------------------");
    //System.out.println();

    // Define the commandline options
    @SuppressWarnings("static-access")
    Option help = OptionBuilder.withDescription("display usage").withLongOpt("help").create('h');

    @SuppressWarnings("static-access")
    Option workingDir = OptionBuilder.hasArg().withArgName("FILE").withDescription("use result directory FILE")
            .withLongOpt("result-dir").create('R');

    @SuppressWarnings("static-access")
    Option xccdfResultFilename = OptionBuilder.hasArg().withArgName("FILENAME")
            .withDescription("use result filename FILENAME").withLongOpt("xccdf-result-filename").create("F");

    @SuppressWarnings("static-access")
    Option nocpe = OptionBuilder.withDescription("do not process CPE references").withLongOpt("no-cpe")
            .create();

    @SuppressWarnings("static-access")
    Option noresults = OptionBuilder.withDescription("do not display rule results").withLongOpt("no-results")
            .create();

    @SuppressWarnings("static-access")
    Option nocheck = OptionBuilder.withDescription("do not process checks").withLongOpt("no-check").create();

    @SuppressWarnings("static-access")
    Option profile = OptionBuilder.hasArg().withArgName("PROFILE").withDescription("use given profile id")
            .withLongOpt("profile-id").create('P');

    @SuppressWarnings("static-access")
    Option ssValidation = OptionBuilder.hasArg().withArgName("SS-VALIDATION")
            .withDescription("use given validation id").withLongOpt("ssValidation-id").create("S");

    @SuppressWarnings("static-access")
    Option cpeDictionary = OptionBuilder.hasArg().withArgName("FILE")
            .withDescription("use given CPE 2.0 Dictionary file").withLongOpt("cpe-dictionary").create('C');

    @SuppressWarnings("static-access")
    Option cpeOVALDefinition = OptionBuilder.hasArg().withArgName("FILE")
            .withDescription("use given CPE OVAL definition file for CPE evaluation").withLongOpt("cpe-oval")
            .create('c');

    @SuppressWarnings("static-access")
    Option verbose = OptionBuilder.withDescription("produce verbose output").create("v");

    // Build the options list
    Options options = new Options();
    options.addOption(help);
    options.addOption(workingDir);
    options.addOption(xccdfResultFilename);
    options.addOption(profile);
    options.addOption(ssValidation);
    options.addOption(nocpe);
    options.addOption(noresults);
    options.addOption(nocheck);
    options.addOption(cpeDictionary);
    options.addOption(cpeOVALDefinition);
    options.addOption(verbose);

    // create the parser
    CommandLineParser parser = new GnuParser();
    try {
        // parse the command line arguments
        CommandLine line = parser.parse(options, args);

        String[] remainingArgs = line.getArgs();

        if (line.hasOption("help") || remainingArgs.length != 1) {
            if (remainingArgs.length != 1) {
                System.err.print("Invalid arguments: ");
                for (String arg : remainingArgs) {
                    System.err.print("'" + arg + "' ");
                }
                System.out.println();
            }

            // automatically generate the help statement
            System.out.println();
            showHelp(options);
            System.exit(0);
        }

        File xccdfFile = new File(remainingArgs[0]);

        if (!xccdfFile.exists()) {
            System.err.println(
                    "!! the specified XCCDF file '" + xccdfFile.getAbsolutePath() + "' does not exist!");
            System.exit(1);
        }

        XCCDFInterpreter interpreter = new XCCDFInterpreter(xccdfFile.getCanonicalFile());

        //System.out.println("** validating XCCDF content");

        if (!interpreter.validate()) {
            System.err.println("!! the XCCDF document is invalid. aborting.");
            System.exit(8);
        }

        if (line.hasOption(verbose.getOpt())) {
            verboseOutput = true;
            interpreter.setVerboseOutput(true);
        }

        if (line.hasOption(workingDir.getOpt())) {
            String lineOpt = line.getOptionValue(workingDir.getOpt());
            String workingDirValue = (lineOpt == null) ? "" : lineOpt;

            File f = new File(workingDirValue);
            if (!f.exists()) {
                if (verboseOutput)
                    System.out.println("** creating directory: " + f.getAbsolutePath());
                if (!f.mkdirs()) {
                    System.err.println("!! unable to create the result directory: " + f.getAbsolutePath());
                    System.exit(2);
                }
            }

            if (!f.isDirectory()) {
                System.err.println("!! the path specified for the result directory is not a directory: "
                        + f.getAbsolutePath());
                System.exit(3);
            }

            if (!f.canWrite()) {
                System.err.println("!! the path specified for the result directory is not writable: "
                        + f.getAbsolutePath());
                System.exit(4);
            }
            interpreter.setResultDirectory(f);
        }

        if (line.hasOption(xccdfResultFilename.getOpt())) {
            interpreter.setXccdfResultsFilename(line.getOptionValue(xccdfResultFilename.getOpt()));
        }

        if (line.hasOption(profile.getOpt())) {
            interpreter.setProfileId(line.getOptionValue(profile.getOpt()));
        }

        if (line.hasOption(ssValidation.getOpt())) {
            interpreter.setssValidationId(line.getOptionValue(ssValidation.getOpt()));
        }

        if (line.hasOption(nocpe.getLongOpt())) {
            interpreter.setProcessCPE(false);
        }

        if (line.hasOption(noresults.getLongOpt())) {
            interpreter.setDisplayResults(false);
        }

        if (line.hasOption(nocheck.getLongOpt())) {
            interpreter.setProcessChecks(false);
        }

        if (interpreter.processCPE == true) {

            if (line.hasOption(cpeDictionary.getOpt())) {
                String lineOpt = line.getOptionValue(cpeDictionary.getOpt());
                String cpeDict = (lineOpt == null) ? "" : lineOpt;

                File f = new File(cpeDict);

                if (!f.exists()) {
                    System.err.println("The CPE dictionary file does not exist: " + f.getAbsolutePath());
                    System.exit(5);
                }

                if (!f.isFile()) {
                    System.err.println("The path specified for the CPE dictionary file is not a file: "
                            + f.getAbsolutePath());
                    System.exit(6);
                }

                if (!f.canRead()) {
                    System.err.println("The path specified for the CPE dictionary file is not readable: "
                            + f.getAbsolutePath());
                    System.exit(7);
                }
                interpreter.setCPEDictionaryFile(f);
            }

            if (line.hasOption(cpeOVALDefinition.getOpt())) {
                String lineOpt = line.getOptionValue(cpeOVALDefinition.getOpt());
                String cpeOVAL = (lineOpt == null) ? "" : lineOpt;

                File f = new File(cpeOVAL);

                if (!f.exists()) {
                    System.err.println(
                            "!! the CPE OVAL inventory definition file does not exist: " + f.getAbsolutePath());
                    System.exit(5);
                }

                if (!f.isFile()) {
                    System.err.println(
                            "!! the path specified for the CPE OVAL inventory definition file is not a file: "
                                    + f.getAbsolutePath());
                    System.exit(6);
                }

                if (!f.canRead()) {
                    System.err.println(
                            "!! the path specified for the CPE OVAL inventory definition file is not readable: "
                                    + f.getAbsolutePath());
                    System.exit(7);
                }
                interpreter.setCPEOVALDefinitionFile(f);
            }

        } // END IF processCPE

        interpreter.process();

    } catch (ParseException ex) {
        System.err.println("!! parsing failed : " + ex.getMessage());
        System.out.println();
        showHelp(options);
    } catch (ProfileNotFoundException ex) {
        if (verboseOutput == true)
            ex.printStackTrace();
        else
            System.err.println("!! checklist processing failed : " + ex.getMessage());
    } catch (CircularReferenceException ex) {
        System.err.println("!! checklist processing failed : " + ex.getMessage());
        if (verboseOutput == true)
            ex.printStackTrace();
        else
            System.err.println("!! checklist processing failed : " + ex.getMessage());
    } catch (ExtensionScopeException ex) {
        if (verboseOutput == true)
            ex.printStackTrace();
        else
            System.err.println("!! checklist processing failed : " + ex.getMessage());
    } catch (ItemNotFoundException ex) {
        if (verboseOutput == true)
            ex.printStackTrace();
        else
            System.err.println("!! checklist processing failed : " + ex.getMessage());
    } catch (PropertyNotFoundException ex) {
        if (verboseOutput == true)
            ex.printStackTrace();
        else
            System.err.println("!! checklist processing failed : " + ex.getMessage());
    } catch (CPEEvaluationException ex) {
        if (verboseOutput == true)
            ex.printStackTrace();
        else
            System.err.println("!! checklist processing failed : " + ex.getMessage());
    } catch (Exception ex) {
        if (verboseOutput == true)
            ex.printStackTrace();
        else
            System.err.println("!! checklist processing failed : " + ex.getMessage());
    }

}

From source file:org.mocksy.server.http.MocksyServer.java

/**
 * Parses the program arguments into an Apache CLI CommandLine. If the
 * -h switch is present, the usage info will be printed to System.out.
 * If anything else goes wrong, the exception will be printed.
 * /*from   w  w  w  . j a va 2 s .co m*/
 * @param args the program arguments
 * @return an Apache CLI CommandLine
 */
static CommandLine parseCommandLine(String[] args) {
    CommandLineParser parser = new GnuParser();
    Options options = new Options();
    options.addOption("h", "help", false, "show this message");
    options.addOption("r", "ruleset", true,
            "root configuration directory, URL or Java class name (default: working directory)");
    options.addOption("p", "port", true, "port that server will listen on (default: 8080)");
    options.addOption("k", "keystore", true,
            "location of the keystore, if running in SSL (default: ./keystore.jks)");
    options.addOption("P", "password", true, "password to open the keystore (default: password)");
    options.addOption("a", "admin", false, "open admin port (one higher than request port)");

    CommandLine line = null;
    boolean help = true;
    try {
        line = parser.parse(options, args);
        help = line.hasOption("h");
    } catch (ParseException e) {
        e.printStackTrace();
    }
    if (help) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("java -jar mocksy-server-full.jar", options, true);
        System.exit(0);
    }
    return line;
}