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:com.xx_dev.apn.socks.test.SocksClientHandler.java

License:Apache License

@Override
protected void channelRead0(ChannelHandlerContext ctx, SocksResponse socksResponse) throws Exception {
    switch (socksResponse.responseType()) {
    case INIT: {//from  w w w. j av a  2s. c om
        ctx.pipeline().addAfter("log", "cmdResponseDecoder", new SocksCmdResponseDecoder());
        ctx.write(new SocksCmdRequest(SocksCmdType.CONNECT, SocksAddressType.DOMAIN, "www.baidu.com", 80));
        break;
    }
    case AUTH:
        ctx.pipeline().addAfter("log", "cmdResponseDecoder", new SocksCmdResponseDecoder());
        ctx.write(new SocksCmdRequest(SocksCmdType.CONNECT, SocksAddressType.DOMAIN, "www.baidu.com", 80));
        break;
    case CMD:
        SocksCmdResponse res = (SocksCmdResponse) socksResponse;
        if (res.cmdStatus() == SocksCmdStatus.SUCCESS) {
            ctx.pipeline().addLast(new SocksClientConnectHandler());
            ctx.pipeline().remove(this);
            //ctx.fireChannelRead(socksResponse);

            String s = "GET / HTTP/1.1\r\nHOST: www.baidu.com\r\n\r\n";

            ctx.writeAndFlush(Unpooled.copiedBuffer(s, CharsetUtil.UTF_8));
        } else {
            ctx.close();
        }
        break;
    case UNKNOWN:
        ctx.close();
        break;
    }
}

From source file:com.zaradai.distributor.messaging.netty.handler.AbstractHandshakeHandler.java

License:Apache License

private void removeFromPipeline(ChannelHandlerContext handlerContext) {
    LOGGER.debug("Handshake done removing from pipeline");
    handlerContext.pipeline().remove(this);
}

From source file:com.zaradai.distributor.messaging.netty.handler.ConnectionAuthenticatorHandler.java

License:Apache License

@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
    InetSocketAddress address = (InetSocketAddress) ctx.channel().remoteAddress();
    // no more needed
    ctx.pipeline().remove(this);

    if (address != null) {
        if (authenticator.authenticate(address)) {
            accepted(ctx, address);/*  w  ww. jav  a  2  s  .  c o m*/
        } else {
            rejected(ctx, address);
        }
    } else {
        // No remote address so this is a local connection, assume authenticated??
        LOGGER.debug("Remote address is invalid, unable to authenticate");
    }

    super.channelActive(ctx);
}

From source file:com.zextras.modules.chat.server.xmpp.netty.FirstTags.java

License:Open Source License

@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) {
    String xmlTag = (String) msg;
    ChatLog.log.debug("FirstTags: " + xmlTag);

    if (xmlTag.startsWith("<?xml")) {
        //TODO: parse new charset
        Charset newCharset = Charset.forName("UTF-8");

        ctx.pipeline().replace("SubTagTokenizer", "SubTagTokenizer", new XmlSubTagTokenizer(newCharset));
    } else {/*  ww w  .  j  av a2  s  .c om*/
        if (xmlTag.trim().startsWith("<stream:stream")) {
            ctx.pipeline().addLast("XmlTagTokenizer", new XmlTagTokenizer());

            ctx.pipeline().addLast("StanzaProcessor",
                    new StanzaProcessor(mXmppHandlerFactory, mEventManager, mSocketChannel, mSchemaProvider,
                            mZimbraSSLContext, mSsl, mChatProperties, mNettyService, mProxyAuthRequestEncoder,
                            mXmppEventFilter, mXmppFilterOut));
            ctx.fireChannelRead(xmlTag);
            // ctx.fireChannelRead("</stream:stream>");
            ctx.pipeline().remove("FirstTags");
        } else {
            throw new RuntimeException("Invalid first xml tag: " + xmlTag);
        }
    }
}

From source file:connection.bootstrap.Handler.java

@Override
public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
    Channel incomming = ctx.channel();
    final SslHandler sslHandler = ctx.pipeline().get(SslHandler.class);
    System.out.println("Attempting handshake");
    sslHandler.handshakeFuture().addListener(new Authentication(sslHandler));
}

From source file:connexion.ServerHandler.java

@Override
public void channelActive(final ChannelHandlerContext ctx) {
    // Once session is secured, send a greeting and register the channel to the global channel
    // list so the channel received the messages from others.
    ctx.pipeline().get(SslHandler.class).handshakeFuture()
            .addListener(new GenericFutureListener<Future<Channel>>() {
                @Override//from w w w. ja  v a2  s .co  m
                public void operationComplete(Future<Channel> future) throws Exception {
                    ctx.writeAndFlush("");

                    channels.add(ctx.channel());
                }
            });
}

From source file:cyril.server.io.AuthHandler.java

License:Open Source License

