Example usage for java.lang Integer parseInt

List of usage examples for java.lang Integer parseInt

Introduction

In this page you can find the example usage for java.lang Integer parseInt.

Prototype

public static int parseInt(String s) throws NumberFormatException 

Source Link

Document

Parses the string argument as a signed decimal integer.

Usage

From source file:com.cloudera.oryx.app.traffic.TrafficUtil.java

public static void main(String[] args) throws Exception {
    if (args.length < 3) {
        System.err.println("usage: TrafficUtil [hosts] [requestIntervalMS] [threads] [... other args]");
        return;/*www.  ja v a  2 s.  com*/
    }

    String[] hostStrings = COMMA.split(args[0]);
    Preconditions.checkArgument(hostStrings.length >= 1);
    int requestIntervalMS = Integer.parseInt(args[1]);
    Preconditions.checkArgument(requestIntervalMS >= 0);
    int numThreads = Integer.parseInt(args[2]);
    Preconditions.checkArgument(numThreads >= 1);

    String[] otherArgs = new String[args.length - 3];
    System.arraycopy(args, 3, otherArgs, 0, otherArgs.length);

    List<URI> hosts = Arrays.stream(hostStrings).map(URI::create).collect(Collectors.toList());

    int perClientRequestIntervalMS = numThreads * requestIntervalMS;

    Endpoints alsEndpoints = new Endpoints(ALSEndpoint.buildALSEndpoints());
    AtomicLong requestCount = new AtomicLong();
    AtomicLong serverErrorCount = new AtomicLong();
    AtomicLong clientErrorCount = new AtomicLong();
    AtomicLong exceptionCount = new AtomicLong();

    long start = System.currentTimeMillis();
    ExecUtils.doInParallel(numThreads, numThreads, true, i -> {
        RandomGenerator random = RandomManager.getRandom(Integer.toString(i).hashCode() ^ System.nanoTime());
        ExponentialDistribution msBetweenRequests;
        if (perClientRequestIntervalMS > 0) {
            msBetweenRequests = new ExponentialDistribution(random, perClientRequestIntervalMS);
        } else {
            msBetweenRequests = null;
        }

        ClientConfig clientConfig = new ClientConfig();
        PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager();
        connectionManager.setMaxTotal(numThreads);
        connectionManager.setDefaultMaxPerRoute(numThreads);
        clientConfig.property(ApacheClientProperties.CONNECTION_MANAGER, connectionManager);
        clientConfig.connectorProvider(new ApacheConnectorProvider());
        Client client = ClientBuilder.newClient(clientConfig);

        try {
            while (true) {
                try {
                    WebTarget target = client.target("http://" + hosts.get(random.nextInt(hosts.size())));
                    Endpoint endpoint = alsEndpoints.chooseEndpoint(random);
                    Invocation invocation = endpoint.makeInvocation(target, otherArgs, random);

                    long startTime = System.currentTimeMillis();
                    Response response = invocation.invoke();
                    try {
                        response.readEntity(String.class);
                    } finally {
                        response.close();
                    }
                    long elapsedMS = System.currentTimeMillis() - startTime;

                    int statusCode = response.getStatusInfo().getStatusCode();
                    if (statusCode >= 400) {
                        if (statusCode >= 500) {
                            serverErrorCount.incrementAndGet();
                        } else {
                            clientErrorCount.incrementAndGet();
                        }
                    }

                    endpoint.recordTiming(elapsedMS);

                    if (requestCount.incrementAndGet() % 10000 == 0) {
                        long elapsed = System.currentTimeMillis() - start;
                        log.info("{}ms:\t{} requests\t({} client errors\t{} server errors\t{} exceptions)",
                                elapsed, requestCount.get(), clientErrorCount.get(), serverErrorCount.get(),
                                exceptionCount.get());
                        for (Endpoint e : alsEndpoints.getEndpoints()) {
                            log.info("{}", e);
                        }
                    }

                    if (msBetweenRequests != null) {
                        int desiredElapsedMS = (int) Math.round(msBetweenRequests.sample());
                        if (elapsedMS < desiredElapsedMS) {
                            Thread.sleep(desiredElapsedMS - elapsedMS);
                        }
                    }
                } catch (Exception e) {
                    exceptionCount.incrementAndGet();
                    log.warn("{}", e.getMessage());
                }
            }
        } finally {
            client.close();
        }
    });
}

