Example usage for io.netty.util Attribute set

List of usage examples for io.netty.util Attribute set

Introduction

In this page you can find the example usage for io.netty.util Attribute set.

Prototype

void set(T value);

Source Link

Document

Sets the value

Usage

From source file:at.yawk.dbus.protocol.codec.IncomingMessageAdapter.java

@Override
protected void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception {
    Attribute<MessageHeader> headerAttribute = ctx.channel().attr(Local.CURRENT_HEADER);
    if (msg instanceof MessageHeader) {
        if (((MessageHeader) msg).getMessageBodyLength() == 0) {
            DbusMessage message = new DbusMessage();
            message.setHeader((MessageHeader) msg);
            consumer.accept(message);/*w  ww .java  2s  .  co m*/
        } else {
            if (consumer.requireAccept((MessageHeader) msg)) {
                headerAttribute.set((MessageHeader) msg);
            } else {
                headerAttribute.set(null);
            }
        }
    } else if (msg instanceof MessageBody) {
        MessageHeader header = headerAttribute.get();
        if (header != null) {
            DbusMessage message = new DbusMessage();
            message.setHeader(header);
            message.setBody((MessageBody) msg);
            consumer.accept(message);
            headerAttribute.set(null);
        }
    } else {
        log.warn("Did not handle {}", msg);
    }
}

From source file:com.couchbase.client.core.endpoint.dcp.DCPConnection.java

License:Apache License

void consumed(short partition, int delta) {
    if (env.dcpConnectionBufferSize() > 0) {
        ChannelHandlerContext ctx = contexts.get(partition);
        if (ctx == null) {
            return;
        }/*from   ww w . java 2  s. c om*/
        synchronized (ctx) {
            Attribute<Integer> attr = ctx.attr(CONSUMED_BYTES);
            Integer consumedBytes = attr.get();
            if (consumedBytes == null) {
                consumedBytes = 0;
            }
            consumedBytes += MINIMUM_HEADER_SIZE + delta;
            if (consumedBytes >= env.dcpConnectionBufferSize() * env.dcpConnectionBufferAckThreshold()) {
                ctx.writeAndFlush(createBufferAcknowledgmentRequest(ctx, consumedBytes));
                consumedBytes = 0;
            }
            attr.set(consumedBytes);
        }
    }
}

From source file:com.dempe.chat.common.mqtt.codec.ConnectDecoder.java

License:Open Source License

