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:net.sf.taverna.t2.security.credentialmanager.impl.PossibleURILookupsTest.java

@BeforeClass
public static void setUp() throws CMException, IOException {

    try {/*from  ww  w . j ava2s  .co  m*/
        credentialManager = new CredentialManagerImpl();
    } catch (CMException e) {
        System.out.println(e.getStackTrace());
    }
    Random randomGenerator = new Random();
    String credentialManagerDirectoryPath = System.getProperty("java.io.tmpdir")
            + System.getProperty("file.separator") + "taverna-security-" + randomGenerator.nextInt(1000000);
    System.out.println("Credential Manager's directory path: " + credentialManagerDirectoryPath);
    credentialManagerDirectory = new File(credentialManagerDirectoryPath);
    try {
        credentialManager.setConfigurationDirectoryPath(credentialManagerDirectory);
    } catch (CMException e) {
        System.out.println(e.getStackTrace());
    }

    // Create the dummy master password provider
    masterPasswordProvider = new DummyMasterPasswordProvider();
    /* Short password to avoid issues with key sizes and Java strong crypto policy*/
    masterPasswordProvider.setMasterPassword("uber");
    List<MasterPasswordProvider> masterPasswordProviders = new ArrayList<MasterPasswordProvider>();
    masterPasswordProviders.add(masterPasswordProvider);
    credentialManager.setMasterPasswordProviders(masterPasswordProviders);

    // Put our HTTP authenticator in the list of service username and password providers
    httpAuthProvider = new HTTPAuthenticatorServiceUsernameAndPasswordProvider();
    ArrayList<ServiceUsernameAndPasswordProvider> serviceUsernameAndPasswordProviders = new ArrayList<ServiceUsernameAndPasswordProvider>();
    serviceUsernameAndPasswordProviders.add(httpAuthProvider);
    credentialManager.setServiceUsernameAndPasswordProviders(serviceUsernameAndPasswordProviders);

    // These can be empty
    credentialManager.setJavaTruststorePasswordProviders(new ArrayList<JavaTruststorePasswordProvider>());
    credentialManager.setTrustConfirmationProviders(new ArrayList<TrustConfirmationProvider>());
}

From source file:com.webarch.common.lang.StringSeriesTools.java

/**
 * ??/*from   w  ww  .j  a  v a  2s .  c om*/
 *
 * @return
 */
public static String getNumber6FromRandom() {
    Random r = new Random();
    int xx = r.nextInt(1000000);
    while (xx < 100000) {
        xx = r.nextInt(1000000);
    }
    return String.valueOf(xx);
}

From source file:Main.java

public static ArrayList<Integer> getRandomNumbers(int range, int count, Random rnd) {
    if (count > range) {
        return null;
    }/*  w  w  w.j av a2 s. com*/
    if (count < 0 || range < 0) {
        return null;
    }
    HashMap<Integer, Integer> used = new HashMap<Integer, Integer>();
    ArrayList<Integer> indices = new ArrayList<Integer>();
    int n = range;
    while (indices.size() < count) {
        Integer r = Integer.valueOf(rnd.nextInt(n));
        if (used.containsKey(r)) {
            indices.add(used.get(r));
        } else {
            indices.add(r);
        }
        addToUsed(used, r, n - 1);
        n--;
    }
    return indices;
}

From source file:org.dasein.cloud.azure.Azure.java

private static int getNextIndex(Random rnd, int len, char[] pswd) {
    int index = rnd.nextInt(len);
    while (pswd[index = rnd.nextInt(len)] != 0)
        ;/*from  ww  w  .j  av  a2s  .  c  o m*/
    return index;
}

From source file:justdailscrapper.vik.utility.FetchPageWithoutProxy.java