From source file:com.uber.tchannel.ping.PingClient.java

public static void main(String[] args) throws Exception {
    Options options = new Options();
    options.addOption("h", "host", true, "Server Host to connect to");
    options.addOption("p", "port", true, "Server Port to connect to");
    options.addOption("n", "requests", true, "Number of requests to make");
    options.addOption("?", "help", false, "Usage");
    HelpFormatter formatter = new HelpFormatter();

    CommandLineParser parser = new DefaultParser();
    CommandLine cmd = parser.parse(options, args);

    if (cmd.hasOption("?")) {
        formatter.printHelp("PingClient", options, true);
        return;//  w  w  w  .  j  a  va2  s.c o  m
    }

    String host = cmd.getOptionValue("h", "localhost");
    int port = Integer.parseInt(cmd.getOptionValue("p", "8888"));
    int requests = Integer.parseInt(cmd.getOptionValue("n", "10000"));

    System.out.println(String.format("Connecting from client to server on port: %d", port));
    new PingClient(host, port, requests).run();
    System.out.println("Stopping Client...");
}

From source file:ca.uqac.lif.bullwinkle.BullwinkleCli.java

/**
 * @param args/*w ww .ja v  a2 s  .com*/
 */
public static void main(String[] args) {
    // Setup parameters
    int verbosity = 1;
    String output_format = "xml", grammar_filename = null, filename_to_parse = null;

    // Parse command line arguments
    Options options = setupOptions();
    CommandLine c_line = setupCommandLine(args, options);
    assert c_line != null;
    if (c_line.hasOption("verbosity")) {
        verbosity = Integer.parseInt(c_line.getOptionValue("verbosity"));
    }
    if (verbosity > 0) {
        showHeader();
    }
    if (c_line.hasOption("version")) {
        System.err.println("(C) 2014 Sylvain Hall et al., Universit du Qubec  Chicoutimi");
        System.err.println("This program comes with ABSOLUTELY NO WARRANTY.");
        System.err.println("This is a free software, and you are welcome to redistribute it");
        System.err.println("under certain conditions. See the file LICENSE-2.0 for details.\n");
        System.exit(ERR_OK);
    }
    if (c_line.hasOption("h")) {
        showUsage(options);
        System.exit(ERR_OK);
    }
    if (c_line.hasOption("f")) {
        output_format = c_line.getOptionValue("f");
    }
    // Get grammar file
    @SuppressWarnings("unchecked")
    List<String> remaining_args = c_line.getArgList();
    if (remaining_args.isEmpty()) {
        System.err.println("ERROR: no grammar file specified");
        System.exit(ERR_ARGUMENTS);
    }
    grammar_filename = remaining_args.get(0);
    // Get file to parse, if any
    if (remaining_args.size() >= 2) {
        filename_to_parse = remaining_args.get(1);
    }

    // Read grammar file
    BnfParser parser = null;
    try {
        parser = new BnfParser(new File(grammar_filename));
    } catch (InvalidGrammarException e) {
        System.err.println("ERROR: invalid grammar");
        System.exit(ERR_GRAMMAR);
    } catch (IOException e) {
        System.err.println("ERROR reading grammar " + grammar_filename);
        System.exit(ERR_IO);
    }
    assert parser != null;

    // Read input file
    BufferedReader bis = null;
    if (filename_to_parse == null) {
        // Read from stdin
        bis = new BufferedReader(new InputStreamReader(System.in));
    } else {
        // Read from file
        try {
            bis = new BufferedReader(new InputStreamReader(new FileInputStream(new File(filename_to_parse))));
        } catch (FileNotFoundException e) {
            System.err.println("ERROR: file not found " + filename_to_parse);
            System.exit(ERR_IO);
        }
    }
    assert bis != null;
    String str;
    StringBuilder input_file = new StringBuilder();
    try {
        while ((str = bis.readLine()) != null) {
            input_file.append(str).append("\n");
        }
    } catch (IOException e) {
        System.err.println("ERROR reading input");
        System.exit(ERR_IO);
    }
    String file_contents = input_file.toString();

    // Parse contents of file
    ParseNode p_node = null;
    try {
        p_node = parser.parse(file_contents);
    } catch (ca.uqac.lif.bullwinkle.BnfParser.ParseException e) {
        System.err.println("ERROR parsing input\n");
        e.printStackTrace();
        System.exit(ERR_PARSE);
    }
    if (p_node == null) {
        System.err.println("ERROR parsing input\n");
        System.exit(ERR_PARSE);
    }
    assert p_node != null;

    // Output parse node to desired format
    PrintStream output = System.out;
    OutputFormatVisitor out_vis = null;
    if (output_format.compareToIgnoreCase("xml") == 0) {
        // Output to XML
        out_vis = new XmlVisitor();
    } else if (output_format.compareToIgnoreCase("dot") == 0) {
        // Output to DOT
        out_vis = new GraphvizVisitor();
    } else if (output_format.compareToIgnoreCase("txt") == 0) {
        // Output to indented plain text
        out_vis = new IndentedTextVisitor();
    } else if (output_format.compareToIgnoreCase("json") == 0) {
        // Output to JSON
    }
    if (out_vis == null) {
        System.err.println("ERROR: unknown output format " + output_format);
        System.exit(ERR_ARGUMENTS);
    }
    assert out_vis != null;
    p_node.prefixAccept(out_vis);
    output.print(out_vis.toOutputString());

    // Terminate without error
    System.exit(ERR_OK);
}

