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

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

Introduction

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

Prototype

HelpFormatter

Source Link

Usage

From source file:com.github.brandtg.switchboard.MysqlReplicator.java

/** Main. */
public static void main(String[] args) throws Exception {
    Options options = new Options();
    options.addOption("u", "user", true, "MySQL user");
    options.addOption("p", "password", true, "MySQL password");
    options.addOption("h", "host", true, "MySQL host");
    options.addOption("P", "port", true, "MySQL port");
    options.addOption("s", "sinkPort", true, "Local sink port");
    options.addOption("l", "lastIndex", true, "Last transaction ID");
    options.addOption("h", "help", false, "Prints help message");
    CommandLine commandLine = new GnuParser().parse(options, args);

    if (commandLine.getArgs().length < 2 || commandLine.hasOption("help")) {
        HelpFormatter helpFormatter = new HelpFormatter();
        helpFormatter.printHelp("usage: [opts] switchboardHost:port db1 [db2 ...]", options);
        System.exit(1);//from  w  w w  .j a  v a  2  s  .  c  om
    }

    // Switchboard host
    String[] hostPort = commandLine.getArgs()[0].split(":");
    InetSocketAddress source = new InetSocketAddress(hostPort[0], Integer.valueOf(hostPort[1]));
    InetSocketAddress sink = new InetSocketAddress(
            Integer.valueOf(commandLine.getOptionValue("sinkPort", "9090")));

    // Databases to replicate
    String[] databases = Arrays.copyOfRange(commandLine.getArgs(), 1, commandLine.getArgs().length);

    // JDBC params for local copy
    String user = commandLine.getOptionValue("user", "root");
    String password = commandLine.getOptionValue("password", "");
    String jdbcString = String.format("jdbc:mysql://%s:%d", commandLine.getOptionValue("host", "localhost"),
            Integer.valueOf(commandLine.getOptionValue("port", "3306")));
    Long lastIndex = Long.valueOf(commandLine.getOptionValue("lastIndex", "-1"));

    // Create replicators
    final List<MysqlReplicator> replicators = new ArrayList<>();
    for (String database : databases) {
        MysqlReplicator replicator = new MysqlReplicator(database, source, sink, jdbcString, user, password,
                lastIndex);
        replicators.add(replicator);
    }

    // Shutdown hook
    Runtime.getRuntime().addShutdownHook(new Thread() {
        @Override
        public void run() {
            for (MysqlReplicator replicator : replicators) {
                try {
                    replicator.shutdown();
                } catch (Exception e) {
                    LOG.error("Could not shut down {}", replicator, e);
                }
            }
        }
    });

    for (MysqlReplicator replicator : replicators) {
        replicator.start();
        LOG.info("Started {}", replicator);
    }
}

From source file:com.asakusafw.dmdl.thundergate.Main.java

/**
 * ???/*from w  w  w .ja v  a2 s .  co  m*/
 * @param args ???????????
 */
public static void main(String... args) {
    GenerateTask task;
    try {
        Configuration conf = loadConfigurationFromArguments(args);
        task = new GenerateTask(conf);
    } catch (Exception e) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.setWidth(Integer.MAX_VALUE);
        formatter.printHelp(MessageFormat.format("java -classpath ... {0}", Main.class.getName()), OPTIONS,
                true);
        e.printStackTrace(System.out);
        System.exit(1);
        return;
    }
    try {
        task.call();
    } catch (Exception e) {
        e.printStackTrace(System.out);
        System.exit(1);
        return;
    }
}

