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:edu.cmu.lti.oaqa.knn4qa.apps.CollectionDiffer.java

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

    options.addOption("i1", null, true, "Input file 1");
    options.addOption("i2", null, true, "Input file 2");
    options.addOption("o", null, true, "Output file");

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

    try {//from   w  w w  .  j  a v  a 2 s  .c o m
        CommandLine cmd = parser.parse(options, args);

        InputStream input1 = null, input2 = null;

        if (cmd.hasOption("i1")) {
            input1 = CompressUtils.createInputStream(cmd.getOptionValue("i1"));
        } else {
            Usage("Specify 'Input file 1'");
        }
        if (cmd.hasOption("i2")) {
            input2 = CompressUtils.createInputStream(cmd.getOptionValue("i2"));
        } else {
            Usage("Specify 'Input file 2'");
        }

        HashSet<String> hSubj = new HashSet<String>();

        BufferedWriter out = null;

        if (cmd.hasOption("o")) {
            String outFile = cmd.getOptionValue("o");

            out = new BufferedWriter(new OutputStreamWriter(CompressUtils.createOutputStream(outFile)));
        } else {
            Usage("Specify 'Output file'");
        }

        XmlIterator inpIter2 = new XmlIterator(input2, YahooAnswersReader.DOCUMENT_TAG);

        int docNum = 1;
        for (String oneRec = inpIter2.readNext(); !oneRec.isEmpty(); oneRec = inpIter2.readNext(), ++docNum) {
            if (docNum % 10000 == 0) {
                System.out.println(String.format(
                        "Loaded and memorized questions for %d documents from the second input file", docNum));
            }
            ParsedQuestion q = YahooAnswersParser.parse(oneRec, false);
            hSubj.add(q.mQuestion);
        }

        XmlIterator inpIter1 = new XmlIterator(input1, YahooAnswersReader.DOCUMENT_TAG);

        System.out.println("=============================================");
        System.out.println("Memoization is done... now let's diff!!!");
        System.out.println("=============================================");

        docNum = 1;
        int skipOverlapQty = 0, skipErrorQty = 0;
        for (String oneRec = inpIter1.readNext(); !oneRec.isEmpty(); ++docNum, oneRec = inpIter1.readNext()) {
            if (docNum % 10000 == 0) {
                System.out.println(String.format("Processed %d documents from the first input file", docNum));
            }

            oneRec = oneRec.trim() + System.getProperty("line.separator");

            ParsedQuestion q = null;
            try {
                q = YahooAnswersParser.parse(oneRec, false);
            } catch (Exception e) {
                // If <bestanswer>...</bestanswer> is missing we may end up here...
                // This is a bit funny, because this element is supposed to be mandatory,
                // but it's not.
                System.err.println("Skipping due to parsing error, exception: " + e);
                skipErrorQty++;
                continue;
            }
            if (hSubj.contains(q.mQuestion.trim())) {
                //System.out.println(String.format("Skipping uri='%s', question='%s'", q.mQuestUri, q.mQuestion));
                skipOverlapQty++;
                continue;
            }

            out.write(oneRec);
        }
        System.out.println(
                String.format("Processed %d documents, skipped because of overlap/errors %d/%d documents",
                        docNum - 1, skipOverlapQty, skipErrorQty));
        out.close();
    } catch (ParseException e) {
        Usage("Cannot parse arguments");
    } catch (Exception e) {
        e.printStackTrace();
        System.err.println("Terminating due to an exception: " + e);
        System.exit(1);
    }
}

