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

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

Introduction

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

Prototype

Options

Source Link

Usage

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.com*/
 */
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:fr.inria.atlanmod.kyanos.benchmarks.KyanosMapQueryList.java

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

    Option inputOpt = OptionBuilder.create(IN);
    inputOpt.setArgName("INPUT");
    inputOpt.setDescription("Input Kyanos resource directory");
    inputOpt.setArgs(1);//  w  ww .  j av a 2  s  .c om
    inputOpt.setRequired(true);

    Option inClassOpt = OptionBuilder.create(EPACKAGE_CLASS);
    inClassOpt.setArgName("CLASS");
    inClassOpt.setDescription("FQN of EPackage implementation class");
    inClassOpt.setArgs(1);
    inClassOpt.setRequired(true);

    options.addOption(inputOpt);
    options.addOption(inClassOpt);

    CommandLineParser parser = new PosixParser();

    try {
        PersistenceBackendFactoryRegistry.getFactories().put(NeoMapURI.NEO_MAP_SCHEME,
                new MapPersistenceBackendFactory());

        CommandLine commandLine = parser.parse(options, args);

        URI uri = NeoMapURI.createNeoMapURI(new File(commandLine.getOptionValue(IN)));

        Class<?> inClazz = KyanosMapQueryList.class.getClassLoader()
                .loadClass(commandLine.getOptionValue(EPACKAGE_CLASS));
        inClazz.getMethod("init").invoke(null);

        ResourceSet resourceSet = new ResourceSetImpl();
        resourceSet.getResourceFactoryRegistry().getProtocolToFactoryMap().put(NeoMapURI.NEO_MAP_SCHEME,
                PersistentResourceFactory.eINSTANCE);

        Resource resource = resourceSet.createResource(uri);

        Map<String, Object> loadOpts = new HashMap<String, Object>();
        resource.load(loadOpts);
        {
            LOG.log(Level.INFO, "Start query");
            long begin = System.currentTimeMillis();
            EList<MethodDeclaration> list = JavaQueries.getUnusedMethodsList(resource);
            long end = System.currentTimeMillis();
            LOG.log(Level.INFO, "End query");
            LOG.log(Level.INFO, MessageFormat.format("Query result (list) contains {0} elements", list.size()));
            LOG.log(Level.INFO, MessageFormat.format("Time spent: {0}", MessageUtil.formatMillis(end - begin)));
        }

        if (resource instanceof PersistentResourceImpl) {
            PersistentResourceImpl.shutdownWithoutUnload((PersistentResourceImpl) resource);
        } else {
            resource.unload();
        }

    } catch (ParseException e) {
        MessageUtil.showError(e.toString());
        MessageUtil.showError("Current arguments: " + Arrays.toString(args));
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("java -jar <this-file.jar>", options, true);
    } catch (Throwable e) {
        MessageUtil.showError(e.toString());
    }
}

From source file:gr.forth.ics.isl.preprocessfilter1.controller.Controller.java

