Example usage for java.util Random nextInt

List of usage examples for java.util Random nextInt

Introduction

In this page you can find the example usage for java.util Random nextInt.

Prototype

public int nextInt(int bound) 

Source Link

Document

Returns a pseudorandom, uniformly distributed int value between 0 (inclusive) and the specified value (exclusive), drawn from this random number generator's sequence.

Usage

From source file:fsm.process.test.ProcessTest.java

public static void main(String args[]) throws Exception {
    try {//from   w w w .j a  va2  s  .com
        initDataBase();
        Integer auditorId1 = createOperator("wd", "13399999999");
        Integer auditorId2 = createOperator("lm", "13499999999");

        Integer orgId1 = createOrganization("", "", "100010", "10099900393");
        Integer orgId2 = createOrganization("?", "?", "100011", "10099900394");

        List<User> agents = new ArrayList<User>();

        Integer agentId1 = registerAgent("zs", "13511111111", orgId1, "001", "001001");
        agents.add(userDao.find(agentId1));
        Integer agentId2 = registerAgent("zs2", "13511111112", orgId1, "001", "001002");
        agents.add(userDao.find(agentId2));
        Integer agentId3 = registerAgent("zs3", "13511111113", orgId1, "001", "001003");
        agents.add(userDao.find(agentId3));
        Integer agentId4 = registerAgent("zs4", "13511111114", orgId1, "001", "001004");
        agents.add(userDao.find(agentId4));
        Integer agentId5 = registerAgent("zs5", "13511111115", orgId1, "002", "002001");
        agents.add(userDao.find(agentId5));
        Integer agentId6 = registerAgent("zs6", "13511111116", orgId1, "002", "002002");
        agents.add(userDao.find(agentId6));
        Integer agentId7 = registerAgent("zs7", "13511111117", orgId1, "002", "002003");
        agents.add(userDao.find(agentId7));

        Integer agentId8 = registerAgent("zs8", "13511111118", orgId2, "001", "001001");
        agents.add(userDao.find(agentId8));
        Integer agentId9 = registerAgent("zs9", "13511111119", orgId2, "001", "001002");
        agents.add(userDao.find(agentId9));
        Integer agentId10 = registerAgent("zs10", "13511111120", orgId2, "001", "001003");
        agents.add(userDao.find(agentId10));
        Integer agentId11 = registerAgent("zs11", "13511111121", orgId2, "001", "001004");
        agents.add(userDao.find(agentId11));
        Integer agentId12 = registerAgent("zs12", "13511111122", orgId2, "002", "002001");
        agents.add(userDao.find(agentId12));
        Integer agentId13 = registerAgent("zs13", "13511111123", orgId2, "002", "002002");
        agents.add(userDao.find(agentId13));
        Integer agentId14 = registerAgent("zs14", "13511111124", orgId2, "002", "002003");
        agents.add(userDao.find(agentId14));

        auditAgent(agentId1, true);
        auditAgent(agentId2, false);
        auditAgent(agentId3, true);
        auditAgent(agentId4, false);
        auditAgent(agentId5, true);
        auditAgent(agentId6, true);
        auditAgent(agentId7, true);
        auditAgent(agentId8, true);
        auditAgent(agentId9, true);
        auditAgent(agentId10, true);
        auditAgent(agentId11, true);
        auditAgent(agentId12, true);
        auditAgent(agentId13, true);
        auditAgent(agentId14, true);

        reApplyAgent(agentId2);
        reApplyAgent(agentId4);

        auditAgent(agentId2, true);
        auditAgent(agentId4, true);

        Integer proId1 = createProduct("", agentId1, "001001", orgId1, Product.TYPE_XINYONG,
                ";;",
                "?;?;?");
        addProductAction(1, proId1, "", "?", 5);
        addProductAction(2, proId1, "", "?", 7);
        addProductAction(3, proId1, "", "??", 3);
        applyAuditProduct(proId1);
        auditProduct(proId1, true);

        Integer proId2 = createProduct("", agentId2, "002001", orgId1, Product.TYPE_XIAOFEI,
                ";;",
                "?;?;?");
        addProductAction(1, proId2, "", "?", 6);
        addProductAction(2, proId2, "", "?", 4);
        addProductAction(3, proId2, "", "??", 1);
        applyAuditProduct(proId2);
        auditProduct(proId2, false);
        applyAuditProduct(proId2);
        auditProduct(proId2, true);

        String[] steps = { "?", "?", "?",
                "?", "?", "?" };
        String[] profits = { "", "???", "", "??",
                "?" };
        String[] requires = { "?", "???",
                "??", "?2000", "?",
                "?" };

        for (User agent : agents) {
            Random ran = new Random();

            String profitstr = profits[ran.nextInt(100) % 5] + ";" + profits[ran.nextInt(100) % 5] + ";"
                    + profits[ran.nextInt(100) % 5];
            String requirestr = requires[ran.nextInt(100) % 6] + ";" + requires[ran.nextInt(100) % 6] + ";"
                    + requires[ran.nextInt(100) % 6];

            Integer proId_fangdai = createProduct("", agent.getId(), agent.getCity(),
                    agent.getOrganizationId(), Product.TYPE_HOUSE, profitstr, requirestr);

            int step = ran.nextInt(6);
            for (int i = 0; i < step; i++) {
                addProductAction((i + 1), proId_fangdai, "" + i, steps[i], ran.nextInt(10));
            }
            applyAuditProduct(proId_fangdai);
            auditProduct(proId_fangdai, true);

            profitstr = profits[ran.nextInt(100) % 5] + ";" + profits[ran.nextInt(100) % 5] + ";"
                    + profits[ran.nextInt(100) % 5];
            requirestr = requires[ran.nextInt(100) % 6] + ";" + requires[ran.nextInt(100) % 6] + ";"
                    + requires[ran.nextInt(100) % 6];
            Integer proId_jingyingdai = createProduct("??", agent.getId(), agent.getCity(),
                    agent.getOrganizationId(), Product.TYPE_JINGYING, profitstr, requirestr);
            step = ran.nextInt(6);
            for (int i = 0; i < step; i++) {
                addProductAction((i + 1), proId_jingyingdai, "" + i, steps[i], ran.nextInt(10));
            }
            applyAuditProduct(proId_jingyingdai);
            auditProduct(proId_jingyingdai, true);

            profitstr = profits[ran.nextInt(100) % 5] + ";" + profits[ran.nextInt(100) % 5] + ";"
                    + profits[ran.nextInt(100) % 5];
            requirestr = requires[ran.nextInt(100) % 6] + ";" + requires[ran.nextInt(100) % 6] + ";"
                    + requires[ran.nextInt(100) % 6];
            Integer proId_chedai = createProduct("", agent.getId(), agent.getCity(),
                    agent.getOrganizationId(), Product.TYPE_CAR, profitstr, requirestr);
            step = ran.nextInt(6);
            for (int i = 0; i < step; i++) {
                addProductAction((i + 1), proId_chedai, "" + i, steps[i], ran.nextInt(10));
            }
            applyAuditProduct(proId_chedai);
            auditProduct(proId_chedai, true);

            profitstr = profits[ran.nextInt(100) % 5] + ";" + profits[ran.nextInt(100) % 5] + ";"
                    + profits[ran.nextInt(100) % 5];
            requirestr = requires[ran.nextInt(100) % 6] + ";" + requires[ran.nextInt(100) % 6] + ";"
                    + requires[ran.nextInt(100) % 6];
            Integer proId_diyadai = createProduct("", agent.getId(), agent.getCity(),
                    agent.getOrganizationId(), Product.TYPE_DIYA, profitstr, requirestr);
            step = ran.nextInt(6);
            for (int i = 0; i < step; i++) {
                addProductAction((i + 1), proId_diyadai, "" + i, steps[i], ran.nextInt(10));
            }
            applyAuditProduct(proId_diyadai);
            auditProduct(proId_diyadai, true);

            profitstr = profits[ran.nextInt(100) % 5] + ";" + profits[ran.nextInt(100) % 5] + ";"
                    + profits[ran.nextInt(100) % 5];
            requirestr = requires[ran.nextInt(100) % 6] + ";" + requires[ran.nextInt(100) % 6] + ";"
                    + requires[ran.nextInt(100) % 6];
            Integer proId_xiaofeidai = createProduct("", agent.getId(), agent.getCity(),
                    agent.getOrganizationId(), Product.TYPE_XIAOFEI, profitstr, requirestr);
            step = ran.nextInt(6);
            for (int i = 0; i < step; i++) {
                addProductAction((i + 1), proId_xiaofeidai, "" + i, steps[i], ran.nextInt(10));
            }
            applyAuditProduct(proId_xiaofeidai);
            auditProduct(proId_xiaofeidai, true);

            profitstr = profits[ran.nextInt(100) % 5] + ";" + profits[ran.nextInt(100) % 5] + ";"
                    + profits[ran.nextInt(100) % 5];
            requirestr = requires[ran.nextInt(100) % 6] + ";" + requires[ran.nextInt(100) % 6] + ";"
                    + requires[ran.nextInt(100) % 6];
            Integer proId_xinyongdai = createProduct("", agent.getId(), agent.getCity(),
                    agent.getOrganizationId(), Product.TYPE_XINYONG, profitstr, requirestr);
            step = ran.nextInt(6);
            for (int i = 0; i < step; i++) {
                addProductAction((i + 1), proId_xinyongdai, "" + i, steps[i], ran.nextInt(10));
            }
            applyAuditProduct(proId_xinyongdai);
            auditProduct(proId_xinyongdai, true);
        }

        Integer userId1 = userRegister("wangxiaopang", "13899977889");
        Integer userId2 = userRegister("wangxiaoshuai", "13899977890");

        Integer operationId1 = applyOperation(userId1, Product.TYPE_XINYONG, 20, 24, "001", "001001");
        updateOperation(operationId1, proId1, agentId1);

        Integer operationId2 = applyOperation(userId2, Product.TYPE_XIAOFEI, 15, 120, "002", "002001");
        updateOperation(operationId2, proId2, agentId2);

        auditOperation(operationId1, true);
        auditOperation(operationId2, false);
        reApplyOperation(operationId2);
        auditOperation(operationId2, true);

        takeoverOperation(operationId1, agentId1);
        takeoverOperation(operationId2, agentId2);
        handleOperation(operationId1);
        handleOperation(operationId2);

    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        System.exit(0);
    }

}

