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:org.rzo.netty.ahessian.rpc.client.HessianProxyFactory.java

License:Apache License

@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
    _channel = ctx.channel();//  w ww. j a va2  s .  c om
    if (_connectedListener != null)
        _executor.execute(new Runnable() {
            @Override
            public void run() {
                try {
                    _connectedListener.run();
                } catch (Throwable ex) {
                    Constants.ahessianLogger.warn("", ex);
                }
            }
        });
    _lock.lock();
    try {
        if (!_sessionListenerAdded) {
            if (ctx.pipeline().get(ClientSessionFilter.class) != null) {
                ClientSessionFilter sessionHandler = (ClientSessionFilter) ctx.pipeline()
                        .get(ClientSessionFilter.class);
                sessionHandler.addSessionClosedListener(new Runnable() {
                    public void run() {
                        _lock.lock();
                        try {
                            invalidateProxies();
                            _openCalls.clear();

                            _pendingCalls.clear();
                        } finally {
                            _lock.unlock();
                        }
                        if (_closedSessionListener != null)
                            try {
                                _closedSessionListener.run();
                            } catch (Throwable ex) {
                                Constants.ahessianLogger.warn("", ex);
                            }
                    }
                });
                sessionHandler.addSessionNewListener(new Runnable() {
                    public void run() {
                        if (_newSessionListener != null)
                            try {
                                _newSessionListener.run();
                            } catch (Throwable ex) {
                                Constants.ahessianLogger.warn("", ex);
                            }
                    }
                });
                _sessionListenerAdded = true;
            }
        }
    } finally {
        _connected.signal();
        _lock.unlock();
        super.channelActive(ctx);
    }
}

From source file:org.rzo.netty.ahessian.rpc.message.HessianRPCCallEncoder.java

License:Apache License

@Override
public void connect(ChannelHandlerContext ctx, SocketAddress remoteAddress, SocketAddress localAddress,
        ChannelPromise promise) throws Exception {
    super.connect(ctx, remoteAddress, localAddress, promise);
    _hasSessionFilter = ctx.pipeline().context(ClientSessionFilter.class) != null;
    if (hOut == null) {
        OutputStream out = getOutputStream(ctx);
        hOut = new Hessian2Output(out);
        hOut.getSerializerFactory().addFactory(sFactory);
    } else//from   w ww.j av a2  s.  c o m
        hOut.reset();
}

From source file:org.rzo.netty.ahessian.session.ServerSessionFilter.java

License:Apache License

public static ServerSessionFilter getServerSessionFilter(ChannelHandlerContext ctx) {
    return (ServerSessionFilter) ctx.pipeline().context(ServerSessionFilter.class).handler();
}

From source file:org.rzo.netty.ahessian.stopable.StopHandler.java

License:Apache License

@Override
public void channelInactive(final ChannelHandlerContext ctx) throws Exception {
    ChannelPipeline p = ctx.pipeline();
    Iterator<Entry<String, ChannelHandler>> it = p.iterator();
    while (it.hasNext()) {
        Entry<String, ChannelHandler> e = it.next();
        if (e.getValue() instanceof StopableHandler) {
            StopableHandler h = (StopableHandler) e.getValue();
            if (h.isStopEnabled())
                h.stop();/*from   ww  w  .j  a v a2s.  c  o m*/
        }

    }
    if (_executor != null && !_executor.isShuttingDown() && !_executor.isTerminated())
        _executor.shutdownGracefully();
}

From source file:org.spongepowered.common.mixin.core.status.MixinPingResponseHandler.java

License:MIT License

/**
 * @author minecrell - January 18th, 2015
 * @reason Implements our Ping Status Response API for throwing
 * events and delegating to plugins.//from  ww  w.  j  a  v a 2 s. c o  m
 *
 * @param ctx The context
 * @param msg The message
 * @throws Exception For reasons unexplained
 */
@Override
@Overwrite
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
    ByteBuf m = (ByteBuf) msg;
    this.buf.writeBytes(m);
    m.release();

    this.buf.markReaderIndex();
    boolean result = false;

    try {
        result = readLegacy(ctx, this.buf);
    } finally {
        this.buf.resetReaderIndex();
        if (!result) {
            ByteBuf buf = this.buf;
            this.buf = null;

            ctx.pipeline().remove("legacy_query");
            ctx.fireChannelRead(buf);
        }
    }
}

From source file:org.spout.api.protocol.dynamicid.DynamicMessageDecoder.java

License:Open Source License