public static void main(String[] args) throws XPathExpressionException, ParserConfigurationException,
        SAXException, IOException, PreprocessFilterException, org.apache.commons.cli.ParseException {
    PropertyReader prop = new PropertyReader();

    //The following block of code is executed if there are arguments from the command line
    if (args.length > 0) {

        try {//from w ww .  j ava 2s .co m

            //The values of the arguments are handled as Option instances
            Options options = new Options();
            CommandLineParser PARSER = new PosixParser();

            Option inputFile = new Option("inputFile", true, "input xml file");
            Option outputFile = new Option("outputFile", true, "output xml file");
            Option parentNode = new Option("parentNode", true, "output xml file");
            Option delimeter = new Option("delimeter", true, "output xml file");
            Option newParentNode = new Option("newParentNode", true, "output xml file");
            Option intermediateNodes = new Option("intermediateNodes", true, "output xml file");
            Option intermediateNode = new Option("intermediateNode", true, "output xml file");

            options.addOption(inputFile).addOption(outputFile).addOption(parentNode).addOption(newParentNode)
                    .addOption(intermediateNode).addOption(intermediateNodes).addOption(delimeter);

            CommandLine cli = PARSER.parse(options, args);

            String inputFileArg = cli.getOptionValue("inputFile");
            String outputFileArg = cli.getOptionValue("outputFile");
            String parentNodeArg = cli.getOptionValue("parentNode");
            String newParentNodeArg = cli.getOptionValue("newParentNode");
            String intermediateNodeArg = cli.getOptionValue("intermediateNode");
            String intermediateNodesArg = cli.getOptionValue("intermediateNodes");
            String delimeterArg = cli.getOptionValue("delimeter");

            PreprocessFilterUtilities process = new PreprocessFilterUtilities();

            //System.out.println("INPUT:"+inputFileArg);
            //System.out.println("OUTPUT:"+outputFileArg);
            //System.out.println("PARENT NODE:"+parentNodeArg);
            //System.out.println("NEW PARENT NODE:"+newParentNodeArg);
            //System.out.println("INTERMEDIATE NODE:"+intermediateNodeArg);
            //System.out.println("INTERMEDIATE NODES:"+intermediateNodesArg);
            //System.out.println("DELIMETER:"+delimeterArg);
            //The filter's code is executed with the command line arguments as parameters
            if (process.createOutputFile(inputFileArg, outputFileArg, parentNodeArg, newParentNodeArg,
                    intermediateNodeArg, intermediateNodesArg, delimeterArg)) {
                System.out.println("Succesfull PreProcessing!!!");
            }
        } catch (PreprocessFilterException ex) {
            Logger.getLogger(Controller.class.getName()).log(Level.SEVERE, null, ex);
            throw new PreprocessFilterException("PreProcess Filter Exception:", ex);
        }

    } //If there are no command line arguments then the .config file is being used.
    else {

        try {

            String inputFilePathProp = prop.getProperty(inputFilePath);
            String outputFilePathProp = prop.getProperty(outputFilePath);
            String parentNodeProp = prop.getProperty(parentNode);
            String delimeterProp = prop.getProperty(delimeter);

            String newParentNodeProp = prop.getProperty(newParentNode);
            String intermediateNodesProp = prop.getProperty(intermediateNodes);
            String intermediateNodeProp = prop.getProperty(intermediateNode);

            PreprocessFilterUtilities process = new PreprocessFilterUtilities();

            //The filter's code is executed with the .config file's resources as parameters
            if (process.createOutputFile(inputFilePathProp, outputFilePathProp, parentNodeProp,
                    newParentNodeProp, intermediateNodeProp, intermediateNodesProp, delimeterProp)) {
                System.out.println("Succesfull PreProcessing!!!");
            }
        } catch (PreprocessFilterException ex) {
            Logger.getLogger(Controller.class.getName()).log(Level.SEVERE, null, ex);
            throw new PreprocessFilterException("PreProcess Filter Exception:", ex);
        }

    }
}