From source file:fr.inria.atlanmod.kyanos.benchmarks.XmiCreator.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);//  w ww  .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(EPACKAGE_CLASS);
    inClassOpt.setArgName("CLASS");
    inClassOpt.setDescription("FQN of EPackage implementation class");
    inClassOpt.setArgs(1);
    inClassOpt.setRequired(true);

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

    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 = XmiCreator.class.getClassLoader()
                .loadClass(commandLine.getOptionValue(EPACKAGE_CLASS));
        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.createResource(sourceUri);
        Map<String, Object> loadOpts = new HashMap<String, Object>();
        if ("zxmi".equals(sourceUri.fileExtension())) {
            loadOpts.put(XMIResource.OPTION_ZIP, Boolean.TRUE);
        }

        Runtime.getRuntime().gc();
        long initialUsedMemory = Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory();
        LOG.log(Level.INFO, MessageFormat.format("Used memory before loading: {0}",
                MessageUtil.byteCountToDisplaySize(initialUsedMemory)));
        LOG.log(Level.INFO, "Loading source resource");
        sourceResource.load(loadOpts);
        LOG.log(Level.INFO, "Source resource loaded");
        Runtime.getRuntime().gc();
        long finalUsedMemory = Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory();
        LOG.log(Level.INFO, MessageFormat.format("Used memory after loading: {0}",
                MessageUtil.byteCountToDisplaySize(finalUsedMemory)));
        LOG.log(Level.INFO, MessageFormat.format("Memory use increase: {0}",
                MessageUtil.byteCountToDisplaySize(finalUsedMemory - initialUsedMemory)));

        Resource targetResource = resourceSet.createResource(targetUri);

        Map<String, Object> saveOpts = new HashMap<String, Object>();
        targetResource.save(saveOpts);

        LOG.log(Level.INFO, "Start moving elements");
        targetResource.getContents().clear();
        targetResource.getContents().addAll(sourceResource.getContents());
        LOG.log(Level.INFO, "End moving elements");
        LOG.log(Level.INFO, "Start saving");
        targetResource.save(saveOpts);
        LOG.log(Level.INFO, "Saved");

        targetResource.unload();

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

From source file:name.wagners.bpp.Bpp.java

public static void main(final String[] args) {

    // create the command line parser
    CommandLineParser parser = new PosixParser();

    // create the Options
    Options options = new Options();

    options.addOption(OptionBuilder.hasArg().withArgName("int").withLongOpt("generations")
            .withDescription("Number of generations [default: 50]").create("g"));

    options.addOption(OptionBuilder.hasArg().withArgName("int").withLongOpt("mutrate")
            .withDescription("Mutation rate [default: 1]").create());

    options.addOption(OptionBuilder.hasArg().withArgName("double").withLongOpt("mutprop")
            .withDescription("Mutation propability [default: 0.5]").create());

    options.addOption(OptionBuilder.hasArg().withArgName("int").withLongOpt("populationsize")
            .withDescription("Size of population [default: 20]").create());

    options.addOption(OptionBuilder.hasArg().withArgName("a|b").withLongOpt("recombalg")
            .withDescription("Recombination algorithm [default: a]").create());

    // options.addOption(OptionBuilder
    // .hasArg()//from w w w .j a v a  2  s.  c  o m
    // .withArgName("int")
    // .withLongOpt("recombrate")
    // .withDescription("Recombination rate [default: 1]")
    // .create());

    options.addOption(OptionBuilder.hasArg().withArgName("double").withLongOpt("recombprop")
            .withDescription("Recombination propability [default: 0.8]").create());

    options.addOption(OptionBuilder.hasArg().withArgName("a").withLongOpt("selalg")
            .withDescription("Selection algorithm [default: a]").create());

    options.addOption(OptionBuilder.hasArg().withArgName("int").withLongOpt("selectionpressure")
            .withDescription("Selection pressure [default: 4]").create());

    options.addOption(OptionBuilder.hasArg().withArgName("bool").withLongOpt("elitism")
            .withDescription("Enable Elitism [default: 1]").create("e"));

    options.addOption(OptionBuilder.hasArg().withArgName("filename")
            // .isRequired()
            .withLongOpt("datafile").withDescription("Problem data file [default: \"binpack.txt\"]")
            .create("f"));

    options.addOptionGroup(new OptionGroup()
            .addOption(OptionBuilder.withLongOpt("verbose").withDescription("be extra verbose").create("v"))
            .addOption(OptionBuilder.withLongOpt("quiet").withDescription("be extra quiet").create("q")));

    options.addOption(OptionBuilder.withLongOpt("version")
            .withDescription("print the version information and exit").create("V"));

    options.addOption(OptionBuilder.withLongOpt("help").withDescription("print this message").create("h"));

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

        // validate that block-size has been set
        if (line.hasOption("help")) {
            // automatically generate the help statement
            HelpFormatter formatter = new HelpFormatter();
            formatter.printHelp("Bpp", options);

            System.exit(0);
        }

        if (line.hasOption("version")) {
            log.info("Bpp 0.1 (c) 2007 by Daniel Wagner");
        }

        if (line.hasOption("datafile")) {
            fname = line.getOptionValue("datafile");
        }

        if (line.hasOption("elitism")) {
            elitism = Boolean.parseBoolean(line.getOptionValue("elitism"));
        }

        if (line.hasOption("generations")) {
            gen = Integer.parseInt(line.getOptionValue("generations"));
        }

        if (line.hasOption("mutprop")) {
            mp = Double.parseDouble(line.getOptionValue("mutprop"));
        }

        if (line.hasOption("mutrate")) {
            mr = Integer.parseInt(line.getOptionValue("mutrate"));
        }

        if (line.hasOption("populationsize")) {
            ps = Integer.parseInt(line.getOptionValue("populationsize"));
        }

        if (line.hasOption("recombalg")) {
            sel = line.getOptionValue("recombalg").charAt(0);
        }

        if (line.hasOption("recombprop")) {
            rp = Double.parseDouble(line.getOptionValue("recombprop"));
        }

        if (line.hasOption("selalg")) {
            selalg = line.getOptionValue("selalg").charAt(0);
        }

        if (line.hasOption("selectionpressure")) {
            sp = Integer.parseInt(line.getOptionValue("selectionpressure"));
        }

    } catch (ParseException exp) {
        log.info("Unexpected exception:" + exp.getMessage(), exp);

        // automatically generate the help statement
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("Bpp", options);

        System.exit(1);
    }

    // Ausgabe der eingestellten Optionen

    log.info("Configuration");
    log.info("  Datafile:                  " + fname);
    log.info("  Generations:               " + gen);
    log.info("  Population size:           " + ps);
    log.info("  Elitism:                   " + elitism);
    log.info("  Mutation propapility:      " + mp);
    log.info("  Mutation rate:             " + mr);
    log.info("  Recombination algorithm    " + (char) sel);
    log.info("  Recombination propapility: " + rp);
    log.info("  Selection pressure:        " + sp);

    // Daten laden
    instance = new Instance();
    instance.load(fname);

    Evolutionizer e = new Evolutionizer(instance);

    e.run();
}

