Example usage for io.netty.buffer ByteBuf nioBuffer

List of usage examples for io.netty.buffer ByteBuf nioBuffer

Introduction

In this page you can find the example usage for io.netty.buffer ByteBuf nioBuffer.

Prototype

public abstract ByteBuffer nioBuffer();

Source Link

Document

Exposes this buffer's readable bytes as an NIO ByteBuffer .

Usage

From source file:io.crate.blob.DigestBlob.java

License:Apache License

public void addToHead(BytesReference content) throws IOException {
    if (content == null) {
        return;// www.ja  v a2  s.c  om
    }

    int written = 0;
    ByteBuf byteBuf = Netty4Utils.toByteBuf(content);
    int readableBytes = byteBuf.readableBytes();
    assert readableBytes + headSize.get() <= headLength : "Got too many bytes in addToHead()";

    ByteBuffer byteBuffer = byteBuf.nioBuffer();
    while (written < readableBytes) {
        updateDigest(byteBuffer);
        written += headFileChannel.write(byteBuffer);
    }
    headSize.addAndGet(written);
    if (headSize.get() == headLength) {
        headCatchedUpLatch.countDown();
    }
}

From source file:io.hydramq.disk.DiskSegment.java

License:Open Source License

public void write(Message message, MessageIOListener messageIOListener) throws HydraRuntimeException {
    try {// w  ww.ja va2s.c o m
        ByteBuf buffer = allocator.directBuffer();
        buffer.writeInt(0);
        conversionContext.write(message, buffer);
        int messageSize = buffer.readableBytes() - 4;
        buffer.setInt(0, messageSize);
        boolean shouldFlush = flushStrategy.requiresFlush(buffer.readableBytes());
        indexWriteBuffer.clear();
        indexWriteBuffer.putInt((int) data.size());
        indexWriteBuffer.putLong(Clock.systemUTC().millis());
        indexWriteBuffer.flip();
        ByteBuffer nioBuffer = buffer.nioBuffer();
        while (nioBuffer.hasRemaining()) {
            data.write(nioBuffer);
        }
        while (indexWriteBuffer.hasRemaining()) {
            index.write(indexWriteBuffer);
        }
        buffer.release();
        if (shouldFlush) {
            data.force(true);
            index.force(true);
        }
        size += 1;
        if (messageIOListener != null) {
            messageIOListener.onMessage(1, messageSize);
        }
    } catch (IOException ex) {
        throw new HydraRuntimeException("Error writing message to segment " + segmentDirectory.toString());
    }
}

From source file:io.jsync.file.impl.DefaultAsyncFile.java

License:Open Source License

@Override
public AsyncFile write(Buffer buffer, long position, final Handler<AsyncResult<Void>> handler) {
    check();//from ww w.  j  a v a2 s  .c om
    final ByteBuf buf = buffer.getByteBuf();
    if (buf.nioBufferCount() > 1) {
        final Iterator<ByteBuffer> buffers = Arrays.asList(buf.nioBuffers()).iterator();
        doWrite(buffers, position, handler);
    } else {
        ByteBuffer bb = buf.nioBuffer();
        doWrite(bb, position, bb.limit(), handler);
    }
    return this;
}

From source file:io.jsync.file.impl.DefaultAsyncFile.java

License:Open Source License

@Override
public AsyncFile write(Buffer buffer) {
    check();// w  w w  .j  a v  a2  s.  c o m
    final int length = buffer.length();
    Handler<AsyncResult<Void>> handler = new Handler<AsyncResult<Void>>() {

        public void handle(AsyncResult<Void> deferred) {
            if (deferred.succeeded()) {
                checkContext();
                checkDrained();
                if (writesOutstanding == 0 && closedDeferred != null) {
                    closedDeferred.run();
                }
            } else {
                handleException(deferred.cause());
            }
        }
    };

    ByteBuf buf = buffer.getByteBuf();
    if (buf.nioBufferCount() > 1) {
        final Iterator<ByteBuffer> buffers = Arrays.asList(buf.nioBuffers()).iterator();
        doWrite(buffers, writePos, handler);
    } else {
        ByteBuffer bb = buf.nioBuffer();
        doWrite(bb, writePos, bb.limit(), handler);
    }
    writePos += length;
    return this;
}

From source file:io.moquette.parser.netty.TestUtils.java

License:Open Source License

static void verifyBuff(int numBytes, ByteBuffer bytes, ByteBuf buff) {
    assertTrue(numBytes <= buff.readableBytes());
    assertEquals(bytes, buff.nioBuffer());
}

From source file:io.vertx.core.file.impl.AsyncFileImpl.java

License:Open Source License

private synchronized AsyncFile doWrite(Buffer buffer, long position, Handler<AsyncResult<Void>> handler) {
    Objects.requireNonNull(buffer, "buffer");
    Arguments.require(position >= 0, "position must be >= 0");
    check();//from   www . j  a v a  2  s .c  om
    Handler<AsyncResult<Void>> wrapped = ar -> {
        if (ar.succeeded()) {
            checkContext();
            if (writesOutstanding == 0 && closedDeferred != null) {
                closedDeferred.run();
            } else {
                checkDrained();
            }
            if (handler != null) {
                handler.handle(ar);
            }
        } else {
            if (handler != null) {
                handler.handle(ar);
            } else {
                handleException(ar.cause());
            }
        }
    };
    ByteBuf buf = buffer.getByteBuf();
    if (buf.nioBufferCount() > 1) {
        doWrite(buf.nioBuffers(), position, wrapped);
    } else {
        ByteBuffer bb = buf.nioBuffer();
        doWrite(bb, position, bb.limit(), wrapped);
    }
    return this;
}

