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:de.unipassau.isl.evs.ssh.master.network.UDPDiscoveryServer.java

License:Open Source License

/**
 * Send a response with the ConnectInformation of this Master to the requesting Client.
 *
 * @param request the request sent from a {@link Client}
 *//*  www  . ja v  a  2 s .  c  o  m*/
private void sendDiscoveryResponse(DatagramPacket request) {
    final ByteBuf buffer = channel.channel().alloc().heapBuffer();

    // gather information
    final byte[] header = DISCOVERY_PAYLOAD_RESPONSE.getBytes();
    final String addressString = request.recipient().getAddress().getHostAddress();
    final byte[] address = addressString.getBytes();
    final InetSocketAddress serverAddress = requireComponent(Server.KEY).getAddress();
    if (serverAddress == null) {
        Log.w(TAG, "Could not respond to UDP discovery request as Server is not started yet");
        return;
    }
    final int port = serverAddress.getPort();
    Log.i(TAG, "sendDiscoveryResponse with connection data " + addressString + ":" + port + " to "
            + request.sender());

    // write it to the buffer
    buffer.writeInt(header.length);
    buffer.writeBytes(header);
    buffer.writeInt(address.length);
    buffer.writeBytes(address);
    buffer.writeInt(port);

    // and sign the data
    try {
        Signature signature = Signature.getInstance("ECDSA");
        signature.initSign(requireComponent(KeyStoreController.KEY).getOwnPrivateKey());
        signature.update(buffer.nioBuffer());
        final byte[] sign = signature.sign();
        buffer.writeInt(sign.length);
        buffer.writeBytes(sign);
    } catch (GeneralSecurityException e) {
        Log.w(TAG, "Could not send UDP discovery response", e);
    }

    final DatagramPacket response = new DatagramPacket(buffer, request.sender());
    channel.channel().writeAndFlush(response);
}

From source file:divconq.http.multipart.AbstractDiskHttpData.java

License:Apache License

@Override
public void setContent(ByteBuf buffer) throws IOException {
    if (buffer == null) {
        throw new NullPointerException("buffer");
    }//  w  w w  .  j  a  v a2 s.co m
    try {
        size = buffer.readableBytes();
        checkSize(size);
        if (definedSize > 0 && definedSize < size) {
            throw new IOException("Out of size: " + size + " > " + definedSize);
        }
        if (file == null) {
            file = tempFile();
        }
        if (buffer.readableBytes() == 0) {
            // empty file
            if (!file.createNewFile()) {
                throw new IOException("file exists already: " + file);
            }
            return;
        }
        FileOutputStream outputStream = new FileOutputStream(file);
        FileChannel localfileChannel = outputStream.getChannel();
        ByteBuffer byteBuffer = buffer.nioBuffer();
        int written = 0;
        while (written < size) {
            written += localfileChannel.write(byteBuffer);
        }
        buffer.readerIndex(buffer.readerIndex() + written);
        localfileChannel.force(false);
        localfileChannel.close();
        outputStream.close();
        setCompleted();
    } finally {
        // Release the buffer as it was retained before and we not need a reference to it at all
        // See https://github.com/netty/netty/issues/1516
        buffer.release();
    }
}

From source file:divconq.http.multipart.AbstractDiskHttpData.java

License:Apache License

@Override
public void addContent(ByteBuf buffer, boolean last) throws IOException {
    if (buffer != null) {
        try {/*  w w  w  .  java2 s.com*/
            int localsize = buffer.readableBytes();
            checkSize(size + localsize);
            if (definedSize > 0 && definedSize < size + localsize) {
                throw new IOException("Out of size: " + (size + localsize) + " > " + definedSize);
            }
            ByteBuffer byteBuffer = buffer.nioBufferCount() == 1 ? buffer.nioBuffer()
                    : buffer.copy().nioBuffer();
            int written = 0;
            if (file == null) {
                file = tempFile();
            }
            if (fileChannel == null) {
                FileOutputStream outputStream = new FileOutputStream(file);
                fileChannel = outputStream.getChannel();
            }
            while (written < localsize) {
                written += fileChannel.write(byteBuffer);
            }
            size += localsize;
            buffer.readerIndex(buffer.readerIndex() + written);
        } finally {
            // Release the buffer as it was retained before and we not need a reference to it at all
            // See https://github.com/netty/netty/issues/1516
            buffer.release();
        }
    }
    if (last) {
        if (file == null) {
            file = tempFile();
        }
        if (fileChannel == null) {
            FileOutputStream outputStream = new FileOutputStream(file);
            fileChannel = outputStream.getChannel();
        }
        fileChannel.force(false);
        fileChannel.close();
        fileChannel = null;
        setCompleted();
    } else {
        if (buffer == null) {
            throw new NullPointerException("buffer");
        }
    }
}

