Example usage for java.util Random nextBytes

List of usage examples for java.util Random nextBytes

Introduction

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

Prototype

public void nextBytes(byte[] bytes) 

Source Link

Document

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

Usage

From source file:org.apache.edgent.samples.utils.sensor.PeriodicRandomSensor.java

/**
 * Create a periodic sensor stream with readings from {@link Random#nextBytes(byte[])}.
 * @param t the topology to add the sensor stream to
 * @param periodMsec how frequently to generate a reading
 * @param nBytes the number of bytes in each reading tuple
 * @return the sensor value stream// w ww  .  j  a  v a2 s .c o m
 */
public TStream<Pair<Long, byte[]>> newBytes(Topology t, long periodMsec, int nBytes) {
    Random r = newRandom();
    return t.poll(() -> {
        byte[] bytes = new byte[nBytes];
        r.nextBytes(bytes);
        return new Pair<Long, byte[]>(System.currentTimeMillis(), bytes);
    }, periodMsec, TimeUnit.MILLISECONDS);
}

From source file:de.elomagic.carafile.client.CaraFileClientTest.java

@Test
public void testUpload() throws Exception {
    byte[] data = new byte[DEFAULT_PIECE_SIZE + 128];
    Random random = new Random();
    random.nextBytes(data);

    client.setRegistryURI(getURI()).uploadFile(new ByteArrayInputStream(data), "abc.txt", data.length);
}

From source file:org.apache.wink.itest.standard.JAXRSInputStreamTest.java

/**
 * Tests posting to an InputStream// w  w w.java 2 s.  c o  m
 * 
 * @throws HttpException
 * @throws IOException
 */
public void testPostInputStream() throws HttpException, IOException {
    HttpClient client = new HttpClient();

    PostMethod postMethod = new PostMethod(getBaseURI() + "/providers/standard/inputstream");
    byte[] barr = new byte[100000];
    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(200, postMethod.getStatusCode());
        InputStream is = postMethod.getResponseBodyAsStream();

        byte[] receivedBArr = new byte[barr.length];
        DataInputStream dis = new DataInputStream(is);
        dis.readFully(receivedBArr);

        int checkEOF = dis.read();
        assertEquals(-1, checkEOF);
        for (int c = 0; c < barr.length; ++c) {
            assertEquals(barr[c], receivedBArr[c]);
        }
        assertEquals("text/plain", postMethod.getResponseHeader("Content-Type").getValue());
        Header contentLengthHeader = postMethod.getResponseHeader("Content-Length");
        assertNull(contentLengthHeader == null ? "null" : contentLengthHeader.getValue(), contentLengthHeader);
    } finally {
        postMethod.releaseConnection();
    }
}

From source file:com.koda.integ.hbase.test.BlockCacheSimpleTest.java

/**
 * Test byte cacheable./*ww w  . j ava 2 s. co m*/
 *
 * @throws IOException Signals that an I/O exception has occurred.
 */
public void testByteCacheable() throws IOException {
    LOG.info("Test byte cacheable started");

    byte[] array = new byte[30000];
    Random r = new Random();
    r.nextBytes(array);

    ByteArrayCacheable bac = new ByteArrayCacheable(array);

    ByteBuffer buf = ByteBuffer.allocate(100000);

    bac.serialize(buf);

    buf.flip();

    ByteArrayCacheable bb = (ByteArrayCacheable) ByteArrayCacheable.deserializer.deserialize(buf);

    assertTrue(bb.equals(bac));
    LOG.info("Test byte cacheable finished");
}

From source file:com.google.code.jahath.common.io.SwappableInputStreamTest.java

@Test
public void test() throws Throwable {
    final SwappableInputStream swappableInputStream = new SwappableInputStream("test");
    final CRC actualCRC = new CRC();
    final AtomicReference<Throwable> thrown = new AtomicReference<Throwable>();
    Thread thread = new Thread(new Runnable() {
        public void run() {
            try {
                actualCRC.update(swappableInputStream);
            } catch (Throwable ex) {
                thrown.set(ex);//from w ww  .ja  v  a2 s.co m
            }
        }
    });
    thread.start();
    Random random = new Random();
    CRC expectedCRC = new CRC();
    for (int i = 0; i < 100; i++) {
        int len = 2048 + random.nextInt(4096);
        byte[] data = new byte[len];
        random.nextBytes(data);
        expectedCRC.update(data);
        CountingInputStream in = new CountingInputStream(new ByteArrayInputStream(data));
        swappableInputStream.swap(in);
        // Check that the stream has been consumed entirely
        Assert.assertEquals(len, in.getCount());
    }
    swappableInputStream.sendEndOfStream();
    thread.join();
    if (thrown.get() != null) {
        throw thrown.get();
    }
    Assert.assertEquals(expectedCRC.getValue(), actualCRC.getValue());
}

