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.hadoop.hdfs.server.datanode.TestBlockFileChannelCache.java

@Test
public void testMultiThread() throws Exception {
    Path fileName = new Path("/user/facebook/file2");
    int numBlocks = 8;
    //DFSTestUtil.createFile(dfs, fileName, 
    //    numBlocks * DEFAULT_BLOCK_SIZE, (short)1, 1);
    byte[] buffer = new byte[(int) (numBlocks * DEFAULT_BLOCK_SIZE)];
    Random random = new Random();
    random.nextBytes(buffer);
    createFile(fileName, buffer);/*  w  w w.  j a v a2  s  .c o m*/

    DataNode datanode = cluster.getDataNodes().get(0);

    assertEquals(0, datanode.fileHandlerCache.size());
    int numThreads = 20;
    ExecutorService executor = Executors.newFixedThreadPool(numThreads);
    List<Future<Boolean>> futures = new ArrayList<Future<Boolean>>();
    for (int i = 0; i < numThreads; i++) {
        futures.add(executor.submit(new ReadWorker(fileName, dfs, buffer)));
    }

    for (int i = 0; i < numThreads; i++) {
        assertTrue(futures.get(i).get());
    }
    assertEquals(2, datanode.fileHandlerCache.size());
    LOG.info("testMultiThread finished.");
}

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

/**
 * Tests receiving an empty byte array.//from   ww w  .jav  a2s. c o m
 * 
 * @throws HttpException
 * @throws IOException
 */
public void testWithRequestAcceptHeaderWillReturnRequestedContentType() throws HttpException, IOException {
    HttpClient client = new HttpClient();

    PutMethod putMethod = new PutMethod(getBaseURI() + "/providers/standard/inputstream");
    byte[] barr = new byte[100000];
    Random r = new Random();
    r.nextBytes(barr);
    putMethod.setRequestEntity(new InputStreamRequestEntity(new ByteArrayInputStream(barr), "any/type"));
    try {
        client.executeMethod(putMethod);
        assertEquals(204, putMethod.getStatusCode());
    } finally {
        putMethod.releaseConnection();
    }

    GetMethod getMethod = new GetMethod(getBaseURI() + "/providers/standard/inputstream");
    getMethod.addRequestHeader("Accept", "mytype/subtype");
    try {
        client.executeMethod(getMethod);
        assertEquals(200, getMethod.getStatusCode());
        InputStream is = getMethod.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("mytype/subtype", getMethod.getResponseHeader("Content-Type").getValue());
        Header contentLengthHeader = getMethod.getResponseHeader("Content-Length");
        assertNull(contentLengthHeader == null ? "null" : contentLengthHeader.getValue(), contentLengthHeader);
    } finally {
        getMethod.releaseConnection();
    }
}

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

/**
 * Tests putting and then getting a byte array.
 * /*from  w ww  . ja  v a 2  s. co m*/
 * @throws HttpException
 * @throws IOException
 */
public void testPutInputStream() throws HttpException, IOException {
    HttpClient client = new HttpClient();

    PutMethod putMethod = new PutMethod(getBaseURI() + "/providers/standard/inputstream");
    byte[] barr = new byte[100000];
    Random r = new Random();
    r.nextBytes(barr);
    putMethod.setRequestEntity(new InputStreamRequestEntity(new ByteArrayInputStream(barr), "bytes/array"));
    try {
        client.executeMethod(putMethod);
        assertEquals(204, putMethod.getStatusCode());
    } finally {
        putMethod.releaseConnection();
    }

    GetMethod getMethod = new GetMethod(getBaseURI() + "/providers/standard/inputstream");
    try {
        client.executeMethod(getMethod);
        assertEquals(200, getMethod.getStatusCode());
        InputStream is = getMethod.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]);
        }

        String contentType = (getMethod.getResponseHeader("Content-Type") == null) ? null
                : getMethod.getResponseHeader("Content-Type").getValue();
        assertNotNull(contentType, contentType);
        Header contentLengthHeader = getMethod.getResponseHeader("Content-Length");
        assertNull(contentLengthHeader == null ? "null" : contentLengthHeader.getValue(), contentLengthHeader);
    } finally {
        getMethod.releaseConnection();
    }
}

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

/**
 * Tests posting to a DataSource subclass. This should result in a 415
 * error.//from   www.ja  va2 s .  c  o  m
 * 
 * @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();
    }
}

From source file:org.opennms.test.FileAnticipator.java

/**
 * <p>generateRandomHexString</p>
 *
 * @param length a int./*w w w .  j av  a2 s  . c  o m*/
 * @return a {@link java.lang.String} object.
 */
