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:com.microsoft.azure.storage.queue.CloudQueueEncryptionTests.java

@Test
public void testQueueAddUpdateEncryptedBinaryMessage()
        throws StorageException, InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException {
    // Create the Key to be used for wrapping.
    SymmetricKey aesKey = TestHelper.getSymmetricKey();

    byte[] messageBytes = new byte[100];
    Random rand = new Random();
    rand.nextBytes(messageBytes);

    CloudQueueMessage message = new CloudQueueMessage(messageBytes);

    QueueRequestOptions options = new QueueRequestOptions();
    options.setEncryptionPolicy(new QueueEncryptionPolicy(aesKey, null));

    // add message
    this.queue.addMessage(message, 0, 0, options, null);

    // Retrieve message
    CloudQueueMessage retrMessage = this.queue.retrieveMessage(30, options, null);
    assertArrayEquals(messageBytes, retrMessage.getMessageContentAsByte());
}

From source file:org.coltram.nsd.bonjour.BonjourProcessor.java

public void exposeService(String serviceType, String friendlyName, String deviceType, JSONObject service,
        AtomConnection connection) throws JSONException {
    try {// www.  ja va  2 s.  c  o  m
        String type = serviceType.substring(9);
        final HashMap<String, String> values = new HashMap<String, String>();
        values.put("DName", friendlyName);
        String desc = service.toString();
        values.put("Desc", topManager.getHttpServer().addResource(UUID.randomUUID().toString() + ".json",
                desc.getBytes()));
        values.put("txtvers", "1");
        Random random = new Random();
        byte[] name = new byte[6];
        random.nextBytes(name);
        ServerSocket serverSocket = new ServerSocket(0);
        int bonjourServicePort = serverSocket.getLocalPort();
        ServiceInfo si = ServiceInfo.create(type, deviceType + "_" + toHex(name), bonjourServicePort, 0, 0,
                values);
        LocalExposedBonjourService exposedService = new LocalExposedBonjourService(topManager, serverSocket, si,
                si.getQualifiedName(), service);
        connection.add(exposedService);
        topManager.getConnectionManager().getJmdns().registerService(si);
        exposedService.start();
        connection.setExposedService(si.getQualifiedName());
        log.fine("register " + si.getQualifiedName());
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:com.microsoft.azure.storage.queue.CloudQueueEncryptionTests.java

@Test
public void testQueueAddUpdateEncryptedEncodedMessage()
        throws StorageException, InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException {
    // Create the Key to be used for wrapping.
    SymmetricKey aesKey = TestHelper.getSymmetricKey();

    byte[] messageBytes = new byte[100];
    Random rand = new Random();
    rand.nextBytes(messageBytes);

    String inputMessage = Base64.encode(messageBytes);
    CloudQueueMessage message = new CloudQueueMessage(inputMessage);
    this.queue.setShouldEncodeMessage(false);

    QueueRequestOptions options = new QueueRequestOptions();
    options.setEncryptionPolicy(new QueueEncryptionPolicy(aesKey, null));

    // add message
    this.queue.addMessage(message, 0, 0, options, null);

    // Retrieve message
    CloudQueueMessage retrMessage = this.queue.retrieveMessage(30, options, null);
    assertEquals(inputMessage, retrMessage.getMessageContentAsString());
}

From source file:accismus.benchmark.BenchTestIT.java

@Test
public void test1() throws Exception {

    LoaderExecutorProperties lep = new LoaderExecutorProperties(connectionProps);
    lep.setNumThreads(0).setQueueSize(0);
    LoaderExecutor lexecutor = new LoaderExecutor(lep);

    Map<ByteSequence, Document> expected = new HashMap<ByteSequence, Document>();

    Random rand = new Random();

    for (int i = 0; i < 10; i++) {
        Document doc = new Document(rand);
        expected.put(doc.getUrl(), doc);
        lexecutor.execute(new DocumentLoader(doc));
    }//  w  w  w. jav  a 2s.c  o m

    miniAccismus.waitForObservers();

    verify(expected);
    verifyMR();

    // update a document
    ByteSequence uri = expected.keySet().iterator().next();
    Random r = new Random();
    byte newContent[] = new byte[1004];
    r.nextBytes(newContent);
    Document newDoc = new Document(uri, new ArrayByteSequence(newContent));

    lexecutor.execute(new DocumentLoader(newDoc));

    expected.put(uri, newDoc);

    miniAccismus.waitForObservers();

    verify(expected);

    miniAccismus.waitForObservers();
}

From source file:org.apache.hadoop.hdfs.server.namenode.snapshot.TestINodeFileUnderConstructionWithSnapshot.java

private HdfsDataOutputStream appendFileWithoutClosing(Path file, int length) throws IOException {
    byte[] toAppend = new byte[length];
    Random random = new Random();
    random.nextBytes(toAppend);
    HdfsDataOutputStream out = (HdfsDataOutputStream) hdfs.append(file);
    out.write(toAppend);/*w w  w  . j  a  v  a 2s.c om*/
    return out;
}

From source file:org.opcfoundation.ua.examples.BigCertificateExample.java

@Override
public void onActivateSession(
        EndpointServiceRequest<ActivateSessionRequest, ActivateSessionResponse> msgExchange)
        throws ServiceFaultException {
    ActivateSessionResponse res = new ActivateSessionResponse();
    byte[] nonce = new byte[32];
    Random r = new Random();
    r.nextBytes(nonce);
    res.setServerNonce(nonce);//from   w w w  .  j ava  2s  . co  m
    res.setResults(new StatusCode[] { StatusCode.GOOD });
    msgExchange.sendResponse(res);
}

From source file:org.i3xx.step.uno.impl.service.DeployServiceImpl.java

private File getFile(File parent, String target) {

    while (target.contains("*")) {
        String tmp = target;//  w ww. j  a  v a  2 s .com
        while (tmp.contains("*")) {
            int p = tmp.lastIndexOf('*');

            byte[] bytes = new byte[4];

            Random r = new Random();
            r.nextBytes(bytes);
            String s = Base64.encodeBase64URLSafeString(bytes);

            tmp = tmp.substring(0, p) + s + tmp.substring(p + 1);
        } //while

        File f = new File(parent, tmp);
        if (!f.exists())
            return f; //exit
    } //while

    return new File(parent, target);
}

From source file:org.apache.activemq.usage.PeriodicDiskUsageLimitTest.java

protected void writeTestFile(int size) throws IOException {
    final byte[] data = new byte[size];
    final Random rng = new Random();
    rng.nextBytes(data);
    try (FileOutputStream stream = new FileOutputStream(testfile)) {
        IOUtils.write(data, stream);//  www . j av a  2  s.c o  m
    }
}

From source file:com.barchart.udt.TestSocketFile.java

/**
 * verify basic file send/receive//from w  w  w .j av a2 s .  co m
 */
@Test(timeout = 10 * 1000)
public void fileTransfer() throws Exception {

    final InetSocketAddress addr1 = localSocketAddress();
    final InetSocketAddress addr2 = localSocketAddress();

    final SocketUDT peer1 = new SocketUDT(TypeUDT.STREAM);
    final SocketUDT peer2 = new SocketUDT(TypeUDT.STREAM);

    peer1.setBlocking(false);
    peer2.setBlocking(false);

    peer1.setRendezvous(true);
    peer2.setRendezvous(true);

    peer1.bind(addr1);
    peer2.bind(addr2);

    socketAwait(peer1, StatusUDT.OPENED);
    socketAwait(peer2, StatusUDT.OPENED);

    peer1.connect(addr2);
    peer2.connect(addr1);

    socketAwait(peer1, StatusUDT.CONNECTED);
    socketAwait(peer2, StatusUDT.CONNECTED);

    log.info("state 0 - connected");
    log.info("peer1 : {}", peer1);
    log.info("peer2 : {}", peer2);

    final int size = 64 * 1024;

    final Random random = new Random(0);
    final byte[] array1 = new byte[size];
    final byte[] array2 = new byte[size];
    random.nextBytes(array1);
    random.nextBytes(array2);

    final File folder = new File("./target/file");
    folder.mkdirs();

    final File source = File.createTempFile("source", "data", folder);
    final File target = File.createTempFile("target", "data", folder);

    FileUtils.writeByteArrayToFile(source, array1);
    FileUtils.writeByteArrayToFile(target, array2);

    assertEquals(size, source.length());
    assertEquals(size, target.length());

    assertFalse("files are different", FileUtils.contentEquals(source, target));

    // sender
    final Runnable task1 = new Runnable() {
        @Override
        public void run() {
            try {
                log.info("init send");
                final long length = peer1.sendFile(source, 0, size);
                assertEquals(length, size);
            } catch (final Exception e) {
                log.error("", e);
            }
        }
    };

    // receiver
    final Runnable task2 = new Runnable() {
        @Override
        public void run() {
            try {
                log.info("init recv");
                final long length = peer2.receiveFile(target, 0, size);
                assertEquals(length, size);
            } catch (final Exception e) {
                log.error("", e);
            }
        }
    };

    final ExecutorService executor = Executors.newFixedThreadPool(2);

    executor.submit(task1);
    executor.submit(task2);

    Thread.sleep(5 * 1000);

    executor.shutdownNow();

    assertTrue("files are the same", FileUtils.contentEquals(source, target));

    peer1.close();
    peer2.close();

}

From source file:net.lizalab.util.RdRandRandomTest.java

/**
 * Verifies Generation of random bytes and their population
 * in the specified array./*from  ww w  .j a v  a 2 s. c  o m*/
 */
@Test
public final void testNextBytes() {
    // Prepare array to receive random bytes
    byte[] bytes = new byte[32];
    Random random = new RdRandRandom();
    random.nextBytes(bytes);
    byte[] emptyBytes = new byte[32];
    // Verify the library filled the provided array with random byte values.
    assertFalse(Arrays.equals(bytes, emptyBytes));
}