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.atmosphere.nettosphere.HttpStaticFileServerHandler.java

License:Apache License

@Override
public void channelRead0(ChannelHandlerContext ctx, FullHttpRequest request) throws Exception {
    if (!request.getDecoderResult().isSuccess()) {
        sendError(ctx, BAD_REQUEST, request);
        return;/*w  w w .ja  v a 2  s.  com*/
    }

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

    File file = null;
    RandomAccessFile raf = null;
    boolean found = true;
    for (String p : paths) {
        String path = p + sanitizeUri(request.getUri());

        if (path.endsWith("/") || path.endsWith(File.separator)) {
            path += "index.html";
        }

        if (path.endsWith("/favicon.ico") || path.endsWith(File.separator)) {
            request.headers().add(SERVICED, "true");
            found = false;
            continue;
        }

        file = new File(path);
        if (file.isHidden() || !file.exists() || !file.isFile()) {
            found = false;
            continue;
        }

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

        try {
            raf = new RandomAccessFile(file, "r");
            found = true;
            break;
        } catch (FileNotFoundException ignore) {
            sendError(ctx, NOT_FOUND, request);
            return;
        }
    }

    if (!found) {
        sendError(ctx, NOT_FOUND, request);
        return;
    }
    request.headers().add(SERVICED, "true");

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

    long fileLength = raf.length();

    ctx.pipeline().addBefore(BridgeRuntime.class.getName(), "encoder", new HttpResponseEncoder());
    HttpResponse response = new DefaultHttpResponse(HTTP_1_1, OK);
    HttpHeaders.setContentLength(response, fileLength);
    contentType(request, 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;
    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.writeAndFlush(new HttpChunkedInput(new ChunkedFile(raf, 0, fileLength, 8192)),
                ctx.newProgressivePromise());
        // HttpChunkedInput will write the end marker (LastHttpContent) for us.
        lastContentFuture = sendFileFuture;
    }

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

        @Override
        public void operationComplete(ChannelProgressiveFuture future) {
            logger.trace(future.channel() + " Transfer complete.");
        }
    });

    // Close the connection when the whole content is written out.
    lastContentFuture.addListener(ChannelFutureListener.CLOSE);
}

From source file:org.ballerinalang.test.util.websocket.server.WebSocketHeadersHandler.java

License:Open Source License

@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
    log.error("Exception Caught: " + cause.getMessage());
    ctx.pipeline().remove(this);
    ctx.fireExceptionCaught(cause);//  w w  w . ja va  2 s  .  com
}

From source file:org.ballerinalang.test.util.websocket.server.WebSocketHeadersHandler.java

License:Open Source License

@Override
public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception {
    if (msg instanceof HttpResponse) {
        HttpResponse response = (HttpResponse) msg;
        response.headers().add("X-server-header", "server-header-value");
        promise.addListener(future -> ctx.pipeline().remove(ctx.name()));
    }//from  w w  w  .  jav a2 s.c  o  m
    super.write(ctx, msg, promise);
}

From source file:org.beaconmc.network.socket.pipeline.PacketLegacy.java

License:Open Source License

private void close(ChannelHandlerContext channelHandlerContext) {
    channelHandlerContext.pipeline().close();
}

From source file:org.beaconmc.network.socket.pipeline.PacketLegacy.java

License:Open Source License

private void sendPingAndClose(ChannelHandlerContext channelHandlerContext, ByteBuf byteBuf) {
    channelHandlerContext.pipeline().firstContext().writeAndFlush(byteBuf)
            .addListeners(ChannelFutureListener.CLOSE);
}

From source file:org.betawares.jorre.Server.java

License:Open Source License

/**
 * Starts the Server with the specified {@link Connection} settings.
 * /*www  . j  av  a 2 s . c o  m*/
 * @param connection  a {@link Connection} instance specifying the connection settings
 * 
 * @throws Exception  thrown if there is an error starting the server
 */
