Example usage for java.util Random nextBytes

List of usage examples for java.util Random nextBytes

Introduction

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

Prototype

public void nextBytes(byte[] bytes) 

Source Link

Document

Generates random bytes and places them into a user-supplied byte array.

Usage

From source file:net.sf.ehcache.DiskStoreTest.java

/**
 * This test is designed to be used with a profiler to explore the ways in which DiskStore
 * uses memory. It does not do much on its own.
 *//* w w w.  j  a  v a  2  s  .co m*/
public void testOutOfMemoryErrorOnOverflowToDisk() throws Exception {

    //Set size so the second element overflows to disk.
    Cache cache = new Cache("test", 1000, MemoryStoreEvictionPolicy.LRU, true, null, true, 500, 500, false, 1,
            null);
    manager.addCache(cache);
    int i = 0;

    Random random = new Random();
    for (; i < 5500; i++) {
        byte[] bytes = new byte[10000];
        random.nextBytes(bytes);
        cache.put(new Element("" + i, bytes));
    }
    LOG.info("Elements written: " + i);
    //Thread.sleep(100000);
}

From source file:org.opencastproject.util.ZipUtilTest.java

/**
 * Test compression of >4GB file//w  w  w.ja va 2 s  .c  o m
 */
@Test
@Ignore
public void testOver4GB() throws Exception {

    if (bigFile.exists() || bigFile.createNewFile()) {
        if (bigFile.getUsableSpace() >= bigFileSize) {

            FileOutputStream fos = new FileOutputStream(bigFile);
            byte[] buffer = new byte[1024];
            Random rdn = new Random();
            File destZip = new File(destDir, "bigZip.zip");

            for (long i = 0; i < bigFileSize; i += buffer.length) {
                rdn.nextBytes(buffer);
                fos.write(buffer);
            }

            fos.close();

            ZipUtil.zip(new File[] { bigFile }, destZip, ZipUtil.NO_COMPRESSION);

            Assert.assertTrue(destZip.exists());
            Assert.assertTrue(destZip.length() >= bigFileSize);
        } else {
            logger.warn("This test needs more than 4GB of disk free space: {}", bigFile.getUsableSpace());
            logger.warn("Skipping...");
        }
    } else
        logger.warn("Couldn't create the File descriptor");
}

From source file:syndeticlogic.catena.array.ArrayTest.java

@Test
public void updateVariableLengthArrayTest() {
    CompositeKey newKey = new CompositeKey();
    newKey.append(this.key);
    newKey.append(1);/*from  w  w  w.  ja  v  a2s. c  o  m*/
    this.key = newKey;

    arrayRegistry.createArray(key, Type.BINARY);
    array = arrayRegistry.createArrayInstance(key);

    VariableLengthArrayGenerator vlag = new VariableLengthArrayGenerator(37, 13);
    List<byte[]> arrayValues = vlag.generateMemoryArray(300);
    Random r = new Random(337);
    int skip = r.nextInt() % 13;
    List<byte[]> skipList = new LinkedList<byte[]>();

    assertEquals(0, array.position());

    for (byte[] value : arrayValues) {
        array.append(value, 0, value.length);
    }

    assertEquals(300, array.position());
    assertFalse(array.hasMore());

    for (int i = 0; i < arrayValues.size(); i++) {
        if (i % skip == 0) {
            byte[] updateBytes = new byte[r.nextInt(8192) + 1];
            r.nextBytes(updateBytes);
            skipList.add(updateBytes);
            array.position(i, LockType.WriteLock);
            array.update(updateBytes, 0, updateBytes.length);
            array.complete(LockType.WriteLock);
        }
    }

    array.position(0, BinaryArray.LockType.ReadLock);
    for (int i = 0, j = 0; i < arrayValues.size(); i++) {
        byte[] value = arrayValues.get(i);
        if (i % skip == 0) {
            value = skipList.get(j);
            j++;
        }
        byte[] buffer = new byte[value.length];
        array.scan(array.createIODescriptor(buffer, 0));
        assertArrayEquals(value, buffer);
    }
    array.complete(BinaryArray.LockType.ReadLock);

}

From source file:syndeticlogic.catena.array.ArrayTest.java

