Example usage for io.netty.channel ChannelHandlerContext fireChannelRead

List of usage examples for io.netty.channel ChannelHandlerContext fireChannelRead

Introduction

In this page you can find the example usage for io.netty.channel ChannelHandlerContext fireChannelRead.

Prototype

@Override
    ChannelHandlerContext fireChannelRead(Object msg);

Source Link

Usage

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

License:Apache License

@Override
public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
    if (!(evt instanceof IdleStateEvent)) {
        LOG.trace("Dropping unhandled event '{}' for key '{}'", evt, cacheKey.name());
        return;/*  ww w  .  j av  a2s . c  o m*/
    }
    IdleStateEvent idleStateEvent = (IdleStateEvent) evt;
    if (idleStateEvent != IdleStateEvent.FIRST_READER_IDLE_STATE_EVENT) {
        LOG.trace("Dropping event, expecting FIRST_READER_IDLE_STATE_EVENT for key '{}'", cacheKey.name());
        return;
    }
    List<SingleMetric> batchList = ctx.attr(cacheKey).getAndRemove();
    if (batchList != null && !batchList.isEmpty()) {
        LOG.trace("Batch delay reached for key '{}', forwarding {} metrics", cacheKey.name(), batchList.size());
        ctx.fireChannelRead(batchList);
    }
}

From source file:org.iotivity.cloud.base.protocols.coap.CoapLogHandler.java

License:Open Source License

@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {

    String log = null;//from   w  w w  .  j av  a 2 s . c o m

    if (msg instanceof CoapRequest) {
        log = composeCoapRequest(ctx.channel().id().asLongText().substring(26), (CoapRequest) msg);
    } else {
        log = composeCoapResponse(ctx.channel().id().asLongText().substring(26), (CoapResponse) msg);
    }

    Log.v(log);

    ctx.fireChannelRead(msg);
}

From source file:org.iotivity.cloud.base.protocols.coap.websocket.WebSocketFrameHandler.java

License:Open Source License

@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
    // TODO check ping pong

    if (msg instanceof BinaryWebSocketFrame) {

        List<Object> messages = new ArrayList<>();
        new CoapDecoder().decode(((BinaryWebSocketFrame) msg).content(), messages,
                ((BinaryWebSocketFrame) msg).content().readableBytes());

        for (Object message : messages) {
            if (message instanceof CoapMessage) {
                CoapMessage coapMessage = (CoapMessage) message;

                // convert content format to cbor if content format is json.
                if (coapMessage.getPayloadSize() != 0
                        && coapMessage.getContentFormat().equals(ContentFormat.APPLICATION_JSON)) {
                    byte[] payload = coapMessage.getPayload();
                    coapMessage.setPayload(convertJsonToCbor(payload));
                    coapMessage.setContentFormat(ContentFormat.APPLICATION_CBOR);
                }/*from ww w  .ja  va2 s  .c  o  m*/
                ctx.fireChannelRead(coapMessage);
            }
        }
    } else {
        throw new BadRequestException("invalid request message type");
    }
}

From source file:org.iotivity.cloud.base.protocols.http.HCProxyHandler.java

License:Open Source License

