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

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

Introduction

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

Prototype

BasicParser

Source Link

Usage

From source file:com.genentech.retrival.tabExport.TABExporter.java

public static void main(String[] args) throws ParseException, JDOMException, IOException {
    long start = System.currentTimeMillis();
    int nStruct = 0;

    // create command line Options object
    Options options = new Options();
    Option opt = new Option("sqlFile", true, "sql-xml file");
    opt.setRequired(true);//www.  j a  va2s.com
    options.addOption(opt);

    opt = new Option("sqlName", true, "name of SQL element in xml file");
    opt.setRequired(true);
    options.addOption(opt);

    opt = new Option("o", true, "output file");
    opt.setRequired(false);
    options.addOption(opt);

    opt = new Option("newLineReplacement", true,
            "If given newlines in fields will be replaced by this string.");
    options.addOption(opt);

    opt = new Option("noHeader", false, "Do not output header line");
    options.addOption(opt);

    CommandLineParser parser = new BasicParser();
    CommandLine cmd = null;
    try {
        cmd = parser.parse(options, args);
    } catch (Exception e) {
        System.err.println(e.getMessage());
        exitWithHelp(options);
    }
    args = cmd.getArgs();

    String outFile = cmd.getOptionValue("o");
    String sqlFile = cmd.getOptionValue("sqlFile");
    String sqlName = cmd.getOptionValue("sqlName");
    String newLineReplacement = cmd.getOptionValue("newLineReplacement");

    args = cmd.getArgs();

    try {
        PrintStream out = System.out;
        if (outFile != null)
            out = new PrintStream(outFile);

        SQLStatement stmt = SQLStatement.createFromFile(new File(sqlFile), sqlName);
        Object[] sqlArgs = args;
        if (stmt.getParamTypes().length != args.length) {
            System.err.printf(
                    "\nWarining sql statement needs %d parameters but got only %d. Filling up with NULLs.\n",
                    stmt.getParamTypes().length, args.length);
            sqlArgs = new Object[stmt.getParamTypes().length];
            System.arraycopy(args, 0, sqlArgs, 0, args.length);
        }

        Selecter sel = Selecter.factory(stmt);
        if (!sel.select(sqlArgs)) {
            System.err.println("No rows returned!");
            System.exit(0);
        }

        String[] fieldNames = sel.getFieldNames();
        if (fieldNames.length == 0) {
            System.err.println("Query did not return any columns");
            exitWithHelp(options);
        }

        if (!cmd.hasOption("noHeader")) {
            StringBuilder sb = new StringBuilder(200);
            for (String f : fieldNames)
                sb.append(f).append('\t');
            if (sb.length() > 1)
                sb.setLength(sb.length() - 1); // chop last \t
            String header = sb.toString();

            out.println(header);
        }

        StringBuilder sb = new StringBuilder(200);
        while (sel.hasNext()) {
            Record sqlRec = sel.next();
            sb.setLength(0);

            for (int i = 0; i < fieldNames.length; i++) {
                String fld = sqlRec.getStrg(i);
                if (newLineReplacement != null)
                    fld = NEWLinePattern.matcher(fld).replaceAll(newLineReplacement);

                sb.append(fld).append('\t');
            }

            if (sb.length() > 1)
                sb.setLength(sb.length() - 1); // chop last \t
            String row = sb.toString();

            out.println(row);

            nStruct++;
        }

    } catch (Exception e) {
        throw new Error(e);
    } finally {
        System.err.printf("TABExporter: Exported %d records in %dsec\n", nStruct,
                (System.currentTimeMillis() - start) / 1000);
    }
}

From source file:io.github.azige.whitespace.Cli.java

