Example usage for org.apache.commons.cli HelpFormatter printHelp

List of usage examples for org.apache.commons.cli HelpFormatter printHelp

Introduction

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

Prototype

public void printHelp(String cmdLineSyntax, Options options) 

Source Link

Document

Print the help for options with the specified command line syntax.

Usage

From source file:com.evolveum.midpoint.testing.model.client.sample.RunScript.java

/**
* @param args/*from   w  ww. j  a va  2  s .com*/
*/
public static void main(String[] args) {
    try {

        Options options = new Options();
        options.addOption(OPT_HELP, "help", false, "Print this help information");
        options.addOption(OPT_SCRIPT, "script", true, "Script file (XML for the moment)");
        options.addOption(OPT_URL, true, "Endpoint URL (default: " + DEFAULT_ENDPOINT_URL + ")");
        options.addOption(OPT_USER, "user", true, "User name (default: " + ADM_USERNAME + ")");
        options.addOption(OPT_PASSWORD, "password", true, "Password");
        options.addOption(OPT_FILE_FOR_DATA, "file-for-data", true,
                "Name of the file to write resulting XML data into");
        options.addOption(OPT_FILE_FOR_CONSOLE, "file-for-console", true,
                "Name of the file to write resulting console output into");
        options.addOption(OPT_FILE_FOR_RESULT, "file-for-result", true,
                "Name of the file to write operation result into");
        options.addOption(OPT_HIDE_DATA, "hide-data", false, "Don't display data output");
        options.addOption(OPT_HIDE_SCRIPT, "hide-script", false, "Don't display input script");
        options.addOption(OPT_HIDE_CONSOLE, "hide-console", false, "Don't display console output");
        options.addOption(OPT_HIDE_RESULT, "hide-result", false,
                "Don't display detailed operation result (default: showing if not SUCCESS)");
        options.addOption(OPT_SHOW_RESULT, "show-result", false,
                "Always show detailed operation result (default: showing if not SUCCESS)");
        options.addOption(OptionBuilder.withArgName("property=value").hasArgs(2).withValueSeparator()
                .withDescription("use value for given property").create("D"));
        CommandLineParser parser = new GnuParser();
        CommandLine cmdline = parser.parse(options, args);

        if (!cmdline.hasOption(OPT_SCRIPT) || cmdline.hasOption("h")) {
            HelpFormatter helpFormatter = new HelpFormatter();
            helpFormatter.printHelp("runscript", options);
            System.exit(0);
        }

        ExecuteScriptsType request = new ExecuteScriptsType();
        String script = readXmlFile(cmdline.getOptionValue(OPT_SCRIPT));
        script = replaceParameters(script, cmdline.getOptionProperties("D"));
        request.setMslScripts(script); // todo fix this hack
        ExecuteScriptsOptionsType optionsType = new ExecuteScriptsOptionsType();
        optionsType.setOutputFormat(OutputFormatType.MSL); // todo fix this hack
        request.setOptions(optionsType);

        if (!cmdline.hasOption(OPT_HIDE_SCRIPT)) {
            System.out.println("\nScript to execute:\n" + script);
        }
        System.out.println("=================================================================");

        ModelPortType modelPort = createModelPort(cmdline);

        ExecuteScriptsResponseType response = modelPort.executeScripts(request);

        System.out.println("=================================================================");

        for (SingleScriptOutputType output : response.getOutputs().getOutput()) {
            if (!cmdline.hasOption(OPT_HIDE_DATA)) {
                System.out.println("Data:\n" + output.getMslData());
                System.out.println("-----------------------------------------------------------------");
            }
            if (cmdline.hasOption(OPT_FILE_FOR_DATA)) {
                IOUtils.write(output.getMslData(),
                        new FileOutputStream(cmdline.getOptionValue(OPT_FILE_FOR_DATA)), "UTF-8");
            }
            if (!cmdline.hasOption(OPT_HIDE_CONSOLE)) {
                System.out.println("Console output:\n" + output.getTextOutput());
            }
            if (cmdline.hasOption(OPT_HIDE_CONSOLE)) {
                IOUtils.write(output.getMslData(),
                        new FileWriter(cmdline.getOptionValue(OPT_FILE_FOR_CONSOLE)));
            }
        }

        System.out.println("=================================================================");
        System.out.println("Operation result: " + getResultStatus(response.getResult()));
        if (!cmdline.hasOption(OPT_HIDE_RESULT)
                && (cmdline.hasOption(OPT_SHOW_RESULT) || response.getResult() == null
                        || response.getResult().getStatus() != OperationResultStatusType.SUCCESS)) {
            System.out.println("\n\n" + marshalResult(response.getResult()));
        }
        if (cmdline.hasOption(OPT_FILE_FOR_RESULT)) {
            IOUtils.write(marshalResult(response.getResult()),
                    new FileWriter(cmdline.getOptionValue(OPT_FILE_FOR_RESULT)));
        }

    } catch (Exception e) {
        e.printStackTrace();
        System.exit(-1);
    }
}