@Override
void decode(AttributeMap ctx, ByteBuf in, List<Object> out) throws UnsupportedEncodingException {
    in.resetReaderIndex();/*from   w  w  w  .  j  a v a 2s  . c o  m*/
    //Common decoding part
    ConnectMessage message = new ConnectMessage();
    if (!decodeCommonHeader(message, 0x00, in)) {
        in.resetReaderIndex();
        return;
    }
    int remainingLength = message.getRemainingLength();
    int start = in.readerIndex();

    int protocolNameLen = in.readUnsignedShort();
    byte[] encProtoName;
    String protoName;
    Attribute<Integer> versionAttr = ctx.attr(MQTTDecoder.PROTOCOL_VERSION);
    switch (protocolNameLen) {
    case 6:
        //MQTT version 3.1 "MQIsdp"
        //ProtocolName 8 bytes or 6 bytes
        if (in.readableBytes() < 10) {
            in.resetReaderIndex();
            return;
        }

        encProtoName = new byte[6];
        in.readBytes(encProtoName);
        protoName = new String(encProtoName, "UTF-8");
        if (!"MQIsdp".equals(protoName)) {
            in.resetReaderIndex();
            throw new CorruptedFrameException("Invalid protoName: " + protoName);
        }
        message.setProtocolName(protoName);

        versionAttr.set((int) Utils.VERSION_3_1);
        break;
    case 4:
        //MQTT version 3.1.1 "MQTT"
        //ProtocolName 6 bytes
        if (in.readableBytes() < 8) {
            in.resetReaderIndex();
            return;
        }
        encProtoName = new byte[4];
        in.readBytes(encProtoName);
        protoName = new String(encProtoName, "UTF-8");
        if (!"MQTT".equals(protoName)) {
            in.resetReaderIndex();
            throw new CorruptedFrameException("Invalid protoName: " + protoName);
        }
        message.setProtocolName(protoName);
        versionAttr.set((int) Utils.VERSION_3_1_1);
        break;
    default:
        //protocol broken
        throw new CorruptedFrameException("Invalid protoName size: " + protocolNameLen);
    }

    //ProtocolVersion 1 byte (value 0x03 for 3.1, 0x04 for 3.1.1)
    message.setProtocolVersion(in.readByte());
    if (message.getProtocolVersion() == Utils.VERSION_3_1_1) {
        //if 3.1.1, check the flags (dup, retain and qos == 0)
        if (message.isDupFlag() || message.isRetainFlag()
                || message.getQos() != AbstractMessage.QOSType.MOST_ONE) {
            throw new CorruptedFrameException("Received a CONNECT with fixed header flags != 0");
        }

        //check if this is another connect from the same client on the same session
        Attribute<Boolean> connectAttr = ctx.attr(ConnectDecoder.CONNECT_STATUS);
        Boolean alreadyConnected = connectAttr.get();
        if (alreadyConnected == null) {
            //never set
            connectAttr.set(true);
        } else if (alreadyConnected) {
            throw new CorruptedFrameException("Received a second CONNECT on the same network connection");
        }
    }

    //Connection flag
    byte connFlags = in.readByte();
    if (message.getProtocolVersion() == Utils.VERSION_3_1_1) {
        if ((connFlags & 0x01) != 0) { //bit(0) of connection flags is != 0
            throw new CorruptedFrameException("Received a CONNECT with connectionFlags[0(bit)] != 0");
        }
    }

    boolean cleanSession = ((connFlags & 0x02) >> 1) == 1;
    boolean willFlag = ((connFlags & 0x04) >> 2) == 1;
    byte willQos = (byte) ((connFlags & 0x18) >> 3);
    if (willQos > 2) {
        in.resetReaderIndex();
        throw new CorruptedFrameException("Expected will QoS in range 0..2 but found: " + willQos);
    }
    boolean willRetain = ((connFlags & 0x20) >> 5) == 1;
    boolean passwordFlag = ((connFlags & 0x40) >> 6) == 1;
    boolean userFlag = ((connFlags & 0x80) >> 7) == 1;
    //a password is true iff user is true.
    if (!userFlag && passwordFlag) {
        in.resetReaderIndex();
        throw new CorruptedFrameException(
                "Expected password flag to true if the user flag is true but was: " + passwordFlag);
    }
    message.setCleanSession(cleanSession);
    message.setWillFlag(willFlag);
    message.setWillQos(willQos);
    message.setWillRetain(willRetain);
    message.setPasswordFlag(passwordFlag);
    message.setUserFlag(userFlag);

    //Keep Alive timer 2 bytes
    //int keepAlive = Utils.readWord(in);
    int keepAlive = in.readUnsignedShort();
    message.setKeepAlive(keepAlive);

    if ((remainingLength == 12 && message.getProtocolVersion() == Utils.VERSION_3_1)
            || (remainingLength == 10 && message.getProtocolVersion() == Utils.VERSION_3_1_1)) {
        out.add(message);
        return;
    }

    //Decode the ClientID
    String clientID = Utils.decodeString(in);
    if (clientID == null) {
        in.resetReaderIndex();
        return;
    }
    message.setClientID(clientID);

    //Decode willTopic
    if (willFlag) {
        String willTopic = Utils.decodeString(in);
        if (willTopic == null) {
            in.resetReaderIndex();
            return;
        }
        message.setWillTopic(willTopic);
    }

    //Decode willMessage
    if (willFlag) {
        byte[] willMessage = Utils.readFixedLengthContent(in);
        if (willMessage == null) {
            in.resetReaderIndex();
            return;
        }
        message.setWillMessage(willMessage);
    }

    //Compatibility check with v3.0, remaining length has precedence over
    //the user and password flags
    int readed = in.readerIndex() - start;
    if (readed == remainingLength) {
        out.add(message);
        return;
    }

    //Decode username
    if (userFlag) {
        String userName = Utils.decodeString(in);
        if (userName == null) {
            in.resetReaderIndex();
            return;
        }
        message.setUsername(userName);
    }

    readed = in.readerIndex() - start;
    if (readed == remainingLength) {
        out.add(message);
        return;
    }

    //Decode password
    if (passwordFlag) {
        byte[] password = Utils.readFixedLengthContent(in);
        if (password == null) {
            in.resetReaderIndex();
            return;
        }
        message.setPassword(password);
    }

    out.add(message);
}