From source file:com.opensearchserver.hadse.Hadse.java

public static void main(String[] args) {
    if (args != null)
        for (String arg : args) {
            String s[] = StringUtils.split(arg, "=");
            if (s.length < 2)
                continue;
            if ("--server.port".equals(s[0]))
                port = Integer.parseInt(s[1]);
        }//from   w w  w  .java 2  s  .c om
    SpringApplication app = new SpringApplication(Hadse.class);
    app.setShowBanner(false);
    app.run(args);
}

From source file:mamo.vanillaVotifier.VanillaVotifier.java

public static void main(String[] args) {
    String[] javaVersion = System.getProperty("java.version").split("\\.");
    if (!(javaVersion.length >= 1 && Integer.parseInt(javaVersion[0]) >= 1 && javaVersion.length >= 2
            && Integer.parseInt(javaVersion[1]) >= 6)) {
        System.out.println(("You need at least Java 1.6 to run this program! Current version: "
                + System.getProperty("java.version") + "."));
        return;/*from   w  w w .  j a va2  s.  co m*/
    }

    VanillaVotifier votifier = new VanillaVotifier();
    for (String arg : args) {
        if (arg.equalsIgnoreCase("-report-exceptions")) {
            votifier.reportExceptions = true;
        } else if (arg.equalsIgnoreCase("-help")) {
            votifier.getLogger().printlnTranslation("s58");
            return;
        } else {
            votifier.getLogger().printlnTranslation("s55",
                    new AbstractMap.SimpleEntry<String, Object>("option", arg));
            return;
        }
    }
    votifier.getLogger().printlnTranslation("s42");
    if (!(loadConfig(votifier) && startServer(votifier))) {
        return;
    }
    Scanner in = new Scanner(System.in);

    while (true) {
        String command;
        try {
            command = in.nextLine();
        } catch (NoSuchElementException e) {
            // NoSuchElementException: Can only happen at unexpected program interruption (i. e. CTRL+C). Ignoring.
            continue;
        } catch (Exception e) {
            votifier.getLogger().printlnTranslation("s57",
                    new AbstractMap.SimpleEntry<String, Object>("exception", e));
            if (!stopServer(votifier)) {
                System.exit(0); // "return" somehow isn't enough.
            }
            return;
        }
        if (command.equalsIgnoreCase("stop") || command.toLowerCase().startsWith("stop ")) {
            if (command.split(" ").length == 1) {
                stopServer(votifier);
                break;
            } else {
                votifier.getLogger().printlnTranslation("s17");
            }
        } else if (command.equalsIgnoreCase("restart") || command.toLowerCase().startsWith("restart ")) {
            if (command.split(" ").length == 1) {
                Listener listener = new Listener() {
                    @Override
                    public void onEvent(Event event, VanillaVotifier votifier) {
                        if (event instanceof ServerStoppedEvent) {
                            if (loadConfig((VanillaVotifier) votifier)
                                    && startServer((VanillaVotifier) votifier)) {
                                votifier.getServer().getListeners().remove(this);
                            } else {
                                System.exit(0);
                            }
                        }
                    }
                };
                votifier.getServer().getListeners().add(listener);
                if (!stopServer(votifier)) { // Kill the process if the server doesn't stop
                    System.exit(0); // "return" somehow isn't enough.
                    return;
                }
            } else {
                votifier.getLogger().printlnTranslation("s56");
            }
        } else if (command.equalsIgnoreCase("gen-key-pair") || command.startsWith("gen-key-pair ")) {
            String[] commandArgs = command.split(" ");
            int keySize;
            if (commandArgs.length == 1) {
                keySize = 2048;
            } else if (commandArgs.length == 2) {
                try {
                    keySize = Integer.parseInt(commandArgs[1]);
                } catch (NumberFormatException e) {
                    votifier.getLogger().printlnTranslation("s19");
                    continue;
                }
                if (keySize < 512) {
                    votifier.getLogger().printlnTranslation("s51");
                    continue;
                }
                if (keySize > 16384) {
                    votifier.getLogger().printlnTranslation("s52");
                    continue;
                }
            } else {
                votifier.getLogger().printlnTranslation("s20");
                continue;
            }
            votifier.getLogger().printlnTranslation("s16");
            votifier.getConfig().genKeyPair(keySize);
            try {
                votifier.getConfig().save();
            } catch (Exception e) {
                votifier.getLogger().printlnTranslation("s21",
                        new AbstractMap.SimpleEntry<String, Object>("exception", e));
            }
            votifier.getLogger().printlnTranslation("s23");
        } else if (command.equalsIgnoreCase("test-vote") || command.toLowerCase().startsWith("test-vote ")) {
            String[] commandArgs = command.split(" ");
            if (commandArgs.length == 2) {
                try {
                    votifier.getTester().testVote(new Vote("TesterService", commandArgs[1],
                            votifier.getConfig().getInetSocketAddress().getAddress().getHostName()));
                } catch (Exception e) { // GeneralSecurityException, IOException
                    votifier.getLogger().printlnTranslation("s27",
                            new AbstractMap.SimpleEntry<String, Object>("exception", e));
                }
            } else {
                votifier.getLogger().printlnTranslation("s26");
            }
        } else if (command.equalsIgnoreCase("test-query") || command.toLowerCase().startsWith("test-query ")) {
            if (command.split(" ").length >= 2) {
                try {
                    votifier.getTester()
                            .testQuery(command.replaceFirst("test-query ", "").replaceAll("---", "\n"));
                } catch (Exception e) { // GeneralSecurityException, IOException
                    votifier.getLogger().printlnTranslation("s35",
                            new AbstractMap.SimpleEntry<String, Object>("exception", e));
                }
            } else {
                votifier.getLogger().printlnTranslation("s34");
            }
        } else if (command.equalsIgnoreCase("help") || command.toLowerCase().startsWith("help ")) {
            if (command.split(" ").length == 1) {
                votifier.getLogger().printlnTranslation("s31");
            } else {
                votifier.getLogger().printlnTranslation("s32");
            }
        } else if (command.equalsIgnoreCase("manual") || command.toLowerCase().startsWith("manual ")) {
            if (command.split(" ").length == 1) {
                votifier.getLogger().printlnTranslation("s36");
            } else {
                votifier.getLogger().printlnTranslation("s37");
            }
        } else if (command.equalsIgnoreCase("info") || command.toLowerCase().startsWith("info ")) {
            if (command.split(" ").length == 1) {
                votifier.getLogger().printlnTranslation("s40");
            } else {
                votifier.getLogger().printlnTranslation("s41");
            }
        } else if (command.equalsIgnoreCase("license") || command.toLowerCase().startsWith("license ")) {
            if (command.split(" ").length == 1) {
                votifier.getLogger().printlnTranslation("s43");
            } else {
                votifier.getLogger().printlnTranslation("s44");
            }
        } else {
            votifier.getLogger().printlnTranslation("s33");
        }
    }
}