@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {

    // Wait translating the request until the end of content is received
    if (msg instanceof HttpRequest) {

        StringBuilder contentStrBuilder = new StringBuilder();
        ctx.channel().attr(HCProxyProcessor.ctxStrContent).set(contentStrBuilder);

        HttpRequest httpRequest = (HttpRequest) msg;

        HCProxyProcessor hcProxyProcessor = new HCProxyProcessor(ctx);

        HCProxyHandler.hcProxyProcessorMap.put(ctx.channel().id().asLongText(), hcProxyProcessor);

        // Set the values for required attributes in hcProxyProcessor
        hcProxyProcessor.setHttpMethod(httpRequest.method());
        hcProxyProcessor.setHostingHttpUri(httpRequest.uri());
        HttpHeaders httpHeaders = httpRequest.headers();
        hcProxyProcessor.setContentType(httpHeaders.get(HttpHeaderNames.CONTENT_TYPE));

        // Check Session-ID for the already signed-in transaction
        hcProxyProcessor.checkSessionId(httpHeaders.get(HttpHeaderNames.COOKIE));
    }//w  w  w .j a va 2s .  com

    // Do not hand over the message to next handler until the end of content
    if (msg instanceof HttpContent) {

        HttpContent content = (HttpContent) msg;

        StringBuilder contentStrBuilder = ctx.channel().attr(HCProxyProcessor.ctxStrContent).get();
        contentStrBuilder.append(content.content().toString(CharsetUtil.UTF_8));

        if (content instanceof LastHttpContent) {

            HCProxyProcessor hcProxyProcessor = HCProxyHandler.hcProxyProcessorMap
                    .get(ctx.channel().id().asLongText());

            if (hcProxyProcessor != null && hcProxyProcessor.getContentType() != null) {
                hcProxyProcessor.setContent(contentStrBuilder.toString());
            }

            contentStrBuilder.setLength(0);

            // Check HTTP request whether there is an error or not
            String errorStatusCode = hcProxyProcessor.checkHttpRequest();

            if (errorStatusCode != null) {

                Log.v("HTTP Error: " + errorStatusCode);

                HttpResponse httpResponse = hcProxyProcessor.getErrorResponse(errorStatusCode);

                ctx.writeAndFlush(httpResponse);
            }

            // Create a message request from HTTP request
            Message message = null;

            if (hcProxyProcessor != null) {
                message = hcProxyProcessor.getRequestMessage();
            }

            if (message != null) {
                ctx.fireChannelRead(message);
            } else {
                errorStatusCode = "500 Internal Server Error: " + "HTTP-Method does not recognized.";

                Log.v("HTTP Error: " + errorStatusCode);

                HttpResponse httpResponse = hcProxyProcessor.getErrorResponse(errorStatusCode);

                ctx.writeAndFlush(httpResponse);
            }
        }
    }
}

From source file:org.iotivity.cloud.base.protocols.http.HttpLogHandler.java

License:Open Source License

@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {

    if (!(msg instanceof HttpObject)) {
        Log.v("Non-HTTP message has been received to the HC proxy:\n" + msg.toString());
    }//from w w  w.j a  v a2s.c  om

    if (msg instanceof HttpRequest) {

        StringBuilder contentStrBuilder = new StringBuilder();
        ctx.channel().attr(HCProxyProcessor.ctxStrContent).set(contentStrBuilder);

        HttpRequest httpRequest = (HttpRequest) msg;

        Log.v(httpRequest.toString());

        if (HttpUtil.isTransferEncodingChunked(httpRequest)) {
            Log.v("BEGINNING OF HTTP CHUNKED CONTENT");
        } else {
            Log.v("BEGINNING OF HTTP CONTENT");
        }
    }

    if (msg instanceof HttpContent) {

        HttpContent content = (HttpContent) msg;

        StringBuilder contentStrBuilder = ctx.channel().attr(HCProxyProcessor.ctxStrContent).get();
        contentStrBuilder.append(content.content().toString(CharsetUtil.UTF_8));

        if (content instanceof LastHttpContent) {

            Log.v(contentStrBuilder.toString());

            Log.v("END OF HTTP CONTENT");

            contentStrBuilder.setLength(0);
        }
    }

    ctx.fireChannelRead(msg);
}

From source file:org.iotivity.cloud.util.CoapLogHandler.java

License:Open Source License

@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {

    if (msg instanceof CoapMessage) {

        CoapMessage coapMessage = (CoapMessage) msg;

        StringBuilder strBuilder = new StringBuilder();
        strBuilder.append(getStringCtx(ctx));
        strBuilder//from   ww  w.  j a v  a 2  s.  c  o m
                .append("\n/******************************************************************************/\n");
        strBuilder.append(getStringCoapMessage(coapMessage));
        strBuilder
                .append("\n/******************************************************************************/\n");
        Logger.d(strBuilder.toString());

    } else if (msg instanceof ByteBuf) {

        ByteBuf inByteBuf = (ByteBuf) msg;

        String message = null;
        StringBuffer strBuffer = new StringBuffer();
        while (inByteBuf.isReadable()) {
            strBuffer.append((char) inByteBuf.readByte());
        }
        message = strBuffer.toString();

        StringBuilder strBuilder = new StringBuilder();
        strBuilder.append(getStringCtx(ctx));
        strBuilder
                .append("\n/******************************************************************************/\n");
        strBuilder.append(message);
        strBuilder
                .append("\n/******************************************************************************/\n");
        Logger.d(strBuilder.toString());
    }

    ctx.fireChannelRead(msg);
}

From source file:org.janusgraph.graphdb.tinkerpop.gremlin.server.handler.HttpHMACAuthenticationHandler.java

License:Apache License