From source file:fr.inria.atlanmod.kyanos.benchmarks.CdoQueryThrownExceptionsPerPackage.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);/*from w  ww. j  a  va2 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);

    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 = CdoQueryThrownExceptionsPerPackage.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();
                HashMap<String, EList<TypeAccess>> map = JavaQueries.getThrownExceptionsPerPackage(resource);
                long end = System.currentTimeMillis();
                LOG.log(Level.INFO, "End query");
                LOG.log(Level.INFO,
                        MessageFormat.format("Query result contains {0} elements", map.entrySet().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:cc.twittertools.search.api.TrecSearchThriftServer.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("port").hasArg().withDescription("port").create(PORT_OPTION));
    options.addOption(/*  w w  w.  j a  va  2  s . c  o m*/
            OptionBuilder.withArgName("index").hasArg().withDescription("index location").create(INDEX_OPTION));
    options.addOption(OptionBuilder.withArgName("num").hasArg()
            .withDescription("max number of threads in thread pool").create(MAX_THREADS_OPTION));
    options.addOption(OptionBuilder.withArgName("file").hasArg()
            .withDescription("file containing access tokens").create(CREDENTIALS_OPTION));

    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(INDEX_OPTION)) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp(TrecSearchThriftServer.class.getName(), options);
        System.exit(-1);
    }

    int port = cmdline.hasOption(PORT_OPTION) ? Integer.parseInt(cmdline.getOptionValue(PORT_OPTION))
            : DEFAULT_PORT;
    int maxThreads = cmdline.hasOption(MAX_THREADS_OPTION)
            ? Integer.parseInt(cmdline.getOptionValue(MAX_THREADS_OPTION))
            : DEFAULT_MAX_THREADS;
    File index = new File(cmdline.getOptionValue(INDEX_OPTION));

    Map<String, String> credentials = null;
    if (cmdline.hasOption(CREDENTIALS_OPTION)) {
        credentials = Maps.newHashMap();
        File cfile = new File(cmdline.getOptionValue(CREDENTIALS_OPTION));
        if (!cfile.exists()) {
            System.err.println("Error: " + cfile + " does not exist!");
            System.exit(-1);
        }
        for (String s : Files.readLines(cfile, Charsets.UTF_8)) {
            try {
                String[] arr = s.split(":");
                credentials.put(arr[0], arr[1]);
            } catch (Exception e) {
                // Catch any exceptions from parsing file contain access tokens
                System.err.println("Error reading access tokens from " + cfile + "!");
                System.exit(-1);
            }
        }
    }

    if (!index.exists()) {
        System.err.println("Error: " + index + " does not exist!");
        System.exit(-1);
    }

    TServerSocket serverSocket = new TServerSocket(port);
    TrecSearch.Processor<TrecSearch.Iface> searchProcessor = new TrecSearch.Processor<TrecSearch.Iface>(
            new TrecSearchHandler(index, credentials));

    TThreadPoolServer.Args serverArgs = new TThreadPoolServer.Args(serverSocket);
    serverArgs.maxWorkerThreads(maxThreads);
    TServer thriftServer = new TThreadPoolServer(
            serverArgs.processor(searchProcessor).protocolFactory(new TBinaryProtocol.Factory()));

    thriftServer.serve();
}