From source file:de.thkwalter.et.pulsmuster.SchaltwinkelRaumzeigermodulation.java

/**
 * Diese Methode bildet den Einsprungpunkt in die Berechnung der Schaltwinkel. 
 * //from   w  w  w .  ja  v  a 2  s.c  om
 * @param args Die Kommandozeilenparameter. Das Programm muss mit genau einem Kommandozeilenparameter aufgerufen werden, 
 * nmlich mit der Pulszahl.
 */
public static void main(String[] args) {
    // Falls das Programm nicht mit genau einem Parameter gestartet wurde, wird eine Fehlermeldung ausgegeben.
    if (args == null || args.length != 1) {
        System.out.println(
                "Das Programm muss mit genau einem Parameter gestartet werden, nmlich mit der Pulszahl!");
    }

    // Falls das Programm mit genau einem Programm gestartet wurde, ...
    else {
        // Das erste Kommandozeilenargument wird in die Pulszahl umgewandelt.
        int pulszahl = Integer.MIN_VALUE;
        try {
            pulszahl = Integer.parseInt(args[0]);
        } catch (NumberFormatException e) {
            System.out.println("Der Parameter muss eine ");
        }

        if (pulszahl < 0) {
            System.out.println("Der Parameter");
        }

        else {
            // Die Schaltwinkel werden berechnet.
            SchaltwinkelRaumzeigermodulation schaltwinkelRaumzeigermodulation = new SchaltwinkelRaumzeigermodulation(
                    pulszahl);

            // Die berechneten Schaltwinkel werden gelesen und auf der Kommandozeile ausgegeben.
            for (double schaltwinkel : schaltwinkelRaumzeigermodulation.getSchaltwinkel()) {
                System.out.println(schaltwinkel);
            }
        }
    }
}

