Example usage for java.nio ByteBuffer flip

List of usage examples for java.nio ByteBuffer flip

Introduction

In this page you can find the example usage for java.nio ByteBuffer flip.

Prototype

public final Buffer flip() 

Source Link

Document

Flips this buffer.

Usage

From source file:com.github.neoio.net.message.staging.file.TestFileMessageStaging.java

@Test
public void test() throws Exception {
    ByteBuffer buffer = ByteBuffer.allocate(1024);

    buffer.put("Hello World".getBytes("US-ASCII"));
    buffer.flip();
    Assert.assertEquals(11, staging.writeTempReadBytes(buffer));
    Assert.assertTrue(staging.hasTempReadBytes());
    buffer.clear();/*from w  w w .  jav a 2s  .  com*/
    Assert.assertEquals(11, staging.readTempReadBytes(buffer));
    buffer.put("Hello World".getBytes("US-ASCII"));
    buffer.flip();
    staging.writePrimaryStaging(buffer, 22);
    buffer.clear();
    staging.getPrimaryStage().read(buffer);
    Assert.assertEquals("Hello WorldHello World", new String(buffer.array(), 0, 22));
}

From source file:io.druid.segment.writeout.WriteOutBytesTest.java

@Test
public void testCrossBufferRandomAccess() throws IOException {
    WriteOutBytes writeOutBytes = segmentWriteOutMedium.makeWriteOutBytes();
    for (int i = 0; i < ByteBufferWriteOutBytes.BUFFER_SIZE; i++) {
        writeOutBytes.write('0');
    }/* w  w w.  j  a  v a 2 s  .co m*/
    writeOutBytes.write('1');
    writeOutBytes.write('2');
    writeOutBytes.write('3');
    ByteBuffer bb = ByteBuffer.allocate(4);
    writeOutBytes.readFully(ByteBufferWriteOutBytes.BUFFER_SIZE - 1, bb);
    bb.flip();
    Assert.assertEquals("0123", StringUtils.fromUtf8(bb));
}

From source file:edu.csun.ecs.cs.multitouchj.ui.control.Canvas.java

protected ByteBuffer prepareImage(Image image) {
    ByteBuffer imageData = ByteBuffer.allocateDirect(image.getData().length).order(ByteOrder.nativeOrder());
    imageData.put(image.getData());/*from www.  ja va  2 s .  c o m*/
    imageData.flip();

    return imageData;
}

From source file:com.olacabs.fabric.compute.sources.kafka.impl.TransactionManager.java

private long readLastTransactionId() throws Exception {
    byte[] data = curator.getData().forPath(txnIdPath());
    ByteBuffer read = ByteBuffer.allocate(Long.BYTES).put(data, 0, data.length);
    read.flip();
    return read.getLong();
}

From source file:com.offbynull.portmapper.pcp.PcpDiscovery.java

private static Set<InetAddress> discoverGateways() throws InterruptedException, IOException {
    final Set<InetAddress> foundGateways = Collections.synchronizedSet(new HashSet<InetAddress>());
    Set<InetAddress> potentialGateways = NetworkUtils.getPotentialGatewayAddresses(); // port 5351

    DatagramChannel unicastChannel = null;
    try {// www.j ava 2  s. c  om
        unicastChannel = DatagramChannel.open();
        unicastChannel.configureBlocking(false);
        unicastChannel.socket().bind(new InetSocketAddress(0));
    } catch (IOException ioe) {
        IOUtils.closeQuietly(unicastChannel);
        throw ioe;
    }

    UdpCommunicator communicator = null;
    try {
        communicator = new UdpCommunicator(Collections.singletonList(unicastChannel));
        communicator.startAsync().awaitRunning();
        communicator.addListener(new UdpCommunicatorListener() {

            @Override
            public void incomingPacket(InetSocketAddress sourceAddress, DatagramChannel channel,
                    ByteBuffer packet) {
                foundGateways.add(sourceAddress.getAddress());
            }
        });

        ByteBuffer outBuf = ByteBuffer.allocate(1100);
        MapPcpRequest mpr = new MapPcpRequest(ByteBuffer.allocate(12), 0, 0, 0, InetAddress.getByName("::"),
                0L);
        mpr.dump(outBuf, InetAddress.getByAddress(new byte[4])); // should get back an error for this, but this
                                                                 // should be fine because all we're looking for is a response, not
                                                                 // nessecarily a correct response -- self address being sent is
                                                                 // 0.0.0.0 (IPV4)
                                                                 //
                                                                 // also, we need to pass in MAP because Apple's garbage routers
                                                                 // give back NATPMP responses when you pass in ANNOUNCE

        outBuf.flip();

        for (InetAddress potentialGateway : potentialGateways) {
            communicator.send(unicastChannel, new InetSocketAddress(potentialGateway, 5351),
                    outBuf.asReadOnlyBuffer());
        }

        Thread.sleep(5000L);
    } finally {
        if (communicator != null) {
            communicator.stopAsync().awaitTerminated();
        }
    }

    foundGateways.retainAll(potentialGateways); // just incase we get back some unsolicited responses
    return new HashSet<>(foundGateways);
}