public static void main(String[] args) {
    Options options = new Options().addOption("h", "help", false, "??")
            .addOptionGroup(new OptionGroup()
                    .addOption(new Option("p",
                            "????????"))
                    .addOption(new Option("c", "?????")))
            .addOption(null, "szm", false,
                    "????")
            .addOption("e", "encoding", true, "??" + DEFAULT_ENCODING);

    try {/* w  w  w  .j  a  va2  s.  c o  m*/
        CommandLineParser parser = new BasicParser();
        CommandLine cl = parser.parse(options, args);

        if (cl.hasOption('h')) {
            printHelp(System.out, options);
            return;
        }

        if (cl.hasOption('e')) {
            encoding = Charset.forName(cl.getOptionValue('e'));
        } else {
            encoding = Charset.forName(DEFAULT_ENCODING);
        }

        if (cl.hasOption("szm")) {
            useSzm = true;
        }

        String[] fileArgs = cl.getArgs();
        if (fileArgs.length != 1) {
            printHelp(System.err, options);
            return;
        }

        try (InputStream input = Files.newInputStream(Paths.get(fileArgs[0]))) {
            if (cl.hasOption('p')) {
                printPseudoCode(input);
            } else if (cl.hasOption('c')) {
                compile(input, fileArgs[0]);
            } else {
                execute(input, fileArgs[0]);
            }
        }
    } catch (ParseException ex) {
        ex.printStackTrace();
        printHelp(System.err, options);
    } catch (Exception ex) {
        ex.printStackTrace();
    }
}

From source file:FULRequestor.java

public static void main(String[] args) throws Exception {
    String hostId = "";
    String partnerId = "";
    String userId = "";

    CommandLineParser parser = new BasicParser();
    Options options = new Options();
    options.addOption("h", "host", true, "EBICS Host ID");
    options.addOption("p", "partner", true, "Registred Partner ID for you user");
    options.addOption("u", "user", true, "User ID to initiate");

    // Parse the program arguments
    CommandLine commandLine = parser.parse(options, args);

    if (!commandLine.hasOption('h')) {
        System.out.println("Host-ID is mandatory");
        System.exit(0);//from w ww  .  j av a2 s.  com
    } else {
        hostId = commandLine.getOptionValue('h');
        System.out.println("host: " + hostId);
    }

    if (!commandLine.hasOption('p')) {
        System.out.println("Partner-ID is mandatory");
        System.exit(0);
    } else {
        partnerId = commandLine.getOptionValue('p');
        System.out.println("partnerId: " + partnerId);
    }

    if (!commandLine.hasOption('u')) {
        System.out.println("User-ID is mandatory");
        System.exit(0);
    } else {
        userId = commandLine.getOptionValue('u');
        System.out.println("userId: " + userId);
    }

    FULRequestor hbbRequestor;
    PasswordCallback pwdHandler;
    Product product;
    String filePath;

    hbbRequestor = new FULRequestor();
    product = new Product("kopiLeft Dev 1.0", Locale.FRANCE, null);
    pwdHandler = new UserPasswordHandler(userId, "2012");

    // Load alredy created user
    hbbRequestor.loadUser(hostId, partnerId, userId, pwdHandler);

    filePath = System.getProperty("user.home") + File.separator + "test.txt";
    // Send FUL Requets
    hbbRequestor.sendFile(filePath, userId, product);
}

From source file:diffhunter.DiffHunter.java

/**
 * @param args the command line arguments
 * @throws org.apache.commons.cli.ParseException
 * @throws java.io.IOException//w  ww  .j av a2 s . c om
 */
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:edu.cuhk.hccl.cmd.AppSearchEngine.java