From source file:com.joliciel.lefff.Lefff.java

/**
 * @param args//from  w w w. ja  v  a 2  s . c o m
 */
public static void main(String[] args) throws Exception {
    long startTime = (new Date()).getTime();
    String command = args[0];

    String memoryBaseFilePath = "";
    String lefffFilePath = "";
    String posTagSetPath = "";
    String posTagMapPath = "";
    String word = null;
    List<String> categories = null;
    int startLine = -1;
    int stopLine = -1;

    boolean firstArg = true;
    for (String arg : args) {
        if (firstArg) {
            firstArg = false;
            continue;
        }
        int equalsPos = arg.indexOf('=');
        String argName = arg.substring(0, equalsPos);
        String argValue = arg.substring(equalsPos + 1);
        if (argName.equals("memoryBase"))
            memoryBaseFilePath = argValue;
        else if (argName.equals("lefffFile"))
            lefffFilePath = argValue;
        else if (argName.equals("startLine"))
            startLine = Integer.parseInt(argValue);
        else if (argName.equals("stopLine"))
            stopLine = Integer.parseInt(argValue);
        else if (argName.equals("posTagSet"))
            posTagSetPath = argValue;
        else if (argName.equals("posTagMap"))
            posTagMapPath = argValue;
        else if (argName.equals("word"))
            word = argValue;
        else if (argName.equals("categories")) {
            String[] parts = argValue.split(",");
            categories = new ArrayList<String>();
            for (String part : parts) {
                categories.add(part);
            }
        } else
            throw new RuntimeException("Unknown argument: " + argName);
    }

    final LefffServiceLocator locator = new LefffServiceLocator();
    locator.setDataSourcePropertiesFile("jdbc-live.properties");

    TalismaneServiceLocator talismaneServiceLocator = TalismaneServiceLocator.getInstance();

    final LefffService lefffService = locator.getLefffService();
    if (command.equals("load")) {
        if (lefffFilePath.length() == 0)
            throw new RuntimeException("Required argument: lefffFile");
        final LefffLoader loader = lefffService.getLefffLoader();
        File file = new File(lefffFilePath);
        if (startLine > 0)
            loader.setStartLine(startLine);
        if (stopLine > 0)
            loader.setStopLine(stopLine);

        loader.LoadFile(file);
    } else if (command.equals("serialiseBase")) {
        if (memoryBaseFilePath.length() == 0)
            throw new RuntimeException("Required argument: memoryBase");
        if (posTagSetPath.length() == 0)
            throw new RuntimeException("Required argument: posTagSet");
        if (posTagMapPath.length() == 0)
            throw new RuntimeException("Required argument: posTagMap");

        PosTaggerServiceLocator posTaggerServiceLocator = talismaneServiceLocator.getPosTaggerServiceLocator();
        PosTaggerService posTaggerService = posTaggerServiceLocator.getPosTaggerService();
        File posTagSetFile = new File(posTagSetPath);
        PosTagSet posTagSet = posTaggerService.getPosTagSet(posTagSetFile);

        File posTagMapFile = new File(posTagMapPath);
        LefffPosTagMapper posTagMapper = lefffService.getPosTagMapper(posTagMapFile, posTagSet);

        Map<PosTagSet, LefffPosTagMapper> posTagMappers = new HashMap<PosTagSet, LefffPosTagMapper>();
        posTagMappers.put(posTagSet, posTagMapper);

        LefffMemoryLoader loader = new LefffMemoryLoader();
        LefffMemoryBase memoryBase = loader.loadMemoryBaseFromDatabase(lefffService, posTagMappers, categories);
        File memoryBaseFile = new File(memoryBaseFilePath);
        memoryBaseFile.delete();
        loader.serializeMemoryBase(memoryBase, memoryBaseFile);
    } else if (command.equals("deserialiseBase")) {
        if (memoryBaseFilePath.length() == 0)
            throw new RuntimeException("Required argument: memoryBase");

        LefffMemoryLoader loader = new LefffMemoryLoader();
        File memoryBaseFile = new File(memoryBaseFilePath);
        LefffMemoryBase memoryBase = loader.deserializeMemoryBase(memoryBaseFile);

        String[] testWords = new String[] { "avoir" };
        if (word != null) {
            testWords = word.split(",");
        }

        for (String testWord : testWords) {
            Set<PosTag> possiblePosTags = memoryBase.findPossiblePosTags(testWord);
            LOG.debug("##### PosTags for '" + testWord + "': " + possiblePosTags.size());
            int i = 1;
            for (PosTag posTag : possiblePosTags) {
                LOG.debug("### PosTag " + (i++) + ":" + posTag);
            }

            List<? extends LexicalEntry> entriesForWord = memoryBase.getEntries(testWord);
            LOG.debug("##### Entries for '" + testWord + "': " + entriesForWord.size());
            i = 1;
            for (LexicalEntry entry : entriesForWord) {
                LOG.debug("### Entry " + (i++) + ":" + entry.getWord());
                LOG.debug("Category " + entry.getCategory());
                LOG.debug("Predicate " + entry.getPredicate());
                LOG.debug("Lemma " + entry.getLemma());
                LOG.debug("Morphology " + entry.getMorphology());
            }

            List<? extends LexicalEntry> entriesForLemma = memoryBase.getEntriesForLemma(testWord, "");
            LOG.debug("##### Entries for '" + testWord + "' lemma: " + entriesForLemma.size());
            for (LexicalEntry entry : entriesForLemma) {
                LOG.debug("### Entry " + entry.getWord());
                LOG.debug("Category " + entry.getCategory());
                LOG.debug("Predicate " + entry.getPredicate());
                LOG.debug("Lemma " + entry.getLemma());
                LOG.debug("Morphology " + entry.getMorphology());
                for (PredicateArgument argument : entry.getPredicateArguments()) {
                    LOG.debug("Argument: " + argument.getFunction() + ",Optional? " + argument.isOptional());
                    for (String realisation : argument.getRealisations()) {
                        LOG.debug("Realisation: " + realisation);
                    }
                }
            }
        }

    } else {
        System.out.println("Usage : Lefff load filepath");
    }
    long endTime = (new Date()).getTime() - startTime;
    LOG.debug("Total runtime: " + ((double) endTime / 1000) + " seconds");
}

