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:io.scalecube.socketio.pipeline.WebSocketHandler.java

License:Apache License

@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
    // ?//  w  ww.  j  av  a  2s.c  o  m
    if (msg instanceof FullHttpRequest) {
        FullHttpRequest req = (FullHttpRequest) msg;
        if (req.getMethod() == HttpMethod.GET && req.getUri().startsWith(connectPath)) {
            final QueryStringDecoder queryDecoder = new QueryStringDecoder(req.getUri());
            final String requestPath = queryDecoder.path();

            if (log.isDebugEnabled())
                log.debug("Received HTTP {} handshake request: {} {} from channel: {}",
                        getTransportType().getName(), req.getMethod(), requestPath, ctx.channel());

            handshake(ctx, req, requestPath);

            ReferenceCountUtil.release(msg);
            return;
        }
    } else if (msg instanceof WebSocketFrame && isCurrentHandlerSession(ctx)) {
        handleWebSocketFrame(ctx, (WebSocketFrame) msg);
        return;
    }
    ctx.fireChannelRead(msg);
}

From source file:io.scalecube.socketio.pipeline.WebSocketHandler.java

License:Apache License

private void connect(ChannelHandlerContext ctx, HttpRequest req, String sessionId) throws Exception {
    sessionIdByChannel.put(ctx.channel(), sessionId);

    SocketAddress clientIp = PipelineUtils.getHeaderClientIPParamValue(req, remoteAddressHeader);

    final ConnectPacket packet = new ConnectPacket(sessionId, PipelineUtils.getOrigin(req));
    packet.setTransportType(getTransportType());
    packet.setRemoteAddress(clientIp);/*from   w w w.j a va  2s  . co m*/

    ctx.fireChannelRead(packet);
}

From source file:io.scalecube.socketio.pipeline.WebSocketHandler.java

License:Apache License

private void handleWebSocketFrame(ChannelHandlerContext ctx, WebSocketFrame msg) throws Exception {
    if (log.isDebugEnabled())
        log.debug("Received {} WebSocketFrame: {} from channel: {}", getTransportType().getName(), msg,
                ctx.channel());//from   w ww . j a v a2 s  .  c o m

    if (msg instanceof CloseWebSocketFrame) {
        sessionIdByChannel.remove(ctx.channel());
        ChannelFuture f = ctx.writeAndFlush(msg);
        f.addListener(ChannelFutureListener.CLOSE);
        return;
    } else if (msg instanceof PingWebSocketFrame) {
        ctx.writeAndFlush(new PongWebSocketFrame(msg.content()));
        return;
    } else if (!(msg instanceof TextWebSocketFrame)) {
        msg.release();
        log.warn(String.format("%s frame types not supported", msg.getClass().getName()));
        return;
    }

    TextWebSocketFrame frame = (TextWebSocketFrame) msg;
    Packet packet = PacketDecoder.decodePacket(frame.content());
    packet.setTransportType(getTransportType());
    String sessionId = sessionIdByChannel.get(ctx.channel());
    packet.setSessionId(sessionId);
    msg.release();
    ctx.fireChannelRead(packet);
}

From source file:io.scalecube.socketio.pipeline.XHRPollingHandler.java

License:Apache License