From source file:io.druid.examples.rabbitmq.RabbitMQProducerMain.java

public static void main(String[] args) throws Exception {
    // We use a List to keep track of option insertion order. See below.
    final List<Option> optionList = new ArrayList<Option>();

    optionList.add(OptionBuilder.withLongOpt("help").withDescription("display this help message").create("h"));
    optionList.add(OptionBuilder.withLongOpt("hostname").hasArg()
            .withDescription("the hostname of the AMQP broker [defaults to AMQP library default]").create("b"));
    optionList.add(OptionBuilder.withLongOpt("port").hasArg()
            .withDescription("the port of the AMQP broker [defaults to AMQP library default]").create("n"));
    optionList.add(OptionBuilder.withLongOpt("username").hasArg()
            .withDescription("username to connect to the AMQP broker [defaults to AMQP library default]")
            .create("u"));
    optionList.add(OptionBuilder.withLongOpt("password").hasArg()
            .withDescription("password to connect to the AMQP broker [defaults to AMQP library default]")
            .create("p"));
    optionList.add(OptionBuilder.withLongOpt("vhost").hasArg()
            .withDescription("name of virtual host on the AMQP broker [defaults to AMQP library default]")
            .create("v"));
    optionList.add(OptionBuilder.withLongOpt("exchange").isRequired().hasArg()
            .withDescription("name of the AMQP exchange [required - no default]").create("e"));
    optionList.add(OptionBuilder.withLongOpt("key").hasArg()
            .withDescription("the routing key to use when sending messages [default: 'default.routing.key']")
            .create("k"));
    optionList.add(OptionBuilder.withLongOpt("type").hasArg()
            .withDescription("the type of exchange to create [default: 'topic']").create("t"));
    optionList.add(OptionBuilder.withLongOpt("durable")
            .withDescription("if set, a durable exchange will be declared [default: not set]").create("d"));
    optionList.add(OptionBuilder.withLongOpt("autodelete")
            .withDescription("if set, an auto-delete exchange will be declared [default: not set]")
            .create("a"));
    optionList.add(OptionBuilder.withLongOpt("single")
            .withDescription("if set, only a single message will be sent [default: not set]").create("s"));
    optionList.add(OptionBuilder.withLongOpt("start").hasArg()
            .withDescription("time to use to start sending messages from [default: 2010-01-01T00:00:00]")
            .create());// www.  j  av  a 2 s.  c  om
    optionList.add(OptionBuilder.withLongOpt("stop").hasArg().withDescription(
            "time to use to send messages until (format: '2013-07-18T23:45:59') [default: current time]")
            .create());
    optionList.add(OptionBuilder.withLongOpt("interval").hasArg()
            .withDescription("the interval to add to the timestamp between messages in seconds [default: 10]")
            .create());
    optionList.add(OptionBuilder.withLongOpt("delay").hasArg()
            .withDescription("the delay between sending messages in milliseconds [default: 100]").create());

    // An extremely silly hack to maintain the above order in the help formatting.
    HelpFormatter formatter = new HelpFormatter();
    // Add a comparator to the HelpFormatter using the ArrayList above to sort by insertion order.
    formatter.setOptionComparator(new Comparator() {
        @Override
        public int compare(Object o1, Object o2) {
            // I know this isn't fast, but who cares! The list is short.
            return optionList.indexOf(o1) - optionList.indexOf(o2);
        }
    });

    // Now we can add all the options to an Options instance. This is dumb!
    Options options = new Options();
    for (Option option : optionList) {
        options.addOption(option);
    }

    CommandLine cmd = null;

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

    } catch (ParseException e) {
        formatter.printHelp("RabbitMQProducerMain", e.getMessage(), options, null);
        System.exit(1);
    }

    if (cmd.hasOption("h")) {
        formatter.printHelp("RabbitMQProducerMain", options);
        System.exit(2);
    }

    ConnectionFactory factory = new ConnectionFactory();

    if (cmd.hasOption("b")) {
        factory.setHost(cmd.getOptionValue("b"));
    }
    if (cmd.hasOption("u")) {
        factory.setUsername(cmd.getOptionValue("u"));
    }
    if (cmd.hasOption("p")) {
        factory.setPassword(cmd.getOptionValue("p"));
    }
    if (cmd.hasOption("v")) {
        factory.setVirtualHost(cmd.getOptionValue("v"));
    }
    if (cmd.hasOption("n")) {
        factory.setPort(Integer.parseInt(cmd.getOptionValue("n")));
    }

    String exchange = cmd.getOptionValue("e");
    String routingKey = "default.routing.key";
    if (cmd.hasOption("k")) {
        routingKey = cmd.getOptionValue("k");
    }

    boolean durable = cmd.hasOption("d");
    boolean autoDelete = cmd.hasOption("a");
    String type = cmd.getOptionValue("t", "topic");
    boolean single = cmd.hasOption("single");
    int interval = Integer.parseInt(cmd.getOptionValue("interval", "10"));
    int delay = Integer.parseInt(cmd.getOptionValue("delay", "100"));

    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
    Date stop = sdf.parse(cmd.getOptionValue("stop", sdf.format(new Date())));

    Random r = new Random();
    Calendar timer = Calendar.getInstance();
    timer.setTime(sdf.parse(cmd.getOptionValue("start", "2010-01-01T00:00:00")));

    String msg_template = "{\"utcdt\": \"%s\", \"wp\": %d, \"gender\": \"%s\", \"age\": %d}";

    Connection connection = factory.newConnection();
    Channel channel = connection.createChannel();

    channel.exchangeDeclare(exchange, type, durable, autoDelete, null);

    do {
        int wp = (10 + r.nextInt(90)) * 100;
        String gender = r.nextBoolean() ? "male" : "female";
        int age = 20 + r.nextInt(70);

        String line = String.format(msg_template, sdf.format(timer.getTime()), wp, gender, age);

        channel.basicPublish(exchange, routingKey, null, line.getBytes());

        System.out.println("Sent message: " + line);

        timer.add(Calendar.SECOND, interval);

        Thread.sleep(delay);
    } while ((!single && stop.after(timer.getTime())));

    connection.close();
}