protected static String generateRandomHexString(int length) {
    if (length < 0) {
        throw new IllegalArgumentException("length argument is " + length + " and cannot be below zero");
    }

    Random random = new Random();
    /*
    SecureRandom sometimes gets tied up in knots in testing (the test process goes off into lala land and never returns from .nextBytes)
    Slow debugging (with pauses) seems to work most of the time, but manual Thread.sleeps doesn't
    Using Random instead of SecureRandom (which should be fine in this context) works much better.  Go figure
            
    SecureRandom random = null;
    try {
    random = SecureRandom.getInstance("SHA1PRNG");
    } catch (NoSuchAlgorithmException e) {
    fail("Could not initialize SecureRandom: " + e);
    }*/

    byte[] bytes = new byte[length];
    random.nextBytes(bytes);

    StringBuffer sb = new StringBuffer();
    for (byte b : bytes) {
        sb.append(String.format("%02x", b));
    }
    return sb.toString();
}

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

@Test
public void testDownload2() throws Exception {
    Random random = new Random();
    random.nextBytes(data0);
    random.nextBytes(data1);/*from   w  ww .j av  a 2s  .  c o  m*/

    chunkId0 = Hex.encodeHexString(DigestUtils.sha1(data0));
    chunkId1 = Hex.encodeHexString(DigestUtils.sha1(data1));

    MessageDigest messageDigest = DigestUtils.getSha1Digest();
    messageDigest.update(data0);
    messageDigest.update(data1);

    id = Hex.encodeHexString(messageDigest.digest());

    ByteArrayOutputStream baos = new ByteArrayOutputStream();

    client.setRegistryURI(getURI()).downloadFile(id, baos);

    Assert.assertArrayEquals(data0, Arrays.copyOf(baos.toByteArray(), DEFAULT_PIECE_SIZE));
    Assert.assertArrayEquals(data1,
            Arrays.copyOfRange(baos.toByteArray(), DEFAULT_PIECE_SIZE, DEFAULT_PIECE_SIZE + 128));
}

From source file:net.alegen.datpass.library.crypto.CryptoManager.java

public EncryptionOutput encrypt(String plaintext, String password) {
    try {/*from  w  w  w. j a  v a 2  s .c  o m*/
        // set up the encryption key
        Random r = new Random(System.currentTimeMillis());
        byte[] salt = new byte[50];
        r.nextBytes(salt);
        SecretKey key = this.derivateKey(KeyDerivationFunctions.PBKDF2_HMAC_SHA1, password, salt,
                AES_KEY_LENGTH, DEFAULT_ITERATIONS);
        salt = Base64.encodeBase64(salt);
        key = new SecretKeySpec(key.getEncoded(), "AES");

        // encrypt plain text with AES using generated key         
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        cipher.init(Cipher.ENCRYPT_MODE, key);
        AlgorithmParameters params = cipher.getParameters();
        byte[] iv = Base64.encodeBase64(params.getParameterSpec(IvParameterSpec.class).getIV());
        byte[] ciphertext = Base64.encodeBase64(cipher.doFinal(plaintext.getBytes("UTF-8")));

        // package output and return
        return new EncryptionOutput(new String(ciphertext, "UTF-8"), new String(salt, "UTF-8"),
                new String(iv, "UTF-8"));
    } catch (NoSuchAlgorithmException | NoSuchPaddingException | InvalidKeyException | IllegalBlockSizeException
            | BadPaddingException | UnsupportedEncodingException | InvalidParameterSpecException e) {
        log.error("An error occured while encrypting the message.");
        return null;
    }
}

From source file:org.apache.hadoop.hdfs.TestRaidDfs.java

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);//from  ww w .ja v a2s.c o m
        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();
}

From source file:org.commonjava.util.partyline.JoinableFileTest.java

private void assertReadOfExistingFileOfSize(String s) throws IOException, InterruptedException {
    File f = temp.newFile("read-target.txt");
    int sz = (int) FileSize.valueOf("11mb").getSize();
    byte[] src = new byte[sz];

    Random rand = new Random();
    rand.nextBytes(src);

    try (OutputStream out = new FileOutputStream(f)) {
        IOUtils.write(src, out);//from w w w  .  j a v a 2  s  . c o m
    }

    final JoinableFile jf = new JoinableFile(f, newLockOwner(f.getAbsolutePath(), read), false);

    try (InputStream stream = jf.joinStream()) {
        byte[] result = IOUtils.toByteArray(stream);
        assertThat(result, equalTo(src));
    }
}

From source file:de.codesourcery.hex2raw.IntelHexTest.java

public void testRoundtrips() throws IOException {

    final Random rnd = new Random();

    for (int i = 0; i < 100; i++) {
        final int len = 1024 + rnd.nextInt(2048);
        final byte[] data = new byte[len];
        rnd.nextBytes(data);
        assertRoundTripWorks(data);/*w w w. j  av a2 s . c om*/
    }
}