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.springframework.boot.context.embedded.netty.ServletContentHandler.java

License:Apache License

@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
    if (msg instanceof HttpRequest) {
        HttpRequest request = (HttpRequest) msg;
        HttpResponse response = new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK, false);
        HttpHeaders.setKeepAlive(response, HttpHeaders.isKeepAlive(request));
        NettyHttpServletResponse servletResponse = new NettyHttpServletResponse(ctx, servletContext, response);
        NettyHttpServletRequest servletRequest = new NettyHttpServletRequest(ctx, servletContext, request,
                servletResponse, inputStream);
        if (HttpHeaders.is100ContinueExpected(request)) {
            ctx.write(new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.CONTINUE),
                    ctx.voidPromise());/*w  w  w .j a v  a  2 s . com*/
        }
        ctx.fireChannelRead(servletRequest);
    }
    if (msg instanceof HttpContent) {
        inputStream.addContent((HttpContent) msg);
    }
}

From source file:org.thingsboard.mqtt.MqttPingHandler.java

License:Apache License

@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
    if (!(msg instanceof MqttMessage)) {
        ctx.fireChannelRead(msg);
        return;//  w w w .  ja v  a 2 s . c o  m
    }
    MqttMessage message = (MqttMessage) msg;
    if (message.fixedHeader().messageType() == MqttMessageType.PINGREQ) {
        this.handlePingReq(ctx.channel());
    } else if (message.fixedHeader().messageType() == MqttMessageType.PINGRESP) {
        this.handlePingResp();
    } else {
        ctx.fireChannelRead(ReferenceCountUtil.retain(msg));
    }
}

From source file:org.thingsplode.synapse.endpoint.handlers.HttpRequestHandler.java

License:Apache License

@Override
protected void channelRead0(ChannelHandlerContext ctx, FullHttpRequest httpRequest) throws Exception {
    //todo: support for API keys
    ///endpoints/json?api_key=565656
    try {/*from  w w  w . j  a va 2s . c o  m*/
        // Handle a bad request.
        if (!httpRequest.decoderResult().isSuccess()) {
            HttpResponseHandler.sendError(ctx, HttpResponseStatus.BAD_REQUEST, "Could not decode request.",
                    httpRequest);
            return;
        }

        if (httpRequest.method().equals(HttpMethod.HEAD) || httpRequest.method().equals(HttpMethod.PATCH)
                || httpRequest.method().equals(HttpMethod.TRACE)
                || httpRequest.method().equals(HttpMethod.CONNECT)
                || httpRequest.method().equals(HttpMethod.OPTIONS)) {
            HttpResponseHandler.sendError(ctx, HttpResponseStatus.FORBIDDEN,
                    "Method forbidden (The following are not supported: HEAD, PATCH, TRACE, CONNECT, OPTIONS).",
                    httpRequest);
            return;
        }

        //check websocket upgrade request
        String upgradeHeader = httpRequest.headers().get(HttpHeaderNames.UPGRADE);
        if (!Util.isEmpty(upgradeHeader) && UPGRADE_TO_WEBSOCKET.equalsIgnoreCase(upgradeHeader)) {
            //case websocket upgrade request is detected -> Prepare websocket handshake
            upgradeToWebsocket(ctx, httpRequest);
            return;
        } else {
            //case simple http request
            Request request = new Request(prepareHeader(ctx, httpRequest));

            //no information about the object type / it will be processed in a later stage
            //todo: with requestbodytype header value early deserialization would be possible, however not beneficial in routing cases
            request.setBody(httpRequest.content());
            ctx.fireChannelRead(request);
        }
    } catch (Exception ex) {
        logger.error("Channel read error: " + ex.getMessage(), ex);
        HttpResponseHandler.sendError(ctx, HttpResponseStatus.INTERNAL_SERVER_ERROR,
                ex.getClass().getSimpleName() + ": " + ex.getMessage(), httpRequest);
    }
}

From source file:org.thingsplode.synapse.endpoint.handlers.HttpRequestIntrospector.java

License:Apache License

@Override
protected void channelRead0(ChannelHandlerContext ctx, HttpRequest msg) throws Exception {
    try {/*from  w w  w . j  a  v a 2  s.  com*/
        if (msg == null) {
            logger.warn("Message@Endpoint received: NULL");
        } else if (logger.isDebugEnabled()) {
            final StringBuilder hb = new StringBuilder();
            msg.headers().entries().forEach(e -> {
                hb.append(e.getKey()).append(" : ").append(e.getValue()).append("\n");
            });
            String payloadAsSring = null;
            if (msg instanceof FullHttpRequest) {
                ByteBuf content = ((FullHttpRequest) msg).content();
                byte[] dst = new byte[content.capacity()];
                content.copy().getBytes(0, dst);
                content.retain();
                payloadAsSring = new String(dst, Charset.forName("UTF-8"));
            }
            logger.debug("Message@Endpoint received: \n\n" + "Uri: " + msg.uri() + "\n" + "Method: "
                    + msg.method() + "\n" + hb.toString() + "\n" + "Payload -> "
                    + (!Util.isEmpty(payloadAsSring) ? payloadAsSring + "\n" : "EMPTY\n"));
        }
    } catch (Throwable th) {
        logger.error(th.getClass().getSimpleName() + " caught while introspecting request, with message: "
                + th.getMessage(), th);
    }
    if (msg != null && msg instanceof FullHttpRequest) {
        ((FullHttpRequest) msg).content().retain();
    }
    ctx.fireChannelRead(msg);
}