public static void main(String[] args) throws IOException {

    // Get parameters
    CommandLineParser parser = new BasicParser();
    Options options = createOptions();/*w  ww .  j  ava  2 s.  c  om*/

    File dataFolder = null;
    String queryStr = null;
    int topK = 0;
    File resultFile = null;
    String queryType = null;
    File similarityFile = null;

    try {
        CommandLine line = parser.parse(options, args);

        dataFolder = new File(line.getOptionValue('d'));
        queryStr = line.getOptionValue('q');
        queryType = line.getOptionValue('t');

        topK = Integer.parseInt(line.getOptionValue('k'));
        resultFile = new File(line.getOptionValue('f'));
        similarityFile = new File(line.getOptionValue('s'));

        if (line.hasOption('m')) {
            String modelPath = line.getOptionValue('m');

            if (queryType.equalsIgnoreCase("WordVector")) {
                expander = new WordVectorExpander(modelPath);
            } else if (queryType.equalsIgnoreCase("WordNet")) {
                expander = new WordNetExpander(modelPath);
            } else {
                System.out.println("Please choose a correct expander: WordNet or WordVector!");
                System.exit(-1);
            }
        }

    } catch (ParseException exp) {
        System.out.println("Error in parameters: \n" + exp.getMessage());
        System.exit(-1);
    }

    // Create Index
    StandardAnalyzer analyzer = new StandardAnalyzer();
    Directory index = createIndex(dataFolder, analyzer);

    // Build query
    Query query = buildQuery(analyzer, queryStr, queryType);

    // Search index for topK hits
    IndexReader reader = DirectoryReader.open(index);
    IndexSearcher searcher = new IndexSearcher(reader);
    TopScoreDocCollector collector = TopScoreDocCollector.create(topK, true);
    searcher.search(query, collector);
    ScoreDoc[] hits = collector.topDocs().scoreDocs;

    // Show search results
    System.out.println("\n[INFO] " + hits.length + " hits were returned:");
    List<String> hitLines = new ArrayList<String>();

    for (int i = 0; i < hits.length; i++) {
        int docId = hits[i].doc;
        Document d = searcher.doc(docId);

        String line = (i + 1) + "\t" + d.get(PATH_FIELD) + "\t" + hits[i].score;

        System.out.println(line);

        hitLines.add(line);
    }

    // Compute cosine similarity between documents
    List<String> simLines = new ArrayList<String>();
    for (int m = 0; m < hits.length; m++) {
        int doc1 = hits[m].doc;
        Terms terms1 = reader.getTermVector(doc1, CONTENT_FIELD);

        for (int n = m + 1; n < hits.length; n++) {
            int doc2 = hits[n].doc;
            Terms terms2 = reader.getTermVector(doc2, CONTENT_FIELD);

            CosineDocumentSimilarity cosine = new CosineDocumentSimilarity(terms1, terms2);
            double similarity = cosine.getCosineSimilarity();
            String line = searcher.doc(doc1).get(PATH_FIELD) + "\t" + searcher.doc(doc2).get(PATH_FIELD) + "\t"
                    + similarity;
            simLines.add(line);
        }
    }

    // Release resources
    reader.close();
    if (expander != null) {
        expander.close();
    }

    // Save search results
    System.out.println("\n[INFO] Search results are saved in file: " + resultFile.getPath());
    FileUtils.writeLines(resultFile, hitLines, false);

    System.out.println("\n[INFO] Cosine similarities are saved in file: " + similarityFile.getPath());
    FileUtils.writeLines(similarityFile, simLines, false);
}

From source file:com.ibm.soatf.SOATestingFramework.java

/**
 * SOA Testing Framework main static method.
 *
 * @param args Main input parameters./*from ww w.  j  a v  a 2 s  .  c  o  m*/
 */
