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

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

Introduction

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

Prototype

public synchronized Throwable getCause() 

Source Link

Document

Returns the cause of this throwable or null if the cause is nonexistent or unknown.

Usage

From source file:net.lldp.checksims.ChecksimsRunner.java

/**
 * CLI entrypoint of Checksims.//from   ww  w  . j  av  a 2s .  co  m
 *
 * @param args CLI arguments
 */
public static void main(String[] args) {
    try {
        ChecksimsCommandLine.runCLI(args);
    } catch (ParseException e) {
        System.err.println(e.getMessage());
        System.exit(-1);
    } catch (ChecksimsException e) {
        System.err.println(e.toString());
        if (e.getCause() != null) {
            System.err.println("Caused by: " + e.getCause().toString());
        }
        // Print the stack trace for internal exceptions, they may be serious
        e.printStackTrace();
        System.exit(-1);
    } catch (IOException e) {
        System.err.println("I/O Error!");
        System.err.println(e.getMessage());
        System.exit(-1);
    }

    System.exit(0);
}

From source file:co.turnus.analysis.buffers.BoundedBufferSchedulingCliLauncher.java

public static void main(String[] args) {
    try {//w ww  . j a  v a  2 s  . c o m
        CommandLineParser parser = new GnuParser();
        CommandLine cmd = parser.parse(cliOptions, args);
        Configuration config = parseCommandLine(cmd);

        // init models
        AnalysisActivator.init();

        // set logger verbosity
        if (config.getBoolean(VERBOSE, false)) {
            TurnusLogger.setLevel(TurnusLevel.ALL);
        }

        File tDir = new File(config.getString(TRACE_PROJECT));
        TraceProject project = TraceProject.load(tDir);

        BoundedBufferScheduling bbs = new BoundedBufferScheduling(project);
        bbs.setConfiguration(config);

        BufferMinimizationData data = bbs.run();

        TurnusLogger.info("Storing results...");
        File outPath = new File(config.getString(OUTPUT_PATH));

        // store the analysis report
        String uuid = UUID.randomUUID().toString();
        File rFile = new File(outPath, uuid + "." + TurnusExtension.REPORT);
        Report report = DataFactory.eINSTANCE.createReport();
        report.setDate(new Date());
        report.setComment("Report with only Bounded Buffer Scheduling results analysis");
        report.getDataSet().add(data);
        EcoreHelper.storeEObject(report, new ResourceSetImpl(), rFile);
        TurnusLogger.info("TURNUS report stored in " + rFile);

        // store formatted reports
        String xlsName = config.getString(XLS, "");
        if (!xlsName.isEmpty()) {
            File xlsFile = new File(outPath, xlsName + ".xls");
            new XlsBufferMinimizationDataWriter().write(data, xlsFile);
            TurnusLogger.info("XLS report stored in " + xlsFile);
        }

        String bxdfName = config.getString(BXDF, "");
        if (!bxdfName.isEmpty()) {
            File bxdfFile = new File(outPath, bxdfName + ".bxdf");
            new XmlBufferMinimizationDataWriter().write(data, bxdfFile);
            TurnusLogger.info("BXDF files (one for each configuration) " + "stored in " + outPath);
        }

        TurnusLogger.info("Analysis Done!");

    } catch (ParseException e) {
        TurnusLogger.error(e.getMessage());
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp(BoundedBufferSchedulingCliLauncher.class.getSimpleName(), cliOptions);
    } catch (Exception e) {
        TurnusLogger.error(e.getCause().toString());
    }
}

From source file:com.hs.mail.container.simple.SimpleSpringContainer.java

/**
* @param args//w w w.ja v a  2s .  co m
*/
public static void main(String[] args) {
    CommandLine cli = null;
    try {
        cli = new PosixParser().parse(OPTS, args);
    } catch (ParseException e) {
        usage();
        System.exit(0);
    }

    try {
        String configLocation = cli.getOptionValue("c", DEFAULT_CONFIG_LOCATION);
        System.setProperty("app.home", new File(configLocation).getParentFile().getParent());
        SimpleSpringContainer container = new SimpleSpringContainer(new String[] { configLocation });
        container.start();

        if (cli.hasOption("dm")) {
            startPerformanceMonitor(cli.getOptionValue("dm", "5"));
        }
    } catch (Exception e) {
        String errMsg = (e.getMessage() != null) ? e.getMessage() : e.getCause().getMessage();
        System.err.println(errMsg);
        logger.fatal(errMsg, e);
    }
}

From source file:edu.osu.ling.pep.Pep.java

/**
 * Invokes Pep from the command line.//from  w w w.  j  a  va 2  s.  co  m
 * <p>
 * The main work this method does, apart from tokenizing the arguments and
 * input tokens, is to load and parse the XML grammar file (as specified by
 * <code>-g</code> or <code>--grammar</code>). If any of the arguments
 * <code>-g</code>, <code>--grammar</code>, <code>-s</code>,
 * <code>--seed</code>, <code>-o</code>, <code>--option</code>, occur with
 * no argument following, this method prints an error notifying the user.
 * 
 * @param args
 *            The expected arguments are as follows, and can occur in any
 *            particular order:
 *            <ul>
 *            <li><code>-g|--grammar &lt;grammar file&gt;</code></li> <li>
 *            <code>-s|--seed &lt;seed category&gt;</code></li> <li><code>
 *            -v|--verbose {verbosity level}</code></li> <li><code>
 *            -o|--option &lt;OPTION_NAME=value&gt;</code></li> <li><code>
 *            -h|--help (prints usage information)</code></li> <li><code>
 *            &lt;token1 ... token<em>n</em>&gt;</code> (or <code>-</code>
 *            for standard input)</li>
 *            </ul>
 *            <code>OPTION_NAME</code> must be the name of one of the
 *            recognized {@link ParserOption options}. If <code>-h</code> or
 *            <code>--help</code> occur anywhere in the arguments, usage
 *            information is printed and no parsing takes place.
 */