From source file:fr.inria.atlanmod.kyanos.benchmarks.KyanosMapQueryLoop.java

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

    Option inputOpt = OptionBuilder.create(IN);
    inputOpt.setArgName("INPUT");
    inputOpt.setDescription("Input Kyanos resource directory");
    inputOpt.setArgs(1);/*from   ww w . j  a  va  2 s.com*/
    inputOpt.setRequired(true);

    Option inClassOpt = OptionBuilder.create(EPACKAGE_CLASS);
    inClassOpt.setArgName("CLASS");
    inClassOpt.setDescription("FQN of EPackage implementation class");
    inClassOpt.setArgs(1);
    inClassOpt.setRequired(true);

    options.addOption(inputOpt);
    options.addOption(inClassOpt);

    CommandLineParser parser = new PosixParser();

    try {
        PersistenceBackendFactoryRegistry.getFactories().put(NeoMapURI.NEO_MAP_SCHEME,
                new MapPersistenceBackendFactory());

        CommandLine commandLine = parser.parse(options, args);

        URI uri = NeoMapURI.createNeoMapURI(new File(commandLine.getOptionValue(IN)));

        Class<?> inClazz = KyanosMapQueryLoop.class.getClassLoader()
                .loadClass(commandLine.getOptionValue(EPACKAGE_CLASS));
        inClazz.getMethod("init").invoke(null);

        ResourceSet resourceSet = new ResourceSetImpl();
        resourceSet.getResourceFactoryRegistry().getProtocolToFactoryMap().put(NeoMapURI.NEO_MAP_SCHEME,
                PersistentResourceFactory.eINSTANCE);

        Resource resource = resourceSet.createResource(uri);

        Map<String, Object> loadOpts = new HashMap<String, Object>();
        resource.load(loadOpts);

        {
            LOG.log(Level.INFO, "Start query");
            long begin = System.currentTimeMillis();
            EList<MethodDeclaration> list = JavaQueries.getUnusedMethodsLoop(resource);
            long end = System.currentTimeMillis();
            LOG.log(Level.INFO, "End query");
            LOG.log(Level.INFO,
                    MessageFormat.format("Query result (loops) contains {0} elements", list.size()));
            LOG.log(Level.INFO, MessageFormat.format("Time spent: {0}", MessageUtil.formatMillis(end - begin)));
        }

        if (resource instanceof PersistentResourceImpl) {
            PersistentResourceImpl.shutdownWithoutUnload((PersistentResourceImpl) resource);
        } else {
            resource.unload();
        }

    } catch (ParseException e) {
        MessageUtil.showError(e.toString());
        MessageUtil.showError("Current arguments: " + Arrays.toString(args));
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("java -jar <this-file.jar>", options, true);
    } catch (Throwable e) {
        MessageUtil.showError(e.toString());
    }
}

From source file:fr.inria.atlanmod.kyanos.benchmarks.KyanosMapQueryGrabats.java

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

    Option inputOpt = OptionBuilder.create(IN);
    inputOpt.setArgName("INPUT");
    inputOpt.setDescription("Input Kyanos resource directory");
    inputOpt.setArgs(1);/*w  ww.  ja v  a 2  s  .  c  o  m*/
    inputOpt.setRequired(true);

    Option inClassOpt = OptionBuilder.create(EPACKAGE_CLASS);
    inClassOpt.setArgName("CLASS");
    inClassOpt.setDescription("FQN of EPackage implementation class");
    inClassOpt.setArgs(1);
    inClassOpt.setRequired(true);

    options.addOption(inputOpt);
    options.addOption(inClassOpt);

    CommandLineParser parser = new PosixParser();

    try {
        PersistenceBackendFactoryRegistry.getFactories().put(NeoMapURI.NEO_MAP_SCHEME,
                new MapPersistenceBackendFactory());

        CommandLine commandLine = parser.parse(options, args);

        URI uri = NeoMapURI.createNeoMapURI(new File(commandLine.getOptionValue(IN)));

        Class<?> inClazz = KyanosMapQueryGrabats.class.getClassLoader()
                .loadClass(commandLine.getOptionValue(EPACKAGE_CLASS));
        inClazz.getMethod("init").invoke(null);

        ResourceSet resourceSet = new ResourceSetImpl();
        resourceSet.getResourceFactoryRegistry().getProtocolToFactoryMap().put(NeoMapURI.NEO_MAP_SCHEME,
                PersistentResourceFactory.eINSTANCE);

        Resource resource = resourceSet.createResource(uri);

        Map<String, Object> loadOpts = new HashMap<String, Object>();
        resource.load(loadOpts);
        {
            LOG.log(Level.INFO, "Start query");
            long begin = System.currentTimeMillis();
            EList<ClassDeclaration> list = JavaQueries.grabats09(resource);
            long end = System.currentTimeMillis();
            LOG.log(Level.INFO, "End query");
            LOG.log(Level.INFO, MessageFormat.format("Query result contains {0} elements", list.size()));
            LOG.log(Level.INFO, MessageFormat.format("Time spent: {0}", MessageUtil.formatMillis(end - begin)));
        }

        if (resource instanceof PersistentResourceImpl) {
            PersistentResourceImpl.shutdownWithoutUnload((PersistentResourceImpl) resource);
        } else {
            resource.unload();
        }

    } catch (ParseException e) {
        MessageUtil.showError(e.toString());
        MessageUtil.showError("Current arguments: " + Arrays.toString(args));
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("java -jar <this-file.jar>", options, true);
    } catch (Throwable e) {
        MessageUtil.showError(e.toString());
    }
}