From source file:com.heliosapm.tsdblite.metric.Trace.java

@SuppressWarnings("javadoc")
public static void main(String[] args) {
    log("Trace Test");
    Map<String, String> tags = new HashMap<String, String>(4);
    tags.put("host", "localhost");
    tags.put("app", "test");
    tags.put("cpu", "" + 1);
    tags.put("type", "combined");
    final Trace trace = new Trace("sys.cpu", tags, false, 34, -1, System.currentTimeMillis());
    log("toString: " + trace);
    String json = JSON.serializeToString(trace);
    log("JSON: " + json);
    final Trace t = JSON.parseToObject(json, Trace.class);
    log("fromJson: " + t);
    log("=====================================");
    final Trace[] traces = new Trace[Constants.CORES];
    final Random r = new Random(System.currentTimeMillis());
    for (int i = 0; i < Constants.CORES; i++) {
        tags = new HashMap<String, String>(4);
        tags.put("host", "localhost");
        tags.put("app", "test");
        tags.put("cpu", "" + i);
        tags.put("type", "combined");
        traces[i] = new Trace("sys.cpu", tags, false, Math.abs(r.nextInt(100)), -1, System.currentTimeMillis());
        log("toString:" + traces[i]);
    }/* w  w w .  j  a  va  2s.com*/
    json = JSON.serializeToString(traces);
    log("JSON: " + json);
    Trace[] ts = JSON.parseToObject(json, Trace[].class);
    for (Trace x : ts) {
        log("fromJson: " + x);
    }
}