@SuppressWarnings("static-access")
public static final void main(final String[] args) {
    try {
        final Options opts = new Options();

        opts.addOption(OptionBuilder.withLongOpt("grammar").withDescription("the grammar to use").hasArg()
                .isRequired().withArgName("grammar file").create('g'));

        opts.addOption(OptionBuilder.withLongOpt("seed").withDescription("the seed category to parse for")
                .hasArg().isRequired().withArgName("seed category").create('s'));

        opts.addOption(OptionBuilder.withLongOpt("verbose").withDescription("0-3").hasOptionalArg()
                .withArgName("verbosity level").create('v'));

        opts.addOption(OptionBuilder.withLongOpt("option").withDescription("sets parser options")
                .withArgName("OPTION=value").hasArgs(2).withValueSeparator()
                .withDescription("use value for given property").create("o"));

        opts.addOption(OptionBuilder.withLongOpt("help").withDescription("prints this message").create('h'));

        final CommandLineParser parser = new GnuParser();
        try {
            final CommandLine line = parser.parse(opts, args);
            if (line.hasOption('h')) {
                Pep.printHelp(opts);
            } else {
                final int v = Integer.parseInt(line.getOptionValue('v', Integer.toString(Pep.V_PARSE)));
                if (v < 0) {
                    throw new PepException("verbosity < 0: " + v);
                }

                Pep.verbosity = v;
                final Map<ParserOption, Boolean> options = new EnumMap<ParserOption, Boolean>(
                        ParserOption.class);

                final Properties props = line.getOptionProperties("o");
                for (final Object key : props.keySet()) {
                    try {
                        options.put(ParserOption.valueOf(key.toString()),
                                Boolean.valueOf(props.get(key).toString()));
                    } catch (final IllegalArgumentException iae) {
                        Pep.printError("no option named " + key.toString());
                        Pep.printHelp(opts);
                        return;
                    }
                }

                final Pep pep = new Pep(options);
                // final Grammar grammar =
                // new GrammarParser(Pep.findGrammar(line
                // .getOptionValue('g'))).t.parse();

                final List<?> ts = line.getArgList();
                List<String> tokens = null;
                if (ts.isEmpty() || ts.get(0).equals("-")) {
                    tokens = Pep.readTokens(new Scanner(System.in));
                } else {
                    tokens = new ArrayList<String>(ts.size());
                    for (final Object t : ts) {
                        tokens.add(t.toString());
                    }
                }

                pep.lastParseStart = System.currentTimeMillis();
                // try {
                // pep.parse(grammar, tokens,
                // new Category(line.getOptionValue('s')));
                // } catch (final PepException ignore) {
                // // ignore here, we're listening
                // }
            }
        } catch (final ParseException pe) {
            Pep.printError("command-line syntax problem: " + pe.getMessage());
            Pep.printHelp(opts);
        }
    } catch (final PepException pe) {
        final Throwable cause = pe.getCause();
        Pep.printError((cause == null) ? pe : cause);
    } catch (final RuntimeException re) {
        Pep.printError(re);
    }
}

From source file:ml.shifu.shifu.util.ShifuCLI.java

/**
 * Main entry for the whole framework.//from w  w  w .  j  a  v  a 2 s  . c  o  m
 *
 * @throws IOException
 */