From source file:diffhunter.DiffHunter.java

/**
 * @param args the command line arguments
 * @throws org.apache.commons.cli.ParseException
 * @throws java.io.IOException// w  w w.  j a  va  2  s  .  co  m
 */
public static void main(String[] args) throws ParseException, IOException {

    //String test_ = Paths.get("J:\\VishalData\\additional\\", "Sasan" + "_BDB").toAbsolutePath().toString();

    // TODO code application logic here
    /*args = new String[]
    {
    "-i", "-b", "J:\\VishalData\\additional\\Ptbp2_E18_5_cortex_CLIP_mm9_plus_strand_sorted.bed", "-r", "J:\\VishalData\\additional\\mouse_mm9.txt", "-o", "J:\\VishalData"
    };*/

    /*args = new String[]
    {
    "-c", "-r", "J:\\VishalData\\additional\\mouse_mm9.txt", "-1", "J:\\VishalData\\Ptbp2_Adult_testis_CLIP_mm9_plus_strand_sorted_BDB", "-2", "J:\\VishalData\\Ptbp2_E18_5_cortex_CLIP_mm9_plus_strand_sorted_BDB", "-w", "200", "-s", "50", "-o", "J:\\VishalData"
    };*/
    Options options = new Options();

    // add t option
    options.addOption("i", "index", false, "Indexing BED files.");
    options.addOption("b", "bed", true, "bed file to be indexed");
    options.addOption("o", "output", true, "Folder that the index/comparison file will be created.");
    options.addOption("r", "reference", true, "Reference annotation file to be used for indexing");
    options.addOption("c", "compare", false, "Finding differences between two conditions");
    options.addOption("1", "first", true, "First sample index location");
    options.addOption("2", "second", true, "Second sample index location");
    options.addOption("w", "window", true, "Length of window for identifying differences");
    options.addOption("s", "sliding", true, "Length of sliding");

    CommandLineParser parser = new BasicParser();
    CommandLine cmd = parser.parse(options, args);

    boolean indexing = false;
    boolean comparing = false;

    //Indexing!
    if (cmd.hasOption("i")) {
        //if(cmd.hasOption("1"))
        //System.err.println("sasan");

        //System.out.println("sasa");
        indexing = true;

    } else if (cmd.hasOption("c")) {
        //System.err.println("");
        comparing = true;

    } else {
        //System.err.println("Option is not deteced.");
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("diffhunter", options);
        return;
    }

    //Indexing is selected
    //
    if (indexing == true) {
        //Since indexing is true.
        //User have to provide file for indexing.
        if (!(cmd.hasOption("o") || cmd.hasOption("r") || cmd.hasOption("b"))) {
            HelpFormatter formatter = new HelpFormatter();
            formatter.printHelp("diffhunter", options);
            return;
        }
        String bedfile_ = cmd.getOptionValue("b");
        String reference_file = cmd.getOptionValue("r");
        String folder_loc = cmd.getOptionValue("o");

        String sample_name = FilenameUtils.getBaseName(bedfile_);

        try (Database B2 = BerkeleyDB_Box.Get_BerkeleyDB(
                Paths.get(folder_loc, sample_name + "_BDB").toAbsolutePath().toString(), true, sample_name)) {
            Indexer indexing_ = new Indexer(reference_file);
            indexing_.Make_Index(B2, bedfile_,
                    Paths.get(folder_loc, sample_name + "_BDB").toAbsolutePath().toString());
            B2.close();

        }
    } else if (comparing == true) {
        if (!(cmd.hasOption("o") || cmd.hasOption("w") || cmd.hasOption("s") || cmd.hasOption("1")
                || cmd.hasOption("2"))) {
            HelpFormatter formatter = new HelpFormatter();
            formatter.printHelp("diffhunter", options);
            return;
        }
        String folder_loc = cmd.getOptionValue("o");
        int window_ = Integer.parseInt(cmd.getOptionValue("w"));
        //int window_=600;

        int slide_ = Integer.parseInt(cmd.getOptionValue("s"));

        String first = cmd.getOptionValue("1").replace("_BDB", "");
        String second = cmd.getOptionValue("2").replace("_BDB", "");
        String reference_file = cmd.getOptionValue("r");
        //String folder_loc=cmd.getOptionValue("o");

        String sample_name_first = FilenameUtils.getBaseName(first);
        String sample_name_second = FilenameUtils.getBaseName(second);

        Database B1 = BerkeleyDB_Box.Get_BerkeleyDB(first + "_BDB", false, sample_name_first);
        Database B2 = BerkeleyDB_Box.Get_BerkeleyDB(second + "_BDB", false, sample_name_second);

        List<String> first_condition_genes = Files
                .lines(Paths.get(first + "_BDB", sample_name_first + ".txt").toAbsolutePath())
                .collect(Collectors.toList());
        List<String> second_condition_genes = Files
                .lines(Paths.get(second + "_BDB", sample_name_second + ".txt").toAbsolutePath())
                .collect(Collectors.toList());
        System.out.println("First and second condition are loaded!!! ");
        List<String> intersection_ = new ArrayList<>(first_condition_genes);
        intersection_.retainAll(second_condition_genes);

        BufferedWriter output = new BufferedWriter(
                new FileWriter(Paths.get(folder_loc, "differences_" + window_ + "_s" + slide_ + "_c" + ".txt")
                        .toAbsolutePath().toString(), false));
        List<Result_Window> final_results = Collections.synchronizedList(new ArrayList<>());
        Worker_New worker_class = new Worker_New();
        worker_class.Read_Reference(reference_file);

        while (!intersection_.isEmpty()) {
            List<String> selected_genes = new ArrayList<>();
            //if (intersection_.size()<=10000){selected_genes.addAll(intersection_.subList(0, intersection_.size()));}
            //else selected_genes.addAll(intersection_.subList(0, 10000));
            if (intersection_.size() <= intersection_.size()) {
                selected_genes.addAll(intersection_.subList(0, intersection_.size()));
            } else {
                selected_genes.addAll(intersection_.subList(0, intersection_.size()));
            }
            intersection_.removeAll(selected_genes);
            //System.out.println("Intersection count is:"+intersection_.size());
            //final List<Result_Window> resultssss_=new ArrayList<>();
            IntStream.range(0, selected_genes.size()).parallel().forEach(i -> {
                System.out.println(selected_genes.get(i) + "\tprocessing......");
                String gene_of_interest = selected_genes.get(i);//"ENSG00000142657|PGD";//intersection_.get(6);////"ENSG00000163395|IGFN1";//"ENSG00000270066|SCARNA2";
                int start = worker_class.dic_genes.get(gene_of_interest).start_loc;
                int end = worker_class.dic_genes.get(gene_of_interest).end_loc;

                Map<Integer, Integer> first_ = Collections.EMPTY_MAP;
                try {
                    first_ = BerkeleyDB_Box.Get_Coord_Read(B1, gene_of_interest);
                } catch (IOException | ClassNotFoundException ex) {
                    Logger.getLogger(DiffHunter.class.getName()).log(Level.SEVERE, null, ex);
                }

                Map<Integer, Integer> second_ = Collections.EMPTY_MAP;
                try {
                    second_ = BerkeleyDB_Box.Get_Coord_Read(B2, gene_of_interest);
                } catch (IOException | ClassNotFoundException ex) {
                    Logger.getLogger(DiffHunter.class.getName()).log(Level.SEVERE, null, ex);
                }
                List<Window> top_windows_first = worker_class.Get_Top_Windows(window_, first_, slide_);
                List<Window> top_windows_second = worker_class.Get_Top_Windows(window_, second_, slide_);
                //System.out.println("passed for window peak call for gene \t"+selected_genes.get(i));
                // System.out.println("top_window_first_Count\t"+top_windows_first.size());
                // System.out.println("top_window_second_Count\t"+top_windows_second.size());
                if (top_windows_first.isEmpty() && top_windows_second.isEmpty()) {
                    return;
                }

                List<Result_Window> res_temp = new Worker_New().Get_Significant_Windows(gene_of_interest, start,
                        end, top_windows_first, top_windows_second, second_, first_, sample_name_first,
                        sample_name_second, 0.01);
                if (!res_temp.isEmpty()) {
                    final_results.addAll(res_temp);//final_results.addAll(worker_class.Get_Significant_Windows(gene_of_interest, start, end, top_windows_first, top_windows_second, second_, first_, first_condition, second_condition, 0.01));

                } //System.out.println(selected_genes.get(i)+"\tprocessed.");

            });

            /*selected_genes.parallelStream().forEach(i ->
             {
                    
                    
             });*/
            List<Double> pvals = new ArrayList<>();

            for (int i = 0; i < final_results.size(); i++) {
                pvals.add(final_results.get(i).p_value);
            }
            List<Double> qvals = MultipleTestCorrection.benjaminiHochberg(pvals);

            System.out.println("Writing to file...");
            output.append("Gene_Symbol\tContributing_Sample\tStart\tEnd\tOddsRatio\tp_Value\tFDR");
            output.newLine();

            for (int i = 0; i < final_results.size(); i++) {
                Result_Window item = final_results.get(i);
                output.append(item.associated_gene_symbol + "\t" + item.contributing_windows + "\t"
                        + item.start_loc + "\t" + item.end_loc + "\t" + item.oddsratio_ + "\t" + item.p_value
                        + "\t" + qvals.get(i)); //+ "\t" + item.average_other_readcount_cotributing + "\t" + item.average_other_readcount_cotributing + "\t" + item.average_window_readcount_non + "\t" + item.average_other_readcount_non);
                output.newLine();
            }

            /* for (Result_Window item : final_results)
             {
            output.append(item.associated_gene_symbol + "\t" + item.contributing_windows + "\t" + item.start_loc + "\t" + item.end_loc + "\t" + item.oddsratio_ + "\t" + item.p_value); //+ "\t" + item.average_other_readcount_cotributing + "\t" + item.average_other_readcount_cotributing + "\t" + item.average_window_readcount_non + "\t" + item.average_other_readcount_non);
            output.newLine();
             }
               */
            final_results.clear();

        }
        output.close();

    }
    System.out.println("Done.");

}