/**
 * Handles and compares the incoming token. Automatically switches to
 * "discard mode" to be more efficient without revealing the fact that a
 * wrong byte has been encountered.<br />
 * If the transmission of the token is complete (and both tokens match), the
 * login process is complete. The next handler is automatically called, and
 * this handler is dislodged from the channel.
 * //from   w  w  w  .  j  av  a  2s.  co m
 * @param ctx
 *            The current context
 * @param in
 *            The buffer to read from (guaranteed to have at least one
 *            readable byte)
 * @return whether further processing may happen
 */
private boolean handleIncomingToken(ChannelHandlerContext ctx, ByteBuf in) {
    // This *does* work with 0 length tokens, but only if the next packet
    // starts right away.
    // This doesn't pose a security threat -- if you ever hand out 0 byte
    // tokens, there's no security anymore that could be threatened.

    int checkable = Math.min(login.token.length - index, in.readableBytes());
    for (; checkable > 0; checkable--) {
        if (login.token[index] != in.readByte()) {
            paketState = PaketPosition.DECLINED_WAIT;
            break;
        }
        index++;
    }

    if (index >= login.token.length) {
        // Token is correct!
        // Dispensing product
        killTask.cancel(false);
        paketState = PaketPosition.AUTHENTICATED;
        listener.stateChanged(ctx.channel(), ConnectionState.GOOD_AUTH);
        service.handleNewSession(ctx.channel(), login);
        ctx.pipeline().remove(this);
    }

    return false;
}

From source file:cyril.server.io.SpamHandler.java

License:Open Source License

@Override
public void inboundBufferUpdated(ChannelHandlerContext ctx, ByteBuf in) throws IOException {
    SpamState s = spamState.getAndSet(null);

    if (s == null) {
        // KillTask has just triggered, ignore
        return;//from   w w  w .  j  a  v a2  s  . c o  m
    }

    if (in.readableBytes() < s.getExpectedLength()) {
        // Ignore, not enough bytes
        spamState.set(s);
        return;
    }

    final SocketChannel ch = (SocketChannel) ctx.channel();

    if (!s.isBufOkay(in)) {
        // Connection has to be aborted, client sent wrong data
        listener.stateChanged(ch, ConnectionState.WRONG_DATA);
        ch.close();
        return;
    }

    // Buf was okay, go to the next state:
    switch (s.getConnectionState()) {
    case START:
        s = SPAM_MAGIC;
        break;
    case FIRST_BYTE:
        // TODO: Correct buffer? Size? Usage?
        s = new SpamInteraction(ctx.nextOutboundByteBuffer());
        break;
    case GOOD_MAGIC:
        s = null;
        break;
    default: // Bad. Disconnect, so if it happens too often,
        // the server admin will notice.
        listener.stateChanged(ch, ConnectionState.WRONG_DATA);
        ch.close();
        return;
    }

    if (s != null) {
        // Stay in this handler
        spamState.set(s);
        listener.stateChanged(ch, s.getConnectionState());
        prepareFor(ctx, s);
        return;
    }

    // Help GC
    spamState.set(null);
    try {
        next.initChannel(ch);
    } catch (Exception e) {
        throw new IOException("Could not initialize next stage", e);
    } finally {
        ctx.pipeline().remove(this);
    }
}

From source file:de.cubeisland.engine.core.webapi.HttpRequestHandler.java

License:Open Source License

@Override
protected void channelRead0(ChannelHandlerContext ctx, FullHttpRequest message) throws Exception {
    InetSocketAddress inetSocketAddress = (InetSocketAddress) ctx.channel().remoteAddress();
    this.log.info("{} connected...", inetSocketAddress.getAddress().getHostAddress());
    if (!this.server.isAddressAccepted(inetSocketAddress.getAddress())) {
        this.log.info("Access denied!");
        ctx.channel().close();/*from w ww  .j  a v  a2s .c om*/
    }

    if (message.getDecoderResult().isFailure()) {
        this.error(ctx, UNKNOWN_ERROR);
        this.log.info(message.getDecoderResult().cause(), "The decoder failed on this request...");
        return;
    }

    boolean authorized = this.server.isAuthorized(inetSocketAddress.getAddress());
    QueryStringDecoder qsDecoder = new QueryStringDecoder(message.getUri(), this.UTF8, true, 100);
    final Parameters params = new Parameters(qsDecoder.parameters(),
            core.getCommandManager().getProviderManager());
    User authUser = null;
    if (!authorized) {
        if (!core.getModuleManager().getServiceManager().isImplemented(Permission.class)) {
            this.error(ctx, AUTHENTICATION_FAILURE, new ApiRequestException("Authentication deactivated", 200));
            return;
        }
        String user = params.get("user", String.class);
        String pass = params.get("pass", String.class);
        if (user == null || pass == null) {
            this.error(ctx, AUTHENTICATION_FAILURE,
                    new ApiRequestException("Could not complete authentication", 200));
            return;
        }
        User exactUser = core.getUserManager().findExactUser(user);
        if (exactUser == null || !exactUser.isPasswordSet()
                || !CubeEngine.getUserManager().checkPassword(exactUser, pass)) {
            this.error(ctx, AUTHENTICATION_FAILURE,
                    new ApiRequestException("Could not complete authentication", 200));
            return;
        }
        authUser = exactUser;
    }
    String path = qsDecoder.path().trim();
    if (path.length() == 0 || "/".equals(path)) {
        this.error(ctx, ROUTE_NOT_FOUND);
        return;
    }
    path = normalizePath(path);

    // is this request intended to initialize a websockets connection?
    if (WEBSOCKET_ROUTE.equals(path)) {
        WebSocketRequestHandler handler;
        if (!(ctx.pipeline().last() instanceof WebSocketRequestHandler)) {
            handler = new WebSocketRequestHandler(core, server, objectMapper, authUser);
            ctx.pipeline().addLast("wsEncoder", new TextWebSocketFrameEncoder(objectMapper));
            ctx.pipeline().addLast("handler", handler);
        } else {
            handler = (WebSocketRequestHandler) ctx.pipeline().last();
        }
        this.log.info("received a websocket request...");
        handler.doHandshake(ctx, message);
        return;
    }

    this.handleHttpRequest(ctx, message, path, params, authUser);
}

