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:io.s4.util.LoadGenerator.java

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

    options.addOption(/*from  w  w  w.ja  v a 2  s  . co m*/
            OptionBuilder.withArgName("rate").hasArg().withDescription("Rate (events per second)").create("r"));

    options.addOption(OptionBuilder.withArgName("display_rate").hasArg()
            .withDescription("Display Rate at specified second boundary").create("d"));

    options.addOption(OptionBuilder.withArgName("start_boundary").hasArg()
            .withDescription("Start boundary in seconds").create("b"));

    options.addOption(OptionBuilder.withArgName("run_for").hasArg()
            .withDescription("Run for a specified number of seconds").create("x"));

    options.addOption(OptionBuilder.withArgName("cluster_manager").hasArg().withDescription("Cluster manager")
            .create("z"));

    options.addOption(OptionBuilder.withArgName("sender_application_name").hasArg()
            .withDescription("Sender application name").create("a"));

    options.addOption(OptionBuilder.withArgName("listener_application_name").hasArg()
            .withDescription("Listener application name").create("g"));

    options.addOption(
            OptionBuilder.withArgName("sleep_overhead").hasArg().withDescription("Sleep overhead").create("o"));

    options.addOption(new Option("w", "Warm-up"));

    CommandLineParser parser = new GnuParser();

    CommandLine line = null;
    try {
        // parse the command line arguments
        line = parser.parse(options, args);
    } catch (ParseException exp) {
        // oops, something went wrong
        System.err.println("Parsing failed.  Reason: " + exp.getMessage());
        System.exit(1);
    }

    int expectedRate = 250;
    if (line.hasOption("r")) {
        try {
            expectedRate = Integer.parseInt(line.getOptionValue("r"));
        } catch (Exception e) {
            System.err.println("Bad expected rate specified " + line.getOptionValue("r"));
            System.exit(1);
        }
    }

    int displayRateIntervalSeconds = 20;
    if (line.hasOption("d")) {
        try {
            displayRateIntervalSeconds = Integer.parseInt(line.getOptionValue("d"));
        } catch (Exception e) {
            System.err.println("Bad display rate value specified " + line.getOptionValue("d"));
            System.exit(1);
        }
    }

    int startBoundary = 2;
    if (line.hasOption("b")) {
        try {
            startBoundary = Integer.parseInt(line.getOptionValue("b"));
        } catch (Exception e) {
            System.err.println("Bad start boundary value specified " + line.getOptionValue("b"));
            System.exit(1);
        }
    }

    int updateFrequency = 0;
    if (line.hasOption("f")) {
        try {
            updateFrequency = Integer.parseInt(line.getOptionValue("f"));
        } catch (Exception e) {
            System.err.println("Bad query udpdate frequency specified " + line.getOptionValue("f"));
            System.exit(1);
        }
        System.out.printf("Update frequency is %d\n", updateFrequency);
    }

    int runForTime = 0;
    if (line.hasOption("x")) {
        try {
            runForTime = Integer.parseInt(line.getOptionValue("x"));
        } catch (Exception e) {
            System.err.println("Bad run for time specified " + line.getOptionValue("x"));
            System.exit(1);
        }
        System.out.printf("Run for time is %d\n", runForTime);
    }

    String clusterManagerAddress = null;
    if (line.hasOption("z")) {
        clusterManagerAddress = line.getOptionValue("z");
    }

    String senderApplicationName = null;
    if (line.hasOption("a")) {
        senderApplicationName = line.getOptionValue("a");
    }

    String listenerApplicationName = null;
    if (line.hasOption("a")) {
        listenerApplicationName = line.getOptionValue("g");
    }

    if (listenerApplicationName == null) {
        listenerApplicationName = senderApplicationName;
    }

    long sleepOverheadMicros = -1;
    if (line.hasOption("o")) {
        try {
            sleepOverheadMicros = Long.parseLong(line.getOptionValue("o"));
        } catch (NumberFormatException e) {
            System.err.println("Bad sleep overhead specified " + line.getOptionValue("o"));
            System.exit(1);
        }
        System.out.printf("Specified sleep overhead is %d\n", sleepOverheadMicros);
    }

    if (line.hasOption("w")) {
        warmUp = true;
    }

    List loArgs = line.getArgList();
    if (loArgs.size() < 1) {
        System.err.println("No input file specified");
        System.exit(1);
    }

    String inputFilename = (String) loArgs.get(0);

    EventEmitter emitter = null;

    SerializerDeserializer serDeser = new KryoSerDeser();

    CommLayerEmitter clEmitter = new CommLayerEmitter();
    clEmitter.setAppName(senderApplicationName);
    clEmitter.setListenerAppName(listenerApplicationName);
    clEmitter.setClusterManagerAddress(clusterManagerAddress);
    clEmitter.setSenderId(String.valueOf(System.currentTimeMillis() / 1000));
    clEmitter.setSerDeser(serDeser);
    clEmitter.init();
    emitter = clEmitter;

    long endTime = 0;
    if (runForTime > 0) {
        endTime = System.currentTimeMillis() + (runForTime * 1000);
    }

    LoadGenerator loadGenerator = new LoadGenerator();
    loadGenerator.setInputFilename(inputFilename);
    loadGenerator.setEventEmitter(clEmitter);
    loadGenerator.setDisplayRateInterval(displayRateIntervalSeconds);
    loadGenerator.setExpectedRate(expectedRate);
    loadGenerator.run();

    System.exit(0);
}

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

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

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

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

    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 = KyanosGraphQueryGrabats.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 query");
            long begin = System.currentTimeMillis();
            EList<ClassDeclaration> list = JavaQueries.grabats09(resource);
            long end = System.currentTimeMillis();
            LOG.log(Level.INFO, "End query");
            LOG.log(Level.INFO, MessageFormat.format("Query result contains {0} elements", list.size()));
            LOG.log(Level.INFO, MessageFormat.format("Time spent: {0}", MessageUtil.formatMillis(end - begin)));
        }

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

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

