java.util.Random

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

1. 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());
}

2. 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;
}

3. TestCaseBase#doDeleteRecordTest()

Project: jackrabbit
Source File: TestCaseBase.java
View license
/**
     * Test {@link 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();
}

4. 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);
}

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. 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);
}

7. 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);
}

8. 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();
}

9. 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));
}

10. 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);
}

11. 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);
}

12. 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);
}

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. JNADirectMemoryTest#testCopyData()

Project: orientdb
Source File: JNADirectMemoryTest.java
View license
public void testCopyData() {
    final Random rnd = new Random();
    ODirectMemory directMemory = new OJNADirectMemory();
    byte[] value = new byte[256];
    rnd.nextBytes(value);
    long pointer = directMemory.allocate(value.length);
    directMemory.set(pointer, value, 0, value.length);
    directMemory.moveData(pointer, pointer + value.length / 2, value.length / 2);
    System.arraycopy(value, 0, value, value.length / 2, value.length / 2);
    Assert.assertEquals(value, directMemory.get(pointer, value.length));
    directMemory.free(pointer);
}

19. 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());
}

20. 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));
}

21. 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;
}

22. 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());
}

23. 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);
    }
}

24. 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();
}

25. 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();
}

26. 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())));
}

27. 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;
}

28. 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;
}

29. 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();
}

30. 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;
}

31. 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()????????????????
         */
/**
         * ??
         * ??????????????
         */
}

32. 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();
}

33. 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
}

34. 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);
}

35. 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;
}

36. 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);
}

37. 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();
}

38. 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();
}

39. 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);
}

40. 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();
}

41. 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);
}

42. 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();
    }
}

43. 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();
}

44. 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();
}

45. 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();
}

46. 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());
}

47. 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());
}

48. JNADirectMemoryTest#testCopyDataOverlapInterval()

Project: orientdb
Source File: JNADirectMemoryTest.java
View license
public void testCopyDataOverlapInterval() {
    final Random rnd = new Random();
    ODirectMemory directMemory = new OJNADirectMemory();
    byte[] value = new byte[256];
    rnd.nextBytes(value);
    long pointer = directMemory.allocate(value.length);
    directMemory.set(pointer, value, 0, value.length);
    directMemory.moveData(pointer + 2, pointer + 5, value.length / 3);
    System.arraycopy(value, 2, value, 5, value.length / 3);
    Assert.assertEquals(value, directMemory.get(pointer, value.length));
    directMemory.free(pointer);
}

49. JNADirectMemoryTest#testCopyDataOverlap()

Project: orientdb
Source File: JNADirectMemoryTest.java
View license
public void testCopyDataOverlap() {
    final Random rnd = new Random();
    ODirectMemory directMemory = new OJNADirectMemory();
    byte[] value = new byte[256];
    rnd.nextBytes(value);
    long pointer = directMemory.allocate(value.length);
    directMemory.set(pointer, value, 0, value.length);
    directMemory.moveData(pointer, pointer + 1, value.length / 3);
    System.arraycopy(value, 0, value, 1, value.length / 3);
    Assert.assertEquals(value, directMemory.get(pointer, value.length));
    directMemory.free(pointer);
}

50. JNADirectMemoryTest#testBytesWithOffset()

Project: orientdb
Source File: JNADirectMemoryTest.java
View license
public void testBytesWithOffset() {
    final Random rnd = new Random();
    ODirectMemory directMemory = new OJNADirectMemory();
    byte[] value = new byte[256];
    rnd.nextBytes(value);
    long pointer = directMemory.allocate(value.length);
    directMemory.set(pointer, value, value.length / 2, value.length / 2);
    Assert.assertEquals(directMemory.get(pointer, value.length / 2), Arrays.copyOfRange(value, value.length / 2, value.length));
    directMemory.free(pointer);
}

51. JNADirectMemoryTest#testBytesWithoutOffset()

