Example usage for java.util Random Random

List of usage examples for java.util Random Random

Introduction

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

Prototype

public Random() 

Source Link

Document

Creates a new random number generator.

Usage

From source file:Main.java

public static void shuffle(final Object[] array) {
    final Random r = new Random();
    final int limit = array.length;
    for (int i = 0; i < limit; ++i) {
        swap(array, i, r.nextInt(limit));
    }//from   w w w.ja  va2s.  co m
}

From source file:com.cloud.test.stress.TestClientWithAPI.java

public static void main(String[] args) {
    String host = "http://localhost";
    String port = "8092";
    String devPort = "8080";
    String apiUrl = "/client/api";

    try {//ww  w .  jav a2 s. c o m
        // Parameters
        List<String> argsList = Arrays.asList(args);
        Iterator<String> iter = argsList.iterator();
        while (iter.hasNext()) {
            String arg = iter.next();
            // host
            if (arg.equals("-h")) {
                host = "http://" + iter.next();
            }

            if (arg.equals("-p")) {
                port = iter.next();
            }
            if (arg.equals("-dp")) {
                devPort = iter.next();
            }

            if (arg.equals("-t")) {
                numThreads = Integer.parseInt(iter.next());
            }

            if (arg.equals("-s")) {
                sleepTime = Long.parseLong(iter.next());
            }
            if (arg.equals("-a")) {
                accountName = iter.next();
            }

            if (arg.equals("-c")) {
                cleanUp = Boolean.parseBoolean(iter.next());
                if (!cleanUp)
                    sleepTime = 0L; // no need to wait if we don't ever
                // cleanup
            }

            if (arg.equals("-r")) {
                repeat = Boolean.parseBoolean(iter.next());
            }

            if (arg.equals("-u")) {
                numOfUsers = Integer.parseInt(iter.next());
            }

            if (arg.equals("-i")) {
                internet = Boolean.parseBoolean(iter.next());
            }

            if (arg.equals("-w")) {
                wait = Integer.parseInt(iter.next());
            }

            if (arg.equals("-z")) {
                zoneId = iter.next();
            }

            if (arg.equals("-snapshot")) {
                snapshot_test = "yes";
            }

            if (arg.equals("-so")) {
                serviceOfferingId = iter.next();
            }

            if (arg.equals("-do")) {
                diskOfferingId = iter.next();
            }

            if (arg.equals("-no")) {
                networkOfferingId = iter.next();
            }

            if (arg.equals("-pass")) {
                vmPassword = iter.next();
            }

            if (arg.equals("-url")) {
                downloadUrl = iter.next();
            }

        }

        final String server = host + ":" + port + "/";
        final String developerServer = host + ":" + devPort + apiUrl;
        s_logger.info("Starting test against server: " + server + " with " + numThreads + " thread(s)");
        if (cleanUp)
            s_logger.info("Clean up is enabled, each test will wait " + sleepTime + " ms before cleaning up");

        if (numOfUsers > 0) {
            s_logger.info("Pre-generating users for test of size : " + numOfUsers);
            users = new String[numOfUsers];
            Random ran = new Random();
            for (int i = 0; i < numOfUsers; i++) {
                users[i] = Math.abs(ran.nextInt()) + "-user";
            }
        }

        for (int i = 0; i < numThreads; i++) {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    do {
                        String username = null;
                        try {
                            long now = System.currentTimeMillis();
                            Random ran = new Random();
                            if (users != null) {
                                username = users[Math.abs(ran.nextInt()) % numOfUsers];
                            } else {
                                username = Math.abs(ran.nextInt()) + "-user";
                            }
                            NDC.push(username);

                            s_logger.info("Starting test for the user " + username);
                            int response = executeDeployment(server, developerServer, username, snapshot_test);
                            boolean success = false;
                            String reason = null;

                            if (response == 200) {
                                success = true;
                                if (internet) {
                                    s_logger.info("Deploy successful...waiting 5 minute before SSH tests");
                                    Thread.sleep(300000L); // Wait 60
                                    // seconds so
                                    // the windows VM
                                    // can boot up and do a sys prep.

                                    if (accountName == null) {
                                        s_logger.info("Begin Linux SSH test for account " + _account.get());
                                        reason = sshTest(_linuxIP.get(), _linuxPassword.get(), snapshot_test);
                                    }

                                    if (reason == null) {
                                        s_logger.info(
                                                "Linux SSH test successful for account " + _account.get());
                                        s_logger.info("Begin WindowsSSH test for account " + _account.get());

                                        reason = sshTest(_linuxIP.get(), _linuxPassword.get(), snapshot_test);
                                        // reason = sshWinTest(_windowsIP.get());
                                    }

                                    // release the linux IP now...
                                    _linuxIP.set(null);
                                    // release the Windows IP now
                                    _windowsIP.set(null);
                                }

                                // sleep for 3 min before getting the latest network stat
                                // s_logger.info("Sleeping for 5 min before getting the lates network stat for the account");
                                // Thread.sleep(300000);
                                // verify that network stat is correct for the user; if it's not - stop all the resources
                                // for the user
                                // if ((reason == null) && (getNetworkStat(server) == false) ) {
                                // s_logger.error("Stopping all the resources for the account " + _account.get() +
                                // " as network stat is incorrect");
                                // int stopResponseCode = executeStop(
                                // server, developerServer,
                                // username, false);
                                // s_logger
                                // .info("stop command finished with response code: "
                                // + stopResponseCode);
                                // success = false; // since the SSH test
                                //
                                // } else
                                if (reason == null) {
                                    if (internet) {
                                        s_logger.info(
                                                "Windows SSH test successful for account " + _account.get());
                                    } else {
                                        s_logger.info("deploy test successful....now cleaning up");
                                        if (cleanUp) {
                                            s_logger.info(
                                                    "Waiting " + sleepTime + " ms before cleaning up vms");
                                            Thread.sleep(sleepTime);
                                        } else {
                                            success = true;
                                        }
                                    }

                                    if (usageIterator >= numThreads) {
                                        int eventsAndBillingResponseCode = executeEventsAndBilling(server,
                                                developerServer);
                                        s_logger.info(
                                                "events and usage records command finished with response code: "
                                                        + eventsAndBillingResponseCode);
                                        usageIterator = 1;

                                    } else {
                                        s_logger.info(
                                                "Skipping events and usage records for this user: usageIterator "
                                                        + usageIterator + " and number of Threads "
                                                        + numThreads);
                                        usageIterator++;
                                    }

                                    if ((users == null) && (accountName == null)) {
                                        s_logger.info("Sending cleanup command");
                                        int cleanupResponseCode = executeCleanup(server, developerServer,
                                                username);
                                        s_logger.info("cleanup command finished with response code: "
                                                + cleanupResponseCode);
                                        success = (cleanupResponseCode == 200);
                                    } else {
                                        s_logger.info("Sending stop DomR / destroy VM command");
                                        int stopResponseCode = executeStop(server, developerServer, username,
                                                true);
                                        s_logger.info("stop(destroy) command finished with response code: "
                                                + stopResponseCode);
                                        success = (stopResponseCode == 200);
                                    }

                                } else {
                                    // Just stop but don't destroy the
                                    // VMs/Routers
                                    s_logger.info("SSH test failed for account " + _account.get()
                                            + "with reason '" + reason + "', stopping VMs");
                                    int stopResponseCode = executeStop(server, developerServer, username,
                                            false);
                                    s_logger.info(
                                            "stop command finished with response code: " + stopResponseCode);
                                    success = false; // since the SSH test
                                    // failed, mark the
                                    // whole test as
                                    // failure
                                }
                            } else {
                                // Just stop but don't destroy the
                                // VMs/Routers
                                s_logger.info("Deploy test failed with reason '" + reason + "', stopping VMs");
                                int stopResponseCode = executeStop(server, developerServer, username, true);
                                s_logger.info("stop command finished with response code: " + stopResponseCode);
                                success = false; // since the deploy test
                                // failed, mark the
                                // whole test as failure
                            }

                            if (success) {
                                s_logger.info("***** Completed test for user : " + username + " in "
                                        + ((System.currentTimeMillis() - now) / 1000L) + " seconds");

                            } else {
                                s_logger.info("##### FAILED test for user : " + username + " in "
                                        + ((System.currentTimeMillis() - now) / 1000L)
                                        + " seconds with reason : " + reason);
                            }
                            s_logger.info("Sleeping for " + wait + " seconds before starting next iteration");
                            Thread.sleep(wait);
                        } catch (Exception e) {
                            s_logger.warn("Error in thread", e);
                            try {
                                int stopResponseCode = executeStop(server, developerServer, username, true);
                                s_logger.info("stop response code: " + stopResponseCode);
                            } catch (Exception e1) {
                            }
                        } finally {
                            NDC.clear();
                        }
                    } while (repeat);
                }
            }).start();
        }
    } catch (Exception e) {
        s_logger.error(e);
    }
}