public static void main(String[] args) {
    Options options = new Options();
    options.addOption(new Option("gui", "Display a GUI"));

    options.addOption(OptionBuilder.withArgName("environment").hasArg()
            .withDescription("Environment to run the tests on").create("env")); // has a value
    options.addOption(OptionBuilder.withArgName("project").hasArg()
            .withDescription("Project to run the tests on").create("p")); // has a value
    options.addOption(OptionBuilder.withArgName("interface").hasArg()
            .withDescription("Interface to run the tests on").create("i")); // has a value
    CommandLineParser parser = new BasicParser();
    try {
        CommandLine cmd = parser.parse(options, args);
        validate(cmd);

        if (cmd.hasOption("gui")) {

            /* Set the Nimbus look and feel */
            //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
            /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
             * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
             */
            try {
                if (false) { //disabled the OS Look'n'Feel
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } else {
                    for (UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                        if ("Nimbus".equals(info.getName())) {
                            javax.swing.UIManager.setLookAndFeel(info.getClassName());
                            break;
                        }
                    }
                    UIManager.getLookAndFeelDefaults().put("nimbusOrange", (new Color(0, 128, 255)));
                }
            } catch (ClassNotFoundException | InstantiationException | IllegalAccessException
                    | javax.swing.UnsupportedLookAndFeelException ex) {
                logger.error("Cannot set look and feel", ex);
            }
            //</editor-fold>

            final SOATestingFrameworkGUI soatfgui = new SOATestingFrameworkGUI();
            java.awt.EventQueue.invokeLater(new Runnable() {

                @Override
                public void run() {
                    soatfgui.setVisible(true);
                }
            });
        } else {
            //<editor-fold defaultstate="collapsed" desc="Command line mode">
            try {
                // Initialization of configuration manager.
                ConfigurationManager.getInstance().init();

                String env = cmd.getOptionValue("env", null);
                String ifaceName;
                boolean inboundOnly = false;
                if (cmd.hasOption("p")) {
                    String projectName = cmd.getOptionValue("p");
                    MasterConfiguration masterConfig = ConfigurationManager.getInstance().getMasterConfig();
                    List<SOATestingFrameworkMasterConfiguration.Interfaces.Interface> interfaces = masterConfig
                            .getInterfaces();
                    all: for (Interface iface : interfaces) {
                        List<Project> projects = iface.getProjects().getProject();
                        for (Project project : projects) {
                            if (project.getName().equals(projectName)) {
                                inboundOnly = "INBOUND".equalsIgnoreCase(project.getDirection());
                                ifaceName = iface.getName();
                                break all;
                            }
                        }
                    }
                    throw new FrameworkExecutionException(
                            "No such project found in master configuration: " + projectName);
                } else {
                    ifaceName = cmd.getOptionValue("i");
                    inboundOnly = false;
                }
                DirectoryStructureManager.checkFrameworkDirectoryStructure(ifaceName);
                FlowExecutor flowExecutor = new FlowExecutor(inboundOnly, env, ifaceName);
                flowExecutor.execute();
            } catch (FrameworkConfigurationException ex) {
                logger.fatal("Configuration corrupted. See the exception stack trace for details.", ex);
            } catch (FrameworkException ex) {
                logger.fatal(ex);
            }
            //</editor-fold>
        }
    } catch (ParseException ex) {
        logger.fatal("Could not parse the command line arguments. Reason: " + ex);
        printUsage();
    } catch (Throwable ex) {
        logger.fatal("Unexpected error occured: ", ex);
        printUsage();
        System.exit(-1);
    }
}

From source file:com.example.geomesa.kafka08.KafkaListener.java

public static void main(String[] args) throws Exception {
    // read command line args for a connection to Kafka
    CommandLineParser parser = new BasicParser();
    Options options = getCommonRequiredOptions();
    CommandLine cmd = parser.parse(options, args);

    // create the consumer KafkaDataStore object
    Map<String, String> dsConf = getKafkaDataStoreConf(cmd);
    dsConf.put("isProducer", "false");
    DataStore consumerDS = DataStoreFinder.getDataStore(dsConf);

    // verify that we got back our KafkaDataStore object properly
    if (consumerDS == null) {
        throw new Exception("Null consumer KafkaDataStore");
    }/*  ww w.j a  v a2 s.  c  om*/

    // create the schema which creates a topic in Kafka
    // (only needs to be done once)
    // TODO: This should be rolled into the Command line options to make this more general.
    registerListeners(consumerDS);

    while (true) {
        // Wait for user to terminate with ctrl-C.
    }
}

From source file:com.versusoft.packages.jodl.gui.CommandLineGUI.java