From source file:com.ebay.jetstream.messaging.transport.netty.eventproducer.EventProducer.java

License:MIT License

/**
 * write the event object to the MINA IoSession. In the process create a
 * DispatchId and add it to the IoSession object. The Dispatchid is used as
 * a key to store the event object in the sent message bucket. The event
 * object will remain in the bucket till the Mina layer calls back and
 * informs us that either there has been an error or the event was
 * successfully dispatched to the remote consumer.
 * //from  w w  w  .j a v  a2s.  co  m
 * @param session
 * @param obj
 */

private void dispatch(EventConsumerInfo info, JetstreamMessage msg) {

    ConsumerChannelContext ccc = info.getNextChannelContext(); // added for trunking

    Channel channel;

    if (ccc == null) {
        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug("session is null for host - " + info.getAdvertisement().getHostName());
        }

        // now take out this consumer from event topic registry

        if (!m_transportConfig.isAsyncConnect()) {
            try {
                channel = activateEventConsumerSession(info, m_transportConfig.isAsyncConnect(),
                        m_transportConfig.getConnectionPoolSz());

                ccc = info.getNextChannelContext();

            } catch (Exception e) {
                printSevere("Failed to connect to host - " + info.getAdvertisement().getHostName());
                m_deadConsumerQueue.offer(info);

                if (m_advisoryListener != null) {
                    postResendAdvisory(msg);
                    m_noConsumerAdvisories.increment();
                } else {
                    m_dropsForNoConsumer.increment();
                    m_totalMsgsDropped.increment();
                }
                return;

            }
        } else {

            // if we are here we could have missed catching a channel that is disconnected.
            // let us reinsert the event in to downstream queue after decrement the TTL.

            if (msg.decTTL() > 0) {
                SendEventRequest ser = new SendEventRequest(this, msg);
                if (!m_dataQueue.offer(ser)) {
                    if (m_advisoryListener != null) {
                        postResendAdvisory(msg);
                        m_noConsumerAdvisories.increment();
                    } else {
                        m_totalMsgsDropped.increment();
                        m_dropsForNoConsumer.increment();
                    }
                }
            } else {
                if (m_advisoryListener != null) {
                    postResendAdvisory(msg);
                    m_noConsumerAdvisories.increment();
                } else {
                    m_totalMsgsDropped.increment();
                    m_dropsForNoConsumer.increment();
                }
            }
            return;
        }

    } else
        channel = ccc.getChannel();

    if (msg.getSequenceId() < 0) {
        msg.setSequenceId(info.getSeqid(msg.getTopic()));
    }

    String remoteHost = ((InetSocketAddress) channel.remoteAddress()).getHostName();
    if ((remoteHost.equals(m_hostName) || remoteHost.equals("127.0.0.1"))
            && m_nt.isListeningToPort(((InetSocketAddress) channel.remoteAddress()).getPort())) {
        try {

            if (m_ec != null)
                m_ec.receive(msg);
            else
                m_messageServiceProxy.postMessage(msg, m_queueStats);
            m_avgMsgsSentPerSec.increment();
            m_totalMsgsSent.increment();
            return;

        } catch (MessageServiceException e) {
            if (LOGGER.isDebugEnabled())
                LOGGER.debug("Failed to dispath upstream" + e.getLocalizedMessage());
            if (m_advisoryListener != null) {
                postResendAdvisory(msg);
            } else {
                m_totalMsgsDropped.increment();

            }

        }
    }

    if (!channel.isActive()) {
        removeSession(ccc);
        tryResendMessage(msg);
        return;

    }

    if (LOGGER.isDebugEnabled())
        LOGGER.debug(msg.toString());

    EventConsumerChannelFuture promise = new EventConsumerChannelFuture(channel, ccc.getVirtualQueueMonitor());

    promise.setconsumerChannelContext(ccc);

    promise.setMessage(msg); // we need to add the message to the future so
    // we can reschedule the message in case of
    // failure. Look at operationComplete()
    // to see how we handle this.

    //set compression flag based on consumer advertisement 
    if (info.getAdvertisement().isCompressionEnabled()) {

        promise.setCompressionEnabled(true);

        Attribute<Boolean> attrVal = channel.attr(m_eckey);

        attrVal.set(promise.isCompressionEnabled());

    }

    if (info.getAdvertisement().isKryoSerializationEnabled()) {

        Attribute<Boolean> attrVal = channel.attr(m_kskey);

        attrVal.set(true);
    } else {
        Attribute<Boolean> attrVal = channel.attr(m_kskey);

        attrVal.set(false);
    }

    // check if the socket is backing up - if it is we will add the event to over flow buffer - if that is also full we will drop the event
    // and post advice. Otherwise we will hit OOM errors very quickly as
    // events will start accumulating in netty queues.

    if (!ccc.getVirtualQueueMonitor().isQueueFull()) {

        promise.addListener(this);

        if (m_transportConfig.getAutoFlushSz() == 0)
            channel.writeAndFlush(msg, promise);
        else
            channel.write(msg, promise);

        ccc.getVirtualQueueMonitor().increment();

    } else {
        if (m_advisoryListener != null) {
            postResendAdvisory(msg);
            m_vqOverflowAdvisories.increment();
        } else {
            m_totalMsgsDropped.increment();
            m_dropsForVQOverflow.increment();
        }
    }

    if (LOGGER.isDebugEnabled())
        LOGGER.debug("netty queue backlog = " + ccc.getVirtualQueueMonitor().getQueueBackLog());

}

