Example usage for io.netty.util Attribute get

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

Introduction

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

Prototype

T get();

Source Link

Document

Returns the current value, which may be null

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  w  w  .j av  a2  s. c o  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:at.yawk.dbus.protocol.codec.Local.java

/**
 * Generate a serial for the given channel.
 *//*from  w w  w.  jav  a2s . co  m*/
static int generateSerial(ChannelHandlerContext ctx) {
    int serial;
    Attribute<Integer> attr = ctx.attr(LAST_SERIAL);
    Integer lastSerial;
    do {
        lastSerial = attr.get();
        serial = (lastSerial == null ? 0 : lastSerial) + 1;
        if (serial == 0) {
            serial = 1;
        }
    } while (!attr.compareAndSet(lastSerial, serial));
    return serial;
}

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 w ww.ja va 2 s.co  m*/
        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();//w  w w .  j a v  a2s .  co 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.dempe.chat.common.mqtt.codec.Utils.java

License:Open Source License

static boolean isMQTT3_1_1(AttributeMap attrsMap) {
    Attribute<Integer> versionAttr = attrsMap.attr(MQTTDecoder.PROTOCOL_VERSION);
    Integer protocolVersion = versionAttr.get();
    if (protocolVersion == null) {
        return true;
    }/* ww  w  .j av a 2s. c  om*/
    return protocolVersion == VERSION_3_1_1;
}

From source file:com.dempe.chat.connector.NettyUtils.java

License:Open Source License

public static Object getAttribute(ChannelHandlerContext ctx, AttributeKey<Object> key) {
    Attribute<Object> attr = ctx.channel().attr(key);
    return attr.get();
}

From source file:com.dinstone.rpc.netty.client.SessionUtil.java

License:Apache License

@SuppressWarnings("unchecked")
public static Map<Integer, CallFuture> getCallFutureMap(Channel session) {
    Attribute<Object> attr = session.attr(CALL_KEY);
    Map<Integer, CallFuture> cfMap = (Map<Integer, CallFuture>) attr.get();
    if (cfMap == null) {
        cfMap = new ConcurrentHashMap<Integer, CallFuture>();
        if (!attr.compareAndSet(null, cfMap)) {
            cfMap = (Map<Integer, CallFuture>) attr.get();
        }/*from   www  . j ava  2s. c o m*/
    }

    return cfMap;
}

From source file:com.ebay.jetstream.http.netty.server.KeepAliveHandler.java

License:MIT License

@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
    Attribute<AtomicInteger> attr = ctx.attr(REQUEST_COUNT);
    if (attr.get() == null) {
        attr.setIfAbsent(new AtomicInteger());
    }//from  w  ww .  j  a v a 2  s .  c o m
    attr.get().incrementAndGet();
    ctx.fireChannelRead(msg);
}

From source file:com.ebay.jetstream.messaging.transport.netty.compression.MessageCompressionHandler.java

License:MIT License

/**
 * Invoked when {@link Channel#write(Object)} is called.
 *///from ww  w.  jav  a2 s.com
public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception {

    try {

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

        Boolean enableCompression = attr.get();

        if ((enableCompression != null) && (enableCompression == true)) {

            ByteBuf chbuf = (ByteBuf) msg;

            int msglen = chbuf.readableBytes();
            ExtendedChannelPromise epromise = (ExtendedChannelPromise) promise;
            epromise.setRawBytes(msglen);

            byte[] compressed = Snappy.rawCompress(chbuf.readBytes(msglen).array(), msglen);

            epromise.setCompressedBytes(compressed.length + 4);
            chbuf.release(); // need to release the original buffer - do I need to check if this this a ref counted buffer

            ByteBuf sendbuf = ctx.alloc().buffer();

            sendbuf.writeInt(compressed.length);
            sendbuf.writeBytes(compressed);

            ctx.write(sendbuf, promise);

            m_totalMessagesCompressed.increment();

        } else {

            ctx.write(msg, promise);

        }

    } catch (Throwable t) {
        m_totalMessagesDropped.increment();
        LOGGER.debug("Failed to compress message - " + t.getLocalizedMessage());

    }

}

From source file:com.ebay.jetstream.messaging.transport.netty.serializer.KryoObjectEncoder.java

License:MIT License

@Override
public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception {

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

    Boolean enableKryo = attr.get();

    if ((enableKryo != null) && (enableKryo == true))
        super.write(ctx, msg, promise);
    else/*from w  ww . j  a va  2s.c  o m*/
        ctx.write(msg, promise);

}