public static String fetchPage(URI newurl, List<ProxyImport> proxyList)
        throws IOException, InterruptedException {

    Random r = new Random();

    ProxyImport obj = proxyList.get(r.nextInt(proxyList.size()));

    String ip = obj.proxyIP;//  ww w . j  a  v  a2 s  .co  m
    int portno = Integer.parseInt(obj.proxyPort);
    String username = "";
    String password = "";
    if (obj.proxyLen > 2) {
        username = obj.proxyUserName;
        password = obj.proxyPassword;
    }

    //        int portNo = generateRandomPort();
    CredentialsProvider credsprovider = new BasicCredentialsProvider();
    credsprovider.setCredentials(new AuthScope(ip, portno),
            new UsernamePasswordCredentials(username, password));
    HttpHost proxy = new HttpHost(ip, portno);
    //-----------------------------------------------------------------------
    RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(5000).setConnectTimeout(5000)
            .setConnectionRequestTimeout(5000).build();

    CloseableHttpClient httpclient = HttpClients.custom().setDefaultCredentialsProvider(credsprovider)
            .setUserAgent("Mozilla/5.0 (Windows NT 6.1; WOW64; rv:35.0) Gecko/20100101 Firefox/35.0")
            .setDefaultRequestConfig(requestConfig).setProxy(proxy).build();
    String responsebody = "";
    String responsestatus = null;
    int count = 0;
    try {
        HttpGet httpget = new HttpGet(newurl);
        httpget.addHeader("Accept", "*/*");
        httpget.addHeader("Accept-Encoding", "gzip, deflate, br");
        httpget.addHeader("Accept-Language", "en-US,en;q=0.5");
        httpget.addHeader("Host", "www.justdial.com");
        httpget.addHeader("Referer", "https://www.justdial.com/Bangalore/Yamaha-Two-Wheeler-Dealers");
        httpget.addHeader("Connection", "keep-alive");
        httpget.addHeader("X-Requested-With", "XMLHttpReques");
        System.out.println("Response status " + httpget.getRequestLine());
        CloseableHttpResponse resp = httpclient.execute(httpget);
        responsestatus = resp.getStatusLine().toString();
        if (responsestatus.contains("503") || responsestatus.contains("502") || responsestatus.contains("403")
                || responsestatus.contains("400") || responsestatus.contains("407")
                || responsestatus.contains("401") || responsestatus.contains("402")
                || responsestatus.contains("404") || responsestatus.contains("405")
                || responsestatus.contains("SSLHandshakeException") || responsestatus.contains("999")
                || responsestatus.contains("ClientProtocolException")
                || responsestatus.contains("SocketTimeoutException") || "".equals(responsestatus)) {
            Thread.sleep(10000);
            do {
                count++;
                responsebody = fetchPageSourcefromClientGoogleSecond(newurl, proxyList);
                if (responsebody == null) {
                    Thread.sleep(10000);
                    System.out.println("PROX FAILURE");
                }
                if (count > 20) {
                    Thread.sleep(1000);
                    break;
                }
            } while (responsebody == null || "".equals(responsebody));
        } else {
            HttpEntity entity = resp.getEntity();
            System.out.println(resp.getStatusLine());
            if (entity != null) {
                System.out.println("Response content length: " + entity.getContentLength());
                BufferedReader in = new BufferedReader(new InputStreamReader(entity.getContent()));
                String inputLine;
                while ((inputLine = in.readLine()) != null) {
                    responsebody = new StringBuilder().append(responsebody).append(inputLine).toString();
                }
                // writeResponseFile(responsebody, pagename);
            }
            EntityUtils.consume(entity);
        }
    } catch (IOException | IllegalStateException e) {
        System.out.println("Exception = " + e);
        do {
            count++;
            responsebody = fetchPageSourcefromClientGoogleSecond(newurl, proxyList);
            if (responsebody == null) {
                System.out.println("PROX FAILURE");
            }
            if (count > 15) {
                Thread.sleep(50000);
                //                    responsebody = fetchPageSourcefromClientGoogleSecond(newurl);
                break;
            }
        } while (responsebody == null || "".equals(responsebody));
    } finally {
        httpclient.close();
    }
    return responsebody;
}