From source file:com.github.thebigs.foscam.recorder.Recorder.java

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

    options.addOption("c", true, "Cam url (eg. http://<ip>:<port>/<stream page>?<params>");
    options.addOption("o", true,
            "Output dir location (default: './'). File names will default to '<YYYY.MM.DD-mm-ss>-<webcam name>.mp4'.");
    options.addOption("n", true, "Webcam name. Defaults to 'webcam'.");
    options.addOption("d", true, "Duration (in mins) before cycling to new video file (Defaults to 60mins).");
    options.addOption("x", true,
            "Max disk space (in megabytes [1024kb]) to use before overwritting recordings. Oldest recordings will be overwritten first. Defaults to -1 (unlimited)");
    options.addOption("h", false, "Print this help message.");

    try {/*from ww w .  j  a  v a 2s. c  o m*/
        CommandLine cli = new GnuParser().parse(options, args);

        String camUrl = null;
        String camName = null;
        String outputDir = null;
        Long durationMins = null;
        Long maxDiskSpaceMb = null;

        if (cli.hasOption("h")) {
            HelpFormatter formatter = new HelpFormatter();
            formatter.printHelp("java -jar recorder.jar", options);
            System.exit(-1);
        }
        if (cli.hasOption("c")) {
            camUrl = cli.getOptionValue("c");
        } else {
            System.err.println("Cam Url (-c) is required. Use -h for more information.");
            System.exit(-1);
        }
        if (cli.hasOption("n")) {
            camName = cli.getOptionValue("n");
        }
        if (cli.hasOption("o")) {
            outputDir = cli.getOptionValue("o");
        }
        if (cli.hasOption("d")) {
            durationMins = Long.parseLong(cli.getOptionValue("d"));
        }
        if (cli.hasOption("x")) {
            maxDiskSpaceMb = Long.parseLong(cli.getOptionValue("x"));
        }

        Recorder recording = new Recorder(camUrl, camName, outputDir, durationMins, maxDiskSpaceMb);

        System.out.println("Starting recording...");
        recording.run(); // stay here until program is terminated
    } catch (ParseException e) {
        System.err.println("Unable to parse command line options: " + e.getMessage());
    } catch (Exception e) {
        System.err.println("Unable to parse command line options: " + e.getMessage());
    }
}

