Example usage for io.netty.channel ChannelHandlerContext alloc

List of usage examples for io.netty.channel ChannelHandlerContext alloc

Introduction

In this page you can find the example usage for io.netty.channel ChannelHandlerContext alloc.

Prototype

ByteBufAllocator alloc();

Source Link

Document

Return the assigned ByteBufAllocator which will be used to allocate ByteBuf s.

Usage

From source file:io.grpc.alts.internal.TsiFrameHandler.java

License:Apache License

@Override
@SuppressWarnings("FutureReturnValueIgnored") // for aggregatePromise.doneAllocatingPromises
public void flush(final ChannelHandlerContext ctx) throws GeneralSecurityException {
    if (pendingUnprotectedWrites == null || pendingUnprotectedWrites.isEmpty()) {
        // Return early if there's nothing to write. Otherwise protector.protectFlush() below may
        // not check for "no-data" and go on writing the 0-byte "data" to the socket with the
        // protection framing.
        return;//from  w  ww.  j  a  v a2s  .  c  o  m
    }
    // Flushes can happen after close, but only when there are no pending writes.
    checkState(protector != null, "flush() called after close()");
    final ProtectedPromise aggregatePromise = new ProtectedPromise(ctx.channel(), ctx.executor(),
            pendingUnprotectedWrites.size());
    List<ByteBuf> bufs = new ArrayList<>(pendingUnprotectedWrites.size());

    // Drain the unprotected writes.
    while (!pendingUnprotectedWrites.isEmpty()) {
        ByteBuf in = (ByteBuf) pendingUnprotectedWrites.current();
        bufs.add(in.retain());
        // Remove and release the buffer and add its promise to the aggregate.
        aggregatePromise.addUnprotectedPromise(pendingUnprotectedWrites.remove());
    }

    final class ProtectedFrameWriteFlusher implements Consumer<ByteBuf> {

        @Override
        public void accept(ByteBuf byteBuf) {
            ctx.writeAndFlush(byteBuf, aggregatePromise.newPromise());
        }
    }

    protector.protectFlush(bufs, new ProtectedFrameWriteFlusher(), ctx.alloc());
    // We're done writing, start the flow of promise events.
    aggregatePromise.doneAllocatingPromises();
}

From source file:io.grpc.alts.internal.TsiHandshakeHandler.java

License:Apache License

@Override
protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
    // Process the data. If we need to send more data, do so now.
    if (handshaker.processBytesFromPeer(in) && handshaker.isInProgress()) {
        sendHandshake(ctx);/*  w  w  w. j  a v  a  2  s. c  o m*/
    }

    // If the handshake is complete, transition to the framing state.
    if (!handshaker.isInProgress()) {
        TsiPeer peer = handshaker.extractPeer();
        Object authContext = handshaker.extractPeerObject();
        SecurityDetails details = handshakeValidator.validatePeerObject(authContext);
        // createFrameProtector must be called last.
        TsiFrameProtector protector = handshaker.createFrameProtector(ctx.alloc());
        TsiFrameHandler framer;
        boolean success = false;
        try {
            framer = new TsiFrameHandler(protector);
            // adding framer and next handler after this handler before removing Decoder (current
            // handler). This will prevents any missing read from decoder and/or unframed write from
            // next handler.
            ctx.pipeline().addAfter(ctx.name(), null, framer);
            ctx.pipeline().addAfter(ctx.pipeline().context(framer).name(), null, next);
            ctx.pipeline().remove(ctx.name());
            fireProtocolNegotiationEvent(ctx, peer, authContext, details);
            success = true;
        } finally {
            if (!success && protector != null) {
                protector.destroy();
            }
        }
    }
}

From source file:io.grpc.alts.internal.TsiHandshakeHandler.java

License:Apache License

/** Sends as many bytes as are available from the handshaker to the remote peer. */
@SuppressWarnings("FutureReturnValueIgnored") // for addListener
private void sendHandshake(ChannelHandlerContext ctx) throws GeneralSecurityException {
    while (true) {
        boolean written = false;
        ByteBuf buf = ctx.alloc().buffer(HANDSHAKE_FRAME_SIZE).retain(); // refcnt = 2
        try {/*w  w  w .j  a  v a2 s  .c  o  m*/
            handshaker.getBytesToSendToPeer(buf);
            if (buf.isReadable()) {
                ctx.writeAndFlush(buf).addListener(ChannelFutureListener.FIRE_EXCEPTION_ON_FAILURE);
                written = true;
            } else {
                break;
            }
        } catch (GeneralSecurityException e) {
            throw new GeneralSecurityException("TsiHandshakeHandler encountered exception", e);
        } finally {
            buf.release(written ? 1 : 2);
        }
    }
}

From source file:io.grpc.netty.NettyHandlerTestBase.java

License:Apache License

protected final ChannelHandlerContext newMockContext() {
    ChannelHandlerContext ctx = mock(ChannelHandlerContext.class);
    when(ctx.alloc()).thenReturn(UnpooledByteBufAllocator.DEFAULT);
    EventLoop eventLoop = mock(EventLoop.class);
    when(ctx.executor()).thenReturn(eventLoop);
    when(ctx.channel()).thenReturn(channel);
    return ctx;/*  w  ww.j  av  a2 s . c  o  m*/
}

From source file:io.grpc.netty.NettyServerHandler.java

License:Apache License