From source file:com.jolira.testing.CachingRESTProxy.java

/**
 * @param args//from   www  .  j  a v a 2 s .c o m
 * @throws Exception
 */
public static void main(final String[] args) throws Exception {
    final Parser parser = new GnuParser();
    final HelpFormatter formatter = new HelpFormatter();
    final Options options = new Options();

    options.addOption("c", CACHE, true, "chache directory (mandatory!)");
    options.addOption("s", SERVER, true, "server name and port number as server:port");
    options.addOption("x", USE_SSL, false, "use ssl");
    options.addOption("?", HELP, false, "display help");

    final CommandLine cli = parser.parse(options, args);
    final String server = cli.getOptionValue(SERVER);
    final String cache = cli.getOptionValue(CACHE);
    final boolean ssl = cli.hasOption(USE_SSL);

    if (cli.hasOption(HELP) || cache == null) {
        formatter.printHelp(CachingRESTProxy.class.getName(), options);
        return;
    }

    final CachingRESTProxy proxy = new CachingRESTProxy(ssl, server, new File(cache));

    proxy.start();
}

From source file:fr.inria.atlanmod.kyanos.benchmarks.CdoQueryRenameAllMethods.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 ww w.  ja  v  a2 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 = CdoQueryRenameAllMethods.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();
            ((CDONet4jSession) session).options().setCommitTimeout(50 * 1000);
            CDOTransaction transaction = session.openTransaction();
            Resource resource = transaction.getRootResource();

            String name = UUID.randomUUID().toString();
            {
                LOG.log(Level.INFO, "Start query");
                long begin = System.currentTimeMillis();
                JavaQueries.renameAllMethods(resource, name);
                long end = System.currentTimeMillis();
                transaction.commit();
                LOG.log(Level.INFO, "End query");
                LOG.log(Level.INFO,
                        MessageFormat.format("Time spent: {0}", MessageUtil.formatMillis(end - begin)));
            }

            //            {
            //               transaction.close();
            //               session.close();
            //               
            //               session = server.openSession();
            //               transaction = session.openTransaction();
            //               resource = transaction.getRootResource();
            //               
            //               EList<? extends EObject> methodList = JavaQueries.getAllInstances(resource, JavaPackage.eINSTANCE.getMethodDeclaration());
            //               int i = 0;
            //               for (EObject eObject: methodList) {
            //                  MethodDeclaration method = (MethodDeclaration) eObject;
            //                  if (name.equals(method.getName())) {
            //                     i++;
            //                  }
            //               }
            //               LOG.log(Level.INFO, MessageFormat.format("Renamed {0} methods", i));
            //            }

            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:com.threadswarm.imagefeedarchiver.driver.CommandLineDriver.java