public void start(Connection connection) throws Exception {

    SslContext sslCtx;

    if (connection.isSSL()) {
        SelfSignedCertificate ssc = new SelfSignedCertificate();
        sslCtx = SslContextBuilder.forServer(ssc.certificate(), ssc.privateKey()).build();
    } else {
        sslCtx = null;
    }

    bossGroup = new NioEventLoopGroup();
    workerGroup = new NioEventLoopGroup();

    ServerBootstrap bootstrap = new ServerBootstrap();
    bootstrap.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
            .handler(new LoggingHandler(LogLevel.DEBUG)).childHandler(new ChannelInitializer<SocketChannel>() {
                @Override
                public void initChannel(SocketChannel ch) {
                    if (sslCtx != null) {
                        ch.pipeline().addLast(sslCtx.newHandler(ch.alloc()));
                    }
                    ch.pipeline()
                            .addLast(new ObjectDecoder(10 * 1024 * 1024, ClassResolvers.cacheDisabled(null)));
                    ch.pipeline().addLast(encoder);
                    ch.pipeline().addLast("idleStateHandler", new IdleStateHandler(connection.getIdleTimeout(),
                            connection.getIdlePingTime(), 0, TimeUnit.MILLISECONDS));
                    ch.pipeline().addLast(handlersExecutor, "heartbeatHandler",
                            new ServerHeartbeatHandler(Server.this));
                    ch.pipeline().addLast("pingMessageHandler", pingMessageHandler);
                    ch.pipeline().addLast("pongMessageHandler", pongMessageHandler);

                    ch.pipeline().addLast("connectionHandler", new ChannelInboundHandlerAdapter() {
                        @Override
                        public void channelActive(ChannelHandlerContext ctx) throws Exception {
                            clients.add(ctx.channel());
                            ctx.pipeline().remove(this);
                            super.channelActive(ctx);
                        }
                    });
                    ch.pipeline().addLast(handlersExecutor, "serverMessageHandler", serverRequestHandler);
                    ch.pipeline().addLast("exceptionHandler", exceptionHandler);
                }
            });
    bootstrap.bind(connection.getPort()).sync();

}

From source file:org.bridje.http.impl.HttpWsSwitch.java

License:Apache License

@Override
protected void decode(ChannelHandlerContext ctx, HttpObject msg, List<Object> out) {
    if (!added && msg instanceof HttpRequest) {
        String path = ((HttpRequest) msg).getUri();
        WsServerHandler handler = findHandler(path);
        if (handler != null) {
            ctx.pipeline().addAfter("switch", "aggregator", new HttpObjectAggregator(65536));
            ctx.pipeline().addAfter("aggregator", "wsprotocol",
                    new WebSocketServerProtocolHandler(path, null, true));
            ctx.pipeline().addAfter("wsprotocol", "wshandler", new WsFrameHandler(handler));
            added = true;/*from   ww  w .j a  v a 2 s . co  m*/
        }
    }
    ReferenceCountUtil.retain(msg);
    out.add(msg);
}

From source file:org.dcache.xrootd.core.XrootdAuthenticationHandler.java

License:Open Source License

private void authenticated(ChannelHandlerContext context, Subject subject) throws XrootdException {
    _session.setSubject(login(context, subject));
    _state = State.AUTH;/* ww w  .ja  v a 2  s .com*/

    if (_signingPolicy.isSigningOn()) {
        /*
         * Add the sigver decoder to the pipeline and remove the original
         * message decoder.
         */
        BufferDecrypter decrypter = _authenticationHandler.getDecrypter();
        context.pipeline().addAfter("decoder", "sigverDecoder",
                new XrootdSigverDecoder(_signingPolicy, decrypter));
        context.pipeline().remove("decoder");
        _log.trace("switched decoder to sigverDecoder, decrypter {}.", decrypter);
    }

    _authenticationHandler = null;
}

From source file:org.dcache.xrootd.plugins.authn.gsi.pre49.GSIPre49ClientRequestHandler.java

License:Open Source License