From source file:fr.inria.atlanmod.kyanos.benchmarks.CdoQueryClassDeclarationAttributes.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);//from   w  w  w . j a  v a 2s.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);

    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 = CdoQueryClassDeclarationAttributes.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();
                HashMap<String, EList<NamedElement>> map = JavaQueries.getClassDeclarationAttributes(resource);
                long end = System.currentTimeMillis();
                LOG.log(Level.INFO, "End query");
                LOG.log(Level.INFO,
                        MessageFormat.format("Query result contains {0} elements", map.entrySet().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:ca.uqac.dim.mapreduce.ltl.ParaLTLValidation.java

/**
 * Program entry point.//from w  w w. j  av  a 2 s .co  m
 * @param args Command-line arguments
 */
@SuppressWarnings("static-access")
public static void main(String[] args) {
    // Define and process command line arguments
    Options options = new Options();
    HelpFormatter help_formatter = new HelpFormatter();
    Option opt;
    options.addOption("h", "help", false, "Show help");
    opt = OptionBuilder.withArgName("property").hasArg()
            .withDescription("Property to verify, enclosed in double quotes").create("p");
    options.addOption(opt);
    opt = OptionBuilder.withArgName("filename").hasArg().withDescription("Input filename").create("i");
    options.addOption(opt);
    opt = OptionBuilder.withArgName("x").hasArg()
            .withDescription("Set verbosity level to x (default: 0 = quiet)").create("v");
    options.addOption(opt);
    opt = OptionBuilder.withArgName("ParserType").hasArg().withDescription("Parser type (Dom or Sax)")
            .create("t");
    options.addOption(opt);
    opt = OptionBuilder.withLongOpt("redirection").withArgName("x").hasArg()
            .withDescription("Set the redirection file for the System.out").create("r");
    options.addOption(opt);
    opt = OptionBuilder.withLongOpt("mapper").withArgName("x").hasArg()
            .withDescription("Set the number of mapper").create("m");
    options.addOption(opt);
    opt = OptionBuilder.withLongOpt("reducer").withArgName("x").hasArg()
            .withDescription("Set the number of reducer").create("n");
    options.addOption(opt);
    CommandLine c_line = parseCommandLine(options, args);

    String redirectionFile = "";

    //Contains a redirection file for the output
    if (c_line.hasOption("redirection")) {
        try {
            redirectionFile = c_line.getOptionValue("redirection");
            PrintStream ps;
            ps = new PrintStream(redirectionFile);
            System.setOut(ps);
        } catch (FileNotFoundException e) {
            System.out.println("Redirection error !!!");
            e.printStackTrace();
        }
    }

    if (!c_line.hasOption("p") || !c_line.hasOption("i") | c_line.hasOption("h")) {
        help_formatter.printHelp(app_name, options);
        System.exit(1);
    }
    assert c_line.hasOption("p");
    assert c_line.hasOption("i");
    String trace_filename = c_line.getOptionValue("i");
    String trace_format = getExtension(trace_filename);
    String property_str = c_line.getOptionValue("p");
    String ParserType = "";
    int MapperNum = 0;
    int ReducerNum = 0;

    //Contains a parser type
    if (c_line.hasOption("t")) {
        ParserType = c_line.getOptionValue("t");
    } else {
        System.err.println("No Parser Type in Arguments");
        System.exit(ERR_ARGUMENTS);
    }

    //Contains a mapper number
    if (c_line.hasOption("m")) {
        MapperNum = Integer.parseInt(c_line.getOptionValue("m"));
    } else {
        System.err.println("No Mapper Number in Arguments");
        System.exit(ERR_ARGUMENTS);
    }

    //Contains a reducer number
    if (c_line.hasOption("n")) {
        ReducerNum = Integer.parseInt(c_line.getOptionValue("n"));
    } else {
        System.err.println("No Reducer Number in Arguments");
        System.exit(ERR_ARGUMENTS);
    }

    if (c_line.hasOption("v"))
        m_verbosity = Integer.parseInt(c_line.getOptionValue("v"));

    // Obtain the property to verify and break into subformulas
    Operator property = null;
    try {
        int preset = Integer.parseInt(property_str);
        property = new Edoc2012Presets().property(preset);
    } catch (NumberFormatException e) {
        try {
            property = Operator.parseFromString(property_str);
        } catch (Operator.ParseException pe) {
            System.err.println("ERROR: parsing");
            System.exit(1);
        }
    }
    Set<Operator> subformulas = property.getSubformulas();

    // Initialize first collector depending on input file format
    int max_loops = property.getDepth();
    int max_tuples_total = 0, total_tuples_total = 0;
    long time_begin = System.nanoTime();
    TraceCollector initial_collector = null;
    {
        File in_file = new File(trace_filename);
        if (trace_format.compareToIgnoreCase(".txt") == 0) {
            initial_collector = new CharacterTraceCollector(in_file, subformulas);
        } else if (trace_format.compareToIgnoreCase(".xml") == 0) {
            if (ParserType.equals("Dom")) {
                initial_collector = new XmlDomTraceCollector(in_file, subformulas);
            } else if (ParserType.equals("Sax")) {
                initial_collector = new XmlSaxTraceCollector(in_file, subformulas);
            } else {
                initial_collector = new XmlSaxTraceCollector(in_file, subformulas);
            }
        }
    }
    if (initial_collector == null) {
        System.err.println("ERROR: unrecognized input format");
        System.exit(1);
    }

    // Start workflow
    int trace_len = initial_collector.getTraceLength();
    InCollector<Operator, LTLTupleValue> loop_collector = initial_collector;
    print(System.out, property.toString(), 2);
    print(System.out, loop_collector.toString(), 3);
    for (int i = 0; i < max_loops; i++) {
        print(System.out, "Loop " + i, 2);
        LTLParallelWorkflow w = new LTLParallelWorkflow(new LTLMapper(subformulas),
                new LTLReducer(subformulas, trace_len), loop_collector,
                new ResourceManager<Operator, LTLTupleValue>(MapperNum),
                new ResourceManager<Operator, LTLTupleValue>(ReducerNum));
        loop_collector = w.run();
        max_tuples_total += w.getMaxTuples();
        total_tuples_total += w.getTotalTuples();

        if (m_verbosity >= 3) {
            print(System.out, loop_collector.toString(), 3);
        }
    }
    boolean result = getVerdict(loop_collector, property);
    long time_end = System.nanoTime();
    if (result)
        print(System.out, "Formula is true", 1);
    else
        print(System.out, "Formula is false", 1);

    long time_total = (time_end - time_begin) / 1000000;
    System.out.println(trace_len + "," + max_tuples_total + "," + total_tuples_total + "," + time_total);
}

From source file:com.kappaware.logtrawler.Main.java

@SuppressWarnings("static-access")
static public void main(String[] argv) throws Throwable {

    Config config;/*  ww  w .ja va 2  s .  com*/

    Options options = new Options();

    options.addOption(OptionBuilder.hasArg().withArgName("configFile").withLongOpt("config-file")
            .withDescription("JSON configuration file").create("c"));
    options.addOption(OptionBuilder.hasArg().withArgName("folder").withLongOpt("folder")
            .withDescription("Folder to monitor").create("f"));
    options.addOption(OptionBuilder.hasArg().withArgName("exclusion").withLongOpt("exclusion")
            .withDescription("Exclusion regex").create("x"));
    options.addOption(OptionBuilder.hasArg().withArgName("adminEndpoint").withLongOpt("admin-endpoint")
            .withDescription("Endpoint for admin REST").create("e"));
    options.addOption(OptionBuilder.hasArg().withArgName("outputFlow").withLongOpt("output-flow")
            .withDescription("Target to post result on").create("o"));
    options.addOption(OptionBuilder.hasArg().withArgName("hostname").withLongOpt("hostname")
            .withDescription("This hostname").create("h"));
    options.addOption(OptionBuilder.withLongOpt("displayDot").withDescription("Display Dot").create("d"));
    options.addOption(OptionBuilder.hasArg().withArgName("mimeType").withLongOpt("mime-type")
            .withDescription("Valid MIME type").create("m"));
    options.addOption(OptionBuilder.hasArg().withArgName("allowedAdmin").withLongOpt("allowedAdmin")
            .withDescription("Allowed admin network").create("a"));
    options.addOption(OptionBuilder.hasArg().withArgName("configFile").withLongOpt("gen-config-file")
            .withDescription("Generate JSON configuration file").create("g"));
    options.addOption(OptionBuilder.hasArg().withArgName("maxBatchSize").withLongOpt("max-batch-size")
            .withDescription("Max JSON batch (array) size").create("b"));

    CommandLineParser clParser = new BasicParser();
    CommandLine line;
    String configFile = null;
    try {
        // parse the command line argument
        line = clParser.parse(options, argv);
        if (line.hasOption("c")) {
            configFile = line.getOptionValue("c");
            config = Json.fromJson(Config.class,
                    new BufferedReader(new InputStreamReader(new FileInputStream(configFile))));
        } else {
            config = new Config();
        }
        if (line.hasOption("f")) {
            String[] fs = line.getOptionValues("f");
            // Get the first agent (Create it if needed)
            if (config.getAgents() == null || config.getAgents().size() == 0) {
                Config.Agent agent = new Config.Agent("default");
                config.addAgent(agent);
            }
            Config.Agent agent = config.getAgents().iterator().next();
            for (String f : fs) {
                agent.addFolder(new Config.Agent.Folder(f, false));
            }
        }
        if (line.hasOption("e")) {
            String e = line.getOptionValue("e");
            config.setAdminEndpoint(e);
        }
        if (line.hasOption("o")) {
            String[] es = line.getOptionValues("o");
            if (config.getAgents() != null) {
                for (Agent agent : config.getAgents()) {
                    for (String s : es) {
                        agent.addOuputFlow(s);
                    }
                }
            }
        }
        if (line.hasOption("h")) {
            String e = line.getOptionValue("h");
            config.setHostname(e);
        }
        if (line.hasOption("x")) {
            if (config.getAgents() != null) {
                for (Agent agent : config.getAgents()) {
                    if (agent.getFolders() != null) {
                        for (Folder folder : agent.getFolders()) {
                            String[] exs = line.getOptionValues("x");
                            for (String ex : exs) {
                                folder.addExcludedPath(ex);
                            }
                        }
                    }
                }
            }
        }
        if (line.hasOption("m")) {
            if (config.getAgents() != null) {
                for (Agent agent : config.getAgents()) {
                    String[] exs = line.getOptionValues("m");
                    for (String ex : exs) {
                        agent.addLogMimeType(ex);
                    }
                }
            }
        }
        if (line.hasOption("a")) {
            String[] exs = line.getOptionValues("a");
            for (String ex : exs) {
                config.addAdminAllowedNetwork(ex);
            }
        }
        if (line.hasOption("d")) {
            config.setDisplayDot(true);
        }
        if (line.hasOption("b")) {
            Integer i = getIntegerParameter(line, "b");
            if (config.getAgents() != null) {
                for (Agent agent : config.getAgents()) {
                    agent.setOutputMaxBatchSize(i);
                }
            }
        }
        config.setDefault();
        if (line.hasOption("g")) {
            String fileName = line.getOptionValue("g");
            PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(fileName, false)));
            out.println(Json.toJson(config, true));
            out.flush();
            out.close();
            System.exit(0);
        }
    } catch (ParseException exp) {
        // oops, something went wrong
        usage(options, exp.getMessage());
        return;
    }

    try {
        // Check config
        if (config.getAgents() == null || config.getAgents().size() < 1) {
            throw new ConfigurationException("At least one folder to monitor must be provided!");
        }
        Map<String, AgentHandler> agentHandlerByName = new HashMap<String, AgentHandler>();
        for (Config.Agent agent : config.getAgents()) {
            agentHandlerByName.put(agent.getName(), new AgentHandler(agent));
        }
        if (!Utils.isNullOrEmpty(config.getAdminEndpoint())) {
            new AdminServer(config, agentHandlerByName);
        }
    } catch (ConfigurationException e) {
        log.error(e.toString());
        System.exit(1);
    } catch (Throwable t) {
        log.error("Error in main", t);
        System.exit(2);
    }
}

