Example usage for io.netty.channel ChannelHandlerContext pipeline

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

Introduction

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

Prototype

ChannelPipeline pipeline();

Source Link

Document

Return the assigned ChannelPipeline

Usage

From source file:io.liveoak.container.protocols.http.HttpRequestBodyHandler.java

License:Open Source License

@Override
protected void decode(ChannelHandlerContext ctx, Object msg, List<Object> out) throws Exception {

    if (msg instanceof LastHttpContent) {

        ByteBuf content = ((HttpContent) msg).content();
        if (fileUpload != null) {
            // if it's a PUT or a POST
            fileUpload.addContent(content.retain(), true);

            // TODO - not sure this is ever necessary - defensive coding
            if (request.state() != null) {
                ((LazyResourceState) request.state()).fileUpload(fileUpload);
            } else {
                fileUpload.delete();/*w w  w.  j a  v a  2 s . com*/
            }

            if (completion != null) {
                // complete the request as body is now fully available
                completion.run();
                completion = null;
            } else {
                // mark that body is fully available
                complete = true;
            }
        } else if (content.readableBytes() > 0) {
            log.debug("on LastHttpContent: " + content.readableBytes() + " bytes discarded!");
        }

    } else if (msg instanceof HttpContent) {

        ByteBuf content = ((HttpContent) msg).content();
        if (fileUpload != null) {
            fileUpload.addContent(content.retain(), false);
        } else if (content.readableBytes() > 0) {
            log.debug("on HttpContent: " + content.readableBytes() + " bytes discarded!");
        }

        // only continue reading body if resource has declared interest
        if (completion != null) {
            ctx.pipeline().firstContext().read();
        }

    } else if (msg instanceof ResourceRequest) {
        // beginning of a new request
        complete = false;
        if (fileUpload != null) {
            fileUpload.delete();
        }
        fileUpload = null;

        ResourceRequest request = (ResourceRequest) msg;
        if (request.requestType() != RequestType.CREATE && request.requestType() != RequestType.UPDATE) {
            // not POST or PUT
            out.add(request);
            ctx.pipeline().firstContext().read();
            return;
        }

        // use original HttpRequest to get to Content-Length, and Content-Type
        HttpRequest original = (HttpRequest) request.requestContext().requestAttributes()
                .getAttribute("HTTP_REQUEST");

        // use last component of target URI as posted resource filename
        List<ResourcePath.Segment> segments = request.resourcePath().segments();
        String filename = segments.size() < 1 ? "unknown" : segments.get(segments.size() - 1).name();
        factory.createAttribute(original, "filename", filename);

        String contentLength = original.headers().get(CONTENT_LENGTH);
        long clen = 0;
        if (contentLength != null) {
            factory.createAttribute(original, CONTENT_LENGTH, contentLength);
            try {
                clen = Long.parseLong(contentLength);
            } catch (Exception ignored) {
                log.debug("Invalid Content-Length received: " + contentLength);
            }
        }

        String contentType = original.headers().get(CONTENT_TYPE);
        if (contentType == null) {
            contentType = "application/octet-stream";
        }

        factory.createAttribute(original, CONTENT_TYPE, contentType);
        fileUpload = factory.createFileUpload(original, request.resourcePath().toString(), filename,
                contentType, "binary", Charset.forName("utf-8"), clen);

        // save request for later, so we can update it with fileUpload once body is fully available
        this.request = request;

        out.add(request);

    } else if (msg instanceof Invocation) {

        Invocation invocation = (Invocation) msg;
        if (complete) {
            // body is fully available we should continue processing the request
            invocation.run();
        } else {
            completion = invocation;
        }
    } else {
        // in any other case simply pass the message on as if we're not here
        out.add(ReferenceCountUtil.retain(msg));
    }
}

From source file:io.liveoak.container.protocols.http.HttpResourceResponseEncoder.java

License:Open Source License

