Example usage for io.netty.buffer ByteBuf readUnsignedInt

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

Introduction

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

Prototype

public abstract long readUnsignedInt();

Source Link

Document

Gets an unsigned 32-bit integer at the current readerIndex and increases the readerIndex by 4 in this buffer.

Usage

From source file:com.cdg.study.netty.time.TimeClientHandler.java

License:Open Source License

@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) {
    ByteBuf m = (ByteBuf) msg; // (1)
    try {//from   w ww  .j  a  va 2s  .co  m
        long currentTimeMillis = (m.readUnsignedInt() - 2208988800L) * 1000L;
        System.out.println(new Date(currentTimeMillis));
        ctx.close();
    } finally {
        m.release();
    }
}

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

License:Apache License

private void onOpenSecureChannel(ChannelHandlerContext ctx, ByteBuf buffer) throws UaException {
    buffer.skipBytes(3 + 1 + 4); // skip messageType, chunkType, messageSize

    long secureChannelId = buffer.readUnsignedInt();

    secureChannel.setChannelId(secureChannelId);

    AsymmetricSecurityHeader securityHeader = AsymmetricSecurityHeader.decode(buffer);
    if (!headerRef.compareAndSet(null, securityHeader)) {
        if (!securityHeader.equals(headerRef.get())) {
            throw new UaRuntimeException(StatusCodes.Bad_SecurityChecksFailed,
                    "subsequent AsymmetricSecurityHeader did not match");
        }//from   w  w  w.ja  v  a  2 s . c o  m
    }

    int chunkSize = buffer.readerIndex(0).readableBytes();

    if (chunkSize > maxChunkSize) {
        throw new UaException(StatusCodes.Bad_TcpMessageTooLarge,
                String.format("max chunk size exceeded (%s)", maxChunkSize));
    }

    chunkBuffers.add(buffer.retain());

    if (chunkBuffers.size() > maxChunkCount) {
        throw new UaException(StatusCodes.Bad_TcpMessageTooLarge,
                String.format("max chunk count exceeded (%s)", maxChunkCount));
    }

    char chunkType = (char) buffer.getByte(3);

    if (chunkType == 'A' || chunkType == 'F') {
        final List<ByteBuf> buffersToDecode = chunkBuffers;
        chunkBuffers = new ArrayList<>(maxChunkCount);

        serializationQueue.decode((binaryDecoder, chunkDecoder) -> {
            ByteBuf decodedBuffer = null;

            try {
                decodedBuffer = chunkDecoder.decodeAsymmetric(secureChannel, buffersToDecode);

                UaResponseMessage responseMessage = binaryDecoder.setBuffer(decodedBuffer).decodeMessage(null);

                StatusCode serviceResult = responseMessage.getResponseHeader().getServiceResult();

                if (serviceResult.isGood()) {
                    OpenSecureChannelResponse response = (OpenSecureChannelResponse) responseMessage;

                    secureChannel.setChannelId(response.getSecurityToken().getChannelId().longValue());
                    logger.debug("Received OpenSecureChannelResponse.");

                    installSecurityToken(ctx, response);
                } else {
                    ServiceFault serviceFault = (responseMessage instanceof ServiceFault)
                            ? (ServiceFault) responseMessage
                            : new ServiceFault(responseMessage.getResponseHeader());

                    throw new UaServiceFaultException(serviceFault);
                }
            } catch (MessageAbortedException e) {
                logger.error("Received message abort chunk; error={}, reason={}", e.getStatusCode(),
                        e.getMessage());
                ctx.close();
            } catch (Throwable t) {
                logger.error("Error decoding OpenSecureChannelResponse: {}", t.getMessage(), t);
                ctx.close();
            } finally {
                if (decodedBuffer != null) {
                    decodedBuffer.release();
                }
                buffersToDecode.clear();
            }
        });
    }
}

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

License:Apache License

private void onSecureMessage(ChannelHandlerContext ctx, ByteBuf buffer) throws UaException {
    buffer.skipBytes(3 + 1 + 4); // skip messageType, chunkType, messageSize

    long secureChannelId = buffer.readUnsignedInt();
    if (secureChannelId != secureChannel.getChannelId()) {
        throw new UaException(StatusCodes.Bad_SecureChannelIdInvalid,
                "invalid secure channel id: " + secureChannelId);
    }//from   w w  w.  j a va2s.  c  o  m

    if (accumulateChunk(buffer)) {
        final List<ByteBuf> buffersToDecode = ImmutableList.copyOf(chunkBuffers);
        chunkBuffers = new LinkedList<>();

        serializationQueue.decode((binaryDecoder, chunkDecoder) -> {
            ByteBuf decodedBuffer = null;

            try {
                decodedBuffer = chunkDecoder.decodeSymmetric(secureChannel, buffersToDecode);

                binaryDecoder.setBuffer(decodedBuffer);
                UaResponseMessage response = binaryDecoder.decodeMessage(null);

                UaRequestFuture request = pending.remove(chunkDecoder.getLastRequestId());

                if (request != null) {
                    client.getExecutorService().execute(() -> request.getFuture().complete(response));
                } else {
                    logger.warn("No UaRequestFuture for requestId={}", chunkDecoder.getLastRequestId());
                }
            } catch (MessageAbortedException e) {
                logger.debug("Received message abort chunk; error={}, reason={}", e.getStatusCode(),
                        e.getMessage());

                UaRequestFuture request = pending.remove(chunkDecoder.getLastRequestId());

                if (request != null) {
                    client.getExecutorService().execute(() -> request.getFuture().completeExceptionally(e));
                } else {
                    logger.warn("No UaRequestFuture for requestId={}", chunkDecoder.getLastRequestId());
                }
            } catch (Throwable t) {
                logger.error("Error decoding symmetric message: {}", t.getMessage(), t);
                serializationQueue.pause();
                ctx.close();
            } finally {
                if (decodedBuffer != null) {
                    decodedBuffer.release();
                }
            }
        });
    }
}

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