From source file:com.zarkonnen.longan.Main.java

public static void main(String[] args) throws IOException {
    // Use Apache Commons CLI (packaged into the Jar) to parse command line options.
    Options options = new Options();
    Option helpO = OptionBuilder.withDescription("print help").create("h");
    Option versionO = OptionBuilder.withDescription("print version").create("v");
    Option outputO = OptionBuilder.withDescription("output file").withLongOpt("out").hasArg()
            .withArgName("file").create("o");
    Option formatO = OptionBuilder
            .withDescription("output format: one of plaintext (default) and visualize (debug output in png)")
            .hasArg().withArgName("format").withLongOpt("format").create();
    Option serverO = OptionBuilder.withDescription("launches server mode: Server mode reads "
            + "command line strings one per line exactly as above. If no output file is "
            + "specified, returns a line containing the number of output lines before the "
            + "output. If there is an error, returns a single line with the error message. "
            + "Shut down server by sending \"quit\".").withLongOpt("server").create();
    Option openCLO = OptionBuilder
            .withDescription(/* w  ww. j a v  a  2  s.  co  m*/
                    "enables use of the graphics card to " + "support the OCR system. Defaults to true.")
            .withLongOpt("enable-opencl").hasArg().withArgName("enabled").create();
    options.addOption(helpO);
    options.addOption(versionO);
    options.addOption(outputO);
    options.addOption(formatO);
    options.addOption(serverO);
    options.addOption(openCLO);
    CommandLineParser clp = new GnuParser();
    try {
        CommandLine line = clp.parse(options, args);
        if (line.hasOption("h")) {
            new HelpFormatter().printHelp(INVOCATION, options);
            System.exit(0);
        }
        if (line.hasOption("v")) {
            System.out.println(Longan.VERSION);
            System.exit(0);
        }
        boolean enableOpenCL = true;
        if (line.hasOption("enable-opencl")) {
            enableOpenCL = line.getOptionValue("enable-opencl").toLowerCase().equals("true")
                    || line.getOptionValue("enable-opencl").equals("1");
        }
        if (line.hasOption("server")) {
            Longan longan = Longan.getDefaultImplementation(enableOpenCL);
            BufferedReader inputR = new BufferedReader(new InputStreamReader(System.in));
            while (true) {
                String input = inputR.readLine();
                if (input.trim().equals("quit")) {
                    return;
                }
                String[] args2 = splitInput(input);
                Options o2 = new Options();
                o2.addOption(outputO);
                o2.addOption(formatO);
                try {
                    line = clp.parse(o2, args2);

                    File outFile = null;
                    if (line.hasOption("o")) {
                        outFile = new File(line.getOptionValue("o"));
                    }

                    ResultConverter format = FORMATS.get(line.getOptionValue("format", "plaintext"));
                    if (format != DEFAULT_FORMAT && outFile == null) {
                        System.out.println("You must specify an output file for non-plaintext output.");
                        continue;
                    }

                    if (line.getArgList().isEmpty()) {
                        System.out.println("Please specify an input image.");
                        continue;
                    }
                    if (line.getArgList().size() > 1) {
                        System.err.println("Please specify one input image at a time");
                        continue;
                    }

                    File inFile = new File((String) line.getArgList().get(0));

                    if (!inFile.exists()) {
                        System.out.println("The input image does not exist.");
                        continue;
                    }

                    try {
                        Result result = longan.process(ImageIO.read(inFile));
                        if (outFile == null) {
                            String txt = DEFAULT_FORMAT.convert(result);
                            System.out.println(numNewlines(txt) + 1);
                            System.out.print(txt);
                        } else {
                            if (outFile.getAbsoluteFile().getParentFile() != null
                                    && !outFile.getAbsoluteFile().getParentFile().exists()) {
                                outFile.getParentFile().mkdirs();
                            }
                            FileOutputStream fos = new FileOutputStream(outFile);
                            try {
                                format.write(result, fos);
                            } finally {
                                fos.close();
                            }
                        }
                    } catch (Exception e) {
                        System.out.println("Processing error: " + exception(e));
                    }
                } catch (ParseException e) {
                    System.out.println("Input not recognized: " + exception(e));
                }
            } // End server loop
        } else {
            // Single invocation
            File outFile = null;
            if (line.hasOption("o")) {
                outFile = new File(line.getOptionValue("o"));
            }

            ResultConverter format = FORMATS.get(line.getOptionValue("format", "plaintext"));
            if (format != DEFAULT_FORMAT && outFile == null) {
                System.err.println("You must specify an output file for non-plaintext output.");
                System.exit(1);
            }

            if (line.getArgList().isEmpty()) {
                System.err.println("Please specify an input image.");
                new HelpFormatter().printHelp(INVOCATION, options);
                System.exit(1);
            }
            if (line.getArgList().size() > 1) {
                System.err.println("Please specify one input image only. To process multiple "
                        + "images, use server mode.");
                System.exit(1);
            }
            File inFile = new File((String) line.getArgList().get(0));

            if (!inFile.exists()) {
                System.err.println("The input image does not exist.");
                System.exit(1);
            }

            try {
                Result result = Longan.getDefaultImplementation(enableOpenCL).process(ImageIO.read(inFile));
                if (outFile == null) {
                    String txt = DEFAULT_FORMAT.convert(result);
                    System.out.print(txt);
                } else {
                    if (outFile.getAbsoluteFile().getParentFile() != null
                            && !outFile.getAbsoluteFile().getParentFile().exists()) {
                        outFile.getParentFile().mkdirs();
                    }
                    FileOutputStream fos = new FileOutputStream(outFile);
                    try {
                        format.write(format.convert(result), fos);
                    } finally {
                        fos.close();
                    }
                }
            } catch (Exception e) {
                System.err.println("Processing error: " + exception(e));
                System.exit(1);
            }
        }
    } catch (ParseException e) {
        System.err.println("Parsing command line input failed: " + exception(e));
        System.exit(1);
    }
}

