Example usage for org.apache.commons.cli CommandLineParser parse

List of usage examples for org.apache.commons.cli CommandLineParser parse

Introduction

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

Prototype

CommandLine parse(Options options, String[] arguments) throws ParseException;

Source Link

Document

Parse the arguments according to the specified options.

Usage

From source file:edu.gslis.ts.ThriftToTREC.java

public static void main(String[] args) {
    try {//from  w  w  w  . j a  v  a  2  s  .c o m
        // Get the commandline options
        Options options = createOptions();
        CommandLineParser parser = new GnuParser();
        CommandLine cmd = parser.parse(options, args);

        String in = cmd.getOptionValue("i");
        String outfile = cmd.getOptionValue("o");
        String sentenceParser = cmd.getOptionValue("p");

        // Setup the filter
        ThriftToTREC f = new ThriftToTREC();

        if (in != null && outfile != null) {
            File infile = new File(in);
            if (infile.isDirectory()) {
                for (File file : infile.listFiles()) {
                    if (file.isDirectory()) {
                        for (File filefile : file.listFiles()) {
                            f.filter(filefile, new File(outfile), sentenceParser);
                        }
                    } else {
                        f.filter(file, new File(outfile), sentenceParser);
                    }
                }
            } else
                f.filter(infile, new File(outfile), sentenceParser);
        }

    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:knowledgeMiner.InformationDripBootstrapping.java

public static void main(String[] args) {
    Options options = new Options();
    options.addOption("r", true, "The number of ripples (-1 for unlimited).");
    options.addOption("c", true, "The concept to begin with (\"article\" or #concept).");
    options.addOption("N", true, "The initial hashmap size for the nodes.");
    options.addOption("i", true, "Initial run number.");

    CommandLineParser parser = new BasicParser();
    try {//  ww w.j a va2 s .c  o  m
        CommandLine parse = parser.parse(options, args);
        InformationDripBootstrapping rb = new InformationDripBootstrapping(parse.getOptionValue("c"),
                parse.getOptionValue("r"), parse.getOptionValue("N"), parse.getOptionValue("i"));
        rb.run();
    } catch (Exception e) {
        e.printStackTrace();
        System.exit(1);
    }
}

From source file:edu.cmu.lti.oaqa.annographix.apps.SolrSimpleIndexApp.java

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

    options.addOption("i", null, true, "Input File");
    options.addOption("u", null, true, "Solr URI");
    options.addOption("n", null, true, "Batch size");

    CommandLineParser parser = new org.apache.commons.cli.GnuParser();

    try {//  w w w  .j  av  a  2 s . co m
        CommandLine cmd = parser.parse(options, args);

        if (cmd.hasOption("i")) {
            inputFile = cmd.getOptionValue("i");
        } else {
            Usage("Specify Input File");
        }

        if (cmd.hasOption("u")) {
            solrURI = cmd.getOptionValue("u");
        } else {
            Usage("Specify Solr URI");
        }

        if (cmd.hasOption("n")) {
            batchQty = Integer.parseInt(cmd.getOptionValue("n"));
        }

        SolrServerWrapper solrServer = new SolrServerWrapper(solrURI);

        BufferedReader inpText = new BufferedReader(
                new InputStreamReader(CompressUtils.createInputStream(inputFile)));

        XmlHelper xmlHlp = new XmlHelper();

        String docText = XmlHelper.readNextXMLIndexEntry(inpText);

        for (int docNum = 1; docText != null; ++docNum, docText = XmlHelper.readNextXMLIndexEntry(inpText)) {

            // 1. Read document text
            Map<String, String> docFields = null;
            HashMap<String, Object> objDocFields = new HashMap<String, Object>();

            try {
                docFields = xmlHlp.parseXMLIndexEntry(docText);
            } catch (SAXException e) {
                System.err.println("Parsing error, offending DOC:" + NL + docText);
                throw new Exception("Parsing error.");
            }

            for (Map.Entry<String, String> e : docFields.entrySet()) {
                //System.out.println(e.getKey() + " " + e.getValue());
                objDocFields.put(e.getKey(), e.getValue());
            }

            solrServer.indexDocument(objDocFields);
            if ((docNum - 1) % batchQty == 0)
                solrServer.indexCommit();
        }
        solrServer.indexCommit();

    } catch (ParseException e) {
        Usage("Cannot parse arguments");
    } catch (Exception e) {
        System.err.println("Terminating due to an exception: " + e);
        System.exit(1);
    }

}

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

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

    Option inputOpt = OptionBuilder.create(IN);
    inputOpt.setArgName("INPUT");
    inputOpt.setDescription("Input CDO resource directory");
    inputOpt.setArgs(1);//w  ww  .  j a  v  a  2s  . 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);

    Option repoOpt = OptionBuilder.create(REPO_NAME);
    repoOpt.setArgName("REPO_NAME");
    repoOpt.setDescription("CDO Repository name");
    repoOpt.setArgs(1);
    repoOpt.setRequired(true);

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

    CommandLineParser parser = new PosixParser();

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

        String repositoryDir = commandLine.getOptionValue(IN);
        String repositoryName = commandLine.getOptionValue(REPO_NAME);

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

        EmbeddedCDOServer server = new EmbeddedCDOServer(repositoryDir, repositoryName);
        try {
            server.run();
            CDOSession session = server.openSession();
            CDOTransaction transaction = session.openTransaction();
            Resource resource = transaction.getRootResource();

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

            transaction.close();
            session.close();
        } finally {
            server.stop();
        }
    } 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:at.ac.tuwien.dsg.comot.m.adapter.Main.java