@Override
protected void decode(ChannelHandlerContext ctx, Message message, List<Object> out) throws Exception {
    Message unwrapped = message;/*from ww  w .  j  a  v  a  2  s .  c om*/
    Session session = ctx.pipeline().get(CommonHandler.class).getSession();
    if (session != null) {
        Protocol protocol = session.getProtocol();
        while (unwrapped instanceof DynamicWrapperMessage) {
            unwrapped = ((DynamicWrapperMessage) unwrapped).unwrap(protocol);
        }
    }
    if (unwrapped != null) {
        out.add(unwrapped);
    }
}

From source file:org.spout.api.protocol.dynamicid.DynamicMessageEncoder.java

License:Open Source License

@Override
protected void encode(ChannelHandlerContext ctx, Message o, List<Object> out) throws Exception {
    Session session = ctx.pipeline().get(CommonHandler.class).getSession();
    if (session != null) {
        Protocol protocol = session.getProtocol();
        MessageCodec<?> codec = protocol.getCodecLookupService().find(o.getClass());
        if (codec != null && codec.isDynamic()) {
            o = protocol.getWrappedMessage(o);
        }//from   ww  w  .j av a  2  s  . c o  m
    }
    out.add(o);
}

From source file:org.teiid.transport.SSLAwareChannelHandler.java

License:Apache License

@Override
public void channelActive(final ChannelHandlerContext ctx) throws Exception {
    ChannelListener listener = this.listenerFactory.createChannelListener(new ObjectChannelImpl(ctx.channel()));
    this.listeners.put(ctx.channel(), listener);
    maxChannels = Math.max(maxChannels, this.listeners.size());
    SslHandler sslHandler = ctx.pipeline().get(SslHandler.class);
    if (sslHandler != null) {
        sslHandler.handshakeFuture().addListener(new GenericFutureListener<DefaultPromise<Channel>>() {
            @Override//w  w w. j a v a  2 s.c o m
            public void operationComplete(DefaultPromise<Channel> future) throws Exception {
                onConnection(ctx.channel());

            }
        });
    } else {
        onConnection(ctx.channel());
    }
}

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

License:Apache License

@Override
protected void channelRead0(ChannelHandlerContext ctx, FileRequest req) throws Exception {

    Optional<String> uri = getSanitizedPath(req.getHeader().getUri().getPath());
    if (!uri.isPresent()) {
        HttpResponseHandler.sendError(ctx, HttpResponseStatus.FORBIDDEN, "Path is not available.");
        return;/*from  ww  w. j  a v a  2s.  co m*/
    }

    if (!this.redirects.isEmpty()) {
        for (Entry<Pattern, String> e : this.redirects.entrySet()) {
            if (e.getKey().matcher(uri.get()).matches()) {
                HttpResponseHandler.sendRedirect(ctx, createRedirectUrl(req.getHeader(), e.getValue()),
                        req.getHeader());
                break;
            }
        }
    }

    if (uri.get().endsWith("/")) {
        HttpResponseHandler.sendRedirect(ctx, uri.get() + "index.html", req.getHeader());
        return;
    }

    File file = null;
    if (webroot != null) {
        file = new File(webroot, uri.get());
    }
    //if ((!file.exists()) && "/index.html".equals(msg.getHeader().getUri().getPath())) {
    //    file = new File(sanitizeUri("/index.html"));
    //}

    RandomAccessFile raf = null;
    if (file == null || !file.exists() || file.isHidden() || file.isDirectory()) {
        raf = Loader.extractResource(uri.get());
        if (raf == null) {
            HttpResponseHandler.sendError(ctx, HttpResponseStatus.NOT_FOUND, "File not found.");
            return;
        }
    }

    if (file == null && raf == null) {
        HttpResponseHandler.sendError(ctx, HttpResponseStatus.NOT_FOUND, "File not found.");
        return;
    }

    if (raf == null && !file.isFile()) {
        HttpResponseHandler.sendError(ctx, HttpResponseStatus.FORBIDDEN, "Is not a file.");
        return;
    }

    String contentType = MIME_TYPES_MAP.getContentType(file.getPath());
    try {
        if (raf == null) {
            raf = new RandomAccessFile(file, "r");
        }
    } catch (FileNotFoundException ex) {
        HttpResponseHandler.sendError(ctx, HttpResponseStatus.NOT_FOUND, ex.getMessage());
        return;
    }
    //don't send apps
    //if ("application/octet-stream".equals(contentType)) {
    //    file = new File(sanitizeUri("/index.html"));
    //}

    // Cache Validation
    if (file.exists()) {
        Optional<String> ifModifiedSinceOpt = req.getHeader()
                .getProperty(HttpHeaderNames.IF_MODIFIED_SINCE.toString());
        if (ifModifiedSinceOpt.isPresent() && !Util.isEmpty(ifModifiedSinceOpt.get())) {
            SimpleDateFormat dateFormatter = new SimpleDateFormat(HTTP_DATE_FORMAT, Locale.US);
            Date ifModifiedSinceDate = dateFormatter.parse(ifModifiedSinceOpt.get());

            // Only compare up to the second because the datetime format we send to the client
            // does not have milliseconds
            long ifModifiedSinceDateSeconds = ifModifiedSinceDate.getTime() / 1000;
            long fileLastModifiedSeconds = file.lastModified() / 1000;
            if (ifModifiedSinceDateSeconds == fileLastModifiedSeconds) {
                sendNotModified(ctx);
                return;
            }
        }
    }

    long fileLength = raf.length();

    HttpResponse response = new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK);
    HttpUtil.setContentLength(response, fileLength);
    setContentTypeHeader(response, file);
    setDateAndCacheHeaders(response, file);
    if (isKeepAlive(req.getHeader())) {
        response.headers().set(HttpHeaderNames.CONNECTION, HttpHeaderNames.CONNECTION);
    }
    // Write the initial line and the header.
    ctx.write(response);
    // Write the content.
    ChannelFuture sendFileFuture;
    ChannelFuture lastContentFuture;
    if (ctx.pipeline().get(SslHandler.class) == null) {
        sendFileFuture = ctx.write(new DefaultFileRegion(raf.getChannel(), 0, fileLength),
                ctx.newProgressivePromise());
        // Write the end marker.
        lastContentFuture = ctx.writeAndFlush(LastHttpContent.EMPTY_LAST_CONTENT);
    } else {
        sendFileFuture = ctx.write(new HttpChunkedInput(new ChunkedFile(raf, 0, fileLength, 8192)),
                ctx.newProgressivePromise());
        // HttpChunkedInput will write the end marker (LastHttpContent) for us.
        lastContentFuture = sendFileFuture;
    }

}

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