From source file:boa.evaluator.BoaEvaluator.java

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

    options.addOption("i", "input", true, "input Boa source file (*.boa)");
    options.addOption("d", "data", true, "path to local data directory");
    options.addOption("o", "output", true, "output directory");

    options.getOption("i").setRequired(true);
    options.getOption("d").setRequired(true);

    try {//from   w  w  w .ja  v  a2s.co m
        if (args.length == 0) {
            printHelp(options, null);
            return;
        } else {
            final CommandLine cl = new PosixParser().parse(options, args);

            if (cl.hasOption('i') && cl.hasOption('d')) {
                final BoaEvaluator evaluator;
                try {
                    if (cl.hasOption('o')) {
                        evaluator = new BoaEvaluator(cl.getOptionValue('i'), cl.getOptionValue('d'),
                                cl.getOptionValue('o'));
                    } else {
                        evaluator = new BoaEvaluator(cl.getOptionValue('i'), cl.getOptionValue('d'));
                    }
                } catch (final IOException e) {
                    System.err.print(e);
                    return;
                }

                if (!evaluator.compile()) {
                    System.err.println("Compilation Failed");
                    return;
                }

                final long start = System.currentTimeMillis();
                evaluator.evaluate();
                final long end = System.currentTimeMillis();

                System.out.println("Total Time Taken: " + (end - start));
                System.out.println(evaluator.getResults());
            } else {
                printHelp(options, "missing required options: -i <arg> and -d <arg>");
                return;
            }
        }
    } catch (final org.apache.commons.cli.ParseException e) {
        printHelp(options, e.getMessage());
    }
}