From source file:com.github.netfreer.shadowducks.client.handler.SocksServerConnectHandler.java

License:Apache License

@Override
public void channelRead0(final ChannelHandlerContext ctx, final SocksMessage message) throws Exception {
    if (message instanceof Socks4CommandRequest) {
        final Socks4CommandRequest request = (Socks4CommandRequest) message;
        Promise<Channel> promise = ctx.executor().newPromise();
        promise.addListener(new FutureListener<Channel>() {
            @Override//from  w  ww. j a  v a2 s.  c  o  m
            public void operationComplete(final Future<Channel> future) throws Exception {
                final Channel outboundChannel = future.getNow();
                if (future.isSuccess()) {
                    ChannelFuture responseFuture = ctx.channel()
                            .writeAndFlush(new DefaultSocks4CommandResponse(Socks4CommandStatus.SUCCESS));

                    responseFuture.addListener(new ChannelFutureListener() {
                        @Override
                        public void operationComplete(ChannelFuture channelFuture) {
                            ctx.pipeline().remove(SocksServerConnectHandler.this);
                            outboundChannel.pipeline().addLast(new RelayHandler(ctx.channel()));
                            ctx.pipeline().addLast(new RelayHandler(outboundChannel));
                        }
                    });
                } else {
                    ctx.channel().writeAndFlush(
                            new DefaultSocks4CommandResponse(Socks4CommandStatus.REJECTED_OR_FAILED));
                    SocksServerUtils.closeOnFlush(ctx.channel());
                }
            }
        });

        final Channel inboundChannel = ctx.channel();
        b.group(inboundChannel.eventLoop()).channel(NioSocketChannel.class)
                .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 10000).option(ChannelOption.SO_KEEPALIVE, true)
                .handler(new DirectClientHandler(promise));

        b.connect(request.dstAddr(), request.dstPort()).addListener(new ChannelFutureListener() {
            @Override
            public void operationComplete(ChannelFuture future) throws Exception {
                if (future.isSuccess()) {
                    // Connection established use handler provided results
                } else {
                    // Close the connection if the connection attempt has failed.
                    ctx.channel().writeAndFlush(
                            new DefaultSocks4CommandResponse(Socks4CommandStatus.REJECTED_OR_FAILED));
                    SocksServerUtils.closeOnFlush(ctx.channel());
                }
            }
        });
    } else if (message instanceof Socks5CommandRequest) {
        final Socks5CommandRequest request = (Socks5CommandRequest) message;
        Promise<Channel> promise = ctx.executor().newPromise();
        promise.addListener(new FutureListener<Channel>() {
            @Override
            public void operationComplete(final Future<Channel> future) throws Exception {
                final Channel outboundChannel = future.getNow();
                if (future.isSuccess()) {
                    ChannelFuture responseFuture = ctx.channel()
                            .writeAndFlush(new DefaultSocks5CommandResponse(Socks5CommandStatus.SUCCESS,
                                    request.dstAddrType(), request.dstAddr(), request.dstPort()));

                    responseFuture.addListener(new ChannelFutureListener() {
                        @Override
                        public void operationComplete(ChannelFuture channelFuture) {
                            ctx.pipeline().remove(SocksServerConnectHandler.this);
                            outboundChannel.pipeline().addLast(new RelayHandler(ctx.channel()));
                            ctx.pipeline().addLast(new RelayHandler(outboundChannel));
                        }
                    });
                } else {
                    ctx.channel().writeAndFlush(new DefaultSocks5CommandResponse(Socks5CommandStatus.FAILURE,
                            request.dstAddrType()));
                    SocksServerUtils.closeOnFlush(ctx.channel());
                }
            }
        });

        final Channel inboundChannel = ctx.channel();
        b.group(inboundChannel.eventLoop()).channel(NioSocketChannel.class)
                .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 10000).option(ChannelOption.SO_KEEPALIVE, true)
                .handler(new DirectClientHandler(promise));
        b.connect(request.dstAddr(), request.dstPort()).addListener(new ChannelFutureListener() {
            @Override
            public void operationComplete(ChannelFuture future) throws Exception {
                Attribute<Long> beginTimeAttr = ctx.channel().attr(AttrKeys.CHANNEL_BEGIN_TIME);
                final long parseTime = beginTimeAttr.get();
                long usedTime = System.currentTimeMillis() - parseTime;
                if (future.isSuccess()) {
                    // Connection established use handler provided results
                    logger.info("connect {}:{} success, use time {} millis.", request.dstAddr(),
                            request.dstPort(), usedTime);
                } else {
                    // Close the connection if the connection attempt has failed.
                    ctx.channel().writeAndFlush(new DefaultSocks5CommandResponse(Socks5CommandStatus.FAILURE,
                            request.dstAddrType()));
                    SocksServerUtils.closeOnFlush(ctx.channel());
                    logger.info("connect {}:{} failure, use time {} millis.", request.dstAddr(),
                            request.dstPort(), usedTime);
                }
                beginTimeAttr.set(null);
            }
        });
    } else {
        ctx.close();
    }
}

