Example usage for org.apache.commons.cli DefaultParser DefaultParser

List of usage examples for org.apache.commons.cli DefaultParser DefaultParser

Introduction

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

Prototype

DefaultParser

Source Link

Usage

From source file:com.movielabs.availstool.AvailsTool.java

public static void main(String[] args) throws Exception {
    String fileName, outFile, sheetName;
    int sheetNum = -1;

    Logger log = LogManager.getLogger(AvailsTool.class.getName());
    log.info("Initializing logger");

    Options options = new Options();
    options.addOption(Opts.v.name(), false, "verbose mode");
    options.addOption(Opts.s.name(), true, "specify sheet");
    options.addOption(Opts.f.name(), true, "specify file name");
    options.addOption(Opts.o.name(), true, "specify output file name");
    options.addOption(Opts.sstoxml.name(), false, "convert avails spreadsheet to XML");
    options.addOption(Opts.xmltoss.name(), false, "convert avails XML to a spreadsheet");
    options.addOption(Opts.dumpsheet.name(), false, "dump a single sheet from a spreadsheet");
    options.addOption(Opts.dumpss.name(), false, "dump a spreadsheet file");
    options.addOption(Opts.wx.name(), false, "treat warning as fatal error");
    options.addOption(Opts.clean.name(), false, "clean up data entries");

    CommandLineParser cli = new DefaultParser();

    try {//from ww  w  .  j a  va  2 s. c  o m
        CommandLine cmd = cli.parse(options, args);
        boolean optToXML = cmd.hasOption(Opts.sstoxml.name());
        boolean optToSS = cmd.hasOption(Opts.xmltoss.name());
        boolean optDumpSS = cmd.hasOption(Opts.dumpss.name());
        boolean optDumpSheet = cmd.hasOption(Opts.dumpsheet.name());
        fileName = cmd.getOptionValue(Opts.f.name());
        sheetName = cmd.getOptionValue(Opts.s.name());
        boolean clean = cmd.hasOption(Opts.clean.name());
        boolean wx = cmd.hasOption(Opts.wx.name());
        boolean verbose = cmd.hasOption(Opts.v.name());
        AvailSS ss;
        AvailsSheet as;
        String message;

        if (sheetName != null) {
            Pattern pat = Pattern.compile("^\\d+$");
            Matcher m = pat.matcher(sheetName);
            if (m.matches())
                sheetNum = Integer.parseInt(sheetName);
        }

        if (fileName == null)
            throw new ParseException("input file not specified");

        if (!(optToXML | optToSS | optDumpSS | optDumpSheet))
            throw new ParseException("missing operation");

        if (optToXML) {
            if (optToSS | optDumpSS | optDumpSheet)
                throw new ParseException("more than one operation specified");
            outFile = cmd.getOptionValue(Opts.o.name());
            if (outFile == null)
                throw new ParseException("output file not specified");

            ss = new AvailSS(fileName, log, wx, clean);
            if (sheetNum < 0)
                as = ss.addSheet(sheetName);
            else
                as = ss.addSheet(sheetNum);
            message = "toXML file: " + fileName + " sheet: " + sheetName;
            log.info(message);
            if (verbose)
                System.out.println(message);
            log.info("Options: -clean:" + clean + "; -wx:" + wx + "; output file: " + outFile);
            String timeStamp = new SimpleDateFormat("yyyy.MM.dd.HH.mm.ss").format(new java.util.Date());
            String shortDesc = String.format("generated XML from %s:%s on %s", fileName, sheetName, timeStamp);
            as.makeXMLFile(outFile, shortDesc);
        } else if (optToSS) {
            if (optToXML | optDumpSS | optDumpSheet)
                throw new ParseException("more than one operation specified");
            // TODO implement this
            outFile = cmd.getOptionValue(Opts.o.name());
            if (outFile == null)
                throw new ParseException("output file not specified");
            AvailXML x = new AvailXML(fileName, log);
            x.makeSS(outFile);
        } else if (optDumpSS) {
            if (optToXML | optToSS | optDumpSheet)
                throw new ParseException("more than one operation specified");
            message = "dumping file: " + fileName;
            log.info(message);
            if (verbose)
                System.out.println(message);
            AvailSS.dumpFile(fileName);
        } else { // dumpSheet
            if (sheetName == null)
                throw new ParseException("sheet name not specified");
            message = "dumping file: " + fileName + " sheet: " + sheetName;
            log.info(message);
            if (verbose)
                System.out.println(message);
            ss = new AvailSS(fileName, log, wx, clean);
            if (sheetNum < 0)
                as = ss.addSheet(sheetName);
            else
                as = ss.addSheet(sheetNum);

            ss.dumpSheet(sheetName);
        }
    } catch (ParseException exp) {
        System.out.println("bad command line: " + exp.getMessage());
        usage();
        System.exit(-1);
    }
}

