java.util.Random

Here are the examples of the java api class java.util.Random taken from open source projects.

1. LocalWordService#onStartCommand()

View license
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    Random random = new Random();
    if (random.nextBoolean()) {
        list.add("Linux");
    }
    if (random.nextBoolean()) {
        list.add("Android");
    }
    if (random.nextBoolean()) {
        list.add("iPhone");
    }
    if (random.nextBoolean()) {
        list.add("Windows7");
    }
    if (list.size() >= 20) {
        list.remove(0);
    }
    return Service.START_NOT_STICKY;
}

2. User#insecureRandom()

Project: Peergos
Source File: User.java
View license
public static User insecureRandom() {
    byte[] secretSignBytes = new byte[64];
    byte[] publicSignBytes = new byte[32];
    byte[] secretBoxBytes = new byte[32];
    byte[] publicBoxBytes = new byte[32];
    Random rnd = new Random();
    rnd.nextBytes(secretSignBytes);
    rnd.nextBytes(publicSignBytes);
    rnd.nextBytes(secretBoxBytes);
    rnd.nextBytes(publicBoxBytes);
    return random(secretSignBytes, publicSignBytes, secretBoxBytes, publicBoxBytes, new JavaEd25519(), new JavaCurve25519(), new SafeRandom.Java());
}

3. TailAppendingInputStreamTest#setUp()

View license
@Before
public void setUp() {
    Random random = new Random();
    random.setSeed(RANDOM_SEED);
    mBytes = new byte[BYTES_LENGTH];
    mTail = new byte[TAIL_LENGTH];
    mOutputBuffer = new byte[OUTPUT_LENGTH];
    random.nextBytes(mBytes);
    random.nextBytes(mTail);
    InputStream stream = new ByteArrayInputStream(mBytes);
    mTailAppendingInputStream = new TailAppendingInputStream(stream, mTail);
}

4. TestCrcConcat#testConcatCrcBlocks()

Project: hadoop-20
Source File: TestCrcConcat.java
View license
@Test
public void testConcatCrcBlocks() throws Exception {
    int lastBlockLength = 38888889;
    Random random;
    // Verify concatenating two 256MB blocks
    random = new Random(1);
    int checksumb1 = getChecksum(random, 256 * 1024 * 1024);
    int checksumb2 = getChecksum(random, 256 * 1024 * 1024);
    int checksumb3 = getChecksum(random, lastBlockLength);
    // Verify concatenating two blocks' CRC
    random = new Random(1);
    int checksum2b = getChecksum(random, 2 * 256 * 1024 * 1024);
    ;
    int concatedChcksum2b = CrcConcat.concatCrc(checksumb1, checksumb2, 256 * 1024 * 1024);
    TestCase.assertEquals(checksum2b, concatedChcksum2b);
    // Verify full CRC.
    random = new Random(1);
    int checksum_all = getChecksum(random, 2 * 256 * 1024 * 1024 + lastBlockLength);
    int concatedChcksum_all = CrcConcat.concatCrc(checksum2b, checksumb3, lastBlockLength);
    TestCase.assertEquals(checksum_all, concatedChcksum_all);
}

5. HtmlCore#fireRandom()

Project: HiBench
Source File: HtmlCore.java
View license
public void fireRandom(int rseed) {
    randRandSeed = new Random(rseed);
    randUrl = new Random(randRandSeed.nextLong());
    randElinks = new Random(randRandSeed.nextLong());
    if (null != lzipf) {
        lzipf.setRandSeed(randRandSeed.nextLong());
    }
    if (null != wzipf) {
        wzipf.setRandSeed(randRandSeed.nextLong());
    }
    randPageGo = new Random(randRandSeed.nextLong());
}

6. TestCaseBase#doDeleteRecordTest()

Project: jackrabbit
Source File: TestCaseBase.java
View license
/**
     * Test [email protected] MultiDataStoreAware#deleteRecord(DataIdentifier)}.
     */
protected void doDeleteRecordTest() throws Exception {
    ds = createDataStore();
    Random random = randomGen;
    byte[] data1 = new byte[dataLength];
    random.nextBytes(data1);
    DataRecord rec1 = ds.addRecord(new ByteArrayInputStream(data1));
    byte[] data2 = new byte[dataLength];
    random.nextBytes(data2);
    DataRecord rec2 = ds.addRecord(new ByteArrayInputStream(data2));
    byte[] data3 = new byte[dataLength];
    random.nextBytes(data3);
    DataRecord rec3 = ds.addRecord(new ByteArrayInputStream(data3));
    ((MultiDataStoreAware) ds).deleteRecord(rec2.getIdentifier());
    assertNull("rec2 should be null", ds.getRecordIfStored(rec2.getIdentifier()));
    assertEquals(new ByteArrayInputStream(data1), ds.getRecord(rec1.getIdentifier()).getStream());
    assertEquals(new ByteArrayInputStream(data3), ds.getRecord(rec3.getIdentifier()).getStream());
    ds.close();
}

7. MineshaftAlgorithm_Base#isValidLocation()

Project: amidst
Source File: MineshaftAlgorithm_Base.java
View license
@Override
public boolean isValidLocation(int chunkX, int chunkY) {
    Random random = new Random(seed);
    long var13 = (long) chunkX * random.nextLong();
    long var15 = (long) chunkY * random.nextLong();
    random.setSeed(var13 ^ var15 ^ seed);
    random.nextInt();
    return getResult(chunkX, chunkY, random) && random.nextInt(80) < Math.max(Math.abs(chunkX), Math.abs(chunkY));
}

8. ArraysTest#testMergeSort()

Project: fastutil
Source File: ArraysTest.java
View license
@Test
public void testMergeSort() {
    testMergeSort(new int[] { 2, 1, 0, 4 });
    testMergeSort(new int[] { 2, -1, 0, -4 });
    testMergeSort(IntArrays.shuffle(IntArraysTest.identity(100), new Random(0)));
    int[] t = new int[100];
    Random random = new Random(0);
    for (int i = t.length; i-- != 0; ) t[i] = random.nextInt();
    testMergeSort(t);
    t = new int[100000];
    random = new Random(0);
    for (int i = t.length; i-- != 0; ) t[i] = random.nextInt();
    testMergeSort(t);
    for (int i = 100; i-- != 10; ) t[i] = random.nextInt();
    testMergeSort(t, 10, 100);
    for (int i = t.length; i-- != 0; ) t[i] = random.nextInt() & 0xF;
    testMergeSort(t);
    t = new int[10000000];
    random = new Random(0);
    for (int i = t.length; i-- != 0; ) t[i] = random.nextInt();
    testMergeSort(t);
}

9. ArraysTest#testQuickSort()

Project: fastutil
Source File: ArraysTest.java
View license
@Test
public void testQuickSort() {
    testQuickSort(new int[] { 2, 1, 0, 4 });
    testQuickSort(new int[] { 2, -1, 0, -4 });
    testQuickSort(IntArrays.shuffle(IntArraysTest.identity(100), new Random(0)));
    int[] t = new int[100];
    Random random = new Random(0);
    for (int i = t.length; i-- != 0; ) t[i] = random.nextInt();
    testQuickSort(t);
    t = new int[100000];
    random = new Random(0);
    for (int i = t.length; i-- != 0; ) t[i] = random.nextInt();
    testQuickSort(t);
    for (int i = 100; i-- != 10; ) t[i] = random.nextInt();
    testQuickSort(t, 10, 100);
    for (int i = t.length; i-- != 0; ) t[i] = random.nextInt() & 0xF;
    testQuickSort(t);
    t = new int[10000000];
    random = new Random(0);
    for (int i = t.length; i-- != 0; ) t[i] = random.nextInt();
    testQuickSort(t);
}

10. ArraysTest#testParallelQuickSort()

Project: fastutil
Source File: ArraysTest.java
View license
@Test
public void testParallelQuickSort() {
    testParallelQuickSort(new int[] { 2, 1, 0, 4 });
    testParallelQuickSort(new int[] { 2, -1, 0, -4 });
    testParallelQuickSort(IntArrays.shuffle(IntArraysTest.identity(100), new Random(0)));
    int[] t = new int[100];
    Random random = new Random(0);
    for (int i = t.length; i-- != 0; ) t[i] = random.nextInt();
    testParallelQuickSort(t);
    t = new int[100000];
    random = new Random(0);
    for (int i = t.length; i-- != 0; ) t[i] = random.nextInt();
    testParallelQuickSort(t);
    for (int i = 100; i-- != 10; ) t[i] = random.nextInt();
    testParallelQuickSort(t, 10, 100);
    for (int i = t.length; i-- != 0; ) t[i] = random.nextInt() & 0xF;
    testParallelQuickSort(t);
    t = new int[10000000];
    random = new Random(0);
    for (int i = t.length; i-- != 0; ) t[i] = random.nextInt();
    testParallelQuickSort(t);
}

11. PooledFileRandomAccessBufferTest#innerTestSimplePooling()

View license
private void innerTestSimplePooling(int sz) throws IOException {
    fds.setMaxFDs(1);
    PooledFileRandomAccessBuffer a = construct(sz);
    PooledFileRandomAccessBuffer b = construct(sz);
    byte[] buf1 = new byte[sz];
    byte[] buf2 = new byte[sz];
    Random r = new Random(1153);
    r.nextBytes(buf1);
    r.nextBytes(buf2);
    a.pwrite(0, buf1, 0, buf1.length);
    b.pwrite(0, buf2, 0, buf2.length);
    byte[] cmp1 = new byte[sz];
    byte[] cmp2 = new byte[sz];
    a.pread(0, cmp1, 0, cmp1.length);
    b.pread(0, cmp2, 0, cmp2.length);
    assertTrue(Arrays.equals(cmp1, buf1));
    assertTrue(Arrays.equals(cmp2, buf2));
    a.close();
    b.close();
    a.free();
    b.free();
}