From source file:luceneGazateer.EntryData.java

public static void main(String[] args) throws IOException {
    Option buildOpt = OptionBuilder.withArgName("gazetteer file").hasArg().withLongOpt("build")
            .withDescription("The Path to the Geonames allCountries.txt").create('b');

    Option searchOpt = OptionBuilder.withArgName("set of location names").withLongOpt("search").hasArgs()
            .withDescription("Location names to search the Gazetteer for").create('s');

    Option indexOpt = OptionBuilder.withArgName("directoryPath").withLongOpt("index").hasArgs()
            .withDescription("The path to the Lucene index directory to either create or read").create('i');

    Option helpOpt = OptionBuilder.withLongOpt("help").withDescription("Print this message.").create('h');

    String indexPath = null;/*  w ww  .j  av a 2s.co m*/
    String gazetteerPath = null;
    ArrayList<String> geoTerms = null;
    Options options = new Options();
    options.addOption(buildOpt);
    options.addOption(searchOpt);
    options.addOption(indexOpt);
    options.addOption(helpOpt);

    // create the parser
    CommandLineParser parser = new DefaultParser();
    GeoNameResolver resolver = new GeoNameResolver();

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

        if (line.hasOption("index")) {
            indexPath = line.getOptionValue("index");
        }

        if (line.hasOption("build")) {
            gazetteerPath = line.getOptionValue("build");
        }

        if (line.hasOption("help")) {
            HelpFormatter formatter = new HelpFormatter();
            formatter.printHelp("lucene-geo-gazetteer", options);
            System.exit(1);
        }

        if (indexPath != null && gazetteerPath != null) {
            LOG.info("Building Lucene index at path: [" + indexPath + "] with geoNames.org file: ["
                    + gazetteerPath + "]");
            resolver.buildIndex(gazetteerPath, indexPath);
        }

        if (line.hasOption("search")) {
            String temp_s = "";
            for (String string : line.getOptionValues("search")) {
                temp_s += string;
            }

            produceCandidates(indexPath, temp_s, resolver);
        }

    } catch (ParseException exp) {
        // oops, something went wrong
        System.err.println("Parsing failed.  Reason: " + exp.getMessage());
    }
}