public static void main(String[] args) {
    // invalid input and help options
    if (args.length < 1 || (isHelpOption(args[0]))) {
        printUsage();
        System.exit(args.length < 1 ? -1 : 0);
    }

    // process -v and -version conditions manually
    if (isVersionOption(args[0])) {
        printVersionString();
        System.exit(0);
    }

    CommandLineParser parser = new GnuParser();
    Options opts = buildModelSetOptions(args);
    CommandLine cmd = null;

    try {
        cmd = parser.parse(opts, args);
    } catch (ParseException e) {
        log.error("Invalid command options. Please check help message.");
        printUsage();
        System.exit(1);
    }

    try {
        if (args[0].equals(NEW) && args.length >= 2 && StringUtils.isNotEmpty(args[1])) {
            // modelset step
            String modelName = args[1];
            int status = createNewModel(modelName, cmd.getOptionValue(MODELSET_CMD_TYPE),
                    cmd.getOptionValue(MODELSET_CMD_M));
            if (status == 0) {
                printModelSetCreatedSuccessfulLog(modelName);
            }
            // copyModel(manager, cmd.getOptionValues(MODELSET_CMD_CP));
        } else {
            if (args[0].equals(MODELSET_CMD_CP) && args.length >= 3 && StringUtils.isNotEmpty(args[1])
                    && StringUtils.isNotEmpty(args[2])) {
                String newModelSetName = args[2];
                // modelset step
                copyModel(new String[] { args[1], newModelSetName });
                printModelSetCopiedSuccessfulLog(newModelSetName);
            } else if (args[0].equals(INIT_CMD)) {
                // init step
                if (cmd.getOptions() == null || cmd.getOptions().length == 0) {
                    int status = initializeModel();
                    if (status == 0) {
                        log.info(
                                "ModelSet initilization is successful. Please continue next step by using 'shifu stats'.");
                    }
                } else if (cmd.hasOption(INIT_CMD_MODEL)) {
                    initializeModelParam();
                } else {
                    log.error("Invalid command, please check help message.");
                    printUsage();
                }
            } else if (args[0].equals(STATS_CMD)) {
                // stats step
                calModelStats();
                log.info(
                        "Do model set statistics successfully. Please continue next step by using 'shifu varselect'.");
            } else if (args[0].equals(NORMALIZE_CMD)) {
                // normalize step
                normalizeTrainData();
                log.info(
                        "Do model set normalization successfully. Please continue next step by using 'shifu train'.");
            } else if (args[0].equals(VARSELECT_CMD)) {
                // variable selected step
                selectModelVar();
                log.info(
                        "Do model set variables selection successfully. Please continue next step by using 'shifu normalize'.");
            } else if (args[0].equals(TRAIN_CMD)) {
                // train step
                trainModel(cmd.hasOption(TRAIN_CMD_DRY), cmd.hasOption(TRAIN_CMD_DEBUG));
                log.info(
                        "Do model set training successfully. Please continue next step by using 'shifu posttrain' or if no need posttrain you can go through with 'shifu eval'.");
            } else if (args[0].equals(POSTTRAIN_CMD)) {
                // post train step
                postTrainModel();
                log.info(
                        "Do model set post-training successfully. Please configurate your eval set in ModelConfig.json and continue next step by using 'shifu eval' or 'shifu eval -new <eval set>' to create a new eval set.");
            } else if (args[0].equals(SAVE)) {
                String newModelSetName = args.length >= 2 ? args[1] : null;
                saveCurrentModel(newModelSetName);
            } else if (args[0].equals(SWITCH)) {
                String newModelSetName = args[1];
                switchCurrentModel(newModelSetName);
            } else if (args[0].equals(SHOW)) {
                ManageModelProcessor p = new ManageModelProcessor(ModelAction.SHOW, null);
                p.run();
            } else if (args[0].equals(EVAL_CMD)) {
                // eval step
                if (args.length == 1) {
                    //run everything
                    runEvalSet(cmd.hasOption(TRAIN_CMD_DRY));
                    log.info("Run eval performance with all eval sets successfully.");
                } else if (cmd.getOptionValue(MODELSET_CMD_NEW) != null) {
                    //create new eval
                    createNewEvalSet(cmd.getOptionValue(MODELSET_CMD_NEW));
                    log.info(
                            "Create eval set successfully. You can configurate EvalConfig.json or directly run 'shifu eval -run <evalSetName>' to get performance info.");
                } else if (cmd.hasOption(EVAL_CMD_RUN)) {
                    runEvalSet(cmd.getOptionValue(EVAL_CMD_RUN), cmd.hasOption(TRAIN_CMD_DRY));
                    log.info("Finish run eval performance with eval set {}.", cmd.getOptionValue(EVAL_CMD_RUN));
                } else if (cmd.hasOption(SCORE)) {

                    //run score
                    runEvalScore(cmd.getOptionValue(SCORE));
                    log.info("Finish run score with eval set {}.", cmd.getOptionValue(SCORE));
                } else if (cmd.hasOption(CONFMAT)) {

                    //run confusion matrix
                    runEvalConfMat(cmd.getOptionValue(CONFMAT));
                    log.info("Finish run confusion matrix with eval set {}.", cmd.getOptionValue(CONFMAT));

                } else if (cmd.hasOption(PERF)) {
                    //run perfermance
                    runEvalPerf(cmd.getOptionValue(PERF));
                    log.info("Finish run performance maxtrix with eval set {}.", cmd.getOptionValue(PERF));

                } else if (cmd.hasOption(LIST)) {
                    //list all evaluation sets
                    listEvalSet();
                } else if (cmd.hasOption(DELETE)) {
                    // delete some evaluation set
                    deleteEvalSet(cmd.getOptionValue(DELETE));
                } else {
                    log.error("Invalid command, please check help message.");
                    printUsage();
                }
            } else {
                log.error("Invalid command, please check help message.");
                printUsage();
            }
        }
    } catch (ShifuException e) {
        // need define error code in each step.
        log.error(e.getError().toString(), e.getCause());
        exceptionExit(e);
    } catch (Exception e) {
        exceptionExit(e);
    }
}

From source file:com.databasepreservation.Main.java

