Example usage for io.netty.buffer ByteBuf readSlice

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

Introduction

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

Prototype

public abstract ByteBuf readSlice(int length);

Source Link

Document

Returns a new slice of this buffer's sub-region starting at the current readerIndex and increases the readerIndex by the size of the new slice (= length ).

Usage

From source file:org.dcache.xrootd.core.XrootdSigverDecoder.java

License:Open Source License

@Override
protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) {
    int length = verifyMessageLength(in);

    if (length < 0) {
        ctx.channel().close();/*from   w  ww.jav  a2 s. c  om*/
        return;
    }

    if (length == 0) {
        return;
    }

    ByteBuf frame = in.readSlice(length);
    XrootdRequest request = getRequest(frame);

    try {
        if (request instanceof SigverRequest) {
            setSigver((SigverRequest) request);
            /*
             *  No need to pass it downstream.
             */
            return;
        }

        int requestId = request.getRequestId();

        if (signingPolicy.requiresSigning(requestId)) {
            verifySignedHash(request.getStreamId(), requestId, frame, ctx);
        }
    } catch (XrootdException e) {
        ErrorResponse<?> response = new ErrorResponse<>(request, e.getError(),
                Strings.nullToEmpty(e.getMessage()));
        ctx.writeAndFlush(response).addListener(ChannelFutureListener.FIRE_EXCEPTION_ON_FAILURE);
        return;
    }

    out.add(request);
}

From source file:org.dcache.xrootd.tpc.core.XrootdClientDecoder.java

License:Open Source License

@Override
protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) {
    ChannelId id = ctx.channel().id();//from  ww  w  .  j a v a 2  s .c o m
    int readable = in.readableBytes();

    if (readable < SERVER_RESPONSE_LEN) {
        return;
    }

    int pos = in.readerIndex();
    int headerFrameLength = in.getInt(pos + 4);

    if (headerFrameLength < 0) {
        LOGGER.error("Decoder {}, channel {}: received illegal " + "frame length in " + "xrootd header: {}."
                + " Closing channel.", sourceUrn, id, headerFrameLength);
        ctx.channel().close();
        return;
    }

    int length = SERVER_RESPONSE_LEN + headerFrameLength;

    if (readable < length) {
        return;
    }

    ByteBuf frame = in.readSlice(length);
    int requestId = client.getExpectedResponse();

    try {
        switch (frame.getUnsignedShort(2)) {
        case kXR_error:
            LOGGER.trace("Decoder {}, channel {}: adding error response.", sourceUrn, id);
            out.add(new InboundErrorResponse(frame));
            return;
        case kXR_wait:
            LOGGER.trace("Decoder {}, channel {}: adding wait response.", sourceUrn, id);
            out.add(new InboundWaitResponse(frame, requestId));
            return;
        case kXR_waitresp:
            LOGGER.trace("Decoder {}, channel {}: adding waitresp response.", sourceUrn, id);
            out.add(new InboundWaitRespResponse(frame, requestId));
            return;
        case kXR_redirect:
            LOGGER.trace("Decoder {}, channel {}: adding redirect response.", sourceUrn, id);
            out.add(new InboundRedirectResponse(frame, requestId));
            return;
        case kXR_attn:
            LOGGER.trace("Decoder {}, channel {}: adding attn response.", sourceUrn, id);
            out.add(new InboundAttnResponse(frame, requestId));
            return;
        }

        switch (requestId) {
        case kXR_handshake:
            LOGGER.trace("Decoder {}, channel {}: adding handshake response.", sourceUrn, id);
            out.add(new InboundHandshakeResponse(frame));
            break;
        case kXR_protocol:
            LOGGER.trace("Decoder {}, channel {}: adding protocol response.", sourceUrn, id);
            out.add(new InboundProtocolResponse(frame));
            break;
        case kXR_login:
            LOGGER.trace("Decoder {}, channel {}: adding login response.", sourceUrn, id);
            out.add(new InboundLoginResponse(frame));
            break;
        case kXR_auth:
            LOGGER.trace("Decoder {}, channel {}: adding authentication response.", sourceUrn, id);
            out.add(new InboundAuthenticationResponse(frame));
            break;
        case kXR_open:
            LOGGER.trace("Decoder {}, channel {}: adding open response.", sourceUrn, id);
            out.add(new InboundOpenReadOnlyResponse(frame));
            break;
        case kXR_read:
            LOGGER.trace("Decoder {}, channel {}: adding read response.", sourceUrn, id);
            out.add(new InboundReadResponse(frame));
            break;
        case kXR_query:
            LOGGER.trace("Decoder {}, channel {}: adding query response.", sourceUrn, id);
            out.add(new InboundChecksumResponse(frame));
            break;
        case kXR_close:
            LOGGER.trace("Decoder {}, channel {}: adding close response.", sourceUrn, id);
            out.add(new InboundCloseResponse(frame));
            break;
        case kXR_endsess:
            LOGGER.trace("Decoder {}, channel {}: adding endsess response.", sourceUrn, id);
            out.add(new InboundEndSessionResponse(frame));
            break;
        default:
            LOGGER.trace("Decoder {}, channel {}, received incorrect " + "response of request type {}.",
                    sourceUrn, id, requestId);
            throw new XrootdException(kXR_error, "received incorrect response type.");
        }
    } catch (ParseException | XrootdException e) {
        LOGGER.error("Decoder {}, channel {}: error for request type {}: {}. " + "Closing channel.", requestId,
                id, e.getMessage());
        client.setError(e);
        try {
            client.shutDown(ctx);
        } catch (InterruptedException e1) {
            LOGGER.warn("client shutdown interrupted.");
        }
    }
}