Project: orientdb
Source File: JNADirectMemoryTest.java
View license
public void testBytesWithoutOffset() {
    final Random rnd = new Random();
    ODirectMemory directMemory = new OJNADirectMemory();
    byte[] value = new byte[256];
    rnd.nextBytes(value);
    long pointer = directMemory.allocate(value.length);
    directMemory.set(pointer, value, 0, value.length);
    Assert.assertEquals(directMemory.get(pointer, value.length), value);
    Assert.assertEquals(directMemory.get(pointer, value.length / 2), Arrays.copyOf(value, value.length / 2));
    byte[] result = new byte[value.length];
    directMemory.get(pointer, result, value.length / 2, value.length / 2);
    byte[] expectedResult = new byte[value.length];
    System.arraycopy(value, 0, expectedResult, expectedResult.length / 2, expectedResult.length / 2);
    Assert.assertEquals(result, expectedResult);
    directMemory.free(pointer);
}

52. JNADirectMemoryTest#testByte()

Project: orientdb
Source File: JNADirectMemoryTest.java
View license
public void testByte() {
    final Random rnd = new Random();
    ODirectMemory directMemory = new OJNADirectMemory();
    byte[] value = new byte[1];
    rnd.nextBytes(value);
    long pointer = directMemory.allocate(1);
    directMemory.setByte(pointer, value[0]);
    Assert.assertEquals(directMemory.getByte(pointer), value[0]);
    directMemory.free(pointer);
}

53. RandomStreamTest#testDoubleStream()

Project: openjdk
Source File: RandomStreamTest.java
View license
@Test
public void testDoubleStream() {
    final long seed = System.currentTimeMillis();
    final Random r1 = new Random(seed);
    final double[] a = new double[SIZE];
    for (int i = 0; i < SIZE; i++) {
        a[i] = r1.nextDouble();
    }
    // same seed
    final Random r2 = new Random(seed);
    final double[] b = r2.doubles().limit(SIZE).toArray();
    assertEquals(a, b);
}

54. RandomStreamTest#testLongStream()

Project: openjdk
Source File: RandomStreamTest.java
View license
@Test
public void testLongStream() {
    final long seed = System.currentTimeMillis();
    final Random r1 = new Random(seed);
    final long[] a = new long[SIZE];
    for (int i = 0; i < SIZE; i++) {
        a[i] = r1.nextLong();
    }
    // same seed
    final Random r2 = new Random(seed);
    final long[] b = r2.longs().limit(SIZE).toArray();
    assertEquals(a, b);
}

55. RandomStreamTest#testIntStream()

Project: openjdk
Source File: RandomStreamTest.java
View license
@Test
public void testIntStream() {
    final long seed = System.currentTimeMillis();
    final Random r1 = new Random(seed);
    final int[] a = new int[SIZE];
    for (int i = 0; i < SIZE; i++) {
        a[i] = r1.nextInt();
    }
    // same seed
    final Random r2 = new Random(seed);
    final int[] b = r2.ints().limit(SIZE).toArray();
    assertEquals(a, b);
}

56. EntryProtectionTest#setUp()

Project: openjdk
Source File: EntryProtectionTest.java
View license
private void setUp() {
    out.println("Using KEYSTORE_PATH:" + KEYSTORE_PATH);
    Utils.createKeyStore(Utils.KeyStoreType.pkcs12, KEYSTORE_PATH, ALIAS);
    Random rand = RandomFactory.getRandom();
    rand.nextBytes(SALT);
    out.print("Salt: ");
    for (byte b : SALT) {
        out.format("%02X ", b);
    }
    out.println("");
    PASSWORD_PROTECTION.add(new KeyStore.PasswordProtection(PASSWORD, "PBEWithMD5AndDES", new PBEParameterSpec(SALT, ITERATION_COUNT)));
    PASSWORD_PROTECTION.add(new KeyStore.PasswordProtection(PASSWORD, "PBEWithSHA1AndDESede", null));
    PASSWORD_PROTECTION.add(new KeyStore.PasswordProtection(PASSWORD, "PBEWithSHA1AndRC2_40", null));
    PASSWORD_PROTECTION.add(new KeyStore.PasswordProtection(PASSWORD, "PBEWithSHA1AndRC2_128", null));
    PASSWORD_PROTECTION.add(new KeyStore.PasswordProtection(PASSWORD, "PBEWithSHA1AndRC4_40", null));
    PASSWORD_PROTECTION.add(new KeyStore.PasswordProtection(PASSWORD, "PBEWithSHA1AndRC4_128", null));
}