private static int run(CLI cli) {
    DatabaseImportModule importModule;//from w  w  w. j  a v  a 2s  .  c o  m
    DatabaseExportModule exportModule;

    try {
        importModule = cli.getImportModule();
        exportModule = cli.getExportModule();
    } catch (ParseException e) {
        LOGGER.error(e.getMessage(), e);
        logProgramFinish(EXIT_CODE_COMMAND_PARSE_ERROR);
        return EXIT_CODE_COMMAND_PARSE_ERROR;
    } catch (LicenseNotAcceptedException e) {
        LOGGER.trace("LicenseNotAcceptedException", e);
        LOGGER.info("The license must be accepted to use this module.");
        LOGGER.info("==================================================");
        LOGGER.info(e.getLicense());
        LOGGER.info("==================================================");
        logProgramFinish(EXIT_CODE_LICENSE_NOT_ACCEPTED);
        return EXIT_CODE_LICENSE_NOT_ACCEPTED;
    }

    int exitStatus = EXIT_CODE_GENERIC_ERROR;

    try {
        long startTime = System.currentTimeMillis();
        LOGGER.info("Converting database: " + cli.getImportModuleName() + " to " + cli.getExportModuleName());
        importModule.getDatabase(exportModule);
        long duration = System.currentTimeMillis() - startTime;
        LOGGER.info("Run time " + (duration / 60000) + "m " + (duration % 60000 / 1000) + "s");
        exitStatus = EXIT_CODE_OK;
    } catch (ModuleException e) {
        if (e.getCause() != null && e.getCause() instanceof ClassNotFoundException
                && "sun.jdbc.odbc.JdbcOdbcDriver".equals(e.getCause().getMessage())) {
            LOGGER.error(
                    "Could not find the Java ODBC driver, "
                            + "please run this program under Windows to use the JDBC-ODBC bridge.",
                    e.getCause());
        } else if ("SQL error while connecting".equalsIgnoreCase(e.getMessage())) {
            LOGGER.error("Connection error while importing/exporting", e);
            exitStatus = EXIT_CODE_CONNECTION_ERROR;
        }

        if (e.getModuleErrors() != null) {
            for (Map.Entry<String, Throwable> entry : e.getModuleErrors().entrySet()) {
                LOGGER.error(entry.getKey(), entry.getValue());
            }
        } else {
            LOGGER.error("Fatal error while converting the database (" + e.getMessage() + ")", e);
        }
    } catch (UnknownTypeException | InvalidDataException e) {
        LOGGER.error("Fatal error while converting the database (" + e.getMessage() + ")", e);
    } catch (Exception e) {
        LOGGER.error("Fatal error: Unexpected exception (" + e.getMessage() + ")", e);
    }
    return exitStatus;
}

From source file:ml.shifu.shifu.ShifuCLI.java