12. AbstractBlobStoreTest#testReference()

View license
@Test
public void testReference() throws Exception {
    assumeThat(store, instanceOf(AbstractBlobStore.class));
    AbstractBlobStore abs = (AbstractBlobStore) store;
    Random r = new Random();
    byte[] key = new byte[256];
    r.nextBytes(key);
    abs.setReferenceKey(key);
    byte[] data = new byte[1000];
    r.nextBytes(data);
    String blobId = store.writeBlob(new ByteArrayInputStream(data));
    String reference = store.getReference(blobId);
    String blobId2 = store.getBlobId(reference);
    assertEquals(blobId, blobId2);
}

13. ByteBufUtilTest#equalsBufferSubsections()

Project: netty
Source File: ByteBufUtilTest.java
View license
@Test
public void equalsBufferSubsections() {
    byte[] b1 = new byte[128];
    byte[] b2 = new byte[256];
    Random rand = new Random();
    rand.nextBytes(b1);
    rand.nextBytes(b2);
    final int iB1 = b1.length / 2;
    final int iB2 = iB1 + b1.length;
    final int length = b1.length - iB1;
    System.arraycopy(b1, iB1, b2, iB2, length);
    assertTrue(ByteBufUtil.equals(Unpooled.wrappedBuffer(b1), iB1, Unpooled.wrappedBuffer(b2), iB2, length));
}

14. ByteBufUtilTest#notEqualsBufferSubsections()

Project: netty
Source File: ByteBufUtilTest.java
View license
@Test
public void notEqualsBufferSubsections() {
    byte[] b1 = new byte[50];
    byte[] b2 = new byte[256];
    Random rand = new Random();
    rand.nextBytes(b1);
    rand.nextBytes(b2);
    final int iB1 = b1.length / 2;
    final int iB2 = iB1 + b1.length;
    final int length = b1.length - iB1;
    System.arraycopy(b1, iB1, b2, iB2, length);
    // Randomly pick an index in the range that will be compared and make the value at that index differ between
    // the 2 arrays.
    int diffIndex = random(rand, iB1, iB1 + length - 1);
    ++b1[diffIndex];
    assertFalse(ByteBufUtil.equals(Unpooled.wrappedBuffer(b1), iB1, Unpooled.wrappedBuffer(b2), iB2, length));
}

15. ByteBufUtilTest#notEqualsBufferOverflow()

Project: netty
Source File: ByteBufUtilTest.java
View license
@Test
public void notEqualsBufferOverflow() {
    byte[] b1 = new byte[8];
    byte[] b2 = new byte[16];
    Random rand = new Random();
    rand.nextBytes(b1);
    rand.nextBytes(b2);
    final int iB1 = b1.length / 2;
    final int iB2 = iB1 + b1.length;
    final int length = b1.length - iB1;
    System.arraycopy(b1, iB1, b2, iB2, length - 1);
    assertFalse(ByteBufUtil.equals(Unpooled.wrappedBuffer(b1), iB1, Unpooled.wrappedBuffer(b2), iB2, Math.max(b1.length, b2.length) * 2));
}

16. ByteBufUtilTest#notEqualsBufferUnderflow()

Project: netty
Source File: ByteBufUtilTest.java
View license
@Test(expected = IllegalArgumentException.class)
public void notEqualsBufferUnderflow() {
    byte[] b1 = new byte[8];
    byte[] b2 = new byte[16];
    Random rand = new Random();
    rand.nextBytes(b1);
    rand.nextBytes(b2);
    final int iB1 = b1.length / 2;
    final int iB2 = iB1 + b1.length;
    final int length = b1.length - iB1;
    System.arraycopy(b1, iB1, b2, iB2, length - 1);
    assertFalse(ByteBufUtil.equals(Unpooled.wrappedBuffer(b1), iB1, Unpooled.wrappedBuffer(b2), iB2, -1));
}

17. BloomFilterUtilsTest#probability()

Project: sling
Source File: BloomFilterUtilsTest.java
View license
@Test
public void probability() {
    byte[] bloom = BloomFilterUtils.createFilter(20, 64);
    System.out.println(bloom.length);
    Random random = new Random(1);
    random.setSeed(1);
    for (int i = 0; i < 20; i++) {
        BloomFilterUtils.add(bloom, random.nextInt());
    }
    random.setSeed(1);
    for (int i = 0; i < 20; i++) {
        assertTrue(BloomFilterUtils.probablyContains(bloom, random.nextInt()));
    }
    int falsePositives = 0;
    for (int i = 20; i < 100000; i++) {
        if (BloomFilterUtils.probablyContains(bloom, random.nextInt())) {
            falsePositives++;
        }
    }
    assertEquals(4594, falsePositives);
}

18. UUIDGenerator#generateDummyAddress()

Project: activemq-artemis
Source File: UUIDGenerator.java
View license
public byte[] generateDummyAddress() {
    Random rnd = getRandomNumberGenerator();
    byte[] dummy = new byte[6];
    rnd.nextBytes(dummy);
    /* Need to set the broadcast bit to indicate it's not a real
       * address.
       */
    dummy[0] |= (byte) 0x01;
    if (ActiveMQUtilLogger.LOGGER.isDebugEnabled()) {
        ActiveMQUtilLogger.LOGGER.debug("using dummy address " + UUIDGenerator.asString(dummy));
    }
    return dummy;
}

19. AlbianLogicIdService#makeStringUNID()

Project: Albianj2
Source File: AlbianLogicIdService.java
View license
/* (non-Javadoc)
	 * @see org.albianj.kernel.impl.AlbianLogicIdServide#makeStringUNID(java.lang.String)
	 */
@Override
public synchronized String makeStringUNID(String appName) {
    // ?????????????????????????????????????????????????????????
    Random rnd = new Random();
    rnd.setSeed(10000);
    int numb = rnd.nextInt(10000);
    // ????????????????????????
    numb = (numb ^ serial.getAndIncrement()) % 10000;
    serial.compareAndSet(10000, 0);
    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
    String app = appName;
    if (app.length() < 7) {
        app = StringHelper.padLeft(app, 7);
    }
    if (app.length() > 7) {
        app = app.substring(0, 7);
    }
    return String.format("%1$s-%2$s-%3$s-%4$04d", StringHelper.padLeft(KernelSetting.getKernelId(), 4), app, dateFormat.format(new Date()), numb);
}

20. NetherFortressAlgorithm#isValidLocation()

Project: amidst
Source File: NetherFortressAlgorithm.java
View license
@Override
public boolean isValidLocation(int x, int y) {
    int i = x >> 4;
    int j = y >> 4;
    Random random = new Random(i ^ j << 4 ^ seed);
    random.nextInt();
    // @formatter:off
    return random.nextInt(3) == 0 && x == (i << 4) + 4 + random.nextInt(8) && y == (j << 4) + 4 + random.nextInt(8);
// @formatter:on
}

21. TestUtils#randomMACAddress()

Project: android-proxy
Source File: TestUtils.java
View license
private static String randomMACAddress() {
    Random rand = new Random();
    byte[] macAddr = new byte[6];
    rand.nextBytes(macAddr);
    //zeroing last 2 bytes to make it unicast and locally adminstrated
    macAddr[0] = (byte) (macAddr[0] & (byte) 254);
    StringBuilder sb = new StringBuilder(18);
    for (byte b : macAddr) {
        if (sb.length() > 0)
            sb.append(":");
        sb.append(String.format("%02x", b));
    }
    return sb.toString();
}

22. I151SChapter02Activity#suggest30()

View license
/**
     * ??30? ??????????
     */
private void suggest30() {
    Random r1 = new Random();
    for (int i = 0; i < 4; i++) {
        Log.e(TAG, "?" + i + "?" + r1.nextInt());
    }
    Random r2 = new Random(1000);
    for (int i = 0; i < 4; i++) {
        Log.e(TAG, "?" + i + "?" + r2.nextInt());
    }
/*
        ????????r1??????????????r2????????????????
        ??????????????????
        ??????????????????Java????????????????????
        ??????????????
        ?????????????
        ????????????????????
        ???????Java?????????????????java.util.Random?????
        ?????Math.random?????Math.random()??????????Random?????
        ????nextDouble()????????????????
         */
/**
         * ??
         * ??????????????
         */
}

23. HTTPBin#getGzippedResponse()