@Override
protected void encode(ChannelHandlerContext ctx, DefaultResourceResponse msg, List<Object> out)
        throws Exception {

    int responseStatusCode = 0;
    String responseMessage = null;
    HttpHeaders responseHeaders = new DefaultHttpHeaders();

    boolean shouldEncodeState = false;
    boolean shouldCheckForHtmlApp = true;
    switch (msg.responseType()) {
    case CREATED:
        responseStatusCode = HttpResponseStatus.CREATED.code();
        responseMessage = HttpResponseStatus.CREATED.reasonPhrase();
        shouldEncodeState = true;/* w  w  w.  j av a 2 s  .  com*/
        break;
    case READ:
        responseStatusCode = HttpResponseStatus.OK.code();
        responseMessage = HttpResponseStatus.OK.reasonPhrase();
        shouldEncodeState = true;
        break;
    case UPDATED:
        responseStatusCode = HttpResponseStatus.OK.code();
        responseMessage = HttpResponseStatus.OK.reasonPhrase();
        shouldEncodeState = true;
        break;
    case DELETED:
        responseStatusCode = HttpResponseStatus.OK.code();
        responseMessage = HttpResponseStatus.OK.reasonPhrase();
        shouldEncodeState = true;
        break;
    case ERROR:
        if (msg instanceof ResourceErrorResponse) {
            shouldEncodeState = true;
            shouldCheckForHtmlApp = false;
            switch (((DefaultResourceErrorResponse) msg).errorType()) {
            case NOT_AUTHORIZED:
                responseStatusCode = HttpResponseStatus.UNAUTHORIZED.code();
                responseMessage = HttpResponseStatus.UNAUTHORIZED.reasonPhrase();
                break;
            case FORBIDDEN:
                responseStatusCode = HttpResponseStatus.FORBIDDEN.code();
                responseMessage = HttpResponseStatus.FORBIDDEN.reasonPhrase();
                break;
            case NOT_ACCEPTABLE:
                responseStatusCode = HttpResponseStatus.NOT_ACCEPTABLE.code();
                responseMessage = HttpResponseStatus.NOT_ACCEPTABLE.reasonPhrase();
                break;
            case NO_SUCH_RESOURCE:
                responseStatusCode = HttpResponseStatus.NOT_FOUND.code();
                responseMessage = HttpResponseStatus.NOT_FOUND.reasonPhrase();
                break;
            case RESOURCE_ALREADY_EXISTS:
                responseStatusCode = HttpResponseStatus.NOT_ACCEPTABLE.code();
                responseMessage = HttpResponseStatus.NOT_ACCEPTABLE.reasonPhrase();
                break;
            case CREATE_NOT_SUPPORTED:
                responseStatusCode = HttpResponseStatus.METHOD_NOT_ALLOWED.code();
                responseMessage = "Create not supported";
                break;
            case READ_NOT_SUPPORTED:
                responseStatusCode = HttpResponseStatus.METHOD_NOT_ALLOWED.code();
                responseMessage = "Read not supported";
                break;
            case UPDATE_NOT_SUPPORTED:
                responseStatusCode = HttpResponseStatus.METHOD_NOT_ALLOWED.code();
                responseMessage = "UpdateStep not supported";
                break;
            case DELETE_NOT_SUPPORTED:
                responseStatusCode = HttpResponseStatus.METHOD_NOT_ALLOWED.code();
                responseMessage = "Delete not supported";
                break;
            case INTERNAL_ERROR:
                responseStatusCode = HttpResponseStatus.INTERNAL_SERVER_ERROR.code();
                responseMessage = HttpResponseStatus.INTERNAL_SERVER_ERROR.reasonPhrase();
                break;
            }

            //TODO: add content values here to return proper error messages to the client
            // eg unique error id, short error message, link to page with more information, etc...
            //response.content().writeBytes(...)

        }
        break;
    case MOVED:
        if (msg instanceof ResourceMovedResponse) {
            ResourceMovedResponse resourceMovedResponse = (ResourceMovedResponse) msg;

            switch (resourceMovedResponse.movedType()) {
            case MOVED_PERMANENTLY:
                responseStatusCode = HttpResponseStatus.MOVED_PERMANENTLY.code();
                responseMessage = HttpResponseStatus.MOVED_PERMANENTLY.reasonPhrase();
                break;
            case MOVED_TEMPORARILY:
                responseStatusCode = HttpResponseStatus.FOUND.code();
                responseMessage = HttpResponseStatus.FOUND.reasonPhrase();
                break;
            }

            Integer maxAge = resourceMovedResponse.maxAge();
            if (maxAge != null) {
                responseHeaders.add(HttpHeaders.Names.CACHE_CONTROL, "max-age=" + maxAge);
            }

            responseHeaders.add(HttpHeaders.Names.LOCATION, ((ResourceMovedResponse) msg).redirectURL());
        }
        break;
    }

    DefaultHttpResponse response;
    HttpResponseStatus responseStatus;

    EncodingResult encodingResult = null;
    if (shouldEncodeState) {
        MediaTypeMatcher matcher = msg.inReplyTo().mediaTypeMatcher();

        if (shouldCheckForHtmlApp) {
            Application app = msg.inReplyTo().requestContext().application();
            if (app != null && app instanceof InternalApplication) {
                ResourcePath htmlAppPath = ((InternalApplication) app).htmlApplicationResourcePath();
                if ((!(msg.resource() instanceof BinaryResource)) && (htmlAppPath != null)) {
                    MediaType bestMatch = matcher.findBestMatch(this.codecManager.mediaTypes());
                    if (bestMatch == MediaType.HTML) {
                        // HTML was requested and we have an HTML app
                        ResourceRequest htmlAppRequest = new DefaultResourceRequest.Builder(RequestType.READ,
                                htmlAppPath).mediaTypeMatcher(msg.inReplyTo().mediaTypeMatcher())
                                        .requestAttributes(msg.inReplyTo().requestContext().requestAttributes())
                                        .build();
                        ctx.channel().pipeline().fireChannelRead(htmlAppRequest);
                        return;
                    }
                }
            }
        }

        try {
            encodingResult = encodeState(msg.inReplyTo().requestContext(), matcher, msg);
        } catch (IncompatibleMediaTypeException e) {
            log.error("Incompatible media type", e);
            responseStatus = new HttpResponseStatus(HttpResponseStatus.NOT_ACCEPTABLE.code(), e.getMessage());
            response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, responseStatus);
            response.headers().add(HttpHeaders.Names.CONTENT_LENGTH, 0);
            out.add(response);
            return;
        } catch (Throwable e) {
            log.error("Could not encode HTTP response", e);
            responseStatus = new HttpResponseStatus(HttpResponseStatus.INTERNAL_SERVER_ERROR.code(),
                    HttpResponseStatus.INTERNAL_SERVER_ERROR.reasonPhrase());
            response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, responseStatus);
            response.headers().add(HttpHeaders.Names.CONTENT_LENGTH, 0);
            out.add(response);
            return;
        }
    }

    responseStatus = new HttpResponseStatus(responseStatusCode, responseMessage);

    if (encodingResult != null) {

        if (msg.resource() instanceof BinaryResource) {
            BinaryResource bin = (BinaryResource) msg.resource();
            if (bin.contentLength() == 0) {
                response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, responseStatus);
                response.headers().add(HttpHeaders.Names.CONTENT_LENGTH, 0);
            } else {
                response = new DefaultHttpResponse(HttpVersion.HTTP_1_1, responseStatus);
                response.headers().add(HttpHeaders.Names.CONTENT_LENGTH, bin.contentLength());
                response.headers().add(HttpHeaders.Names.LOCATION, msg.resource().uri().toString());
                response.headers().add(HttpHeaders.Names.CONTENT_TYPE, bin.mediaType());

                final HttpResponse res = response;
                bin.readContent(msg.inReplyTo().requestContext(), new BinaryContentSink() {
                    {
                        ctx.write(res);
                    }

                    @Override
                    public void close() {
                        ctx.writeAndFlush(new DefaultLastHttpContent(Unpooled.EMPTY_BUFFER));
                        ctx.pipeline().fireUserEventTriggered(new RequestCompleteEvent(msg.requestId()));
                    }

                    @Override
                    public void accept(ByteBuf byteBuf) {
                        ctx.write(new DefaultHttpContent(byteBuf));
                    }
                });
                return;
            }
        } else {
            ByteBuf content = encodingResult.encoded();

            response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, responseStatus, content);
            response.headers().add(HttpHeaders.Names.CONTENT_LENGTH, content.readableBytes());
            if (msg.resource() != null) {
                response.headers().add(HttpHeaders.Names.LOCATION, msg.resource().uri().toString());
            } else {
                response.headers().add(HttpHeaders.Names.LOCATION, msg.inReplyTo().resourcePath().toString());
            }
            response.headers().add(HttpHeaders.Names.CONTENT_TYPE, encodingResult.mediaType());
        }
    } else {
        response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, responseStatus);
        response.headers().add(HttpHeaders.Names.CONTENT_LENGTH, 0);
    }

    response.headers().add(responseHeaders);

    out.add(response);
    ctx.fireUserEventTriggered(new RequestCompleteEvent(msg.requestId()));
}