From source file:com.github.sylvek.wsmqttfwd.decoder.ConnectDecoder.java

License:Open Source License

@Override
public ConnectMessage decode(AttributeMap ctx, ByteBuf in) throws UnsupportedEncodingException {
    in.resetReaderIndex();/*w ww .j a va2s  .c  om*/
    //Common decoding part
    ConnectMessage message = new ConnectMessage();
    if (!decodeCommonHeader(message, 0x00, in)) {
        in.resetReaderIndex();
        return null;
    }
    int remainingLength = message.getRemainingLength();
    int start = in.readerIndex();

    int protocolNameLen = in.readUnsignedShort();
    byte[] encProtoName;
    String protoName;
    Attribute<Integer> versionAttr = ctx.attr(PROTOCOL_VERSION);
    switch (protocolNameLen) {
    case 6:
        //MQTT version 3.1 "MQIsdp"
        //ProtocolName 8 bytes or 6 bytes
        if (in.readableBytes() < 10) {
            in.resetReaderIndex();
            return null;
        }

        encProtoName = new byte[6];
        in.readBytes(encProtoName);
        protoName = new String(encProtoName, "UTF-8");
        if (!"MQIsdp".equals(protoName)) {
            in.resetReaderIndex();
            throw new CorruptedFrameException("Invalid protoName: " + protoName);
        }
        message.setProtocolName(protoName);

        versionAttr.set((int) Utils.VERSION_3_1);
        break;
    case 4:
        //MQTT version 3.1.1 "MQTT"
        //ProtocolName 6 bytes
        if (in.readableBytes() < 8) {
            in.resetReaderIndex();
            return null;
        }
        encProtoName = new byte[4];
        in.readBytes(encProtoName);
        protoName = new String(encProtoName, "UTF-8");
        if (!"MQTT".equals(protoName)) {
            in.resetReaderIndex();
            throw new CorruptedFrameException("Invalid protoName: " + protoName);
        }
        message.setProtocolName(protoName);
        versionAttr.set((int) Utils.VERSION_3_1_1);
        break;
    default:
        //protocol broken
        throw new CorruptedFrameException("Invalid protoName size: " + protocolNameLen);
    }

    //ProtocolVersion 1 byte (value 0x03 for 3.1, 0x04 for 3.1.1)
    message.setProtocolVersion(in.readByte());
    if (message.getProtocolVersion() == Utils.VERSION_3_1_1) {
        //if 3.1.1, check the flags (dup, retain and qos == 0)
        if (message.isDupFlag() || message.isRetainFlag()
                || message.getQos() != AbstractMessage.QOSType.MOST_ONE) {
            throw new CorruptedFrameException("Received a CONNECT with fixed header flags != 0");
        }

        //check if this is another connect from the same client on the same session
        Attribute<Boolean> connectAttr = ctx.attr(ConnectDecoder.CONNECT_STATUS);
        Boolean alreadyConnected = connectAttr.get();
        if (alreadyConnected == null) {
            //never set
            connectAttr.set(true);
        } else if (alreadyConnected) {
            throw new CorruptedFrameException("Received a second CONNECT on the same network connection");
        }
    }

    //Connection flag
    byte connFlags = in.readByte();
    if (message.getProtocolVersion() == Utils.VERSION_3_1_1) {
        if ((connFlags & 0x01) != 0) { //bit(0) of connection flags is != 0
            throw new CorruptedFrameException("Received a CONNECT with connectionFlags[0(bit)] != 0");
        }
    }

    boolean cleanSession = ((connFlags & 0x02) >> 1) == 1;
    boolean willFlag = ((connFlags & 0x04) >> 2) == 1;
    byte willQos = (byte) ((connFlags & 0x18) >> 3);
    if (willQos > 2) {
        in.resetReaderIndex();
        throw new CorruptedFrameException("Expected will QoS in range 0..2 but found: " + willQos);
    }
    boolean willRetain = ((connFlags & 0x20) >> 5) == 1;
    boolean passwordFlag = ((connFlags & 0x40) >> 6) == 1;
    boolean userFlag = ((connFlags & 0x80) >> 7) == 1;
    //a password is true iff user is true.
    if (!userFlag && passwordFlag) {
        in.resetReaderIndex();
        throw new CorruptedFrameException(
                "Expected password flag to true if the user flag is true but was: " + passwordFlag);
    }
    message.setCleanSession(cleanSession);
    message.setWillFlag(willFlag);
    message.setWillQos(willQos);
    message.setWillRetain(willRetain);
    message.setPasswordFlag(passwordFlag);
    message.setUserFlag(userFlag);

    //Keep Alive timer 2 bytes
    //int keepAlive = Utils.readWord(in);
    int keepAlive = in.readUnsignedShort();
    message.setKeepAlive(keepAlive);

    if ((remainingLength == 12 && message.getProtocolVersion() == Utils.VERSION_3_1)
            || (remainingLength == 10 && message.getProtocolVersion() == Utils.VERSION_3_1_1)) {
        return message;
    }

    //Decode the ClientID
    String clientID = Utils.decodeString(in);
    if (clientID == null) {
        in.resetReaderIndex();
        return null;
    }
    message.setClientID(clientID);

    //Decode willTopic
    if (willFlag) {
        String willTopic = Utils.decodeString(in);
        if (willTopic == null) {
            in.resetReaderIndex();
            return null;
        }
        message.setWillTopic(willTopic);
    }

    //Decode willMessage
    if (willFlag) {
        byte[] willMessage = Utils.readFixedLengthContent(in);
        if (willMessage == null) {
            in.resetReaderIndex();
            return null;
        }
        message.setWillMessage(willMessage);
    }

    //Compatibility check with v3.0, remaining length has precedence over
    //the user and password flags
    int readed = in.readerIndex() - start;
    if (readed == remainingLength) {
        return message;
    }

    //Decode username
    if (userFlag) {
        String userName = Utils.decodeString(in);
        if (userName == null) {
            in.resetReaderIndex();
            return null;
        }
        message.setUsername(userName);
    }

    readed = in.readerIndex() - start;
    if (readed == remainingLength) {
        return message;
    }

    //Decode password
    if (passwordFlag) {
        byte[] password = Utils.readFixedLengthContent(in);
        if (password == null) {
            in.resetReaderIndex();
            return null;
        }
        message.setPassword(password);
    }

    return message;
}