From source file:flink.iso8583.example.Client.java

public static void main(String[] args) throws Exception {
    Random rng = new Random(System.currentTimeMillis());
    log.debug("Reading config");
    mfact = ConfigParser.createFromClasspathConfig("flink/iso8583/example/config.xml");
    mfact.setAssignDate(true);//from  w ww. j av a2  s  .c  om
    mfact.setTraceNumberGenerator(new SimpleTraceGenerator((int) (System.currentTimeMillis() % 10000)));
    log.debug("Connecting to server");
    Socket sock = new Socket("localhost", 9999);
    //Send 10 messages, then wait for the responses
    Client reader = new Client(sock);
    reader.start();
    for (int i = 0; i < 10; i++) {
        IsoMessage req = mfact.newMessage(0x200);
        req.setValue(4, amounts[rng.nextInt(amounts.length)], IsoType.AMOUNT, 0);
        req.setValue(12, req.getObjectValue(7), IsoType.TIME, 0);
        req.setValue(13, req.getObjectValue(7), IsoType.DATE4, 0);
        req.setValue(15, req.getObjectValue(7), IsoType.DATE4, 0);
        req.setValue(17, req.getObjectValue(7), IsoType.DATE4, 0);
        req.setValue(37, new Long(System.currentTimeMillis() % 1000000), IsoType.NUMERIC, 12);
        req.setValue(41, data[rng.nextInt(data.length)], IsoType.ALPHA, 16);
        req.setValue(48, data[rng.nextInt(data.length)], IsoType.LLLVAR, 0);
        pending.put(req.getField(11).toString(), req);
        log.debug("Sending request " + req.getField(11));
        req.write(sock.getOutputStream(), 2);
    }
    log.debug("Waiting for responses");
    while (pending.size() > 0 && sock.isConnected()) {
        sleep(500);
    }
    reader.interrupt();
    sock.close();
    log.debug("DONE.");
}