From source file:org.apache.jackrabbit.oak.plugins.document.persistentCache.CacheTest.java

@Test
public void test() throws Exception {
    FileUtils.deleteDirectory(new File("target/cacheTest"));
    PersistentCache cache = new PersistentCache("target/cacheTest,size=1,-compress");
    try {/*from   ww  w .  ja v a2  s .  c o  m*/
        MemoryBlobStore mem = new MemoryBlobStore();
        mem.setBlockSizeMin(100);
        BlobStore b = cache.wrapBlobStore(mem);
        Random r = new Random();
        for (int i = 0; i < 10000; i++) {
            byte[] data = new byte[100];
            r.nextBytes(data);
            String id = b.writeBlob(new ByteArrayInputStream(data));
            b.readBlob(id, 0, new byte[1], 0, 1);
        }
    } finally {
        cache.close();
    }
}

From source file:org.sakaiproject.content.impl.serialize.impl.test.MySQLByteStorage.java

@Test
public void testBlobData() throws SQLException {
    // run the test 10 times to make really certain there is no problem
    for (int k = 0; k < 10; k++) {
        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, cin.length);
        String sin = new String(cin);

        char[] cout = sin.toCharArray();
        ByteStorageConversion.toByte(cout, 0, bout, 0, cout.length);

        for (int i = 0; i < bin.length; i++) {
            Assert.assertEquals(/*from ww w.j av a 2  s.  c om*/
                    "Internal Byte conversion failed at " + bin[i] + "=>" + (int) cin[i] + "=>" + bout[i],
                    bin[i], bout[i]);
        }

        Connection connection = null;
        PreparedStatement statement = null;
        PreparedStatement statement2 = null;
        ResultSet rs = null;
        try {
            connection = tds.getConnection();
            statement = connection.prepareStatement("insert into blobtest ( id, bval ) values ( ?, ? )");
            statement.clearParameters();
            statement.setInt(1, k);
            statement.setString(2, sin);
            statement.executeUpdate();

            statement2 = connection.prepareStatement("select bval from blobtest where id =  ? ");
            statement2.clearParameters();
            statement2.setInt(1, k);
            rs = statement2.executeQuery();
            String sout = null;
            if (rs.next()) {
                sout = rs.getString(1);
            }

            // ensure no NPE, but maybe this is not ok because cout current value may be invalid
            if (sout != null) {
                cout = sout.toCharArray();
            }
            ByteStorageConversion.toByte(cout, 0, bout, 0, cout.length);

            if (sout != null) {
                Assert.assertEquals("Input and Output Lenghts are not the same ", sin.length(), sout.length());
            }

            for (int i = 0; i < bin.length; i++) {
                Assert.assertEquals(
                        "Database Byte conversion failed at " + bin[i] + "=>" + (int) cin[i] + "=>" + bout[i],
                        bin[i], bout[i]);
            }
        } finally {
            try {
                rs.close();
            } catch (Exception ex) {

            }
            try {
                statement2.close();
            } catch (Exception ex) {

            }
            try {
                statement.close();
            } catch (Exception ex) {

            }
            try {
                connection.close();
            } catch (Exception ex) {

            }
        }
    }
}

From source file:PerformanceEvaluation.java

public static byte[] generateValue(final Random r) {
    byte[] b = new byte[ROW_LENGTH];
    r.nextBytes(b);
    return b;/*from  w w  w.  j  a v  a 2  s  .c  om*/
}

From source file:org.anarres.lzo.LzopStreamTest.java

@Test
public void testRandom() throws Exception {
    Random r = new Random();
    for (int i = 0; i < 10; i++) {
        byte[] orig = new byte[256 * 1024];
        r.nextBytes(orig);
        try {// www  .ja  va2 s  . c om
            testAlgorithm(LzoAlgorithm.LZO1X, orig);
        } catch (UnsupportedOperationException e) {
            // LOG.info("Unsupported algorithm " + algorithm);
        }
    }
}

From source file:com.google.nigori.common.DSATest.java

@Test
public void signVerifies() throws NoSuchAlgorithmException {
    // Can have bugs which depend on particular bit values (such as sign bits) so iterate to reduce
    // probability of false positive
    for (int i = 0; i < 4; ++i) {
        Random random = new Random();
        byte[] privateKey = new byte[NigoriConstants.B_DSA];
        random.nextBytes(privateKey);
        DSASign signer = new DSASign(privateKey);
        DSASignature sig = signer.sign(MessageLibrary.toBytes("message"));
        DSAVerify verifier = new DSAVerify(signer.getPublicKey());
        assertTrue("Did not verify on iteration: " + i, verifier.verify(sig));
    }/*  www .j  a v  a 2s  .c  o  m*/
}