From source file:com.act.lcms.db.io.LoadStandardIonAnalysisTableIntoDB.java

public static void main(String[] args) throws Exception {
    Options opts = new Options();
    for (Option.Builder b : OPTION_BUILDERS) {
        opts.addOption(b.build());/*from   ww  w . jav  a  2  s .c  o 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(LoadStandardIonAnalysisTableIntoDB.class.getCanonicalName(), HELP_MESSAGE,
                opts, null, true);
        System.exit(1);
    }

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

    File inputFile = new File(cl.getOptionValue(OPTION_FILE_PATH));
    if (!inputFile.exists()) {
        System.err.format("Unable to find input file at %s\n", cl.getOptionValue(OPTION_FILE_PATH));
        new HelpFormatter().printHelp(LoadConstructAnalysisTableIntoDB.class.getCanonicalName(), opts, true);
        System.exit(1);
    }

    try (DB db = DB.openDBFromCLI(cl)) {
        db.getConn().setAutoCommit(false);

        TSVParser parser = new TSVParser();
        parser.parse(inputFile);

        for (Map<String, String> row : parser.getResults()) {
            Integer standardIonResultId = Integer.parseInt(row.get(
                    ExportStandardIonResultsFromDB.STANDARD_ION_HEADER_FIELDS.STANDARD_ION_RESULT_ID.name()));

            String dbValueOfMetlinIon = ExportStandardIonResultsFromDB.NULL_VALUE;
            StandardIonResult ionResult = StandardIonResult.getInstance().getById(db, standardIonResultId);
            if (ionResult.getManualOverrideId() != null) {
                // There is an existing manual override ion in the DB
                CuratedStandardMetlinIon curatedChemical = CuratedStandardMetlinIon.getBestMetlinIon(db,
                        ionResult.getManualOverrideId());
                dbValueOfMetlinIon = curatedChemical.getBestMetlinIon();
            }

            String manualPickOfMetlinIon = row
                    .get(ExportStandardIonResultsFromDB.STANDARD_ION_HEADER_FIELDS.MANUAL_PICK.name());

            // If the manual metlin ion pick row is not NULL and it is not the same as the value stored in the DB, then
            // we need to add a new entry to the curated metlin ion table.
            if (!manualPickOfMetlinIon.equals(ExportStandardIonResultsFromDB.NULL_VALUE)
                    && !manualPickOfMetlinIon.equals(dbValueOfMetlinIon)) {
                System.out.format("Manual override has been found, so updating the DB\n");
                // A manual entry was created.
                if (!MS1.VALID_MS1_IONS.contains(manualPickOfMetlinIon)) {
                    System.err.format("ERROR: found invalid chemical name: %s\n", manualPickOfMetlinIon);
                    System.exit(-1);
                }

                String note = row.get(ExportStandardIonResultsFromDB.STANDARD_ION_HEADER_FIELDS.NOTE.name());
                CuratedStandardMetlinIon result = CuratedStandardMetlinIon.insertCuratedStandardMetlinIonIntoDB(
                        db, LocalDateTime.now(CuratedStandardMetlinIon.utcDateTimeZone),
                        cl.getOptionValue(OPTION_AUTHOR), manualPickOfMetlinIon, note, standardIonResultId);

                if (result == null) {
                    System.err.format(
                            "WARNING: Could not insert curated entry to the curated metlin ion table\n",
                            manualPickOfMetlinIon);
                    System.exit(-1);
                } else {
                    StandardIonResult getIonResult = StandardIonResult.getInstance().getById(db,
                            standardIonResultId);
                    getIonResult.setManualOverrideId(result.getId());
                    if (!StandardIonResult.getInstance().update(db, getIonResult)) {
                        System.err.format(
                                "WARNING: Could not insert manual override id to the standard ion table\n",
                                manualPickOfMetlinIon);
                        System.exit(-1);
                    } else {
                        System.out.format(
                                "Successfully committed updates to the standard ion table and the curated metlin ion table\n");
                    }
                }
            }
        }

        db.getConn().commit();
    }
}

From source file:com.act.lcms.db.io.ExportPlateCompositionFromDB.java

public static void main(String[] args) throws Exception {
    Options opts = new Options();
    opts.addOption(Option.builder("b").argName("barcode").desc("The barcode of the plate to print").hasArg()
            .longOpt("barcode").build());
    opts.addOption(Option.builder("n").argName("name").desc("The name of the plate to print").hasArg()
            .longOpt("name").build());

    opts.addOption(Option.builder("o").argName("output file").desc(
            "An output file to which to write this plate's composition table (writes to stdout if omitted")
            .hasArg().longOpt("output-file").build());

    // DB connection options.
    opts.addOption(Option.builder().argName("database url")
            .desc("The url to use when connecting to the LCMS db").hasArg().longOpt("db-url").build());
    opts.addOption(Option.builder("u").argName("database user").desc("The LCMS DB user").hasArg()
            .longOpt("db-user").build());
    opts.addOption(Option.builder("p").argName("database password").desc("The LCMS DB password").hasArg()
            .longOpt("db-pass").build());
    opts.addOption(Option.builder("H").argName("database host")
            .desc(String.format("The LCMS DB host (default = %s)", DB.DEFAULT_HOST)).hasArg().longOpt("db-host")
            .build());//  w w  w.j  ava2 s.co  m
    opts.addOption(Option.builder("P").argName("database port")
            .desc(String.format("The LCMS DB port (default = %d)", DB.DEFAULT_PORT)).hasArg().longOpt("db-port")
            .build());
    opts.addOption(Option.builder("N").argName("database name")
            .desc(String.format("The LCMS DB name (default = %s)", DB.DEFAULT_DB_NAME)).hasArg()
            .longOpt("db-name").build());

    // Everybody needs a little help from their friends.
    opts.addOption(
            Option.builder("h").argName("help").desc("Prints this help message").longOpt("help").build());

    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());
        new HelpFormatter().printHelp(LoadPlateCompositionIntoDB.class.getCanonicalName(), opts, true);
        System.exit(1);
    }

    if (cl.hasOption("help")) {
        new HelpFormatter().printHelp(LoadPlateCompositionIntoDB.class.getCanonicalName(), opts, true);
        return;
    }

    if (!cl.hasOption("b") && !cl.hasOption("n")) {
        System.err.format("Must specify either plate barcode or plate name.");
        new HelpFormatter().printHelp(LoadPlateCompositionIntoDB.class.getCanonicalName(), opts, true);
        System.exit(1);
    }

    DB db = null;
    try {
        if (cl.hasOption("db-url")) {
            db = new DB().connectToDB(cl.getOptionValue("db-url"));
        } else {
            Integer port = null;
            if (cl.getOptionValue("P") != null) {
                port = Integer.parseInt(cl.getOptionValue("P"));
            }
            db = new DB().connectToDB(cl.getOptionValue("H"), port, cl.getOptionValue("N"),
                    cl.getOptionValue("u"), cl.getOptionValue("p"));
        }

        Writer writer = null;
        if (cl.hasOption("o")) {
            writer = new FileWriter(cl.getOptionValue("o"));
        } else {
            writer = new OutputStreamWriter(System.out);
        }

        PlateCompositionWriter cw = new PlateCompositionWriter();
        if (cl.hasOption("b")) {
            cw.writePlateCompositionByBarcode(db, cl.getOptionValue("b"), writer);
        } else if (cl.hasOption("n")) {
            cw.writePlateCompositionByName(db, cl.getOptionValue("n"), writer);
        }

        writer.close();
    } finally {
        if (db != null) {
            db.close();
        }
    }
}

From source file:com.blackducksoftware.integration.hubdiff.HubDiff.java

public static void main(String[] args) throws IOException, IllegalArgumentException, EncryptionException,
        HubIntegrationException, JSONException {
    Options options = new Options();
    Option optUrl1 = new Option("h1", "hub-url-1", true,
            "the base url to the hub. Example: http://int-hub01.dc1.lan:8080");
    Option optUsername1 = new Option("u1", "username-1", true, "the username for your hub instance");
    Option optPassword1 = new Option("p1", "password-1", true,
            "the password for your hub instance and username");
    Option optUrl2 = new Option("h2", "hub-url-2", true,
            "the base url to the hub. Example: http://int-auto.dc1.lan:9000");
    Option optUsername2 = new Option("u2", "username-2", true, "the username for your hub instance");
    Option optPassword2 = new Option("p2", "password-2", true,
            "the password for your hub instance and username");
    Option optOutputFile = new Option("o", "output", true, "the file path to your output file");

    optUrl1.setRequired(true);/*www  . jav  a 2 s.c  o  m*/
    optUsername1.setRequired(true);
    optPassword1.setRequired(true);
    optUsername2.setRequired(true);
    optUrl1.setRequired(true);
    optPassword2.setRequired(true);
    optOutputFile.setRequired(false);

    // Add options to collection
    options.addOption(optUrl1);
    options.addOption(optUsername1);
    options.addOption(optPassword1);
    options.addOption(optUrl2);
    options.addOption(optUsername2);
    options.addOption(optPassword2);
    options.addOption(optOutputFile);

    // Parse the arguments array for the options
    CommandLineParser cliParser = new DefaultParser();
    HelpFormatter formatter = new HelpFormatter();
    CommandLine optionParser;
    try {
        optionParser = cliParser.parse(options, args);
    } catch (ParseException e) {
        formatter.printHelp("hub-model-generator", options);
        log.error(e.getMessage());
        System.exit(1);
        return;
    }

    // Read arguments
    String url1 = optionParser.getOptionValue("hub-url-1");
    String username1 = optionParser.getOptionValue("username-1");
    String password1 = optionParser.getOptionValue("password-1");
    String url2 = optionParser.getOptionValue("hub-url-2");
    String username2 = optionParser.getOptionValue("username-2");
    String password2 = optionParser.getOptionValue("password-2");
    String outputFilePath = optionParser.getOptionValue("output");

    HubServerConfigBuilder configBuilder = new HubServerConfigBuilder();
    configBuilder.setHubUrl(url1);
    configBuilder.setUsername(username1);
    configBuilder.setPassword(password1);
    HubServerConfig config1 = configBuilder.build();

    HubServerConfigBuilder configBuilder2 = new HubServerConfigBuilder();
    configBuilder2.setHubUrl(url2);
    configBuilder2.setUsername(username2);
    configBuilder2.setPassword(password2);
    HubServerConfig config2 = configBuilder2.build();

    HubDiff hubDiff = new HubDiff(config1, config2);
    hubDiff.printDiff(System.out);

    if (outputFilePath != null) {
        File outputFile = new File(outputFilePath);
        hubDiff.writeDiffAsCSV(outputFile);
    }
}

From source file:com.act.biointerpretation.desalting.ChemicalDesalter.java

public static void main(String[] args) throws Exception {
    Options opts = new Options();
    for (Option.Builder b : OPTION_BUILDERS) {
        opts.addOption(b.build());//w w w.  j a v  a2  s .c o 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(ReactionDesalter.class.getCanonicalName(), HELP_MESSAGE, opts, null, true);
        return;
    }

    ChemicalDesalter runner = new ChemicalDesalter();
    String outAnalysis = cl.getOptionValue(OPTION_OUTPUT_PREFIX);
    if (cl.hasOption(OPTION_INCHI_INPUT_LIST)) {
        File inputFile = new File(cl.getOptionValue(OPTION_INCHI_INPUT_LIST));
        if (!inputFile.exists()) {
            System.err.format("Cannot find input file at %s\n", inputFile.getAbsolutePath());
            HELP_FORMATTER.printHelp(LoadPlateCompositionIntoDB.class.getCanonicalName(), HELP_MESSAGE, opts,
                    null, true);
            System.exit(1);
        }
        runner.exampleChemicalsList(outAnalysis, inputFile);
    }
}

From source file:com.hpe.nv.samples.basic.BasicNVTest.java

public static void main(String[] args) {
    try {//  ww  w.j  a va  2  s  .c  o m
        // program arguments
        Options options = new Options();
        options.addOption("i", "server-ip", true, "[mandatory] NV Test Manager IP");
        options.addOption("o", "server-port", true, "[mandatory] NV Test Manager port");
        options.addOption("u", "username", true, "[mandatory] NV username");
        options.addOption("w", "password", true, "[mandatory] NV password");
        options.addOption("e", "ssl", true, "[optional] Pass true to use SSL. Default: false");
        options.addOption("y", "proxy", true, "[optional] Proxy server host:port");
        options.addOption("b", "browser", true,
                "[optional] The browser for which the Selenium WebDriver is built. Possible values: Chrome and Firefox. Default: Firefox");
        options.addOption("d", "debug", true,
                "[optional] Pass true to view console debug messages during execution. Default: false");
        options.addOption("h", "help", false, "[optional] Generates and prints help information");

        // parse and validate the command line arguments
        CommandLineParser parser = new DefaultParser();
        CommandLine line = parser.parse(options, args);

        if (line.hasOption("help")) {
            // print help if help argument is passed
            HelpFormatter formatter = new HelpFormatter();
            formatter.printHelp("BasicNVTest.java", options);
            return;
        }

        if (line.hasOption("server-ip")) {
            serverIp = line.getOptionValue("server-ip");
            if (serverIp.equals("0.0.0.0")) {
                throw new Exception(
                        "Please replace the server IP argument value (0.0.0.0) with your NV Test Manager IP");
            }
        } else {
            throw new Exception("Missing argument -i/--server-ip <serverIp>");
        }

        if (line.hasOption("server-port")) {
            serverPort = Integer.parseInt(line.getOptionValue("server-port"));
        } else {
            throw new Exception("Missing argument -o/--server-port <serverPort>");
        }

        if (line.hasOption("username")) {
            username = line.getOptionValue("username");
        } else {
            throw new Exception("Missing argument -u/--username <username>");
        }

        if (line.hasOption("password")) {
            password = line.getOptionValue("password");
        } else {
            throw new Exception("Missing argument -w/--password <password>");
        }

        if (line.hasOption("ssl")) {
            ssl = Boolean.parseBoolean(line.getOptionValue("ssl"));
        }

        if (line.hasOption("proxy")) {
            proxySetting = line.getOptionValue("proxy");
        }

        if (line.hasOption("browser")) {
            browser = line.getOptionValue("browser");
        } else {
            browser = "Firefox";
        }

        if (line.hasOption("debug")) {
            debug = Boolean.parseBoolean(line.getOptionValue("debug"));
        }

        String newLine = System.getProperty("line.separator");
        String testDescription = "***   This sample demonstrates the use of the most basic NV methods.                               ***"
                + newLine
                + "***                                                                                                ***"
                + newLine
                + "***   First, the sample creates a TestManager object and initializes it.                           ***"
                + newLine
                + "***   The sample starts an NV test over an emulated \"3G Busy\" network.                             ***"
                + newLine
                + "***   (\"3G Busy\" is one of NV's built-in network profiles. A network profile specifies the         ***"
                + newLine
                + "***   network traffic behavior, including latency, packet loss, and incoming/outgoing bandwidth.   ***"
                + newLine
                + "***   Network profiles are used to emulate traffic over real-world networks.)                      ***"
                + newLine
                + "***                                                                                                ***"
                + newLine
                + "***   Next, the sample navigates to the home page in the HPE Network Virtualization website        ***"
                + newLine
                + "***   using the Selenium WebDriver.                                                                ***"
                + newLine
                + "***                                                                                                ***"
                + newLine
                + "***   Finally, the sample stops the NV test.                                                       ***"
                + newLine
                + "***                                                                                                ***"
                + newLine
                + "***   You can view the actual steps of this sample in the BasicNVTest.java file.                   ***"
                + newLine;

        // print the sample's description
        System.out.println(testDescription);

        // start console spinner
        if (!debug) {
            spinner = new Thread(new Spinner());
            spinner.start();
        }

        // sample execution steps
        /*****    Part 1 - Create a TestManager object and initialize it                                   *****/
        printPartDescription("\b------    Part 1 - Create a TestManager object and initialize it");
        initTestManager();
        printPartSeparator();
        /*****    Part 2 - Start the NV test with the "3G Busy" network scenario                           *****/
        printPartDescription("------    Part 2 - Start the NV test with the \"3G Busy\" network scenario");
        startTest();
        testRunning = true;
        printPartSeparator();
        /*****    Part 3 - Navigate to the HPE Network Virtualization website                              *****/
        printPartDescription("------    Part 3 - Navigate to the HPE Network Virtualization website");
        buildSeleniumWebDriver();
        seleniumNavigateToPage();
        driverCloseAndQuit();
        printPartSeparator();
        /*****    Part 4 - Stop the NV test                                                                *****/
        printPartDescription("------    Part 4 - Stop the NV test");
        stopTest();
        testRunning = false;
        printPartSeparator();
        doneCallback();
    } catch (Exception e) {
        try {
            handleError(e.getMessage());
        } catch (Exception e2) {
            System.out.println("Error occurred: " + e2.getMessage());
        }
    }
}

From source file:com.act.lcms.db.io.report.IonAnalysisInterchangeModelOperations.java

public static void main(String[] args) throws IOException {
    Options opts = new Options();
    for (Option.Builder b : OPTION_BUILDERS) {
        opts.addOption(b.build());/*  w  ww.j av  a2s . c  o m*/
    }

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

    if (cl.hasOption("help")) {
        HELP_FORMATTER.printHelp(IonAnalysisInterchangeModelOperations.class.getCanonicalName(), HELP_MESSAGE,
                opts, null, true);
        System.exit(1);
    }

    if (cl.hasOption(OPTION_LOG_DISTRIBUTION)) {
        IonAnalysisInterchangeModel model = new IonAnalysisInterchangeModel();
        model.loadResultsFromFile(new File(cl.getOptionValue(OPTION_INPUT_FILE)));
        Map<Pair<Double, Double>, Integer> rangeToCount = model
                .computeLogFrequencyDistributionOfMoleculeCountToMetric(
                        IonAnalysisInterchangeModel.METRIC.valueOf(cl.getOptionValue(OPTION_LOG_DISTRIBUTION)));

        try (BufferedWriter predictionWriter = new BufferedWriter(
                new FileWriter(new File(OPTION_OUTPUT_FILE)))) {
            for (Map.Entry<Pair<Double, Double>, Integer> entry : rangeToCount.entrySet()) {
                String value = String.format("%f,%d", entry.getKey().getLeft(), entry.getValue());
                predictionWriter.write(value);
                predictionWriter.newLine();
            }
        }
    }
}

From source file:com.act.lcms.db.io.PrintConstructInfo.java

public static void main(String[] args) throws Exception {
    Options opts = new Options();
    for (Option.Builder b : OPTION_BUILDERS) {
        opts.addOption(b.build());//ww  w . jav  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)) {
        System.out.print("Loading/updating LCMS scan files into DB\n");
        ScanFile.insertOrUpdateScanFilesInDirectory(db, lcmsDir);

        String construct = cl.getOptionValue(OPTION_CONSTRUCT);
        List<LCMSWell> lcmsWells = LCMSWell.getInstance().getByConstructID(db, construct);
        Collections.sort(lcmsWells, new Comparator<LCMSWell>() {
            @Override
            public int compare(LCMSWell o1, LCMSWell o2) {
                return o1.getId().compareTo(o2.getId());
            }
        });

        Set<String> uniqueMSIDs = new HashSet<>();
        Map<Integer, Plate> platesById = new HashMap<>();

        System.out.format("\n\n-- Construct %s --\n\n", construct);

        List<ChemicalAssociatedWithPathway> pathwayChems = ChemicalAssociatedWithPathway.getInstance()
                .getChemicalsAssociatedWithPathwayByConstructId(db, construct);
        System.out.print("Chemicals associated with pathway:\n");
        System.out.format("  %-8s%-15s%-45s\n", "index", "kind", "chemical");
        for (ChemicalAssociatedWithPathway chem : pathwayChems) {
            System.out.format("  %-8d%-15s%-45s\n", chem.getIndex(), chem.getKind(), chem.getChemical());
        }

        System.out.print("\nLCMS wells:\n");
        System.out.format("  %-15s%-6s%-15s%-15s%-15s\n", "barcode", "well", "msid", "fed", "lcms_count");
        for (LCMSWell well : lcmsWells) {
            uniqueMSIDs.add(well.getMsid());

            Plate p = platesById.get(well.getPlateId());
            if (p == null) {
                // TODO: migrate Plate to be a subclass of BaseDBModel.
                p = Plate.getPlateById(db, well.getPlateId());
                platesById.put(p.getId(), p);
            }

            String chem = well.getChemical();
            List<ScanFile> scanFiles = ScanFile.getScanFileByPlateIDRowAndColumn(db, p.getId(),
                    well.getPlateRow(), well.getPlateColumn());

            System.out.format("  %-15s%-6s%-15s%-15s%-15d\n", p.getBarcode(), well.getCoordinatesString(),
                    well.getMsid(), chem == null || chem.isEmpty() ? "--" : chem, scanFiles.size());
            System.out.flush();
        }

        List<Integer> plateIds = Arrays.asList(platesById.keySet().toArray(new Integer[platesById.size()]));
        Collections.sort(plateIds);
        System.out.print("\nAppears in plates:\n");
        for (Integer id : plateIds) {
            Plate p = platesById.get(id);
            System.out.format("  %s: %s\n", p.getBarcode(), p.getName());
        }

        List<String> msids = Arrays.asList(uniqueMSIDs.toArray(new String[uniqueMSIDs.size()]));
        Collections.sort(msids);
        System.out.format("\nMSIDS: %s\n", StringUtils.join(msids, ", "));

        Set<String> availableNegativeControls = new HashSet<>();
        for (Map.Entry<Integer, Plate> entry : platesById.entrySet()) {
            List<LCMSWell> wells = LCMSWell.getInstance().getByPlateId(db, entry.getKey());
            for (LCMSWell well : wells) {
                if (!construct.equals(well.getComposition())) {
                    availableNegativeControls.add(well.getComposition());
                }
            }
        }

        // Print available standards for each step w/ plate barcodes and coordinates.
        System.out.format("\nAvailable Standards:\n");
        Map<Integer, Plate> plateCache = new HashMap<>();
        for (ChemicalAssociatedWithPathway chem : pathwayChems) {
            List<StandardWell> matchingWells = StandardWell.getInstance().getStandardWellsByChemical(db,
                    chem.getChemical());
            for (StandardWell well : matchingWells) {
                if (!plateCache.containsKey(well.getPlateId())) {
                    Plate p = Plate.getPlateById(db, well.getPlateId());
                    plateCache.put(p.getId(), p);
                }
            }
            Map<Integer, List<StandardWell>> standardWellsByPlateId = new HashMap<>();
            for (StandardWell well : matchingWells) {
                List<StandardWell> plateWells = standardWellsByPlateId.get(well.getPlateId());
                if (plateWells == null) {
                    plateWells = new ArrayList<>();
                    standardWellsByPlateId.put(well.getPlateId(), plateWells);
                }
                plateWells.add(well);
            }
            List<Pair<String, Integer>> plateBarcodes = new ArrayList<>(plateCache.size());
            for (Plate p : plateCache.values()) {
                if (p.getBarcode() == null) {
                    plateBarcodes.add(Pair.of("(no barcode)", p.getId()));
                } else {
                    plateBarcodes.add(Pair.of(p.getBarcode(), p.getId()));
                }
            }
            Collections.sort(plateBarcodes);
            System.out.format("  %s:\n", chem.getChemical());
            for (Pair<String, Integer> barcodePair : plateBarcodes) {
                // TODO: hoist this whole sorting/translation step into a utility class.
                List<StandardWell> wells = standardWellsByPlateId.get(barcodePair.getRight());
                if (wells == null) {
                    // Don't print plates that don't apply to this chemical, which can happen because we're caching the plates.
                    continue;
                }
                Collections.sort(wells, new Comparator<StandardWell>() {
                    @Override
                    public int compare(StandardWell o1, StandardWell o2) {
                        int c = o1.getPlateRow().compareTo(o2.getPlateRow());
                        if (c != 0)
                            return c;
                        return o1.getPlateColumn().compareTo(o2.getPlateColumn());
                    }
                });
                List<String> descriptions = new ArrayList<>(wells.size());
                for (StandardWell well : wells) {
                    descriptions.add(String.format("%s in %s%s", well.getCoordinatesString(), well.getMedia(),
                            well.getConcentration() == null ? ""
                                    : String.format(" c. %f", well.getConcentration())));
                }
                System.out.format("    %s: %s\n", barcodePair.getLeft(), StringUtils.join(descriptions, ", "));
            }
        }

        List<String> negativeControlStrains = Arrays
                .asList(availableNegativeControls.toArray(new String[availableNegativeControls.size()]));
        Collections.sort(negativeControlStrains);
        System.out.format("\nAvailable negative controls: %s\n", StringUtils.join(negativeControlStrains, ","));
        System.out.print("\n----------\n");
        System.out.print("\n\n");
    }
}

From source file:com.dustindoloff.s3websitedeploy.Main.java

public static void main(final String[] args) {
    final Options options = buildOptions();
    final CommandLineParser parser = new DefaultParser();
    final CommandLine commandLine;
    try {//from w ww.j  av  a  2 s .c  o m
        commandLine = parser.parse(options, args);
    } catch (final ParseException e) {
        System.out.println(e.getMessage());
        new HelpFormatter().printHelp("s3WebsiteDeploy", options);
        System.exit(1);
        return;
    }

    final File websiteZip = new File(commandLine.getOptionValue(ARG_WEBSITE_ZIP));
    final String s3Bucket = commandLine.getOptionValue(ARG_BUCKET);
    final String awsAccessKey = commandLine.getOptionValue(ARG_AWS_ACCESS_KEY);
    final String awsSecretKey = commandLine.getOptionValue(ARG_AWS_SECRET_KEY);

    final ZipFile zipFile = getAsValidZip(websiteZip);
    if (zipFile == null) {
        System.out.println("Invalid zip file passed in");
        System.exit(2);
        return;
    }

    System.out.println("Running S3 Website Deploy");

    final AmazonS3 s3Client = new AmazonS3Client(new BasicAWSCredentials(awsAccessKey, awsSecretKey));

    final Region bucketRegion = getBucketRegion(s3Client, s3Bucket);

    if (bucketRegion == null) {
        System.out.println("Unable to get the region for the bucket.");
        System.exit(3);
        return;
    }

    s3Client.setRegion(bucketRegion);

    if (!emptyBucket(s3Client, s3Bucket)) {
        System.out.println("Unable to upload to empty bucket.");
        System.exit(4);
        return;
    }

    if (!upload(s3Client, s3Bucket, zipFile)) {
        System.out.println("Unable to upload to S3.");
        System.exit(5);
        return;
    }

    System.out.println("Deployment Complete");
}

From source file:eu.freme.bpt.Main.java

public static void main(String[] args) {
    final List<String> services = new ArrayList<>();
    for (EService eService : EService.values()) {
        services.add(eService.getName());
    }//w w w.j  a v a  2 s  . c  o  m

    Pair<EService, String[]> serviceAndArgs = extractService(args, services);

    EService service = serviceAndArgs.getName();

    // create options that will be parsed from the args
    /////// General BPT options ///////
    Option helpOption = new Option("h", "help", false, "Prints this message");
    Option inputOption = Option.builder("if").longOpt("input-file").argName("input file").desc(
            "The input file or directory to process. In case of a directory, each file in that directory is processed. "
                    + "If not given, standard in is used.")
            .hasArg().build();
    Option outputOption = Option.builder("od").longOpt("output-dir").argName("output dir")
            .desc("The output directory. If not given, output is written to standard out.").hasArg().build();
    Option propertiesOption = Option.builder("prop").longOpt("properties").argName("properties file")
            .desc("The properties file that contains configuration of the tool.").hasArg().build();

    Options options = new Options().addOption(helpOption).addOption(inputOption).addOption(outputOption)
            .addOption(propertiesOption);

    /////// Common service options ///////
    Option informatOption = Option.builder("f").longOpt("informat").argName("FORMAT")
            .desc("The format of the input document(s). Defaults to 'turtle'").hasArg().build();
    Option outformatOption = Option.builder("o").longOpt("outformat").argName("FORMAT")
            .desc("The desired output format of the service. Defaults to 'turtle'").hasArg().build();
    options.addOption(informatOption).addOption(outformatOption);

    /////// Service specific options ///////
    if (service != null) {
        switch (service) {
        case E_TRANSLATION:
            ETranslation.addOptions(options);
            break;
        case E_ENTITY:
            EEntity.addOptions(options);
            break;
        case E_LINK:
            ELink.addOptions(options);
            break;
        case E_TERMINOLOGY:
            ETerminology.addOptions(options);
            break;
        case PIPELINING:
            Pipelining.addOptions(options);
            break;
        case E_PUBLISHING:
            // TODO !
        default:
            logger.warn("Unknown service {}. Skipping!", service);
            break;
        }
    } else {
        ETranslation.addOptions(options);
        EEntity.addOptions(options);
        ELink.addOptions(options);
        ETerminology.addOptions(options);
        Pipelining.addOptions(options);
    }

    CommandLine commandLine = null;
    int exitValue;
    try {
        CommandLineParser parser = new DefaultParser();
        commandLine = parser.parse(options, serviceAndArgs.getValue());
        exitValue = 0;
    } catch (ParseException e) {
        System.err.println(e.getMessage());
        exitValue = 1;
    }
    if ((exitValue != 0) || commandLine.hasOption("h") || service == null) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.setWidth(132);
        formatter.printHelp("java -jar <this jar file> <e-service> ", options, true);
        System.exit(exitValue);
    }

    logger.debug("Commandline successfully parsed!");

    try {
        BPT batchProcessingTool = new BPT();
        if (commandLine.hasOption("prop")) {
            batchProcessingTool.loadProperties(commandLine.getOptionValue("prop"));
        }
        if (commandLine.hasOption("if")) {
            batchProcessingTool.setInput(commandLine.getOptionValue("if"));
        }
        if (commandLine.hasOption("od")) {
            batchProcessingTool.setOutput(commandLine.getOptionValue("od"));
        }
        if (commandLine.hasOption('f')) {
            batchProcessingTool.setInFormat(Format.valueOf(commandLine.getOptionValue('f').replace('-', '_')));
        }
        if (commandLine.hasOption('o')) {
            batchProcessingTool.setOutFormat(Format.valueOf(commandLine.getOptionValue('o').replace('-', '_')));
        }

        switch (service) {
        case E_TRANSLATION:
            batchProcessingTool.eTranslation(commandLine.getOptionValue("source-lang"),
                    commandLine.getOptionValue("target-lang"), commandLine.getOptionValue("system"),
                    commandLine.getOptionValue("domain"), commandLine.getOptionValue("key"));
            break;
        case E_ENTITY:
            batchProcessingTool.eEntity(commandLine.getOptionValue("language"),
                    commandLine.getOptionValue("dataset"), commandLine.getOptionValue("mode"));
            break;
        case E_LINK:
            batchProcessingTool.eLink(commandLine.getOptionValue("templateid"));
            break;
        case E_TERMINOLOGY:
            batchProcessingTool.eTerminology(commandLine.getOptionValue("source-lang"),
                    commandLine.getOptionValue("target-lang"), commandLine.getOptionValue("collection"),
                    commandLine.getOptionValue("domain"), commandLine.getOptionValue("key"),
                    commandLine.getOptionValue("mode"));
            break;
        case PIPELINING:
            batchProcessingTool.pipelining(commandLine.getOptionValue("templateid"));
            break;
        case E_PUBLISHING:
        default:
            logger.error("Unknown service {}. Aborting!", service);
            System.exit(3);
        }
    } catch (Exception e) {
        logger.error("Cannot handle input or output. Reason: ", e);
        System.exit(2);
    }
}