From source file:org.thingsplode.synapse.endpoint.handlers.RequestHandler.java

License:Apache License

@Override
protected void channelRead0(ChannelHandlerContext ctx, Request request) throws Exception {
    Response response = null;//w  w  w. ja  v  a  2  s .co m
    boolean fileDownload = filePattern.matcher(request.getHeader().getUri().getPath()).find();
    if (!fileDownload) {
        try {
            if (request.getBody() != null && (request.getBody() instanceof ByteBuf)) {
                //the body is in unmarshalled
                //eg. http case
                ByteBuf content = (ByteBuf) request.getBody();
                byte[] dst = new byte[content.capacity()];
                content.getBytes(0, dst);
                String jsonBody = new String(dst, Charset.forName("UTF-8"));
                response = registry.invokeWithParsable(request.getHeader(), jsonBody);
            } else {
                //the complete body is unmarshalled already for an object
                //eg. websocket case
                response = registry.invokeWithObject(request.getHeader(), request.getBody());
            }
            //else {
            //    response = new Response(new Response.ResponseHeader(request.getHeader(), HttpResponseStatus.valueOf(HttpStatus.BAD_REQUEST.value()), new MediaType("text/plain; charset=UTF-8")), RequestHandler.class.getSimpleName() + ": Body type not supported.");
            //}
        } catch (MethodNotFoundException mex) {
            //simple listing, no stack trace (normal issue)
            logger.warn("Couldn't process request due to " + mex.getClass().getSimpleName() + " with message: "
                    + mex.getMessage());
            response = new Response(
                    new Response.ResponseHeader(request.getHeader(),
                            HttpResponseStatus.valueOf(mex.getResponseStatus().value()), MediaType.TEXT_PLAIN),
                    mex.getClass().getSimpleName() + ": " + mex.getMessage());
        } catch (SynapseException ex) {
            //it could be an internal issue
            logger.error("Error processing REST request: " + ex.getMessage(), ex);
            response = new Response(
                    new Response.ResponseHeader(request.getHeader(),
                            HttpResponseStatus.valueOf(ex.getResponseStatus().value()), MediaType.TEXT_PLAIN),
                    ex.getClass().getSimpleName() + ": " + ex.getMessage());
        }
    }

    if (fileDownload || response == null || isFileDownloadRetriable(response)) {
        FileRequest fr = new FileRequest(request.getHeader());
        ctx.fireChannelRead(fr);
    } else {
        ctx.fireChannelRead(response);
    }
}

From source file:org.thingsplode.synapse.endpoint.handlers.ResponseEncoder.java

License:Apache License

public static void sendError(ChannelHandlerContext ctx, HttpResponseStatus status, String errorMsg,
        Request request) {//from w ww .  j av a  2s.  c  o  m
    Response response;
    if (request != null) {
        response = new Response(
                new Response.ResponseHeader(request.getHeader(), status, MediaType.APPLICATION_JSON));
    } else {
        response = new Response(new Response.ResponseHeader(status));
        response.getHeader().setContentType(MediaType.APPLICATION_JSON);
    }
    response.setBody(errorMsg);
    ctx.fireChannelRead(response);
}

From source file:org.thingsplode.synapse.endpoint.handlers.WebsocketIntrospector.java

License:Apache License

@Override
protected void channelRead0(ChannelHandlerContext ctx, WebSocketFrame msg) throws Exception {
    try {/*from  ww  w. j ava  2  s  .  c o  m*/
        if (msg == null) {
            logger.warn("Message@Endpoint received: NULL");
        } else if (logger.isDebugEnabled()) {
            if (msg instanceof TextWebSocketFrame) {
                logger.debug("WebsocketFrame@Endpoint received: \n\n" + ((TextWebSocketFrame) msg).text());
            } else {
                logger.debug("WebsocketFrame@Endpoint of type [" + msg.getClass().getCanonicalName()
                        + "] received.");
            }
        }
    } catch (Throwable th) {
        logger.error(th.getClass().getSimpleName() + " caught while introspecting request, with message: "
                + th.getMessage(), th);
    }
    if (msg != null) {
        msg.retain();
    }
    ctx.fireChannelRead(msg);
}

From source file:org.thingsplode.synapse.endpoint.handlers.WebsocketRequestHandler.java