@Override
public void channelRead(final ChannelHandlerContext ctx, final Object msg) {
    if (msg instanceof FullHttpRequest) {
        final FullHttpRequest req = (FullHttpRequest) msg;
        final HttpMethod method = req.getMethod();
        final Map<String, String> credentialsMap = getCredentialsMap(ctx, req);
        if (credentialsMap == null) {
            sendError(ctx, msg);//from  w ww .java2 s.c  o  m
            return;
        }
        if ("/session".equals(req.getUri()) && method.equals(HttpMethod.GET)) {
            try {
                credentialsMap.put(PROPERTY_GENERATE_TOKEN, "true");
                authenticator.authenticate(credentialsMap);
            } catch (Exception e) {
                sendError(ctx, msg);
                return;
            }
            replyWithToken(ctx, msg, credentialsMap.get(PROPERTY_TOKEN));
        } else {
            try {
                authenticator.authenticate(credentialsMap);
                ctx.fireChannelRead(req);
            } catch (Exception e) {
                sendError(ctx, msg);
                return;
            }
        }
    }
}

From source file:org.janusgraph.graphdb.tinkerpop.gremlin.server.handler.HttpHMACAuthenticationHandlerTest.java

License:Apache License

@Test
public void testChannelReadBasicAuth() throws Exception {
    final ChannelHandlerContext ctx = createMock(ChannelHandlerContext.class);
    final FullHttpRequest msg = createMock(FullHttpRequest.class);
    final HttpHeaders headers = createMock(HttpHeaders.class);
    final Authenticator authenticator = createMock(Authenticator.class);
    final String encodedUserNameAndPass = Base64.getEncoder().encodeToString("user:pass".getBytes());
    expect(msg.getMethod()).andReturn(HttpMethod.POST);
    expect(msg.headers()).andReturn(headers).anyTimes();
    expect(msg.getUri()).andReturn("/");
    expect(headers.get(eq("Authorization"))).andReturn("Basic " + encodedUserNameAndPass);
    expect(ctx.fireChannelRead(isA(FullHttpRequest.class))).andReturn(ctx);
    expect(authenticator.authenticate(isA(Map.class))).andReturn(new AuthenticatedUser("foo"));
    final HttpHMACAuthenticationHandler handler = new HttpHMACAuthenticationHandler(authenticator);
    replayAll();/*from   www. j  a va  2  s .co  m*/
    handler.channelRead(ctx, (Object) msg);
    verifyAll();
}

From source file:org.janusgraph.graphdb.tinkerpop.gremlin.server.handler.HttpHMACAuthenticationHandlerTest.java

License:Apache License

@Test
public void testChannelReadTokenAuth() throws Exception {
    final ChannelHandlerContext ctx = createMock(ChannelHandlerContext.class);
    final FullHttpRequest msg = createMock(FullHttpRequest.class);
    final HttpHeaders headers = createMock(HttpHeaders.class);
    final Authenticator authenticator = createMock(Authenticator.class);
    final String encodedToken = Base64.getEncoder().encodeToString("askdjhf823asdlkfsasd".getBytes());
    expect(msg.getMethod()).andReturn(HttpMethod.GET);
    expect(msg.headers()).andReturn(headers).anyTimes();
    expect(msg.getUri()).andReturn("/");
    expect(headers.get(eq("Authorization"))).andReturn("Token " + encodedToken);
    expect(ctx.fireChannelRead(isA(FullHttpRequest.class))).andReturn(ctx);
    expect(authenticator.authenticate(isA(Map.class))).andReturn(new AuthenticatedUser("foo"));
    final HttpHMACAuthenticationHandler handler = new HttpHMACAuthenticationHandler(authenticator);
    replayAll();/*from w ww  .  j av  a  2  s. com*/
    handler.channelRead(ctx, (Object) msg);
    verifyAll();
}

From source file:org.janusgraph.graphdb.tinkerpop.gremlin.server.handler.SaslAndHMACAuthenticationHandler.java

License:Apache License

@Override
public void channelRead(final ChannelHandlerContext ctx, final Object obj) throws Exception {
    if (obj instanceof HttpMessage && !isWebSocket((HttpMessage) obj)) {
        if (null == ctx.pipeline().get(HMAC_AUTH)) {
            final HttpHMACAuthenticationHandler authHandler = new HttpHMACAuthenticationHandler(
                    hmacAuthenticator);/*from   w  w w .j a v  a  2  s  . co  m*/
            ctx.pipeline().addAfter(PIPELINE_AUTHENTICATOR, HMAC_AUTH, authHandler);
        }
        ctx.fireChannelRead(obj);
    } else {
        super.channelRead(ctx, obj);
    }
}