From source file:dhtaccess.benchmark.LatencyMeasure.java

public static void main(String[] args) {
    boolean details = false;
    int repeats = DEFAULT_REPEATS;
    boolean doPut = true;

    // parse options
    Options options = new Options();
    options.addOption("h", "help", false, "print help");
    options.addOption("d", "details", false, "requests secret hash and TTL");
    options.addOption("r", "repeats", true, "number of requests");
    options.addOption("n", "no-put", false, "does not put");

    CommandLineParser parser = new PosixParser();
    CommandLine cmd = null;//from   w  w w . j  a  va2 s  .  c o  m
    try {
        cmd = parser.parse(options, args);
    } catch (ParseException e) {
        System.out.println("There is an invalid option.");
        e.printStackTrace();
        System.exit(1);
    }

    String optVal;
    if (cmd.hasOption('h')) {
        usage(COMMAND);
        System.exit(1);
    }
    if (cmd.hasOption('d')) {
        details = true;
    }
    optVal = cmd.getOptionValue('r');
    if (optVal != null) {
        repeats = Integer.parseInt(optVal);
    }
    if (cmd.hasOption('n')) {
        doPut = false;
    }

    args = cmd.getArgs();

    // parse arguments
    if (args.length < 1) {
        usage(COMMAND);
        System.exit(1);
    }

    // prepare for RPC
    int numAccessor = args.length;
    DHTAccessor[] accessorArray = new DHTAccessor[numAccessor];
    try {
        for (int i = 0; i < numAccessor; i++) {
            accessorArray[i] = new DHTAccessor(args[i]);
        }
    } catch (MalformedURLException e) {
        e.printStackTrace();
        System.exit(1);
    }

    // generate key prefix
    Random rnd = new Random(System.currentTimeMillis());

    StringBuilder sb = new StringBuilder();
    for (int i = 0; i < KEY_PREFIX_LENGTH; i++) {
        sb.append((char) ('a' + rnd.nextInt(26)));
    }
    String keyPrefix = sb.toString();
    String valuePrefix = VALUE_PREFIX;

    // benchmarking
    System.out.println("Repeats " + repeats + " times.");

    if (doPut) {
        System.out.println("Putting: " + keyPrefix + "<number>");

        for (int i = 0; i < repeats; i++) {
            byte[] key = null, value = null;
            try {
                key = (keyPrefix + i).getBytes(ENCODE);
                value = (valuePrefix + i).getBytes(ENCODE);
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
                System.exit(1);
            }

            int accIndex = rnd.nextInt(numAccessor);
            DHTAccessor acc = accessorArray[accIndex];
            acc.put(key, value, TTL);
        }
    }

    System.out.println("Benchmarking by getting.");

    int count = 0;
    long startTime = System.currentTimeMillis();

    if (details) {
        for (int i = 0; i < repeats; i++) {
            byte[] key = null;
            try {
                key = (keyPrefix + i).getBytes(ENCODE);
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
                System.exit(1);
            }

            int accIndex = rnd.nextInt(numAccessor);
            DHTAccessor acc = accessorArray[accIndex];
            Set<DetailedGetResult> valueSet = acc.getDetails(key);
            if (valueSet != null && !valueSet.isEmpty()) {
                count++;
            }
        }
    } else {
        for (int i = 0; i < repeats; i++) {
            byte[] key = null;
            try {
                key = (keyPrefix + i).getBytes(ENCODE);
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
                System.exit(1);
            }

            int accIndex = rnd.nextInt(numAccessor);
            DHTAccessor acc = accessorArray[accIndex];
            Set<byte[]> valueSet = acc.get(key);
            if (valueSet != null && !valueSet.isEmpty()) {
                count++;
            }
        }
    }

    System.out.println(System.currentTimeMillis() - startTime + " msec.");
    System.out.println("Rate of successful gets: " + count + " / " + repeats);
}