public static void main(String[] args) {

    Options options = createOptions();// w w  w  . j a  va 2s .  c o  m

    try {
        CommandLineParser parser = new PosixParser();
        CommandLine cmd = parser.parse(options, args);

        if (cmd.hasOption("mh") && cmd.hasOption("ih") && cmd.hasOption("ip")) {

            Integer infoPort = null;

            try {
                infoPort = new Integer(cmd.getOptionValue("ip"));
            } catch (NumberFormatException e) {
                LOG.warn("infoPort must be a number");
                showHelp(options);
            }

            AppContextAdapter.setBrokerHost(cmd.getOptionValue("mh"));
            AppContextAdapter.setInfoHost(cmd.getOptionValue("ih"));
            AppContextAdapter.setInfoPort(infoPort);

            context = new AnnotationConfigApplicationContext(AppContextAdapter.class);

            Runtime.getRuntime().addShutdownHook(new Thread() {
                public void run() {
                    if (context != null) {
                        context.close();
                    }
                }
            });

            if (cmd.hasOption("m") || cmd.hasOption("r") || cmd.hasOption("s")) {

                Manager manager = context.getBean(EpsAdapterManager.class);
                String serviceId = getServiceInstanceId();
                String participantId = context.getBean(InfoClient.class).getOsuInstanceByServiceId(serviceId)
                        .getId();

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

                    Monitoring processor = context.getBean(Monitoring.class);
                    manager.start(participantId, processor);

                } else if (cmd.hasOption("r")) {

                    Control processor = context.getBean(Control.class);
                    manager.start(participantId, processor);

                } else if (cmd.hasOption("s")) {

                    Deployment processor = context.getBean(Deployment.class);
                    manager.start(participantId, processor);
                }

            } else {
                LOG.warn("No adapter type specified");
                showHelp(options);
            }
        } else {
            LOG.warn("Required parameters were not specified.");
            showHelp(options);
        }
    } catch (Exception e) {
        LOG.error("{}", e);
        showHelp(options);
    }
}

From source file:edu.gslis.ts.RunQuery.java