Project: AntennaPod
Source File: HTTPBin.java
View license
private Response getGzippedResponse(int size) throws IOException {
    try {
        Thread.sleep(200);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
    final byte[] buffer = new byte[size];
    Random random = new Random(System.currentTimeMillis());
    random.nextBytes(buffer);
    ByteArrayOutputStream compressed = new ByteArrayOutputStream(buffer.length);
    GZIPOutputStream gzipOutputStream = new GZIPOutputStream(compressed);
    gzipOutputStream.write(buffer);
    gzipOutputStream.close();
    InputStream inputStream = new ByteArrayInputStream(compressed.toByteArray());
    Response response = new Response(Response.Status.OK, MIME_PLAIN, inputStream);
    response.addHeader("Content-Encoding", "gzip");
    response.addHeader("Content-Length", String.valueOf(compressed.size()));
    return response;
}

24. TestDTFileByteArrays#testFailureKeyLongerThan64K()

View license
@Test
public void testFailureKeyLongerThan64K() throws IOException {
    if (skip) {
        return;
    }
    byte[] buf = new byte[64 * K + 1];
    Random rand = new Random();
    rand.nextBytes(buf);
    try {
        writer.append(buf, "valueX".getBytes());
    } catch (IndexOutOfBoundsException e) {
    }
    closeOutput();
}

25. StreamTest#storeAndCheckByteStreams()

Project: atlasdb
Source File: StreamTest.java
View license
private long storeAndCheckByteStreams(int size) throws IOException {
    byte[] reference = PtBytes.toBytes("ref");
    final byte[] bytesToStore = new byte[size];
    Random rand = new Random();
    rand.nextBytes(bytesToStore);
    final long id = timestampService.getFreshTimestamp();
    PersistentStreamStore store = StreamTestStreamStore.of(txManager, StreamTestTableFactory.of());
    txManager.runTaskWithRetry( t -> {
        store.storeStreams(t, ImmutableMap.of(id, new ByteArrayInputStream(bytesToStore)));
        store.markStreamAsUsed(t, id, reference);
        return null;
    });
    verifyLoadingStreams(id, bytesToStore, store);
    store.storeStream(new ByteArrayInputStream(bytesToStore));
    verifyLoadingStreams(id, bytesToStore, store);
    return id;
}

26. StreamTest#storeAndCheckExpiringByteStreams()

Project: atlasdb
Source File: StreamTest.java
View license
private long storeAndCheckExpiringByteStreams(int size) throws IOException {
    final byte[] bytesToStore = new byte[size];
    Random rand = new Random();
    rand.nextBytes(bytesToStore);
    final long id = timestampService.getFreshTimestamp();
    StreamTestWithHashStreamStore store = StreamTestWithHashStreamStore.of(txManager, StreamTestTableFactory.of());
    store.storeStream(id, new ByteArrayInputStream(bytesToStore), 5, TimeUnit.SECONDS);
    verifyLoadingStreams(id, bytesToStore, store);
    return id;
}

27. StreamTest#testStoreCopy()

Project: atlasdb
Source File: StreamTest.java
View license
@Test
public void testStoreCopy() {
    final byte[] bytes = new byte[2 * StreamTestStreamStore.BLOCK_SIZE_IN_BYTES];
    Random rand = new Random();
    rand.nextBytes(bytes);
    long id1 = timestampService.getFreshTimestamp();
    long id2 = timestampService.getFreshTimestamp();
    ImmutableMap<Long, InputStream> streams = ImmutableMap.of(id1, new ByteArrayInputStream(bytes), id2, new ByteArrayInputStream(bytes));
    PersistentStreamStore store = StreamTestStreamStore.of(txManager, StreamTestTableFactory.of());
    txManager.runTaskWithRetry( t -> store.storeStreams(t, streams));
    Pair<Long, Sha256Hash> idAndHash1 = store.storeStream(new ByteArrayInputStream(bytes));
    Pair<Long, Sha256Hash> idAndHash2 = store.storeStream(new ByteArrayInputStream(bytes));
    //verify hashes are the same
    assertThat(idAndHash1.getRhSide(), equalTo(idAndHash2.getRhSide()));
    //verify ids are different
    assertThat(idAndHash1.getLhSide(), not(equalTo(idAndHash2.getLhSide())));
}

28. MultipleSegmentUploaderTests#GenerateFileData()

View license
private static String GenerateFileData(byte[] contents) throws IOException {
    File tempFile = File.createTempFile("adlmsu", ".data");
    Random rnd = new Random(0);
    rnd.nextBytes(contents);
    Assert.assertTrue("The temp file at the following path was not created: " + tempFile.getAbsolutePath(), tempFile.exists());
    try (FileOutputStream stream = new FileOutputStream(tempFile)) {
        stream.write(contents);
    }
    return tempFile.getAbsolutePath();
}

29. TestHelpers#GenerateFileData()

Project: azure-sdk-for-java
Source File: TestHelpers.java
View license
/**
     * Generates some random data and writes it out to a temp file and to an in-memory array
     *
     * @param contents The array to write random data to (the length of this array will be the size of the file).
     * @return The path of the file that will be created.
     * @throws IOException
     */
static String GenerateFileData(byte[] contents) throws IOException {
    File filePath = File.createTempFile("adlUploader", "test.data");
    Random rnd = new Random(0);
    rnd.nextBytes(contents);
    if (filePath.exists()) {
        filePath.delete();
    }
    FileOutputStream writer = new FileOutputStream(filePath);
    writer.write(contents);
    writer.flush();
    writer.close();
    return filePath.toString();
}

30. PGPPacketTest#readBackTest()

Project: bc-java
Source File: PGPPacketTest.java
View license
private void readBackTest(PGPLiteralDataGenerator generator) throws IOException {
    Random rand = new Random();
    byte[] buf = new byte[MAX];
    rand.nextBytes(buf);
    for (int i = 1; i <= 200; i++) {
        bufferTest(generator, buf, i);
    }
    bufferTest(generator, buf, 8382);
    bufferTest(generator, buf, 8383);
    bufferTest(generator, buf, 8384);
    bufferTest(generator, buf, 8385);
    for (int i = 200; i < MAX; i += 100) {
        bufferTest(generator, buf, i);
    }
}

31. CollectionsTest#testMapWithLargePartition()

Project: cassandra
Source File: CollectionsTest.java
View license
@Test
public void testMapWithLargePartition() throws Throwable {
    Random r = new Random();
    long seed = System.nanoTime();
    System.out.println("Seed " + seed);
    r.setSeed(seed);
    int len = (1024 * 1024) / 100;
    createTable("CREATE TABLE %s (userid text PRIMARY KEY, properties map<int, text>) with compression = {}");
    final int numKeys = 200;
    for (int i = 0; i < numKeys; i++) {
        byte[] b = new byte[len];
        r.nextBytes(b);
        execute("UPDATE %s SET properties[?] = ? WHERE userid = 'user'", i, new String(b));
    }
    flush();
    Object[][] rows = getRows(execute("SELECT properties from %s where userid = 'user'"));
    assertEquals(1, rows.length);
    assertEquals(numKeys, ((Map) rows[0][0]).size());
}

32. UUIDTypeTest#random()

Project: cassandra
Source File: UUIDTypeTest.java
View license
static ByteBuffer[] random(int count, byte... types) {
    Random random = new Random();
    long seed = random.nextLong();
    random.setSeed(seed);
    System.out.println("UUIDTypeTest.random.seed=" + seed);
    ByteBuffer[] uuids = new ByteBuffer[count * types.length];
    for (int i = 0; i < types.length; i++) {
        for (int j = 0; j < count; j++) {
            int k = (i * count) + j;
            uuids[k] = ByteBuffer.allocate(16);
            random.nextBytes(uuids[k].array());
            // set version to 1
            uuids[k].array()[6] &= 0x0F;
            uuids[k].array()[6] |= types[i];
        }
    }
    return uuids;
}

33. ZipUtilsTest#setUp()

Project: che
Source File: ZipUtilsTest.java
View license
@BeforeMethod
public void setUp() throws IOException {
    zipFile = File.createTempFile("test", "zip");
    zipFile.deleteOnExit();
    byte[] testData = new byte[2048];
    Random random = new Random();
    random.nextBytes(testData);
    try (ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(zipFile))) {
        ZipEntry entry = new ZipEntry("test");
        entry.setSize(testData.length);
        zos.putNextEntry(entry);
        zos.write(testData);
        zos.closeEntry();
        zos.close();
    }
}

34. CipherReadBenchmark#setUp()

Project: conceal
Source File: CipherReadBenchmark.java
View license
@Override
public void setUp() throws Exception {
    // Initialize the buffers
    Random random = new Random();
    mData = new byte[size];
    random.nextBytes(mData);
    mReadBuffer = new byte[1024];
    // Initialize the ciphers and Macs.
    mHMAC = HMAC.getInstance();
    mNativeGCMCipherHelper = NativeGCMCipherHelper.getInstance();
    mAESCipher = AESCipher.getInstance();
    Security.addProvider(new BouncyCastleProvider());
    mBCGCMCipher = BouncyCastleGCMCipher.getInstance();
    // Initialize the ciphered outputs.
    mNativeGCMCipheredData = generateCipherText(mNativeGCMCipherHelper);
    mBCGCMCipheredData = generateCipherText(mBCGCMCipher);
    mAESCipherText = generateCipherText(mAESCipher);
}

35. CipherWriteBenchmark#setUp()

Project: conceal
Source File: CipherWriteBenchmark.java
View license
@Override
public void setUp() throws Exception {
    Random random = new Random();
    mData = new byte[size];
    random.nextBytes(mData);
    mNullOutputStream = new NullOutputStream();
    mHMAC = HMAC.getInstance();
    mNativeGCMCipherHelper = NativeGCMCipherHelper.getInstance();
    mAESCipher = AESCipher.getInstance();
    Security.addProvider(new BouncyCastleProvider());
    mBCGCMCipher = BouncyCastleGCMCipher.getInstance();
}

36. NativeGCMCipherInputStreamTest#setUp()

View license
protected void setUp() throws Exception {
    super.setUp();
    mNativeCryptoLibrary = new SystemNativeCryptoLibrary();
    KeyChain keyChain = new FakeKeyChain();
    mCrypto = new Crypto(keyChain, mNativeCryptoLibrary);
    mIV = keyChain.getNewIV();
    mKey = keyChain.getCipherKey();
    // Encrypt some data before each test.
    mData = new byte[CryptoTestUtils.NUM_DATA_BYTES];
    Random random = new Random();
    random.nextBytes(mData);
    ByteArrayOutputStream cipherOutputStream = new ByteArrayOutputStream();
    OutputStream outputStream = mCrypto.getCipherOutputStream(cipherOutputStream, new Entity(CryptoTestUtils.ENTITY_NAME));
    outputStream.write(mData);
    outputStream.close();
    mCipheredData = cipherOutputStream.toByteArray();
    mCipherInputStream = new ByteArrayInputStream(mCipheredData);
}