57. ModPow65537#testSigning()

Project: openjdk
Source File: ModPow65537.java
View license
private static void testSigning(KeyPair kp) throws Exception {
    System.out.println(kp.getPublic());
    byte[] data = new byte[1024];
    Random random = RandomFactory.getRandom();
    random.nextBytes(data);
    Signature sig = Signature.getInstance("SHA1withRSA", "SunRsaSign");
    sig.initSign(kp.getPrivate());
    sig.update(data);
    byte[] sigBytes = sig.sign();
    sig.initVerify(kp.getPublic());
    sig.update(data);
    if (sig.verify(sigBytes) == false) {
        throw new Exception("signature verification failed");
    }
    System.out.println("OK");
}

58. BufferTest#equalsAndHashCodeSpanningSegments()

Project: okio
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());
}

59. R#captchaChar()

Project: nutz
Source File: R.java
View license
/**
     * ??????????+??(?????)??????
     * 
     * @param length
     *            ????
     * @param caseSensitivity
     *            ???????
     * @return
     */
public static String captchaChar(int length, boolean caseSensitivity) {
    StringBuilder sb = new StringBuilder();
    // ????????????
    Random rand = new Random();
    Random randdata = new Random();
    int data = 0;
    for (int i = 0; i < length; i++) {
        int index = rand.nextInt(caseSensitivity ? 3 : 2);
        // ?????????????????
        switch(index) {
            case 0:
                // ?????0~9, 0~9?ASCII?48~57
                data = randdata.nextInt(10);
                sb.append(data);
                break;
            case 1:
                // ??????ASCII?97~122(a-z)?????,
                data = randdata.nextInt(26) + 97;
                sb.append((char) data);
                break;
            case // caseSensitivity?true???, ???????
            2:
                // ??????ASCII?65~90(A~Z)?????
                data = randdata.nextInt(26) + 65;
                sb.append((char) data);
                break;
        }
    }
    return sb.toString();
}

60. HuffmanTest#testHuffman()

Project: netty
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);
}

61. BufferUtilsTest#testGetCompactClone()

Project: mina-sshd
Source File: BufferUtilsTest.java
View license
@Test
public void testGetCompactClone() {
    byte[] expected = getCurrentTestName().getBytes(StandardCharsets.UTF_8);
    final int testOffset = Byte.SIZE / 2;
    byte[] data = new byte[expected.length + 2 * testOffset];
    Random rnd = new Random(System.nanoTime());
    rnd.nextBytes(data);
    System.arraycopy(expected, 0, data, testOffset, expected.length);
    Buffer buf = ByteArrayBuffer.getCompactClone(data, testOffset, expected.length);
    assertEquals("Mismatched cloned buffer read position", 0, buf.rpos());
    assertEquals("Mismatched cloned buffer available size", expected.length, buf.available());
    byte[] actual = buf.array();
    assertNotSame("Original data not cloned", data, actual);
    assertArrayEquals("Mismatched cloned contents", expected, actual);
}

62. TopN#main()

Project: scouter
Source File: TopN.java
View license
public static void main(String[] args) {
    long stime = System.currentTimeMillis();
    TopN<Integer> list = new TopN<Integer>(1000, TopN.DIRECTION.DESC);
    Random r = new Random();
    r.setSeed(System.currentTimeMillis());
    for (int i = 0; i < 100000; i++) {
        list.add(new Integer(r.nextInt(100000)));
    }
    System.out.println(list.size() + " : " + list.getList());
    long etime = System.currentTimeMillis();
    System.out.println((etime - stime) + " ms");
}