From source file:justdailscrapper.vik.utility.FetchPageWithoutProxy.java

public static String fetchPageSourcefromClientGoogle(URI newurl, List<ProxyImport> proxyList)
        throws IOException, InterruptedException {

    Random r = new Random();

    ProxyImport obj = proxyList.get(r.nextInt(proxyList.size()));

    String ip = obj.proxyIP;//from ww  w.jav a 2  s .  com
    int portno = Integer.parseInt(obj.proxyPort);
    String username = "";
    String password = "";
    if (obj.proxyLen > 2) {
        username = obj.proxyUserName;
        password = obj.proxyPassword;
    }

    //        int portNo = generateRandomPort();
    CredentialsProvider credsprovider = new BasicCredentialsProvider();
    credsprovider.setCredentials(new AuthScope(ip, portno),
            new UsernamePasswordCredentials(username, password));
    HttpHost proxy = new HttpHost(ip, portno);
    //-----------------------------------------------------------------------
    RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(5000).setConnectTimeout(5000)
            .setConnectionRequestTimeout(5000).build();

    CloseableHttpClient httpclient = HttpClients.custom().setDefaultCredentialsProvider(credsprovider)
            .setUserAgent("Mozilla/5.0 (Windows NT 6.3; WOW64; rv:52.0) Gecko/20100101 Firefox/52.0")
            .setDefaultRequestConfig(requestConfig).setProxy(proxy).build();
    String responsebody = "";
    String responsestatus = null;
    int count = 0;
    try {
        HttpGet httpget = new HttpGet(newurl);
        httpget.addHeader("Accept", "*/*");
        httpget.addHeader("Accept-Encoding", "gzip, deflate, br");
        httpget.addHeader("Accept-Language", "en-US,en;q=0.5");
        httpget.addHeader("Host", "www.justdial.com");
        httpget.addHeader("Referer", "https://www.justdial.com/Bangalore/Yamaha-Two-Wheeler-Dealers");
        httpget.addHeader("Connection", "keep-alive");
        httpget.addHeader("X-Requested-With", "XMLHttpReques");

        System.out.println("Response status " + httpget.getRequestLine());
        CloseableHttpResponse resp = httpclient.execute(httpget);
        responsestatus = resp.getStatusLine().toString();
        if (responsestatus.contains("503") || responsestatus.contains("502") || responsestatus.contains("403")
                || responsestatus.contains("400") || responsestatus.contains("407")
                || responsestatus.contains("401") || responsestatus.contains("402")
                || responsestatus.contains("404") || responsestatus.contains("405")
                || responsestatus.contains("SSLHandshakeException") || responsestatus.contains("999")
                || responsestatus.contains("ClientProtocolException")
                || responsestatus.contains("SocketTimeoutException") || "".equals(responsestatus)) {
            Thread.sleep(10000);
            do {
                count++;
                responsebody = fetchPageSourcefromClientGoogleSecond(newurl, proxyList);
                if (responsebody == null) {
                    Thread.sleep(10000);
                    System.out.println("PROX FAILURE");
                }
                if (count > 20) {
                    Thread.sleep(1000);
                    break;
                }
            } while (responsebody == null || "".equals(responsebody));
        } else {
            HttpEntity entity = resp.getEntity();
            System.out.println(resp.getStatusLine());
            if (entity != null) {
                System.out.println("Response content length: " + entity.getContentLength());
                BufferedReader in = new BufferedReader(new InputStreamReader(entity.getContent()));
                String inputLine;
                while ((inputLine = in.readLine()) != null) {
                    responsebody = new StringBuilder().append(responsebody).append(inputLine).toString();
                }
                // writeResponseFile(responsebody, pagename);
            }
            EntityUtils.consume(entity);
        }
    } catch (IOException | IllegalStateException e) {
        System.out.println("Exception = " + e);
        do {
            count++;
            responsebody = fetchPageSourcefromClientGoogleSecond(newurl, proxyList);
            if (responsebody == null) {
                System.out.println("PROX FAILURE");
            }
            if (count > 15) {
                Thread.sleep(50000);
                //                    responsebody = fetchPageSourcefromClientGoogleSecond(newurl);
                break;
            }
        } while (responsebody == null || "".equals(responsebody));
    } finally {
        httpclient.close();
    }
    return responsebody;
}