From source file:io.liveoak.container.protocols.ProtocolDetector.java

License:Open Source License

@Override
protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {

    int nonNewlineBytes = in.bytesBefore((byte) '\n');

    in.markReaderIndex();//from   w w w  . j av a  2  s . co  m

    if (nonNewlineBytes > 0) {
        ByteBuf lineBuffer = in.readBytes(nonNewlineBytes);
        String line = lineBuffer.toString(UTF_8);

        //SslHandler sslHandler = context.getPipeline().writeState( SslHandler.class );

        in.resetReaderIndex();
        ByteBuf fullBuffer = in.readBytes(super.actualReadableBytes());

        if (line.startsWith("CONNECT") || line.startsWith("STOMP")) {
            this.configurator.switchToPureStomp(ctx.pipeline());
        } else {
            this.configurator.switchToHttpWebSockets(ctx.pipeline());
        }

        ctx.pipeline().fireChannelRead(fullBuffer);
    }
}

From source file:io.liveoak.container.protocols.websocket.WebSocketHandshakerHandler.java

License:Open Source License

@Override
protected void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception {
    if (!(msg instanceof FullHttpRequest)) {
        DefaultHttpRequest req = (DefaultHttpRequest) msg;
        String upgrade = req.headers().get(HttpHeaders.Names.UPGRADE);
        if (HttpHeaders.Values.WEBSOCKET.equalsIgnoreCase(upgrade)) {
            // ensure FullHttpRequest by installing HttpObjectAggregator in front of this handler
            ReferenceCountUtil.retain(msg);
            this.configurator.switchToWebSocketsHandshake(ctx.pipeline());
            ctx.pipeline().fireChannelRead(msg);
        } else {//ww  w .j a va 2 s .  c o  m
            ReferenceCountUtil.retain(msg);
            this.configurator.switchToPlainHttp(ctx.pipeline());
            ctx.pipeline().fireChannelRead(msg);
        }
    } else {
        // do the handshake
        FullHttpRequest req = (FullHttpRequest) msg;
        WebSocketServerHandshakerFactory wsFactory = new WebSocketServerHandshakerFactory(req.getUri(), null,
                false);
        WebSocketServerHandshaker handshaker = wsFactory.newHandshaker(req);
        if (handshaker == null) {
            WebSocketServerHandshakerFactory.sendUnsupportedVersionResponse(ctx.channel());
        } else {
            ChannelFuture future = handshaker.handshake(ctx.channel(), req);
            future.addListener(f -> {
                this.configurator.switchToWebSockets(ctx.pipeline());
            });
        }
    }
}