63. ByteStorageConversionCheck#testRandomConversion()

View license
@Test
public void testRandomConversion() {
    byte[] bin = new byte[102400];
    char[] cin = new char[102400];
    byte[] bout = new byte[102400];
    Random r = new Random();
    r.nextBytes(bin);
    ByteStorageConversion.toChar(bin, 0, cin, 0, bin.length);
    ByteStorageConversion.toByte(cin, 0, bout, 0, cin.length);
    for (int i = 0; i < bin.length; i++) {
        if (bin[i] != bout[i]) {
            Assert.assertEquals("Internal Byte conversion failed at " + bin[i] + "=>" + (int) cin[i] + "=>" + bout[i], bin[i], bout[i]);
        }
    }
    log.info("Internal Byte (random set) conversion test Passed Ok");
}

64. SwiftFileHandlerTest#setUpClass()

Project: sakai
Source File: SwiftFileHandlerTest.java
View license
@BeforeClass
public static void setUpClass() throws IOException {
    Properties props = new Properties();
    try {
        props.load(SwiftFileHandlerTest.class.getResourceAsStream("/swift.properties"));
    } catch (IOException e) {
        System.out.println("Cannot read Swift configuration (src/test/resources/swift.properties)... Bailing out.");
        throw e;
    }
    swift.setEndpoint(props.getProperty("endpoint"));
    swift.setRegion(props.getProperty("region"));
    swift.setIdentity(props.getProperty("identity"));
    swift.setCredential(props.getProperty("credential"));
    swift.setDeleteEmptyContainers(Boolean.valueOf(props.getProperty("deleteEmptyContainers")));
    swift.init();
    Random r = new Random(System.currentTimeMillis());
    r.nextBytes(BINARY);
}

65. CompactIntSetTest#addRandom()

Project: S-Space
Source File: CompactIntSetTest.java
View license
@Test
public void addRandom() {
    Random r = new Random();
    long seed = System.currentTimeMillis();
    r.setSeed(seed);
    System.out.println("addRandom() seed: " + seed);
    Set<Integer> test = new CompactIntSet();
    Set<Integer> control = new HashSet<Integer>();
    for (int i = 0; i < 100; ++i) {
        int j = r.nextInt(1024);
        test.add(j);
        control.add(j);
    }
    assertEquals(control.size(), test.size());
    for (Integer i : test) assertTrue(control.contains(i));
}

66. OpenIntSetTest#addRandom()

Project: S-Space
Source File: OpenIntSetTest.java
View license
@Test
public void addRandom() {
    Random r = new Random();
    long seed = System.currentTimeMillis();
    r.setSeed(seed);
    System.out.println("addRandom() seed: " + seed);
    Set<Integer> test = new OpenIntSet();
    Set<Integer> control = new HashSet<Integer>();
    for (int i = 0; i < 100; ++i) {
        int j = r.nextInt(Integer.MAX_VALUE);
        test.add(j);
        control.add(j);
    }
    assertEquals(control.size(), test.size());
    for (Integer i : test) assertTrue(control.contains(i));
}

67. GroupCommunicationMessageCodecTest#testEncodeDecode()