From source file:fr.inria.atlanmod.kyanos.benchmarks.Migrator.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);/* ww w  .j  a v a 2  s.co  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 outClassOpt = OptionBuilder.create(OUT_EPACKAGE_CLASS);
    outClassOpt.setArgName("CLASS");
    outClassOpt.setDescription("FQN of output EPackage implementation class");
    outClassOpt.setArgs(1);
    outClassOpt.setRequired(true);

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

    CommandLineParser parser = new PosixParser();

    try {
        CommandLine commandLine = parser.parse(options, args);
        URI sourceUri = URI.createFileURI(commandLine.getOptionValue(IN));
        URI targetUri = URI.createFileURI(commandLine.getOptionValue(OUT));
        Class<?> inClazz = Migrator.class.getClassLoader()
                .loadClass(commandLine.getOptionValue(IN_EPACKAGE_CLASS));
        Class<?> outClazz = Migrator.class.getClassLoader()
                .loadClass(commandLine.getOptionValue(OUT_EPACKAGE_CLASS));

        @SuppressWarnings("unused")
        EPackage inEPackage = (EPackage) inClazz.getMethod("init").invoke(null);
        EPackage outEPackage = (EPackage) outClazz.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);
        Resource targetResource = resourceSet.createResource(targetUri);

        targetResource.getContents().clear();
        LOG.log(Level.INFO, "Start migration");
        targetResource.getContents()
                .add(MigratorUtil.migrate(sourceResource.getContents().get(0), outEPackage));
        LOG.log(Level.INFO, "Migration finished");

        Map<String, Object> saveOpts = new HashMap<String, Object>();
        saveOpts.put(XMIResource.OPTION_ZIP, Boolean.TRUE);
        LOG.log(Level.INFO, "Start saving");
        targetResource.save(saveOpts);
        LOG.log(Level.INFO, "Saving done");
    } 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:at.salzburgresearch.vgi.vgianalyticsframework.activityanalysis.application.VgiAnalysis.java

public static void main(String[] args) {
    /**//from   w  ww . java  2 s. com
     * Read input parameter
     */
    Options options = new Options();
    options.addOption("h", "help", false, "Display this help page");
    /** Settings */
    options.addOption(Option.builder("s").longOpt("settings").hasArg().argName("settings_file")
            .desc("settings file").build());
    options.addOption(Option.builder("p").longOpt("polygons").hasArg().argName("polygon_file")
            .desc("polygon file").build());

    launch(options, args);
}