@Test
public void commitUpdateVariableLengthArrayTest() {
    CompositeKey newKey = new CompositeKey();
    newKey.append(this.key);
    newKey.append("1" + System.getProperty("file.separator"));
    key = newKey;/*  w  w w  . ja  v  a 2  s . c om*/
    arrayRegistry.createArray(key, Type.BINARY);
    array = arrayRegistry.createArrayInstance(key);
    VariableLengthArrayGenerator vlag = new VariableLengthArrayGenerator(37, 13);
    List<byte[]> arrayValues = vlag.generateMemoryArray(300);
    Random r = new Random(337);
    int skip = r.nextInt() % 13;
    List<byte[]> updateList = new LinkedList<byte[]>();

    assertEquals(0, array.position());

    for (byte[] value : arrayValues) {
        array.append(value, 0, value.length);
    }
    assertEquals(300, array.position());
    assertFalse(array.hasMore());
    //int cumdelta = 0;
    for (int i = 0; i < arrayValues.size(); i++) {
        if (i % skip == 0) {
            byte[] updateBytes = new byte[r.nextInt(8192) + 1];
            r.nextBytes(updateBytes);
            updateList.add(updateBytes);
            array.position(i, LockType.WriteLock);

            //int delta = updateBytes.length - arrayValues.get(i).length;
            //cumdelta += delta;
            array.update(updateBytes, 0, updateBytes.length);
            array.complete(LockType.WriteLock);
        }
    }
    array.commit();
    reconfigure();
    array.position(0, BinaryArray.LockType.ReadLock);
    for (int i = 0, j = 0; i < arrayValues.size(); i++) {
        byte[] value = arrayValues.get(i);
        if (i % skip == 0) {
            value = updateList.get(j);
            j++;
        }

        byte[] buffer = new byte[value.length];
        array.scan(array.createIODescriptor(buffer, 0));
        System.out.println("i = " + i + " value.size = " + value.length);
        assertArrayEquals(value, buffer);

    }
    array.complete(BinaryArray.LockType.ReadLock);
    assertFalse(array.hasMore());
}

From source file:dk.statsbiblioteket.util.LineReaderTest.java

public void dumpSpeed() throws Exception {
    Random random = new Random();
    int[] sizes = new int[] { 100, 10000, 1000000, 10000000 };
    Profiler profiler = new Profiler();
    for (int size : sizes) {
        System.out.print("Creating test-file of size " + size + "...");
        File temp = createTempFile();
        LineReader lr = new LineReader(temp, "rw");
        byte[] bytes = new byte[size];
        random.nextBytes(bytes);
        System.gc();//from www . j  a v a 2 s  .  co  m
        profiler.reset();
        lr.write(bytes);
        lr.close();
        System.out.println(" in " + profiler.getSpendTime());
        dumpSpeed2Helper(temp);
        temp.delete();
    }
}

From source file:org.commonjava.indy.promote.data.PromotionManagerTest.java