/**
 * The challenge cipher sent in the kXR_certreq step is sent back.
 *
 * The cipher is signed by the source's private key. We use the
 * included public key to verify it./*from   w ww.j a  v  a  2s.co m*/
 *
 * Then we sign the included challenge from the server, and
 * return it with our host cert (public key).
 */
public OutboundAuthenticationRequest handleCertStep(InboundAuthenticationResponse response,
        ChannelHandlerContext ctx) throws XrootdException {
    try {
        InboundResponseBuckets inbound = new InboundResponseBuckets(response, client);

        inbound.validateCiphers();
        inbound.validateDigests();
        inbound.validateCertificate();
        inbound.validateSignedChallenge();
        inbound.signChallenge();
        inbound.encodeHostCerts();
        inbound.finalizeDHSessionKey();

        SigningPolicy signingPolicy = client.getSigningPolicy();

        if (signingPolicy.isSigningOn()) {
            BufferEncrypter encrypter = new DHBufferHandler(inbound.session, SERVER_SYNC_CIPHER_MODE,
                    SERVER_SYNC_CIPHER_NAME, SERVER_SYNC_CIPHER_BLOCKSIZE);
            /*
             * Insert sigver encoder into pipeline.  Added after the encoder,
             * but for outbound processing, it gets called before the encoder.
             */
            TpcSigverRequestEncoder sigverRequestEncoder = new TpcSigverRequestEncoder(encrypter,
                    signingPolicy);

            ctx.pipeline().addAfter("encoder", "sigverEncoder", sigverRequestEncoder);
        }

        GSIBucketContainer container = new OutboundResponseBuckets(inbound, ctx).buildContainer();

        return new OutboundAuthenticationRequest(response.getStreamId(), container.getSize(), PROTOCOL,
                kXGC_cert, container.getBuckets());
    } catch (IOException e) {
        LOGGER.error("Problems during cert step {}." + e.getMessage() == null ? e.getClass().getName()
                : e.getMessage());
        throw new XrootdException(kXR_ServerError, "Internal error occurred during cert step.");
    } catch (InvalidKeyException e) {
        LOGGER.error("The key negotiated by DH key exchange appears to " + "be invalid: {}", e.getMessage());
        throw new XrootdException(kXR_InvalidRequest,
                "Could not decrypt server " + "information with negotiated key.");
    } catch (GeneralSecurityException e) {
        LOGGER.error("Cryptographic issues encountered during cert step: {}", e.getMessage());
        throw new XrootdException(kXR_ServerError,
                "Could not complete cert step: an error " + "occurred during " + "cryptographic operations.");
    }
}

From source file:org.dcache.xrootd.plugins.authn.unix.UnixClientAuthenticationHandler.java

License:Open Source License

@Override
protected void sendAuthenticationRequest(ChannelHandlerContext ctx) {
    /*/*from w  w  w  . jav a  2 s .  c o m*/
     * Insert sigver encoder into pipeline.  Added after the encoder,
     * but for outbound processing, it gets called before the encoder.
     */
    TpcSigverRequestEncoder sigverRequestEncoder = new TpcSigverRequestEncoder(null, client.getSigningPolicy());
    ctx.pipeline().addAfter("encoder", "sigverEncoder", sigverRequestEncoder);

    Map<BucketType, XrootdBucket> nestedBuckets = new EnumMap<>(BucketType.class);
    StringBucket unameBucket = new StringBucket(kXRS_creds, client.getUname());
    nestedBuckets.put(unameBucket.getType(), unameBucket);
    NestedBucketBuffer mainBucket = new NestedBucketBuffer(kXRS_main, PROTOCOL, kXGC_cert, nestedBuckets);
    OutboundAuthenticationRequest request = new OutboundAuthenticationRequest(client.getStreamId(),
            mainBucket.getSize(), PROTOCOL, kXGC_cert, Collections.singletonList(mainBucket));
    client.setExpectedResponse(kXR_auth);
    client.setAuthResponse(null);
    ctx.writeAndFlush(request, ctx.newPromise()).addListener(FIRE_EXCEPTION_ON_FAILURE);
}