From source file:ar.com.ergio.uncoma.cei.MiniPas.java

/**
 * @param args/*  w w w  .  jav  a2s.  c om*/
 * @throws IOException 
 */
@SuppressWarnings("static-access")
public static void main(String[] args) throws IOException {
    // Config logging system -- TODO improve this
    Handler console = new ConsoleHandler();
    ROOT_LOG.addHandler(console);

    // Create cmdline options - TODO - I18N
    final Options options = new Options();
    options.addOption(new Option("help", "Muestra este mensaje"));
    options.addOption(new Option("version", "Muestra la informaci\u00f3 de versi\u00f3n y termina"));
    options.addOption(new Option("debug", "Muestra informaci\u00f3n para depuraci\u00f3n"));
    options.addOption(
            OptionBuilder.withArgName("file").hasArg().withDescription("Archivo de log").create("logFile"));

    final CommandLineParser cmdlineParser = new GnuParser();
    final HelpFormatter formatter = new HelpFormatter();
    try {
        final CommandLine cmdline = cmdlineParser.parse(options, args);

        // Process command line args  -- TODO Improve this
        if (args.length == 0 || cmdline.hasOption("help")) {
            formatter.printHelp("minipas", options, true);
        } else if (cmdline.hasOption("version")) {
            System.out.println("MiniPas versi\u00f3n: 0.0.1");
        } else if (cmdline.hasOption("debug")) {
            ROOT_LOG.setLevel(Level.FINE);
        } else {
            ROOT_LOG.fine("Arguments: " + Arrays.toString(args));
            final Scanner scanner = new Scanner(args[0]);
            while (scanner.hasTokens()) {
                System.out.println(scanner.nextToken());
            }
        }

    } catch (ParseException e) {
        formatter.printHelp("minipas", options, true);
    }
}