From source file:com.linecorp.armeria.client.Clients.java

License:Apache License

/**
 * Sets the specified HTTP header manipulating function in a thread-local variable so that the manipulated
 * headers are sent by the client call made from the current thread. Use the `try-with-resources` block
 * with the returned {@link SafeCloseable} to unset the thread-local variable automatically:
 * <pre>{@code/*www.  ja  va2 s . c  om*/
 * import static com.linecorp.armeria.common.HttpHeaderNames.AUTHORIZATION;
 * import static com.linecorp.armeria.common.HttpHeaderNames.USER_AGENT;
 *
 * try (SafeCloseable ignored = withHttpHeaders(headers -> {
 *     headers.set(HttpHeaders.AUTHORIZATION, myCredential)
 *            .set(HttpHeaders.USER_AGENT, myAgent);
 * })) {
 *     client.executeSomething(..);
 * }
 * }</pre>
 * You can also nest the header manipulation:
 * <pre>{@code
 * import static com.linecorp.armeria.common.HttpHeaderNames.AUTHORIZATION;
 * import static com.linecorp.armeria.common.HttpHeaderNames.USER_AGENT;
 *
 * try (SafeCloseable ignored = withHttpHeaders(h -> h.set(USER_AGENT, myAgent))) {
 *     for (String secret : secrets) {
 *         try (SafeCloseable ignored2 = withHttpHeaders(h -> h.set(AUTHORIZATION, secret))) {
 *             // Both USER_AGENT and AUTHORIZATION will be set.
 *             client.executeSomething(..);
 *         }
 *     }
 * }
 * }</pre>
 *
 * @see #withHttpHeader(AsciiString, String)
 */