From source file:microbiosima.Microbiosima.java

/**
 * @param args/*from   www  .  ja  v  a  2s .  com*/
 *            the command line arguments
 * @throws java.io.FileNotFoundException
 * @throws java.io.UnsupportedEncodingException
 */
public static void main(String[] args) throws FileNotFoundException, UnsupportedEncodingException {
    //Init with default values
    int populationSize = 500;
    int microSize = 1000;
    int numberOfSpecies = 150;
    int numberOfGeneration = 10000;
    int numberOfObservation = 100;
    int numberOfReplication = 1;
    double pctEnv = 0;
    double pctPool = 0;

    Options options = new Options();

    Option help = new Option("h", "help", false, "print this message");
    Option version = new Option("v", "version", false, "print the version information and exit");
    options.addOption(help);
    options.addOption(version);

    options.addOption(Option.builder("o").longOpt("obs").hasArg().argName("OBS")
            .desc("Number generation for observation [default: 100]").build());
    options.addOption(Option.builder("r").longOpt("rep").hasArg().argName("REP")
            .desc("Number of replication [default: 1]").build());

    Builder C = Option.builder("c").longOpt("config").numberOfArgs(4).argName("Pop Micro Spec Gen")
            .desc("Four Parameters in the following orders: "
                    + "(1) population size, (2) microbe size, (3) number of species, (4) number of generation"
                    + " [default: 500 1000 150 10000]");
    options.addOption(C.build());

    HelpFormatter formatter = new HelpFormatter();
    String syntax = "microbiosima pctEnv pctPool";
    String header = "\nSimulates the evolutionary and ecological dynamics of microbiomes within a population of hosts.\n\n"
            + "required arguments:\n" + "  pctEnv             Percentage of environmental acquisition\n"
            + "  pctPool            Percentage of pooled environmental component\n" + "\noptional arguments:\n";
    String footer = "\n";

    formatter.setWidth(80);

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

    try {
        cmd = parser.parse(options, args);
        String[] pct_config = cmd.getArgs();

        if (cmd.hasOption("h") || args.length == 0) {
            formatter.printHelp(syntax, header, options, footer, true);
            System.exit(0);
        }
        if (cmd.hasOption("v")) {
            System.out.println("Microbiosima " + VERSION);
            System.exit(0);
        }
        if (pct_config.length != 2) {
            System.out.println("ERROR! Required exactly two argumennts for pct_env and pct_pool. It got "
                    + pct_config.length + ": " + Arrays.toString(pct_config));
            formatter.printHelp(syntax, header, options, footer, true);
            System.exit(3);
        } else {
            pctEnv = Double.parseDouble(pct_config[0]);
            pctPool = Double.parseDouble(pct_config[1]);
            if (pctEnv < 0 || pctEnv > 1) {
                System.out.println(
                        "ERROR: pctEnv (Percentage of environmental acquisition) must be between 0 and 1 (pctEnv="
                                + pctEnv + ")! EXIT");
                System.exit(3);
            }
            if (pctPool < 0 || pctPool > 1) {
                System.out.println(
                        "ERROR: pctPool (Percentage of pooled environmental component must) must be between 0 and 1 (pctPool="
                                + pctPool + ")! EXIT");
                System.exit(3);
            }

        }
        if (cmd.hasOption("config")) {
            String[] configs = cmd.getOptionValues("config");
            populationSize = Integer.parseInt(configs[0]);
            microSize = Integer.parseInt(configs[1]);
            numberOfSpecies = Integer.parseInt(configs[2]);
            numberOfGeneration = Integer.parseInt(configs[3]);
        }
        if (cmd.hasOption("obs")) {
            numberOfObservation = Integer.parseInt(cmd.getOptionValue("obs"));
        }
        if (cmd.hasOption("rep")) {
            numberOfReplication = Integer.parseInt(cmd.getOptionValue("rep"));
        }

    } catch (ParseException e) {
        e.printStackTrace();
        System.exit(3);
    }

    StringBuilder sb = new StringBuilder();
    sb.append("Configuration Summary:").append("\n\tPopulation size: ").append(populationSize)
            .append("\n\tMicrobe size: ").append(microSize).append("\n\tNumber of species: ")
            .append(numberOfSpecies).append("\n\tNumber of generation: ").append(numberOfGeneration)
            .append("\n\tNumber generation for observation: ").append(numberOfObservation)
            .append("\n\tNumber of replication: ").append(numberOfReplication).append("\n");
    System.out.println(sb.toString());

    //      System.exit(3);
    // LogNormalDistribution lgd=new LogNormalDistribution(0,1);
    // environment=lgd.sample(150);
    // double environment_sum=0;
    // for (int i=0;i<No;i++){
    // environment_sum+=environment[i];
    // }
    // for (int i=0;i<No;i++){
    // environment[i]/=environment_sum;
    // }

    double[] environment = new double[numberOfSpecies];
    for (int i = 0; i < numberOfSpecies; i++) {
        environment[i] = 1 / (double) numberOfSpecies;
    }

    for (int rep = 0; rep < numberOfReplication; rep++) {
        String prefix = "" + (rep + 1) + "_";
        String sufix = "_E" + pctEnv + "_P" + pctPool + ".txt";

        System.out.println("Output 5 result files in the format of: " + prefix + "[****]" + sufix);
        try {

            PrintWriter file1 = new PrintWriter(
                    new BufferedWriter(new FileWriter(prefix + "gamma_diversity" + sufix)));
            PrintWriter file2 = new PrintWriter(
                    new BufferedWriter(new FileWriter(prefix + "alpha_diversity" + sufix)));
            PrintWriter file3 = new PrintWriter(
                    new BufferedWriter(new FileWriter(prefix + "beta_diversity" + sufix)));
            PrintWriter file4 = new PrintWriter(new BufferedWriter(new FileWriter(prefix + "sum" + sufix)));
            PrintWriter file5 = new PrintWriter(
                    new BufferedWriter(new FileWriter(prefix + "inter_generation_distance" + sufix)));
            PrintWriter file6 = new PrintWriter(
                    new BufferedWriter(new FileWriter(prefix + "environment_population_distance" + sufix)));

            Population population = new Population(microSize, environment, populationSize, pctEnv, pctPool, 0,
                    0);

            while (population.getNumberOfGeneration() < numberOfGeneration) {
                population.sumSpecies();
                if (population.getNumberOfGeneration() % numberOfObservation == 0) {
                    file1.println(population.gammaDiversity(true));
                    file2.println(population.alphaDiversity(true));
                    file3.print(population.betaDiversity(true));
                    file3.print("\t");
                    file3.println(population.BrayCurtis(true));
                    file4.println(population.printOut());
                    file5.println(population.interGenerationDistance());
                    file6.println(population.environmentPopulationDistance());
                }
                population.getNextGen();
            }
            file1.close();
            file2.close();
            file3.close();
            file4.close();
            file5.close();
            file6.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

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

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

    Option inputOpt = OptionBuilder.create(IN);
    inputOpt.setArgName("INPUT");
    inputOpt.setDescription("Input Kyanos resource directory");
    inputOpt.setArgs(1);//from ww w  .j  a va2  s  . co  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 = KyanosGraphQuery.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 query");
            long begin = System.currentTimeMillis();
            EList<MethodDeclaration> list = JavaQueries.getUnusedMethodsList(resource);
            long end = System.currentTimeMillis();
            LOG.log(Level.INFO, "End query");
            LOG.log(Level.INFO, MessageFormat.format("Query result (list) contains {0} elements", list.size()));
            LOG.log(Level.INFO, MessageFormat.format("Time spent: {0}", MessageUtil.formatMillis(end - begin)));
        }

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

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

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

From source file:com.aerospike.examples.BatchUpdateTTL.java

public static void main(String[] args) throws AerospikeException {
    try {/*  ww w. j  av a 2s  .c o  m*/
        Options options = new Options();
        options.addOption("h", "host", true, "Server hostname (default: 127.0.0.1)");
        options.addOption("p", "port", true, "Server port (default: 3000)");
        options.addOption("n", "namespace", true, "Namespace (default: test)");
        options.addOption("s", "set", true, "Set (default: demo)");
        options.addOption("u", "usage", false, "Print usage.");

        CommandLineParser parser = new PosixParser();
        CommandLine cl = parser.parse(options, args, false);

        String host = cl.getOptionValue("h", "127.0.0.1");
        String portString = cl.getOptionValue("p", "3000");
        int port = Integer.parseInt(portString);
        String namespace = cl.getOptionValue("n", "test");
        String set = cl.getOptionValue("s", "demo");
        log.debug("Host: " + host);
        log.debug("Port: " + port);
        log.debug("Namespace: " + namespace);
        log.debug("Set: " + set);

        @SuppressWarnings("unchecked")
        List<String> cmds = cl.getArgList();
        if (cmds.size() == 0 && cl.hasOption("u")) {
            logUsage(options);
            return;
        }

        BatchUpdateTTL as = new BatchUpdateTTL(host, port, namespace, set);

        as.work();

    } catch (Exception e) {
        log.error("Critical error", e);
    }
}

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

/**
 * SOA Testing Framework main static method.
 *
 * @param args Main input parameters.//w  w  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:fr.inria.atlanmod.kyanos.benchmarks.KyanosGraphQueryOrphanNonPrimitiveTypes.java

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

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

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

    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 = KyanosGraphQueryOrphanNonPrimitiveTypes.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 query");
            long begin = System.currentTimeMillis();
            EList<Type> list = JavaQueries.getOrphanNonPrimitivesTypes(resource);
            long end = System.currentTimeMillis();
            LOG.log(Level.INFO, "End query");
            LOG.log(Level.INFO, MessageFormat.format("Query result contains {0} elements", list.size()));
            LOG.log(Level.INFO, MessageFormat.format("Time spent: {0}", MessageUtil.formatMillis(end - begin)));
        }

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

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

From source file:demo.learn.shiro.tool.PasswordMatcherTool.java

/**
 * Main method.//from ww  w.j  a  v  a  2  s . c o m
 * @param args Pass in plain text password, hashed password,
 * and salt. These arguments are generated from
 * {@link PasswordEncryptionTool}.
 * @throws ParseException
 */
@SuppressWarnings("static-access")
public static void main(String[] args) throws ParseException {
    String username = "";
    String plainTextPassword = "root";
    String hashedPasswordBase64 = "ZzIkhapTVzGkhWRQqdUn2zod5npt9RJMSni8My6X+r8=";
    String saltBase64 = "BobnkcsIXcZGksA30eOySA==";
    String realmName = "";

    Option p = OptionBuilder.withArgName("password").hasArg().withDescription("plain text password")
            .isRequired(false).create('p');
    Option h = OptionBuilder.withArgName("password").hasArg().withDescription("hashed password")
            .isRequired(false).create('h');
    Option s = OptionBuilder.withArgName("salt").hasArg().withDescription("salt (Base64 encoded)")
            .isRequired(false).create('s');

    Options options = new Options();
    options.addOption(p);
    options.addOption(h);
    options.addOption(s);

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

        if (cmd.hasOption("p")) {
            plainTextPassword = cmd.getOptionValue("p");
        }
        if (cmd.hasOption("h")) {
            hashedPasswordBase64 = cmd.getOptionValue("h");
        }
        if (cmd.hasOption("s")) {
            saltBase64 = cmd.getOptionValue("s");
        }
    } catch (ParseException pe) {
        String cmdLineSyntax = "java -cp %CLASSPATH% demo.learn.shiro.tool.PasswordMatcherTool";
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp(cmdLineSyntax, options, false);
        return;
    }

    SimpleByteSource salt = new SimpleByteSource(Base64.decode(saltBase64));
    SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(username, hashedPasswordBase64, salt,
            realmName);
    UsernamePasswordToken token = new UsernamePasswordToken(username, plainTextPassword);

    HashedCredentialsMatcher matcher = new HashedCredentialsMatcher();
    matcher.setHashIterations(S.HASH_ITER);
    matcher.setStoredCredentialsHexEncoded(false);
    matcher.setHashAlgorithmName(S.ALGORITHM_NAME);

    boolean result = matcher.doCredentialsMatch(token, info);
    System.out.println("match? " + result);

}

From source file:fr.inria.atlanmod.kyanos.benchmarks.KyanosGraphQueryUnusedMethodsList.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  v  a  2  s  .  c  o  m
    inputOpt.setRequired(true);

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

    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 = KyanosGraphQueryUnusedMethodsList.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 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 contains {0} elements", list.size()));
            LOG.log(Level.INFO, MessageFormat.format("Time spent: {0}", MessageUtil.formatMillis(end - begin)));
        }

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

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

