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

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

Introduction

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

Prototype

public String getMessage() 

Source Link

Document

Returns the detail message string of this throwable.

Usage

From source file:net.douglasthrift.bigscreenbot.BigScreenBot.java

public static void main(String[] args) {
    Options options = new Options();

    options.addOption("h", "help", false, "show this help message and exit");
    options.addOption("v", "verbose", false, "");

    CommandLine line = null;/*  w w w . ja  v a2 s .c  o m*/

    try {
        line = new GnuParser().parse(options, args);
    } catch (ParseException exception) {
        System.err.println("bigscreenbot: " + exception.getMessage());
    }

    if (line.hasOption('h')) {
        new HelpFormatter().printHelp("bigscreenbot", options, true);

        return;
    }

    new BigScreenBot(line.hasOption('v'));
}

From source file:com.archivas.clienttools.arcmover.cli.ArcProfileMgr.java

@SuppressWarnings({ "UseOfSystemOutOrSystemErr" })
public static void main(String args[]) {
    ArcProfileMgr arcProfileMgr = null;/*w  w  w .  j av  a 2  s  .  c  o m*/

    ConfigurationHelper.validateLaunchOK();

    try {
        arcProfileMgr = new ArcProfileMgr(args);
        arcProfileMgr.parseArgs();
        if (arcProfileMgr.printHelp) {
            System.out.println(arcProfileMgr.helpScreen());
        } else {
            arcProfileMgr.execute(new PrintWriter(System.out), new PrintWriter(System.err));
        }
    } catch (ParseException e) {
        System.out.println("Error: " + e.getMessage());
        System.out.println();
        System.out.println(arcProfileMgr.helpScreen());
        arcProfileMgr.setExitCode(EXIT_CODE_OPTION_PARSE_ERROR);
    } catch (Exception e) {
        LOG.log(Level.SEVERE, "Unexpected Exception.", e);
        System.out.println();
        System.out.println("Failed to create a new profile " + e.getMessage());
        arcProfileMgr.setExitCode(EXIT_CODE_DM_ERROR);
    } finally {
        if (arcProfileMgr != null) {
            arcProfileMgr.exit();
        }
    }
}

From source file:de.unisb.cs.st.javaslicer.slicing.Slicer.java

public static void main(String[] args) throws InterruptedException {
    Options options = createOptions();/*w w w.j  av a2s .  c om*/
    CommandLineParser parser = new GnuParser();
    CommandLine cmdLine;

    try {
        cmdLine = parser.parse(options, args, true);
    } catch (ParseException e) {
        System.err.println("Error parsing the command line arguments: " + e.getMessage());
        return;
    }

    if (cmdLine.hasOption('h')) {
        printHelp(options, System.out);
        System.exit(0);
    }

    String[] additionalArgs = cmdLine.getArgs();
    if (additionalArgs.length != 2) {
        printHelp(options, System.err);
        System.exit(-1);
    }
    // ?? 1. ? 2.?
    File traceFile = new File(additionalArgs[0]);
    String slicingCriterionString = additionalArgs[1];

    Long threadId = null;
    if (cmdLine.hasOption('t')) { // the interesting thread id for slicing 
        try {
            threadId = Long.parseLong(cmdLine.getOptionValue('t'));
        } catch (NumberFormatException e) {
            System.err.println("Illegal thread id: " + cmdLine.getOptionValue('t'));
            System.exit(-1);
        }
    }

    TraceResult trace;
    try {
        trace = TraceResult.readFrom(traceFile);
    } catch (IOException e) {
        System.err.format("Could not read the trace file \"%s\": %s%n", traceFile, e);
        System.exit(-1);
        return;
    }

    List<SlicingCriterion> sc = null; // a list contains the instruction's info corresponds to the slicing criterion
    //slicingCriterionString get from additionalArgs[1]
    try {
        sc = StaticSlicingCriterion.parseAll(slicingCriterionString, trace.getReadClasses());
    } catch (IllegalArgumentException e) {
        System.err.println("Error parsing slicing criterion: " + e.getMessage());
        System.exit(-1);
        return;
    }

    List<ThreadId> threads = trace.getThreads(); // the threads that generate the traces
    if (threads.size() == 0) {
        System.err.println("The trace file contains no tracing information.");
        System.exit(-1);
    }

    // threadID is used to mark the interesting thread
    ThreadId tracing = null;
    for (ThreadId t : threads) {
        if (threadId == null) {
            if ("main".equals(t.getThreadName())
                    && (tracing == null || t.getJavaThreadId() < tracing.getJavaThreadId()))
                tracing = t;
        } else if (t.getJavaThreadId() == threadId.longValue()) {
            tracing = t;
        }
    }

    if (tracing == null) {
        System.err.println(threadId == null ? "Couldn't find the main thread."
                : "The thread you specified was not found.");
        System.exit(-1);
        return;
    }

    long startTime = System.nanoTime();
    Slicer slicer = new Slicer(trace);
    if (cmdLine.hasOption("progress")) // the parameter process indicates that we need to monitor the process of slicing
        slicer.addProgressMonitor(new ConsoleProgressMonitor());
    boolean multithreaded;
    if (cmdLine.hasOption("multithreaded")) {
        String multithreadedStr = cmdLine.getOptionValue("multithreaded");
        multithreaded = ("1".equals(multithreadedStr) || "true".equals(multithreadedStr));
    } else {
        multithreaded = Runtime.getRuntime().availableProcessors() > 1;
    }

    boolean warnUntracedMethods = cmdLine.hasOption("warn-untraced"); // give some warns when encounters untraced functions

    //sliceInstructionCollector implements the interface slice visitor, which travel the dependence graph
    SliceInstructionsCollector collector = new SliceInstructionsCollector(); // the collector is used to collect the instructions in the dependence graph according to the slice criterion. 
    slicer.addSliceVisitor(collector);
    // zhushi by yhb

    if (warnUntracedMethods)
        slicer.addUntracedCallVisitor(new PrintUniqueUntracedMethods()); // the user need the untraced function info, so add untraced call visitor

    slicer.process(tracing, sc, multithreaded); //----------------------the key process of slicing!!!
    Set<InstructionInstance> slice = collector.getDynamicSlice(); // return the slice result from the collector
    long endTime = System.nanoTime();

    Instruction[] sliceArray = slice.toArray(new Instruction[slice.size()]); // convert the set to array
    Arrays.sort(sliceArray); // in order to ensure the sequence of dynamic execution

    // show the slicing result
    System.out.println("The dynamic slice for criterion " + sc + ":");
    for (Instruction insn : sliceArray) {
        System.out.format((Locale) null, "%s.%s:%d %s%n", insn.getMethod().getReadClass().getName(),
                insn.getMethod().getName(), insn.getLineNumber(), insn.toString());
    }
    System.out.format((Locale) null, "%nSlice consists of %d bytecode instructions.%n", sliceArray.length);
    System.out.format((Locale) null, "Computation took %.2f seconds.%n", 1e-9 * (endTime - startTime));
}