From source file:com.ontotext.s4.SBTDemo.Main.java

public static void main(String[] args) {
    /*//from  w  ww  .  j a  v a2 s  . com
     * Read log4j properties file.
     */
    org.apache.log4j.PropertyConfigurator.configure(args.length >= 1 ? args[1] : DEFAULT_LOG4J_FILE);

    /*
     * Read properties file  List all annotated files. We should
     * use absolute path to the files
     */
    init(args);

    ProcessingDocuments processingDocuments = new ProcessingDocuments(
            programProperties.getProperty(PropertiesNames.S4_API_KEY),
            programProperties.getProperty(PropertiesNames.S4_API_PASS),
            programProperties.getProperty(PropertiesNames.RAW_FOLDER),
            programProperties.getProperty(PropertiesNames.ANNOTATED_FOLDER),
            programProperties.getProperty(PropertiesNames.SERVICE),
            programProperties.getProperty(PropertiesNames.MIME_TYPE),
            programProperties.getProperty(PropertiesNames.RESPONSE_FORMAT),
            Integer.parseInt(programProperties.getProperty(PropertiesNames.NUMBER_OF_THREADS)));

    processingDocuments.ProcessData();

    File directory = new File(programProperties.getProperty(PropertiesNames.ANNOTATED_FOLDER));
    listOfAllAnnotatedFiles = FileUtils.listFiles(directory, new RegexFileFilter("^(.*?)"),
            DirectoryFileFilter.DIRECTORY);

    RepoManager repoManager = new RepoManager(programProperties.getProperty(PropertiesNames.REPOSITORY_URL));
    JsonToRDF jsonToRdfParser = new JsonToRDF(programProperties.getProperty(PropertiesNames.MIME_TYPE),
            programProperties.getProperty(PropertiesNames.RDFIZE_FOLDER));

    for (File file : listOfAllAnnotatedFiles) {
        String fileContent = null;
        try {
            fileContent = FileUtils.readFileToString(file, "UTF-8");
        } catch (IOException e) {
            logger.error(e);
        }

        Model graph = jsonToRdfParser.wirteDataToRDF(fileContent, file.getName(),
                programProperties.getProperty(PropertiesNames.RDFIZE_FOLDER));
        try {
            repoManager.sendDataTOGraphDB(graph);
        } catch (RepositoryException e) {
            logger.error(e);
        }

    }

    repoManager.close();
}