37. NativeMacLayeredInputStreamTest#setUp()

View license
public void setUp() throws Exception {
    mKeyChain = new FakeKeyChain();
    mCrypto = AndroidConceal.get().createCrypto128Bits(mKeyChain);
    mData = new byte[CryptoTestUtils.NUM_DATA_BYTES];
    Random random = new Random();
    random.nextBytes(mData);
    ByteArrayOutputStream bout = new ByteArrayOutputStream();
    mEntity = new Entity(CryptoTestUtils.ENTITY_NAME);
    OutputStream outputStream = mCrypto.getMacOutputStream(bout, mEntity);
    outputStream.write(mData);
    outputStream.close();
    mDataWithMac = bout.toByteArray();
}

38. LuceneDocCollectorBenchmark#generateRowSource()

View license
private byte[] generateRowSource() throws IOException {
    Random random = RandomizedTest.getRandom();
    byte[] buffer = new byte[32];
    random.nextBytes(buffer);
    return XContentFactory.jsonBuilder().startObject().field("areaInSqKm", random.nextFloat()).field("continent", new BytesArray(buffer, 0, 4).toUtf8()).field("countryCode", new BytesArray(buffer, 4, 8).toUtf8()).field("countryName", new BytesArray(buffer, 8, 24).toUtf8()).field("population", random.nextInt(Integer.MAX_VALUE)).endObject().bytes().toBytes();
}

39. TestPagedByteArray#testReadWriteArray()

Project: Cubert
Source File: TestPagedByteArray.java
View license
@Test
public void testReadWriteArray() throws Exception {
    final int n = 100;
    byte[] bytes = new byte[n];
    final Random rand = new Random(seed);
    rand.nextBytes(bytes);
    PagedByteArray pba = new PagedByteArray(100);
    final int someOffset = 172;
    pba.write(bytes, 0, bytes.length, someOffset);
    byte[] result = new byte[n];
    pba.read(result, 0, bytes.length, someOffset);
    Assert.assertEquals(result, bytes);
}

40. ByteArraySerializerTest#testEquals()

View license
@Test
public void testEquals() throws Exception {
    ByteArraySerializer serializer = new ByteArraySerializer();
    long now = System.currentTimeMillis();
    LOGGER.info("ByteArraySerializer test with seed {}", now);
    Random random = new Random(now);
    byte[] bytes = new byte[64];
    random.nextBytes(bytes);
    ByteBuffer serialized = serializer.serialize(bytes);
    assertThat(serializer.equals(bytes, serialized), is(true));
    serialized.rewind();
    byte[] read = serializer.read(serialized);
    assertThat(Arrays.equals(read, bytes), is(true));
}

41. BZip2OutputStreamTests#test4Tables()

View license
/**
	 * @throws java.io.IOException
	 */
@Test
public void test4Tables() throws IOException {
    byte[] testData = new byte[1100];
    // Create test block
    Random random = new Random(1234);
    random.nextBytes(testData);
    // Compress
    ByteArrayOutputStream byteOutput = new ByteArrayOutputStream();
    BZip2OutputStream output = new BZip2OutputStream(byteOutput);
    output.write(testData);
    output.close();
    // Decompress
    ByteArrayInputStream byteInput = new ByteArrayInputStream(byteOutput.toByteArray());
    BZip2InputStream input = new BZip2InputStream(byteInput, false);
    byte[] decodedTestData = new byte[testData.length];
    input.read(decodedTestData, 0, decodedTestData.length);
    // Compare
    assertArrayEquals(testData, decodedTestData);
    assertEquals(-1, input.read());
}

42. ByteBufferInputStreamTest#readMultipleBytesInLoop()

View license
@Test
public void readMultipleBytesInLoop() throws IOException {
    //generate 1KB of test data
    Random random = new Random();
    byte testData[] = new byte[1024];
    random.nextBytes(testData);
    final ByteBuffer buf = ByteBuffer.wrap(testData);
    InputStream is = new ByteBufferInputStream(new TestableByteBufferAccessor(buf));
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    byte readBuf[] = new byte[56];
    int read = -1;
    while ((read = is.read(readBuf)) > -1) {
        assertLessThanOrEqual(readBuf.length, read);
        baos.write(readBuf, 0, read);
    }
    assertArrayEquals(testData, baos.toByteArray());
}

43. ByteBufferInputStreamTest#readMultipleBytesSpecificInLoop()

View license
@Test
public void readMultipleBytesSpecificInLoop() throws IOException {
    //generate 1KB of test data
    Random random = new Random();
    byte testData[] = new byte[1024];
    random.nextBytes(testData);
    final ByteBuffer buf = ByteBuffer.wrap(testData);
    InputStream is = new ByteBufferInputStream(new TestableByteBufferAccessor(buf));
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    byte readBuf[] = new byte[56];
    int read = -1;
    while ((read = is.read(readBuf, 0, readBuf.length)) > -1) {
        assertLessThanOrEqual(readBuf.length, read);
        baos.write(readBuf, 0, read);
    }
    assertArrayEquals(testData, baos.toByteArray());
}

44. AEADStreamsTest#testCloseEarly()

Project: fred
Source File: AEADStreamsTest.java
View license
/** Check whether we can close the stream early. 
     * @throws IOException */
public void testCloseEarly() throws IOException {
    ArrayBucket input = new ArrayBucket();
    BucketTools.fill(input, 2048);
    int keysize = 16;
    Random random = new Random(0x47f6709f);
    byte[] key = new byte[keysize];
    random.nextBytes(key);
    Bucket output = new ArrayBucket();
    OutputStream os = output.getOutputStream();
    AEADOutputStream cos = AEADOutputStream.innerCreateAES(os, key, random);
    BucketTools.copyTo(input, cos, 2048);
    cos.close();
    InputStream is = output.getInputStream();
    AEADInputStream cis = AEADInputStream.createAES(is, key);
    byte[] first1KReadEncrypted = new byte[1024];
    new DataInputStream(cis).readFully(first1KReadEncrypted);
    byte[] first1KReadOriginal = new byte[1024];
    new DataInputStream(input.getInputStream()).readFully(first1KReadOriginal);
    assertTrue(Arrays.equals(first1KReadEncrypted, first1KReadOriginal));
    cis.close();
}

45. EncryptedRandomAccessBucketTest#testIrregularWrites()

View license
public void testIrregularWrites() throws IOException {
    Random r = new Random(6032405);
    int length = 1024 * 64 + 1;
    byte[] data = new byte[length];
    RandomAccessBucket bucket = (RandomAccessBucket) makeBucket(length);
    OutputStream os = bucket.getOutputStream();
    r.nextBytes(data);
    for (int written = 0; written < length; ) {
        int toWrite = Math.min(length - written, 4095);
        os.write(data, written, toWrite);
        written += toWrite;
    }
    os.close();
    InputStream is = bucket.getInputStream();
    for (int moved = 0; moved < length; ) {
        int readBytes = Math.min(length - moved, 4095);
        byte[] buf = new byte[readBytes];
        readBytes = is.read(buf);
        assertTrue(readBytes > 0);
        assertTrue(Arrays.equals(Arrays.copyOfRange(buf, 0, readBytes), Arrays.copyOfRange(data, moved, moved + readBytes)));
        moved += readBytes;
    }
    is.close();
    bucket.free();
}

46. EncryptedRandomAccessBucketTest#testIrregularWritesNotOverlapping()

View license
public void testIrregularWritesNotOverlapping() throws IOException {
    Random r = new Random(6032405);
    int length = 1024 * 64 + 1;
    byte[] data = new byte[length];
    RandomAccessBucket bucket = (RandomAccessBucket) makeBucket(length);
    OutputStream os = bucket.getOutputStream();
    r.nextBytes(data);
    for (int written = 0; written < length; ) {
        int toWrite = Math.min(length - written, 4095);
        os.write(data, written, toWrite);
        written += toWrite;
    }
    os.close();
    InputStream is = bucket.getInputStream();
    for (int moved = 0; moved < length; ) {
        // Co-prime with 4095
        int readBytes = Math.min(length - moved, 4093);
        byte[] buf = new byte[readBytes];
        readBytes = is.read(buf);
        assertTrue(readBytes > 0);
        assertTrue(Arrays.equals(Arrays.copyOfRange(buf, 0, readBytes), Arrays.copyOfRange(data, moved, moved + readBytes)));
        moved += readBytes;
    }
    is.close();
    bucket.free();
}

47. RandomAccessFileWrapperTest#testStoreTo()

View license
public void testStoreTo() throws IOException, StorageFormatException, ResumeFailedException {
    File tempFile = File.createTempFile("test-storeto", ".tmp", base);
    byte[] buf = new byte[4096];
    Random r = new Random(1267612);
    r.nextBytes(buf);
    FileRandomAccessBuffer rafw = new FileRandomAccessBuffer(tempFile, buf.length, false);
    rafw.pwrite(0, buf, 0, buf.length);
    byte[] tmp = new byte[buf.length];
    rafw.pread(0, tmp, 0, buf.length);
    assertArrayEquals(buf, tmp);
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    DataOutputStream dos = new DataOutputStream(baos);
    rafw.storeTo(dos);
    dos.close();
    rafw.close();
    DataInputStream dis = new DataInputStream(new ByteArrayInputStream(baos.toByteArray()));
    FileRandomAccessBuffer restored = (FileRandomAccessBuffer) BucketTools.restoreRAFFrom(dis, null, null, null);
    assertEquals(buf.length, restored.size());
    assertEquals(rafw, restored);
    tmp = new byte[buf.length];
    restored.pread(0, tmp, 0, buf.length);
    assertArrayEquals(buf, tmp);
    restored.close();
    restored.free();
}

