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:org.ebayopensource.scc.filter.NettyResponseProxyFilterTest.java

License:Apache License

@Test
public void testFilterFullHttpResponse() {
    PolicyManager policyManager = mock(PolicyManager.class);
    AppConfiguration appConfig = mock(AppConfiguration.class);
    when(appConfig.getBoolean(AppConfiguration.KEY_DEBUG_INFO)).thenReturn(true);

    NettyResponseProxyFilter filter = new NettyResponseProxyFilter(policyManager,
            Executors.newCachedThreadPool());

    ChannelHandlerContext ctx = mock(ChannelHandlerContext.class);
    when(ctx.attr(any(AttributeKey.class))).thenReturn(mock(Attribute.class));
    Attribute cachable = mock(Attribute.class);
    when(ctx.attr(NettyRequestProxyFilter.IS_CACHABLE)).thenReturn(cachable);
    when(cachable.get()).thenReturn(Boolean.FALSE);
    assertNull(filter.filterResponse(null, ctx));

    when(cachable.get()).thenReturn(Boolean.TRUE);
    assertNull(filter.filterResponse(null, ctx));

    HttpResponse resp = mock(HttpResponse.class);
    when(resp.getStatus()).thenReturn(HttpResponseStatus.OK);
    assertEquals(resp, filter.filterResponse(resp, ctx));

    resp = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.NOT_FOUND);
    assertEquals(resp, filter.filterResponse(resp, ctx));

    resp.setStatus(HttpResponseStatus.OK);
    assertEquals(resp, filter.filterResponse(resp, ctx));

    Attribute cacheKey = mock(Attribute.class);
    when(ctx.attr(NettyRequestProxyFilter.CACHE_KEY)).thenReturn(cacheKey);
    when(cacheKey.getAndRemove()).thenReturn("key");
    when(policyManager.getCacheManager()).thenReturn(mock(CacheManager.class));
    assertEquals(resp, filter.filterResponse(resp, ctx));

    when(cacheKey.get()).thenReturn("key");
    assertEquals(resp, filter.filterResponse(resp, ctx));
}

From source file:org.ebayopensource.scc.filter.NettyResponseProxyFilterTest.java

License:Apache License

@Test
public void testFilterChunkeResponses() throws InterruptedException {
    PolicyManager policyManager = mock(PolicyManager.class);
    AppConfiguration appConfig = mock(AppConfiguration.class);
    when(appConfig.getBoolean(AppConfiguration.KEY_DEBUG_INFO)).thenReturn(true);

    ExecutorService tp = Executors.newCachedThreadPool();
    NettyResponseProxyFilter filter = new NettyResponseProxyFilter(policyManager, tp);

    ChannelHandlerContext ctx = mock(ChannelHandlerContext.class);
    when(ctx.attr(any(AttributeKey.class))).thenReturn(mock(Attribute.class));
    Attribute cachable = mock(Attribute.class);
    when(ctx.attr(NettyRequestProxyFilter.IS_CACHABLE)).thenReturn(cachable);
    when(cachable.get()).thenReturn(Boolean.TRUE);

    Attribute cacheKey = mock(Attribute.class);
    when(ctx.attr(NettyRequestProxyFilter.CACHE_KEY)).thenReturn(cacheKey);
    when(cacheKey.get()).thenReturn("key");

    HttpResponse resp = mock(HttpResponse.class);
    when(resp.getStatus()).thenReturn(HttpResponseStatus.OK);
    filter.filterResponse(resp, ctx);//w  ww  .  ja  v a 2  s. co  m
    HttpContent httpContent = mock(HttpContent.class);
    when(httpContent.duplicate()).thenReturn(mock(HttpContent.class));
    filter.filterResponse(httpContent, ctx);
    LastHttpContent lastHttpContent = mock(LastHttpContent.class);
    when(lastHttpContent.duplicate()).thenReturn(mock(LastHttpContent.class));
    filter.filterResponse(lastHttpContent, ctx);

    filter.filterResponse(resp, ctx);
    filter.filterResponse(lastHttpContent, ctx);

    tp.awaitTermination(10, TimeUnit.SECONDS);
}

From source file:org.eclipse.moquette.parser.netty.ConnectDecoderTest.java

License:Open Source License

@Test
public void testBaseHeader_311() throws UnsupportedEncodingException {
    m_buff = Unpooled.buffer(12);//from  w  w w.  jav a2  s . c o m
    initBaseHeader311(m_buff);
    List<Object> results = new ArrayList<Object>();

    //Excercise
    m_msgdec.decode(this.attrMap, m_buff, results);

    //Verify
    assertFalse(results.isEmpty());
    verifyBaseHeader311((ConnectMessage) results.get(0));
    Attribute<Integer> attr = this.attrMap.attr(MQTTDecoder.PROTOCOL_VERSION);
    assertEquals(VERSION_3_1_1, attr.get().intValue());
}

From source file:org.eclipse.moquette.server.netty.NettyUtils.java

License:Open Source License

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

From source file:org.hawkular.metrics.clients.ptrans.MetricBatcher.java

License:Apache License