From source file:org.eclipse.milo.opcua.stack.client.transport.uasc.UascClientAcknowledgeHandler.java

License:Open Source License

@Override
protected void decode(ChannelHandlerContext ctx, ByteBuf buffer, List<Object> out) throws Exception {
    int maxChunkSize = config.getMessageLimits().getMaxChunkSize();

    while (buffer.readableBytes() >= HEADER_LENGTH) {
        int messageLength = getMessageLength(buffer, maxChunkSize);

        if (buffer.readableBytes() < messageLength) {
            break;
        }//from  w  w w  . j a  v  a2 s .  c om

        MessageType messageType = MessageType.fromMediumInt(buffer.getMediumLE(buffer.readerIndex()));

        switch (messageType) {
        case Acknowledge:
            onAcknowledge(ctx, buffer.readSlice(messageLength));
            break;

        case Error:
            onError(ctx, buffer.readSlice(messageLength));
            break;

        default:
            out.add(buffer.readSlice(messageLength).retain());
        }
    }
}

From source file:org.eclipse.milo.opcua.stack.client.transport.uasc.UascClientMessageHandler.java

License:Open Source License

private void decodeMessage(ChannelHandlerContext ctx, ByteBuf buffer) throws UaException {
    int messageLength = getMessageLength(buffer, maxChunkSize);
    MessageType messageType = MessageType.fromMediumInt(buffer.getMediumLE(buffer.readerIndex()));

    switch (messageType) {
    case OpenSecureChannel:
        onOpenSecureChannel(ctx, buffer.readSlice(messageLength));
        break;/* w ww. ja  v  a  2s . c  o m*/

    case SecureMessage:
        onSecureMessage(ctx, buffer.readSlice(messageLength));
        break;

    case Error:
        onError(ctx, buffer.readSlice(messageLength));
        break;

    default:
        throw new UaException(StatusCodes.Bad_TcpMessageTypeInvalid, "unexpected MessageType: " + messageType);
    }
}

From source file:org.eclipse.milo.opcua.stack.server.transport.uasc.UascServerAsymmetricHandler.java

License:Open Source License

@Override
protected void decode(ChannelHandlerContext ctx, ByteBuf buffer, List<Object> out) throws Exception {
    while (buffer.readableBytes() >= HEADER_LENGTH) {
        int messageLength = getMessageLength(buffer, maxChunkSize);

        if (buffer.readableBytes() < messageLength) {
            break;
        }/*from  w ww.  jav a 2s.  co  m*/

        MessageType messageType = MessageType.fromMediumInt(buffer.getMediumLE(buffer.readerIndex()));

        switch (messageType) {
        case OpenSecureChannel:
            onOpenSecureChannel(ctx, buffer.readSlice(messageLength));
            break;

        case CloseSecureChannel:
            logger.debug("Received CloseSecureChannelRequest");

            buffer.skipBytes(messageLength);

            if (secureChannelTimeout != null) {
                secureChannelTimeout.cancel();
                secureChannelTimeout = null;
            }

            ctx.close();
            break;

        default:
            throw new UaException(StatusCodes.Bad_TcpMessageTypeInvalid,
                    "unexpected MessageType: " + messageType);
        }
    }
}

From source file:org.eclipse.milo.opcua.stack.server.transport.uasc.UascServerHelloHandler.java

License:Open Source License