public static void main(String[] args) throws InterruptedException, ExecutionException, ParseException {
    // define available command-line options
    Options options = new Options();
    options.addOption("h", "help", false, "display usage information");
    options.addOption("u", "url", true, "RSS feed URL");
    options.addOption("a", "user-agent", true, "User-Agent header value to use when making HTTP requests");
    options.addOption("o", "output-directory", true, "output directory for downloaded images");
    options.addOption("t", "thread-count", true, "number of worker threads, defaults to cpu-count + 1");
    options.addOption("d", "delay", true, "delay between image downloads (in milliseconds)");
    options.addOption("p", "notrack", false, "tell websites that you don't wish to be tracked (DNT)");
    options.addOption("s", "https", false, "Rewrite image URLs to leverage SSL/TLS");

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

    // print usage information if 'h'/'help' or no-args were given
    if (args.length == 0 || commandLine.hasOption("h")) {
        HelpFormatter helpFormatter = new HelpFormatter();
        helpFormatter.printHelp("java -jar ImageFeedArchiver.jar", options);
        return; //abort execution
    }// ww  w  .j  a va2s . c o  m

    URI rssFeedUri = null;
    if (commandLine.hasOption("u")) {
        String rssFeedUrlString = commandLine.getOptionValue("u");
        try {
            rssFeedUri = FeedUtils.getUriFromUrlString(rssFeedUrlString);
        } catch (MalformedURLException | URISyntaxException e) {
            LOGGER.error("The Feed URL you supplied was malformed or violated syntax rules.. exiting", e);
            System.exit(1);
        }
        LOGGER.info("Target RSS feed URL: {}", rssFeedUri);
    } else {
        throw new IllegalStateException("RSS feed URL was not specified!");
    }

    File outputDirectory = null;
    if (commandLine.hasOption("o")) {
        outputDirectory = new File(commandLine.getOptionValue("o"));
        if (!outputDirectory.isDirectory())
            throw new IllegalArgumentException("output directory must be a *directory*!");
        LOGGER.info("Using output directory: '{}'", outputDirectory);
    } else {
        throw new IllegalStateException("output directory was not specified!");
    }

    String userAgentString = null;
    if (commandLine.hasOption("a")) {
        userAgentString = commandLine.getOptionValue("a");
        LOGGER.info("Setting 'User-Agent' header value to '{}'", userAgentString);
    }

    int threadCount;
    if (commandLine.hasOption("t")) {
        threadCount = Integer.parseInt(commandLine.getOptionValue("t"));
    } else {
        threadCount = Runtime.getRuntime().availableProcessors() + 1;
    }
    LOGGER.info("Using {} worker threads", threadCount);

    long downloadDelay = 0;
    if (commandLine.hasOption("d")) {
        String downloadDelayString = commandLine.getOptionValue("d");
        downloadDelay = Long.parseLong(downloadDelayString);
    }
    LOGGER.info("Using a download-delay of {} milliseconds", downloadDelay);

    boolean doNotTrackRequested = commandLine.hasOption("p");

    boolean forceHttps = commandLine.hasOption("s");

    ApplicationContext context = new ClassPathXmlApplicationContext("META-INF/applicationContext.xml");
    ((ConfigurableApplicationContext) context).registerShutdownHook();

    HttpClient httpClient = (HttpClient) context.getBean("httpClient");
    if (userAgentString != null)
        httpClient.getParams().setParameter(CoreProtocolPNames.USER_AGENT, userAgentString);

    ProcessedRssItemDAO processedRssItemDAO = (ProcessedRssItemDAO) context.getBean("processedRssItemDAO");

    CommandLineDriver.Builder driverBuilder = new CommandLineDriver.Builder(rssFeedUri);
    driverBuilder.setDoNotTrackRequested(doNotTrackRequested).setOutputDirectory(outputDirectory)
            .setDownloadDelay(downloadDelay).setThreadCount(threadCount).setHttpClient(httpClient)
            .setForceHttps(forceHttps).setProcessedRssItemDAO(processedRssItemDAO);

    CommandLineDriver driver = driverBuilder.build();
    driver.run();
}