public static void main(String[] args) {
    try {//from ww w .ja va 2 s . c om
        // Get the commandline options
        Options options = createOptions();
        CommandLineParser parser = new GnuParser();
        CommandLine cmd = parser.parse(options, args);

        String inputPath = cmd.getOptionValue("input");
        String eventsPath = cmd.getOptionValue("events");
        String stopPath = cmd.getOptionValue("stop");
        int queryId = Integer.valueOf(cmd.getOptionValue("query"));

        List<String> ids = FileUtils.readLines(new File(inputPath + File.separator + "ids.txt"));

        Stopper stopper = new Stopper(stopPath);
        Map<Integer, FeatureVector> queries = readEvents(eventsPath, stopper);

        FeatureVector query = queries.get(queryId);

        Pairtree ptree = new Pairtree();
        Bag<String> words = new HashBag<String>();

        for (String streamId : ids) {

            String ppath = ptree.mapToPPath(streamId.replace("-", ""));

            String inpath = inputPath + File.separator + ppath + File.separator + streamId + ".xz";
            //                System.out.println(inpath);
            File infile = new File(inpath);
            InputStream in = new XZInputStream(new FileInputStream(infile));

            TTransport inTransport = new TIOStreamTransport(new BufferedInputStream(in));
            TBinaryProtocol inProtocol = new TBinaryProtocol(inTransport);
            inTransport.open();
            final StreamItem item = new StreamItem();

            while (true) {
                try {
                    item.read(inProtocol);
                    //                        System.out.println("Read " + item.stream_id);

                } catch (TTransportException tte) {
                    // END_OF_FILE is used to indicate EOF and is not an exception.
                    if (tte.getType() != TTransportException.END_OF_FILE)
                        tte.printStackTrace();
                    break;
                }
            }

            // Do something with this document...
            String docText = item.getBody().getClean_visible();

            StringTokenizer itr = new StringTokenizer(docText);
            while (itr.hasMoreTokens()) {
                words.add(itr.nextToken());
            }

            inTransport.close();

        }

        for (String term : words.uniqueSet()) {
            System.out.println(term + ":" + words.getCount(term));
        }

    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:edu.ucsb.cs.eager.sa.cerebro.Cerebro.java

public static void main(String[] args) {
    Options options = new Options();
    options.addOption("ccp", "cerebro-classpath", true, "Cerebro classpath");
    options.addOption("c", "class", true, "Class to be used as the starting point");
    options.addOption("dnc", "disable-nec-classes", false, "Disable loading of necessary classes");
    options.addOption("wp", "whole-program", false, "Enable whole program mode");

    CommandLine cmd;/*  w  w  w . j  ava  2 s . co  m*/
    try {
        CommandLineParser parser = new BasicParser();
        cmd = parser.parse(options, args);
    } catch (ParseException e) {
        System.err.println("Error: " + e.getMessage() + "\n");
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("Cerebro", options);
        return;
    }

    String classPath = cmd.getOptionValue("ccp");
    if (classPath == null) {
        System.err.println("Cerebro classpath (ccp) option is required");
        return;
    } else {
        String[] paths = classPath.split(":");
        for (String p : paths) {
            File file = new File(p);
            if (!file.exists()) {
                System.err.println("Path segment: " + p + " mentioned in classpath does not exist");
                return;
            }
        }
    }

    String startingPoint = cmd.getOptionValue("c");
    if (startingPoint == null) {
        System.err.println("Starting point class (c) option is required");
        return;
    }

    Cerebro cerebro = new Cerebro(classPath, startingPoint);
    cerebro.setLoadNecessaryClasses(!cmd.hasOption("dnc"));
    cerebro.setWholeProgramMode(cmd.hasOption("wp"));
    cerebro.setVerbose(true);
    cerebro.analyze();
}

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

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

    Option inputOpt = OptionBuilder.create(IN);
    inputOpt.setArgName("INPUT");
    inputOpt.setDescription("Input file");
    inputOpt.setArgs(1);/*from  ww  w . j ava  2  s  . c o m*/
    inputOpt.setRequired(true);

    Option outputOpt = OptionBuilder.create(OUT);
    outputOpt.setArgName("OUTPUT");
    outputOpt.setDescription("Output file");
    outputOpt.setArgs(1);
    outputOpt.setRequired(true);

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

    Option labelOpt = OptionBuilder.create(LABEL);
    labelOpt.setArgName("LABEL");
    labelOpt.setDescription("Label for the data set");
    labelOpt.setArgs(1);
    labelOpt.setRequired(true);

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

    CommandLineParser parser = new PosixParser();

    try {
        CommandLine commandLine = parser.parse(options, args);
        URI sourceUri = URI.createFileURI(commandLine.getOptionValue(IN));
        Class<?> inClazz = ReferencesCounter.class.getClassLoader()
                .loadClass(commandLine.getOptionValue(IN_EPACKAGE_CLASS));
        @SuppressWarnings("unused")
        EPackage inEPackage = (EPackage) inClazz.getMethod("init").invoke(null);

        ResourceSet resourceSet = new ResourceSetImpl();
        resourceSet.getResourceFactoryRegistry().getExtensionToFactoryMap().put("xmi",
                new XMIResourceFactoryImpl());
        resourceSet.getResourceFactoryRegistry().getExtensionToFactoryMap().put("zxmi",
                new XMIResourceFactoryImpl());

        Resource sourceResource = resourceSet.getResource(sourceUri, true);

        FileWriter writer = new FileWriter(new File(commandLine.getOptionValue(OUT)));
        try {
            writer.write(commandLine.getOptionValue(LABEL));
            writer.write("\n");

            for (Iterator<EObject> iterator = sourceResource.getAllContents(); iterator.hasNext();) {
                EObject eObject = iterator.next();
                for (EStructuralFeature feature : eObject.eClass().getEAllStructuralFeatures()) {
                    if (feature.isMany() && eObject.eIsSet(feature)) {
                        EList<?> value = (EList<?>) eObject.eGet(feature);
                        //                     if (value.size() > 10) 
                        writer.write(String.format("%d\n", value.size()));
                    }
                }
            }
        } finally {
            IOUtils.closeQuietly(writer);
        }

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

From source file:info.bitoo.Daemon.java

public static void main(String[] args) throws IOException {
    CommandLineParser parser = new PosixParser();
    CommandLine cmd = null;/*from  ww w . java  2  s .  co  m*/
    try {
        cmd = parser.parse(createCommandLineOptions(), args);
    } catch (ParseException e) {
        System.err.println("Parsing failed.  Reason: " + e.getMessage());
    }

    Properties props = Main.readConfiguration(cmd);

    BufferedReader input = new BufferedReader(new FileReader(cmd.getOptionValue("p")));

    Daemon daemon = new Daemon(props, input);
    daemon.deamonMain();
}

From source file:com.dsf.dbxtract.cdc.App.java

/**
 * <p>/*  w w  w.  ja v  a2 s  .  com*/
 * Starts the dbxtract app.
 * </p>
 * <p>
 * usage: java -jar dbxtract.jar --config &lt;file&gt; [--list | --start]
 * </p>
 * 
 * <pre>
 * --config &lt;file&gt; configuration file pathname
 * --list          list configuration parameters and values
 * --start         start dbxtract agent
 * </pre>
 * 
 * @param args
 *            execution call arguments
 */
public static void main(String[] args) {

    Options options = prepareCmdLineOptions();
    try {
        CommandLineParser parser = new DefaultParser();

        CommandLine cmd = parser.parse(options, args);
        parseCommand(cmd);

    } catch (ParseException e1) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("java -jar dbxtract.jar", options, true);

        error("Unable to parse parameters", e1);

    } catch (Exception e) {
        error("Unable to start dbxtract", e);
    }
}