From source file:justdailscrapper.vik.utility.FetchPageWithProxy.java

public static String fetchPageSourcefromClientGoogle(URI newurl, List<ProxyImport> proxyList)
        throws IOException, InterruptedException {

    Random r = new Random();

    ProxyImport obj = proxyList.get(r.nextInt(proxyList.size()));

    String ip = obj.proxyIP;//  w w  w.j av a  2 s .  c om
    int portno = Integer.parseInt(obj.proxyPort);
    String username = "";
    String password = "";
    if (obj.proxyLen > 2) {
        username = obj.proxyUserName;
        password = obj.proxyPassword;
    }

    //        int portNo = generateRandomPort();
    CredentialsProvider credsprovider = new BasicCredentialsProvider();
    credsprovider.setCredentials(new AuthScope(ip, portno),
            new UsernamePasswordCredentials(username, password));
    HttpHost proxy = new HttpHost(ip, portno);
    //-----------------------------------------------------------------------
    RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(5000).setConnectTimeout(5000)
            .setConnectionRequestTimeout(5000).build();

    CloseableHttpClient httpclient = HttpClients.custom().setDefaultCredentialsProvider(credsprovider)
            .setUserAgent("Mozilla/5.0 (Windows NT 6.3; WOW64; rv:52.0) Gecko/20100101 Firefox/52.0")
            .setDefaultRequestConfig(requestConfig).setProxy(proxy).build();
    String responsebody = "";
    String responsestatus = null;
    int count = 0;
    try {
        HttpGet httpget = new HttpGet(newurl);
        httpget.addHeader("Accept", "*/*");
        httpget.addHeader("Accept-Encoding", "gzip, deflate, br");
        httpget.addHeader("Accept-Language", "en-US,en;q=0.5");
        httpget.addHeader("Host", "www.justdial.com");
        httpget.addHeader("Referer", "https://www.justdial.com/Bangalore/Yamaha-Two-Wheeler-Dealers");
        httpget.addHeader("Connection", "keep-alive");
        httpget.addHeader("X-Requested-With", "XMLHttpReques");

        System.out.println("Response status " + httpget.getRequestLine());
        CloseableHttpResponse resp = httpclient.execute(httpget);
        responsestatus = resp.getStatusLine().toString();
        if (responsestatus.contains("503") || responsestatus.contains("502") || responsestatus.contains("403")
                || responsestatus.contains("400") || responsestatus.contains("407")
                || responsestatus.contains("401") || responsestatus.contains("402")
                || responsestatus.contains("404") || responsestatus.contains("405")
                || responsestatus.contains("SSLHandshakeException") || responsestatus.contains("999")
                || responsestatus.contains("ClientProtocolException")
                || responsestatus.contains("SocketTimeoutException") || "".equals(responsestatus)) {
            Thread.sleep(10000);
            do {
                count++;
                responsebody = fetchPageSourcefromClientGoogleSecond(newurl, proxyList);
                if (responsebody == null) {
                    Thread.sleep(10000);
                    logTextArea.append("PROX FAILURE\n");
                }
                if (count > 20) {
                    Thread.sleep(1000);
                    break;
                }
            } while (responsebody == null || "".equals(responsebody));
        } else {
            HttpEntity entity = resp.getEntity();
            System.out.println(resp.getStatusLine());
            if (entity != null) {
                logTextArea.append("Response content length: " + entity.getContentLength() + "\n");
                BufferedReader in = new BufferedReader(new InputStreamReader(entity.getContent()));
                String inputLine;
                while ((inputLine = in.readLine()) != null) {
                    responsebody = new StringBuilder().append(responsebody).append(inputLine).toString();
                }
                // writeResponseFile(responsebody, pagename);
            }
            EntityUtils.consume(entity);
        }
    } catch (IOException | IllegalStateException e) {
        System.out.println("Exception = " + e);
        do {
            count++;
            responsebody = fetchPageSourcefromClientGoogleSecond(newurl, proxyList);
            if (responsebody == null) {
                System.out.println("PROX FAILURE");
            }
            if (count > 15) {
                Thread.sleep(50000);
                //                    responsebody = fetchPageSourcefromClientGoogleSecond(newurl);
                break;
            }
        } while (responsebody == null || "".equals(responsebody));
    } finally {
        httpclient.close();
    }
    return responsebody;
}