public static void main(String[] args) {
    String[] cleanedArgs = cleanArgs(args);
    // invalid input and help options
    if (cleanedArgs.length < 1 || (isHelpOption(cleanedArgs[0]))) {
        printUsage();//from  www. j  a  v  a 2s. com
        System.exit(cleanedArgs.length < 1 ? -1 : 0);
    }

    // process -v and -version conditions manually
    if (isVersionOption(cleanedArgs[0])) {
        printLogoAndVersion();
        System.exit(0);
    }

    CommandLineParser parser = new GnuParser();
    Options opts = buildModelSetOptions();
    CommandLine cmd = null;

    try {
        cmd = parser.parse(opts, cleanedArgs);
    } catch (ParseException e) {
        log.error("Invalid command options. Please check help message.");
        printUsage();
        System.exit(1);
    }

    int status = 0;

    try {
        if (cleanedArgs[0].equals(NEW) && cleanedArgs.length >= 2 && StringUtils.isNotEmpty(cleanedArgs[1])) {
            // modelset step
            String modelName = cleanedArgs[1];
            status = createNewModel(modelName, cmd.getOptionValue(MODELSET_CMD_TYPE),
                    cmd.getOptionValue(MODELSET_CMD_M));
            if (status == 0) {
                printModelSetCreatedSuccessfulLog(modelName);
            } else {
                log.warn("Error in create new model set, please check your shifu config or report issue");
            }
            System.exit(status);
            // copyModel(manager, cmd.getOptionValues(MODELSET_CMD_CP));
        } else {
            if (cleanedArgs[0].equals(MODELSET_CMD_CP) && cleanedArgs.length >= 3
                    && StringUtils.isNotEmpty(cleanedArgs[1]) && StringUtils.isNotEmpty(cleanedArgs[2])) {
                String newModelSetName = cleanedArgs[2];
                // modelset step
                copyModel(new String[] { cleanedArgs[1], newModelSetName });
                printModelSetCopiedSuccessfulLog(newModelSetName);
            } else if (cleanedArgs[0].equals(INIT_CMD)) {
                // init step
                if (cmd.getOptions() == null || cmd.getOptions().length == 0) {
                    status = initializeModel();
                    if (status == 0) {
                        log.info(
                                "ModelSet initialization is successful. Please continue next step by using 'shifu stats'.");
                    } else {
                        log.warn(
                                "Error in ModelSet initialization, please check your shifu config or report issue");
                    }
                } else if (cmd.hasOption(INIT_CMD_MODEL)) {
                    initializeModelParam();
                } else {
                    log.error("Invalid command, please check help message.");
                    printUsage();
                }
            } else if (cleanedArgs[0].equals(STATS_CMD)) {
                Map<String, Object> params = new HashMap<String, Object>();
                params.put(Constants.IS_COMPUTE_CORR,
                        cmd.hasOption(CORRELATION) || cmd.hasOption(SHORT_CORRELATION));
                params.put(Constants.IS_REBIN, cmd.hasOption(REBIN));
                params.put(Constants.REQUEST_VARS, cmd.getOptionValue(VARS));
                params.put(Constants.EXPECTED_BIN_NUM, cmd.getOptionValue(N));
                params.put(Constants.IV_KEEP_RATIO, cmd.getOptionValue(IVR));
                params.put(Constants.MINIMUM_BIN_INST_CNT, cmd.getOptionValue(BIC));
                params.put(Constants.IS_COMPUTE_PSI, cmd.hasOption(PSI) || cmd.hasOption(SHORT_PSI));

                // stats step
                status = calModelStats(params);
                if (status == 0) {
                    if (cmd.hasOption(CORRELATION) || cmd.hasOption(SHORT_CORRELATION)) {
                        log.info(
                                "Do model set correlation computing successfully. Please continue next step by using 'shifu normalize or shifu norm'. For tree ensemble model, no need do norm, please continue next step by using 'shifu varsel'");
                    }
                    if (cmd.hasOption(PSI) || cmd.hasOption(SHORT_PSI)) {
                        log.info(
                                "Do model set psi computing successfully. Please continue next step by using 'shifu normalize or shifu norm'. For tree ensemble model, no need do norm, please continue next step by using 'shifu varsel'");
                    } else {
                        log.info(
                                "Do model set statistic successfully. Please continue next step by using 'shifu normalize or shifu norm or shifu transform'. For tree ensemble model, no need do norm, please continue next step by using 'shifu varsel'");
                    }
                } else {
                    log.warn(
                            "Error in model set stats computation, please report issue on http:/github.com/shifuml/shifu/issues.");
                }
            } else if (cleanedArgs[0].equals(NORMALIZE_CMD) || cleanedArgs[0].equals(NORM_CMD)
                    || cleanedArgs[0].equals(TRANSFORM_CMD)) {
                // normalize step
                Map<String, Object> params = new HashMap<String, Object>();
                params.put(Constants.IS_TO_SHUFFLE_DATA, cmd.hasOption(SHUFFLE));
                status = normalizeTrainData(params);
                if (status == 0) {
                    log.info(
                            "Do model set normalization successfully. Please continue next step by using 'shifu varselect or shifu varsel'.");
                } else {
                    log.warn(
                            "Error in model set stats computation, please report issue on http:/github.com/shifuml/shifu/issues.");
                }
            } else if (cleanedArgs[0].equals(VARSELECT_CMD) || cleanedArgs[0].equals(VARSEL_CMD)) {
                Map<String, Object> params = new HashMap<String, Object>();
                params.put(Constants.IS_TO_RESET, cmd.hasOption(RESET));
                params.put(Constants.IS_TO_LIST, cmd.hasOption(LIST));
                params.put(Constants.IS_TO_FILTER_AUTO, cmd.hasOption(FILTER_AUTO));
                params.put(Constants.IS_TO_RECOVER_AUTO, cmd.hasOption(RECOVER_AUTO));
                params.put(Constants.RECURSIVE_CNT, cmd.getOptionValue(RECURSIVE));

                // variable selected step
                status = selectModelVar(params);
                if (status == 0) {
                    log.info(
                            "Do model set variables selection successfully. Please continue next step by using 'shifu train'.");
                } else {
                    log.info("Do variable selection with error, please check error message or report issue.");
                }
            } else if (cleanedArgs[0].equals(TRAIN_CMD)) {
                // train step
                status = trainModel(cmd.hasOption(TRAIN_CMD_DRY), cmd.hasOption(TRAIN_CMD_DEBUG),
                        cmd.hasOption(SHUFFLE));
                if (status == 0) {
                    log.info(
                            "Do model set training successfully. Please continue next step by using 'shifu posttrain' or if no need posttrain you can go through with 'shifu eval'.");
                } else {
                    log.info("Do model training with error, please check error message or report issue.");
                }
            } else if (cleanedArgs[0].equals(CMD_ENCODE)) {
                Map<String, Object> params = new HashMap<String, Object>();
                params.put(ModelDataEncodeProcessor.ENCODE_DATA_SET, cmd.getOptionValue(EVAL_CMD_RUN));
                params.put(ModelDataEncodeProcessor.ENCODE_REF_MODEL, cmd.getOptionValue(REF));
                status = runEncode(params);
            } else if (cleanedArgs[0].equals(CMD_COMBO)) {
                if (cmd.hasOption(MODELSET_CMD_NEW)) {
                    log.info("Create new commbo models");
                    status = createNewCombo(cmd.getOptionValue(MODELSET_CMD_NEW));
                } else if (cmd.hasOption(INIT_CMD)) {
                    log.info("Init commbo models");
                    status = initComboModels();
                } else if (cmd.hasOption(EVAL_CMD_RUN)) {
                    log.info("Run combo model - with toShuffle: {}, with toResume: {}", opts.hasOption(SHUFFLE),
                            opts.hasOption(RESUME));
                    status = runComboModels(cmd.hasOption(SHUFFLE), cmd.hasOption(RESUME));
                    // train combo models
                } else if (cmd.hasOption(EVAL_CMD)) {
                    log.info("Eval combo model.");
                    // eval combo model performance
                    status = evalComboModels(cmd.hasOption(RESUME));
                } else {
                    log.error("Invalid command usage.");
                    printUsage();
                }
            } else if (cleanedArgs[0].equals(POSTTRAIN_CMD)) {
                // post train step
                status = postTrainModel();
                if (status == 0) {
                    log.info(
                            "Do model set post-training successfully. Please configure your eval set in ModelConfig.json and continue next step by using 'shifu eval' or 'shifu eval -new <eval set>' to create a new eval set.");
                } else {
                    log.info("Do model post training with error, please check error message or report issue.");
                }
            } else if (cleanedArgs[0].equals(SAVE)) {
                String newModelSetName = cleanedArgs.length >= 2 ? cleanedArgs[1] : null;
                saveCurrentModel(newModelSetName);
            } else if (cleanedArgs[0].equals(SWITCH)) {
                String newModelSetName = cleanedArgs[1];
                switchCurrentModel(newModelSetName);
            } else if (cleanedArgs[0].equals(SHOW)) {
                ManageModelProcessor p = new ManageModelProcessor(ModelAction.SHOW, null);
                p.run();
            } else if (cleanedArgs[0].equals(EVAL_CMD)) {
                Map<String, Object> params = new HashMap<String, Object>();

                // eval step
                if (cleanedArgs.length == 1) {
                    // run everything
                    status = runEvalSet(cmd.hasOption(TRAIN_CMD_DRY));
                    if (status == 0) {
                        log.info("Run eval performance with all eval sets successfully.");
                    } else {
                        log.info("Do evaluation with error, please check error message or report issue.");
                    }
                } else if (cmd.getOptionValue(MODELSET_CMD_NEW) != null) {
                    // create new eval
                    createNewEvalSet(cmd.getOptionValue(MODELSET_CMD_NEW));
                    log.info(
                            "Create eval set successfully. You can configure EvalConfig.json or directly run 'shifu eval -run <evalSetName>' to get performance info.");
                } else if (cmd.hasOption(EVAL_CMD_RUN)) {
                    runEvalSet(cmd.getOptionValue(EVAL_CMD_RUN), cmd.hasOption(TRAIN_CMD_DRY));
                    log.info("Finish run eval performance with eval set {}.", cmd.getOptionValue(EVAL_CMD_RUN));
                } else if (cmd.hasOption(SCORE)) {
                    params.put(EvalModelProcessor.NOSORT, cmd.hasOption(NOSORT));
                    // run score
                    runEvalScore(cmd.getOptionValue(SCORE), params);
                    log.info("Finish run score with eval set {}.", cmd.getOptionValue(SCORE));
                } else if (cmd.hasOption(CONFMAT)) {
                    // run confusion matrix
                    runEvalConfMat(cmd.getOptionValue(CONFMAT));
                    log.info("Finish run confusion matrix with eval set {}.", cmd.getOptionValue(CONFMAT));
                } else if (cmd.hasOption(PERF)) {
                    // run perfermance
                    runEvalPerf(cmd.getOptionValue(PERF));
                    log.info("Finish run performance maxtrix with eval set {}.", cmd.getOptionValue(PERF));
                } else if (cmd.hasOption(LIST)) {
                    // list all evaluation sets
                    listEvalSet();
                } else if (cmd.hasOption(DELETE)) {
                    // delete some evaluation set
                    deleteEvalSet(cmd.getOptionValue(DELETE));
                } else if (cmd.hasOption(NORM)) {
                    runEvalNorm(cmd.getOptionValue(NORM), cmd.hasOption(STRICT));
                } else {
                    log.error("Invalid command, please check help message.");
                    printUsage();
                }
            } else if (cleanedArgs[0].equals(CMD_EXPORT)) {
                Map<String, Object> params = new HashMap<String, Object>();
                params.put(ExportModelProcessor.IS_CONCISE, cmd.hasOption(EXPORT_CONCISE));
                params.put(ExportModelProcessor.REQUEST_VARS, cmd.getOptionValue(VARS));
                params.put(ExportModelProcessor.EXPECTED_BIN_NUM, cmd.getOptionValue(N));
                params.put(ExportModelProcessor.IV_KEEP_RATIO, cmd.getOptionValue(IVR));
                params.put(ExportModelProcessor.MINIMUM_BIN_INST_CNT, cmd.getOptionValue(BIC));
                status = exportModel(cmd.getOptionValue(MODELSET_CMD_TYPE), params);
                if (status == 0) {
                    log.info("Export models/columnstats/corr successfully.");
                } else {
                    log.warn("Fail to export models/columnstats/corr, please check or report issue.");
                }
            } else if (cleanedArgs[0].equals(CMD_TEST)) {
                Map<String, Object> params = new HashMap<String, Object>();
                params.put(ShifuTestProcessor.IS_TO_TEST_FILTER, cmd.hasOption(FILTER));
                params.put(ShifuTestProcessor.TEST_TARGET, cmd.getOptionValue(FILTER));
                params.put(ShifuTestProcessor.TEST_RECORD_CNT, cmd.getOptionValue(N));
                status = runShifuTest(params);
                if (status == 0) {
                    log.info("Run test for Shifu Successfully.");
                } else {
                    log.warn("Fail to run Shifu test.");
                }
            } else if (cleanedArgs[0].equals(CMD_CONVERT)) {
                int optType = -1;
                if (cmd.hasOption(TO_ZIPB)) {
                    optType = 1;
                } else if (cmd.hasOption(TO_TREEB)) {
                    optType = 2;
                }

                String[] convertArgs = new String[2];
                int j = 0;
                for (int i = 1; i < cleanedArgs.length; i++) {
                    if (!cleanedArgs[i].startsWith("-")) {
                        convertArgs[j++] = cleanedArgs[i];
                    }
                }

                if (optType < 0 || StringUtils.isBlank(convertArgs[0]) || StringUtils.isBlank(convertArgs[1])) {
                    printUsage();
                } else {
                    status = runShifuConvert(optType, convertArgs[0], convertArgs[1]);
                }
            } else if (cleanedArgs[0].equals(CMD_ANALYSIS)) {
                if (cmd.hasOption(FI)) {
                    String modelPath = cmd.getOptionValue(FI);
                    analysisModelFi(modelPath);
                }
            } else {
                log.error("Invalid command, please check help message.");
                printUsage();
            }
        }
        // for some case jvm cannot stop
        System.exit(status);
    } catch (ShifuException e) {
        // need define error code in each step.
        log.error(e.getError().toString() + "; msg: " + e.getMessage(), e.getCause());
        exceptionExit(e);
    } catch (Exception e) {
        exceptionExit(e);
    }
}