From source file:org.ala.harvester.RawFileHarvestRunner.java

/**
* Main method//from w w w.  j a  v  a  2s .  co m
 *
 * @param args
*/
public static void main(String[] args) {
    // Get Spring context
    context = new ClassPathXmlApplicationContext("classpath*:spring.xml");
    //InfoSourceDAO infoSourceDAORO = (InfoSourceDAO) context.getBean("infoSourceDao");

    RawFileHarvestRunner hr = (RawFileHarvestRunner) context.getBean("rawFileHarvestRunner");

    if (args.length < 1) {
        System.out.println(
                "Please enter an info source ID to harvest OR enter \"all\" " + "to harvest all info sources");
        System.exit(-1);
    } else if (args[0].equalsIgnoreCase("all")) {
        logger.info("Harvesting all info sources...");
        List<Integer> infoSourceIds = hr.getAllIds();
        hr.harvest(infoSourceIds);
    } else {
        try {
            Integer infoSourceId = Integer.parseInt(args[0]);
            List<Integer> infoSourceIds = new ArrayList<Integer>();
            infoSourceIds.add(infoSourceId);
            hr.harvest(infoSourceIds);
        } catch (NumberFormatException ex) {
            logger.error("info source id was not recognised as a number: " + ex.getMessage());
        }
    }
}