@Override
protected void decode(ChannelHandlerContext ctx, ByteBuf buffer, List<Object> out) throws Exception {
    while (buffer.readableBytes() >= HEADER_LENGTH) {
        int messageLength = getMessageLength(buffer, MAX_HELLO_MESSAGE_SIZE);

        if (buffer.readableBytes() < messageLength) {
            break;
        }//www .ja v a 2s .  c om

        MessageType messageType = MessageType.fromMediumInt(buffer.getMediumLE(buffer.readerIndex()));

        switch (messageType) {
        case Hello:
            onHello(ctx, buffer.readSlice(messageLength));
            break;

        default:
            throw new UaException(StatusCodes.Bad_TcpMessageTypeInvalid,
                    "unexpected MessageType: " + messageType);
        }
    }
}

From source file:org.eclipse.milo.opcua.stack.server.transport.uasc.UascServerSymmetricHandler.java

License:Open Source License

@Override
protected void decode(ChannelHandlerContext ctx, ByteBuf buffer, List<Object> out) throws Exception {
    while (buffer.readableBytes() >= HEADER_LENGTH) {
        int messageLength = getMessageLength(buffer, maxChunkSize);

        if (buffer.readableBytes() < messageLength) {
            break;
        }//from  w  w  w. ja  va 2 s.c  om

        MessageType messageType = MessageType.fromMediumInt(buffer.getMediumLE(buffer.readerIndex()));

        switch (messageType) {
        case SecureMessage:
            onSecureMessage(ctx, buffer.readSlice(messageLength));
            break;

        default:
            out.add(buffer.readSlice(messageLength).retain());
        }
    }
}

From source file:org.eclipse.neoscada.protocol.iec60870.apci.APDUDecoder.java

License:Open Source License

@Override
protected void decode(final ChannelHandlerContext ctx, final ByteBuf in, final List<Object> out)
        throws Exception {
    if (logger.isTraceEnabled()) {
        logger.trace("decode - bytes: {}", ByteBufUtil.hexDump(in));
    }/*ww  w . jav  a 2 s .  c om*/

    if (in.readableBytes() < Constants.APCI_MIN_LENGTH) {
        return;
    }

    final byte start = in.getByte(in.readerIndex() + 0);
    if (start != Constants.START_BYTE) {
        throw new DecoderException(
                String.format("ACPI must start with 0x%02x but did with 0x%02x", Constants.START_BYTE, start));
    }

    final short len = in.getUnsignedByte(in.readerIndex() + 1);

    if (len > Constants.APCI_MAX_DATA_LENGTH) {
        throw new DecoderException(String.format("APCI has a maximum length of %s bytes, but we received %s",
                Constants.APCI_MAX_DATA_LENGTH, len));
    }

    if (in.readableBytes() < len + 2) {
        return;
    }

    // we have the full InformationTransfer

    // skip start & len
    in.skipBytes(2);

    // read control fields
    final ByteBuf controlFields = in.readSlice(4);

    final ByteBuf data;
    if (len > 4) {
        data = Unpooled.copiedBuffer(in.readSlice(len - 4)).order(ByteOrder.LITTLE_ENDIAN);
    } else {
        data = null;
    }

    // now add the PDU

    out.add(decode(controlFields, data));
}

From source file:org.eclipse.scada.protocol.syslog.SyslogCodec.java

License:Open Source License

private String[] decodeProcess(final ByteBuf msg) {
    // split by colon
    final int spaceIndex = msg.bytesBefore(COLON);
    if (spaceIndex < 0) {
        throw new CodecException("Unable to find process name");
    }/*  w w w  .  j  ava  2s  .  c  o m*/

    final String process = msg.readSlice(spaceIndex).toString(StandardCharsets.US_ASCII);
    msg.skipBytes(1); // COLON
    if (msg.isReadable()) {
        msg.skipBytes(1); // SPACE
    }

    final Matcher m = PROCESS_PATTERN.matcher(process);
    if (m.matches()) {
        return new String[] { m.group(1), m.group(2) };
    }

    return new String[] { process };
}

From source file:org.eclipse.scada.protocol.syslog.SyslogCodec.java

License:Open Source License

private String decodeHostname(final ByteBuf msg) {
    // split by first space
    final int spaceIndex = msg.bytesBefore(Constants.SP);
    if (spaceIndex < 0) {
        throw new CodecException("Unable to find hostname");
    }/* ww w .j  a  v a  2  s.  c  o  m*/

    final String hostname = msg.readSlice(spaceIndex).toString(StandardCharsets.US_ASCII);

    msg.skipBytes(1); // SPACE

    return hostname;
}