From source file:org.apache.hive.beeline.HiveSchemaTool.java

public static void main(String[] args) {
    CommandLineParser parser = new GnuParser();
    CommandLine line = null;/*from  www .ja  va 2s .  co m*/
    String dbType = null;
    String metaDbType = null;
    String schemaVer = null;
    Options cmdLineOptions = new Options();

    // Argument handling
    initOptions(cmdLineOptions);
    try {
        line = parser.parse(cmdLineOptions, args);
    } catch (ParseException e) {
        System.err.println("HiveSchemaTool:Parsing failed.  Reason: " + e.getLocalizedMessage());
        printAndExit(cmdLineOptions);
    }

    if (line.hasOption("help")) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("schemaTool", cmdLineOptions);
        return;
    }

    if (line.hasOption("dbType")) {
        dbType = line.getOptionValue("dbType");
        if ((!dbType.equalsIgnoreCase(HiveSchemaHelper.DB_DERBY)
                && !dbType.equalsIgnoreCase(HiveSchemaHelper.DB_HIVE)
                && !dbType.equalsIgnoreCase(HiveSchemaHelper.DB_MSSQL)
                && !dbType.equalsIgnoreCase(HiveSchemaHelper.DB_MYSQL)
                && !dbType.equalsIgnoreCase(HiveSchemaHelper.DB_POSTGRACE)
                && !dbType.equalsIgnoreCase(HiveSchemaHelper.DB_ORACLE))) {
            System.err.println("Unsupported dbType " + dbType);
            printAndExit(cmdLineOptions);
        }
    } else {
        System.err.println("no dbType supplied");
        printAndExit(cmdLineOptions);
    }

    if (line.hasOption("metaDbType")) {
        metaDbType = line.getOptionValue("metaDbType");

        if (!dbType.equals(HiveSchemaHelper.DB_HIVE)) {
            System.err.println("metaDbType only supported for dbType = hive");
            printAndExit(cmdLineOptions);
        }

        if (!metaDbType.equalsIgnoreCase(HiveSchemaHelper.DB_DERBY)
                && !metaDbType.equalsIgnoreCase(HiveSchemaHelper.DB_MSSQL)
                && !metaDbType.equalsIgnoreCase(HiveSchemaHelper.DB_MYSQL)
                && !metaDbType.equalsIgnoreCase(HiveSchemaHelper.DB_POSTGRACE)
                && !metaDbType.equalsIgnoreCase(HiveSchemaHelper.DB_ORACLE)) {
            System.err.println("Unsupported metaDbType " + metaDbType);
            printAndExit(cmdLineOptions);
        }
    } else if (dbType.equalsIgnoreCase(HiveSchemaHelper.DB_HIVE)) {
        System.err.println("no metaDbType supplied");
        printAndExit(cmdLineOptions);
    }

    System.setProperty(HiveConf.ConfVars.METASTORE_SCHEMA_VERIFICATION.varname, "true");
    try {
        HiveSchemaTool schemaTool = new HiveSchemaTool(dbType, metaDbType);

        if (line.hasOption("userName")) {
            schemaTool.setUserName(line.getOptionValue("userName"));
        } else {
            schemaTool
                    .setUserName(schemaTool.getHiveConf().get(ConfVars.METASTORE_CONNECTION_USER_NAME.varname));
        }
        if (line.hasOption("passWord")) {
            schemaTool.setPassWord(line.getOptionValue("passWord"));
        } else {
            try {
                schemaTool.setPassWord(ShimLoader.getHadoopShims().getPassword(schemaTool.getHiveConf(),
                        HiveConf.ConfVars.METASTOREPWD.varname));
            } catch (IOException err) {
                throw new HiveMetaException("Error getting metastore password", err);
            }
        }
        if (line.hasOption("url")) {
            schemaTool.setUrl(line.getOptionValue("url"));
        }
        if (line.hasOption("driver")) {
            schemaTool.setDriver(line.getOptionValue("driver"));
        }
        if (line.hasOption("dryRun")) {
            schemaTool.setDryRun(true);
        }
        if (line.hasOption("verbose")) {
            schemaTool.setVerbose(true);
        }
        if (line.hasOption("dbOpts")) {
            schemaTool.setDbOpts(line.getOptionValue("dbOpts"));
        }
        if (line.hasOption("validate") && line.hasOption("servers")) {
            schemaTool.setValidationServers(line.getOptionValue("servers"));
        }
        if (line.hasOption("info")) {
            schemaTool.showInfo();
        } else if (line.hasOption("upgradeSchema")) {
            schemaTool.doUpgrade();
        } else if (line.hasOption("upgradeSchemaFrom")) {
            schemaVer = line.getOptionValue("upgradeSchemaFrom");
            schemaTool.doUpgrade(schemaVer);
        } else if (line.hasOption("initSchema")) {
            schemaTool.doInit();
        } else if (line.hasOption("initSchemaTo")) {
            schemaVer = line.getOptionValue("initSchemaTo");
            schemaTool.doInit(schemaVer);
        } else if (line.hasOption("validate")) {
            schemaTool.doValidate();
        } else {
            System.err.println("no valid option supplied");
            printAndExit(cmdLineOptions);
        }
    } catch (HiveMetaException e) {
        System.err.println(e);
        if (e.getCause() != null) {
            Throwable t = e.getCause();
            System.err.println("Underlying cause: " + t.getClass().getName() + " : " + t.getMessage());
            if (e.getCause() instanceof SQLException) {
                System.err.println("SQL Error code: " + ((SQLException) t).getErrorCode());
            }
        }
        if (line.hasOption("verbose")) {
            e.printStackTrace();
        } else {
            System.err.println("Use --verbose for detailed stacktrace.");
        }
        System.err.println("*** schemaTool failed ***");
        System.exit(1);
    }
    System.out.println("schemaTool completed");

}