@Test
@Ignore("volatile, owing to galley fs locks")
public void promoteAllByPath_RaceToPromote_FirstLocksTargetStore() throws Exception {
    Random rand = new Random();
    final HostedRepository[] sources = { new HostedRepository(MAVEN_PKG_KEY, "source1"),
            new HostedRepository(MAVEN_PKG_KEY, "source2") };
    final String[] paths = { "/path/path1", "/path/path2", "/path3", "/path/path/4" };
    Stream.of(sources).forEach((source) -> {
        try {//from www  . jav  a 2 s.  c  o  m
            storeManager.storeArtifactStore(source, new ChangeSummary(ChangeSummary.SYSTEM_USER, "test setup"),
                    false, true, new EventMetadata());

            Stream.of(paths).forEach((path) -> {
                byte[] buf = new byte[1024 * 1024 * 2];
                rand.nextBytes(buf);
                try {
                    contentManager.store(source, path, new ByteArrayInputStream(buf), TransferOperation.UPLOAD,
                            new EventMetadata());
                } catch (IndyWorkflowException e) {
                    e.printStackTrace();
                    Assert.fail("failed to store generated file to: " + source + path);
                }
            });
        } catch (IndyDataException e) {
            e.printStackTrace();
            Assert.fail("failed to store hosted repository: " + source);
        }
    });

    final HostedRepository target = new HostedRepository(MAVEN_PKG_KEY, "target");
    storeManager.storeArtifactStore(target, new ChangeSummary(ChangeSummary.SYSTEM_USER, "test setup"), false,
            true, new EventMetadata());

    PathsPromoteResult[] results = new PathsPromoteResult[2];
    CountDownLatch cdl = new CountDownLatch(2);

    AtomicInteger counter = new AtomicInteger(0);
    Stream.of(sources).forEach((source) -> {
        int idx = counter.getAndIncrement();
        executor.execute(() -> {
            try {
                results[idx] = manager.promotePaths(
                        new PathsPromoteRequest(source.getKey(), target.getKey(), paths), FAKE_BASE_URL);
            } catch (Exception e) {
                e.printStackTrace();
                Assert.fail("Promotion from source: " + source + " failed.");
            } finally {
                cdl.countDown();
            }
        });

        try {
            Thread.sleep(25);
        } catch (InterruptedException e) {
            Assert.fail("Test interrupted");
        }
    });

    assertThat("Promotions failed to finish.", cdl.await(30, TimeUnit.SECONDS), equalTo(true));

    // first one should succeed.
    PathsPromoteResult result = results[0];
    assertThat(result.getRequest().getSource(), equalTo(sources[0].getKey()));
    assertThat(result.getRequest().getTarget(), equalTo(target.getKey()));

    Set<String> pending = result.getPendingPaths();
    assertThat(pending == null || pending.isEmpty(), equalTo(true));

    Set<String> skipped = result.getSkippedPaths();
    assertThat(skipped == null || skipped.isEmpty(), equalTo(true));

    Set<String> completed = result.getCompletedPaths();
    assertThat(completed, notNullValue());
    assertThat(completed.size(), equalTo(paths.length));

    assertThat(result.getError(), nullValue());

    Stream.of(paths).forEach((path) -> {
        HostedRepository src = sources[0];
        Transfer sourceRef = downloadManager.getStorageReference(src, path);
        Transfer targetRef = downloadManager.getStorageReference(target, path);
        assertThat(targetRef.exists(), equalTo(true));
        try (InputStream sourceIn = sourceRef.openInputStream();
                InputStream targetIn = targetRef.openInputStream()) {
            int s = -1, t = -1;
            while ((s = sourceIn.read()) == (t = targetIn.read())) {
                if (s == -1) {
                    break;
                }
            }

            if (s != -1 && s != t) {
                Assert.fail(path + " doesn't match between source: " + src + " and target: " + target);
            }
        } catch (IOException e) {
            e.printStackTrace();
            Assert.fail("Failed to compare contents of: " + path + " between source: " + src + " and target: "
                    + target);
        }
    });

    // second one should be completely skipped.
    result = results[1];
    assertThat(result.getRequest().getSource(), equalTo(sources[1].getKey()));
    assertThat(result.getRequest().getTarget(), equalTo(target.getKey()));

    pending = result.getPendingPaths();
    assertThat(pending == null || pending.isEmpty(), equalTo(true));

    skipped = result.getSkippedPaths();
    assertThat(skipped, notNullValue());
    assertThat(skipped.size(), equalTo(paths.length));

    completed = result.getCompletedPaths();
    assertThat(completed == null || completed.isEmpty(), equalTo(true));

    assertThat(result.getError(), nullValue());
}

From source file:org.apache.hadoop.hdfs.server.namenode.TestCheckpoint.java

static void writeFile(FileSystem fileSys, Path name, int repl) throws IOException {
    FSDataOutputStream stm = fileSys.create(name, true,
            fileSys.getConf().getInt(CommonConfigurationKeys.IO_FILE_BUFFER_SIZE_KEY, 4096), (short) repl,
            blockSize);/*  w ww  .  j a v  a2 s  .  c  o  m*/
    byte[] buffer = new byte[TestCheckpoint.fileSize];
    Random rand = new Random(TestCheckpoint.seed);
    rand.nextBytes(buffer);
    stm.write(buffer);
    stm.close();
}

From source file:syndeticlogic.catena.array.ArrayTest.java

@Test
public void updateDeleteVariableLengthArrayTest() {
    CompositeKey key = new CompositeKey();
    key.append(this.key);
    key.append(1);/*from   ww  w  .j  a  va 2  s . c o  m*/

    arrayRegistry.createArray(key, Type.BINARY);
    array = arrayRegistry.createArrayInstance(key);
    VariableLengthArrayGenerator vlag = new VariableLengthArrayGenerator(37, 13);
    List<byte[]> arrayValues = vlag.generateMemoryArray(300);
    Random r = new Random(337);
    int skip = r.nextInt() % 13;
    List<byte[]> skipList = new LinkedList<byte[]>();

    assertEquals(0, array.position());

    for (byte[] value : arrayValues) {
        array.append(value, 0, value.length);
    }

    assertEquals(300, array.position());
    assertFalse(array.hasMore());

    for (int i = 0; i < arrayValues.size(); i++) {
        if (i % skip == 0) {
            if (i % 2 == 0) {
                array.position(i, LockType.WriteLock);
                array.delete();
                array.complete(LockType.WriteLock);
                arrayValues.remove(i);
            } else {
                byte[] updateBytes = new byte[r.nextInt(8192) + 1];
                r.nextBytes(updateBytes);
                skipList.add(updateBytes);
                array.position(i, LockType.WriteLock);
                array.update(updateBytes, 0, updateBytes.length);
                array.complete(LockType.WriteLock);
            }
        }
    }

    array.position(0, BinaryArray.LockType.ReadLock);
    for (int i = 0, j = 0; i < arrayValues.size(); i++) {
        byte[] value = arrayValues.get(i);
        if (i % skip == 0 && i % 2 != 0) {
            value = skipList.get(j);
            j++;
        }

        byte[] buffer = new byte[value.length];
        array.scan(array.createIODescriptor(buffer, 0));
        assertArrayEquals(value, buffer);
    }
    array.complete(BinaryArray.LockType.ReadLock);
    assertFalse(array.hasMore());
}

