Example usage for io.netty.channel ChannelHandlerContext flush

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

Introduction

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

Prototype

@Override
    ChannelHandlerContext flush();

Source Link

Usage

From source file:com.couchbase.client.core.io.endpoint.GenericEndpointHandler.java

License:Open Source License

@Override
public void handlerAdded(final ChannelHandlerContext ctx) throws Exception {
    super.handlerAdded(ctx);

    ctx.channel().eventLoop().scheduleAtFixedRate(new Runnable() {
        @Override/*from  w w  w  .j a v  a 2  s . co  m*/
        public void run() {
            ctx.flush();
        }
    }, 0, 75, TimeUnit.MICROSECONDS);
}

From source file:com.digitalpetri.opcua.stack.client.handlers.UaTcpClientAsymmetricHandler.java

License:Apache License

private void sendOpenSecureChannelRequest(ChannelHandlerContext ctx, OpenSecureChannelRequest request) {
    serializationQueue.encode((binaryEncoder, chunkEncoder) -> {
        ByteBuf messageBuffer = BufferUtil.buffer();

        try {//  w  ww  .j a  v a2s .  c om
            binaryEncoder.setBuffer(messageBuffer);
            binaryEncoder.encodeMessage(null, request);

            List<ByteBuf> chunks = chunkEncoder.encodeAsymmetric(secureChannel, MessageType.OpenSecureChannel,
                    messageBuffer, requestId.getAndIncrement());

            ctx.executor().execute(() -> {
                chunks.forEach(c -> ctx.write(c, ctx.voidPromise()));
                ctx.flush();
            });

            ChannelSecurity channelSecurity = secureChannel.getChannelSecurity();

            long currentTokenId = channelSecurity != null
                    ? channelSecurity.getCurrentToken().getTokenId().longValue()
                    : -1L;

            long previousTokenId = channelSecurity != null
                    ? channelSecurity.getPreviousToken().map(t -> t.getTokenId().longValue()).orElse(-1L)
                    : -1L;

            logger.debug("Sent OpenSecureChannelRequest ({}, id={}, currentToken={}, previousToken={}).",
                    request.getRequestType(), secureChannel.getChannelId(), currentTokenId, previousTokenId);
        } catch (UaException e) {
            logger.error("Error encoding OpenSecureChannelRequest: {}", e.getMessage(), e);
            ctx.close();
        } finally {
            messageBuffer.release();
        }
    });
}

From source file:com.digitalpetri.opcua.stack.client.handlers.UaTcpClientAsymmetricHandler.java

License:Apache License

private void sendCloseSecureChannelRequest(ChannelHandlerContext ctx, CloseSecureChannelRequest request) {
    serializationQueue.encode((binaryEncoder, chunkEncoder) -> {
        ByteBuf messageBuffer = BufferUtil.buffer();

        try {//from   w ww .ja  v a 2s  .com
            binaryEncoder.setBuffer(messageBuffer);
            binaryEncoder.encodeMessage(null, request);

            List<ByteBuf> chunks = chunkEncoder.encodeSymmetric(secureChannel, MessageType.CloseSecureChannel,
                    messageBuffer, requestId.getAndIncrement());

            ctx.executor().execute(() -> {
                chunks.forEach(c -> ctx.write(c, ctx.voidPromise()));
                ctx.flush();
                ctx.close();
            });

            secureChannel.setChannelId(0);

            logger.debug("Sent CloseSecureChannelRequest.");
        } catch (UaException e) {
            logger.error("Error Encoding CloseSecureChannelRequest: {}", e.getMessage(), e);
            ctx.close();
        } finally {
            messageBuffer.release();
        }
    });
}

From source file:com.digitalpetri.opcua.stack.client.handlers.UaTcpClientMessageHandler.java

License:Apache License