From source file:divconq.net.ssl.SslHandler.java

License:Apache License

private SSLEngineResult wrap(SSLEngine engine, ByteBuf in, ByteBuf out) throws SSLException {
    ByteBuffer in0 = in.nioBuffer();
    if (!in0.isDirect()) {
        ByteBuffer newIn0 = ByteBuffer.allocateDirect(in0.remaining());
        newIn0.put(in0).flip();//from   www .j av a2 s. c  om
        in0 = newIn0;
    }

    for (;;) {
        ByteBuffer out0 = out.nioBuffer(out.writerIndex(), out.writableBytes());
        SSLEngineResult result = engine.wrap(in0, out0);
        in.skipBytes(result.bytesConsumed());
        out.writerIndex(out.writerIndex() + result.bytesProduced());

        switch (result.getStatus()) {
        case BUFFER_OVERFLOW:
            out.ensureWritable(maxPacketBufferSize);
            break;
        default:
            return result;
        }
    }
}

From source file:divconq.net.ssl.SslHandler.java

License:Apache License

private void unwrap(ChannelHandlerContext ctx, ByteBuffer packet, int initialOutAppBufCapacity)
        throws SSLException {

    // If SSLEngine expects a heap buffer for unwrapping, do the conversion.
    final ByteBuffer oldPacket;
    final ByteBuf newPacket;
    final int oldPos = packet.position();
    if (wantsInboundHeapBuffer && packet.isDirect()) {
        newPacket = ctx.alloc().heapBuffer(packet.limit() - oldPos);
        newPacket.writeBytes(packet);//from  w  w  w .  j av a 2s.  co m
        oldPacket = packet;
        packet = newPacket.nioBuffer();
    } else {
        oldPacket = null;
        newPacket = null;
    }

    boolean wrapLater = false;
    ByteBuf decodeOut = allocate(ctx, initialOutAppBufCapacity);
    try {
        for (;;) {
            final SSLEngineResult result = unwrap(engine, packet, decodeOut);
            final Status status = result.getStatus();
            final HandshakeStatus handshakeStatus = result.getHandshakeStatus();
            final int produced = result.bytesProduced();
            final int consumed = result.bytesConsumed();

            if (status == Status.CLOSED) {
                // notify about the CLOSED state of the SSLEngine. See #137
                sslCloseFuture.trySuccess(ctx.channel());
                break;
            }

            switch (handshakeStatus) {
            case NEED_UNWRAP:
                break;
            case NEED_WRAP:
                wrapNonAppData(ctx, true);
                break;
            case NEED_TASK:
                runDelegatedTasks();
                break;
            case FINISHED:
                setHandshakeSuccess();
                wrapLater = true;
                continue;
            case NOT_HANDSHAKING:
                if (setHandshakeSuccessIfStillHandshaking()) {
                    wrapLater = true;
                    continue;
                }
                if (flushedBeforeHandshakeDone) {
                    // We need to call wrap(...) in case there was a flush done before the handshake completed.
                    //
                    // See https://github.com/netty/netty/pull/2437
                    flushedBeforeHandshakeDone = false;
                    wrapLater = true;
                }

                break;
            default:
                throw new IllegalStateException("Unknown handshake status: " + handshakeStatus);
            }

            if (status == Status.BUFFER_UNDERFLOW || consumed == 0 && produced == 0) {
                break;
            }
        }

        if (wrapLater) {
            wrap(ctx, true);
        }
    } catch (SSLException e) {
        setHandshakeFailure(e);
        throw e;
    } finally {
        // If we converted packet into a heap buffer at the beginning of this method,
        // we should synchronize the position of the original buffer.
        if (newPacket != null) {
            oldPacket.position(oldPos + packet.position());
            newPacket.release();
        }

        if (decodeOut.isReadable()) {
            ctx.fireChannelRead(decodeOut);
        } else {
            decodeOut.release();
        }
    }
}