License:Apache License

@Override
protected void channelRead0(ChannelHandlerContext ctx, WebSocketFrame frame) throws Exception {
    try {/*from  ww w  .ja  v  a2s .  c  o  m*/
        if (frame instanceof CloseWebSocketFrame) {
            handshaker.close(ctx.channel(), (CloseWebSocketFrame) frame.retain());
            return;
        }

        if (frame instanceof PingWebSocketFrame) {
            updateLastSeen(ctx);
            ctx.channel().writeAndFlush(new PongWebSocketFrame(frame.content().retain()));
            return;
        }

        if (frame instanceof PongWebSocketFrame) {
            return;
        }

        if (frame instanceof TextWebSocketFrame) {
            contentBuilder = new StringBuilder(((TextWebSocketFrame) frame).text());
        } else if (frame instanceof ContinuationWebSocketFrame) {
            if (contentBuilder != null) {
                contentBuilder.append(((ContinuationWebSocketFrame) frame).text());
            } else {
                logger.warn("Continuation frame received without initial frame.");
            }
        } else if (frame instanceof BinaryWebSocketFrame) {
            throw new UnsupportedOperationException(
                    String.format("%s frame types not supported", frame.getClass().getName()));
        } else {
            throw new UnsupportedOperationException(
                    String.format("%s frame types not supported", frame.getClass().getName()));
        }

        // Check if Text or Continuation Frame is final fragment and handle if needed.
        if (frame.isFinalFragment()) {
            AbstractMessage synapseMessage = serializationService.getPreferredSerializer(null)
                    .unMarshall(AbstractMessage.class, contentBuilder.toString());
            synapseMessage.addProperty(AbstractMessage.PROP_RCV_TRANSPORT, AbstractMessage.PROP_WS_TRANSPORT);
            contentBuilder = null;
            if (synapseMessage instanceof Request) {
                ((Request) synapseMessage).getHeader().setKeepalive(true);
            }
            ctx.fireChannelRead(synapseMessage);
        }
    } catch (UnsupportedOperationException | SerializationException th) {
        logger.error(th.getClass().getSimpleName() + "error processing ws frame: " + th.getMessage(), th);
    }
}

From source file:org.thingsplode.synapse.proxy.handlers.HttpResponseIntrospector.java

License:Apache License

@Override
protected void channelRead0(ChannelHandlerContext ctx, HttpResponse msg) throws Exception {
    if (msg != null) {
        final StringBuilder hb = new StringBuilder();
        msg.headers().entries().forEach(e -> {
            hb.append(e.getKey()).append(" : ").append(e.getValue()).append("\n");
        });//www  .ja v a  2  s  . c o  m
        String payloadAsSring = null;
        if (msg instanceof FullHttpResponse) {
            ByteBuf content = ((FullHttpResponse) msg).content();
            byte[] dst = new byte[content.capacity()];
            content.copy().getBytes(0, dst);
            content.retain();
            payloadAsSring = new String(dst, Charset.forName("UTF-8"));
        }
        logger.debug("Message@Proxy received [" + msg.getClass().getSimpleName() + "]: \n\n" + "Status: "
                + msg.status() + "\n" + hb.toString() + "\n" + "Payload -> ["
                + (!Util.isEmpty(payloadAsSring) ? payloadAsSring : "EMPTY") + "]\n");
    }
    ctx.fireChannelRead(msg);
}

From source file:org.thingsplode.synapse.proxy.handlers.WSMessageDecoder.java

License:Apache License

@Override
protected void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception {
    Channel ch = ctx.channel();// w w  w  .  j  ava 2  s  .c  o  m
    if (!handshaker.isHandshakeComplete()) {
        handshaker.finishHandshake(ch, (FullHttpResponse) msg);
        logger.debug("Websocket@EndpointProxy: client is conencted.");
        handshakeFuture.setSuccess();
        return;
    }

    if (msg instanceof FullHttpResponse) {
        FullHttpResponse response = (FullHttpResponse) msg;
        throw new IllegalStateException("Unexpected FullHttpResponse (getStatus=" + response.getStatus()
                + ", content=" + response.content().toString(CharsetUtil.UTF_8) + ')');
    }

    WebSocketFrame frame = (WebSocketFrame) msg;
    if (frame instanceof TextWebSocketFrame) {
        TextWebSocketFrame textFrame = (TextWebSocketFrame) frame;
        AbstractMessage rcvdMsg = EndpointProxy.SERIALIZATION_SERVICE.getSerializer(MediaType.APPLICATION_JSON)
                .unMarshall(AbstractMessage.class, textFrame.text());
        ctx.fireChannelRead(rcvdMsg);
    } else if (frame instanceof PongWebSocketFrame) {

    } else if (frame instanceof CloseWebSocketFrame) {
        logger.debug("Closing channel due to received: " + CloseWebSocketFrame.class.getSimpleName());
        ch.close();

    }
}