From source file:com.github.houbin217jz.thumbnail.Thumbnail.java

public static void main(String[] args) {

    Options options = new Options();
    options.addOption("s", "src", true,
            "????????????");
    options.addOption("d", "dst", true, "");
    options.addOption("r", "ratio", true, "/??, 30%???0.3????????");
    options.addOption("w", "width", true, "(px)");
    options.addOption("h", "height", true, "?(px)");
    options.addOption("R", "recursive", false, "???????");

    HelpFormatter formatter = new HelpFormatter();
    String formatstr = "java -jar thumbnail.jar " + "[-s/--src <path>] " + "[-d/--dst <path>] "
            + "[-r/--ratio double] " + "[-w/--width integer] " + "[-h/--height integer] " + "[-R/--recursive] ";

    CommandLineParser parser = new PosixParser();
    CommandLine cmd = null;/*  ww w. j  a  v a  2s .  c o m*/
    try {
        cmd = parser.parse(options, args);
    } catch (ParseException e1) {
        formatter.printHelp(formatstr, options);
        return;
    }

    final Path srcDir, dstDir;
    final Integer width, height;
    final Double ratio;

    //
    if (cmd.hasOption("s")) {
        srcDir = Paths.get(cmd.getOptionValue("s")).toAbsolutePath();
    } else {
        srcDir = Paths.get("").toAbsolutePath(); //??
    }

    //
    if (cmd.hasOption("d")) {
        dstDir = Paths.get(cmd.getOptionValue("d")).toAbsolutePath();
    } else {
        formatter.printHelp(formatstr, options);
        return;
    }

    if (!Files.exists(srcDir, LinkOption.NOFOLLOW_LINKS)
            || !Files.isDirectory(srcDir, LinkOption.NOFOLLOW_LINKS)) {
        System.out.println("[" + srcDir.toAbsolutePath() + "]??????");
        return;
    }

    if (Files.exists(dstDir, LinkOption.NOFOLLOW_LINKS)) {
        if (!Files.isDirectory(dstDir, LinkOption.NOFOLLOW_LINKS)) {
            //????????
            System.out.println("????????");
            return;
        }
    } else {
        //????????
        try {
            Files.createDirectories(dstDir);
        } catch (IOException e) {
            e.printStackTrace();
            return;
        }
    }

    //??
    if (cmd.hasOption("w") && cmd.hasOption("h")) {
        try {
            width = Integer.valueOf(cmd.getOptionValue("width"));
            height = Integer.valueOf(cmd.getOptionValue("height"));
        } catch (NumberFormatException e) {
            System.out.println("??????");
            return;
        }
    } else {
        width = null;
        height = null;
    }

    //?
    if (cmd.hasOption("r")) {
        try {
            ratio = Double.valueOf(cmd.getOptionValue("r"));
        } catch (NumberFormatException e) {
            System.out.println("?????");
            return;
        }
    } else {
        ratio = null;
    }

    if (width != null && ratio != null) {
        System.out.println("??????????????");
        return;
    }

    if (width == null && ratio == null) {
        System.out.println("????????????");
        return;
    }

    //
    int maxDepth = 1;
    if (cmd.hasOption("R")) {
        maxDepth = Integer.MAX_VALUE;
    }

    try {
        //Java 7 ??@see http://docs.oracle.com/javase/jp/7/api/java/nio/file/Files.html
        Files.walkFileTree(srcDir, EnumSet.of(FileVisitOption.FOLLOW_LINKS), maxDepth,
                new SimpleFileVisitor<Path>() {
                    @Override
                    public FileVisitResult visitFile(Path path, BasicFileAttributes basicFileAttributes)
                            throws IOException {

                        //???&???
                        String filename = path.getFileName().toString().toLowerCase();

                        if (filename.endsWith(".jpg") || filename.endsWith(".jpeg")) {
                            //Jpeg??

                            /*
                             * relative??:
                             * rootPath: /a/b/c/d
                             * filePath: /a/b/c/d/e/f.jpg
                             * rootPath.relativize(filePath) = e/f.jpg
                             */

                            /*
                             * resolve??
                             * rootPath: /a/b/c/output
                             * relativePath: e/f.jpg
                             * rootPath.resolve(relativePath) = /a/b/c/output/e/f.jpg
                             */

                            Path dst = dstDir.resolve(srcDir.relativize(path));

                            if (!Files.exists(dst.getParent(), LinkOption.NOFOLLOW_LINKS)) {
                                Files.createDirectories(dst.getParent());
                            }
                            doResize(path.toFile(), dst.toFile(), width, height, ratio);
                        }
                        return FileVisitResult.CONTINUE;
                    }
                });
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:fr.inria.atlanmod.kyanos.benchmarks.KyanosMapQuery.java

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

    Option inputOpt = OptionBuilder.create(IN);
    inputOpt.setArgName("INPUT");
    inputOpt.setDescription("Input Kyanos resource directory");
    inputOpt.setArgs(1);//from   w ww.j a v  a2 s  .  c om
    inputOpt.setRequired(true);

    Option inClassOpt = OptionBuilder.create(EPACKAGE_CLASS);
    inClassOpt.setArgName("CLASS");
    inClassOpt.setDescription("FQN of EPackage implementation class");
    inClassOpt.setArgs(1);
    inClassOpt.setRequired(true);

    options.addOption(inputOpt);
    options.addOption(inClassOpt);

    CommandLineParser parser = new PosixParser();

    try {
        PersistenceBackendFactoryRegistry.getFactories().put(NeoMapURI.NEO_MAP_SCHEME,
                new MapPersistenceBackendFactory());

        CommandLine commandLine = parser.parse(options, args);

        URI uri = NeoMapURI.createNeoMapURI(new File(commandLine.getOptionValue(IN)));

        Class<?> inClazz = KyanosMapQuery.class.getClassLoader()
                .loadClass(commandLine.getOptionValue(EPACKAGE_CLASS));
        inClazz.getMethod("init").invoke(null);

        ResourceSet resourceSet = new ResourceSetImpl();
        resourceSet.getResourceFactoryRegistry().getProtocolToFactoryMap().put(NeoMapURI.NEO_MAP_SCHEME,
                PersistentResourceFactory.eINSTANCE);

        Resource resource = resourceSet.createResource(uri);

        Map<String, Object> loadOpts = new HashMap<String, Object>();
        resource.load(loadOpts);
        {
            LOG.log(Level.INFO, "Start query");
            long begin = System.currentTimeMillis();
            EList<MethodDeclaration> list = JavaQueries.getUnusedMethodsList(resource);
            long end = System.currentTimeMillis();
            LOG.log(Level.INFO, "End query");
            LOG.log(Level.INFO, MessageFormat.format("Query result (list) contains {0} elements", list.size()));
            LOG.log(Level.INFO, MessageFormat.format("Time spent: {0}", MessageUtil.formatMillis(end - begin)));
        }

        {
            LOG.log(Level.INFO, "Start query");
            long begin = System.currentTimeMillis();
            EList<MethodDeclaration> list = JavaQueries.getUnusedMethodsLoop(resource);
            long end = System.currentTimeMillis();
            LOG.log(Level.INFO, "End query");
            LOG.log(Level.INFO,
                    MessageFormat.format("Query result (loops) contains {0} elements", list.size()));
            LOG.log(Level.INFO, MessageFormat.format("Time spent: {0}", MessageUtil.formatMillis(end - begin)));
        }

        if (resource instanceof PersistentResourceImpl) {
            PersistentResourceImpl.shutdownWithoutUnload((PersistentResourceImpl) resource);
        } else {
            resource.unload();
        }

    } catch (ParseException e) {
        MessageUtil.showError(e.toString());
        MessageUtil.showError("Current arguments: " + Arrays.toString(args));
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("java -jar <this-file.jar>", options, true);
    } catch (Throwable e) {
        MessageUtil.showError(e.toString());
    }
}

From source file:cc.twittertools.search.api.SearchStatusesThrift.java

@SuppressWarnings("static-access")
public static void main(String[] args) throws Exception {
    Options options = new Options();

    options.addOption(new Option(HELP_OPTION, "show help"));
    options.addOption(OptionBuilder.withArgName("string").hasArg().withDescription("host").create(HOST_OPTION));
    options.addOption(OptionBuilder.withArgName("port").hasArg().withDescription("port").create(PORT_OPTION));
    options.addOption(/*from   www  .j  ava 2  s.c  o  m*/
            OptionBuilder.withArgName("string").hasArg().withDescription("query id").create(QID_OPTION));
    options.addOption(
            OptionBuilder.withArgName("string").hasArg().withDescription("query text").create(QUERY_OPTION));
    options.addOption(
            OptionBuilder.withArgName("string").hasArg().withDescription("runtag").create(RUNTAG_OPTION));
    options.addOption(OptionBuilder.withArgName("num").hasArg().withDescription("maxid").create(MAX_ID_OPTION));
    options.addOption(OptionBuilder.withArgName("num").hasArg().withDescription("number of results to return")
            .create(NUM_RESULTS_OPTION));
    options.addOption(
            OptionBuilder.withArgName("string").hasArg().withDescription("group id").create(GROUP_OPTION));
    options.addOption(
            OptionBuilder.withArgName("string").hasArg().withDescription("access token").create(TOKEN_OPTION));
    options.addOption(new Option(VERBOSE_OPTION, "print out complete document"));

    CommandLine cmdline = null;
    CommandLineParser parser = new GnuParser();
    try {
        cmdline = parser.parse(options, args);
    } catch (ParseException exp) {
        System.err.println("Error parsing command line: " + exp.getMessage());
        System.exit(-1);
    }

    if (cmdline.hasOption(HELP_OPTION) || !cmdline.hasOption(HOST_OPTION) || !cmdline.hasOption(PORT_OPTION)) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp(SearchStatusesThrift.class.getName(), options);
        System.exit(-1);
    }

    String qid = cmdline.hasOption(QID_OPTION) ? cmdline.getOptionValue(QID_OPTION) : DEFAULT_QID;
    String query = cmdline.hasOption(QUERY_OPTION) ? cmdline.getOptionValue(QUERY_OPTION) : DEFAULT_Q;
    String runtag = cmdline.hasOption(RUNTAG_OPTION) ? cmdline.getOptionValue(RUNTAG_OPTION) : DEFAULT_RUNTAG;
    long maxId = cmdline.hasOption(MAX_ID_OPTION) ? Long.parseLong(cmdline.getOptionValue(MAX_ID_OPTION))
            : DEFAULT_MAX_ID;
    int numResults = cmdline.hasOption(NUM_RESULTS_OPTION)
            ? Integer.parseInt(cmdline.getOptionValue(NUM_RESULTS_OPTION))
            : DEFAULT_NUM_RESULTS;
    boolean verbose = cmdline.hasOption(VERBOSE_OPTION);

    String group = cmdline.hasOption(GROUP_OPTION) ? cmdline.getOptionValue(GROUP_OPTION) : null;
    String token = cmdline.hasOption(TOKEN_OPTION) ? cmdline.getOptionValue(TOKEN_OPTION) : null;
    TrecSearchThriftClient client = new TrecSearchThriftClient(cmdline.getOptionValue(HOST_OPTION),
            Integer.parseInt(cmdline.getOptionValue(PORT_OPTION)), group, token);

    System.err.println("qid: " + qid);
    System.err.println("q: " + query);
    System.err.println("max_id: " + maxId);
    System.err.println("num_results: " + numResults);

    PrintStream out = new PrintStream(System.out, true, "UTF-8");

    List<TResult> results = client.search(query, maxId, numResults);
    int i = 1;
    for (TResult result : results) {
        out.println(String.format("%s Q0 %d %d %f %s", qid, result.id, i, result.rsv, runtag));
        if (verbose) {
            System.out.println("# " + result.toString().replaceAll("[\\n\\r]+", " "));
        }
        i++;
    }
    out.close();
}