/**
 * Batch up incoming SingleMetric messages. If the #minimumBatchSize is not yet reached, the messages are stored
 * locally. Otherwise the list of messages will be forwarded to the next handler.
 * This method will be called for each written message that can be handled
 * by this encoder.//from ww w  . j a v  a  2 s.c  o  m
 *
 * @param ctx           the {@link ChannelHandlerContext} which this {@link MessageToMessageDecoder} belongs to
 * @param msg           the SingleMetric to be batched up
 * @param out           the {@link List} to which decoded messages should be added if the batch size is reached
 * @throws Exception    is thrown if an error occurs
 */
@Override
protected void decode(ChannelHandlerContext ctx, SingleMetric msg, List<Object> out) throws Exception {
    LOG.trace("Incoming metric for key '{}'", cacheKey.name());
    Attribute<List<SingleMetric>> cache = ctx.attr(cacheKey);
    List<SingleMetric> batchList = cache.get();
    if (batchList == null) {
        LOG.trace("Creating new batch list for key '{}'", cacheKey.name());
        batchList = new ArrayList<>(minimumBatchSize);
        cache.set(batchList);
    }
    batchList.add(msg);
    if (batchList.size() >= minimumBatchSize) {
        LOG.trace("Batch size limit '{}' reached for key '{}'", minimumBatchSize, cacheKey.name());
        cache.remove();
        out.add(batchList);
    }
}

From source file:org.jmqtt.core.codec.ConnectDecoder.java

License:Open Source License

@Override
void decode(AttributeMap ctx, ByteBuf in, List<Object> out) throws UnsupportedEncodingException {
    in.resetReaderIndex();// w  ww.  j a  va 2  s  . co  m
    //Common decoding part
    ConnectPacket message = new ConnectPacket();
    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) MqttUtils.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) MqttUtils.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() == MqttUtils.VERSION_3_1_1) {
        //if 3.1.1, check the flags (dup, retain and qos == 0)
        if (message.isDupFlag() || message.isRetainFlag() || message.getQos() != 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() == MqttUtils.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 = MqttUtils.readWord(in);
    int keepAlive = in.readUnsignedShort();
    message.setKeepAlive(keepAlive);

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

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

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

    //Decode willMessage
    if (willFlag) {
        byte[] willMessage = MqttUtils.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 = MqttUtils.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 = MqttUtils.readFixedLengthContent(in);
        if (password == null) {
            in.resetReaderIndex();
            return;
        }
        message.setPassword(password);
    }

    out.add(message);
}

From source file:org.jmqtt.core.util.MqttUtils.java

License:Open Source License

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

From source file:org.jooby.internal.netty.NettyHandler.java

License:Apache License

@Override
public void channelRead0(final ChannelHandlerContext ctx, final Object msg) {
    if (msg instanceof HttpRequest) {
        ctx.channel().attr(NettyRequest.NEED_FLUSH).set(true);

        HttpRequest req = (HttpRequest) msg;
        ctx.channel().attr(PATH).set(req.method().name() + " " + req.uri());

        if (HttpUtil.is100ContinueExpected(req)) {
            ctx.write(new DefaultFullHttpResponse(HTTP_1_1, HttpResponseStatus.CONTINUE));
        }//from   www . j  a  va2  s  .c o m

        boolean keepAlive = HttpUtil.isKeepAlive(req);

        try {
            String streamId = req.headers().get(STREAM_ID);

            handler.handle(new NettyRequest(ctx, req, tmpdir, wsMaxMessageSize),
                    new NettyResponse(ctx, bufferSize, keepAlive, streamId));

        } catch (Throwable ex) {
            exceptionCaught(ctx, ex);
        }
    } else if (msg instanceof WebSocketFrame) {
        Attribute<NettyWebSocket> ws = ctx.channel().attr(NettyWebSocket.KEY);
        ws.get().handle(msg);
    }
}

From source file:org.jooby.internal.netty.NettyHandler.java

License:Apache License

@Override
public void channelReadComplete(final ChannelHandlerContext ctx) throws Exception {
    Attribute<Boolean> attr = ctx.channel().attr(NettyRequest.NEED_FLUSH);
    boolean needFlush = (attr == null || attr.get() == Boolean.TRUE);
    if (needFlush) {
        ctx.flush();/*from w ww.  ja  v  a2 s  . c  o m*/
    }
}

From source file:org.jooby.internal.netty.NettyHandler.java

License:Apache License

@Override
public void exceptionCaught(final ChannelHandlerContext ctx, final Throwable cause) {
    try {/*from   ww w.  java 2 s  .c  o m*/
        if (ConnectionResetByPeer.test(cause)) {
            log.trace("execution of: " + ctx.channel().attr(PATH).get() + " resulted in error", cause);
        } else {
            Attribute<NettyWebSocket> ws = ctx.channel().attr(NettyWebSocket.KEY);
            if (ws != null && ws.get() != null) {
                ws.get().handle(cause);
            } else {
                log.debug("execution of: " + ctx.channel().attr(PATH).get() + " resulted in error", cause);
            }
        }
    } finally {
        ctx.close();
    }

}