From source file:CircularGenerator.java

@SuppressWarnings("static-access")
public static void main(String[] args) throws Exception {
    Options helpOptions = new Options();
    helpOptions.addOption("h", "help", false, "show this help page");
    Options options = new Options();
    options.addOption("h", "help", false, "show this help page");
    options.addOption(OptionBuilder.withLongOpt("input").withArgName("INPUT")
            .withDescription("the input FastA File").isRequired().hasArg().create("i"));
    options.addOption(OptionBuilder.withLongOpt("elongation").withArgName("ELONGATION")
            .withDescription("the elongation factor [INT]").isRequired().hasArg().create("e"));
    options.addOption(OptionBuilder.withLongOpt("seq").withArgName("SEQ")
            .withDescription("the names of the sequences that should to be elongated").isRequired().hasArg()
            .hasOptionalArgs().hasArg().create("s"));
    HelpFormatter helpformatter = new HelpFormatter();
    CommandLineParser parser = new BasicParser();
    try {//from   w  w w. j ava2 s  .c om
        CommandLine cmd = parser.parse(helpOptions, args);
        if (cmd.hasOption('h')) {
            helpformatter.printHelp(CLASS_NAME + "v" + VERSION, options);
            System.exit(0);
        }
    } catch (ParseException e1) {
    }
    String input = "";
    String tmpElongation = "";
    Integer elongation = 0;
    String[] names = new String[0];
    try {
        CommandLine cmd = parser.parse(options, args);
        if (cmd.hasOption('i')) {
            input = cmd.getOptionValue('i');
        }
        if (cmd.hasOption('e')) {
            tmpElongation = cmd.getOptionValue('e');
            try {
                elongation = Integer.parseInt(tmpElongation);
            } catch (Exception e) {
                System.err.println("elongation not an Integer: " + tmpElongation);
                System.exit(0);
            }
        }
        if (cmd.hasOption('s')) {
            names = cmd.getOptionValues('s');
        }
    } catch (ParseException e) {
        helpformatter.printHelp(CLASS_NAME, options);
        System.err.println(e.getMessage());
        System.exit(0);
    }

    CircularGenerator cg = new CircularGenerator(elongation);
    File f = new File(input);
    for (String s : names) {
        cg.keys_to_treat_circular.add(s);
    }
    cg.extendFastA(f);

}