License:Apache License

private void upgradeToWebsocket(ChannelHandlerContext ctx, FullHttpRequest httpRequest) {

    String wsUrl = "ws://" + httpRequest.headers().get(HttpHeaderNames.HOST) + "/" + endpointId;
    //todo: configure frame size
    WebSocketServerHandshakerFactory wsHandshakeFactory = new WebSocketServerHandshakerFactory(wsUrl, null,
            false);// w ww.  j a  v  a2s.c o  m
    WebSocketServerHandshaker handshaker = wsHandshakeFactory.newHandshaker(httpRequest);
    if (handshaker == null) {
        WebSocketServerHandshakerFactory.sendUnsupportedVersionResponse(ctx.channel());
    } else {
        handshaker.handshake(ctx.channel(), httpRequest)
                .addListener((ChannelFutureListener) new ChannelFutureListener() {
                    @Override
                    public void operationComplete(ChannelFuture future) throws Exception {
                        if (future.isSuccess()) {
                            logger.debug("Switching to websocket. Replacing the "
                                    + Endpoint.HTTP_RESPONSE_HANDLER + " with " + Endpoint.WS_RESPONSE_HANDLER);
                            ctx.pipeline().replace(Endpoint.HTTP_REQUEST_HANDLER, Endpoint.WS_REQUEST_HANDLER,
                                    new WebsocketRequestHandler(handshaker));
                            ctx.pipeline().replace(Endpoint.HTTP_RESPONSE_HANDLER, Endpoint.WS_RESPONSE_HANDLER,
                                    new WebsocketResponseHandler());
                            ctx.pipeline().addAfter(Endpoint.WS_RESPONSE_HANDLER, Endpoint.WS_COMMAND_HANDLER,
                                    new Command2WsEncoder());
                            if (ctx.pipeline().get(Endpoint.RESPONSE_INTROSPECTOR) != null) {
                                ctx.pipeline().addAfter(Endpoint.RESPONSE_INTROSPECTOR,
                                        Endpoint.WS_REQUEST_INTROSPECTOR, new WebsocketIntrospector());
                            }
                        } else {
                            String msg = "Dispatching upgrade acknowledgement was not successfull due to ";
                            if (future.cause() != null) {
                                logger.error(msg + future.cause().getClass().getSimpleName() + " with message: "
                                        + future.cause().getMessage(), future.cause());
                            } else {
                                logger.error(msg + " unknown reasons.");
                            }
                        }
                    }
                });
    }
}