From source file:io.liveoak.container.protocols.websocket.WebSocketStompFrameDecoder.java

License:Open Source License

@Override
public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
    ctx.pipeline().addAfter(ctx.name(), "stomp-frame-decoder", new StompFrameDecoder());
}

From source file:io.liveoak.container.protocols.websocket.WebSocketStompFrameEncoder.java

License:Open Source License

@Override
public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
    ctx.pipeline().addAfter(ctx.name(), "stomp-frame-encoder", new StompFrameEncoder());
}

From source file:io.liveoak.stomp.client.protocol.ConnectionNegotiatingHandler.java

License:Open Source License

@Override
protected void handleControlFrame(ChannelHandlerContext ctx, StompControlFrame frame)
        throws StompServerException {
    String version = frame.headers().get(Headers.VERSION);
    if (version != null) {
        this.clientContext.setVersion(Stomp.Version.forVersionString(version));
    }//  w  w w.  ja  v a2s  . c o  m

    ctx.pipeline().replace(this, "stomp-disconnection-negotiator",
            new DisconnectionNegotiatingHandler(this.clientContext));
    this.clientContext.setConnectionState(StompClient.ConnectionState.CONNECTED);
    this.clientContext.setChannel(ctx.channel());
    if (this.callback != null) {
        this.callback.accept(clientContext.getClient());
    }
}