From source file:com.torchmind.authenticator.AbstractTokenGenerator.java

/**
 * Generates a code based on a secret key and challenge.
 *
 * @param secretKey a secret key./*from w w  w . j  av  a  2  s  . c o m*/
 * @param challenge a challenge.
 * @return a code.
 */
@NonNull
protected String generateCode(@NonNull SecretKey secretKey, @NonNull byte[] challenge) {
    try {
        Mac mac = Mac.getInstance("Hmac" + this.algorithm.name());
        mac.init(secretKey);

        byte[] hash = mac.doFinal(challenge);
        int offset = hash[hash.length - 1] & 0x0F;

        ByteBuffer buffer = ByteBuffer.allocate(4).put(hash, offset, 4);
        buffer.flip();

        return String.format("%0" + this.digits + "d", (buffer.getInt() & 0x7FFFFFFF) % this.digitModulo);
    } catch (NoSuchAlgorithmException ex) {
        throw new UnsupportedOperationException(
                "The specified algorithm is not supported by this Java VM implementation: " + ex.getMessage(),
                ex);
    } catch (InvalidKeyException ex) {
        throw new IllegalArgumentException("Invalid shared secret: " + ex.getMessage(), ex);
    }
}

From source file:org.italiangrid.storm.webdav.fs.attrs.DefaultExtendedFileAttributesHelper.java

protected String getAttributeValue(UserDefinedFileAttributeView view, String attributeName) throws IOException {

    if (view.list().contains(attributeName)) {
        ByteBuffer buffer = ByteBuffer.allocateDirect(view.size(attributeName));
        view.read(attributeName, buffer);
        buffer.flip();
        return StandardCharsets.UTF_8.decode(buffer).toString();
    } else {// w  w  w.j a va  2 s . c  om
        return "";
    }
}

From source file:com.mapr.storm.test.TailSpoutTest.java

private byte[] payload(String msg) {
    byte[] content = msg.getBytes(Charsets.UTF_8);
    ByteBuffer buf = ByteBuffer.allocate(4 + content.length);
    buf.putInt(content.length);//from w  w w  . j ava2 s.  c o  m
    buf.put(content);
    buf.flip();
    return buf.array();
}

From source file:net.socket.nio.TimeClientHandle.java

private void doWrite(SocketChannel sc) throws IOException {
    byte[] req = "QUERY TIME ORDER".getBytes();
    ByteBuffer writeBuffer = ByteBuffer.allocate(req.length);
    writeBuffer.put(req);/* w w w .j  av  a  2  s . co m*/
    writeBuffer.flip();
    sc.write(writeBuffer);
    sc.write(writeBuffer);
    if (!writeBuffer.hasRemaining()) {
        System.out.println("Send order 2 server succeed.");
    }
}

From source file:gridool.communication.transport.nio.GridNioServer.java

private static void handleRead(final SocketChannel channel, final SelectionKey key,
        final ByteBuffer sharedReadBuf, final GridTransportListener notifier, final ExecutorService exec) {
    sharedReadBuf.clear();//from   w  w  w .  j  a  v  a  2  s .co  m
    final SocketAddress remoteAddr = channel.socket().getRemoteSocketAddress();
    final int bytesRead;
    try {
        bytesRead = channel.read(sharedReadBuf);
    } catch (IOException e) {
        LOG.warn("Failed to read data from client: " + remoteAddr, e);
        NIOUtils.close(key);
        return;
    }
    if (LOG.isDebugEnabled()) {
        LOG.debug("Read " + bytesRead + " bytes from a client socket: " + remoteAddr);
    }
    if (bytesRead == -1) {
        if (LOG.isTraceEnabled()) {
            LOG.trace("Remote client closed connection: " + remoteAddr);
        }
        NIOUtils.close(key);
        return;
    } else if (bytesRead == 0) {
        return;
    }

    final GridMessageBuffer msgBuf = (GridMessageBuffer) key.attachment();
    sharedReadBuf.flip();
    while (sharedReadBuf.remaining() > 0) {
        msgBuf.read(sharedReadBuf);
        if (msgBuf.isFilled()) {
            exec.execute(new Runnable() {
                public void run() {
                    final GridCommunicationMessage msg = msgBuf.toMessage();
                    msgBuf.reset();
                    if (LOG.isInfoEnabled()) {
                        LOG.info("Recieved a GridCommunicationMessage [" + msg.getMessageId() + "]");
                    }
                    notifier.notifyListener(msg);
                }
            });
            break;
        }
    }
}