48. TempBucketFactoryRAFBase#testBucketToRAFCallTwiceArray()

Project: fred
Source File: TempBucketFactoryRAFBase.java
View license
public void testBucketToRAFCallTwiceArray() throws IOException {
    int len = 4095;
    Random r = new Random(21162101);
    TempBucket bucket = (TempBucket) factory.makeBucket(1024);
    byte[] buf = new byte[len];
    r.nextBytes(buf);
    OutputStream os = bucket.getOutputStream();
    os.write(buf.clone());
    os.close();
    assertTrue(bucket.isRAMBucket());
    assertEquals(len, bucket.size());
    TempRandomAccessBuffer raf = (TempRandomAccessBuffer) bucket.toRandomAccessBuffer();
    assertTrue(raf != null);
    raf = (TempRandomAccessBuffer) bucket.toRandomAccessBuffer();
    assertTrue(raf != null);
    raf.close();
    raf.free();
}

49. TempBucketFactoryRAFBase#testBucketToRAFCallTwiceFile()

Project: fred
Source File: TempBucketFactoryRAFBase.java
View license
public void testBucketToRAFCallTwiceFile() throws IOException {
    int len = 4095;
    Random r = new Random(21162101);
    TempBucket bucket = (TempBucket) factory.makeBucket(1024);
    byte[] buf = new byte[len];
    r.nextBytes(buf);
    OutputStream os = bucket.getOutputStream();
    os.write(buf.clone());
    os.close();
    assertTrue(bucket.isRAMBucket());
    assertEquals(len, bucket.size());
    assertTrue(bucket.migrateToDisk());
    TempRandomAccessBuffer raf = (TempRandomAccessBuffer) bucket.toRandomAccessBuffer();
    assertTrue(raf != null);
    raf = (TempRandomAccessBuffer) bucket.toRandomAccessBuffer();
    assertTrue(raf != null);
    raf.close();
    raf.free();
}

50. TempBucketFactoryRAFBase#testBucketToRAFFreeBucketWhileArray()

Project: fred
Source File: TempBucketFactoryRAFBase.java
View license
public void testBucketToRAFFreeBucketWhileArray() throws IOException {
    int len = 4095;
    Random r = new Random(21162101);
    TempBucket bucket = (TempBucket) factory.makeBucket(1024);
    byte[] buf = new byte[len];
    r.nextBytes(buf);
    OutputStream os = bucket.getOutputStream();
    os.write(buf.clone());
    os.close();
    assertTrue(bucket.isRAMBucket());
    assertEquals(len, bucket.size());
    bucket.getInputStream().close();
    bucket.free();
    try {
        TempRandomAccessBuffer raf = (TempRandomAccessBuffer) bucket.toRandomAccessBuffer();
        fail();
    } catch (IOException e) {
    }
}

51. LimitedInputStreamTest#setUp()

Project: fresco
Source File: LimitedInputStreamTest.java
View license
@Before
public void setUp() {
    mData = new byte[BYTES_LENGTH];
    mReadBuffer = new byte[BYTES_LENGTH];
    final Random random = new Random(RANDOM_SEED);
    random.nextBytes(mData);
    mZeroTail = new byte[BYTES_LENGTH - LIMITED_LENGTH];
    Arrays.fill(mZeroTail, (byte) 0);
    mOriginalStream = new ByteArrayInputStream(mData);
    mLimitedStream = new LimitedInputStream(mOriginalStream, LIMITED_LENGTH);
}

52. GuidTest#testUniqueReplicable()

Project: gobblin
Source File: GuidTest.java
View license
// Obviously not an extensive test, but better than nothing.
@Test
public void testUniqueReplicable() {
    Random random = new Random();
    byte[] b = new byte[10];
    random.nextBytes(b);
    Assert.assertEquals(new Guid(b), new Guid(b));
    byte[] other = new byte[10];
    for (int i = 0; i < 1000; i++) {
        random.nextBytes(other);
        Assert.assertNotEquals(new Guid(b), new Guid(other));
    }
}

53. GuidTest#testSerDe()

Project: gobblin
Source File: GuidTest.java
View license
@Test
public void testSerDe() throws Exception {
    Random random = new Random();
    byte[] b = new byte[10];
    random.nextBytes(b);
    Guid guid = new Guid(b);
    Assert.assertEquals(guid.toString().length(), 2 * Guid.GUID_LENGTH);
    Assert.assertEquals(guid, Guid.deserialize(guid.toString()));
}

54. GuidTest#testFromHasGuid()

Project: gobblin
Source File: GuidTest.java
View license
@Test
public void testFromHasGuid() throws IOException {
    Random random = new Random();
    byte[] b = new byte[10];
    random.nextBytes(b);
    Guid guid = new Guid(b);
    HasGuid hasGuid = new Guid.SimpleHasGuid(guid);
    Assert.assertEquals(hasGuid.guid(), guid);
}

55. UnsignedBytesBenchmark#setUp()

Project: guava
Source File: UnsignedBytesBenchmark.java
View license
@BeforeExperiment
void setUp() throws Exception {
    Random r = new Random();
    ba1 = new byte[length];
    r.nextBytes(ba1);
    ba2 = Arrays.copyOf(ba1, ba1.length);
    // Differ at the last element
    ba3 = Arrays.copyOf(ba1, ba1.length);
    ba4 = Arrays.copyOf(ba1, ba1.length);
    ba3[ba1.length - 1] = (byte) 43;
    ba4[ba1.length - 1] = (byte) 42;
    javaImpl = UnsignedBytes.lexicographicalComparatorJavaImpl();
    unsafeImpl = UnsignedBytes.LexicographicalComparatorHolder.UnsafeComparator.INSTANCE;
}

56. HashTestUtils#assertIndependentHashers()

Project: guava
Source File: HashTestUtils.java
View license
static void assertIndependentHashers(HashFunction hashFunction) {
    int numActions = 100;
    // hashcodes from non-overlapping hash computations
    HashCode expected1 = randomHash(hashFunction, new Random(1L), numActions);
    HashCode expected2 = randomHash(hashFunction, new Random(2L), numActions);
    // equivalent, but overlapping, computations (should produce the same results as above)
    Random random1 = new Random(1L);
    Random random2 = new Random(2L);
    Hasher hasher1 = hashFunction.newHasher();
    Hasher hasher2 = hashFunction.newHasher();
    for (int i = 0; i < numActions; i++) {
        RandomHasherAction.pickAtRandom(random1).performAction(random1, ImmutableSet.of(hasher1));
        RandomHasherAction.pickAtRandom(random2).performAction(random2, ImmutableSet.of(hasher2));
    }
    Assert.assertEquals(expected1, hasher1.hash());
    Assert.assertEquals(expected2, hasher2.hash());
}

57. FilesTest#testMap_readWrite()

Project: guava
Source File: FilesTest.java
View license
public void testMap_readWrite() throws IOException {
    // Test data
    int size = 1024;
    byte[] expectedBytes = new byte[size];
    byte[] bytes = newPreFilledByteArray(1024);
    // Setup
    File file = createTempFile();
    Files.write(bytes, file);
    Random random = new Random();
    random.nextBytes(expectedBytes);
    // Test
    MappedByteBuffer map = Files.map(file, MapMode.READ_WRITE);
    map.put(expectedBytes);
    // Verify
    byte[] actualBytes = Files.toByteArray(file);
    assertTrue(Arrays.equals(expectedBytes, actualBytes));
}

58. TestGridmixRecord#eqSeedTest()

Project: hadoop-20
Source File: TestGridmixRecord.java
View license
static void eqSeedTest(GridmixRecord x, GridmixRecord y, int max) throws Exception {
    final Random r = new Random();
    final long s = r.nextLong();
    r.setSeed(s);
    LOG.info("eqSeed: " + s);
    assertEquals(x.fixedBytes(), y.fixedBytes());
    final int min = x.fixedBytes() + 1;
    final DataOutputBuffer out1 = new DataOutputBuffer();
    final DataOutputBuffer out2 = new DataOutputBuffer();
    for (int i = min; i < max; ++i) {
        final long seed = r.nextLong();
        setSerialize(x, seed, i, out1);
        setSerialize(y, seed, i, out2);
        assertEquals(x, y);
        assertEquals(x.hashCode(), y.hashCode());
        // verify written contents match
        assertEquals(out1.getLength(), out2.getLength());
        // assumes that writes will grow buffer deterministically
        assertEquals("Bad test", out1.getData().length, out2.getData().length);
        assertArrayEquals(out1.getData(), out2.getData());
    }
}

59. TestAvatarSetQuota#testAvatarSetQuota()

Project: hadoop-20
Source File: TestAvatarSetQuota.java
View license
@Test
public void testAvatarSetQuota() throws Exception {
    String test = "/testAvatarSetQuota";
    DFSTestUtil util = new DFSTestUtil(test, 10, 10, 1024);
    util.createFiles(fs, test);
    FSDataOutputStream out = fs.create(new Path(test + "/abc"));
    byte[] buffer = new byte[10 * 1024];
    Random r = new Random();
    r.nextBytes(buffer);
    out.write(buffer);
    out.sync();
    ((DistributedFileSystem) fs).setQuota(new Path(test), 5, -1);
    out.close();
    cluster.getStandbyAvatar(0).avatar.quiesceStandby(-1);
}

60. TestRaidDfs#createTestFilePartialLastBlock()