From source file:syndeticlogic.catena.array.ArrayTest.java

@Test
public void commitUpdateDeleteVariableLengthArrayTest() {
    CompositeKey newKey = new CompositeKey();
    newKey.append(this.key);
    newKey.append("1" + System.getProperty("file.separator"));
    key = newKey;// ww  w. j  a  v a  2  s. c o m
    System.out.println("---------------------------------------key = " + key.toString());
    arrayRegistry.createArray(key, Type.BINARY);
    array = arrayRegistry.createArrayInstance(key);
    VariableLengthArrayGenerator vlag = new VariableLengthArrayGenerator(37, 13);
    List<byte[]> arrayValues = vlag.generateMemoryArray(300);
    Random r = new Random(337);
    int skip = r.nextInt() % 13;
    List<byte[]> updateList = new LinkedList<byte[]>();

    assertEquals(0, array.position());

    for (byte[] value : arrayValues) {
        array.append(value, 0, value.length);
    }

    assertEquals(300, array.position());
    assertFalse(array.hasMore());

    for (int i = 0, alternator = 0; i < arrayValues.size(); i++) {
        if (i % skip == 0) {

            if (alternator % 2 == 0) {
                array.position(i, LockType.WriteLock);
                array.delete();
                array.complete(LockType.WriteLock);
                arrayValues.remove(i);

            } else {
                byte[] updateBytes = new byte[r.nextInt(8192) + 1];
                r.nextBytes(updateBytes);
                updateList.add(updateBytes);
                array.position(i, LockType.WriteLock);
                array.update(updateBytes, 0, updateBytes.length);
                array.complete(LockType.WriteLock);
            }
            alternator++;
        }
    }

    array.commit();
    reconfigure();

    array.position(0, BinaryArray.LockType.ReadLock);
    for (int i = 0, j = 0, alternator = 0; i < arrayValues.size(); i++) {
        byte[] value = arrayValues.get(i);
        if (i % skip == 0) {
            if (alternator % 2 != 0) {
                value = updateList.get(j);
                j++;
            }
            alternator++;
        }

        byte[] buffer = new byte[value.length];
        array.scan(array.createIODescriptor(buffer, 0));
        System.out.println("i = " + i + " value.size = " + value.length);
        assertArrayEquals(value, buffer);

    }
    array.complete(BinaryArray.LockType.ReadLock);
    assertFalse(array.hasMore());
}

From source file:org.apache.beam.sdk.io.synthetic.SyntheticOptions.java

public KV<byte[], byte[]> genKvPair(long seed) {
    Random random = new Random(seed);

    byte[] key = new byte[(int) keySizeBytes];
    // Set the user-key to contain characters other than ordered-code escape characters
    // (specifically '\0' or '\xff'). The user-key is encoded into the shuffle-key using
    // ordered-code, and the shuffle-key is then checked for size limit violations. A user-key
    // consisting of '\0' keySizeBytes would produce a shuffle-key encoding double in size,
    // which would go over the shuffle-key limit (see b/28770924).
    for (int i = 0; i < keySizeBytes; ++i) {
        key[i] = 42;//from   w  ww  .  j a  v  a 2 s  . co m
    }
    // Determines whether to generate hot key or not.
    if (random.nextDouble() < hotKeyFraction) {
        // Generate hot key.
        // An integer is randomly selected from the range [0, numHotKeys-1] with equal probability.
        int randInt = random.nextInt((int) numHotKeys);
        ByteBuffer.wrap(key).putInt(hashFunction().hashInt(randInt).asInt());
    } else {
        // Note that the random generated key might be a hot key.
        // But the probability of being a hot key is very small.
        random.nextBytes(key);
    }

    byte[] val = new byte[(int) valueSizeBytes];
    random.nextBytes(val);
    return KV.of(key, val);
}