From source file:nearenough.examples.NioClient.java

License:Open Source License

@SuppressWarnings("Duplicates")
public static void main(String[] args) throws IOException, InterruptedException {
    InetSocketAddress addr = new InetSocketAddress(INT08H_SERVER_HOST, INT08H_SERVER_PORT);
    System.out.printf("Sending request to %s\n", addr);

    // Nonblocking NIO UDP channel for the remote Roughtime server
    DatagramChannel channel = DatagramChannel.open(StandardProtocolFamily.INET);
    channel.configureBlocking(false);/* w  w  w.ja  va2  s .  c om*/

    // Create a new RoughtimeClient instance
    RoughtimeClient client = new RoughtimeClient(INT08H_SERVER_PUBKEY);

    // Create a request message
    RtMessage request = client.createRequest();

    // Encode for transmission
    ByteBuf encodedRequest = RtWire.toWire(request);

    // Send the message
    channel.send(encodedRequest.nioBuffer(), addr);
    int bytesWritten = channel.send(encodedRequest.nioBuffer(), addr);

    // Ensure the message was sent
    if (bytesWritten != encodedRequest.readableBytes()) {
        throw new RuntimeException("failed to fully write request");
    }

    // Space for receiving the reply
    ByteBuffer recvBuf = ByteBuffer.allocate(4096);
    int attempts = 50;

    // Simple loop to look for the first response. Wait for max 5 seconds.
    while (--attempts > 0) {
        recvBuf.clear();
        channel.receive(recvBuf);
        recvBuf.flip();
        if (recvBuf.hasRemaining()) {
            break;
        }
        Thread.sleep(100L);
    }

    if (recvBuf.hasRemaining()) {
        // A reply from the server has been received
        System.out.printf("Read message of %d bytes from %s:\n", recvBuf.remaining(), addr);

        // Parse the response
        RtMessage response = RtMessage.fromByteBuffer(recvBuf);
        System.out.println(response);

        // Validate the response. Checks that the message is well-formed, all signatures are valid,
        // and our nonce is present in the response.
        client.processResponse(response);

        if (client.isResponseValid()) {
            // Validation passed, the response is good

            // The "midpoint" is the Roughtime server's reported timestamp (in microseconds). And the
            // "radius" is a span of uncertainty around that midpoint. A Roughtime server asserts that
            // its "true time" lies within the span.
            Instant midpoint = Instant.ofEpochMilli(client.midpoint() / 1_000L);
            int radiusSec = client.radius() / 1_000_000;
            System.out.println("midpoint    : " + midpoint + " (radius " + radiusSec + " sec)");

            // For comparison, also print the local clock. If the midpoint and your local time
            // are widely different, check your local machine's time sync!
            Instant local = Instant.now();
            System.out.println("local clock : " + local);

        } else {
            // Validation failed. Print out the reason why.
            System.out.println("Response INVALID: " + client.invalidResponseCause().getMessage());
        }

    } else {
        // No reply within five seconds
        System.out.println("No response from " + addr);
    }

    System.exit(0);
}

From source file:net.hasor.rsf.protocol.hprose.HproseUtils.java

License:Apache License

/***/
public static RequestInfo[] doCall(RsfContext rsfContext, ByteBuf content, String requestURI, String origin)
        throws RsfException {
    ////w w w  . j  av  a 2 s. c  o  m
    HproseReader reader = new HproseReader(content.nioBuffer());
    List<RequestInfo> infoArrays = new ArrayList<RequestInfo>();
    //
    parseRequest(rsfContext, reader, infoArrays);
    content.skipBytes(content.readableBytes());
    //
    for (RequestInfo info : infoArrays) {
        info.addOption(LOCATION, requestURI);
        info.addOption(ORIGIN, origin);
    }
    //
    return infoArrays.toArray(new RequestInfo[infoArrays.size()]);
}

From source file:Netty4.MQSource.NettyTest.NettyTest.NettyDecoder.java

License:Apache License

@Override
public Object decode(ChannelHandlerContext ctx, ByteBuf in) throws Exception {
    ByteBuf frame = null;
    try {/*ww w.  ja  v  a  2  s. c o m*/
        frame = (ByteBuf) super.decode(ctx, in);
        if (null == frame) {
            return null;
        }

        ByteBuffer byteBuffer = frame.nioBuffer();
        int len = byteBuffer.capacity();
        byte[] bodyData = new byte[len];
        byteBuffer.get(bodyData);
        RemotingCommand cmd = RemotingCommand.createRequestCommand();
        cmd.setBody(bodyData);
        return cmd;
    } catch (Exception e) {
        log.error("decode exception, " + RemotingUtil.parseChannelRemoteAddr(ctx.channel()), e);
        RemotingUtil.closeChannel(ctx.channel());
    } finally {
        if (null != frame) {
            frame.release();
        }
    }

    return null;
}

From source file:no.nb.nna.broprox.harvester.proxy.ContentCollector.java

License:Apache License

public void addPayload(ByteBuf payload) {
    if (headersSent) {
        digest.update(CRLF);//w w  w  . j  a  va2 s . c o  m
        size += 2;
    }
    ByteString data = ByteString.copyFrom(payload.nioBuffer());
    digest.update(data.asReadOnlyByteBuffer());
    contentWriterClient.sendPayload(data);
    size += data.size();

    if (shouldCache) {
        if (headersSent) {
            cacheValue = cacheValue.concat(ByteString.copyFrom(CRLF)).concat(data);
        } else {
            cacheValue = data;
        }
    }
}