View license
@Test(timeout = 1000)
public final void testEncodeDecode() {
    final Random r = new Random();
    final byte[] data = new byte[100];
    r.nextBytes(data);
    final GroupCommunicationMessage expMsg = Utils.bldVersionedGCM(GroupName.class, OperName.class, ReefNetworkGroupCommProtos.GroupCommMessage.Type.ChildAdd, "From", 0, "To", 1, data);
    final GroupCommunicationMessageCodec codec = new GroupCommunicationMessageCodec();
    final GroupCommunicationMessage actMsg1 = codec.decode(codec.encode(expMsg));
    Assert.assertEquals("decode(encode(msg)): ", expMsg, actMsg1);
    final ByteArrayOutputStream baos = new ByteArrayOutputStream();
    final DataOutputStream daos = new DataOutputStream(baos);
    codec.encodeToStream(expMsg, daos);
    final GroupCommunicationMessage actMsg2 = codec.decodeFromStream(new DataInputStream(new ByteArrayInputStream(baos.toByteArray())));
    Assert.assertEquals("decodeFromStream(encodeToStream(msg)): ", expMsg, actMsg2);
}

68. NestedRandomTest#addSamples()

Project: log-synth
Source File: NestedRandomTest.java
View license
private void addSamples(Multiset<Integer> samples, NestedRandom twig) {
    int i = 0;
    int sample = 0;
    Random r = null;
    for (NestedRandom leaf : twig) {
        assertEquals(twig.get(i).random().nextDouble(), leaf.random().nextDouble(), 0);
        r = leaf.random();
        sample = r.nextInt();
        samples.add(sample);
        samples.add(leaf.get("q").random().nextInt());
        if (++i > ITERATIONS) {
            break;
        }
    }
    assertNotNull(r);
    Random rx = twig.get(ITERATIONS).random();
    assertEquals(sample, rx.nextInt());
    assertEquals(r.nextInt(), rx.nextInt());
}

69. ScramblingSinkFilter#getCipher()

Project: Launcher
Source File: ScramblingSinkFilter.java
View license
public static Cipher getCipher(int mode, String password) throws InvalidKeySpecException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, InvalidAlgorithmParameterException {
    // These parameters were used for encrypting lastlogin on old official Minecraft launchers
    Random random = new Random(0x29482c2L);
    byte salt[] = new byte[8];
    random.nextBytes(salt);
    PBEParameterSpec paramSpec = new PBEParameterSpec(salt, 5);
    SecretKeyFactory factory = SecretKeyFactory.getInstance("PBEWithMD5AndDES");
    SecretKey key = factory.generateSecret(new PBEKeySpec(password.toCharArray()));
    Cipher cipher = Cipher.getInstance("PBEWithMD5AndDES");
    cipher.init(mode, key, paramSpec);
    return cipher;
}

70. MiniDmxSerial#ping()

Project: PixelController
Source File: MiniDmxSerial.java
View license
/**
	 * send a serial ping command to the arduino board.
	 * 
	 * @return wheter ping was successfull or not
	 */
public boolean ping() {
    //the data is not really needed
    byte data[] = new byte[this.miniDmxPayload.payloadSize];
    //just make sure its initialized with RANDOM data, so it pass the "didFrameChange" method
    Random r = new Random();
    r.nextBytes(data);
    //just send a frame
    return sendFrame(data) > 0;
}

71. TestPigServer#testUniquePigTempDir()

Project: pig
Source File: TestPigServer.java
View license
@Test
public void testUniquePigTempDir() throws Throwable {
    Properties properties = PropertiesUtil.loadDefaultProperties();
    File pigTempDir = new File(tempDir, FILE_SEPARATOR + "tmp" + FILE_SEPARATOR + "test");
    properties.put("pig.temp.dir", pigTempDir.getPath());
    PigContext pigContext = new PigContext(ExecType.LOCAL, properties);
    pigContext.connect();
    FileLocalizer.setInitialized(false);
    Random r = new Random(5);
    FileLocalizer.setR(r);
    String tempPath1 = FileLocalizer.getTemporaryPath(pigContext).toString();
    FileLocalizer.setInitialized(false);
    r = new Random(5);
    FileLocalizer.setR(r);
    String tempPath2 = FileLocalizer.getTemporaryPath(pigContext).toString();
    assertFalse(tempPath1.toString().equals(tempPath2.toString()));
    // cleanup
    pigTempDir.delete();
    FileLocalizer.setInitialized(false);
}