From source file:org.fusesource.hawtjni.generator.HawtJNI.java

public int execute(String[] args) {
    CommandLine cli = null;//w  w w .  j  a  v a2  s  .  c  o  m
    try {
        cli = new PosixParser().parse(createOptions(), args, true);
    } catch (ParseException e) {
        System.err.println("Unable to parse command line options: " + e.getMessage());
        displayHelp();
        return 1;
    }

    if (cli.hasOption("h")) {
        displayHelp();
        return 0;
    }

    if (cli.hasOption("v")) {
        progress = new ProgressMonitor() {
            public void step() {
            }

            public void setTotal(int total) {
            }

            public void setMessage(String message) {
                System.out.println(message);
            }
        };
    }

    name = cli.getOptionValue("n", "hawtjni_native");
    nativeOutput = new File(cli.getOptionValue("o", "."));
    //        javaOutputDir = new File(cli.getOptionValue("j", "."));
    String[] values = cli.getOptionValues("p");
    if (values != null) {
        packages = Arrays.asList(values);
    }

    values = cli.getArgs();
    if (values != null) {
        classpaths = Arrays.asList(values);
    }

    try {
        if (classpaths.isEmpty()) {
            throw new UsageException("No classpath supplied.");
        }
        generate();
    } catch (UsageException e) {
        System.err.println("Invalid usage: " + e.getMessage());
        displayHelp();
        return 1;
    } catch (Throwable e) {
        System.out.flush();
        System.err.println("Unexpected failure:");
        e.printStackTrace();
        Set<Throwable> exceptions = new HashSet<Throwable>();
        exceptions.add(e);
        for (int i = 0; i < 10; i++) {
            e = e.getCause();
            if (e != null && exceptions.add(e)) {
                System.err.println("Reason: " + e);
                e.printStackTrace();
            } else {
                break;
            }
        }
        return 2;
    }
    return 0;
}