From source file:de.eightnine.rec.HttpStaticFileServerHandler.java

License:Apache License

@Override
public void channelRead0(ChannelHandlerContext ctx, FullHttpRequest request) throws Exception {
    if (!request.getDecoderResult().isSuccess()) {
        sendError(ctx, BAD_REQUEST);/*ww w .j a  va  2 s . c  o  m*/
        return;
    }

    if (request.getMethod() != GET) {
        sendError(ctx, METHOD_NOT_ALLOWED);
        return;
    }

    final String uri = request.getUri();
    final String path = sanitizeUri(uri);
    if (path == null) {
        sendError(ctx, FORBIDDEN);
        return;
    }

    File file = new File(path);
    if (file.isHidden() || !file.exists()) {
        sendError(ctx, NOT_FOUND);
        return;
    }

    if (file.isDirectory()) {
        if (uri.endsWith("/")) {
            sendListing(ctx, file);
        } else {
            sendRedirect(ctx, uri + '/');
        }
        return;
    }

    if (!file.isFile()) {
        sendError(ctx, FORBIDDEN);
        return;
    }

    // Cache Validation
    String ifModifiedSince = request.headers().get(IF_MODIFIED_SINCE);
    if (ifModifiedSince != null && !ifModifiedSince.isEmpty()) {
        SimpleDateFormat dateFormatter = new SimpleDateFormat(HTTP_DATE_FORMAT, Locale.US);
        Date ifModifiedSinceDate = dateFormatter.parse(ifModifiedSince);

        // 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;
        }
    }

    RandomAccessFile raf;
    try {
        raf = new RandomAccessFile(file, "r");
    } catch (FileNotFoundException ignore) {
        sendError(ctx, NOT_FOUND);
        return;
    }
    long fileLength = raf.length();

    HttpResponse response = new DefaultHttpResponse(HTTP_1_1, OK);
    HttpHeaders.setContentLength(response, fileLength);
    setContentTypeHeader(response, file);
    setDateAndCacheHeaders(response, file);
    if (HttpHeaders.isKeepAlive(request)) {
        response.headers().set(CONNECTION, HttpHeaders.Values.KEEP_ALIVE);
    }

    // Write the initial line and the header.
    ctx.write(response);

    // Write the content.
    ChannelFuture sendFileFuture;
    if (ctx.pipeline().get(SslHandler.class) == null) {
        sendFileFuture = ctx.write(new DefaultFileRegion(raf.getChannel(), 0, fileLength),
                ctx.newProgressivePromise());
    } else {
        sendFileFuture = ctx.write(new HttpChunkedInput(new ChunkedFile(raf, 0, fileLength, 8192)),
                ctx.newProgressivePromise());
    }

    sendFileFuture.addListener(new ChannelProgressiveFutureListener() {
        @Override
        public void operationProgressed(ChannelProgressiveFuture future, long progress, long total) {
            if (total < 0) { // total unknown
                System.err.println(future.channel() + " Transfer progress: " + progress);
            } else {
                System.err.println(future.channel() + " Transfer progress: " + progress + " / " + total);
            }
        }

        @Override
        public void operationComplete(ChannelProgressiveFuture future) {
            System.err.println(future.channel() + " Transfer complete.");
        }
    });

    // Write the end marker
    ChannelFuture lastContentFuture = ctx.writeAndFlush(LastHttpContent.EMPTY_LAST_CONTENT);

    // Decide whether to close the connection or not.
    if (!HttpHeaders.isKeepAlive(request)) {
        // Close the connection when the whole content is written out.
        lastContentFuture.addListener(ChannelFutureListener.CLOSE);
    }
}