private void respondWithHttpError(ChannelHandlerContext ctx, int streamId, int code, Status.Code statusCode,
        String msg) {//from w  ww  . ja v a 2  s . c om
    Metadata metadata = new Metadata();
    metadata.put(InternalStatus.CODE_KEY, statusCode.toStatus());
    metadata.put(InternalStatus.MESSAGE_KEY, msg);
    byte[][] serialized = InternalMetadata.serialize(metadata);

    Http2Headers headers = new DefaultHttp2Headers(true, serialized.length / 2).status("" + code)
            .set(CONTENT_TYPE_HEADER, "text/plain; encoding=utf-8");
    for (int i = 0; i < serialized.length; i += 2) {
        headers.add(new AsciiString(serialized[i], false), new AsciiString(serialized[i + 1], false));
    }
    encoder().writeHeaders(ctx, streamId, headers, 0, false, ctx.newPromise());
    ByteBuf msgBuf = ByteBufUtil.writeUtf8(ctx.alloc(), msg);
    encoder().writeData(ctx, streamId, msgBuf, 0, true, ctx.newPromise());
}

From source file:io.hekate.network.netty.NettyServerClient.java

License:Apache License

private void write(Object msg, NetworkSendCallback<Object> onSend, ChannelHandlerContext localCtx) {
    if (!validateMessageType(msg, onSend)) {
        return;/*w ww  . j a v  a  2s .  co m*/
    }

    if (debug) {
        log.debug("Sending to client [to={}, message={}]", address(), msg);
    }

    if (metrics != null) {
        metrics.onMessageEnqueue();
    }

    Channel channel = localCtx.channel();

    // Prepare deferred message.
    DeferredMessage deferredMsg;

    boolean failed = false;

    // Maybe pre-encode message.
    if (codec.isStateful()) {
        deferredMsg = new DeferredMessage(msg, channel);
    } else {
        if (trace) {
            log.trace("Pre-encoding message [to={}, message={}]", address(), msg);
        }

        try {
            ByteBuf buf = NetworkProtocolCodec.preEncode(msg, codec, localCtx.alloc());

            deferredMsg = new DeferredEncodedMessage(buf, msg, channel);
        } catch (CodecException e) {
            deferredMsg = fail(msg, channel, e);

            failed = true;
        }
    }

    deferredMsg.addListener(result -> {
        if (metrics != null) {
            metrics.onMessageDequeue();
        }

        if (result.isSuccess()) {
            // Successful operation.
            if (debug) {
                log.debug("Done sending to client [to={}, message={}]", address(), msg);
            }

            if (metrics != null) {
                metrics.onMessageSent();
            }
        } else {
            // Failed operation.
            if (debug) {
                log.debug("Failed to send to client [to={}, message={}]", address(), msg, result.cause());
            }

            // Notify channel pipeline on error (ignore if channel is already closed).
            if (channel.isOpen()) {
                channel.pipeline().fireExceptionCaught(result.cause());
            }
        }

        // Notify user callback.
        if (onSend != null) {
            try {
                Throwable mayBeError = NettyErrorUtils.unwrap(result.cause());

                onSend.onComplete(msg, mayBeError);
            } catch (Throwable t) {
                if (log.isErrorEnabled()) {
                    log.error("Failed to notify network message callback [message={}]", msg, t);
                }
            }
        }
    });

    // Enqueue write operation.
    if (!failed) {
        writeQueue.enqueue(deferredMsg, localCtx.executor());
    }
}

From source file:io.hydramq.core.net.netty.CommandEncoder.java

License:Open Source License

@Override
protected void encode(final ChannelHandlerContext ctx, final Command command, final List<Object> out)
        throws Exception {
    final ByteBuf buffer = ctx.alloc().buffer();
    conversionContext.write(command, buffer);
    out.add(buffer);//from  w  w w .  j av  a 2 s .c om
}

From source file:io.hydramq.network.server.BaseProtocolHandler.java

License:Open Source License

public void send(final ChannelHandlerContext ctx, final Command command) {
    ByteBuf buffer = ctx.alloc().buffer();
    conversionContext.write(command, buffer);
    ctx.writeAndFlush(buffer, ctx.voidPromise());
}

From source file:io.jsync.http.impl.AsyncHttpHandler.java

License:Open Source License

@Override
public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception {
    if (msg instanceof WebSocketFrameInternal) {
        WebSocketFrameInternal frame = (WebSocketFrameInternal) msg;
        ByteBuf buf = frame.getBinaryData();
        if (buf != Unpooled.EMPTY_BUFFER) {
            buf = safeBuffer(buf, ctx.alloc());
        }//from ww w. j ava  2s .  co m
        switch (frame.type()) {
        case BINARY:
            msg = new BinaryWebSocketFrame(buf);
            break;
        case TEXT:
            msg = new TextWebSocketFrame(buf);
            break;
        case CLOSE:
            msg = new CloseWebSocketFrame(true, 0, buf);
            break;
        case CONTINUATION:
            msg = new ContinuationWebSocketFrame(buf);
            break;
        case PONG:
            msg = new PongWebSocketFrame(buf);
            break;
        case PING:
            msg = new PingWebSocketFrame(buf);
            break;
        default:
            throw new IllegalStateException("Unsupported websocket msg " + msg);
        }
    }
    ctx.write(msg, promise);
}

From source file:io.jsync.net.impl.AsyncHandler.java

License:Open Source License

@Override
public void channelRead(ChannelHandlerContext chctx, Object msg) throws Exception {
    final Object message = safeObject(msg, chctx.alloc());
    final C connection = connectionMap.get(chctx.channel());

    DefaultContext context;/*  w  ww .  ja v  a 2 s. c  o m*/
    if (connection != null) {
        context = getContext(connection);
        // Only mark start read if we are on the correct worker. This is needed as while we are in read this may will
        // delay flushes, which is a problem when we are no on the correct worker. This is mainly a problem as
        // WorkerVerticle may block.
        if (context.isOnCorrectWorker(chctx.channel().eventLoop())) {
            connection.startRead();
        }
    } else {
        context = null;
    }
    channelRead(connection, context, chctx, message);
}