72. TestDeleteOnFail#setUp()

Project: pig
Source File: TestDeleteOnFail.java
View license
@Before
public void setUp() throws Exception {
    tmpFile = File.createTempFile("test", ".txt");
    tmpFile.deleteOnExit();
    FileOutputStream fos = new FileOutputStream(tmpFile);
    PrintStream ps = new PrintStream(fos);
    Random r1 = new Random(5);
    Random r2 = new Random(3);
    for (int i = 0; i < LOOP_COUNT; i++) {
        ps.println((char) ('a' + r1.nextInt(26)) + "\t" + r2.nextInt(100));
    }
    ps.close();
    fos.close();
}

73. BufferGenerator#main()

Project: pgjdbc
Source File: BufferGenerator.java
View license
public static void main(String[] args) throws Exception {
    Random random = new Random();
    random.setSeed(new Date().getTime());
    OutputStream out = null;
    try {
        File outFile = new File("target", "buffer.txt");
        outFile.getParentFile().mkdir();
        out = new BufferedOutputStream(new FileOutputStream(outFile));
        for (long i = 0; i < ROW_COUNT; i++) {
            StringBuffer line = new StringBuffer();
            line.append("VERY_LONG_LINE_TO_ASSIST_IN_DETECTION_OF_ISSUE_366_#_").append(i).append('\t');
            // don't really care about uniformity for a test
            int letter = random.nextInt(26);
            // black magic
            char character = (char) ((int) 'A' + letter);
            line.append("VERY_LONG_STRING_TO_REPRODUCE_ISSUE_366_").append(character).append(character);
            line.append(character).append('\t').append(random.nextDouble()).append('\n');
            out.write(line.toString().getBytes("UTF-8"));
        }
    } finally {
        if (out != null) {
            out.close();
        }
    }
}

74. PredictorAlgorithm#main()

View license
/**
     * Simple command line program to test the algorithm.
     *
     * @param args The command line arguments.
     */
public static void main(String[] args) {
    Random rnd = new Random();
    int width = 5;
    int height = 5;
    int bpp = 3;
    byte[] raw = new byte[width * height * bpp];
    rnd.nextBytes(raw);
    System.out.println("raw:   ");
    dump(raw);
    for (int i = 10; i < 15; i++) {
        byte[] decoded = new byte[width * height * bpp];
        byte[] encoded = new byte[width * height * bpp];
        PredictorAlgorithm filter = PredictorAlgorithm.getFilter(i);
        filter.setWidth(width);
        filter.setHeight(height);
        filter.setBpp(bpp);
        filter.encode(raw, encoded);
        filter.decode(encoded, decoded);
        System.out.println(filter.getClass().getName());
        dump(decoded);
    }
}

75. TrSymKeyTest#testEncryptDecrypt()

Project: tahrir
Source File: TrSymKeyTest.java
View license
@Test
public void testEncryptDecrypt() {
    final TrSymKey key = TrCrypto.createAesKey();
    final Random r = new Random();
    final byte[] plainText_ = new byte[512];
    r.nextBytes(plainText_);
    System.out.format("PlainText size: %s bytes%n", plainText_.length);
    final ByteArraySegment plainText = new ByteArraySegment(plainText_);
    final ByteArraySegment cypherText = key.encrypt(plainText);
    System.out.format("CypherText size: %s bytes%n", cypherText.length);
    final ByteArraySegment decryptedCypherText = key.decrypt(cypherText);
    Assert.assertEquals(decryptedCypherText, plainText);
}

76. 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();
}

77. 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();
}

78. 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();
}

79. 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();
}

80. 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();
}

81. 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));
    }
}

82. 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;
}

83. 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;
}

84. 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);
}

85. 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);
}

86. 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;
}

87. 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);
}

88. 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();
}

89. 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();
}

90. 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);
}

91. 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());
    }
}

92. 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));
}

93. 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());
}

94. 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;
}

95. 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);
}

96. 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()));
}