From source file:net.antidot.semantic.rdf.rdb2rdf.main.Db2triples.java

public static void main(String[] args) {
    // Get all options
    Options options = new Options();
    Options r2rmlOptions = new Options();
    Options dmOptions = new Options();
    options.addOption(modeOpt);//from ww  w . j  a  va2  s  .c  o  m
    options.addOption(userNameOpt);
    r2rmlOptions.addOption(userNameOpt);
    dmOptions.addOption(userNameOpt);
    options.addOption(passwordOpt);
    r2rmlOptions.addOption(passwordOpt);
    dmOptions.addOption(passwordOpt);
    options.addOption(URLOpt);
    r2rmlOptions.addOption(URLOpt);
    dmOptions.addOption(URLOpt);
    options.addOption(driverOpt);
    r2rmlOptions.addOption(driverOpt);
    dmOptions.addOption(driverOpt);
    options.addOption(dbOpt);
    r2rmlOptions.addOption(dbOpt);
    dmOptions.addOption(dbOpt);
    options.addOption(baseURIOpt);
    r2rmlOptions.addOption(baseURIOpt);
    dmOptions.addOption(baseURIOpt);
    options.addOption(forceOpt);
    r2rmlOptions.addOption(forceOpt);
    dmOptions.addOption(forceOpt);
    options.addOption(nativeOpt);
    r2rmlOptions.addOption(nativeOpt);
    dmOptions.addOption(nativeOpt);
    options.addOption(nativeStoreNameOpt);
    r2rmlOptions.addOption(nativeStoreNameOpt);
    dmOptions.addOption(nativeStoreNameOpt);
    options.addOption(outputOpt);
    r2rmlOptions.addOption(outputOpt);
    dmOptions.addOption(outputOpt);
    options.addOption(transformSPARQLFile);
    dmOptions.addOption(transformSPARQLFile);
    options.addOption(transformOutputFile);
    dmOptions.addOption(transformOutputFile);
    options.addOption(rdfFormat);
    r2rmlOptions.addOption(rdfFormat);
    dmOptions.addOption(rdfFormat);
    options.addOption(versionOpt);
    dmOptions.addOption(versionOpt);
    options.addOption(r2rmlFileOpt);
    r2rmlOptions.addOption(r2rmlFileOpt);

    // Init parameters
    String mode = null;
    String userName = null;
    String password = null;
    String url = null;
    DriverType driver = null;
    String dbName = null;
    String baseURI = null;
    boolean useNativeStore = false;
    boolean forceExistingRep = false;
    String nativeOutput = null;
    String output = null;
    String sparql = null;
    String sparqlOutput = null;
    String format = null;
    String r2rmlFile = null;
    int int_version = 1;

    // RDF Format output
    RDFFormat rdfFormat = RDFFormat.TURTLE; // Turtle by default
    // Norm version
    Version version = Version.WD_20120529;

    // Option parsing
    // Create the parser
    CommandLineParser parser = new GnuParser();
    try {
        // parse the command line arguments
        CommandLine line = parser.parse(options, args);
        // Database settings
        // Mode
        if (!line.hasOption("mode")) {
            // automatically generate the help statement
            log.error("Mode is required. Use -m option to set it.");
            HelpFormatter formatter = new HelpFormatter();
            formatter.printHelp(projectName, options);
            System.exit(-1);
        } else {
            mode = line.getOptionValue("mode");
            if (!mode.equals("r2rml") && !mode.equals("dm")) {
                log.error("Unkonw mode. Please select 'r2rml' or 'dm' mode.");
                HelpFormatter formatter = new HelpFormatter();
                formatter.printHelp(projectName, options);
                System.exit(-1);
            }
        }
        // user name
        if (!line.hasOption("user")) {
            // automatically generate the help statement
            log.error("User name is required. Use -u option to set it.");
            HelpFormatter formatter = new HelpFormatter();
            if (mode.equals("r2rml")) {
                formatter.printHelp(projectNameR2RMLMode, r2rmlOptions);
            } else {
                formatter.printHelp(projectNameDirectMappingMode, dmOptions);
            }
            System.exit(-1);
        } else {
            userName = line.getOptionValue("user");
        }
        // password
        if (!line.hasOption("pass")) {
            // automatically generate the help statement
            log.error("Password is required. Use -p option to set it.");
            HelpFormatter formatter = new HelpFormatter();
            if (mode.equals("r2rml")) {
                formatter.printHelp(projectNameR2RMLMode, r2rmlOptions);
            } else {
                formatter.printHelp(projectNameDirectMappingMode, dmOptions);
            }
            System.exit(-1);
        } else {
            password = line.getOptionValue("pass");
        }
        // Database URL
        url = line.getOptionValue("url", "jdbc:mysql://localhost/");
        // driver
        driver = new DriverType(line.getOptionValue("driver", defaultDriver.getDriverName()));
        // Database name
        if (!line.hasOption("database")) {
            // automatically generate the help statement
            log.error("Database name is required. Use -b option to set it.");
            HelpFormatter formatter = new HelpFormatter();
            if (mode.equals("r2rml")) {
                formatter.printHelp(projectNameR2RMLMode, r2rmlOptions);
            } else {
                formatter.printHelp(projectNameDirectMappingMode, dmOptions);
            }
            System.exit(-1);
        } else {
            dbName = line.getOptionValue("database");
        }
        // Base URI
        baseURI = line.getOptionValue("base_uri", "http://foo.example/DB/");
        // Use of native store ?
        useNativeStore = line.hasOption("n");
        // Name of native store
        if (useNativeStore && !line.hasOption("native_output")) {
            // automatically generate the help statement
            log.error("Native triplestore path is required. Use -n option to set it.");
            HelpFormatter formatter = new HelpFormatter();
            if (mode.equals("r2rml")) {
                formatter.printHelp(projectNameR2RMLMode, r2rmlOptions);
            } else {
                formatter.printHelp(projectNameDirectMappingMode, dmOptions);
            }
            System.exit(-1);
        } else {
            nativeOutput = line.getOptionValue("native_output");
        }
        // Force loading of repository
        forceExistingRep = line.hasOption("f");
        // Output
        output = line.getOptionValue("output", "output.ttl");
        // SPARQL transformation
        if (line.hasOption("sparql")) {
            if (!mode.equals("dm")) {
                log.warn("sparql option is required only for 'dm' mode : it will be ignored...");
            } else {
                sparql = line.getOptionValue("sparql");
                sparqlOutput = line.getOptionValue("sparql_output", "output_sparql.ttl");
            }
        }
        // RDF Format
        if (line.hasOption("format")) {
            format = line.getOptionValue("format");
            if (format.equals("TURTLE"))
                rdfFormat = RDFFormat.TURTLE;
            else if (format.equals("RDFXML"))
                rdfFormat = RDFFormat.RDFXML;
            else if (format.equals("NTRIPLES"))
                rdfFormat = RDFFormat.NTRIPLES;
            else if (!format.equals("N3")) {
                log.error("Unknown RDF format. Please use RDFXML, TURTLE, N3 or NTRIPLES.");
                HelpFormatter formatter = new HelpFormatter();
                if (mode.equals("r2rml")) {
                    formatter.printHelp(projectNameR2RMLMode, r2rmlOptions);
                } else {
                    formatter.printHelp(projectNameDirectMappingMode, dmOptions);
                }
                System.exit(-1);
            }
        }
        // Norm version
        if (line.hasOption("version")) {
            if (!mode.equals("dm")) {
                log.warn("version option is required only for 'dm' mode : it will be ignored...");
            }
            switch (int_version) {
            case 1:
                version = Version.WD_20120529;
                break;
            case 2:
                version = Version.WD_20110324;
                // Check DB compatibilities
                if (!(driver.equals(DriverType.MysqlDriver) || driver.equals(DriverType.PostgreSQL))) {
                    log.error(
                            "Db2triples in Direct Mapping mode does'nt support this driver for the Working Draft"
                                    + " of 23 March 2011 (only MySQL and PostGreSQL for this time). "
                                    + "You can set the version option to select Working Draft of 20 September 2011.");
                    System.exit(-1);
                }
                break;
            default:
                break;
            }
        }
        // r2rml instance
        if (mode.equals("r2rml")) {
            if (!line.hasOption("r2rml_file")) {
                log.error("R2RML config file is required. Use -r option to set it.");
                // automatically generate the help statement
                HelpFormatter formatter = new HelpFormatter();
                formatter.printHelp(projectNameR2RMLMode, r2rmlOptions);
                System.exit(-1);
            } else {
                r2rmlFile = line.getOptionValue("r2rml_file");
                File r2rmlFileTest = new File(r2rmlFile);
                if (!r2rmlFileTest.exists()) {
                    log.error("R2RML file does not exists.");
                    System.exit(-1);
                }
            }
        }
    } catch (ParseException exp) {
        // oops, something went wrong
        log.error("Parsing failed. Reason : " + exp.getMessage());
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp(projectName, options);
        System.exit(-1);
    }

    // Open test database
    Connection conn = null;
    try {
        // Connect database
        conn = SQLConnector.connect(userName, password, url + dbName, driver);

        // Generate RDF graph
        SesameDataSet g = null;
        // Check nature of storage (memory by default)
        if (useNativeStore) {
            File pathToNativeOutputDir = new File(nativeOutput);
            if (pathToNativeOutputDir.exists() && !forceExistingRep) {
                log.error("Directory " + pathToNativeOutputDir
                        + "  already exists. Use -f option to force loading of existing repository.");
                System.exit(-1);
            }
            // Extract database model according to convert mode
            if (mode.equals("r2rml")) {
                g = R2RMLProcessor.convertDatabase(conn, r2rmlFile, baseURI, nativeOutput, driver);
            } else {
                g = DirectMapper.generateDirectMapping(conn, version, driver, baseURI, null, nativeOutput);
            }
        } else {
            File outputFile = new File(output);
            if (outputFile.exists() && !forceExistingRep) {
                log.error("Output file " + outputFile.getAbsolutePath()
                        + " already exists. Please remove it or modify ouput name option.");
                System.exit(-1);
            }
            // Extract database model
            if (mode.equals("r2rml")) {
                g = R2RMLProcessor.convertDatabase(conn, r2rmlFile, baseURI, driver);
            } else {
                g = DirectMapper.generateDirectMapping(conn, version, driver, baseURI, null, null);
            }
            // Dump graph
            log.info("Serialize RDF graph...");
            g.dumpRDF(output, rdfFormat);
            log.info("RDF graph serialized into " + outputFile.getAbsolutePath());
        }
        if (sparql != null && mode.equals("dm")) {
            log.info("Execute SPARQL transformation...");
            Long start = System.currentTimeMillis();
            String result = g.runSPARQLFromFile(sparql, rdfFormat);
            SesameDataSet gResult = new SesameDataSet();
            gResult.addString(result, rdfFormat);
            gResult.dumpRDF(sparqlOutput, rdfFormat);

            Float stop = Float.valueOf(System.currentTimeMillis() - start) / 1000;
            log.info("Direct Mapping SPARQL query executed in " + stop + " seconds.");
            log.info("[DirectMapping:main] Number of triples after transformation : " + gResult.getSize());
        }
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        try {
            // Close db connection
            conn.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}

From source file:ca.twoducks.vor.ossindex.report.Assistant.java

/** Main method. Very simple, does not perform sanity checks on input.
 * /*w ww . ja  va  2s .  com*/
 * @param args
 * @throws IOException 
 */
public static void main(String[] args) throws IOException {
    CommandLineParser parser = new BasicParser();
    try {
        // parse the command line arguments
        CommandLine line = parser.parse(getOptions(), args);
        if (line.hasOption("help")) {
            HelpFormatter formatter = new HelpFormatter();
            formatter.printHelp("assistant", getOptions());
            return;
        }

        // Instantiate assistant
        Assistant assistant = new Assistant();

        // Add default plugins
        assistant.addScanPlugin(ChecksumPlugin.class);
        assistant.addScanPlugin(HtmlDependencyPlugin.class);
        assistant.addScanPlugin(NodeDependencyPlugin.class);
        assistant.addScanPlugin(MavenDependencyPlugin.class);
        assistant.addScanPlugin(GemfileDependencyPlugin.class);

        if (line.hasOption(NO_DEPENDENCIES_OPTION)) {
            assistant.setExportDependencies(false);
        } else {
            assistant.setExportDependencies(true);
        }
        assistant.setIncludeImages(!line.hasOption(NO_IMAGES_OPTION));
        assistant.setIncludeArtifacts(!line.hasOption(NO_ARTIFACTS_OPTION));

        // Determine operation type
        boolean doScan = line.hasOption("scan");
        boolean doMerge = line.hasOption("merge");
        boolean doImport = line.hasOption("import");
        int count = 0;
        if (doScan)
            count++;
        if (doMerge)
            count++;
        if (doImport)
            count++;
        if (count > 1) {
            System.err.println("Only one of 'scan', 'merge', or import may be selected");
            return;
        }

        if (doScan) {
            // Get the output directory
            if (!line.hasOption("D")) {
                System.err.println("An output directory must be specified");
                return;
            }
            File outputDir = new File(line.getOptionValue("D"));
            if (!outputDir.exists())
                outputDir.mkdir();
            if (!outputDir.isDirectory()) {
                System.err.println("Output option is not a directory: " + outputDir);
                return;
            }

            doScan(assistant, line.getOptionValue("scan"), outputDir, line.hasOption(VERBOSE_OUTPUT_OPTION));
            return;
        }

        if (doMerge) {
            // Get the output directory
            if (!line.hasOption("D")) {
                System.err.println("An output directory must be specified");
                return;
            }
            File outputDir = new File(line.getOptionValue("D"));
            if (!outputDir.exists())
                outputDir.mkdir();
            if (!outputDir.isDirectory()) {
                System.err.println("Output option is not a directory: " + outputDir);
                return;
            }

            doMerge(assistant, line.getOptionValues("merge"), outputDir);
            return;
        }

        if (doImport) {
            // Get the output directory
            if (!line.hasOption("D")) {
                System.err.println("An output directory must be specified");
                return;
            }
            File outputDir = new File(line.getOptionValue("D"));
            if (!outputDir.exists())
                outputDir.mkdir();
            if (!outputDir.isDirectory()) {
                System.err.println("Output option is not a directory: " + outputDir);
                return;
            }

            doImport(assistant, line.getOptionValue("import"), outputDir);
            return;
        }
    } catch (ParseException exp) {
        System.err.println("Parsing failed.  Reason: " + exp.getMessage());
    }

    HelpFormatter formatter = new HelpFormatter();
    formatter.printHelp("assistant", getOptions());
    return;
}

From source file:com.netscape.cms.servlet.test.CATest.java

public static void main(String args[]) {
    String host = null;//  ww  w .ja v  a2  s. c o  m
    String port = null;
    String token_pwd = null;
    String db_dir = "./";
    String protocol = "http";

    // parse command line arguments
    Options options = new Options();
    options.addOption("h", true, "Hostname of the CA");
    options.addOption("p", true, "Port of the CA");
    options.addOption("s", true, "Attempt Optional Secure SSL connection");
    options.addOption("w", true, "Token password");
    options.addOption("d", true, "Directory for tokendb");
    options.addOption("c", true, "Optional SSL Client cert Nickname");

    try {
        CommandLineParser parser = new PosixParser();
        CommandLine cmd = parser.parse(options, args);

        if (cmd.hasOption("h")) {
            host = cmd.getOptionValue("h");
        } else {
            System.err.println("Error: no hostname provided.");
            usage(options);
        }

        if (cmd.hasOption("p")) {
            port = cmd.getOptionValue("p");
        } else {
            System.err.println("Error: no port provided");
            usage(options);
        }

        if (cmd.hasOption("w")) {
            token_pwd = cmd.getOptionValue("w");
        } else {
            log("Notice: no token password provided");
        }

        if (cmd.hasOption("d")) {
            db_dir = cmd.getOptionValue("d");
        }

        if (cmd.hasOption("s")) {
            if (cmd.getOptionValue("s") != null && cmd.getOptionValue("s").equals("true")) {
                protocol = "https";
            }
        }

        if (cmd.hasOption("c")) {
            String nick = cmd.getOptionValue("c");

            if (nick != null && protocol.equals("https")) {
                clientCertNickname = nick;
            }
        }

    } catch (ParseException e) {
        System.err.println("Error in parsing command line options: " + e.getMessage());
        usage(options);
    }

    CryptoManager manager = null;
    CryptoToken token = null;

    // Initialize token
    try {
        CryptoManager.initialize(db_dir);
    } catch (AlreadyInitializedException e) {
        // it is ok if it is already initialized
    } catch (Exception e) {
        log("INITIALIZATION ERROR: " + e.toString());
        System.exit(1);
    }

    // log into token
    try {
        manager = CryptoManager.getInstance();
        token = manager.getInternalKeyStorageToken();
        Password password = new Password(token_pwd.toCharArray());
        try {
            token.login(password);
        } catch (Exception e) {
            log("login Exception: " + e.toString());
            if (!token.isLoggedIn()) {
                token.initPassword(password, password);
            }
        }
    } catch (Exception e) {
        log("Exception in logging into token:" + e.toString());
    }

    CAClient client;
    CACertClient certClient;
    ProfileClient profileClient;

    try {
        ClientConfig config = new ClientConfig();
        config.setServerURL(protocol + "://" + host + ":" + port);
        config.setCertNickname(clientCertNickname);

        client = new CAClient(new PKIClient(config, null));
        certClient = (CACertClient) client.getClient("cert");
        profileClient = (ProfileClient) client.getClient("profile");

    } catch (Exception e) {
        e.printStackTrace();
        return;
    }

    Collection<CertRequestInfo> list = null;
    try {
        list = certClient.listRequests("complete", null, null, null, null, null).getEntries();
    } catch (Exception e) {
        e.printStackTrace();
    }

    printRequests(list);

    //Get a CertInfo
    int certIdToPrint = 1;
    CertId id = new CertId(certIdToPrint);
    CertData certData = null;
    try {
        certData = certClient.getCert(id);
    } catch (CertNotFoundException e) {
        e.printStackTrace();
        log("Cert: " + certIdToPrint + " not found. \n" + e.toString());
    }

    printCertificate(certData);

    //Try an invalid Cert to print out
    //Get a CertInfo
    int certIdBadToPrint = 9999999;
    CertId certIdBad = new CertId(certIdBadToPrint);
    CertData certDataBad = null;
    try {
        certDataBad = certClient.getCert(certIdBad);
    } catch (CertNotFoundException e) {
        e.printStackTrace();
        log("Cert: " + certIdBadToPrint + " not found. \n" + e.toString());
    }

    printCertificate(certDataBad);

    //Get a CertInfoList

    CertDataInfos infos = null;
    try {
        infos = certClient.listCerts("VALID", null, null, null, null);
    } catch (Exception e) {
        e.printStackTrace();
    }

    printCertInfos(infos, "no search filter:");

    //Initiate a Certificate Enrollment

    CertEnrollmentRequest data = createUserCertEnrollment();
    enrollAndApproveCertRequest(certClient, data);

    // submit a RA authenticated user cert request
    CertEnrollmentRequest rdata = createRAUserCertEnrollment();
    enrollCertRequest(certClient, rdata);

    // now try a manually approved server cert
    CertEnrollmentRequest serverData = createServerCertEnrollment();
    enrollAndApproveCertRequest(certClient, serverData);

    // submit using an agent approval profile
    serverData.setProfileId("caAgentServerCert");
    enrollCertRequest(certClient, serverData);

    //Perform a sample certificate search with advanced search terms

    CertSearchRequest searchData = new CertSearchRequest();
    searchData.setSerialNumberRangeInUse(true);
    searchData.setSerialFrom("9999");
    searchData.setSerialTo("99990");

    infos = certClient.findCerts(searchData, 100, 10);

    printCertInfos(infos, new FilterBuilder(searchData).buildFilter());

    // Try to get a non existing request

    RequestId idBad = new RequestId("999999");

    CertRequestInfo infoBad = null;

    try {
        infoBad = certClient.getRequest(idBad);
    } catch (RequestNotFoundException e) {
        e.printStackTrace();
        log("Exception getting request #: " + idBad.toString() + "\n" + e.toString());
    }

    printRequestInfo(infoBad);

    //Perform another sample certificate search with advanced search terms

    searchData = new CertSearchRequest();
    searchData.setSubjectInUse(true);
    searchData.setEmail("jmagne@redhat.com");
    searchData.setMatchExactly(true);

    infos = certClient.findCerts(searchData, 100, 10);

    printCertInfos(infos, new FilterBuilder(searchData).buildFilter());

    //Get a list of Profiles

    ProfileDataInfos pInfos = profileClient.listProfiles(null, null);

    printProfileInfos(pInfos);

    // Get a specific profile
    String pId = "caUserCert";
    ProfileData pData = profileClient.retrieveProfile(pId);

    printProfileData(pData);

}

From source file:com.archivas.clienttools.arcmover.cli.ManagedCLIJob.java

@SuppressWarnings({ "UseOfSystemOutOrSystemErr" })
public static void main(String args[]) {
    if (LOG.isLoggable(Level.FINE)) {
        StringBuffer sb = new StringBuffer();
        sb.append("Program Arguments").append(NEWLINE);
        for (int i = 0; i < args.length; i++) {
            sb.append("    ").append(i).append(": ").append(args[i]);
            sb.append(NEWLINE);//from  w  ww.j a  v  a 2 s  . co m
        }
        LOG.log(Level.FINE, sb.toString());
    }

    ConfigurationHelper.validateLaunchOK();

    ManagedCLIJob arcCmd = null;
    try {
        if (args[0].equals("copy")) {
            arcCmd = new ArcCopy(args, 2);
        } else if (args[0].equals("delete")) {
            arcCmd = new ArcDelete(args, 2);
        } else if (args[0].equals("metadata")) {
            arcCmd = new ArcMetadata(args, 2);
        } else {
            throw new RuntimeException("Unsupported operation: " + args[0]);
        }

        arcCmd.parseArgs();

        if (arcCmd.shouldPrintHelp()) {
            System.out.println(arcCmd.helpScreen());
        } else {
            arcCmd.execute(new PrintWriter(System.out), new PrintWriter(System.err));
        }
    } catch (ParseException e) {
        System.out.println("Error: " + e.getMessage());
        System.out.println();
        System.out.println(arcCmd.helpScreen());
        arcCmd.setExitCode(EXIT_CODE_OPTION_PARSE_ERROR);
    } catch (Exception e) {
        LOG.log(Level.SEVERE, e.getMessage(), e);
        System.out.println();
        System.err.println("Job failed.  " + e.getMessage());
        if (arcCmd != null) {
            arcCmd.setExitCode(EXIT_CODE_DM_ERROR);
        }
    } finally {
        if (arcCmd != null) {
            arcCmd.exit();
        }
    }
}

From source file:erigo.filepump.FilePump.java

public static void main(String[] argsI) {

    boolean local_bShowGUI = true;

    String initial_outputFolder = ".";
    double initial_filesPerSec = 1.0;
    int initial_totNumFiles = 1000;
    String initial_mode_str = "local";
    String initial_ftpHost;/*from   w ww . ja v a  2  s  .  c  om*/
    String initial_ftpUser;
    String initial_ftpPassword;

    //
    // Parse command line arguments
    //
    // We use the Apche Commons CLI library to handle command line
    // arguments. See https://commons.apache.org/proper/commons-cli/usage.html
    // for examples, although note that we use the more up-to-date form
    // (Option.builder) to create Option objects.
    //
    // 1. Setup command line options
    //
    Options options = new Options();
    // Example of a Boolean option (i.e., only the flag, no argument goes with it)
    options.addOption("h", "help", false, "Print this message.");
    // The following example is for: -outputfolder <folder>    Location of output files
    Option outputFolderOption = Option.builder("outputfolder").argName("folder").hasArg()
            .desc("Location of output files; this folder must exist (it will not be created); default = \""
                    + initial_outputFolder + "\".")
            .build();
    options.addOption(outputFolderOption);
    Option filesPerSecOption = Option.builder("fps").argName("filespersec").hasArg()
            .desc("Desired file rate, files/sec; default = " + initial_filesPerSec + ".").build();
    options.addOption(filesPerSecOption);
    Option totNumFilesOption = Option.builder("totnum").argName("num").hasArg().desc(
            "Total number of output files; use -1 for unlimited number; default = " + initial_totNumFiles + ".")
            .build();
    options.addOption(totNumFilesOption);
    Option outputModeOption = Option.builder("mode").argName("mode").hasArg()
            .desc("Specifies output interface, one of <local|ftp|sftp>; default = " + initial_mode_str + ".")
            .build();
    options.addOption(outputModeOption);
    Option ftpHostOption = Option.builder("ftphost").argName("host").hasArg()
            .desc("Host name, for FTP or SFTP.").build();
    options.addOption(ftpHostOption);
    Option ftpUsernameOption = Option.builder("ftpuser").argName("user").hasArg()
            .desc("Username, for FTP or SFTP.").build();
    options.addOption(ftpUsernameOption);
    Option ftpPasswordOption = Option.builder("ftppass").argName("password").hasArg()
            .desc("Password, for FTP or SFTP.").build();
    options.addOption(ftpPasswordOption);
    Option autoRunOption = new Option("x", "Automatically run at startup.");
    options.addOption(autoRunOption);
    //
    // 2. Parse command line options
    //
    CommandLineParser parser = new DefaultParser();
    CommandLine line = null;
    try {
        line = parser.parse(options, argsI);
    } catch (ParseException exp) {
        // oops, something went wrong
        System.err.println("Command line argument parsing failed: " + exp.getMessage());
        return;
    }
    //
    // 3. Retrieve the command line values
    //
    if (line.hasOption("help")) {
        // Display help message and quit
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("FilePump", options);
        return;
    }
    if (line.hasOption("x")) {
        local_bShowGUI = false;
    }
    // Where to write the files to
    initial_outputFolder = line.getOptionValue("outputfolder", initial_outputFolder);
    // How many files per second the pump should output
    try {
        initial_filesPerSec = Double.parseDouble(line.getOptionValue("fps", "" + initial_filesPerSec));
    } catch (NumberFormatException nfe) {
        System.err.println("\nError parsing \"fps\" (it should be a floating point value):\n" + nfe);
        return;
    }
    // Total number of files to write out; -1 indicates unlimited
    try {
        initial_totNumFiles = Integer.parseInt(line.getOptionValue("totnum", "" + initial_totNumFiles));
    } catch (NumberFormatException nfe) {
        System.err.println("\nError parsing \"totnum\" (it should be an integer):\n" + nfe);
        return;
    }
    // Specifies how files will be written out
    initial_mode_str = line.getOptionValue("mode", initial_mode_str);
    if (!initial_mode_str.equals("local") && !initial_mode_str.equals("ftp")
            && !initial_mode_str.equals("sftp")) {
        System.err.println(new String("\nUnrecognized mode, \"" + initial_mode_str + "\""));
        return;
    }
    // FTP hostname
    initial_ftpHost = line.getOptionValue("ftphost", "");
    // FTP username
    initial_ftpUser = line.getOptionValue("ftpuser", "");
    // FTP password
    initial_ftpPassword = line.getOptionValue("ftppass", "");

    // Create the FilePump object
    new FilePump(local_bShowGUI, initial_outputFolder, initial_filesPerSec, initial_totNumFiles,
            initial_mode_str, initial_ftpHost, initial_ftpUser, initial_ftpPassword);

}

From source file:com.act.lcms.db.analysis.StandardIonAnalysis.java

public static void main(String[] args) throws Exception {
    Options opts = new Options();
    for (Option.Builder b : OPTION_BUILDERS) {
        opts.addOption(b.build());/* w ww.j a v  a 2  s . co  m*/
    }

    CommandLine cl = null;
    try {
        CommandLineParser parser = new DefaultParser();
        cl = parser.parse(opts, args);
    } catch (ParseException e) {
        System.err.format("Argument parsing failed: %s\n", e.getMessage());
        HELP_FORMATTER.printHelp(LoadPlateCompositionIntoDB.class.getCanonicalName(), HELP_MESSAGE, opts, null,
                true);
        System.exit(1);
    }

    if (cl.hasOption("help")) {
        HELP_FORMATTER.printHelp(LoadPlateCompositionIntoDB.class.getCanonicalName(), HELP_MESSAGE, opts, null,
                true);
        return;
    }

    File lcmsDir = new File(cl.getOptionValue(OPTION_DIRECTORY));
    if (!lcmsDir.isDirectory()) {
        System.err.format("File at %s is not a directory\n", lcmsDir.getAbsolutePath());
        HELP_FORMATTER.printHelp(LoadPlateCompositionIntoDB.class.getCanonicalName(), HELP_MESSAGE, opts, null,
                true);
        System.exit(1);
    }

    try (DB db = DB.openDBFromCLI(cl)) {
        ScanFile.insertOrUpdateScanFilesInDirectory(db, lcmsDir);
        StandardIonAnalysis analysis = new StandardIonAnalysis();
        HashMap<Integer, Plate> plateCache = new HashMap<>();

        String plateBarcode = cl.getOptionValue(OPTION_STANDARD_PLATE_BARCODE);
        String inputChemicals = cl.getOptionValue(OPTION_STANDARD_CHEMICAL);
        String medium = cl.getOptionValue(OPTION_MEDIUM);

        // If standard chemical is specified, do standard LCMS ion selection analysis
        if (inputChemicals != null && !inputChemicals.equals("")) {
            String[] chemicals;
            if (!inputChemicals.contains(",")) {
                chemicals = new String[1];
                chemicals[0] = inputChemicals;
            } else {
                chemicals = inputChemicals.split(",");
            }

            String outAnalysis = cl.getOptionValue(OPTION_OUTPUT_PREFIX) + "." + CSV_FORMAT;
            String plottingDirectory = cl.getOptionValue(OPTION_PLOTTING_DIR);
            String[] headerStrings = { "Molecule", "Plate Bar Code", "LCMS Detection Results" };
            CSVPrinter printer = new CSVPrinter(new FileWriter(outAnalysis),
                    CSVFormat.DEFAULT.withHeader(headerStrings));

            for (String inputChemical : chemicals) {
                List<StandardWell> standardWells;

                Plate queryPlate = Plate.getPlateByBarcode(db,
                        cl.getOptionValue(OPTION_STANDARD_PLATE_BARCODE));
                if (plateBarcode != null && medium != null) {
                    standardWells = analysis.getStandardWellsForChemicalInSpecificPlateAndMedium(db,
                            inputChemical, queryPlate.getId(), medium);
                } else if (plateBarcode != null) {
                    standardWells = analysis.getStandardWellsForChemicalInSpecificPlate(db, inputChemical,
                            queryPlate.getId());
                } else {
                    standardWells = analysis.getStandardWellsForChemical(db, inputChemical);
                }

                if (standardWells.size() == 0) {
                    throw new RuntimeException("Found no LCMS wells for " + inputChemical);
                }

                // Sort in descending order of media where MeOH and Water related media are promoted to the top and
                // anything derived from yeast media are demoted.
                Collections.sort(standardWells, new Comparator<StandardWell>() {
                    @Override
                    public int compare(StandardWell o1, StandardWell o2) {
                        if (StandardWell.doesMediaContainYeastExtract(o1.getMedia())
                                && !StandardWell.doesMediaContainYeastExtract(o2.getMedia())) {
                            return 1;
                        } else {
                            return 0;
                        }
                    }
                });

                Map<StandardWell, StandardIonResult> wellToIonRanking = StandardIonAnalysis
                        .getBestMetlinIonsForChemical(inputChemical, lcmsDir, db, standardWells,
                                plottingDirectory);

                if (wellToIonRanking.size() != standardWells.size()
                        && !cl.hasOption(OPTION_OVERRIDE_NO_SCAN_FILE_FOUND)) {
                    throw new Exception("Could not find a scan file associated with one of the standard wells");
                }

                for (StandardWell well : wellToIonRanking.keySet()) {
                    LinkedHashMap<String, XZ> snrResults = wellToIonRanking.get(well).getAnalysisResults();

                    String snrRankingResults = "";
                    int numResultsToShow = 0;

                    Plate plateForWellToAnalyze = Plate.getPlateById(db, well.getPlateId());

                    for (Map.Entry<String, XZ> ionToSnrAndTime : snrResults.entrySet()) {
                        if (numResultsToShow > 3) {
                            break;
                        }

                        String ion = ionToSnrAndTime.getKey();
                        XZ snrAndTime = ionToSnrAndTime.getValue();

                        snrRankingResults += String.format(ion + " (%.2f SNR at %.2fs); ",
                                snrAndTime.getIntensity(), snrAndTime.getTime());
                        numResultsToShow++;
                    }

                    String[] resultSet = { inputChemical,
                            plateForWellToAnalyze.getBarcode() + " " + well.getCoordinatesString() + " "
                                    + well.getMedia() + " " + well.getConcentration(),
                            snrRankingResults };

                    printer.printRecord(resultSet);
                }
            }

            try {
                printer.flush();
                printer.close();
            } catch (IOException e) {
                System.err.println("Error while flushing/closing csv writer.");
                e.printStackTrace();
            }
        } else {
            // Get the set of chemicals that includes the construct and all it's intermediates
            Pair<ConstructEntry, List<ChemicalAssociatedWithPathway>> constructAndPathwayChems = analysis
                    .getChemicalsForConstruct(db, cl.getOptionValue(OPTION_CONSTRUCT));
            System.out.format("Construct: %s\n", constructAndPathwayChems.getLeft().getCompositionId());

            for (ChemicalAssociatedWithPathway pathwayChem : constructAndPathwayChems.getRight()) {
                System.out.format("  Pathway chem %s\n", pathwayChem.getChemical());

                // Get all the standard wells for the pathway chemicals. These wells contain only the
                // the chemical added with controlled solutions (ie no organism or other chemicals in the
                // solution)

                List<StandardWell> standardWells;

                if (plateBarcode != null) {
                    Plate queryPlate = Plate.getPlateByBarcode(db,
                            cl.getOptionValue(OPTION_STANDARD_PLATE_BARCODE));
                    standardWells = analysis.getStandardWellsForChemicalInSpecificPlate(db,
                            pathwayChem.getChemical(), queryPlate.getId());
                } else {
                    standardWells = analysis.getStandardWellsForChemical(db, pathwayChem.getChemical());
                }

                for (StandardWell wellToAnalyze : standardWells) {
                    List<StandardWell> negativeControls = analysis.getViableNegativeControlsForStandardWell(db,
                            wellToAnalyze);
                    Map<StandardWell, List<ScanFile>> allViableScanFiles = analysis
                            .getViableScanFilesForStandardWells(db, wellToAnalyze, negativeControls);

                    List<String> primaryStandardScanFileNames = new ArrayList<>();
                    for (ScanFile scanFile : allViableScanFiles.get(wellToAnalyze)) {
                        primaryStandardScanFileNames.add(scanFile.getFilename());
                    }
                    Plate plate = plateCache.get(wellToAnalyze.getPlateId());
                    if (plate == null) {
                        plate = Plate.getPlateById(db, wellToAnalyze.getPlateId());
                        plateCache.put(plate.getId(), plate);
                    }

                    System.out.format("    Standard well: %s @ %s, '%s'%s%s\n", plate.getBarcode(),
                            wellToAnalyze.getCoordinatesString(), wellToAnalyze.getChemical(),
                            wellToAnalyze.getMedia() == null ? ""
                                    : String.format(" in %s", wellToAnalyze.getMedia()),
                            wellToAnalyze.getConcentration() == null ? ""
                                    : String.format(" @ %s", wellToAnalyze.getConcentration()));
                    System.out.format("      Scan files: %s\n",
                            StringUtils.join(primaryStandardScanFileNames, ", "));

                    for (StandardWell negCtrlWell : negativeControls) {
                        plate = plateCache.get(negCtrlWell.getPlateId());
                        if (plate == null) {
                            plate = Plate.getPlateById(db, negCtrlWell.getPlateId());
                            plateCache.put(plate.getId(), plate);
                        }
                        List<String> negativeControlScanFileNames = new ArrayList<>();
                        for (ScanFile scanFile : allViableScanFiles.get(negCtrlWell)) {
                            negativeControlScanFileNames.add(scanFile.getFilename());
                        }

                        System.out.format("      Viable negative: %s @ %s, '%s'%s%s\n", plate.getBarcode(),
                                negCtrlWell.getCoordinatesString(), negCtrlWell.getChemical(),
                                negCtrlWell.getMedia() == null ? ""
                                        : String.format(" in %s", negCtrlWell.getMedia()),
                                negCtrlWell.getConcentration() == null ? ""
                                        : String.format(" @ %s", negCtrlWell.getConcentration()));
                        System.out.format("        Scan files: %s\n",
                                StringUtils.join(negativeControlScanFileNames, ", "));
                        // TODO: do something useful with the standard wells and their scan files, and then stop all the printing.
                    }
                }
            }
        }
    }
}

From source file:io.s4.util.LoadGenerator.java

public static void main(String args[]) {
    Options options = new Options();
    boolean warmUp = false;

    options.addOption(//from ww w.  j a  v  a 2s .c om
            OptionBuilder.withArgName("rate").hasArg().withDescription("Rate (events per second)").create("r"));

    options.addOption(OptionBuilder.withArgName("display_rate").hasArg()
            .withDescription("Display Rate at specified second boundary").create("d"));

    options.addOption(OptionBuilder.withArgName("start_boundary").hasArg()
            .withDescription("Start boundary in seconds").create("b"));

    options.addOption(OptionBuilder.withArgName("run_for").hasArg()
            .withDescription("Run for a specified number of seconds").create("x"));

    options.addOption(OptionBuilder.withArgName("cluster_manager").hasArg().withDescription("Cluster manager")
            .create("z"));

    options.addOption(OptionBuilder.withArgName("sender_application_name").hasArg()
            .withDescription("Sender application name").create("a"));

    options.addOption(OptionBuilder.withArgName("listener_application_name").hasArg()
            .withDescription("Listener application name").create("g"));

    options.addOption(
            OptionBuilder.withArgName("sleep_overhead").hasArg().withDescription("Sleep overhead").create("o"));

    options.addOption(new Option("w", "Warm-up"));

    CommandLineParser parser = new GnuParser();

    CommandLine line = null;
    try {
        // parse the command line arguments
        line = parser.parse(options, args);
    } catch (ParseException exp) {
        // oops, something went wrong
        System.err.println("Parsing failed.  Reason: " + exp.getMessage());
        System.exit(1);
    }

    int expectedRate = 250;
    if (line.hasOption("r")) {
        try {
            expectedRate = Integer.parseInt(line.getOptionValue("r"));
        } catch (Exception e) {
            System.err.println("Bad expected rate specified " + line.getOptionValue("r"));
            System.exit(1);
        }
    }

    int displayRateIntervalSeconds = 20;
    if (line.hasOption("d")) {
        try {
            displayRateIntervalSeconds = Integer.parseInt(line.getOptionValue("d"));
        } catch (Exception e) {
            System.err.println("Bad display rate value specified " + line.getOptionValue("d"));
            System.exit(1);
        }
    }

    int startBoundary = 2;
    if (line.hasOption("b")) {
        try {
            startBoundary = Integer.parseInt(line.getOptionValue("b"));
        } catch (Exception e) {
            System.err.println("Bad start boundary value specified " + line.getOptionValue("b"));
            System.exit(1);
        }
    }

    int updateFrequency = 0;
    if (line.hasOption("f")) {
        try {
            updateFrequency = Integer.parseInt(line.getOptionValue("f"));
        } catch (Exception e) {
            System.err.println("Bad query udpdate frequency specified " + line.getOptionValue("f"));
            System.exit(1);
        }
        System.out.printf("Update frequency is %d\n", updateFrequency);
    }

    int runForTime = 0;
    if (line.hasOption("x")) {
        try {
            runForTime = Integer.parseInt(line.getOptionValue("x"));
        } catch (Exception e) {
            System.err.println("Bad run for time specified " + line.getOptionValue("x"));
            System.exit(1);
        }
        System.out.printf("Run for time is %d\n", runForTime);
    }

    String clusterManagerAddress = null;
    if (line.hasOption("z")) {
        clusterManagerAddress = line.getOptionValue("z");
    }

    String senderApplicationName = null;
    if (line.hasOption("a")) {
        senderApplicationName = line.getOptionValue("a");
    }

    String listenerApplicationName = null;
    if (line.hasOption("a")) {
        listenerApplicationName = line.getOptionValue("g");
    }

    if (listenerApplicationName == null) {
        listenerApplicationName = senderApplicationName;
    }

    long sleepOverheadMicros = -1;
    if (line.hasOption("o")) {
        try {
            sleepOverheadMicros = Long.parseLong(line.getOptionValue("o"));
        } catch (NumberFormatException e) {
            System.err.println("Bad sleep overhead specified " + line.getOptionValue("o"));
            System.exit(1);
        }
        System.out.printf("Specified sleep overhead is %d\n", sleepOverheadMicros);
    }

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

    List loArgs = line.getArgList();
    if (loArgs.size() < 1) {
        System.err.println("No input file specified");
        System.exit(1);
    }

    String inputFilename = (String) loArgs.get(0);

    EventEmitter emitter = null;

    SerializerDeserializer serDeser = new KryoSerDeser();

    CommLayerEmitter clEmitter = new CommLayerEmitter();
    clEmitter.setAppName(senderApplicationName);
    clEmitter.setListenerAppName(listenerApplicationName);
    clEmitter.setClusterManagerAddress(clusterManagerAddress);
    clEmitter.setSenderId(String.valueOf(System.currentTimeMillis() / 1000));
    clEmitter.setSerDeser(serDeser);
    clEmitter.init();
    emitter = clEmitter;

    long endTime = 0;
    if (runForTime > 0) {
        endTime = System.currentTimeMillis() + (runForTime * 1000);
    }

    LoadGenerator loadGenerator = new LoadGenerator();
    loadGenerator.setInputFilename(inputFilename);
    loadGenerator.setEventEmitter(clEmitter);
    loadGenerator.setDisplayRateInterval(displayRateIntervalSeconds);
    loadGenerator.setExpectedRate(expectedRate);
    loadGenerator.run();

    System.exit(0);
}