@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
    // ?/*from  w ww.  j a v a 2s . c  o  m*/
    if (msg instanceof FullHttpRequest) {
        final FullHttpRequest req = (FullHttpRequest) msg;
        final HttpMethod requestMethod = req.getMethod();
        final QueryStringDecoder queryDecoder = new QueryStringDecoder(req.getUri());
        final String requestPath = queryDecoder.path();

        if (requestPath.startsWith(connectPath)) {
            if (log.isDebugEnabled())
                log.debug("Received HTTP XHR-Polling request: {} {} from channel: {}", requestMethod,
                        requestPath, ctx.channel());

            final String sessionId = PipelineUtils.getSessionId(requestPath);
            final String origin = PipelineUtils.getOrigin(req);

            if (HttpMethod.GET.equals(requestMethod)) {
                SocketAddress clientIp = PipelineUtils.getHeaderClientIPParamValue(req, remoteAddressHeader);

                // Process polling request from client
                final ConnectPacket packet = new ConnectPacket(sessionId, origin);
                packet.setTransportType(TransportType.XHR_POLLING);
                packet.setRemoteAddress(clientIp);

                ctx.fireChannelRead(packet);
            } else if (HttpMethod.POST.equals(requestMethod)) {
                // Process message request from client
                List<Packet> packets = PacketFramer.decodePacketsFrame(req.content());
                for (Packet packet : packets) {
                    packet.setSessionId(sessionId);
                    packet.setOrigin(origin);
                    ctx.fireChannelRead(packet);
                }
            } else {
                log.warn("Can't process HTTP XHR-Polling request. Unknown request method: {} from channel: {}",
                        requestMethod, ctx.channel());
            }
            ReferenceCountUtil.release(msg);
            return;
        }
    }

    ctx.fireChannelRead(msg);
}

From source file:io.soliton.protobuf.EnvelopeServerHandler.java

License:Apache License

/**
 * {@inheritDoc}/*from   w  w  w . ja v  a 2 s  .  com*/
 */
@Override
public void channelRead0(ChannelHandlerContext context, I request) throws Exception {
    if (!accept(request)) {
        context.fireChannelRead(request);
        return;
    }

    Envelope envelope = null;
    try {
        envelope = convertRequest(request);
    } catch (RequestConversionException rce) {
        serverLogger.logClientError(rce);
        throw rce;
    }

    if (envelope.hasControl() && envelope.getControl().getCancel()) {
        ListenableFuture<?> pending = pendingRequests.remove(envelope.getRequestId());
        if (pending != null) {
            boolean cancelled = pending.cancel(true);
            context.channel().writeAndFlush(Envelope.newBuilder().setRequestId(envelope.getRequestId())
                    .setControl(Control.newBuilder().setCancel(cancelled)).build());
        }
        return;
    }

    Service service = services.lookupByName(envelope.getService());
    if (service == null) {
        serverLogger.logUnknownService(service);
        logger.warning(String.format("Received request for unknown service %s", envelope.getService()));
        context.channel()
                .writeAndFlush(
                        Envelope.newBuilder().setRequestId(envelope.getRequestId())
                                .setControl(Control.newBuilder()
                                        .setError(String.format("Unknown service %s", envelope.getService())))
                                .build());
        return;
    }

    ServerMethod<? extends Message, ? extends Message> method = service.lookup(envelope.getMethod());
    if (method == null) {
        serverLogger.logUnknownMethod(service, envelope.getMethod());
        logger.warning(String.format("Received request for unknown method %s/%s", envelope.getService(),
                envelope.getMethod()));
        context.channel().writeAndFlush(Envelope.newBuilder().setRequestId(envelope.getRequestId())
                .setControl(Control.newBuilder().setError(
                        String.format("Unknown method %s/%s", envelope.getService(), envelope.getMethod())))
                .build());
        return;
    }
    serverLogger.logMethodCall(service, method);
    invoke(method, envelope.getPayload(), envelope.getRequestId(), context.channel());
}

From source file:io.termd.core.http.netty.HttpRequestHandler.java

License:Apache License