public static void main(String args[]) throws SAXException, IOException {

    Handler fh = new FileHandler(LOG_FILENAME_PATTERN);
    fh.setFormatter(new SimpleFormatter());

    //removeAllLoggersHandlers(Logger.getLogger(""));
    Logger.getLogger("").addHandler(fh);
    Logger.getLogger("").setLevel(Level.FINEST);

    Options options = new Options();

    Option option1 = new Option("in", "ODT file (required)");
    option1.setRequired(true);//from   w  w w . j av  a  2  s.  c  o  m
    option1.setArgs(1);

    Option option2 = new Option("out", "Output file (required)");
    option2.setRequired(false);
    option2.setArgs(1);

    Option option3 = new Option("pic", "extract pics");
    option3.setRequired(false);
    option3.setArgs(1);

    Option option4 = new Option("page", "enable pagination processing");
    option4.setRequired(false);
    option4.setArgs(0);

    options.addOption(option1);
    options.addOption(option2);
    options.addOption(option3);
    options.addOption(option4);

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

    try {
        cmd = parser.parse(options, args);
    } catch (ParseException e) {
        printHelp();
        return;
    }

    if (cmd.hasOption("help")) {
        printHelp();
        return;
    }

    File outFile = new File(cmd.getOptionValue("out"));

    OdtUtils utils = new OdtUtils();

    utils.open(cmd.getOptionValue("in"));
    //utils.correctionStep();
    utils.saveXML(outFile.getAbsolutePath());

    try {

        if (cmd.hasOption("page")) {
            OdtUtils.paginationProcessing(outFile.getAbsolutePath());
        }

        OdtUtils.correctionProcessing(outFile.getAbsolutePath());

    } catch (ParserConfigurationException ex) {
        logger.log(Level.SEVERE, null, ex);
    } catch (SAXException ex) {
        logger.log(Level.SEVERE, null, ex);
    } catch (IOException ex) {
        logger.log(Level.SEVERE, null, ex);
    } catch (TransformerConfigurationException ex) {
        logger.log(Level.SEVERE, null, ex);
    } catch (TransformerException ex) {
        logger.log(Level.SEVERE, null, ex);
    }

    if (cmd.hasOption("pic")) {

        String imageDir = cmd.getOptionValue("pic");
        if (!imageDir.endsWith("/")) {
            imageDir += "/";
        }

        try {

            String basedir = new File(cmd.getOptionValue("out")).getParent().toString()
                    + System.getProperty("file.separator");
            OdtUtils.extractAndNormalizeEmbedPictures(cmd.getOptionValue("out"), cmd.getOptionValue("in"),
                    basedir, imageDir);
        } catch (SAXException ex) {
            logger.log(Level.SEVERE, null, ex);
        } catch (ParserConfigurationException ex) {
            logger.log(Level.SEVERE, null, ex);
        } catch (TransformerConfigurationException ex) {
            logger.log(Level.SEVERE, null, ex);
        } catch (TransformerException ex) {
            logger.log(Level.SEVERE, null, ex);
        }
    }

}