private void sendOpenSecureChannelRequest(ChannelHandlerContext ctx, SecurityTokenRequestType requestType) {
    SecurityAlgorithm algorithm = secureChannel.getSecurityPolicy().getSymmetricEncryptionAlgorithm();
    int nonceLength = NonceUtil.getNonceLength(algorithm);

    ByteString clientNonce = secureChannel.isSymmetricSigningEnabled() ? NonceUtil.generateNonce(nonceLength)
            : ByteString.NULL_VALUE;//from   ww  w  .j ava  2 s  . c  o  m

    secureChannel.setLocalNonce(clientNonce);

    OpenSecureChannelRequest request = new OpenSecureChannelRequest(
            new RequestHeader(null, DateTime.now(), uint(0), uint(0), null, uint(0), null),
            uint(PROTOCOL_VERSION), requestType, secureChannel.getMessageSecurityMode(),
            secureChannel.getLocalNonce(), client.getChannelLifetime());

    encodeMessage(request, MessageType.OpenSecureChannel).whenComplete((t2, ex) -> {
        if (ex != null) {
            ctx.close();
            return;
        }

        List<ByteBuf> chunks = t2.v2();

        ctx.executor().execute(() -> {
            chunks.forEach(c -> ctx.write(c, ctx.voidPromise()));
            ctx.flush();
        });

        ChannelSecurity channelSecurity = secureChannel.getChannelSecurity();

        long currentTokenId = channelSecurity != null
                ? channelSecurity.getCurrentToken().getTokenId().longValue()
                : -1L;

        long previousTokenId = channelSecurity != null
                ? channelSecurity.getPreviousToken().map(token -> token.getTokenId().longValue()).orElse(-1L)
                : -1L;

        logger.debug("Sent OpenSecureChannelRequest ({}, id={}, currentToken={}, previousToken={}).",
                request.getRequestType(), secureChannel.getChannelId(), currentTokenId, previousTokenId);
    });
}

From source file:com.digitalpetri.opcua.stack.client.handlers.UaTcpClientMessageHandler.java

License:Apache License

private void sendCloseSecureChannelRequest(ChannelHandlerContext ctx, CloseSecureChannelRequest request) {
    encodeMessage(request, MessageType.CloseSecureChannel).whenComplete((t2, ex) -> {
        if (ex != null) {
            ctx.close();//from   w  w  w .j  a  va2s . c  o m
            return;
        }

        List<ByteBuf> chunks = t2.v2();

        ctx.executor().execute(() -> {
            chunks.forEach(c -> ctx.write(c, ctx.voidPromise()));
            ctx.flush();
            ctx.close();
        });

        secureChannel.setChannelId(0);
    });
}

From source file:com.digitalpetri.opcua.stack.client.handlers.UaTcpClientMessageHandler.java

License:Apache License

@Override
protected void encode(ChannelHandlerContext ctx, UaRequestFuture request, ByteBuf buffer) throws Exception {
    encodeMessage(request.getRequest(), MessageType.SecureMessage).whenComplete((t2, ex) -> {
        if (ex != null) {
            ctx.close();/*ww  w. java  2s.  c  om*/
            return;
        }

        long requestId = t2.v1();
        List<ByteBuf> chunks = t2.v2();

        pending.put(requestId, request);

        // No matter how we complete, make sure the entry in pending is removed.
        // This covers the case where the request fails due to a timeout in the
        // upper layers as well as normal completion.
        request.getFuture().whenComplete((r, x) -> pending.remove(requestId));

        ctx.executor().execute(() -> {
            chunks.forEach(c -> ctx.write(c, ctx.voidPromise()));
            ctx.flush();
        });
    });
}

From source file:com.digitalpetri.opcua.stack.client.handlers.UaTcpClientSymmetricHandler.java

License:Apache License

@Override
public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
    List<UaMessage> awaitingHandshake = ctx.channel().attr(UaTcpClientAcknowledgeHandler.KEY_AWAITING_HANDSHAKE)
            .get();// w  ww .  ja  v  a  2s.c  o  m

    if (awaitingHandshake != null) {
        logger.debug("{} message(s) queued before handshake completed; sending now.", awaitingHandshake.size());
        awaitingHandshake.forEach(m -> ctx.pipeline().write(m));
        ctx.flush();

        ctx.channel().attr(UaTcpClientAcknowledgeHandler.KEY_AWAITING_HANDSHAKE).remove();
    }

    client.getExecutorService().execute(() -> handshakeFuture.complete(secureChannel));
}

