Example usage for java.util Random nextLong

List of usage examples for java.util Random nextLong

Introduction

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

Prototype

public long nextLong() 

Source Link

Document

Returns the next pseudorandom, uniformly distributed long value from this random number generator's sequence.

Usage

From source file:org.apache.hadoop.hdfs.server.datanode.TestFiDataTransferProtocol2.java

/**
 * 1. create files with dfs/*from  ww  w . j a va 2 s. c o m*/
 * 2. write MIN_N_PACKET to MAX_N_PACKET packets
 * 3. close file
 * 4. open the same file
 * 5. read the bytes and compare results
 */
private static void writeSeveralPackets(String methodName) throws IOException {
    final Random r = FiTestUtil.RANDOM.get();
    final int nPackets = FiTestUtil.nextRandomInt(MIN_N_PACKET, MAX_N_PACKET + 1);
    final int lastPacketSize = FiTestUtil.nextRandomInt(1, PACKET_SIZE + 1);
    final int size = (nPackets - 1) * PACKET_SIZE + lastPacketSize;

    FiTestUtil.LOG.info("size=" + size + ", nPackets=" + nPackets + ", lastPacketSize=" + lastPacketSize);

    final MiniDFSCluster cluster = new MiniDFSCluster.Builder(conf).numDataNodes(REPLICATION + 2).build();
    final FileSystem dfs = cluster.getFileSystem();
    try {
        final Path p = new Path("/" + methodName + "/foo");
        final FSDataOutputStream out = createFile(dfs, p);

        final long seed = r.nextLong();
        final Random ran = new Random(seed);
        ran.nextBytes(bytes);
        out.write(bytes, 0, size);
        out.close();

        final FSDataInputStream in = dfs.open(p);
        int totalRead = 0;
        int nRead = 0;
        while ((nRead = in.read(toRead, totalRead, size - totalRead)) > 0) {
            totalRead += nRead;
        }
        Assert.assertEquals("Cannot read file.", size, totalRead);
        for (int i = 0; i < size; i++) {
            Assert.assertTrue("File content differ.", bytes[i] == toRead[i]);
        }
    } finally {
        dfs.close();
        cluster.shutdown();
    }
}

From source file:org.apache.hadoop.hbase.client.TestClientNoCluster.java

/**
 * Code for each 'client' to run./*from   w  w  w .  ja  va2s .c  o  m*/
 *
 * @param id
 * @param c
 * @param sharedConnection
 * @throws IOException
 */
static void cycle(int id, final Configuration c, final HConnection sharedConnection) throws IOException {
    HTableInterface table = sharedConnection.getTable(BIG_USER_TABLE);
    table.setAutoFlushTo(false);
    long namespaceSpan = c.getLong("hbase.test.namespace.span", 1000000);
    long startTime = System.currentTimeMillis();
    final int printInterval = 100000;
    Random rd = new Random(id);
    boolean get = c.getBoolean("hbase.test.do.gets", false);
    try {
        Stopwatch stopWatch = new Stopwatch();
        stopWatch.start();
        for (int i = 0; i < namespaceSpan; i++) {
            byte[] b = format(rd.nextLong());
            if (get) {
                Get g = new Get(b);
                table.get(g);
            } else {
                Put p = new Put(b);
                p.add(HConstants.CATALOG_FAMILY, b, b);
                table.put(p);
            }
            if (i % printInterval == 0) {
                LOG.info("Put " + printInterval + "/" + stopWatch.elapsedMillis());
                stopWatch.reset();
                stopWatch.start();
            }
        }
        LOG.info("Finished a cycle putting " + namespaceSpan + " in " + (System.currentTimeMillis() - startTime)
                + "ms");
    } finally {
        table.close();
    }
}

From source file:com.ibm.bi.dml.runtime.matrix.data.LibMatrixDatagen.java