From source file:com.hortonworks.registries.storage.tool.TablesInitializer.java

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

    options.addOption(Option.builder("s").numberOfArgs(1).longOpt(OPTION_SCRIPT_ROOT_PATH)
            .desc("Root directory of script path").build());

    options.addOption(Option.builder("c").numberOfArgs(1).longOpt(OPTION_CONFIG_FILE_PATH)
            .desc("Config file path").build());

    options.addOption(Option.builder("m").numberOfArgs(1).longOpt(OPTION_MYSQL_JAR_URL_PATH)
            .desc("Mysql client jar url to download").build());

    options.addOption(Option.builder().hasArg(false).longOpt(OPTION_EXECUTE_CREATE_TABLE)
            .desc("Execute 'create table' script").build());

    options.addOption(Option.builder().hasArg(false).longOpt(OPTION_EXECUTE_DROP_TABLE)
            .desc("Execute 'drop table' script").build());

    options.addOption(Option.builder().hasArg(false).longOpt(OPTION_EXECUTE_CHECK_CONNECTION)
            .desc("Check the connection for configured data source").build());

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

    if (!commandLine.hasOption(OPTION_CONFIG_FILE_PATH) || !commandLine.hasOption(OPTION_SCRIPT_ROOT_PATH)) {
        usage(options);/* ww  w  .j a va2  s . c  o  m*/
        System.exit(1);
    }

    // either create or drop should be specified, not both
    boolean executeCreate = commandLine.hasOption(OPTION_EXECUTE_CREATE_TABLE);
    boolean executeDrop = commandLine.hasOption(OPTION_EXECUTE_DROP_TABLE);
    boolean checkConnection = commandLine.hasOption(OPTION_EXECUTE_CHECK_CONNECTION);

    boolean moreThanOneOperationIsSpecified = executeCreate == executeDrop ? executeCreate : checkConnection;
    boolean noOperationSpecified = !(executeCreate || executeDrop || checkConnection);

    if (moreThanOneOperationIsSpecified) {
        System.out.println(
                "Only one operation can be execute at once, please select 'create' or 'drop', or 'check-connection'.");
        System.exit(1);
    } else if (noOperationSpecified) {
        System.out.println(
                "One of 'create', 'drop', 'check-connection' operation should be specified to execute.");
        System.exit(1);
    }

    String confFilePath = commandLine.getOptionValue(OPTION_CONFIG_FILE_PATH);
    String scriptRootPath = commandLine.getOptionValue(OPTION_SCRIPT_ROOT_PATH);
    String mysqlJarUrl = commandLine.getOptionValue(OPTION_MYSQL_JAR_URL_PATH);

    StorageProviderConfiguration storageProperties;
    try {
        Map<String, Object> conf = Utils.readConfig(confFilePath);

        StorageProviderConfigurationReader confReader = new StorageProviderConfigurationReader();
        storageProperties = confReader.readStorageConfig(conf);
    } catch (IOException e) {
        System.err.println("Error occurred while reading config file: " + confFilePath);
        System.exit(1);
        throw new IllegalStateException("Shouldn't reach here");
    }

    String bootstrapDirPath = null;
    try {
        bootstrapDirPath = System.getProperty("bootstrap.dir");
        MySqlDriverHelper.downloadMySQLJarIfNeeded(storageProperties, bootstrapDirPath, mysqlJarUrl);
    } catch (Exception e) {
        System.err.println("Error occurred while downloading MySQL jar. bootstrap dir: " + bootstrapDirPath);
        System.exit(1);
        throw new IllegalStateException("Shouldn't reach here");
    }

    try {
        SQLScriptRunner sqlScriptRunner = new SQLScriptRunner(storageProperties);

        try {
            sqlScriptRunner.initializeDriver();
        } catch (ClassNotFoundException e) {
            System.err.println(
                    "Driver class is not found in classpath. Please ensure that driver is in classpath.");
            System.exit(1);
        }

        if (checkConnection) {
            if (!sqlScriptRunner.checkConnection()) {
                System.exit(1);
            }
        } else if (executeDrop) {
            doExecuteDrop(sqlScriptRunner, storageProperties, scriptRootPath);
        } else {
            // executeCreate
            doExecuteCreate(sqlScriptRunner, storageProperties, scriptRootPath);
        }
    } catch (IOException e) {
        System.err.println("Error occurred while reading script file. Script root path: " + scriptRootPath);
        System.exit(1);
    }
}

From source file:com.github.zk1931.pulsefs.Main.java