From source file:org.fusesource.mop.MOP.java

public int execute(String[] args) {
    CommandLine cli = null;/*from  www  .  j  av a 2  s.  c  om*/
    try {
        cli = new GnuParser().parse(createOptions(), args, true);
    } catch (ParseException e) {
        System.err.println("Unable to parse command line options: " + e.getMessage());
        displayHelp();
        return 1;
    }

    // lets process the options
    Logger.debug = cli.hasOption("X");

    if (cli.hasOption("n")) {
        getRemoteRepositories().clear();
    }

    String scope = cli.getOptionValue("s", "runtime");
    repository.setScope(scope);
    String[] repos = cli.getOptionValues("r");
    if (repos != null) {
        for (String repo : repos) {
            String[] rc = repo.split("=", 2);
            if (rc.length != 2) {
                System.err.println("Invalid repository.  Expected format is: <id>=<url>, actual: " + repo);
                displayHelp();
                return 1;
            }
            getRemoteRepositories().put(rc[0], rc[1]);
        }
    }

    //        repository.setOnline(!cli.hasOption("o"));
    //        LOG.debug("online mode: " + repository.isOnline());

    String localRepo = cli.getOptionValue('l');
    if (localRepo != null) {
        repository.setLocalRepo(new File(localRepo));
    }

    if (cli.hasOption("h")) {
        displayHelp();
        return 0;
    }

    // now the remaining command line args
    try {
        LinkedList<String> argList = new LinkedList<String>(Arrays.asList(cli.getArgs()));
        executeCommand(argList);
    } catch (UsageException e) {
        displayHelp();
        return 1;
    } catch (Throwable e) {
        System.err.println();
        System.err.println("Failed: " + e);
        e.printStackTrace();
        Set<Throwable> exceptions = new HashSet<Throwable>();
        exceptions.add(e);
        for (int i = 0; i < 10; i++) {
            e = e.getCause();
            if (e != null && exceptions.add(e)) {
                System.err.println("Reason: " + e);
                e.printStackTrace();
            } else {
                break;
            }
        }
        return 2;
    }
    return 0;
}