From source file:com.guye.baffle.obfuscate.Main.java

public static void main(String[] args) throws IOException, BaffleException {
    Options opt = new Options();

    opt.addOption("c", "config", true, "config file path,keep or mapping");

    opt.addOption("o", "output", true, "output mapping writer file");

    opt.addOption("v", "verbose", false, "explain what is being done.");

    opt.addOption("h", "help", false, "print help for the command.");

    opt.getOption("c").setArgName("file list");

    opt.getOption("o").setArgName("file path");

    String formatstr = "baffle [-c/--config filepaths list ][-o/--output filepath][-h/--help] ApkFile TargetApkFile";

    HelpFormatter formatter = new HelpFormatter();
    CommandLineParser parser = new PosixParser();
    CommandLine cl = null;/*from  w w  w .  j  a v a  2s . c o  m*/
    try {
        // ?Options?
        cl = parser.parse(opt, args);

    } catch (ParseException e) {
        formatter.printHelp(formatstr, opt); // ???
        return;
    }

    if (cl == null || cl.getArgs() == null || cl.getArgs().length == 0) {
        formatter.printHelp(formatstr, opt);
        return;
    }

    // ?-h--help??
    if (cl.hasOption("h")) {
        HelpFormatter hf = new HelpFormatter();
        hf.printHelp(formatstr, "", opt, "");
        return;
    }

    // ???DirectoryName
    String[] str = cl.getArgs();
    if (str == null || str.length != 2) {
        HelpFormatter hf = new HelpFormatter();
        hf.printHelp("not specify apk file or taget apk file", opt);
        return;
    }

    if (str[1].equals(str[0])) {
        HelpFormatter hf = new HelpFormatter();
        hf.printHelp("apk file can not rewrite , please specify new target file", opt);
        return;
    }
    File apkFile = new File(str[0]);
    if (!apkFile.exists()) {
        HelpFormatter hf = new HelpFormatter();
        hf.printHelp("apk file not exists", opt);
        return;
    }

    File[] configs = null;
    if (cl.hasOption("c")) {
        String cfg = cl.getOptionValue("c");
        String[] fs = cfg.split(",");
        int len = fs.length;
        configs = new File[fs.length];
        for (int i = 0; i < len; i++) {
            configs[i] = new File(fs[i]);
            if (!configs[i].exists()) {
                HelpFormatter hf = new HelpFormatter();
                hf.printHelp("config file " + fs[i] + " not exists", opt);
                return;
            }
        }
    }

    File mappingfile = null;
    if (cl.hasOption("o")) {
        String mfile = cl.getOptionValue("o");
        mappingfile = new File(mfile);

        if (mappingfile.getParentFile() != null) {
            mappingfile.getParentFile().mkdirs();
        }

    }

    if (cl.hasOption('v')) {
        Logger.getLogger(Obfuscater.LOG_NAME).setLevel(Level.CONFIG);
    } else {
        Logger.getLogger(Obfuscater.LOG_NAME).setLevel(Level.OFF);
    }

    Logger.getLogger(Obfuscater.LOG_NAME).addHandler(new ConsoleHandler());

    Obfuscater obfuscater = new Obfuscater(configs, mappingfile, apkFile, str[1]);

    obfuscater.obfuscate();
}

