Example usage for io.netty.channel ChannelHandlerContext executor

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

Introduction

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

Prototype

EventExecutor executor();

Source Link

Document

Returns the EventExecutor which is used to execute an arbitrary task.

Usage

From source file:com.basho.riak.client.core.netty.RiakSecurityDecoder.java

License:Apache License

private void init(ChannelHandlerContext ctx) {
    state = State.TLS_WAIT;//from w w w  . j  av  a 2  s  . c o m
    promise = new DefaultPromise<Void>(ctx.executor());
    promiseLatch.countDown();
    ctx.channel().writeAndFlush(new RiakMessage(RiakMessageCodes.MSG_StartTls, new byte[0]));

}

From source file:com.book.netty5.client.HeartBeatReqHandler.java

License:Apache License

public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
    NettyMessage message = (NettyMessage) msg;
    // ?????/* w  w  w .  j av  a  2 s  .c om*/
    if (message.getHeader() != null && message.getHeader().getType() == MessageType.LOGIN_RESP.value()) {
        heartBeat = ctx.executor().scheduleAtFixedRate(new HeartBeatReqHandler.HeartBeatTask(ctx), 0, 5000,
                TimeUnit.MILLISECONDS);
    } else if (message.getHeader() != null
            && message.getHeader().getType() == MessageType.HEARTBEAT_RESP.value()) {
        System.out.println("Client receive server heart beat message : ---> " + message);
    } else
        ctx.fireChannelRead(msg);
}

From source file:com.changxx.phei.netty.protocol.netty.client.HeartBeatReqHandler.java

License:Apache License

@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
    NettyMessage message = (NettyMessage) msg;
    // ?????/*from w w w .j  av  a  2  s  .  com*/
    if (message.getHeader() != null && message.getHeader().getType() == MessageType.LOGIN_RESP.value()) {
        heartBeat = ctx.executor().scheduleAtFixedRate(new HeartBeatTask(ctx), 0, 5000, TimeUnit.MILLISECONDS);
    } else if (message.getHeader() != null
            && message.getHeader().getType() == MessageType.HEARTBEAT_RESP.value()) {
        System.out.println("Client receive server heart beat message : ---> " + message);
    } else {
        ctx.fireChannelRead(msg);
    }
}

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

License:Apache License

private void onAcknowledge(ChannelHandlerContext ctx, ByteBuf buffer) {
    logger.debug("Received Acknowledge message on channel={}.", ctx.channel());

    buffer.skipBytes(3 + 1 + 4); // Skip messageType, chunkType, and messageSize

    AcknowledgeMessage acknowledge = AcknowledgeMessage.decode(buffer);

    long remoteProtocolVersion = acknowledge.getProtocolVersion();
    long remoteReceiveBufferSize = acknowledge.getReceiveBufferSize();
    long remoteSendBufferSize = acknowledge.getSendBufferSize();
    long remoteMaxMessageSize = acknowledge.getMaxMessageSize();
    long remoteMaxChunkCount = acknowledge.getMaxChunkCount();

    if (PROTOCOL_VERSION > remoteProtocolVersion) {
        logger.warn("Client protocol version ({}) does not match server protocol version ({}).",
                PROTOCOL_VERSION, remoteProtocolVersion);
    }/*from   w  ww  . j av a 2s. c  om*/

    ChannelConfig config = client.getChannelConfig();

    /* Our receive buffer size is determined by the remote send buffer size. */
    long localReceiveBufferSize = Math.min(remoteSendBufferSize, config.getMaxChunkSize());

    /* Our send buffer size is determined by the remote receive buffer size. */
    long localSendBufferSize = Math.min(remoteReceiveBufferSize, config.getMaxChunkSize());

    /* Max message size the remote can send us; not influenced by remote configuration. */
    long localMaxMessageSize = config.getMaxMessageSize();

    /* Max chunk count the remote can send us; not influenced by remote configuration. */
    long localMaxChunkCount = config.getMaxChunkCount();

    ChannelParameters parameters = new ChannelParameters(Ints.saturatedCast(localMaxMessageSize),
            Ints.saturatedCast(localReceiveBufferSize), Ints.saturatedCast(localSendBufferSize),
            Ints.saturatedCast(localMaxChunkCount), Ints.saturatedCast(remoteMaxMessageSize),
            Ints.saturatedCast(remoteReceiveBufferSize), Ints.saturatedCast(remoteSendBufferSize),
            Ints.saturatedCast(remoteMaxChunkCount));

    ctx.channel().attr(KEY_AWAITING_HANDSHAKE).set(awaitingHandshake);

    ctx.executor().execute(() -> {
        int maxArrayLength = client.getChannelConfig().getMaxArrayLength();
        int maxStringLength = client.getChannelConfig().getMaxStringLength();

        SerializationQueue serializationQueue = new SerializationQueue(client.getConfig().getExecutor(),
                parameters, maxArrayLength, maxStringLength);

        UaTcpClientAsymmetricHandler handler = new UaTcpClientAsymmetricHandler(client, serializationQueue,
                secureChannel, handshakeFuture);

        ctx.pipeline().addLast(handler);
    });
}

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