From source file:kafka.benchmark.AdvertisingTopology.java

public static void main(final String[] args) throws Exception {
    Options opts = new Options();
    opts.addOption("conf", true, "Path to the config file.");

    CommandLineParser parser = new DefaultParser();
    CommandLine cmd = parser.parse(opts, args);
    String configPath = cmd.getOptionValue("conf");
    Map<?, ?> conf = Utils.findAndReadConfigFile(configPath, true);

    Map<String, ?> benchmarkParams = getKafkaConfs(conf);

    LOG.info("conf: {}", conf);
    LOG.info("Parameters used: {}", benchmarkParams);

    KStreamBuilder builder = new KStreamBuilder();
    //        builder.addStateStore(
    //                Stores.create("config-params")
    //                .withStringKeys().withStringValues()
    //                .inMemory().maxEntries(10).build(), "redis");

    String topicsArr[] = { (String) benchmarkParams.get("topic") };
    KStream<String, ?> source1 = builder.stream(topicsArr);

    Properties props = new Properties();
    props.putAll(benchmarkParams);//w  w w. ja  v  a2  s.c om
    //        props.put(StreamsConfig.APPLICATION_ID_CONFIG, "kafka-benchmarks");
    //        props.put(StreamsConfig.BOOTSTRAP_SERVERS_CONFIG, "localhost:9092");
    ////        props.put(StreamsConfig.ZOOKEEPER_CONNECT_CONFIG, "localhost:2181");
    props.put(StreamsConfig.KEY_SERDE_CLASS_CONFIG, Serdes.String().getClass().getName());
    props.put(StreamsConfig.VALUE_SERDE_CLASS_CONFIG, Serdes.String().getClass().getName());

    // setting offset reset to earliest so that we can re-run the demo code with the same pre-loaded data
    //        props.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "earliest");

    source1
            // Parse the String as JSON
            .mapValues(input -> {
                JSONObject obj = new JSONObject(input.toString());
                //System.out.println(obj.toString());
                String[] tuple = { obj.getString("user_id"), obj.getString("page_id"), obj.getString("ad_id"),
                        obj.getString("ad_type"), obj.getString("event_type"), obj.getString("event_time"),
                        obj.getString("ip_address") };
                return tuple;
            })

            // Filter the records if event type is "view"
            .filter(new Predicate<String, String[]>() {
                @Override
                public boolean test(String key, String[] value) {
                    return value[4].equals("view"); // "event_type"
                }
            })

            // project the event
            .mapValues(input -> {
                String[] arr = (String[]) input;
                return new String[] { arr[2], arr[5] }; // "ad_id" and "event_time"
            })

            // perform join with redis data
            .transformValues(new RedisJoinBolt(benchmarkParams)).filter((key, value) -> value != null)

            // create key from value
            .map((key, value) -> {
                String[] arr = (String[]) value;
                return new KeyValue<String, String[]>(arr[0], arr);
            })

            // process campaign
            .aggregateByKey(new Initializer<List<String[]>>() {
                @Override
                public List<String[]> apply() {
                    return new ArrayList<String[]>();
                }
            }, new Aggregator<String, String[], List<String[]>>() {
                @Override
                public List<String[]> apply(String aggKey, String[] value, List<String[]> aggregate) {
                    aggregate.add(value);
                    return aggregate;
                }
            },
                    // UnlimitedWindows.of("kafka-test-unlim"),
                    // HoppingWindows.of("kafka-test-hopping").with(12L).every(5L),
                    TumblingWindows.of("kafka-test-tumbling").with(WINDOW_SIZE), strSerde, arrSerde)
            .toStream().process(new CampaignProcessor(benchmarkParams));

    KafkaStreams streams = new KafkaStreams(builder, props);
    streams.start();
}