@Override
protected void channelRead0(ChannelHandlerContext ctx, FullHttpRequest request) throws Exception {
    if (wsUri.equalsIgnoreCase(request.getUri())) {
        ctx.fireChannelRead(request.retain());
    } else {//from  www .ja  va  2s .c  om
        if (HttpHeaders.is100ContinueExpected(request)) {
            send100Continue(ctx);
        }

        HttpResponse response = new DefaultHttpResponse(request.getProtocolVersion(),
                HttpResponseStatus.INTERNAL_SERVER_ERROR);

        String path = request.getUri();
        if ("/".equals(path)) {
            path = "/index.html";
        }
        URL res = HttpTtyConnection.class.getResource("/io/termd/core/http" + path);
        try {
            if (res != null) {
                DefaultFullHttpResponse fullResp = new DefaultFullHttpResponse(request.getProtocolVersion(),
                        HttpResponseStatus.OK);
                InputStream in = res.openStream();
                byte[] tmp = new byte[256];
                for (int l = 0; l != -1; l = in.read(tmp)) {
                    fullResp.content().writeBytes(tmp, 0, l);
                }
                int li = path.lastIndexOf('.');
                if (li != -1 && li != path.length() - 1) {
                    String ext = path.substring(li + 1, path.length());
                    String contentType;
                    switch (ext) {
                    case "html":
                        contentType = "text/html";
                        break;
                    case "js":
                        contentType = "application/javascript";
                        break;
                    default:
                        contentType = null;
                        break;
                    }
                    if (contentType != null) {
                        fullResp.headers().set(HttpHeaders.Names.CONTENT_TYPE, contentType);
                    }
                }
                response = fullResp;
            } else {
                response.setStatus(HttpResponseStatus.NOT_FOUND);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            ctx.write(response);
            ChannelFuture future = ctx.writeAndFlush(LastHttpContent.EMPTY_LAST_CONTENT);
            future.addListener(ChannelFutureListener.CLOSE);
        }
    }
}

From source file:io.urmia.api.handler.RestApiHandler.java

License:Open Source License

@Override
protected void channelRead0(ChannelHandlerContext ctx, HttpObject msg) throws Exception {

    if (msg instanceof HttpRequest) {

        if (requestState != RequestState.EXPECT_REQUEST) {
            sendError(ctx, ERROR_BAD_REQUEST);
            return;
        }/*from  ww  w  . j a v  a  2s  .co  m*/

        request = (HttpRequest) msg;

        log.info("received HttpRequest: {} {}", request.getMethod(), request.getUri());

        final ObjectRequest r;

        try {
            r = new ObjectRequest(request);
        } catch (ExceptionInInitializerError e) {
            log.warn("unable to parse the request into a command: {}", request.getUri());
            return;
        }

        objectRequest = r;
        httpRequest = request;

        if (HttpMethod.PUT.equals(request.getMethod())) {
            if (objectRequest.isNotDirectory()) // make dir request
                setupProxyToPUT(ctx, objectRequest);

            requestState = RequestState.EXPECT_CONTENT_OR_LAST;
        } else {
            requestState = RequestState.EXPECT_LAST;
            ctx.read();
        }

        return;
    }

    if (objectRequest == null) {
        String uri = request == null ? "" : request.getUri();
        log.warn("not expecting an empty objectRequest. parse error maybe: {}", uri);
        ByteBuf body = request == null || request.getMethod().equals(HttpMethod.HEAD) ? null
                : errorBody("ResourceNotFoundError", uri + " does not exist");
        sendError(ctx, HttpResponseStatus.NOT_FOUND, body);
        return;
    }

    if (msg instanceof HttpContent) {

        if (requestState != RequestState.EXPECT_LAST && requestState != RequestState.EXPECT_CONTENT_OR_LAST) {
            log.warn("not expecting LAST or CONTENT, requestState: {}", requestState);
            sendError(ctx, HttpResponseStatus.NOT_EXTENDED);
            return;
        }

        final boolean last = msg instanceof LastHttpContent;
        final boolean emptyLast = last && msg == LastHttpContent.EMPTY_LAST_CONTENT;

        if (proxyMode && !emptyLast) // todo: the emptyLast was added for mln
            ctx.fireChannelRead(msg);

        // example of reading only if at the end
        if (last) {

            log.debug("received LastHttpContent: {}", msg);
            requestState = RequestState.EXPECT_REQUEST;

            final HttpRequest request = httpRequest;

            if (HttpMethod.HEAD.equals(request.getMethod())) {
                handleHEAD(ctx, objectRequest);
                return;
            }

            if (HttpMethod.GET.equals(request.getMethod())) {
                handleGET(ctx, objectRequest);
                return;
            }

            if (HttpMethod.DELETE.equals(request.getMethod())) {
                handleDELETE(ctx, objectRequest);
                return;
            }

            if (HttpMethod.PUT.equals(request.getMethod())) {
                if (proxyMode)
                    log.info("finished file upload: {}", objectRequest);
                else
                    handlePUTmkdir(ctx, objectRequest);
                return;
            }

            log.warn("unknown request: {}", request);
            sendError(ctx, HttpResponseStatus.BAD_REQUEST);
        }

        return;
    }

    log.warn("unexpected msg type: {}", msg);
    sendError(ctx, HttpResponseStatus.BAD_REQUEST);
}

From source file:io.vertx.core.http.impl.Http1xOrH2CHandler.java

License:Open Source License

private void end(ChannelHandlerContext ctx, ByteBuf buf, boolean h2c) {
    if (current > 0) {
        ByteBuf msg = Unpooled.buffer(current + buf.readableBytes());
        msg.writeBytes(HTTP_2_PREFACE_ARRAY, 0, current);
        msg.writeBytes(buf);/*from w ww  .j  av  a 2  s  .  co m*/
        buf.release();
        buf = msg;
    }
    configure(ctx, h2c);
    ctx.pipeline().remove(this);
    ctx.fireChannelRead(buf);
}

From source file:io.viewserver.network.netty.websocket.WebSocketServerHandler.java

License:Apache License

private void handleWebSocketFrame(ChannelHandlerContext ctx, WebSocketFrame frame) {
    if (frame instanceof CloseWebSocketFrame) {
        handshaker.close(ctx.channel(), (CloseWebSocketFrame) frame.retain());
        return;/*from  ww  w . jav a  2  s .c  o m*/
    }
    if (frame instanceof PingWebSocketFrame) {
        ctx.channel().write(new PongWebSocketFrame(frame.content().retain()));
        return;
    }
    if (!(frame instanceof BinaryWebSocketFrame)) {
        throw new UnsupportedOperationException(
                String.format("%s frame types not supported", frame.getClass().getName()));
    }

    ctx.fireChannelRead(frame.content().retain());
}

From source file:io.werval.server.netty.SubProtocolSwitchHandler.java

License:Apache License

@Override
protected void channelRead0(ChannelHandlerContext context, Object message) throws Exception {
    if (message instanceof HttpRequest) {
        HttpRequest request = (HttpRequest) message;
        LOG.trace("Switching to plain HTTP protocol");
        ChannelPipeline pipeline = context.pipeline();

        int maxBodySize = app.config().intNumber(WERVAL_HTTP_REQUESTS_BODY_MAX_SIZE);
        int diskThreshold = app.config().intNumber(WERVAL_HTTP_REQUESTS_BODY_DISK_THRESHOLD);
        pipeline.addLast("http-aggregator",
                new HttpRequestAggregator(helper, app.events(), maxBodySize, diskThreshold, app.tmpdir()));
        pipeline.addLast("werval-http", new WervalHttpHandler(app, devSpi));

        pipeline.remove(this);

        context.fireChannelRead(request);
    } else if (message instanceof WebSocketFrame) {
        WebSocketFrame frame = (WebSocketFrame) message;
        LOG.trace("Switching to WebSocket protocol");
        ChannelPipeline pipeline = context.pipeline();

        pipeline.addLast("werval-websocket", new WervalSocketHandler(app, devSpi));

        pipeline.remove(this);

        frame.retain(); // TODO Check this
        context.fireChannelRead(frame);// ww  w. j a  v  a 2 s. c  om
    } else {
        LOG.warn("Received a message of an unknown type ({}), channel will be closed.", message.getClass());
        context.channel().close();
    }
}