From source file:com.digitalpetri.opcua.stack.client.handlers.UaTcpClientSymmetricHandler.java

License:Apache License

@Override
protected void encode(ChannelHandlerContext ctx, UaRequestFuture message, ByteBuf out) throws Exception {
    serializationQueue.encode((binaryEncoder, chunkEncoder) -> {
        ByteBuf messageBuffer = BufferUtil.buffer();

        try {//from  w  w  w . j  a va 2  s .  c o  m
            binaryEncoder.setBuffer(messageBuffer);
            binaryEncoder.encodeMessage(null, message.getRequest());

            List<ByteBuf> chunks = chunkEncoder.encodeSymmetric(secureChannel, MessageType.SecureMessage,
                    messageBuffer, requestId.getAndIncrement());

            long requestId = chunkEncoder.getLastRequestId();
            pending.put(requestId, message);

            // No matter how we complete, make sure the entry in pending is removed.
            // This covers the case where the request fails due to a timeout in the
            // upper layers as well as normal completion.
            message.getFuture().whenComplete((r, x) -> pending.remove(requestId));

            ctx.executor().execute(() -> {
                chunks.forEach(c -> ctx.write(c, ctx.voidPromise()));
                ctx.flush();
            });
        } catch (UaException e) {
            logger.error("Error encoding {}: {}", message.getClass(), e.getMessage(), e);
            ctx.close();
        } finally {
            messageBuffer.release();
        }
    });
}

From source file:com.digitalpetri.opcua.stack.server.handlers.UaTcpServerAsymmetricHandler.java

License:Apache License

private void sendOpenSecureChannelResponse(ChannelHandlerContext ctx, long requestId,
        OpenSecureChannelResponse response) {
    serializationQueue.encode((binaryEncoder, chunkEncoder) -> {
        ByteBuf messageBuffer = BufferUtil.buffer();

        try {/*  www.  j  a  v a 2  s.c  om*/
            binaryEncoder.setBuffer(messageBuffer);
            binaryEncoder.encodeMessage(null, response);

            List<ByteBuf> chunks = chunkEncoder.encodeAsymmetric(secureChannel, MessageType.OpenSecureChannel,
                    messageBuffer, requestId);

            if (!symmetricHandlerAdded) {
                ctx.pipeline()
                        .addFirst(new UaTcpServerSymmetricHandler(server, serializationQueue, secureChannel));
                symmetricHandlerAdded = true;
            }

            chunks.forEach(c -> ctx.write(c, ctx.voidPromise()));
            ctx.flush();

            long lifetime = response.getSecurityToken().getRevisedLifetime().longValue();
            server.secureChannelIssuedOrRenewed(secureChannel, lifetime);

            logger.debug("Sent OpenSecureChannelResponse.");
        } catch (UaException e) {
            logger.error("Error encoding OpenSecureChannelResponse: {}", e.getMessage(), e);
            ctx.close();
        } finally {
            messageBuffer.release();
        }
    });
}

From source file:com.digitalpetri.opcua.stack.server.handlers.UaTcpServerSymmetricHandler.java

License:Apache License

@Override
protected void encode(ChannelHandlerContext ctx, ServiceResponse message, ByteBuf out) throws Exception {
    serializationQueue.encode((binaryEncoder, chunkEncoder) -> {
        ByteBuf messageBuffer = BufferUtil.buffer();

        try {//from   www.j a  va  2s  . c om
            binaryEncoder.setBuffer(messageBuffer);
            binaryEncoder.encodeMessage(null, message.getResponse());

            final List<ByteBuf> chunks = chunkEncoder.encodeSymmetric(secureChannel, MessageType.SecureMessage,
                    messageBuffer, message.getRequestId());

            ctx.executor().execute(() -> {
                chunks.forEach(c -> ctx.write(c, ctx.voidPromise()));
                ctx.flush();
            });
        } catch (UaException e) {
            logger.error("Error encoding {}: {}", message.getResponse().getClass(), e.getMessage(), e);
            ctx.close();
        } finally {
            messageBuffer.release();
        }
    });
}