From source file:io.mycat.netty.mysql.MySQLHandshakeHandler.java

License:Apache License

@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
    logger.info("receive authentication, channel read {}", msg);

    // handshake should remove here if authenticate success
    ProtocolTransport transport = new ProtocolTransport(ctx.channel(), (ByteBuf) msg);
    if (transport.getSession() == null) {
        userExecutor.execute(new AuthTask(ctx, transport));
    } else {/*  w w  w  . java  2s  . c o  m*/
        // handshake success, remove self;
        ctx.pipeline().remove(this);
        ctx.fireChannelRead(msg);
    }
}

From source file:io.netlibs.bgp.netty.handlers.BGPv4ClientEndpoint.java

License:Apache License

@Override
// public void channelConnected(final ChannelHandlerContext ctx, final ChannelStateEvent e) throws Exception
public void channelActive(final ChannelHandlerContext ctx) throws Exception {

    log.info("connected to client " + ctx.channel().remoteAddress());

    final BGPv4FSM fsm = this.fsmRegistry.lookupFSM((InetSocketAddress) ctx.channel().remoteAddress());

    if (fsm == null) {
        log.error("Internal Error: client for address " + ctx.channel().remoteAddress() + " is unknown");
        ctx.channel().close();/*from w  ww. j  a va2s .  c o m*/
    } else {

        final ChannelPipeline pipeline = ctx.pipeline();
        final PeerConnectionInformation pci = fsm.getPeerConnectionInformation();

        pipeline.forEach(e -> {

            ChannelHandler handler = e.getValue();

            if (handler.getClass().isAnnotationPresent(PeerConnectionInformationAware.class)) {
                log.info("attaching peer connection information " + pci + " to handler " + e.getKey()
                        + " for client " + ctx.channel().remoteAddress());
                pipeline.context(e.getKey()).attr(PEER_CONNECTION_INFO).set(pci);
            }

        });

        fsm.handleClientConnected(ctx.channel());

        ctx.fireChannelActive();

    }

}

From source file:io.netlibs.bgp.netty.handlers.BGPv4ServerEndpoint.java

License:Apache License

@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {

    final Channel clientChannel = ctx.channel();

    log.info("connected to client " + clientChannel.remoteAddress());

    BGPv4FSM fsm = fsmRegistry.lookupFSM(((InetSocketAddress) clientChannel.remoteAddress()).getAddress());

    if (fsm == null) {
        log.error("Internal Error: client for address " + clientChannel.remoteAddress() + " is unknown");
        clientChannel.close();/*from w w w  .j  a  v a 2  s. c om*/
    } else if (fsm.isCanAcceptConnection()) {

        ChannelPipeline pipeline = ctx.pipeline();
        PeerConnectionInformation pci = fsm.getPeerConnectionInformation();

        pipeline.forEach(e -> {

            ChannelHandler handler = e.getValue();

            if (handler.getClass().isAnnotationPresent(PeerConnectionInformationAware.class)) {
                log.info("attaching peer connection information {} to handler {} for client {}", pci,
                        e.getKey(), clientChannel.remoteAddress());
                pipeline.context(handler).attr(BGPv4ClientEndpoint.PEER_CONNECTION_INFO).set(pci);
            }

        });

        fsm.handleServerOpened(clientChannel);

        trackedChannels.add(clientChannel);
        ctx.fireChannelActive();

    } else {
        log.info("Connection from client {} cannot be accepted", clientChannel.remoteAddress());
        clientChannel.close();
    }

}