From source file:Main.java

public static int getRandomSocketPort() {
    return 1024 + new Random().nextInt(64512);
}

From source file:Main.java

public static long getNewLong() {
    if (random == null) {
        random = new Random();
    }/* w  w w  .j a v a2 s. c  o m*/
    return LOWER_RANGE + (long) (random.nextDouble() * (UPPER_RANGE - LOWER_RANGE));
}

From source file:Main.java

/**
 * This function will return a map that contains entity names as keys, and random integer strings as values. The values are guaranteed not to have appeared
 * in the original xml.//  w  ww . j  av a 2  s .c o  m
 * 
 * @param xml
 *            The xml to generate the replacements for
 * @return a map of entity names to unique random strings
 */
private static Map<String, String> calculateEntityReplacements(final String xml) {
    final Map<String, String> retValue = new HashMap<String, String>();

    final Random randomGenerator = new Random();

    /* compile the regular expression */
    final Pattern injectionSequencePattern = Pattern.compile(XML_ENTITY_RE);
    /* find any matches */
    final Matcher injectionSequencematcher = injectionSequencePattern.matcher(xml);

    /* loop over the regular expression matches */
    while (injectionSequencematcher.find()) {
        final String entityName = injectionSequencematcher.group(XML_ENTITY_NAMED_GROUP);

        if (!retValue.containsKey(entityName)) {
            String randomReplacement;
            do {
                randomReplacement = "[" + randomGenerator.nextInt() + "]";
            } while (xml.indexOf(randomReplacement) != -1);

            retValue.put(entityName, randomReplacement);
        }
    }

    return retValue;
}