Project: hadoop-20
Source File: TestRaidDfs.java
View license
//
// Creates a file with partially full last block. Populate it with random
// data. Returns its crc.
//
public static long createTestFilePartialLastBlock(FileSystem fileSys, Path name, int repl, int numBlocks, long blocksize) throws IOException {
    CRC32 crc = new CRC32();
    Random rand = new Random();
    FSDataOutputStream stm = fileSys.create(name, true, fileSys.getConf().getInt("io.file.buffer.size", 4096), (short) repl, blocksize);
    // Write whole blocks.
    byte[] b = new byte[(int) blocksize];
    for (int i = 1; i < numBlocks; i++) {
        rand.nextBytes(b);
        stm.write(b);
        crc.update(b);
    }
    // Write partial block.
    b = new byte[(int) blocksize / 2 - 1];
    rand.nextBytes(b);
    stm.write(b);
    crc.update(b);
    stm.close();
    return crc.getValue();
}

61. TestDU#createFile()

Project: hadoop-20
Source File: TestDU.java
View license
private void createFile(File newFile, int size) throws IOException {
    // write random data so that filesystems with compression enabled (e.g., ZFS)
    // can't compress the file
    Random random = new Random();
    byte[] data = new byte[size];
    random.nextBytes(data);
    newFile.createNewFile();
    RandomAccessFile file = new RandomAccessFile(newFile, "rws");
    file.write(data);
    file.getFD().sync();
    file.close();
}

62. TestDatanodeFadvise#runFileFadvise()

Project: hadoop-20
Source File: TestDatanodeFadvise.java
View license
private void runFileFadvise(int advise, int expectedFadvise) throws Exception {
    nFadvise.set(0);
    InjectionHandler.set(new FadviseHandler(advise));
    DistributedFileSystem fs = (DistributedFileSystem) cluster.getFileSystem();
    WriteOptions options = new WriteOptions();
    options.setFadvise(advise);
    FSDataOutputStream out = fs.create(new Path("/test"), null, true, 1024, (short) 3, BLOCK_SIZE, 512, null, null, options);
    Random r = new Random();
    byte buffer[] = new byte[BLOCK_SIZE];
    r.nextBytes(buffer);
    out.write(buffer);
    out.close();
    assertTrue(NativeIO.isfadvisePossible());
    waitFadvise(expectedFadvise);
}

63. TestDecommissioningStatus#writeIncompleteFile()

View license
private FSDataOutputStream writeIncompleteFile(FileSystem fileSys, Path name, short repl) throws IOException {
    // create and write a file that contains three blocks of data
    FSDataOutputStream stm = fileSys.create(name, true, fileSys.getConf().getInt("io.file.buffer.size", 4096), repl, (long) blockSize);
    byte[] buffer = new byte[fileSize];
    Random rand = new Random(seed);
    rand.nextBytes(buffer);
    stm.write(buffer);
    // so that it is not garbage collected
    return stm;
}

64. TestAccessTime#createFile()

Project: hadoop-20
Source File: TestAccessTime.java
View license
private void createFile(FileSystem fileSys, Path name, int repl, boolean overwrite) throws IOException {
    // create and write a file that contains three blocks of data
    FSDataOutputStream stm = fileSys.create(name, overwrite, fileSys.getConf().getInt("io.file.buffer.size", 4096), (short) repl, (long) blockSize);
    byte[] buffer = new byte[fileSize];
    Random rand = new Random(seed);
    rand.nextBytes(buffer);
    sleep(1);
    stm.write(buffer);
    FileStatus stat = fileSys.getFileStatus(name);
    long atime1 = stat.getAccessTime();
    long mtime1 = stat.getModificationTime();
    System.out.println("Creating after write: accessTime = " + atime1 + " modTime = " + mtime1);
    sleep(1);
    stm.close();
    stat = fileSys.getFileStatus(name);
    atime1 = stat.getAccessTime();
    mtime1 = stat.getModificationTime();
    System.out.println("Creating after close: accessTime = " + atime1 + " modTime = " + mtime1);
}

65. TestAccessTime#appendFile()

Project: hadoop-20
Source File: TestAccessTime.java
View license
private void appendFile(FileSystem fileSys, Path name, int repl) throws IOException {
    // create and write a file that contains three blocks of data
    FSDataOutputStream stm = fileSys.append(name, fileSys.getConf().getInt("io.file.buffer.size", 4096));
    byte[] buffer = new byte[fileSize];
    Random rand = new Random(seed);
    rand.nextBytes(buffer);
    sleep(1);
    stm.write(buffer);
    FileStatus stat = fileSys.getFileStatus(name);
    long atime1 = stat.getAccessTime();
    long mtime1 = stat.getModificationTime();
    System.out.println("Appending after write: accessTime = " + atime1 + " modTime = " + mtime1);
    sleep(1);
    stm.close();
    stat = fileSys.getFileStatus(name);
    atime1 = stat.getAccessTime();
    mtime1 = stat.getModificationTime();
    System.out.println("Appending after close: accessTime = " + atime1 + " modTime = " + mtime1);
}

66. TestDecommission#writeFile()

Project: hadoop-20
Source File: TestDecommission.java
View license
private void writeFile(FileSystem fileSys, Path name, int repl) throws IOException {
    // create and write a file that contains three blocks of data
    FSDataOutputStream stm = fileSys.create(name, true, fileSys.getConf().getInt("io.file.buffer.size", 4096), (short) repl, (long) blockSize);
    byte[] buffer = new byte[fileSize];
    Random rand = new Random(seed);
    rand.nextBytes(buffer);
    stm.write(buffer);
    stm.close();
    LOG.info("Created file " + name + " with " + repl + " replicas.");
}

67. TestFileStatus#writeFile()

Project: hadoop-20
Source File: TestFileStatus.java
View license
private void writeFile(FileSystem fileSys, Path name, int repl, int fileSize, int blockSize) throws IOException {
    // create and write a file that contains three blocks of data
    FSDataOutputStream stm = fileSys.create(name, true, fileSys.getConf().getInt("io.file.buffer.size", 4096), (short) repl, (long) blockSize);
    byte[] buffer = new byte[fileSize];
    Random rand = new Random(seed);
    rand.nextBytes(buffer);
    stm.write(buffer);
    stm.close();
}

68. TestFileStatusCache#writeFile()

Project: hadoop-20
Source File: TestFileStatusCache.java
View license
private void writeFile(FileSystem fileSys, Path name, int repl, int fileSize, int blockSize) throws IOException {
    // create and write a file that contains three blocks of data
    FSDataOutputStream stm = fileSys.create(name, true, fileSys.getConf().getInt("io.file.buffer.size", 4096), (short) repl, (long) blockSize);
    byte[] buffer = new byte[fileSize];
    Random rand = new Random(seed);
    rand.nextBytes(buffer);
    stm.write(buffer);
    stm.close();
}

69. TestModTime#writeFile()

Project: hadoop-20
Source File: TestModTime.java
View license
private void writeFile(FileSystem fileSys, Path name, int repl) throws IOException {
    // create and write a file that contains three blocks of data
    FSDataOutputStream stm = fileSys.create(name, true, fileSys.getConf().getInt("io.file.buffer.size", 4096), (short) repl, (long) blockSize);
    byte[] buffer = new byte[fileSize];
    Random rand = new Random(seed);
    rand.nextBytes(buffer);
    stm.write(buffer);
    stm.close();
}

70. TestReplication#writeFile()

Project: hadoop-20
Source File: TestReplication.java
View license
private void writeFile(FileSystem fileSys, Path name, int repl) throws IOException {
    // create and write a file that contains three blocks of data
    FSDataOutputStream stm = fileSys.create(name, true, fileSys.getConf().getInt("io.file.buffer.size", 4096), (short) repl, (long) blockSize);
    byte[] buffer = new byte[fileSize];
    Random rand = new Random(seed);
    rand.nextBytes(buffer);
    stm.write(buffer);
    stm.close();
}

71. TestSeekBug#seekReadFile()

Project: hadoop-20
Source File: TestSeekBug.java
View license
private void seekReadFile(FileSystem fileSys, Path name) throws IOException {
    FSDataInputStream stm = fileSys.open(name, 4096);
    byte[] expected = new byte[ONEMB];
    Random rand = new Random(seed);
    rand.nextBytes(expected);
    // First read 128 bytes to set count in BufferedInputStream
    byte[] actual = new byte[128];
    stm.read(actual, 0, actual.length);
    // Now read a byte array that is bigger than the internal buffer
    actual = new byte[100000];
    stm.read(actual, 0, actual.length);
    checkAndEraseData(actual, 128, expected, "First Read Test");
    // now do a small seek, within the range that is already read
    // 4 byte seek
    stm.seek(96036);
    actual = new byte[128];
    stm.read(actual, 0, actual.length);
    checkAndEraseData(actual, 96036, expected, "Seek Bug");
    // all done
    stm.close();
}

72. TestTFileByteArrays#testFailureKeyLongerThan64K()

Project: hadoop-20
Source File: TestTFileByteArrays.java
View license
@Test
public void testFailureKeyLongerThan64K() throws IOException {
    if (skip)
        return;
    byte[] buf = new byte[64 * K + 1];
    Random rand = new Random();
    rand.nextBytes(buf);
    try {
        writer.append(buf, "valueX".getBytes());
    } catch (IndexOutOfBoundsException e) {
    }
    closeOutput();
}

73. TestIndexedSort#sortSorted()

Project: hadoop-20
Source File: TestIndexedSort.java
View license
public void sortSorted(IndexedSorter sorter) throws Exception {
    final int SAMPLE = 500;
    int[] values = new int[SAMPLE];
    Random r = new Random();
    long seed = r.nextLong();
    r.setSeed(seed);
    System.out.println("testSorted seed: " + seed + "(" + sorter.getClass().getName() + ")");
    for (int i = 0; i < SAMPLE; ++i) {
        values[i] = r.nextInt(100);
    }
    Arrays.sort(values);
    SampleSortable s = new SampleSortable(values);
    sorter.sort(s, 0, SAMPLE);
    int[] check = s.getSorted();
    assertTrue(Arrays.toString(values) + "\ndoesn't match\n" + Arrays.toString(check), Arrays.equals(values, check));
}