From source file:cross.io.PropertyFileGenerator.java

/**
 *
 * @param args/*from w  ww.j  a v  a  2  s. c o m*/
 */
public static void main(String[] args) {
    Options options = new Options();
    options.addOption("f", true, "base directory for output of files");
    Option provOptions = new Option("p", true,
            "Comma separated list of provider classes to create Properties for");
    provOptions.setRequired(true);
    provOptions.setValueSeparator(',');
    options.addOption(provOptions);
    CommandLineParser parser = new PosixParser();
    HelpFormatter hf = new HelpFormatter();
    try {
        File basedir = null;
        List<String> providers = Collections.emptyList();
        CommandLine cmd = parser.parse(options, args);
        if (cmd.hasOption("f")) {
            basedir = new File(cmd.getOptionValue("f"));
        } else {
            hf.printHelp("java -cp maltcms.jar " + PropertyFileGenerator.class, options);
        }
        if (cmd.hasOption("p")) {
            String[] str = cmd.getOptionValues("p");
            providers = Arrays.asList(str);
        } else {
            hf.printHelp("java -cp maltcms.jar " + PropertyFileGenerator.class, options);
        }
        for (String provider : providers) {
            createProperties(provider, basedir);
        }
    } catch (ParseException ex) {
        Logger.getLogger(PropertyFileGenerator.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:com.example.dlp.DeIdentification.java

/**
 * Command line application to de-identify data using the Data Loss Prevention API.
 * Supported data format: strings//from   www  . j a va  2 s. com
 */
public static void main(String[] args) throws Exception {

    OptionGroup optionsGroup = new OptionGroup();
    optionsGroup.setRequired(true);

    Option deidentifyMaskingOption = new Option("m", "mask", true, "deid with character masking");
    optionsGroup.addOption(deidentifyMaskingOption);

    Option deidentifyFpeOption = new Option("f", "fpe", true, "deid with FFX FPE");
    optionsGroup.addOption(deidentifyFpeOption);

    Options commandLineOptions = new Options();
    commandLineOptions.addOptionGroup(optionsGroup);

    Option maskingCharacterOption = Option.builder("maskingCharacter").hasArg(true).required(false).build();
    commandLineOptions.addOption(maskingCharacterOption);

    Option numberToMaskOption = Option.builder("numberToMask").hasArg(true).required(false).build();
    commandLineOptions.addOption(numberToMaskOption);

    Option alphabetOption = Option.builder("commonAlphabet").hasArg(true).required(false).build();
    commandLineOptions.addOption(alphabetOption);

    Option wrappedKeyOption = Option.builder("wrappedKey").hasArg(true).required(false).build();
    commandLineOptions.addOption(wrappedKeyOption);

    Option keyNameOption = Option.builder("keyName").hasArg(true).required(false).build();
    commandLineOptions.addOption(keyNameOption);

    CommandLineParser parser = new DefaultParser();
    HelpFormatter formatter = new HelpFormatter();
    CommandLine cmd;

    try {
        cmd = parser.parse(commandLineOptions, args);
    } catch (ParseException e) {
        System.out.println(e.getMessage());
        formatter.printHelp(DeIdentification.class.getName(), commandLineOptions);
        System.exit(1);
        return;
    }

    if (cmd.hasOption("m")) {
        // deidentification with character masking
        int numberToMask = Integer.parseInt(cmd.getOptionValue(numberToMaskOption.getOpt(), "0"));
        char maskingCharacter = cmd.getOptionValue(maskingCharacterOption.getOpt(), "*").charAt(0);
        String val = cmd.getOptionValue(deidentifyMaskingOption.getOpt());
        deIdentifyWithMask(val, maskingCharacter, numberToMask);
    } else if (cmd.hasOption("f")) {
        // deidentification with FPE
        String wrappedKey = cmd.getOptionValue(wrappedKeyOption.getOpt());
        String keyName = cmd.getOptionValue(keyNameOption.getOpt());
        String val = cmd.getOptionValue(deidentifyFpeOption.getOpt());
        FfxCommonNativeAlphabet alphabet = FfxCommonNativeAlphabet.valueOf(
                cmd.getOptionValue(alphabetOption.getOpt(), FfxCommonNativeAlphabet.ALPHA_NUMERIC.name()));
        deIdentifyWithFpe(val, alphabet, keyName, wrappedKey);
    }
}

From source file:jeplus.util.LineEnds.java

public static void main(String[] args) {

    String LN = "\r\n";

    // create the parser
    CommandLineParser parser = new GnuParser();
    Options options = getCommandLineOptions();
    CommandLine commandline = null;//from ww  w  .  ja v a  2  s.  c o  m
    HelpFormatter formatter = new HelpFormatter();
    formatter.setWidth(80);
    try {
        // parse the command line arguments
        commandline = parser.parse(options, args);
        if (commandline.hasOption("help")) {
            // automatically generate the help statement
            formatter.printHelp("java -cp jEPlusNet.jar jeplusplus.util.LineEnds [OPTIONS]", options);
            System.exit(-1);
        }
        // Set log4j configuration
        if (commandline.hasOption("log")) {
            PropertyConfigurator.configure(commandline.getOptionValue("log"));
        } else {
            PropertyConfigurator.configure("log4j.cfg");
        }
    } catch (ParseException exp) {
        // oops, something went wrong
        System.err.println("Parsing failed.  Reason: " + exp.getMessage());
        // automatically generate the help statement
        formatter.printHelp("java -Xmx500m -jar JESS_Client.jar [OPTIONS]", options);
        System.exit(-1);
    }

    if (commandline.hasOption("style")) {
        if (commandline.getOptionValue("style").startsWith("L")) {
            LN = "\n";
        }
    }

    if (commandline.hasOption("file")) {
        File file = new File(commandline.getOptionValue("file"));
        if (file.exists()) {
            if (file.isDirectory()) {
                File[] listOfFiles = file.listFiles();
                for (int i = 0; i < listOfFiles.length; i++) {
                    if (listOfFiles[i].isFile()) {
                        convertFile(listOfFiles[i], LN);
                    }
                }
            } else {
                convertFile(file, LN);
            }
        }
    }
}

From source file:net.cliftonsnyder.svgchart.Main.java

public static void main(String[] args) {
    Options options = new Options();
    options.addOption("c", "stylesheet", true, "CSS stylesheet (default: " + SVGChart.DEFAULT_STYLESHEET + ")");
    options.addOption("h", "height", true, "chart height");
    options.addOption("i", "input-file", true, "input file [default: stdin]");
    options.addOption("o", "output-file", true, "output file [default: stdout]");
    options.addOption("w", "width", true, "chart width");
    options.addOption("?", "help", false, "print a brief help message");

    Option type = new Option("t", "type", true, "chart type " + Arrays.toString(SVGChart.TYPES));
    type.setRequired(true);//from   w w  w.j av  a 2 s  .co  m
    options.addOption(type);

    CommandLineParser parser = new GnuParser();
    HelpFormatter formatter = new HelpFormatter();
    CommandLine line = null;
    try {
        // parse the command line arguments
        line = parser.parse(options, args);
        if (line.hasOption("help")) {
            formatter.printHelp(USAGE, options);
            System.exit(0);
        }
    } catch (ParseException exp) {
        // oops, something went wrong
        System.err.println("unable to parse command line: " + exp.getMessage());
        formatter.printHelp(USAGE, options);
        System.exit(1);
    }

    SVGChart chart = null;
    String tmp = line.getOptionValue("type");
    Matcher m = null;
    for (Pattern p : SVGChart.TYPE_PATTERNS) {
        if ((m = p.matcher(tmp)).matches()) {
            switch (m.group().charAt(0)) {
            case 'l':
                // DEBUG
                System.err.println("line");
                break;
            case 'b':
                System.err.println("bar");
                chart = new BarChart();
                break;
            case 'p':
                System.err.println("pie");
                break;
            default:
                System.err.println("unknown or unimplemented chart type: '" + tmp + "'");
                System.exit(1);
            }
        }
    }

    try {
        chart.setWidth(Double.parseDouble(line.getOptionValue("width", "" + SVGChart.DEFAULT_WIDTH)));
    } catch (NumberFormatException e) {
        System.err.println(
                "unable to parse command line: invalid width value '" + line.getOptionValue("width") + "'");
        System.exit(1);
    }

    try {
        chart.setHeight(Double.parseDouble(line.getOptionValue("height", "" + SVGChart.DEFAULT_HEIGHT)));
    } catch (NumberFormatException e) {
        System.err.println(
                "unable to parse command line: invalid height value '" + line.getOptionValue("height") + "'");
        System.exit(1);
    }

    InputStream in = System.in;
    tmp = line.getOptionValue("input-file", "-");
    if ("-".equals(tmp)) {
        in = System.in;
    } else {
        try {
            in = new FileInputStream(tmp);
        } catch (FileNotFoundException e) {
            System.err.println("input file not found: '" + tmp + "'");
            System.exit(1);
        }
    }

    PrintStream out = System.out;
    tmp = line.getOptionValue("output-file", "-");
    if ("-".equals(tmp)) {
        out = System.out;
    } else {
        try {
            out = new PrintStream(new FileOutputStream(tmp));
        } catch (FileNotFoundException e) {
            System.err.println("output file not found: '" + tmp + "'");
            System.exit(1);
        }
    }

    tmp = line.getOptionValue("stylesheet", SVGChart.DEFAULT_STYLESHEET);
    chart.setStyleSheet(tmp);

    try {
        chart.parseInput(in);
    } catch (IOException e) {
        System.err.println("I/O error while reading input");
        System.exit(1);
    } catch (net.cliftonsnyder.svgchart.parse.ParseException e) {
        System.err.println("error parsing input: " + e.getMessage());
    }

    chart.createChart();

    try {
        chart.printChart(out, true);
    } catch (IOException e) {
        System.err.println("error serializing output");
        System.exit(1);
    }
}

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);//from   ww  w  .ja v a  2 s .co 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);
    }
}