private static long nextLong(Random r, long n) {
    if (n <= 0)
        throw new IllegalArgumentException("n must be positive");

    //if ((n & -n) == n)  // i.e., n is a power of 2
    //    return ((n * (long)r.nextLong()) >> 31);

    long bits, val;
    do {//from  ww  w .ja  v  a2 s. com
        bits = (r.nextLong() << 1) >>> 1;
        val = bits % n;
    } while (bits - val + (n - 1) < 0L);
    return val;
}

From source file:org.brekka.stillingar.example.FieldTypesDOMTest.java

private static Testing writeConfig() {
    Random r = new Random();
    ConfigurationDocument doc = ConfigurationDocument.Factory.newInstance();
    Configuration newConfiguration = doc.addNewConfiguration();
    FeatureFlagType featureFlag = newConfiguration.addNewFeatureFlag();
    featureFlag.setKey("turbo");
    featureFlag.setBooleanValue(true);/*from  w  ww  .ja v  a2  s.  c  o  m*/
    Testing testing = newConfiguration.addNewTesting();
    testing.setAnyURI("http://brekka.org/" + RandomStringUtils.randomAlphanumeric(10));
    testing.setBoolean(r.nextBoolean());
    testing.setByte((byte) r.nextInt());
    Calendar cal = Calendar.getInstance();
    testing.setDate(cal);
    testing.setDateTime(cal);
    testing.setDecimal(BigDecimal.valueOf(r.nextDouble()));
    testing.setDouble(r.nextDouble());
    testing.setFloat(r.nextFloat());
    testing.setInt(r.nextInt());
    testing.setInteger(BigInteger.valueOf(r.nextLong()));
    testing.setLanguage("en");
    testing.setLong(r.nextLong());
    testing.setShort((short) r.nextInt());
    testing.setString(RandomStringUtils.randomAlphanumeric(24));
    testing.setTime(cal);
    testing.setUUID(UUID.randomUUID().toString());
    testing.setPeriod(new GDuration("P5Y2M10DT15H"));
    byte[] binary = new byte[32];
    r.nextBytes(binary);
    testing.setBinary(binary);
    TestSupport.write(doc);
    return testing;
}

From source file:fr.iphc.grid.jobmonitor.CeList.java