From source file:lifetime.backend.util.TestHelper.java

/**
 * Returns a random integer./* w  w w. j  ava 2 s .c om*/
 *
 * @return A random integer value
 */
public static Integer getRandomId() {
    return new Random().nextInt();
}

From source file:com.saax.gestorweb.util.DAOAleatorio.java

public static CentroCusto getCentroCustoAleatorio(EntityManager em) {
    List<CentroCusto> centroCustos = em.createNamedQuery("CentroCusto.findAll").getResultList();
    return centroCustos.get(new Random().nextInt(centroCustos.size() - 1));
}

From source file:Main.java

/**
 * Get a random boolean/*from w w w  .j  ava2  s  . co  m*/
 */
public static boolean getNextRandomBoolean() {

    if (mRandom == null) {
        mRandom = new Random();
    }

    return mRandom.nextBoolean();
}

From source file:net.dovemq.transport.link.LinkTestUtils.java

public static void sendMessagesOnLink(CAMQPLinkSender linkSender, int numMessagesToSend) {
    Random randomGenerator = new Random();
    for (int i = 0; i < numMessagesToSend; i++) {
        int randomInt = randomGenerator.nextInt(5);
        CAMQPMessage message = createMessage(randomGenerator);
        linkSender.sendMessage(new CAMQPMessage(message.getDeliveryTag(), message.getPayload()));
        try {//from  w  ww  . j a  v a2s . c o  m
            Thread.sleep(randomInt);
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }
    }
}

From source file:Main.java

public static int getRandomNumber(int min, int max) {
    return new Random().nextInt((max - min) + 1) + min;
}