Here are the examples of the java api class java.util.Random taken from open source projects.
1. User#insecureRandom()
View licensepublic 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. TestCrcConcat#testConcatCrcBlocks()
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); }
4. HtmlCore#fireRandom()
View licensepublic 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()); }
5. 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); }
6. TestCaseBase#doDeleteRecordTest()
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(); }
7. BloomFilterUtilsTest#probability()
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); }
8. ByteBufUtilTest#notEqualsBufferUnderflow()
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)); }
9. ByteBufUtilTest#notEqualsBufferOverflow()
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)); }
10. ByteBufUtilTest#notEqualsBufferSubsections()
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)); }
11. ByteBufUtilTest#equalsBufferSubsections()
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)); }
12. ArraysTest#testParallelQuickSort()
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. ArraysTest#testQuickSort()
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); }
14. ArraysTest#testMergeSort()
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); }
15. MineshaftAlgorithm_Base#isValidLocation()
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)); }
16. PooledFileRandomAccessBufferTest#innerTestSimplePooling()
View licenseprivate 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(); }
17. 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); }
18. 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()); }
19. 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)); }
20. UUIDTypeTest#random()
View licensestatic 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; }
21. CollectionsTest#testMapWithLargePartition()
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()); }
22. PGPPacketTest#readBackTest()
View licenseprivate 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); } }
23. TestHelpers#GenerateFileData()
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(); }
24. MultipleSegmentUploaderTests#GenerateFileData()
View licenseprivate 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(); }
25. StreamTest#testStoreCopy()
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()))); }
26. StreamTest#storeAndCheckExpiringByteStreams()
View licenseprivate 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#storeAndCheckByteStreams()
View licenseprivate 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; }
28. 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(); }
29. HTTPBin#getGzippedResponse()
View licenseprivate 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; }
30. 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()???????????????? */ /** * ?? * ?????????????? */ }
31. TestUtils#randomMACAddress()
View licenseprivate 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(); }
32. NetherFortressAlgorithm#isValidLocation()
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 }
33. AlbianLogicIdService#makeStringUNID()
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); }
34. UUIDGenerator#generateDummyAddress()
View licensepublic 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; }
35. TestPagedByteArray#testReadWriteArray()
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); }
36. LuceneDocCollectorBenchmark#generateRowSource()
View licenseprivate 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(); }
37. NativeMacLayeredInputStreamTest#setUp()
View licensepublic 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. NativeGCMCipherInputStreamTest#setUp()
View licenseprotected 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); }
39. CipherWriteBenchmark#setUp()
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(); }
40. CipherReadBenchmark#setUp()
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); }
41. ZipUtilsTest#setUp()
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(); } }
42. EncryptedRandomAccessBucketTest#testIrregularWritesNotOverlapping()
View licensepublic 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(); }
43. EncryptedRandomAccessBucketTest#testIrregularWrites()
View licensepublic 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(); }
44. AEADStreamsTest#testCloseEarly()
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. 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()); }
46. 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()); }
47. JNADirectMemoryTest#testCopyDataOverlapInterval()
View licensepublic 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); }
48. JNADirectMemoryTest#testCopyDataOverlap()
View licensepublic 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); }
49. JNADirectMemoryTest#testCopyData()
View licensepublic 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); }
50. JNADirectMemoryTest#testBytesWithOffset()
View licensepublic 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()
View licensepublic 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()
View licensepublic 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()
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()
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()
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()
View licenseprivate 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()
View licenseprivate 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()
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()
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()
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()
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()
View licensepublic 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()
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()
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()
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()
View licenseprivate 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()
View licensepublic 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()
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()
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()
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()
View licensepublic 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()
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()
View licenseprivate 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()
View licenseprivate 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()
View licenseprivate 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()
View licenseprivate 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()
View licenseprivate 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. TestIndexedSort#sortSorted()
View licensepublic 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)); }
82. TestSeekBug#seekReadFile()
View licenseprivate 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(); }
83. TestReplication#writeFile()
View licenseprivate 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. TestModTime#writeFile()
View licenseprivate 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. TestFileStatus#writeFile()
View licenseprivate 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(); }
86. TestDecommission#writeFile()
View licenseprivate 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(); }
87. TestDU#createFile()
View licenseprivate 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(); }
88. TestIndexedSort#sortSorted()
View licensepublic 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)); }
89. TestTFileByteArrays#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(); }
90. TestSeekBug#seekReadFile()
View licenseprivate 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(); }
91. TestReplication#writeFile()
View licenseprivate 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(); }
92. TestModTime#writeFile()
View licenseprivate 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(); }
93. TestFileStatusCache#writeFile()
View licenseprivate 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(); }
94. TestFileStatus#writeFile()
View licenseprivate 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(); }
95. TestDecommission#writeFile()
View licenseprivate 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."); }
96. ProtocolBaseCase#testStupidlyLargeSet()
View licensepublic void testStupidlyLargeSet() throws Exception { Random r = new Random(); SerializingTranscoder st = new SerializingTranscoder(); st.setCompressionThreshold(Integer.MAX_VALUE); byte[] data = new byte[21 * 1024 * 1024]; r.nextBytes(data); try { client.set("bigassthing", 60, data, st).get(); fail("Didn't fail setting bigass thing."); } catch (IllegalArgumentException e) { assertEquals("Cannot cache data larger than " + CachedData.MAX_SIZE + " bytes " + "(you tried to cache a " + data.length + " byte object)", e.getMessage()); } // But I should still be able to do something. client.set("k", 5, "Blah"); assertEquals("Blah", client.get("k")); }
97. ProtocolBaseCase#testStupidlyLargeSetAndSizeOverride()
View licensepublic void testStupidlyLargeSetAndSizeOverride() throws Exception { Random r = new Random(); SerializingTranscoder st = new SerializingTranscoder(Integer.MAX_VALUE); st.setCompressionThreshold(Integer.MAX_VALUE); byte[] data = new byte[21 * 1024 * 1024]; r.nextBytes(data); try { client.set("bigassthing", 60, data, st).get(); fail("Didn't fail setting bigass thing."); } catch (ExecutionException e) { System.err.println("Successful failure setting bigassthing. Ass size " + data.length + " bytes doesn't fit."); e.printStackTrace(); OperationException oe = (OperationException) e.getCause(); assertSame(OperationErrorType.SERVER, oe.getType()); } // But I should still be able to do something. client.set("k", 5, "Blah"); assertEquals("Blah", client.get("k")); }
98. SegmentIdTableTest#randomized()
View license@Test public void randomized() throws IOException { SegmentIdFactory maker = newSegmentIdMaker(); final SegmentIdTable tbl = new SegmentIdTable(); List<SegmentId> refs = new ArrayList<SegmentId>(); Random r = new Random(1); for (int i = 0; i < 16 * 1024; i++) { refs.add(tbl.newSegmentId(r.nextLong(), r.nextLong(), maker)); } assertEquals(16 * 1024, tbl.getEntryCount()); assertEquals(16 * 2048, tbl.getMapSize()); assertEquals(5, tbl.getMapRebuildCount()); r = new Random(1); for (int i = 0; i < 16 * 1024; i++) { refs.add(tbl.newSegmentId(r.nextLong(), r.nextLong(), maker)); assertEquals(16 * 1024, tbl.getEntryCount()); assertEquals(16 * 2048, tbl.getMapSize()); assertEquals(5, tbl.getMapRebuildCount()); } }
99. SegmentIdTableTest#randomized()
View license@Test public void randomized() throws IOException { SegmentTracker tracker = new MemoryStore().getTracker(); final SegmentIdTable tbl = new SegmentIdTable(tracker); List<SegmentId> refs = new ArrayList<SegmentId>(); Random r = new Random(1); for (int i = 0; i < 16 * 1024; i++) { refs.add(tbl.getSegmentId(r.nextLong(), r.nextLong())); } Assert.assertEquals(16 * 1024, tbl.getEntryCount()); Assert.assertEquals(16 * 2048, tbl.getMapSize()); Assert.assertEquals(5, tbl.getMapRebuildCount()); r = new Random(1); for (int i = 0; i < 16 * 1024; i++) { refs.add(tbl.getSegmentId(r.nextLong(), r.nextLong())); Assert.assertEquals(16 * 1024, tbl.getEntryCount()); Assert.assertEquals(16 * 2048, tbl.getMapSize()); Assert.assertEquals(5, tbl.getMapRebuildCount()); } }
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"); } }