static public ArrayList<URL> AvailableLdapCe() throws Exception {
    ArrayList<URL> CeList = new ArrayList<URL>();
    Hashtable<String, String> env = new Hashtable<String, String>();
    env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
    env.put(Context.PROVIDER_URL, "ldap://cclcgtopbdii01.in2p3.fr:2170");
    env.put("java.naming.ldap.attributes.binary", "objectSID");
    try {//  w  w w  .  ja  v  a 2 s  .  c o  m
        // Create initial context
        DirContext ctx = new InitialDirContext(env);
        SearchControls contraints = new SearchControls();
        contraints.setSearchScope(SearchControls.SUBTREE_SCOPE);
        String[] attributIDs = { "GlueCEUniqueID" };
        contraints.setReturningAttributes(attributIDs);
        String BASE_SEARCH = "Mds-Vo-name=local,o=grid";
        String filter = "(&(objectClass=GlueCE)(GlueCEImplementationName=CREAM)(GlueCEAccessControlBaseRule=VO:biomed))";
        NamingEnumeration<SearchResult> answer = ctx.search(BASE_SEARCH, filter, contraints);
        //         int index = 0;
        Random rand = new Random();
        while (answer.hasMore()) {
            //            index++;
            SearchResult result = answer.next();
            //            Attributes attrs = result.getAttributes();
            //            NamingEnumeration f = attrs.getAll();
            //            Attribute attr = (Attribute) f.next();
            String line = "cream://" + result.getAttributes().get("GlueCEUniqueID").get() + "?delegationId="
                    + rand.nextLong();
            URL serviceURL = URLFactory.createURL(line);
            CeList.add(serviceURL);
        }
        // Close the context when we're done
        ctx.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
    ;
    return CeList;
}

From source file:org.diorite.utils.math.DioriteRandomUtils.java

public static long getRandomLong(final Random random, final long min, final long max)
        throws IllegalArgumentException {
    if (min == max) {
        return max;
    }//from w  w  w .  j a  va2  s . c o  m
    Validate.isTrue(max > min, "Max can't be smaller than min!");
    return (Math.abs(random.nextLong()) % ((max - min) + 1)) + min;
}

From source file:com.pavikumbhar.javaheart.util.PasswordGenerator.java

private long generateRandomNumber() {
    Random r = new Random(10000000999l);
    long l1 = r.nextLong();
    long l2 = r.nextLong();
    long l3 = r.nextLong();
    return l1 & l2 & l3 * Calendar.getInstance().getTimeInMillis();
}

From source file:org.sakaiproject.util.TrustedLoginTokenTest.java

@Test
public void testDecode() throws Exception {
    String user = "usersid";
    String secret = "HowManyBottlesAreThereOnTheWall";
    TrustedLoginFilter tlf = new TrustedLoginFilter();
    tlf.setSharedSecret(secret);/*ww w  .  jav a 2  s . c  om*/
    Random ran = new Random();
    String data = user + ";" + ran.nextLong();
    String hash = tlf.byteArrayToHexStr(
            MessageDigest.getInstance("SHA1").digest((secret + ";" + data).getBytes("UTF-8")));
    String token = hash + ";" + data;
    long start = System.currentTimeMillis();

    for (int i = 0; i < 1000; i++) {
        String decodedUser = tlf.decodeToken(token);

        Assert.assertEquals("Users dont match ", user, decodedUser);
    }
    long end = System.currentTimeMillis();
    double t = 1.0 * (end - start) / 1000.0;
    log.info("Per call " + t + " ms");
}

From source file:backup.store.s3.TestS3BackupStore.java

private ExtendedBlock createExtendedBlock(String poolId) {
    Random rand = random.get();
    long blkid = rand.nextLong();
    long len = rand.nextInt(1000);
    long genstamp = rand.nextInt(2000);
    return new ExtendedBlock(poolId, blkid, len, genstamp);
}

From source file:com.codefollower.lealone.omid.tso.TestLongCache.java

@Test
public void testEntriesAge() {

    Cache cache = new LongCache(entries, 16);
    Random random = new Random();

    long seed = random.nextLong();

    LOG.info("Random seed: " + seed);
    random.setSeed(seed);/*  w  ww.ja va 2 s  .  com*/
    int removals = 0;
    long totalAge = 0;
    double tempStdDev = 0;
    double tempAvg = 0;

    int i = 0;
    int largestDeletedTimestamp = 0;
    for (; i < entries * 10; ++i) {
        long removed = cache.set(random.nextLong(), i);
        if (removed > largestDeletedTimestamp) {
            largestDeletedTimestamp = (int) removed;
        }
    }

    long time = System.nanoTime();
    for (; i < entries * 100; ++i) {
        long removed = cache.set(random.nextLong(), i);
        if (removed > largestDeletedTimestamp) {
            largestDeletedTimestamp = (int) removed;
        }
        int gap = i - ((int) largestDeletedTimestamp);
        removals++;
        totalAge += gap;
        double oldAvg = tempAvg;
        tempAvg += (gap - tempAvg) / removals;
        tempStdDev += (gap - oldAvg) * (gap - tempAvg);
        hist.add(gap);
    }
    long elapsed = System.nanoTime() - time;
    LOG.info("Elapsed (ms): " + (elapsed / (double) 1000));

    double avgGap = totalAge / (double) removals;
    LOG.info("Avg gap: " + (tempAvg));
    LOG.info("Std dev gap: " + Math.sqrt((tempStdDev / entries)));
    assertThat(avgGap, is(greaterThan(entries * .6)));
}