From source file:com.github.aptd.simulation.CMain.java

/**
 * main method//from   w  ww.j a va2s  . c  o m
 * @param p_args command-line parameters
 * @throws IOException error on io errors
 */
public static void main(final String[] p_args) throws IOException {
    // --- define CLI options ------------------------------------------------------------------------------------------------------------------------------

    final Options l_clioptions = new Options();
    l_clioptions.addOption("help", false, "shows this information");
    l_clioptions.addOption("generateconfig", false, "generate default configuration");
    l_clioptions.addOption("config", true,
            "path to configuration directory (default: <user home>/.asimov/configuration.yaml)");
    l_clioptions.addOption("interactive", false, "start web server for interactive execution");
    l_clioptions.addOption("sequential", false, "run simulation in sequential (default is parallel)");
    l_clioptions.addOption("iteration", true, "number of iterations");
    l_clioptions.addOption("scenariotype", true, "comma-separated list of scenario types (default: xml)");
    l_clioptions.addOption("scenario", true, "comma-separated list of scenario files");
    l_clioptions.addOption("timemodel", true, "jump for jumping time, step for stepping time (default: step)");
    l_clioptions.addOption("changetimeseed", true,
            "seed for uniform random generator of passenger platform change duration (default: 1)");
    l_clioptions.addOption("changetimemin", true,
            "minimum value for uniform random generator of passenger platform chnge duration in seconds (default: 100)");
    l_clioptions.addOption("changetimemax", true,
            "maximum value for uniform random generator of passenger platform change duration in seconds (default: 100)");
    l_clioptions.addOption("numberofpassengers", true, "number of passengers (default: 20)");
    l_clioptions.addOption("lightbarrierminfreetime", true,
            "minimum duration how long the light barrier has to be free before the door can close (default: 3)");
    l_clioptions.addOption("delayseconds", true, "primary delay of first train in seconds (default: 0)");

    final CommandLine l_cli;
    try {
        l_cli = new DefaultParser().parse(l_clioptions, p_args);
    } catch (final Exception l_exception) {
        System.err.println("command-line arguments parsing error");
        System.exit(-1);
        return;
    }

    // --- process CLI arguments and initialize configuration ----------------------------------------------------------------------------------------------

    if (l_cli.hasOption("help")) {
        new HelpFormatter().printHelp(
                new java.io.File(CMain.class.getProtectionDomain().getCodeSource().getLocation().getPath())
                        .getName(),
                l_clioptions);
        return;
    }

    if (l_cli.hasOption("generateconfig")) {
        System.out
                .println(CCommon.languagestring(CMain.class, "generateconfig", CConfiguration.createdefault()));
        return;
    }

    if (!l_cli.hasOption("scenario")) {
        System.out.println(CCommon.languagestring(CMain.class, "noscenario", CConfiguration.createdefault()));
        System.exit(-1);
        return;
    }

    execute(l_cli);
}

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

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

    Option inputOpt = OptionBuilder.create(IN);
    inputOpt.setArgName("INPUT");
    inputOpt.setDescription("Input Kyanos resource directory");
    inputOpt.setArgs(1);/*ww w  .  ja  v a2s .  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 optFileOpt = OptionBuilder.create(OPTIONS_FILE);
    optFileOpt.setArgName("FILE");
    optFileOpt.setDescription("Properties file holding the options to be used in the Kyanos Resource");
    optFileOpt.setArgs(1);

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

    CommandLineParser parser = new PosixParser();

    try {
        PersistenceBackendFactoryRegistry.getFactories().put(NeoBlueprintsURI.NEO_GRAPH_SCHEME,
                new BlueprintsPersistenceBackendFactory());

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

        URI uri = NeoBlueprintsURI.createNeoGraphURI(new File(commandLine.getOptionValue(IN)));

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

        ResourceSet resourceSet = new ResourceSetImpl();
        resourceSet.getResourceFactoryRegistry().getProtocolToFactoryMap()
                .put(NeoBlueprintsURI.NEO_GRAPH_SCHEME, PersistentResourceFactory.eINSTANCE);

        Resource resource = resourceSet.createResource(uri);

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

        if (commandLine.hasOption(OPTIONS_FILE)) {
            Properties properties = new Properties();
            properties.load(new FileInputStream(new File(commandLine.getOptionValue(OPTIONS_FILE))));
            for (final Entry<Object, Object> entry : properties.entrySet()) {
                loadOpts.put((String) entry.getKey(), (String) entry.getValue());
            }
        }
        resource.load(loadOpts);

        LOG.log(Level.INFO, "Start counting");
        int count = 0;
        long begin = System.currentTimeMillis();
        for (Iterator<EObject> iterator = resource.getAllContents(); iterator.hasNext(); iterator
                .next(), count++)
            ;
        long end = System.currentTimeMillis();
        LOG.log(Level.INFO, "End counting");
        LOG.log(Level.INFO, MessageFormat.format("Resource {0} contains {1} elements", uri, count));
        LOG.log(Level.INFO, MessageFormat.format("Time spent: {0}", MessageUtil.formatMillis(end - begin)));

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

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

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

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

    Option inputOpt = OptionBuilder.create(IN);
    inputOpt.setArgName("INPUT");
    inputOpt.setDescription("Input Kyanos resource directory");
    inputOpt.setArgs(1);//  w w w. j  a va 2s . 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 optFileOpt = OptionBuilder.create(OPTIONS_FILE);
    optFileOpt.setArgName("FILE");
    optFileOpt.setDescription("Properties file holding the options to be used in the Kyanos Resource");
    optFileOpt.setArgs(1);

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

    CommandLineParser parser = new PosixParser();

    try {
        PersistenceBackendFactoryRegistry.getFactories().put(NeoBlueprintsURI.NEO_GRAPH_SCHEME,
                new BlueprintsPersistenceBackendFactory());

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

        URI uri = NeoBlueprintsURI.createNeoGraphURI(new File(commandLine.getOptionValue(IN)));

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

        ResourceSet resourceSet = new ResourceSetImpl();
        resourceSet.getResourceFactoryRegistry().getProtocolToFactoryMap()
                .put(NeoBlueprintsURI.NEO_GRAPH_SCHEME, PersistentResourceFactory.eINSTANCE);

        Resource resource = resourceSet.createResource(uri);

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

        if (commandLine.hasOption(OPTIONS_FILE)) {
            Properties properties = new Properties();
            properties.load(new FileInputStream(new File(commandLine.getOptionValue(OPTIONS_FILE))));
            for (final Entry<Object, Object> entry : properties.entrySet()) {
                loadOpts.put((String) entry.getKey(), (String) entry.getValue());
            }
        }
        resource.load(loadOpts);
        String name = UUID.randomUUID().toString();
        {
            LOG.log(Level.INFO, "Start query");
            long begin = System.currentTimeMillis();
            JavaQueries.renameAllMethods(resource, name);
            long end = System.currentTimeMillis();
            resource.save(Collections.emptyMap());
            LOG.log(Level.INFO, "End query");
            LOG.log(Level.INFO, MessageFormat.format("Time spent: {0}", MessageUtil.formatMillis(end - begin)));
        }

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

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