From source file:PinotThroughput.java

@SuppressWarnings("InfiniteLoopStatement")
public static void main(String[] args) throws Exception {
    final int numQueries = QUERIES.length;
    final Random random = new Random(RANDOM_SEED);
    final AtomicInteger counter = new AtomicInteger(0);
    final AtomicLong totalResponseTime = new AtomicLong(0L);
    final ExecutorService executorService = Executors.newFixedThreadPool(NUM_CLIENTS);

    for (int i = 0; i < NUM_CLIENTS; i++) {
        executorService.submit(new Runnable() {
            @Override/* w w w . j  av a  2 s . c o  m*/
            public void run() {
                try (CloseableHttpClient client = HttpClients.createDefault()) {
                    HttpPost post = new HttpPost("http://localhost:8099/query");
                    CloseableHttpResponse res;
                    while (true) {
                        String query = QUERIES[random.nextInt(numQueries)];
                        post.setEntity(new StringEntity("{\"pql\":\"" + query + "\"}"));
                        long start = System.currentTimeMillis();
                        res = client.execute(post);
                        res.close();
                        counter.getAndIncrement();
                        totalResponseTime.getAndAdd(System.currentTimeMillis() - start);
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    long startTime = System.currentTimeMillis();
    while (true) {
        Thread.sleep(REPORT_INTERVAL_MILLIS);
        double timePassedSeconds = ((double) (System.currentTimeMillis() - startTime)) / MILLIS_PER_SECOND;
        int count = counter.get();
        double avgResponseTime = ((double) totalResponseTime.get()) / count;
        System.out.println("Time Passed: " + timePassedSeconds + "s, Query Executed: " + count + ", QPS: "
                + count / timePassedSeconds + ", Avg Response Time: " + avgResponseTime + "ms");
    }
}

From source file:j8583.example.Client.java

public static void main(String[] args) throws Exception {
    Random rng = new Random(System.currentTimeMillis());
    log.debug("Reading config");
    mfact = ConfigParser.createFromClasspathConfig("j8583/example/config.xml");
    mfact.setAssignDate(true);//from  w  w w  . java2s .c o m
    mfact.setTraceNumberGenerator(new SimpleTraceGenerator((int) (System.currentTimeMillis() % 10000)));
    System.err.println("Connecting to server");
    Socket sock = new Socket("localhost", 9999);
    // Send 10 messages, then wait for the responses
    Client client = new Client(sock);
    Thread reader = new Thread(client, "j8583-client");
    reader.start();
    for (int i = 0; i < 10; i++) {
        IsoMessage req = mfact.newMessage(0x200);
        req.setValue(4, amounts[rng.nextInt(amounts.length)], IsoType.AMOUNT, 0);
        req.setValue(12, req.getObjectValue(7), IsoType.TIME, 0);
        req.setValue(13, req.getObjectValue(7), IsoType.DATE4, 0);
        req.setValue(15, req.getObjectValue(7), IsoType.DATE4, 0);
        req.setValue(17, req.getObjectValue(7), IsoType.DATE4, 0);
        req.setValue(37, System.currentTimeMillis() % 1000000, IsoType.NUMERIC, 12);
        req.setValue(41, data[rng.nextInt(data.length)], IsoType.ALPHA, 16);
        req.setValue(48, data[rng.nextInt(data.length)], IsoType.LLLVAR, 0);
        pending.put(req.getField(11).toString(), req);
        System.err.println(String.format("Sending request %s", req.getField(11)));
        req.write(sock.getOutputStream(), 2);
    }
    log.debug("Waiting for responses");
    while (pending.size() > 0 && sock.isConnected()) {
        Thread.sleep(500);
    }
    client.stop();
    reader.interrupt();
    log.debug("DONE.");
}

From source file:edu.umn.cs.spatialHadoop.operations.KNN.java

public static void main(String[] args) throws IOException {
    final OperationsParams params = new OperationsParams(new GenericOptionsParser(args));
    Path[] paths = params.getPaths();
    if (paths.length <= 1 && !params.checkInput()) {
        printUsage();//w  w  w .  java 2 s.c  o  m
        System.exit(1);
    }
    if (paths.length > 1 && !params.checkInputOutput()) {
        printUsage();
        System.exit(1);
    }
    final Path inputFile = params.getInputPath();
    int count = params.getInt("count", 1);
    double closeness = params.getFloat("closeness", -1.0f);
    final Point[] queryPoints = closeness < 0 ? params.getShapes("point", new Point()) : new Point[count];
    final FileSystem fs = inputFile.getFileSystem(params);
    final int k = params.getInt("k", 1);
    int concurrency = params.getInt("concurrency", 100);
    if (k == 0) {
        LOG.warn("k = 0");
    }

    if (queryPoints.length == 0) {
        printUsage();
        throw new RuntimeException("Illegal arguments");
    }
    final Path outputPath = paths.length > 1 ? paths[1] : null;

    if (closeness >= 0) {
        // Get query points according to its closeness to grid intersections
        GlobalIndex<Partition> gindex = SpatialSite.getGlobalIndex(fs, inputFile);
        long seed = params.getLong("seed", System.currentTimeMillis());
        Random random = new Random(seed);
        for (int i = 0; i < count; i++) {
            int i_block = random.nextInt(gindex.size());
            int direction = random.nextInt(4);
            // Generate a point in the given direction
            // Get center point (x, y)
            Iterator<Partition> iterator = gindex.iterator();
            while (i_block-- >= 0)
                iterator.next();
            Partition partition = iterator.next();
            double cx = (partition.x1 + partition.x2) / 2;
            double cy = (partition.y1 + partition.y2) / 2;
            double cw = partition.x2 - partition.x1;
            double ch = partition.y2 - partition.y1;
            int signx = ((direction & 1) == 0) ? 1 : -1;
            int signy = ((direction & 2) == 1) ? 1 : -1;
            double x = cx + cw * closeness / 2 * signx;
            double y = cy + ch * closeness / 2 * signy;
            queryPoints[i] = new Point(x, y);
        }
    }

    final BooleanWritable exceptionHappened = new BooleanWritable();

    Thread.UncaughtExceptionHandler h = new Thread.UncaughtExceptionHandler() {
        public void uncaughtException(Thread th, Throwable ex) {
            ex.printStackTrace();
            exceptionHappened.set(true);
        }
    };

    // Run each query in a separate thread
    final Vector<Thread> threads = new Vector<Thread>();
    for (int i = 0; i < queryPoints.length; i++) {
        Thread thread = new Thread() {
            @Override
            public void run() {
                try {
                    Point query_point = queryPoints[threads.indexOf(this)];
                    OperationsParams newParams = new OperationsParams(params);
                    OperationsParams.setShape(newParams, "point", query_point);
                    Job job = knn(inputFile, outputPath, params);
                } catch (IOException e) {
                    e.printStackTrace();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } catch (ClassNotFoundException e) {
                    e.printStackTrace();
                }
            }
        };
        thread.setUncaughtExceptionHandler(h);
        threads.add(thread);
    }

    long t1 = System.currentTimeMillis();
    do {
        // Ensure that there is at least MaxConcurrentThreads running
        int i = 0;
        while (i < concurrency && i < threads.size()) {
            Thread.State state = threads.elementAt(i).getState();
            if (state == Thread.State.TERMINATED) {
                // Thread already terminated, remove from the queue
                threads.remove(i);
            } else if (state == Thread.State.NEW) {
                // Start the thread and move to next one
                threads.elementAt(i++).start();
            } else {
                // Thread is still running, skip over it
                i++;
            }
        }
        if (!threads.isEmpty()) {
            try {
                // Sleep for 10 seconds or until the first thread terminates
                threads.firstElement().join(10000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    } while (!threads.isEmpty());
    long t2 = System.currentTimeMillis();
    if (exceptionHappened.get())
        throw new RuntimeException("Not all jobs finished correctly");

    System.out.println("Time for " + queryPoints.length + " jobs is " + (t2 - t1) + " millis");
    System.out.println("Total iterations: " + TotalIterations);
}

From source file:edu.umn.cs.sthadoop.trajectory.KNNDTW.java

public static void main(String[] args) throws IOException {

    args = new String[10];
    args[0] = "/export/scratch/mntgData/geolifeGPS/geolife_Trajectories_1.3/HDFS/index_geolife/yyyy-MM/2008-05";
    args[1] = "/export/scratch/mntgData/geolifeGPS/geolife_Trajectories_1.3/HDFS/knn-dis-result";
    args[2] = "shape:edu.umn.cs.sthadoop.trajectory.GeolifeTrajectory";
    args[3] = "interval:2008-05-01,2008-05-30";
    args[4] = "time:month";
    args[5] = "k:1";
    args[6] = "traj:39.9119983,116.606835;39.9119783,116.6065483;39.9119599,116.6062649;39.9119416,116.6059899;39.9119233,116.6057282;39.9118999,116.6054783;39.9118849,116.6052366;39.9118666,116.6050099;39.91185,116.604775;39.9118299,116.604525;39.9118049,116.6042649;39.91177,116.6040166;39.9117516,116.6037583;39.9117349,116.6035066;39.9117199,116.6032666;39.9117083,116.6030232;39.9117,116.6027566;39.91128,116.5969383;39.9112583,116.5966766;39.9112383,116.5964232;39.9112149,116.5961699;39.9111933,116.5959249;39.9111716,116.5956883";
    args[7] = "-overwrite";
    args[8] = "-local";// "-no-local";
    args[9] = "point:39.9119983,116.606835";

    final OperationsParams params = new OperationsParams(new GenericOptionsParser(args));
    Path[] paths = params.getPaths();
    if (paths.length <= 1 && !params.checkInput()) {
        printUsage();//from  w  w  w  .ja  v  a 2 s .co  m
        System.exit(1);
    }
    if (paths.length > 1 && !params.checkInputOutput()) {
        printUsage();
        System.exit(1);
    }
    final Path inputFile = params.getInputPath();
    int count = params.getInt("count", 1);
    double closeness = params.getFloat("closeness", -1.0f);
    final Point[] queryPoints = closeness < 0 ? params.getShapes("point", new Point()) : new Point[count];
    final FileSystem fs = inputFile.getFileSystem(params);
    final int k = params.getInt("k", 1);
    int concurrency = params.getInt("concurrency", 100);
    if (k == 0) {
        LOG.warn("k = 0");
    }

    if (queryPoints.length == 0) {
        printUsage();
        throw new RuntimeException("Illegal arguments");
    }
    final Path outputPath = paths.length > 1 ? paths[1] : null;

    if (closeness >= 0) {
        // Get query points according to its closeness to grid intersections
        GlobalIndex<Partition> gindex = SpatialSite.getGlobalIndex(fs, inputFile);
        long seed = params.getLong("seed", System.currentTimeMillis());
        Random random = new Random(seed);
        for (int i = 0; i < count; i++) {
            int i_block = random.nextInt(gindex.size());
            int direction = random.nextInt(4);
            // Generate a point in the given direction
            // Get center point (x, y)
            Iterator<Partition> iterator = gindex.iterator();
            while (i_block-- >= 0)
                iterator.next();
            Partition partition = iterator.next();
            double cx = (partition.x1 + partition.x2) / 2;
            double cy = (partition.y1 + partition.y2) / 2;
            double cw = partition.x2 - partition.x1;
            double ch = partition.y2 - partition.y1;
            int signx = ((direction & 1) == 0) ? 1 : -1;
            int signy = ((direction & 2) == 1) ? 1 : -1;
            double x = cx + cw * closeness / 2 * signx;
            double y = cy + ch * closeness / 2 * signy;
            queryPoints[i] = new Point(x, y);
        }
    }

    final BooleanWritable exceptionHappened = new BooleanWritable();

    Thread.UncaughtExceptionHandler h = new Thread.UncaughtExceptionHandler() {
        public void uncaughtException(Thread th, Throwable ex) {
            ex.printStackTrace();
            exceptionHappened.set(true);
        }
    };

    // Run each query in a separate thread
    final Vector<Thread> threads = new Vector<Thread>();
    for (int i = 0; i < queryPoints.length; i++) {
        Thread thread = new Thread() {
            @Override
            public void run() {
                try {
                    Point query_point = queryPoints[threads.indexOf(this)];
                    OperationsParams newParams = new OperationsParams(params);
                    OperationsParams.setShape(newParams, "point", query_point);
                    Job job = knn(inputFile, outputPath, params);
                } catch (IOException e) {
                    e.printStackTrace();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } catch (ClassNotFoundException e) {
                    e.printStackTrace();
                }
            }
        };
        thread.setUncaughtExceptionHandler(h);
        threads.add(thread);
    }

    long t1 = System.currentTimeMillis();
    do {
        // Ensure that there is at least MaxConcurrentThreads running
        int i = 0;
        while (i < concurrency && i < threads.size()) {
            Thread.State state = threads.elementAt(i).getState();
            if (state == Thread.State.TERMINATED) {
                // Thread already terminated, remove from the queue
                threads.remove(i);
            } else if (state == Thread.State.NEW) {
                // Start the thread and move to next one
                threads.elementAt(i++).start();
            } else {
                // Thread is still running, skip over it
                i++;
            }
        }
        if (!threads.isEmpty()) {
            try {
                // Sleep for 10 seconds or until the first thread terminates
                threads.firstElement().join(10000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    } while (!threads.isEmpty());
    long t2 = System.currentTimeMillis();
    if (exceptionHappened.get())
        throw new RuntimeException("Not all jobs finished correctly");

    System.out.println("Time for " + queryPoints.length + " jobs is " + (t2 - t1) + " millis");
    System.out.println("Total iterations: " + TotalIterations);
}

From source file:com.openteach.diamond.network.waverider.network.Packet.java

public static void main(String[] args) {
    /*System.out.println("[DEBUG] Packet Header size = " + getHeaderSize());
            //from w ww .j  a  v a  2  s. c  o m
    SlaveState slaveState = new SlaveState();
    slaveState.setId(1L);
    slaveState.setIsMasterCandidate(false);
    Command command = CommandFactory.createHeartbeatCommand(slaveState.toByteBuffer());
    Packet packet = Packet.newDataPacket(command);
    ByteBuffer buffer = packet.marshall();
    Packet p = Packet.unmarshall(buffer);
    Command cmd = Command.unmarshall(p.getPayLoad());
    SlaveState ss = SlaveState.fromByteBuffer(cmd.getPayLoad());
    System.out.println(cmd.toString());
            
            
    // Test 2
    MasterState masterState = new MasterState();
    masterState.setId(1L);
    masterState.setIp("127.0.0.1");
    masterState.setPort(8206);
    List<SessionState> sessionStateList = new LinkedList<SessionState>();
    masterState.setSessionStateList(sessionStateList);
    SessionState sessionState = null;
    for(int i = 0; i < 10; i++) {
       sessionState = new SessionState();
       sessionState.setIp("127.0.0.1");
       sessionState.setPriority(1L);
       sessionState.setIsMasterCandidate(false);
       sessionStateList.add(sessionState);
    }
    Command command2 = CommandFactory.createHeartbeatCommand(masterState.toByteBuffer());
    Packet packet2 = Packet.newDataPacket(command2);
    ByteBuffer buffer2 = packet2.marshall();
    Packet p2 = Packet.unmarshall(buffer2);
    Command cmd2 = Command.unmarshall(p2.getPayLoad());
    MasterState ms = MasterState.fromByteBuffer(cmd2.getPayLoad());
    System.out.println(cmd.toString());
    */

    System.out.println("[DEBUG] Packet Header size = " + getHeaderSize());

    BlockingQueue<ByteBuffer> queue = new LinkedBlockingQueue<ByteBuffer>();
    Random rand = new Random();
    int count = 0;
    int size = 0;
    for (int i = 0; i < 100000; i++) {
        SlaveState state = new SlaveState();
        state.setId(Long.valueOf(i));
        state.setIsMasterCandidate(true);
        Packet packet = Packet.newDataPacket(
                CommandFactory.createCommand(Command.AVAILABLE_COMMAND_START, state.toByteBuffer()));
        ByteBuffer buffer = packet.marshall();
        rand.setSeed(System.currentTimeMillis());
        count = rand.nextInt(100) + 1;
        size = buffer.remaining() / count;
        for (int j = 0; j < count; j++) {
            ByteBuffer buf = null;
            if (j == count - 1) {
                buf = ByteBuffer.allocate(buffer.remaining() - j * size);
                buf.put(buffer.array(), j * size, buffer.remaining() - j * size);
            } else {
                buf = ByteBuffer.allocate(size);
                buf.put(buffer.array(), j * size, size);
            }
            buf.flip();
            queue.add(buf);
        }
    }

    for (int i = 0; i < 100000; i++) {
        //Packet packet = Packet.parse(queue);
        //Command commad = Command.unmarshall(packet.getPayLoad());
        //SlaveState state = SlaveState.fromByteBuffer(commad.getPayLoad());
        //System.out.println(state.toString());
    }
}

From source file:DruidThroughput.java

@SuppressWarnings("InfiniteLoopStatement")
public static void main(String[] args) throws Exception {
    final int numQueries = QUERIES.length;
    final Random random = new Random(RANDOM_SEED);
    final AtomicInteger counter = new AtomicInteger(0);
    final AtomicLong totalResponseTime = new AtomicLong(0L);
    final ExecutorService executorService = Executors.newFixedThreadPool(NUM_CLIENTS);

    for (int i = 0; i < NUM_CLIENTS; i++) {
        executorService.submit(new Runnable() {
            @Override// w  ww .ja  v a2  s .  co  m
            public void run() {
                try (CloseableHttpClient client = HttpClients.createDefault()) {
                    HttpPost post = new HttpPost("http://localhost:8082/druid/v2/?pretty");
                    post.addHeader("content-type", "application/json");
                    CloseableHttpResponse res;
                    while (true) {
                        try (BufferedReader reader = new BufferedReader(new FileReader(
                                QUERY_FILE_DIR + File.separator + random.nextInt(numQueries) + ".json"))) {
                            int length = reader.read(BUFFER);
                            post.setEntity(new StringEntity(new String(BUFFER, 0, length)));
                        }
                        long start = System.currentTimeMillis();
                        res = client.execute(post);
                        res.close();
                        counter.getAndIncrement();
                        totalResponseTime.getAndAdd(System.currentTimeMillis() - start);
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    long startTime = System.currentTimeMillis();
    while (true) {
        Thread.sleep(REPORT_INTERVAL_MILLIS);
        double timePassedSeconds = ((double) (System.currentTimeMillis() - startTime)) / MILLIS_PER_SECOND;
        int count = counter.get();
        double avgResponseTime = ((double) totalResponseTime.get()) / count;
        System.out.println("Time Passed: " + timePassedSeconds + "s, Query Executed: " + count + ", QPS: "
                + count / timePassedSeconds + ", Avg Response Time: " + avgResponseTime + "ms");
    }
}