74. TestDU#createFile()

Project: hadoop-common
Source File: TestDU.java
View license
private void createFile(File newFile, int size) throws IOException {
    // write random data so that filesystems with compression enabled (e.g., ZFS)
    // can't compress the file
    Random random = new Random();
    byte[] data = new byte[size];
    random.nextBytes(data);
    newFile.createNewFile();
    RandomAccessFile file = new RandomAccessFile(newFile, "rws");
    file.write(data);
    file.getFD().sync();
    file.close();
}

75. TestDecommission#writeFile()

Project: hadoop-common
Source File: TestDecommission.java
View license
private void writeFile(FileSystem fileSys, Path name, int repl) throws IOException {
    // create and write a file that contains three blocks of data
    FSDataOutputStream stm = fileSys.create(name, true, fileSys.getConf().getInt("io.file.buffer.size", 4096), (short) repl, (long) blockSize);
    byte[] buffer = new byte[fileSize];
    Random rand = new Random(seed);
    rand.nextBytes(buffer);
    stm.write(buffer);
    stm.close();
}

76. TestFileStatus#writeFile()

Project: hadoop-common
Source File: TestFileStatus.java
View license
private void writeFile(FileSystem fileSys, Path name, int repl, int fileSize, int blockSize) throws IOException {
    // create and write a file that contains three blocks of data
    FSDataOutputStream stm = fileSys.create(name, true, fileSys.getConf().getInt("io.file.buffer.size", 4096), (short) repl, (long) blockSize);
    byte[] buffer = new byte[fileSize];
    Random rand = new Random(seed);
    rand.nextBytes(buffer);
    stm.write(buffer);
    stm.close();
}

77. TestModTime#writeFile()

Project: hadoop-common
Source File: TestModTime.java
View license
private void writeFile(FileSystem fileSys, Path name, int repl) throws IOException {
    // create and write a file that contains three blocks of data
    FSDataOutputStream stm = fileSys.create(name, true, fileSys.getConf().getInt("io.file.buffer.size", 4096), (short) repl, (long) blockSize);
    byte[] buffer = new byte[fileSize];
    Random rand = new Random(seed);
    rand.nextBytes(buffer);
    stm.write(buffer);
    stm.close();
}

78. TestReplication#writeFile()

Project: hadoop-common
Source File: TestReplication.java
View license
private void writeFile(FileSystem fileSys, Path name, int repl) throws IOException {
    // create and write a file that contains three blocks of data
    FSDataOutputStream stm = fileSys.create(name, true, fileSys.getConf().getInt("io.file.buffer.size", 4096), (short) repl, (long) blockSize);
    byte[] buffer = new byte[fileSize];
    Random rand = new Random(seed);
    rand.nextBytes(buffer);
    stm.write(buffer);
    stm.close();
}

79. TestSeekBug#seekReadFile()

Project: hadoop-common
Source File: TestSeekBug.java
View license
private void seekReadFile(FileSystem fileSys, Path name) throws IOException {
    FSDataInputStream stm = fileSys.open(name, 4096);
    byte[] expected = new byte[ONEMB];
    Random rand = new Random(seed);
    rand.nextBytes(expected);
    // First read 128 bytes to set count in BufferedInputStream
    byte[] actual = new byte[128];
    stm.read(actual, 0, actual.length);
    // Now read a byte array that is bigger than the internal buffer
    actual = new byte[100000];
    stm.read(actual, 0, actual.length);
    checkAndEraseData(actual, 128, expected, "First Read Test");
    // now do a small seek, within the range that is already read
    // 4 byte seek
    stm.seek(96036);
    actual = new byte[128];
    stm.read(actual, 0, actual.length);
    checkAndEraseData(actual, 96036, expected, "Seek Bug");
    // all done
    stm.close();
}

80. TestIndexedSort#sortSorted()

Project: hadoop-common
Source File: TestIndexedSort.java
View license
public void sortSorted(IndexedSorter sorter) throws Exception {
    final int SAMPLE = 500;
    int[] values = new int[SAMPLE];
    Random r = new Random();
    long seed = r.nextLong();
    r.setSeed(seed);
    System.out.println("testSorted seed: " + seed + "(" + sorter.getClass().getName() + ")");
    for (int i = 0; i < SAMPLE; ++i) {
        values[i] = r.nextInt(100);
    }
    Arrays.sort(values);
    SampleSortable s = new SampleSortable(values);
    sorter.sort(s, 0, SAMPLE);
    int[] check = s.getSorted();
    assertTrue(Arrays.toString(values) + "\ndoesn't match\n" + Arrays.toString(check), Arrays.equals(values, check));
}

81. TestDecommission#writeFile()

Project: hadoop-hdfs
Source File: TestDecommission.java
View license
private void writeFile(FileSystem fileSys, Path name, int repl) throws IOException {
    // create and write a file that contains three blocks of data
    FSDataOutputStream stm = fileSys.create(name, true, fileSys.getConf().getInt("io.file.buffer.size", 4096), (short) repl, (long) blockSize);
    byte[] buffer = new byte[fileSize];
    Random rand = new Random(seed);
    rand.nextBytes(buffer);
    stm.write(buffer);
    stm.close();
}

82. TestFileStatus#writeFile()

Project: hadoop-hdfs
Source File: TestFileStatus.java
View license
private void writeFile(FileSystem fileSys, Path name, int repl, int fileSize, int blockSize) throws IOException {
    // create and write a file that contains three blocks of data
    FSDataOutputStream stm = fileSys.create(name, true, fileSys.getConf().getInt("io.file.buffer.size", 4096), (short) repl, (long) blockSize);
    byte[] buffer = new byte[fileSize];
    Random rand = new Random(seed);
    rand.nextBytes(buffer);
    stm.write(buffer);
    stm.close();
}

83. TestModTime#writeFile()

Project: hadoop-hdfs
Source File: TestModTime.java
View license
private void writeFile(FileSystem fileSys, Path name, int repl) throws IOException {
    // create and write a file that contains three blocks of data
    FSDataOutputStream stm = fileSys.create(name, true, fileSys.getConf().getInt("io.file.buffer.size", 4096), (short) repl, (long) blockSize);
    byte[] buffer = new byte[fileSize];
    Random rand = new Random(seed);
    rand.nextBytes(buffer);
    stm.write(buffer);
    stm.close();
}

84. TestReplication#writeFile()

Project: hadoop-hdfs
Source File: TestReplication.java
View license
private void writeFile(FileSystem fileSys, Path name, int repl) throws IOException {
    // create and write a file that contains three blocks of data
    FSDataOutputStream stm = fileSys.create(name, true, fileSys.getConf().getInt("io.file.buffer.size", 4096), (short) repl, (long) blockSize);
    byte[] buffer = new byte[fileSize];
    Random rand = new Random(seed);
    rand.nextBytes(buffer);
    stm.write(buffer);
    stm.close();
}

85. TestSeekBug#seekReadFile()

Project: hadoop-hdfs
Source File: TestSeekBug.java
View license
private void seekReadFile(FileSystem fileSys, Path name) throws IOException {
    FSDataInputStream stm = fileSys.open(name, 4096);
    byte[] expected = new byte[ONEMB];
    Random rand = new Random(seed);
    rand.nextBytes(expected);
    // First read 128 bytes to set count in BufferedInputStream
    byte[] actual = new byte[128];
    stm.read(actual, 0, actual.length);
    // Now read a byte array that is bigger than the internal buffer
    actual = new byte[100000];
    stm.read(actual, 0, actual.length);
    checkAndEraseData(actual, 128, expected, "First Read Test");
    // now do a small seek, within the range that is already read
    // 4 byte seek
    stm.seek(96036);
    actual = new byte[128];
    stm.read(actual, 0, actual.length);
    checkAndEraseData(actual, 96036, expected, "Seek Bug");
    // all done
    stm.close();
}

86. ConstRateAdaptor#nextChunk()

Project: HiTune
Source File: ConstRateAdaptor.java
View license
public ChunkImpl nextChunk(int arraySize) {
    byte[] data = new byte[arraySize];
    Random dataPattern = new Random(offset ^ seed);
    long s = this.seed;
    offset += data.length;
    dataPattern.nextBytes(data);
    for (int i = 0; i < 8; ++i) {
        data[7 - i] = (byte) (s & 0xFF);
        s >>= 8;
    }
    ChunkImpl evt = new ChunkImpl(type, "random (" + this.seed + ")", offset, data, this);
    return evt;
}

87. ConstRateAdaptor#checkChunk()

Project: HiTune
Source File: ConstRateAdaptor.java
View license
public static boolean checkChunk(Chunk chunk) {
    byte[] data = chunk.getData();
    byte[] correctData = new byte[data.length];
    long seed = 0;
    for (int i = 0; i < 8; ++i) seed = (seed << 8) | (0xFF & data[i]);
    seed ^= (chunk.getSeqID() - data.length);
    Random dataPattern = new Random(seed);
    dataPattern.nextBytes(correctData);
    for (int i = 8; i < data.length; ++i) if (data[i] != correctData[i])
        return false;
    return true;
}

88. TempFileUtil#makeBinary()

Project: HiTune
Source File: TempFileUtil.java
View license
public static File makeBinary(int length) throws IOException {
    File tmpOutput = new File(System.getProperty("test.build.data", "/tmp"), "chukwaTest");
    FileOutputStream fos = new FileOutputStream(tmpOutput);
    Random r = new Random();
    byte[] randomData = new byte[length];
    r.nextBytes(randomData);
    // need data to end with \n since default
    randomData[length - 1] = '\n';
    // tailer uses that
    fos.write(randomData);
    fos.flush();
    fos.close();
    return tmpOutput;
}