License:Apache License

private void onSecureMessage(ChannelHandlerContext ctx, ByteBuf buffer) throws UaException {
    buffer.skipBytes(3 + 1 + 4); // skip messageType, chunkType, messageSize

    long secureChannelId = buffer.readUnsignedInt();
    if (secureChannelId != secureChannel.getChannelId()) {
        throw new UaException(StatusCodes.Bad_SecureChannelIdInvalid,
                "invalid secure channel id: " + secureChannelId);
    }/* w w  w  .  ja va2 s  .c  o  m*/

    int chunkSize = buffer.readerIndex(0).readableBytes();
    if (chunkSize > maxChunkSize) {
        throw new UaException(StatusCodes.Bad_TcpMessageTooLarge,
                String.format("max chunk size exceeded (%s)", maxChunkSize));
    }

    chunkBuffers.add(buffer.retain());

    if (chunkBuffers.size() > maxChunkCount) {
        throw new UaException(StatusCodes.Bad_TcpMessageTooLarge,
                String.format("max chunk count exceeded (%s)", maxChunkCount));
    }

    char chunkType = (char) buffer.getByte(3);

    if (chunkType == 'A' || chunkType == 'F') {
        final List<ByteBuf> buffersToDecode = chunkBuffers;
        chunkBuffers = new ArrayList<>(maxChunkCount);

        serializationQueue.decode((binaryDecoder, chunkDecoder) -> {
            ByteBuf decodedBuffer = null;

            try {
                validateChunkHeaders(buffersToDecode);

                decodedBuffer = chunkDecoder.decodeSymmetric(secureChannel, buffersToDecode);

                binaryDecoder.setBuffer(decodedBuffer);
                UaResponseMessage response = binaryDecoder.decodeMessage(null);

                UaRequestFuture request = pending.remove(chunkDecoder.getLastRequestId());

                if (request != null) {
                    client.getExecutorService().execute(() -> request.getFuture().complete(response));
                } else {
                    logger.warn("No UaRequestFuture for requestId={}", chunkDecoder.getLastRequestId());
                }
            } catch (MessageAbortedException e) {
                logger.debug("Received message abort chunk; error={}, reason={}", e.getStatusCode(),
                        e.getMessage());

                UaRequestFuture request = pending.remove(chunkDecoder.getLastRequestId());

                if (request != null) {
                    client.getExecutorService().execute(() -> request.getFuture().completeExceptionally(e));
                } else {
                    logger.warn("No UaRequestFuture for requestId={}", chunkDecoder.getLastRequestId());
                }
            } catch (Throwable t) {
                logger.error("Error decoding symmetric message: {}", t.getMessage(), t);
                ctx.close();
                serializationQueue.pause();
            } finally {
                if (decodedBuffer != null) {
                    decodedBuffer.release();
                }
                buffersToDecode.clear();
            }
        });
    }
}

From source file:com.digitalpetri.opcua.stack.core.channel.headers.SecureMessageHeader.java

License:Apache License

public static SecureMessageHeader decode(ByteBuf buffer) throws UaException {
    return new SecureMessageHeader(MessageType.fromMediumInt(buffer.readMedium()), (char) buffer.readByte(),
            buffer.readUnsignedInt(), buffer.readUnsignedInt());
}

From source file:com.digitalpetri.opcua.stack.core.channel.headers.SequenceHeader.java

License:Apache License

public static SequenceHeader decode(ByteBuf buffer) {
    return new SequenceHeader(buffer.readUnsignedInt(), /*    SequenceNumber  */
            buffer.readUnsignedInt() /*    RequestId       */
    );//from  ww  w  .ja va 2 s .  c o  m
}

From source file:com.digitalpetri.opcua.stack.core.channel.headers.SymmetricSecurityHeader.java

License:Apache License

public static SymmetricSecurityHeader decode(ByteBuf buffer) {
    return new SymmetricSecurityHeader(buffer.readUnsignedInt());
}

From source file:com.digitalpetri.opcua.stack.core.channel.messages.AcknowledgeMessage.java

License:Apache License

public static AcknowledgeMessage decode(ByteBuf buffer) {
    return new AcknowledgeMessage(buffer.readUnsignedInt(), /*    ProtocolVersion     */
            buffer.readUnsignedInt(), /*    ReceiveBufferSize   */
            buffer.readUnsignedInt(), /*    SendBufferSize      */
            buffer.readUnsignedInt(), /*    MaxMessageSize      */
            buffer.readUnsignedInt() /*    MaxChunkCount       */
    );/*ww  w.  j a  v a 2 s  .c  o m*/
}

From source file:com.digitalpetri.opcua.stack.core.channel.messages.ErrorMessage.java

License:Apache License

public static ErrorMessage decode(ByteBuf buffer) {
    return new ErrorMessage(buffer.readUnsignedInt(), decodeString(buffer));
}

From source file:com.digitalpetri.opcua.stack.core.channel.messages.HelloMessage.java

License:Apache License

public static HelloMessage decode(ByteBuf buffer) {
    return new HelloMessage(buffer.readUnsignedInt(), /*    ProtocolVersion    */
            buffer.readUnsignedInt(), /*    ReceiveBufferSize  */
            buffer.readUnsignedInt(), /*    SendBufferSize     */
            buffer.readUnsignedInt(), /*    MaxMessageSize     */
            buffer.readUnsignedInt(), /*    MaxChunkCount      */
            decodeString(buffer) /*    EndpointUrl        */
    );/*from w ww .j ava2 s.c  om*/
}