From source file:faststore.net.netty.common.faststoreprotocol.netty.FastStoreNettyDecoder.java

License:Apache License

@Override
public Object decode(ChannelHandlerContext ctx, ByteBuf in) throws Exception {
    ByteBuf frame = null;
    try {/*from w ww  .j  av a2 s.  c o m*/
        frame = (ByteBuf) super.decode(ctx, in);
        if (null == frame) {
            return null;
        }
        ByteBuffer byteBuffer = frame.nioBuffer();
        return RequestDecoder.decode(byteBuffer);
    } catch (Exception e) {
        //            log.error("decode exception, " + RemotingHelper.parseChannelRemoteAddr(ctx.channel()), e);
        //            RemotingUtil.closeChannel(ctx.channel());
    } finally {
        if (null != frame) {
            frame.release();
        }
    }

    return null;
}

From source file:fr.kissy.zergling_push.infrastructure.FlatBufferMessageHandler.java

License:Apache License

@Override
protected void channelRead0(ChannelHandlerContext ctx, BinaryWebSocketFrame frame) throws Exception {
    ByteBuf content = frame.content();
    ByteBuffer byteBuffer = content.nioBuffer();
    // TODO only make one time sync request ?
    if (TimeSyncRequest.TimeSyncRequestBufferHasIdentifier(byteBuffer)) {
        TimeSyncRequest timeSyncRequest = TimeSyncRequest.getRootAsTimeSyncRequest(byteBuffer);
        ctx.writeAndFlush(createTimeSyncResponse(timeSyncRequest));
    } else if (PlayerMoved.PlayerMovedBufferHasIdentifier(byteBuffer)) {
        world.getPlayer(ctx.channel().id()).moved(PlayerMoved.getRootAsPlayerMoved(byteBuffer));
    } else if (PlayerJoined.PlayerJoinedBufferHasIdentifier(byteBuffer)) {
        world.playerJoined(ctx.channel(), PlayerJoined.getRootAsPlayerJoined(byteBuffer));
    } else if (PlayerConnect.PlayerConnectBufferHasIdentifier(byteBuffer)) {
        ctx.channel().writeAndFlush(createPlayerConnectedMessage(ctx.channel()));
    } else {//from ww  w .  j  a  v a 2  s  .c  o  m
        //messagesQueue.add(new PlayerMessage(ctx.channel(), message));
    }
}

From source file:io.advantageous.conekt.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();/*ww w.  j a va2  s .  c o  m*/
    Handler<AsyncResult<Void>> wrapped = ar -> {
        if (ar.succeeded()) {
            checkContext();
            checkDrained();
            if (writesOutstanding == 0 && closedDeferred != null) {
                closedDeferred.run();
            }
            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:io.cettia.asity.bridge.netty4.NettyServerHttpExchange.java

License:Apache License

void handleChunk(HttpContent chunk) {
    // To obtain chunkAction
    read();//w  w w  . j  a va 2  s .c om
    ByteBuf buf = chunk.content();
    if (buf.isReadable() && this.chunkAction != null) {
        this.chunkAction.on(buf.nioBuffer());
    }
    if (chunk instanceof LastHttpContent) {
        endActions.fire();
    }
}

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

License:Apache License

private void addContent(ByteBuf buffer, boolean last) throws IOException {
    if (buffer != null) {
        int readableBytes = buffer.readableBytes();
        ByteBuffer byteBuffer = buffer.nioBuffer();
        if (file == null) {
            file = createTmpFile();/*from w w  w.  j  a  va  2  s.  c  o m*/
        }
        if (fileChannel == null) {
            FileOutputStream outputStream = new FileOutputStream(file);
            fileChannel = outputStream.getChannel();
        }

        int written = 0;
        do {
            if (headLength == 0) {
                updateDigest(byteBuffer);
            }
            written += fileChannel.write(byteBuffer);
        } while (written < readableBytes);
        size += readableBytes;
        buffer.readerIndex(buffer.readerIndex() + written);
        chunks++;
    }
    if (last) {
        if (file == null) {
            file = createTmpFile();
        }
        if (fileChannel == null) {
            FileOutputStream outputStream = new FileOutputStream(file);
            fileChannel = outputStream.getChannel();
        }
        fileChannel.force(false);
        fileChannel.close();
        fileChannel = null;
    } else {
        if (buffer == null) {
            throw new NullPointerException("buffer");
        }
    }
}