public static SafeCloseable withHttpHeaders(Function<HttpHeaders, HttpHeaders> headerManipulator) {
    requireNonNull(headerManipulator, "headerManipulator");
    return withContextCustomizer(ctx -> {
        final Attribute<HttpHeaders> attr = ctx.attr(HTTP_HEADERS);
        final HttpHeaders headers = attr.get();
        attr.set(headerManipulator.apply(headers != null ? headers : new DefaultHttpHeaders()));
    });
}

From source file:com.linecorp.armeria.internal.DefaultAttributeMapTest.java

License:Apache License

@Test
public void testSetRemove() {
    AttributeKey<Integer> key = AttributeKey.valueOf("key");

    Attribute<Integer> attr = map.attr(key);
    attr.set(1);
    assertSame(1, attr.getAndRemove());/*from ww w .  jav  a  2 s .  c  o  m*/

    Attribute<Integer> attr2 = map.attr(key);
    attr2.set(2);
    assertSame(2, attr2.get());
    assertNotSame(attr, attr2);
}

From source file:com.linecorp.armeria.internal.DefaultAttributeMapTest.java

License:Apache License

@Test
public void testGetAndSetWithNull() {
    AttributeKey<Integer> key = AttributeKey.valueOf("key");

    Attribute<Integer> attr = map.attr(key);
    attr.set(1);
    assertSame(1, attr.getAndSet(null));

    Attribute<Integer> attr2 = map.attr(key);
    attr2.set(2);// w w  w  . j  a va 2 s  . c o m
    assertSame(2, attr2.get());
    assertSame(attr, attr2);
}

From source file:com.mastfrog.netty.http.client.MessageHandlerImpl.java

License:Open Source License

private ResponseState state(ChannelHandlerContext ctx, RequestInfo info) {
    Attribute<ResponseState> st = ctx.channel().attr(RS);
    ResponseState rs = st.get();/*from  www  .j a v a  2 s  .co  m*/
    if (rs == null) {
        rs = new ResponseState(ctx, info.dontAggregate);
        st.set(rs);
    }
    return rs;
}