public static void main(String[] args) throws Exception {
    // Options for command arguments.
    Options options = new Options();

    Option port = OptionBuilder.withArgName("port").hasArg(true).isRequired(true).withDescription("port number")
            .create("port");

    Option addr = OptionBuilder.withArgName("addr").hasArg(true).withDescription("addr (ip:port) for Zab.")
            .create("addr");

    Option join = OptionBuilder.withArgName("join").hasArg(true).withDescription("the addr of server to join.")
            .create("join");

    Option dir = OptionBuilder.withArgName("dir").hasArg(true).withDescription("the directory for logs.")
            .create("dir");

    Option help = OptionBuilder.withArgName("h").hasArg(false).withLongOpt("help")
            .withDescription("print out usages.").create("h");

    Option timeout = OptionBuilder.withArgName("timeout").hasArg(true)
            .withDescription("session timeout(seconds)").create("timeout");

    options.addOption(port).addOption(addr).addOption(join).addOption(dir).addOption(timeout).addOption(help);

    CommandLineParser parser = new BasicParser();
    CommandLine cmd;/*from   w w  w.  j  a  v a 2  s  . c  o m*/
    String usage = "./bin/pulsefs -port port [Options]";
    try {
        cmd = parser.parse(options, args);
        if (cmd.hasOption("h")) {
            HelpFormatter formatter = new HelpFormatter();
            formatter.printHelp(usage, options);
            return;
        }
    } catch (ParseException exp) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp(usage, options);
        return;
    }

    PulseFSConfig config = new PulseFSConfig();

    if (cmd.hasOption("addr")) {
        config.setServerId(cmd.getOptionValue("addr"));
    }
    if (cmd.hasOption("join")) {
        config.setJoinPeer(cmd.getOptionValue("join"));
    }
    if (cmd.hasOption("dir")) {
        config.setLogDir(cmd.getOptionValue("dir"));
    }
    if (cmd.hasOption("timeout")) {
        String sessionTimeout = cmd.getOptionValue("timeout");
        config.setSessionTimeout(Integer.parseInt(sessionTimeout));
    }
    if (cmd.hasOption("port")) {
        config.setPort(Integer.parseInt(cmd.getOptionValue("port")));
    }

    Server server = new Server(config.getPort());
    // Suppress "Server" header in HTTP response.
    for (Connector y : server.getConnectors()) {
        for (ConnectionFactory x : y.getConnectionFactories()) {
            if (x instanceof HttpConnectionFactory) {
                ((HttpConnectionFactory) x).getHttpConfiguration().setSendServerVersion(false);
            }
        }
    }

    PulseFS fs = new PulseFS(config);
    SessionFilter sessionFilter = new SessionFilter(fs);
    FilterHolder filters = new FilterHolder(sessionFilter);

    ServletContextHandler pulsefs = new ServletContextHandler(ServletContextHandler.SESSIONS);
    pulsefs.setContextPath(PulseFSConfig.PULSEFS_ROOT);
    pulsefs.setAllowNullPathInfo(true);
    pulsefs.addServlet(new ServletHolder(new PulseFSHandler(fs)), "/*");
    pulsefs.addFilter(filters, "/*", EnumSet.of(DispatcherType.REQUEST));

    ServletContextHandler servers = new ServletContextHandler(ServletContextHandler.SESSIONS);
    servers.setContextPath(PulseFSConfig.PULSEFS_SERVERS_PATH);
    // Redirects /pulsefs/servers to /pulsefs/servers/
    servers.setAllowNullPathInfo(true);
    servers.addServlet(new ServletHolder(new PulseFSServersHandler(fs)), "/*");
    servers.addFilter(filters, "/*", EnumSet.of(DispatcherType.REQUEST));

    ServletContextHandler tree = new ServletContextHandler(ServletContextHandler.SESSIONS);
    tree.setContextPath("/");
    tree.addServlet(new ServletHolder(new TreeHandler(fs)), "/*");
    tree.addFilter(filters, "/*", EnumSet.of(DispatcherType.REQUEST));

    ServletContextHandler sessions = new ServletContextHandler(ServletContextHandler.SESSIONS);
    sessions.setContextPath(PulseFSConfig.PULSEFS_SESSIONS_PATH);
    // Redirects /pulsefs/sessions to /pulsefs/sessions/
    sessions.setAllowNullPathInfo(true);
    sessions.addServlet(new ServletHolder(new PulseFSSessionsHandler(fs)), "/*");
    sessions.addFilter(filters, "/*", EnumSet.of(DispatcherType.REQUEST));

    ContextHandlerCollection contexts = new ContextHandlerCollection();
    contexts.setHandlers(new Handler[] { sessions, servers, pulsefs, tree });
    server.setHandler(contexts);
    server.start();
    server.join();
}