License:Apache License

private void installSecurityToken(ChannelHandlerContext ctx, OpenSecureChannelResponse response) {
    ChannelSecurity.SecuritySecrets newKeys = null;
    if (response.getServerProtocolVersion().longValue() < PROTOCOL_VERSION) {
        throw new UaRuntimeException(StatusCodes.Bad_ProtocolVersionUnsupported,
                "server protocol version unsupported: " + response.getServerProtocolVersion());
    }//  w  w  w  . j  a va  2  s.c o  m

    ChannelSecurityToken newToken = response.getSecurityToken();

    if (secureChannel.isSymmetricSigningEnabled()) {
        secureChannel.setRemoteNonce(response.getServerNonce());

        newKeys = ChannelSecurity.generateKeyPair(secureChannel, secureChannel.getLocalNonce(),
                secureChannel.getRemoteNonce());
    }

    ChannelSecurity oldSecrets = secureChannel.getChannelSecurity();
    ChannelSecurity.SecuritySecrets oldKeys = oldSecrets != null ? oldSecrets.getCurrentKeys() : null;
    ChannelSecurityToken oldToken = oldSecrets != null ? oldSecrets.getCurrentToken() : null;

    secureChannel.setChannelSecurity(new ChannelSecurity(newKeys, newToken, oldKeys, oldToken));

    DateTime createdAt = response.getSecurityToken().getCreatedAt();
    long revisedLifetime = response.getSecurityToken().getRevisedLifetime().longValue();

    if (revisedLifetime > 0) {
        long renewAt = (long) (revisedLifetime * 0.75);
        renewFuture = ctx.executor().schedule(() -> renewSecureChannel(ctx), renewAt, TimeUnit.MILLISECONDS);
    } else {
        logger.warn("Server revised secure channel lifetime to 0; renewal will not occur.");
    }

    ctx.executor().execute(() -> {
        // SecureChannel is ready; remove the acknowledge handler and add the symmetric handler.
        if (ctx.pipeline().get(UaTcpClientAcknowledgeHandler.class) != null) {
            ctx.pipeline().remove(UaTcpClientAcknowledgeHandler.class);
            ctx.pipeline().addFirst(new UaTcpClientSymmetricHandler(client, serializationQueue, secureChannel,
                    handshakeFuture));
        }
    });

    ChannelSecurity channelSecurity = secureChannel.getChannelSecurity();

    long currentTokenId = channelSecurity.getCurrentToken().getTokenId().longValue();

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

    logger.debug("SecureChannel id={}, currentTokenId={}, previousTokenId={}, lifetime={}ms, createdAt={}",
            secureChannel.getChannelId(), currentTokenId, previousTokenId, revisedLifetime, createdAt);
}

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 va  2 s  .  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  va2 s . c o  m*/
            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  .  ja  v  a  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.  ja  v a 2 s.c om
            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();//from w w w . j av  a  2s.  c o m
            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();
        });
    });
}