89. HuffmanTest#testHuffman()

Project: hpack
Source File: HuffmanTest.java
View license
@Test
public void testHuffman() throws IOException {
    String s = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
    for (int i = 0; i < s.length(); i++) {
        roundTrip(s.substring(0, i));
    }
    Random random = new Random(123456789L);
    byte[] buf = new byte[4096];
    random.nextBytes(buf);
    roundTrip(buf);
}

90. TestHttpAsync#testSinglePost()

Project: httpasyncclient
Source File: TestHttpAsync.java
View license
@Test
public void testSinglePost() throws Exception {
    byte[] b1 = new byte[1024];
    Random rnd = new Random(System.currentTimeMillis());
    rnd.nextBytes(b1);
    HttpPost httppost = new HttpPost("/echo/stuff");
    httppost.setEntity(new NByteArrayEntity(b1));
    Future<HttpResponse> future = this.httpclient.execute(this.target, httppost, null);
    HttpResponse response = future.get();
    Assert.assertNotNull(response);
    Assert.assertEquals(200, response.getStatusLine().getStatusCode());
    HttpEntity entity = response.getEntity();
    Assert.assertNotNull(entity);
    byte[] b2 = EntityUtils.toByteArray(entity);
    Assert.assertArrayEquals(b1, b2);
}

91. TestHttpsAsync#testSinglePost()

Project: httpasyncclient
Source File: TestHttpsAsync.java
View license
@Test
public void testSinglePost() throws Exception {
    byte[] b1 = new byte[1024];
    Random rnd = new Random(System.currentTimeMillis());
    rnd.nextBytes(b1);
    HttpPost httppost = new HttpPost("/echo/stuff");
    httppost.setEntity(new NByteArrayEntity(b1));
    Future<HttpResponse> future = this.httpclient.execute(this.target, httppost, null);
    HttpResponse response = future.get();
    Assert.assertNotNull(response);
    Assert.assertEquals(200, response.getStatusLine().getStatusCode());
    HttpEntity entity = response.getEntity();
    Assert.assertNotNull(entity);
    byte[] b2 = EntityUtils.toByteArray(entity);
    Assert.assertArrayEquals(b1, b2);
}

92. NotificationIteratorTest#testLots()

View license
@Test
public void testLots() {
    IteratorScope scope = IteratorScope.scan;
    Random rand = new Random(42L);
    TestData input = new TestData();
    for (int i = 0; i < 1000; i++) {
        int maxTs = Math.max(1, rand.nextInt(50));
        for (int j = 0; j < maxTs; j++) {
            input.add("row" + i + " ntfy foo:baz " + j, "");
        }
    }
    TestData output = new TestData(newNI(input, scope, true));
    rand = new Random(42L);
    TestData expected = new TestData();
    for (int i = 0; i < 1000; i++) {
        int maxTs = Math.max(1, rand.nextInt(50)) - 1;
        expected.add("row" + i + " ntfy foo:baz " + maxTs, "");
    }
    Assert.assertEquals(expected, output);
}

93. HashMapTest#test_putAllLjava_util_Map_Resize()

Project: j2objc
Source File: HashMapTest.java
View license
public void test_putAllLjava_util_Map_Resize() {
    Random rnd = new Random(666);
    Map<Integer, Integer> m1 = new HashMap<Integer, Integer>();
    int MID = 10000;
    for (int i = 0; i < MID; i++) {
        Integer j = rnd.nextInt();
        m1.put(j, j);
    }
    Map<Integer, Integer> m2 = new HashMap<Integer, Integer>();
    int HI = 30000;
    for (int i = MID; i < HI; i++) {
        Integer j = rnd.nextInt();
        m2.put(j, j);
    }
    m1.putAll(m2);
    rnd = new Random(666);
    for (int i = 0; i < HI; i++) {
        Integer j = rnd.nextInt();
        assertEquals(j, m1.get(j));
    }
}

94. BufferTest#equalsAndHashCodeSpanningSegments()

Project: j2objc
Source File: BufferTest.java
View license
@Test
public void equalsAndHashCodeSpanningSegments() throws Exception {
    byte[] data = new byte[1024 * 1024];
    Random dice = new Random(0);
    dice.nextBytes(data);
    Buffer a = bufferWithRandomSegmentLayout(dice, data);
    Buffer b = bufferWithRandomSegmentLayout(dice, data);
    assertTrue(a.equals(b));
    assertTrue(a.hashCode() == b.hashCode());
    // Change a single byte.
    data[data.length / 2]++;
    Buffer c = bufferWithRandomSegmentLayout(dice, data);
    assertFalse(a.equals(c));
    assertFalse(a.hashCode() == c.hashCode());
}

95. IndexInputStreamTest#checkStream()

View license
private void checkStream(int size, int buffer) throws IOException {
    Random rand = new Random();
    byte[] data = new byte[size];
    rand.nextBytes(data);
    Directory dir = new RAMDirectory();
    IndexOutput out = dir.createOutput("test");
    out.writeBytes(data, data.length);
    out.close();
    InputStream in = new IndexInputStream(dir.openInput("test"));
    if (buffer != 0) {
        in = new BufferedInputStream(in, buffer);
    }
    byte[] buf = new byte[3];
    int len;
    int pos = 0;
    while ((len = in.read(buf)) > -1) {
        for (int i = 0; i < len; i++, pos++) {
            assertEquals(data[pos], buf[i]);
        }
    }
    in.close();
    // assert length
    assertEquals(data.length, pos);
}

96. BinaryValueTest#setProperty()

Project: jackrabbit
Source File: BinaryValueTest.java
View license
protected Property setProperty(Node node, int length) throws RepositoryException {
    Random rand = new Random();
    byte[] data = new byte[length];
    rand.nextBytes(data);
    Binary b = vf.createBinary(new ByteArrayInputStream(data));
    //System.out.println(b.getClass() + ": " + System.identityHashCode(b));
    try {
        return node.setProperty(propertyName1, b);
    } finally {
        b.dispose();
    }
}

97. AbstractBlobStoreTest#doTest()

View license
private void doTest(int maxLength, int count) throws Exception {
    String[] s = new String[count * 2];
    Random r = new Random(0);
    for (int i = 0; i < s.length; ) {
        byte[] data = new byte[r.nextInt(maxLength)];
        r.nextBytes(data);
        s[i++] = store.writeBlob(new ByteArrayInputStream(data));
        s[i++] = store.writeBlob(new ByteArrayInputStream(data));
    }
    r.setSeed(0);
    for (int i = 0; i < s.length; ) {
        int expectedLen = r.nextInt(maxLength);
        byte[] expectedData = new byte[expectedLen];
        r.nextBytes(expectedData);
        assertEquals(expectedLen, store.getBlobLength(s[i++]));
        String id = s[i++];
        doTestRead(expectedData, expectedLen, id);
    }
}

98. IOUtilsTest#testSkipFully()

Project: jackrabbit-oak
Source File: IOUtilsTest.java
View license
public void testSkipFully() throws IOException {
    final Random r = new Random(1);
    byte[] data = new byte[1000];
    r.nextBytes(data);
    FilterInputStream in = new FilterInputStream(new ByteArrayInputStream(data)) {

        @Override
        public int read(byte[] buffer, int off, int max) throws IOException {
            return in.read(buffer, off, Math.min(10, max));
        }
    };
    in.mark(10000);
    IOUtils.skipFully(in, 1000);
    assertEquals(-1, in.read());
    in.reset();
    try {
        IOUtils.skipFully(in, 1001);
        fail();
    } catch (EOFException e) {
    }
}

99. RDBBlobStoreTest#testUpdateAndDelete()

View license
@Test
public void testUpdateAndDelete() throws Exception {
    byte[] data = new byte[256];
    Random r = new Random(0);
    r.nextBytes(data);
    byte[] digest = getDigest(data);
    RDBBlobStoreFriend.storeBlock(blobStore, digest, 0, data);
    String id = StringUtils.convertBytesToHex(digest);
    long until = System.currentTimeMillis() + 1000;
    while (System.currentTimeMillis() < until) {
        try {
            Thread.sleep(100);
        } catch (InterruptedException e) {
        }
    }
    // Force update to update timestamp
    long beforeUpdateTs = System.currentTimeMillis() - 100;
    RDBBlobStoreFriend.storeBlock(blobStore, digest, 0, data);
    // Metadata row should not have been touched
    Assert.assertFalse("entry was cleaned although it shouldn't have", blobStore.deleteChunks(ImmutableList.of(id), beforeUpdateTs));
    // Actual data row should still be present
    Assert.assertNotNull(RDBBlobStoreFriend.readBlockFromBackend(blobStore, digest));
}

100. RDBBlobStoreTest#testResilienceMissingMetaEntry()

View license
@Test
public void testResilienceMissingMetaEntry() throws Exception {
    int test = 1024 * 1024;
    byte[] data = new byte[test];
    Random r = new Random(0);
    r.nextBytes(data);
    byte[] digest = getDigest(data);
    RDBBlobStoreFriend.storeBlock(blobStore, digest, 0, data);
    byte[] data2 = RDBBlobStoreFriend.readBlockFromBackend(blobStore, digest);
    if (!Arrays.equals(data, data2)) {
        throw new Exception("data mismatch");
    }
    RDBBlobStoreFriend.killMetaEntry(blobStore, digest);
    // retry
    RDBBlobStoreFriend.storeBlock(blobStore, digest, 0, data);
    byte[] data3 = RDBBlobStoreFriend.readBlockFromBackend(blobStore, digest);
    if (!Arrays.equals(data, data3)) {
        throw new Exception("data mismatch");
    }
}