From source file:cop.raml.utils.example.JsonExample.java

/**
 * Generates random example for given primitive {@code kind} using given {@code random} generator.
 *
 * @param kind   primitive kind type// w ww  .jav a  2  s . com
 * @param random not {@code null} random generator
 * @return generated random example for given primitive type
 */
private static Object getPrimitiveExample(TypeKind kind, @NotNull Random random) {
    if (kind == TypeKind.BOOLEAN)
        return random.nextBoolean();
    if (kind == TypeKind.BYTE)
        return (byte) random.nextInt(255);
    if (kind == TypeKind.SHORT)
        return (short) random.nextInt(1000);
    if (kind == TypeKind.INT)
        return random.nextInt(1000);
    if (kind == TypeKind.LONG)
        return (long) random.nextInt(1000);
    if (kind == TypeKind.CHAR)
        return (char) ('A' + random.nextInt(28));
    if (kind == TypeKind.FLOAT)
        return (float) random.nextInt(1000);
    if (kind == TypeKind.DOUBLE)
        return (double) random.nextInt(1000);
    return null;
}

From source file:org.dasein.cloud.azure.Azure.java

public static char[] generatePassword(int minLen, int maxLen, int noOfCAPSAlpha, int noOfDigits,
        int noOfSpecialChars) {
    if (minLen > maxLen)
        throw new IllegalArgumentException("Min. Length > Max. Length!");
    if ((noOfCAPSAlpha + noOfDigits + noOfSpecialChars) > minLen)
        throw new IllegalArgumentException(
                "Min. Length should be atleast sum of (CAPS, DIGITS, SPL CHARS) Length!");
    Random rnd = new Random();
    int len = rnd.nextInt(maxLen - minLen + 1) + minLen;
    char[] pswd = new char[len];
    int index = 0;
    for (int i = 0; i < noOfCAPSAlpha; i++) {
        index = getNextIndex(rnd, len, pswd);
        pswd[index] = ALPHA_CAPS.charAt(rnd.nextInt(ALPHA_CAPS.length()));
    }/*from w  w  w .  j av  a 2  s.  c  o m*/
    for (int i = 0; i < noOfDigits; i++) {
        index = getNextIndex(rnd, len, pswd);
        pswd[index] = NUM.charAt(rnd.nextInt(NUM.length()));
    }
    for (int i = 0; i < noOfSpecialChars; i++) {
        index = getNextIndex(rnd, len, pswd);
        pswd[index] = SPECIAL.charAt(rnd.nextInt(SPECIAL.length()));
    }
    for (int i = 0; i < len; i++) {
        if (pswd[i] == 0) {
            pswd[i] = ALPHA.charAt(rnd.nextInt(ALPHA.length()));
        }
    }
    return pswd;
}

From source file:com.alicloud.tablestore.adaptor.client.IntegratedTest.java

public static byte[] generateBytes(int length) {
    StringBuilder keyBuilder = new StringBuilder(length);
    Random random = new Random();
    for (int i = 0; i < length; i++) {
        keyBuilder.append(KEY_SEED_CHARS[random.nextInt(KEY_SEED_LEN)]);
    }/*from  www  .ja  va 2s .c o  m*/
    return Bytes.toBytes(keyBuilder.toString());
}