97. JAXRSReaderTest#testInputStreamImplementation()

Project: wink
Source File: JAXRSReaderTest.java
View license
/**
     * Tests a resource method invoked with a BufferedReader as a parameter.
     * This should fail with a 415 since the reader has no way to necessarily
     * wrap it to the type.
     * 
     * @throws HttpException
     * @throws IOException
     */
public void testInputStreamImplementation() throws HttpException, IOException {
    HttpClient client = new HttpClient();
    PostMethod postMethod = new PostMethod(getBaseURI() + "/providers/standard/reader/subclasses/shouldfail");
    byte[] barr = new byte[1000];
    Random r = new Random();
    r.nextBytes(barr);
    postMethod.setRequestEntity(new InputStreamRequestEntity(new ByteArrayInputStream(barr), "any/type"));
    try {
        client.executeMethod(postMethod);
        assertEquals(415, postMethod.getStatusCode());
    } finally {
        postMethod.releaseConnection();
    }
}

98. JAXRSInputStreamTest#testInputStreamImplementation()

Project: wink
Source File: JAXRSInputStreamTest.java
View license
/**
     * Tests a resource method invoked with a ByteArrayInputStream as a
     * parameter. This should fail with a 415 since the reader has no way to
     * necessarily wrap it to the type.
     * 
     * @throws HttpException
     * @throws IOException
     */
public void testInputStreamImplementation() throws HttpException, IOException {
    HttpClient client = new HttpClient();
    PostMethod postMethod = new PostMethod(getBaseURI() + "/providers/standard/inputstream/subclasses/shouldfail");
    byte[] barr = new byte[100000];
    Random r = new Random();
    r.nextBytes(barr);
    postMethod.setRequestEntity(new InputStreamRequestEntity(new ByteArrayInputStream(barr), "any/type"));
    try {
        client.executeMethod(postMethod);
        assertEquals(415, postMethod.getStatusCode());
    } finally {
        postMethod.releaseConnection();
    }
}

99. JAXRSDataSourceTest#testPostDataSourceSubclass()

Project: wink
Source File: JAXRSDataSourceTest.java
View license
/**
     * Tests posting to a DataSource subclass. This should result in a 415
     * error.
     * 
     * @throws HttpException
     * @throws IOException
     */
public void testPostDataSourceSubclass() throws HttpException, IOException {
    HttpClient client = new HttpClient();
    PostMethod postMethod = new PostMethod(getBaseURI() + "/providers/standard/datasource/subclass/should/fail");
    byte[] barr = new byte[1000];
    Random r = new Random();
    r.nextBytes(barr);
    postMethod.setRequestEntity(new InputStreamRequestEntity(new ByteArrayInputStream(barr), "text/plain"));
    postMethod.addRequestHeader("Accept", "text/plain");
    try {
        client.executeMethod(postMethod);
        assertEquals(415, postMethod.getStatusCode());
    } finally {
        postMethod.releaseConnection();
    }
}

100. JAXRSSourceTest#testSourceSubclassImplementation()

Project: wink
Source File: JAXRSSourceTest.java
View license
/**
     * Tests a resource method invoked with a SAXSource as a parameter. This
     * should fail with a 415 since the reader has no way to necessarily wrap it
     * to the type.
     * 
     * @throws HttpException
     * @throws IOException
     */
public void testSourceSubclassImplementation() throws HttpException, IOException {
    HttpClient client = new HttpClient();
    PostMethod postMethod = new PostMethod(getBaseURI() + "/providers/standard/source/subclasses/shouldfail");
    byte[] barr = new byte[1000];
    Random r = new Random();
    r.nextBytes(barr);
    postMethod.setRequestEntity(new InputStreamRequestEntity(new ByteArrayInputStream(barr), "application/xml"));
    try {
        client.executeMethod(postMethod);
        assertEquals(415, postMethod.getStatusCode());
    } finally {
        postMethod.releaseConnection();
    }
}