Example usage for org.apache.commons.cli CommandLine getOptionValues

List of usage examples for org.apache.commons.cli CommandLine getOptionValues

Introduction

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

Prototype

public String[] getOptionValues(char opt) 

Source Link

Document

Retrieves the array of values, if any, of an option.

Usage

From source file:com.act.lcms.MS2Simple.java

public static void main(String[] args) throws Exception {
    Options opts = new Options();
    for (Option.Builder b : OPTION_BUILDERS) {
        opts.addOption(b.build());/*from w w  w  .j a v  a2 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;
    }

    String fmt = "pdf";
    Double mz;
    try {
        mz = Double.parseDouble(cl.getOptionValue(OPTION_TARGET_TRIGGER_MZ));
    } catch (NumberFormatException e) {
        System.err.format("Trigger mass must be a floating point number: %s\n", e.getMessage());
        HELP_FORMATTER.printHelp(LoadPlateCompositionIntoDB.class.getCanonicalName(), HELP_MESSAGE, opts, null,
                true);
        System.exit(1);
        return; // Silences compiler warnings for `mz`.
    }

    String outPrefix = cl.getOptionValue(OPTION_OUTPUT_PREFIX);
    String ms2mzml = cl.getOptionValue(OPTION_MZML_FILE);
    String ms2nc = cl.getOptionValue(OPTION_NETCDF_FILE);

    String[] ms2SearchMassStrings = cl.getOptionValues(OPTION_MS2_PEAK_SEARCH_MASSES);
    List<Double> ms2SearchMasses;
    if (ms2SearchMassStrings != null && ms2SearchMassStrings.length > 0) {
        ms2SearchMasses = new ArrayList<>(ms2SearchMassStrings.length);
        for (String m : ms2SearchMassStrings) {
            Double d;
            try {
                d = Double.parseDouble(m);
            } catch (NumberFormatException e) {
                System.err.format(
                        "MS2 search mass must be a comma separated list of floating point numbers: %s\n",
                        e.getMessage());
                HELP_FORMATTER.printHelp(LoadPlateCompositionIntoDB.class.getCanonicalName(), HELP_MESSAGE,
                        opts, null, true);
                System.exit(1);
                return; // Silences compiler warnings for `d`.
            }
            ms2SearchMasses.add(d);
        }
    } else {
        ms2SearchMasses = new ArrayList<>(0); // Use an empty array rather than null for easier logic later.
    }

    Integer pickTopNMatches = null;
    if (cl.hasOption(OPTION_PICK_TOP_N_MATCHES)) {
        pickTopNMatches = Integer.valueOf(cl.getOptionValue(OPTION_PICK_TOP_N_MATCHES));
    }

    MS2Simple c = new MS2Simple();
    c.findAndPlotMatchingMS2Scans(mz, ms2SearchMasses, pickTopNMatches, ms2mzml, ms2nc, outPrefix, fmt);
}

From source file:com.act.lcms.db.analysis.IonDetectionAnalysis.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. j  a  v  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", 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_LCMS_FILE_DIRECTORY));
    if (!lcmsDir.isDirectory()) {
        System.err.format("File at %s is not a directory", lcmsDir.getAbsolutePath());
        HELP_FORMATTER.printHelp(LoadPlateCompositionIntoDB.class.getCanonicalName(), HELP_MESSAGE, opts, null,
                true);
        System.exit(1);
    }

    String plottingDirectory = cl.getOptionValue(OPTION_PLOTTING_DIR);

    // Get include and excluse ions from command line
    Set<String> includeIons;
    if (cl.hasOption(OPTION_INCLUDE_IONS)) {
        includeIons = new HashSet<>(Arrays.asList(cl.getOptionValues(OPTION_INCLUDE_IONS)));
        LOGGER.info("Including ions in search: %s", StringUtils.join(includeIons, ", "));
    } else {
        includeIons = new HashSet<>();
        includeIons.add(DEFAULT_ION);
    }

    try (DB db = DB.openDBFromCLI(cl)) {
        ScanFile.insertOrUpdateScanFilesInDirectory(db, lcmsDir);

        File inputPredictionCorpus = new File(cl.getOptionValue(OPTION_INPUT_PREDICTION_CORPUS));

        Map<Double, Set<Pair<String, String>>> massChargeToChemicalAndIon = constructMassChargeToChemicalIonsFromInputFile(
                inputPredictionCorpus, includeIons, cl.hasOption(OPTION_LIST_OF_INCHIS_INPUT_FILE));

        Pair<Set<Pair<String, Double>>, Map<String, Double>> values = constructFakeNameToMassChargeAndSetOfMassChargePairs(
                massChargeToChemicalAndIon.keySet());
        Set<Pair<String, Double>> searchMZs = values.getLeft();
        Map<String, Double> chemIDToMassCharge = values.getRight();

        LOGGER.info("The number of mass charges are: %d", searchMZs.size());

        Map<ScanData.KIND, List<LCMSWell>> wellTypeToLCMSWells = readInputExperimentalSetup(db,
                new File(cl.getOptionValue(OPTION_INPUT_POSITIVE_AND_NEGATIVE_CONTROL_WELLS_FILE)));

        // Get experimental setup ie. positive and negative wells from config file
        List<LCMSWell> positiveWells = wellTypeToLCMSWells.get(ScanData.KIND.POS_SAMPLE);
        List<LCMSWell> negativeWells = wellTypeToLCMSWells.get(ScanData.KIND.NEG_CONTROL);

        LOGGER.info("Number of positive wells is: %d", positiveWells.size());
        LOGGER.info("Number of negative wells is: %d", negativeWells.size());

        HashMap<Integer, Plate> plateCache = new HashMap<>();
        String outputPrefix = cl.getOptionValue(OPTION_OUTPUT_PREFIX);

        IonDetectionAnalysis<LCMSWell> ionDetectionAnalysis = new IonDetectionAnalysis<LCMSWell>(lcmsDir,
                positiveWells, negativeWells, plottingDirectory, plateCache, searchMZs, db);

        ionDetectionAnalysis.runLCMSMiningAnalysisAndPlotResults(chemIDToMassCharge, massChargeToChemicalAndIon,
                outputPrefix, cl.hasOption(OPTION_NON_REPLICATE_ANALYSIS));
    }
}

From source file:com.google.api.ads.adwords.jaxws.extensions.AwReporting.java

/**
 * Main method./*from   w  w  w .  j a v  a 2  s  . c o  m*/
 *
 * @param args the command line arguments.
 */
public static void main(String args[]) {

    // Proxy
    JaxWsProxySelector ps = new JaxWsProxySelector(ProxySelector.getDefault());
    ProxySelector.setDefault(ps);

    Options options = createCommandLineOptions();

    boolean errors = false;
    String propertiesPath = null;

    try {
        CommandLineParser parser = new BasicParser();
        CommandLine cmdLine = parser.parse(options, args);

        // Print full help and quit
        if (cmdLine.hasOption("help")) {
            printHelpMessage(options);
            printSamplePropertiesFile();
            System.exit(0);
        }

        setLogLevel(cmdLine);

        if (cmdLine.hasOption("file")) {
            propertiesPath = cmdLine.getOptionValue("file");
        } else {
            LOGGER.error("Missing required option: 'file'");
            System.exit(0);
        }
        LOGGER.info("Using properties file: " + propertiesPath);

        Set<Long> accountIdsSet = Sets.newHashSet();
        if (cmdLine.hasOption("accountIdsFile")) {
            String accountsFileName = cmdLine.getOptionValue("accountIdsFile");
            addAccountsFromFile(accountIdsSet, accountsFileName);
        }

        Properties properties = initApplicationContextAndProperties(propertiesPath);

        ReportModeService.setReportMode(properties.getProperty("reportMode")); //TODO Any other approach?

        LOGGER.debug("Creating ReportProcessor bean...");
        ReportProcessor processor = createReportProcessor();
        LOGGER.debug("... success.");

        if (cmdLine.hasOption("generatePdf")) {

            LOGGER.debug("GeneratePDF option detected.");

            // Get HTML template and output directoy
            String[] pdfFiles = cmdLine.getOptionValues("generatePdf");
            File htmlTemplateFile = new File(pdfFiles[0]);
            File outputDirectory = new File(pdfFiles[1]);

            LOGGER.debug("Html template file to be used: " + htmlTemplateFile);
            LOGGER.debug("Output directory for PDF: " + outputDirectory);

            // Generate PDFs
            generatePdf(processor, cmdLine.getOptionValue("startDate"), cmdLine.getOptionValue("endDate"),
                    properties, htmlTemplateFile, outputDirectory);

        } else if (cmdLine.hasOption("startDate") && cmdLine.hasOption("endDate")) {
            // Generate Reports

            String dateStart = cmdLine.getOptionValue("startDate");
            String dateEnd = cmdLine.getOptionValue("endDate");

            LOGGER.info("Starting report download for dateStart: " + dateStart + " and dateEnd: " + dateEnd);

            processor.generateReportsForMCC(ReportDefinitionDateRangeType.CUSTOM_DATE, dateStart, dateEnd,
                    accountIdsSet, properties);

        } else if (cmdLine.hasOption("dateRange")) {

            ReportDefinitionDateRangeType dateRangeType = ReportDefinitionDateRangeType
                    .fromValue(cmdLine.getOptionValue("dateRange"));

            LOGGER.info("Starting report download for dateRange: " + dateRangeType.name());

            processor.generateReportsForMCC(dateRangeType, null, null, accountIdsSet, properties);

        } else {
            errors = true;
            LOGGER.error("Configuration incomplete. Missing options for command line.");
        }
    } catch (IOException e) {
        errors = true;
        LOGGER.error("File not found: " + e.getMessage());
    } catch (ParseException e) {
        errors = true;
        System.err.println("Error parsing the values for the command line options: " + e.getMessage());
    } catch (Exception e) {
        errors = true;
        LOGGER.error("Unexpected error accessing the API: " + e.getMessage());
        e.printStackTrace();
    }

    if (errors) {
        System.exit(1);
    } else {
        System.exit(0);
    }
}

From source file:microbiosima.Microbiosima.java

/**
 * @param args//from   w  ww  . ja v  a 2  s  .  c  o m
 *            the command line arguments
 * @throws java.io.FileNotFoundException
 * @throws java.io.UnsupportedEncodingException
 */
public static void main(String[] args) throws FileNotFoundException, UnsupportedEncodingException {
    //Init with default values
    int populationSize = 500;
    int microSize = 1000;
    int numberOfSpecies = 150;
    int numberOfGeneration = 10000;
    int numberOfObservation = 100;
    int numberOfReplication = 1;
    double pctEnv = 0;
    double pctPool = 0;

    Options options = new Options();

    Option help = new Option("h", "help", false, "print this message");
    Option version = new Option("v", "version", false, "print the version information and exit");
    options.addOption(help);
    options.addOption(version);

    options.addOption(Option.builder("o").longOpt("obs").hasArg().argName("OBS")
            .desc("Number generation for observation [default: 100]").build());
    options.addOption(Option.builder("r").longOpt("rep").hasArg().argName("REP")
            .desc("Number of replication [default: 1]").build());

    Builder C = Option.builder("c").longOpt("config").numberOfArgs(4).argName("Pop Micro Spec Gen")
            .desc("Four Parameters in the following orders: "
                    + "(1) population size, (2) microbe size, (3) number of species, (4) number of generation"
                    + " [default: 500 1000 150 10000]");
    options.addOption(C.build());

    HelpFormatter formatter = new HelpFormatter();
    String syntax = "microbiosima pctEnv pctPool";
    String header = "\nSimulates the evolutionary and ecological dynamics of microbiomes within a population of hosts.\n\n"
            + "required arguments:\n" + "  pctEnv             Percentage of environmental acquisition\n"
            + "  pctPool            Percentage of pooled environmental component\n" + "\noptional arguments:\n";
    String footer = "\n";

    formatter.setWidth(80);

    CommandLineParser parser = new DefaultParser();
    CommandLine cmd = null;

    try {
        cmd = parser.parse(options, args);
        String[] pct_config = cmd.getArgs();

        if (cmd.hasOption("h") || args.length == 0) {
            formatter.printHelp(syntax, header, options, footer, true);
            System.exit(0);
        }
        if (cmd.hasOption("v")) {
            System.out.println("Microbiosima " + VERSION);
            System.exit(0);
        }
        if (pct_config.length != 2) {
            System.out.println("ERROR! Required exactly two argumennts for pct_env and pct_pool. It got "
                    + pct_config.length + ": " + Arrays.toString(pct_config));
            formatter.printHelp(syntax, header, options, footer, true);
            System.exit(3);
        } else {
            pctEnv = Double.parseDouble(pct_config[0]);
            pctPool = Double.parseDouble(pct_config[1]);
            if (pctEnv < 0 || pctEnv > 1) {
                System.out.println(
                        "ERROR: pctEnv (Percentage of environmental acquisition) must be between 0 and 1 (pctEnv="
                                + pctEnv + ")! EXIT");
                System.exit(3);
            }
            if (pctPool < 0 || pctPool > 1) {
                System.out.println(
                        "ERROR: pctPool (Percentage of pooled environmental component must) must be between 0 and 1 (pctPool="
                                + pctPool + ")! EXIT");
                System.exit(3);
            }

        }
        if (cmd.hasOption("config")) {
            String[] configs = cmd.getOptionValues("config");
            populationSize = Integer.parseInt(configs[0]);
            microSize = Integer.parseInt(configs[1]);
            numberOfSpecies = Integer.parseInt(configs[2]);
            numberOfGeneration = Integer.parseInt(configs[3]);
        }
        if (cmd.hasOption("obs")) {
            numberOfObservation = Integer.parseInt(cmd.getOptionValue("obs"));
        }
        if (cmd.hasOption("rep")) {
            numberOfReplication = Integer.parseInt(cmd.getOptionValue("rep"));
        }

    } catch (ParseException e) {
        e.printStackTrace();
        System.exit(3);
    }

    StringBuilder sb = new StringBuilder();
    sb.append("Configuration Summary:").append("\n\tPopulation size: ").append(populationSize)
            .append("\n\tMicrobe size: ").append(microSize).append("\n\tNumber of species: ")
            .append(numberOfSpecies).append("\n\tNumber of generation: ").append(numberOfGeneration)
            .append("\n\tNumber generation for observation: ").append(numberOfObservation)
            .append("\n\tNumber of replication: ").append(numberOfReplication).append("\n");
    System.out.println(sb.toString());

    //      System.exit(3);
    // LogNormalDistribution lgd=new LogNormalDistribution(0,1);
    // environment=lgd.sample(150);
    // double environment_sum=0;
    // for (int i=0;i<No;i++){
    // environment_sum+=environment[i];
    // }
    // for (int i=0;i<No;i++){
    // environment[i]/=environment_sum;
    // }

    double[] environment = new double[numberOfSpecies];
    for (int i = 0; i < numberOfSpecies; i++) {
        environment[i] = 1 / (double) numberOfSpecies;
    }

    for (int rep = 0; rep < numberOfReplication; rep++) {
        String prefix = "" + (rep + 1) + "_";
        String sufix = "_E" + pctEnv + "_P" + pctPool + ".txt";

        System.out.println("Output 5 result files in the format of: " + prefix + "[****]" + sufix);
        try {

            PrintWriter file1 = new PrintWriter(
                    new BufferedWriter(new FileWriter(prefix + "gamma_diversity" + sufix)));
            PrintWriter file2 = new PrintWriter(
                    new BufferedWriter(new FileWriter(prefix + "alpha_diversity" + sufix)));
            PrintWriter file3 = new PrintWriter(
                    new BufferedWriter(new FileWriter(prefix + "beta_diversity" + sufix)));
            PrintWriter file4 = new PrintWriter(new BufferedWriter(new FileWriter(prefix + "sum" + sufix)));
            PrintWriter file5 = new PrintWriter(
                    new BufferedWriter(new FileWriter(prefix + "inter_generation_distance" + sufix)));
            PrintWriter file6 = new PrintWriter(
                    new BufferedWriter(new FileWriter(prefix + "environment_population_distance" + sufix)));

            Population population = new Population(microSize, environment, populationSize, pctEnv, pctPool, 0,
                    0);

            while (population.getNumberOfGeneration() < numberOfGeneration) {
                population.sumSpecies();
                if (population.getNumberOfGeneration() % numberOfObservation == 0) {
                    file1.println(population.gammaDiversity(true));
                    file2.println(population.alphaDiversity(true));
                    file3.print(population.betaDiversity(true));
                    file3.print("\t");
                    file3.println(population.BrayCurtis(true));
                    file4.println(population.printOut());
                    file5.println(population.interGenerationDistance());
                    file6.println(population.environmentPopulationDistance());
                }
                population.getNextGen();
            }
            file1.close();
            file2.close();
            file3.close();
            file4.close();
            file5.close();
            file6.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

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

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

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

    try (DB db = DB.openDBFromCLI(cl)) {
        List<String> chemicalNames = new ArrayList<>();
        if (cl.hasOption(OPTION_CONSTRUCT)) {
            // Extract the chemicals in the pathway and their product masses, then look up info on those chemicals
            List<Pair<ChemicalAssociatedWithPathway, Double>> productMasses = Utils
                    .extractMassesForChemicalsAssociatedWithConstruct(db, cl.getOptionValue(OPTION_CONSTRUCT));

            for (Pair<ChemicalAssociatedWithPathway, Double> pair : productMasses) {
                chemicalNames.add(pair.getLeft().getChemical());
            }
        }

        if (cl.hasOption(OPTION_CHEMICALS)) {
            chemicalNames.addAll(Arrays.asList(cl.getOptionValues(OPTION_CHEMICALS)));
        }

        if (chemicalNames.size() == 0) {
            System.err.format("No chemicals can be found from the input query.\n");
            System.exit(-1);
        }

        List<String> standardIonHeaderFields = new ArrayList<String>() {
            {
                add(STANDARD_ION_HEADER_FIELDS.CHEMICAL.name());
                add(STANDARD_ION_HEADER_FIELDS.BEST_ION_FROM_ALGO.name());
                add(STANDARD_ION_HEADER_FIELDS.MANUAL_PICK.name());
                add(STANDARD_ION_HEADER_FIELDS.AUTHOR.name());
                add(STANDARD_ION_HEADER_FIELDS.DIAGNOSTIC_PLOTS.name());
                add(STANDARD_ION_HEADER_FIELDS.NOTE.name());
            }
        };

        String outAnalysis;
        if (cl.hasOption(OPTION_OUTPUT_PREFIX)) {
            outAnalysis = cl.getOptionValue(OPTION_OUTPUT_PREFIX) + "." + TSV_FORMAT;
        } else {
            outAnalysis = String.join("-", chemicalNames) + "." + TSV_FORMAT;
        }

        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);
        }

        String plottingDirectory = cl.getOptionValue(OPTION_PLOTTING_DIR);

        TSVWriter<String, String> resultsWriter = new TSVWriter<>(standardIonHeaderFields);
        resultsWriter.open(new File(outAnalysis));

        // For each chemical, create a TSV row and a corresponding diagnostic plot
        for (String chemicalName : chemicalNames) {
            List<String> graphLabels = new ArrayList<>();
            List<Double> yMaxList = new ArrayList<>();

            String outData = plottingDirectory + "/" + chemicalName + ".data";
            String outImg = plottingDirectory + "/" + chemicalName + ".pdf";

            // For each diagnostic plot, open a new file stream.
            try (FileOutputStream fos = new FileOutputStream(outData)) {

                List<StandardIonResult> getResultByChemicalName = StandardIonResult.getByChemicalName(db,
                        chemicalName);

                if (getResultByChemicalName != null && getResultByChemicalName.size() > 0) {

                    // PART 1: Get the best metlin ion across all standard ion results for a given chemical
                    String bestGlobalMetlinIon = AnalysisHelper
                            .scoreAndReturnBestMetlinIonFromStandardIonResults(getResultByChemicalName,
                                    new HashMap<>(), true, true);

                    // PART 2: Plot all the graphs related to the chemical. The plots are structured as follows:
                    //
                    // Page 1: All graphs (water, MeOH, Yeast) for Global ion picked (best ion among ALL standard ion runs for
                    // the given chemical) by the algorithm
                    // Page 2: All graphs for M+H
                    // Page 3: All graphs for Local ions picked (best ion within a SINGLE standard ion run) + negative controls
                    // for Yeast.
                    //
                    // Each page is demarcated by a blank graph.

                    // Arrange results based on media
                    Map<String, List<StandardIonResult>> categories = StandardIonResult
                            .categorizeListOfStandardWellsByMedia(db, getResultByChemicalName);

                    // This set contains all the best metlin ions corresponding to all the standard ion runs.
                    Set<String> bestLocalIons = new HashSet<>();
                    bestLocalIons.add(bestGlobalMetlinIon);
                    bestLocalIons.add(DEFAULT_ION);

                    for (StandardIonResult result : getResultByChemicalName) {
                        bestLocalIons.add(result.getBestMetlinIon());
                    }

                    // We sort the best local ions are follows:
                    // 1) Global best ion spectra 2) M+H spectra 3) Local best ion spectra
                    List<String> bestLocalIonsArray = new ArrayList<>(bestLocalIons);
                    Collections.sort(bestLocalIonsArray, new Comparator<String>() {
                        @Override
                        public int compare(String o1, String o2) {
                            if (o1.equals(bestGlobalMetlinIon) && !o2.equals(bestGlobalMetlinIon)) {
                                return -1;
                            } else if (o1.equals(DEFAULT_ION) && !o2.equals(bestGlobalMetlinIon)) {
                                return -1;
                            } else {
                                return 1;
                            }
                        }
                    });

                    // This variable stores the index of the array at which all the remaining spectra are contained in one
                    // page. This happens right after the M+H ion spectra.
                    Integer combineAllSpectraIntoPageThreeFromIndex = 0;
                    for (int i = 0; i < bestLocalIonsArray.size(); i++) {
                        if (bestLocalIonsArray.get(i).equals(DEFAULT_ION)) {
                            combineAllSpectraIntoPageThreeFromIndex = i + 1;
                        }
                    }

                    for (int i = 0; i < bestLocalIonsArray.size(); i++) {

                        String ion = bestLocalIonsArray.get(i);
                        for (Map.Entry<String, List<StandardIonResult>> mediaToListOfIonResults : categories
                                .entrySet()) {

                            for (StandardIonResult result : mediaToListOfIonResults.getValue()) {

                                // For every standard ion result, we plot the best global metlin ion and M+H. These plots are in the
                                // pages 1 and 2. For all page 3 (aka miscellaneous spectra), we only plot the best local ion
                                // corresponding to it's spectra and not some other graph's spectra. In the below condition,
                                // we reach the page 3 case with not the same best ion as the spectra, in which case we just continue
                                // and not draw anything on the page.
                                if (i >= combineAllSpectraIntoPageThreeFromIndex
                                        && !(result.getBestMetlinIon().equals(ion))) {
                                    continue;
                                }

                                StandardWell positiveWell = StandardWell.getInstance().getById(db,
                                        result.getStandardWellId());
                                String positiveControlChemical = positiveWell.getChemical();

                                ScanData<StandardWell> encapsulatedDataForPositiveControl = AnalysisHelper
                                        .getScanDataForWell(db, lcmsDir, positiveWell, positiveControlChemical,
                                                positiveControlChemical);

                                Set<String> singletonSet = Collections.singleton(ion);
                                String additionalInfo = generateAdditionalLabelInformation(positiveWell, result,
                                        ion);

                                List<String> labels = AnalysisHelper
                                        .writeScanData(fos, lcmsDir, MAX_INTENSITY,
                                                encapsulatedDataForPositiveControl, false, false, singletonSet)
                                        .stream().map(label -> label + additionalInfo)
                                        .collect(Collectors.toList());

                                yMaxList.add(encapsulatedDataForPositiveControl.getMs1ScanResults()
                                        .getMaxIntensityForIon(ion));

                                List<String> negativeLabels = null;
                                // Only do the negative control in the miscellaneous page (page 3) and if the well is in yeast media.
                                if (mediaToListOfIonResults.getKey()
                                        .equals(StandardWell.MEDIA_TYPE.YEAST.name())
                                        && (i >= combineAllSpectraIntoPageThreeFromIndex
                                                && (result.getBestMetlinIon().equals(ion)))) {
                                    //TODO: Change the representative negative well to one that displays the highest noise in the future.
                                    // For now, we just use the first index among the negative wells.
                                    int representativeIndex = 0;
                                    StandardWell representativeNegativeControlWell = StandardWell.getInstance()
                                            .getById(db, result.getNegativeWellIds().get(representativeIndex));

                                    ScanData encapsulatedDataForNegativeControl = AnalysisHelper
                                            .getScanDataForWell(db, lcmsDir, representativeNegativeControlWell,
                                                    positiveWell.getChemical(),
                                                    representativeNegativeControlWell.getChemical());

                                    String negativePlateAdditionalInfo = generateAdditionalLabelInformation(
                                            representativeNegativeControlWell, null, null);

                                    negativeLabels = AnalysisHelper.writeScanData(fos, lcmsDir, MAX_INTENSITY,
                                            encapsulatedDataForNegativeControl, false, false, singletonSet)
                                            .stream().map(label -> label + negativePlateAdditionalInfo)
                                            .collect(Collectors.toList());

                                    yMaxList.add(encapsulatedDataForNegativeControl.getMs1ScanResults()
                                            .getMaxIntensityForIon(ion));
                                }

                                graphLabels.addAll(labels);

                                if (negativeLabels != null) {
                                    graphLabels.addAll(negativeLabels);
                                }
                            }
                        }

                        // Add a blank graph to demarcate pages.
                        if (i < combineAllSpectraIntoPageThreeFromIndex) {
                            graphLabels.addAll(AnalysisHelper.writeScanData(fos, lcmsDir, 0.0, BLANK_SCAN,
                                    false, false, new HashSet<>()));
                            yMaxList.add(0.0d);
                        }
                    }

                    // We need to pass the yMax values as an array to the Gnuplotter.
                    Double fontScale = null;
                    if (cl.hasOption(FONT_SCALE)) {
                        try {
                            fontScale = Double.parseDouble(cl.getOptionValue(FONT_SCALE));
                        } catch (IllegalArgumentException e) {
                            System.err.format("Argument for font-scale must be a floating point number.\n");
                            System.exit(1);
                        }
                    }

                    Double[] yMaxes = yMaxList.toArray(new Double[yMaxList.size()]);
                    Gnuplotter plotter = fontScale == null ? new Gnuplotter() : new Gnuplotter(fontScale);
                    plotter.plot2D(outData, outImg, graphLabels.toArray(new String[graphLabels.size()]), "time",
                            null, "intensity", "pdf", null, null, yMaxes, outImg + ".gnuplot");

                    Map<String, String> row = new HashMap<>();
                    row.put(STANDARD_ION_HEADER_FIELDS.CHEMICAL.name(), chemicalName);
                    row.put(STANDARD_ION_HEADER_FIELDS.BEST_ION_FROM_ALGO.name(), bestGlobalMetlinIon);
                    row.put(STANDARD_ION_HEADER_FIELDS.DIAGNOSTIC_PLOTS.name(), outImg);

                    resultsWriter.append(row);
                    resultsWriter.flush();
                }
            }
        }

        resultsWriter.flush();
        resultsWriter.close();
    }
}

From source file:com.github.helenusdriver.driver.tools.Tool.java

/**
 * Main point of entry for this tool/*from  ww w.j  ava2s .c  o m*/
 *
 * @author paouelle
 *
 * @param args the command-line arguments to the tool
 */
public static void main(String[] args) {
    Tool.setRootLogLevel(Level.OFF); // disable logging by default
    try {
        final CommandLineParser parser = new GnuParser();
        final CommandLine line = parser.parse(Tool.options, args);

        if (line.hasOption(Tool.verbose.getOpt())) { // do this one first
            Tool.verbose.run(line);
        }
        if (line.hasOption(Tool.trace.getOpt())) { // do this one next
            Tool.trace.run(line);
        }
        for (final Option option : line.getOptions()) { // run these first
            if (option instanceof RunnableFirstOption) {
                ((RunnableFirstOption) option).run(line);
            }
        }
        final String server = line.getOptionValue(Tool.server.getLongOpt(), "127.0.0.1" // defaults to local host
        );
        final boolean connect = (line.hasOption(Tool.objects.getLongOpt())
                || line.hasOption(Tool.schemas.getLongOpt()));

        Tool.mgr = new StatementManagerImpl(Cluster.builder().addContactPoint(server).withQueryOptions(null),
                connect, line.getOptionValues(Tool.filters.getLongOpt()));
        if (line.hasOption(Tool.replicationFactor.getLongOpt())) {
            mgr.setDefaultReplicationFactor(
                    Integer.parseInt(line.getOptionValue(Tool.replicationFactor.getLongOpt())));
        }
        try {
            if (connect && Tool.vflag) {
                System.out.println(Tool.class.getSimpleName() + ": connected to Cassandra on: " + server);
            }
            for (final Option option : line.getOptions()) {
                if (option instanceof RunnableOption) {
                    ((RunnableOption) option).run(line);
                }
            }
        } finally {
            Tool.mgr.close().get(); // shutdown and wait for its completion
        }
    } catch (Exception e) {
        System.err.print(Tool.class.getSimpleName() + ": unexpected exception: ");
        e.printStackTrace(System.err);
        System.exit(1);
    }
}

From source file:es.upm.fi.dia.oeg.sitemap4rdf.Generator.java

/**
 * @param args//from ww w. java  2 s  . c o m
 */
public static void main(String[] args) {
    if (!isConfigFileOptionPresent(args)) {
        createOptions();
        CommandLineParser parser = new PosixParser();
        CommandLine cmd = null;
        try {
            cmd = parser.parse(options, args);
        } catch (ParseException e) {
            System.err.println(e.getMessage());
            System.exit(-1);
        }

        if (cmd.hasOption("h")) {
            printHelp();
            System.exit(0);
        }
        if (cmd.getArgs().length != 2) {
            printHelp();
            System.exit(-1);
        }

        Generator generator = new Generator();

        generator.setEndPoint(cmd.getArgs()[0]);
        generator.setUriPattern(cmd.getArgs()[1]);

        if (cmd.hasOption("o"))
            generator.setOutputDir(cmd.getOptionValue("o"));

        if (cmd.hasOption("f"))
            generator.setChangeFreq(cmd.getOptionValue("f"));

        if (cmd.hasOption("l"))
            generator.setLastMod(cmd.getOptionValue("l"));

        if (cmd.hasOption("x"))
            generator.setExclude(cmd.getOptionValue("x"));

        if (cmd.hasOption("z"))
            generator.setGzip(TRUE);

        if (cmd.hasOption("r"))
            generator.setSiteRoot(cmd.getOptionValue("r"));

        if (cmd.hasOption("d")) {
            for (String ddl : cmd.getOptionValues("d"))
                generator.setDatasetDumpLocation(ddl);
        }
        generator.generate();

    } else {
        Generator generator = new Generator();
        generator.setConfigurationFile(args[1]);
        generator.generate();
    }

}

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

public static void main(String[] args) throws Exception {
    Options opts = new Options();
    for (Option.Builder b : OPTION_BUILDERS) {
        opts.addOption(b.build());/*from   w w w.  ja  v a 2s  . 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(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);
    }

    Double fontScale = null;
    if (cl.hasOption("font-scale")) {
        try {
            fontScale = Double.parseDouble(cl.getOptionValue("font-scale"));
        } catch (IllegalArgumentException e) {
            System.err.format("Argument for font-scale must be a floating point number.\n");
            System.exit(1);
        }
    }

    try (DB db = DB.openDBFromCLI(cl)) {
        Set<String> includeIons = null;
        if (cl.hasOption("include-ions")) {
            String[] ionNames = cl.getOptionValues("include-ions");
            includeIons = new HashSet<>(Arrays.asList(ionNames));
            System.out.format("Including ions in search: %s\n", StringUtils.join(includeIons, ", "));
        }
        Set<String> excludeIons = null;
        if (cl.hasOption("exclude-ions")) {
            String[] ionNames = cl.getOptionValues("exclude-ions");
            excludeIons = new HashSet<>(Arrays.asList(ionNames));
            System.out.format("Excluding ions from search: %s\n", StringUtils.join(excludeIons, ", "));
        }

        Set<Integer> takeSamplesFromPlateIds = null;
        if (cl.hasOption(OPTION_FILTER_BY_PLATE_BARCODE)) {
            String[] plateBarcodes = cl.getOptionValues(OPTION_FILTER_BY_PLATE_BARCODE);
            System.out.format("Considering only sample wells in plates: %s\n",
                    StringUtils.join(plateBarcodes, ", "));
            takeSamplesFromPlateIds = new HashSet<>(plateBarcodes.length);
            for (String plateBarcode : plateBarcodes) {
                Plate p = Plate.getPlateByBarcode(db, plateBarcode);
                if (p == null) {
                    System.err.format("WARNING: unable to find plate in DB with barcode %s\n", plateBarcode);
                } else {
                    takeSamplesFromPlateIds.add(p.getId());
                }
            }
            // Allow filtering on barcode even if we couldn't find any in the DB.
        }

        System.out.format("Loading/updating LCMS scan files into DB\n");
        ScanFile.insertOrUpdateScanFilesInDirectory(db, lcmsDir);

        System.out.format("Processing LCMS scans\n");
        Pair<List<LCMSWell>, Set<Integer>> positiveWellsAndPlateIds = Utils.extractWellsAndPlateIds(db,
                cl.getOptionValues(OPTION_STRAINS), cl.getOptionValues(OPTION_CONSTRUCTS),
                takeSamplesFromPlateIds, false);
        List<LCMSWell> positiveWells = positiveWellsAndPlateIds.getLeft();
        if (positiveWells.size() == 0) {
            throw new RuntimeException("Found no LCMS wells for specified strains/constructs");
        }
        // Only take negative samples from the plates where we found the positive samples.
        Pair<List<LCMSWell>, Set<Integer>> negativeWellsAndPlateIds = Utils.extractWellsAndPlateIds(db,
                cl.getOptionValues(OPTION_NEGATIVE_STRAINS), cl.getOptionValues(OPTION_NEGATIVE_CONSTRUCTS),
                positiveWellsAndPlateIds.getRight(), true);
        List<LCMSWell> negativeWells = negativeWellsAndPlateIds.getLeft();
        if (negativeWells == null || negativeWells.size() == 0) {
            System.err.format("WARNING: no valid negative samples found in same plates as positive samples\n");
        }

        // Extract the reference MZ that will be used in the LCMS trace processing.
        List<Pair<String, Double>> searchMZs = null;
        Set<CuratedChemical> standardChemicals = null;
        List<ChemicalAssociatedWithPathway> pathwayChems = null;
        if (cl.hasOption(OPTION_SEARCH_MZ)) {
            // Assume mz can be an FP number of a chemical name.
            String massStr = cl.getOptionValue(OPTION_SEARCH_MZ);
            Pair<String, Double> searchMZ = Utils.extractMassFromString(db, massStr);
            if (searchMZ != null) {
                searchMZs = Collections.singletonList(searchMZ);
            }
            standardChemicals = Utils.extractTargetsForWells(db, positiveWells);
        } else {
            CuratedChemical targetChemical = Utils.requireOneTarget(db, positiveWells);
            if (targetChemical == null) {
                throw new RuntimeException(
                        "Unable to find a curated chemical entry for specified strains'/constructs' targets.  "
                                + "Please specify a chemical name or m/z explicitly or update the curated chemicals list in the DB.");
            }
            System.out.format("Using reference M/Z for positive target %s (%f)\n", targetChemical.getName(),
                    targetChemical.getMass());
            searchMZs = Collections.singletonList(Pair.of(targetChemical.getName(), targetChemical.getMass()));
            standardChemicals = Collections.singleton(targetChemical);
        }

        // Look up the standard by name, or use the target if none is specified.
        List<StandardWell> standardWells = null;
        if (cl.hasOption(OPTION_NO_STANDARD)) {
            System.err.format("WARNING: skipping standard comparison (no-standard option specified)\n");
            standardWells = new ArrayList<>(0);
        } else if (cl.hasOption(OPTION_STANDARD_WELLS)) {
            String[] standardCoordinates = cl.getOptionValues(OPTION_STANDARD_WELLS);
            standardWells = new ArrayList<>(standardCoordinates.length);
            Plate standardPlate = Plate.getPlateByBarcode(db, cl.getOptionValue(OPTION_STANDARD_PLATE_BARCODE));
            List<String> foundCoordinates = new ArrayList<>(standardCoordinates.length);
            for (String stringCoords : standardCoordinates) {
                Pair<Integer, Integer> coords = Utils.parsePlateCoordinates(stringCoords);
                StandardWell well = StandardWell.getInstance().getStandardWellsByPlateIdAndCoordinates(db,
                        standardPlate.getId(), coords.getLeft(), coords.getRight());
                if (well == null) {
                    System.err.format("Unable to find standard well at %s [%s]\n", standardPlate.getBarcode(),
                            stringCoords);
                    continue;
                }
                standardWells.add(well);
                foundCoordinates.add(stringCoords);
            }
            System.out.format("Using explicitly specified standard wells %s [%s]\n", standardPlate.getBarcode(),
                    StringUtils.join(foundCoordinates, ", "));
        } else if (cl.hasOption(OPTION_STANDARD_NAME)) {
            String standardName = cl.getOptionValue(OPTION_STANDARD_NAME);
            System.out.format("Using explicitly specified standard %s\n", standardName);
            standardWells = Collections.singletonList(Utils.extractStandardWellFromPlate(db,
                    cl.getOptionValue(OPTION_STANDARD_PLATE_BARCODE), standardName));
        } else if (standardChemicals != null && standardChemicals.size() > 0) {
            // Default to using the target chemical(s) as a standard if none is specified.
            standardWells = new ArrayList<>(standardChemicals.size());
            for (CuratedChemical c : standardChemicals) {
                String standardName = c.getName();
                System.out.format("Searching for well containing standard %s\n", standardName);
                standardWells.add(Utils.extractStandardWellFromPlate(db,
                        cl.getOptionValue(OPTION_STANDARD_PLATE_BARCODE), standardName));
            }
        }

        boolean useFineGrainedMZ = cl.hasOption("fine-grained-mz");
        boolean useSNR = cl.hasOption(OPTION_USE_SNR);

        /* Process the standard, positive, and negative wells, producing ScanData containers that will allow them to be
         * iterated over for graph writing. */
        HashMap<Integer, Plate> plateCache = new HashMap<>();
        Pair<List<ScanData<StandardWell>>, Double> allStandardScans = AnalysisHelper.processScans(db, lcmsDir,
                searchMZs, ScanData.KIND.STANDARD, plateCache, standardWells, useFineGrainedMZ, includeIons,
                excludeIons, useSNR);
        Pair<List<ScanData<LCMSWell>>, Double> allPositiveScans = AnalysisHelper.processScans(db, lcmsDir,
                searchMZs, ScanData.KIND.POS_SAMPLE, plateCache, positiveWells, useFineGrainedMZ, includeIons,
                excludeIons, useSNR);
        Pair<List<ScanData<LCMSWell>>, Double> allNegativeScans = AnalysisHelper.processScans(db, lcmsDir,
                searchMZs, ScanData.KIND.NEG_CONTROL, plateCache, negativeWells, useFineGrainedMZ, includeIons,
                excludeIons, useSNR);

        String fmt = "pdf";
        String outImg = cl.getOptionValue(OPTION_OUTPUT_PREFIX) + "." + fmt;
        String outData = cl.getOptionValue(OPTION_OUTPUT_PREFIX) + ".data";
        System.err.format("Writing combined scan data to %s and graphs to %s\n", outData, outImg);

        produceLCMSSearchPlots(lcmsDir, outData, outImg, allStandardScans, allPositiveScans, allNegativeScans,
                fontScale, useFineGrainedMZ, cl.hasOption(OPTION_USE_HEATMAP), useSNR);
    }
}

From source file:com.ignorelist.kassandra.steam.scraper.TaggerCli.java

/**
 * @param args the command line arguments
 * @throws java.io.IOException/* w  w w .  j  a v  a  2  s .  c om*/
 * @throws org.antlr.runtime.RecognitionException
 * @throws org.apache.commons.cli.ParseException
 */
public static void main(String[] args) throws IOException, RecognitionException, ParseException {
    Options options = buildOptions();
    CommandLineParser parser = new DefaultParser();
    CommandLine commandLine;
    try {
        commandLine = parser.parse(options, args);
    } catch (ParseException pe) {
        System.out.println(pe.getMessage());
        System.out.println();
        printHelp(options);
        System.exit(0);
        return;
    }
    if (commandLine.hasOption("h")) {
        printHelp(options);
        System.exit(0);
    }
    final PathResolver pathResolver = new PathResolver();

    Configuration configuration;
    Path configurationFile = pathResolver.findConfiguration();
    if (Files.isRegularFile(configurationFile)) {
        configuration = Configuration.fromPropertiesFile(configurationFile);
    } else {
        configuration = new Configuration();
    }
    configuration = toConfiguration(configuration, commandLine);
    //configuration.toProperties().store(System.err, null);

    if (!Files.isRegularFile(configurationFile)) {
        configuration.writeProperties(configurationFile);
        System.err.println(
                "no configuration file present, write based on CLI options: " + configurationFile.toString());
        configuration.toProperties().store(System.err, null);
    }

    Set<Path> sharedConfigPaths = configuration.getSharedConfigPaths();
    if (sharedConfigPaths.size() > 1 && !commandLine.hasOption("w")) {
        System.err.println("multiple sharedconfig.vdf available:\n" + Joiner.on("\n").join(sharedConfigPaths)
                + "\n, can not write to stdout. Need to specify -w or -f with a single sharedconfig.vdf");
        System.exit(1);
    }

    Tagger.Options taggerOptions = Tagger.Options.fromConfiguration(configuration);

    final String[] removeTagsValues = commandLine.getOptionValues("remove");
    if (null != removeTagsValues) {
        taggerOptions.setRemoveTags(Sets.newHashSet(removeTagsValues));
    }

    Set<TagType> tagTypes = configuration.getTagTypes();
    if (null == tagTypes) {
        System.err.println("no tag types!");
        System.exit(1);
    }

    final boolean printTags = commandLine.hasOption("p");

    final HtmlTagLoader htmlTagLoader = new HtmlTagLoader(pathResolver.findCachePath("html"),
            null == configuration.getCacheExpiryDays() ? 7 : configuration.getCacheExpiryDays());
    final BatchTagLoader tagLoader = new BatchTagLoader(htmlTagLoader, configuration.getDownloadThreads());
    if (true || commandLine.hasOption("v")) {
        tagLoader.registerEventListener(new CliEventLoggerLoaded());
    }
    Tagger tagger = new Tagger(tagLoader);

    if (printTags) {
        Set<String> availableTags = tagger.getAvailableTags(sharedConfigPaths, taggerOptions);
        Joiner.on("\n").appendTo(System.out, availableTags);
    } else {
        for (Path path : sharedConfigPaths) {
            VdfNode tagged = tagger.tag(path, taggerOptions);
            if (commandLine.hasOption("w")) {
                Path backup = path.getParent()
                        .resolve(path.getFileName().toString() + ".bak" + new Date().getTime());
                Files.copy(path, backup, StandardCopyOption.REPLACE_EXISTING);
                System.err.println("backup up " + path + " to " + backup);
                Files.copy(new ByteArrayInputStream(tagged.toPrettyString().getBytes(StandardCharsets.UTF_8)),
                        path, StandardCopyOption.REPLACE_EXISTING);
                try {
                    Files.setPosixFilePermissions(path, SHARED_CONFIG_POSIX_PERMS);
                } catch (Exception e) {
                    System.err.println(e);
                }
                System.err.println("wrote " + path);
            } else {
                System.out.println(tagged.toPrettyString());
                System.err.println("pipe to file and copy to: " + path.toString());
            }
        }
    }
}

From source file:de.urszeidler.ethereum.licencemanager1.deployer.LicenseManagerDeployer.java

/**
 * @param args//from   w  w w  .ja  va2s . c  o  m
 */
public static void main(String[] args) {
    Options options = createOptions();
    CommandLineParser parser = new DefaultParser();
    int returnValue = 0;
    boolean dontExit = false;
    try {
        CommandLine commandLine = parser.parse(options, args);
        if (commandLine.hasOption("h")) {
            printHelp(options);
            return;
        }
        if (commandLine.hasOption("de"))
            dontExit = true;

        String senderKey = null;
        String senderPass = null;
        if (commandLine.hasOption("sk"))
            senderKey = commandLine.getOptionValue("sk");
        if (commandLine.hasOption("sp"))
            senderPass = commandLine.getOptionValue("sp");

        LicenseManagerDeployer manager = new LicenseManagerDeployer();

        try {
            manager.init(senderKey, senderPass);

            long currentMili = 0;
            EthValue balance = null;
            if (commandLine.hasOption("calcDeploymendCost")) {
                currentMili = System.currentTimeMillis();
                balance = manager.ethereum.getBalance(manager.sender);
            }
            if (commandLine.hasOption("observeBlock")) {
                manager.ethereum.events().observeBlocks()
                        .subscribe(b -> System.out.println("Block: " + b.blockNumber + " " + b.receipts));
            }

            if (commandLine.hasOption("f")) {
                String[] values = commandLine.getOptionValues("f");

                String filename = values[0];
                String isCompiled = values[1];
                manager.deployer.setContractSource(filename, Boolean.parseBoolean(isCompiled));
            }
            if (commandLine.hasOption("millis")) {
                manager.setMillis(Long.parseLong(commandLine.getOptionValue("millis")));
            }

            if (commandLine.hasOption("c")) {
                String[] values = commandLine.getOptionValues("c");
                if (values == null || values.length != 2) {
                    System.out.println("Error. Need 2 parameters: paymentAddress,name");
                    System.out.println("");
                    printHelp(options);
                    return;
                }

                String paymentAddress = values[0];
                String name = values[1];
                manager.deployLicenseManager(EthAddress.of(paymentAddress), name);
            } else if (commandLine.hasOption("l")) {
                String contractAddress = commandLine.getOptionValue("l");
                if (contractAddress == null) {
                    System.out.println("Error. Need 1 parameters: contract address");
                    System.out.println("");
                    printHelp(options);
                    return;
                }
                manager.setManager(EthAddress.of(contractAddress));
                manager.listContractData(EthAddress.of(contractAddress));
            } else if (commandLine.hasOption("cic")) {
                String[] values = commandLine.getOptionValues("cic");
                if (values == null || values.length != 6) {
                    System.out.println("Error. Need 6 itemName, textHash, url, lifeTime, price");
                    System.out.println("");
                    printHelp(options);
                    return;
                }
                String contractAddress = values[0];
                String itemName = values[1];
                String textHash = values[2];
                String url = values[3];
                String lifeTime = values[4];
                String price = values[5];

                manager.setManager(EthAddress.of(contractAddress));
                manager.createIssuerContract(itemName, textHash, url, Integer.parseInt(lifeTime),
                        Integer.parseInt(price));
            } else if (commandLine.hasOption("bli")) {
                String[] values = commandLine.getOptionValues("bli");
                if (values == null || values.length < 2 || values.length > 3) {
                    System.out.println(
                            "Error. Need 2-3 issuerAddress, name, optional an address when not use the sender.");
                    System.out.println("");
                    printHelp(options);
                    return;
                }
                String issuerAddress = values[0];
                String name = values[1];
                String address = values.length > 2 ? values[2] : null;

                manager.buyLicense(issuerAddress, name, address);
            } else if (commandLine.hasOption("v")) {
                String[] values = commandLine.getOptionValues("v");

                String issuerAddress = values[0];
                String message = values[1];
                String signature = values[2];
                String publicKey = values[3];

                manager.verifyLicense(issuerAddress, message, signature, publicKey);
            } else if (commandLine.hasOption("cs")) {
                String message = commandLine.getOptionValue("cs");
                if (message == null) {
                    System.out.println("Error. Need 1 parameter: message");
                    System.out.println("");
                    printHelp(options);
                    return;
                }
                String signature = createSignature(manager.sender, message);
                String publicKeyString = toPublicKeyString(manager.sender);
                System.out.println("The signature for the message is:");
                System.out.println(signature);
                System.out.println("The public key is:");
                System.out.println(publicKeyString);
            } else if (commandLine.hasOption("co")) {
                String[] values = commandLine.getOptionValues("co");
                if (values == null || values.length != 2) {
                    System.out.println("Error. Need 2 parameters: contractAddress, newOwnerAddress");
                    System.out.println("");
                    printHelp(options);
                    return;
                }

                String contractAddress = values[0];
                String newOwner = values[1];

                manager.changeOwner(EthAddress.of(contractAddress), EthAddress.of(newOwner));
            } else if (commandLine.hasOption("si")) {
                String contractAddress = commandLine.getOptionValue("si");
                if (contractAddress == null) {
                    System.out.println("Error. Need 1 parameters: contract address");
                    System.out.println("");
                    printHelp(options);
                    return;
                }
                manager.setManager(EthAddress.of(contractAddress));
                manager.stopIssue(contractAddress);
            } else if (commandLine.hasOption("ppuk")) {
                System.out.println("Public key: " + toPublicKeyString(manager.sender));
            }

            if (manager.licenseManager != null && commandLine.hasOption("wca")) {
                String[] values = commandLine.getOptionValues("wca");
                String filename = values[0];

                File file = new File(filename);
                IOUtils.write(
                        !commandLine.hasOption("cic") ? manager.licenseManager.contractAddress.withLeading0x()
                                : manager.licenseManager.contractInstance
                                        .contracts(manager.licenseManager.contractInstance.contractCount() - 1)
                                        .withLeading0x(),
                        new FileOutputStream(file), "UTF-8");
            }

            if (commandLine.hasOption("calcDeploymendCost")) {
                balance = balance.minus(manager.ethereum.getBalance(manager.sender));
                BigDecimal divide = new BigDecimal(balance.inWei())
                        .divide(BigDecimal.valueOf(1_000_000_000_000_000_000L));

                System.out.println("Deployment cost: " + (divide) + " in wei:" + balance.inWei()
                        + " time need: " + (System.currentTimeMillis() - currentMili));
            }

        } catch (Exception e) {
            System.out.println(e.getMessage());
            printHelp(options);
            returnValue = 10;
        }

    } catch (ParseException e1) {
        System.out.println(e1.getMessage());
        printHelp(options);
        returnValue = 10;
    }
    if (!dontExit)
        System.exit(returnValue);
}