Example usage for io.netty.util.concurrent GenericFutureListener GenericFutureListener

List of usage examples for io.netty.util.concurrent GenericFutureListener GenericFutureListener

Introduction

In this page you can find the example usage for io.netty.util.concurrent GenericFutureListener GenericFutureListener.

Prototype

GenericFutureListener

Source Link

Usage

From source file:org.waarp.ftp.core.data.handler.ftps.FtpsTemporaryFirstHandler.java

License:Open Source License

@Override
public void channelActive(final ChannelHandlerContext ctx) throws Exception {
    // Get the SslHandler in the current pipeline.
    Channel channel = ctx.channel();

    if (session == null) {
        setSession(channel);/*from w w  w  .ja v a 2 s . c o  m*/
    }
    if (session == null) {
        logger.error("Cannot find session for SSL");
        return;
    }
    // Server: no renegotiation still, but possible clientAuthent
    // Mode is always as SSL Server mode.
    SslHandler sslHandler = FtpsInitializer.waarpSslContextFactory.initInitializer(true,
            FtpsInitializer.waarpSslContextFactory.needClientAuthentication(),
            FtpChannelUtils.getRemoteInetSocketAddress(session.getControlChannel()).getAddress()
                    .getHostAddress(),
            FtpChannelUtils.getRemoteInetSocketAddress(session.getControlChannel()).getPort());
    WaarpSslUtility.addSslOpenedChannel(channel);
    // Get the SslHandler and begin handshake ASAP.
    logger.debug("SSL found but need handshake: " + ctx.channel().toString());
    final FtpsTemporaryFirstHandler myself = this;
    WaarpSslUtility.addSslHandler(null, ctx.pipeline(), sslHandler,
            new GenericFutureListener<Future<? super Channel>>() {
                public void operationComplete(Future<? super Channel> future) throws Exception {
                    logger.debug("Handshake: " + future.isSuccess() + ":" + ((Channel) future.get()).toString(),
                            future.cause());
                    if (future.isSuccess()) {
                        logger.debug("End of initialization of SSL and data channel");
                        myself.superChannelActive(ctx);
                        ctx.pipeline().remove(myself);
                    } else {
                        ctx.close();
                    }
                }
            });
}

From source file:org.waarp.openr66.protocol.localhandler.LocalServerHandler.java

License:Open Source License

@Override
protected void channelRead0(final ChannelHandlerContext ctx, AbstractLocalPacket msg) throws Exception {
    // action as requested and answer if necessary
    final AbstractLocalPacket packet = msg;
    if (packet.getType() == LocalPacketFactory.STARTUPPACKET) {
        serverHandler.startup(ctx.channel(), (StartupPacket) packet);
    } else {//from  w  w w  .j  a va2 s . c o m
        if (serverHandler.getLocalChannelReference() == null) {
            logger.error("No LocalChannelReference at " + packet.getClass().getName());
            serverHandler.getSession().newState(ERROR);
            final ErrorPacket errorPacket = new ErrorPacket(
                    "No LocalChannelReference at " + packet.getClass().getName(),
                    ErrorCode.ConnectionImpossible.getCode(), ErrorPacket.FORWARDCLOSECODE);
            ctx.channel().writeAndFlush(errorPacket).addListener(ChannelFutureListener.CLOSE);
            if (Configuration.configuration.getR66Mib() != null) {
                Configuration.configuration.getR66Mib().notifyWarning("No LocalChannelReference",
                        packet.getClass().getSimpleName());
            }
            packet.clear();
            return;
        }
        switch (packet.getType()) {
        case LocalPacketFactory.AUTHENTPACKET: {
            serverHandler.authent(ctx.channel(), (AuthentPacket) packet);
            break;
        }
        // Already done case LocalPacketFactory.STARTUPPACKET:
        case LocalPacketFactory.DATAPACKET: {
            if (((DataPacket) packet).getPacketRank() % 100 == 1
                    || serverHandler.getSession().getState() != R66FiniteDualStates.DATAR) {
                serverHandler.getSession().newState(DATAR);
                logger.debug("DATA RANK: " + ((DataPacket) packet).getPacketRank() + " : "
                        + serverHandler.getSession().getRunner().getRank());
            }
            serverHandler.data(ctx.channel(), (DataPacket) packet);
            break;
        }
        case LocalPacketFactory.VALIDPACKET: {
            // SHUTDOWNPACKET does not need authentication
            if (((ValidPacket) packet).getTypeValid() != LocalPacketFactory.SHUTDOWNPACKET
                    && (!serverHandler.getSession().isAuthenticated())) {
                logger.warn("Valid packet received while not authenticated: {} {}", packet,
                        serverHandler.getSession());
                serverHandler.getSession().newState(ERROR);
                packet.clear();
                throw new OpenR66ProtocolNotAuthenticatedException("Not authenticated while Valid received");
            }
            if (((ValidPacket) packet).getTypeValid() == LocalPacketFactory.REQUESTPACKET) {
                String[] fields = ((ValidPacket) packet).getSmiddle()
                        .split(PartnerConfiguration.BAR_SEPARATOR_FIELD);
                String newfilename = fields[0];
                // potential file size changed
                long newSize = -1;
                String newFileInfo = null;
                if (fields.length > 1) {
                    try {
                        newSize = Long.parseLong(fields[1]);
                        // potential fileInfo changed
                        if (fields.length > 2) {
                            newFileInfo = fields[2];
                        }
                    } catch (NumberFormatException e2) {
                        newfilename += PartnerConfiguration.BAR_SEPARATOR_FIELD + fields[1];
                        newSize = -1;
                    }
                }
                if (newFileInfo != null
                        && !newFileInfo.equals(serverHandler.session.getRunner().getFileInformation())) {
                    serverHandler.requestChangeFileInfo(ctx.channel(), newFileInfo);
                }
                serverHandler.requestChangeNameSize(ctx.channel(), newfilename, newSize);
                packet.clear();
            } else {
                serverHandler.valid(ctx.channel(), (ValidPacket) packet);
            }
            break;
        }
        case LocalPacketFactory.ERRORPACKET: {
            serverHandler.getSession().newState(ERROR);
            serverHandler.errorMesg(ctx.channel(), (ErrorPacket) packet);
            break;
        }
        case LocalPacketFactory.CONNECTERRORPACKET: {
            serverHandler.connectionError(ctx.channel(), (ConnectionErrorPacket) packet);
            break;
        }
        case LocalPacketFactory.REQUESTPACKET: {
            serverHandler.request((LocalChannel) ctx.channel(), (RequestPacket) packet);
            break;
        }
        case LocalPacketFactory.SHUTDOWNPACKET: {
            serverHandler.getSession().newState(SHUTDOWN);
            serverHandler.shutdown(ctx.channel(), (ShutdownPacket) packet);
            break;
        }
        case LocalPacketFactory.STOPPACKET:
        case LocalPacketFactory.CANCELPACKET:
        case LocalPacketFactory.CONFIMPORTPACKET:
        case LocalPacketFactory.CONFEXPORTPACKET:
        case LocalPacketFactory.BANDWIDTHPACKET: {
            logger.error("Unimplemented Mesg: " + packet.getClass().getName());
            serverHandler.getSession().newState(ERROR);
            serverHandler.getLocalChannelReference()
                    .invalidateRequest(new R66Result(new OpenR66ProtocolSystemException("Not implemented"),
                            serverHandler.getSession(), true, ErrorCode.Unimplemented, null));
            final ErrorPacket errorPacket = new ErrorPacket(
                    "Unimplemented Mesg: " + packet.getClass().getName(), ErrorCode.Unimplemented.getCode(),
                    ErrorPacket.FORWARDCLOSECODE);
            ChannelUtils.writeAbstractLocalPacket(serverHandler.getLocalChannelReference(), errorPacket, true)
                    .addListener(new GenericFutureListener<Future<? super Void>>() {
                        public void operationComplete(Future<? super Void> future) throws Exception {
                            ctx.close();
                        }
                    });
            packet.clear();
            break;
        }
        case LocalPacketFactory.TESTPACKET: {
            serverHandler.getSession().newState(TEST);
            serverHandler.test(ctx.channel(), (TestPacket) packet);
            break;
        }
        case LocalPacketFactory.ENDTRANSFERPACKET: {
            serverHandler.endTransfer(ctx.channel(), (EndTransferPacket) packet);
            break;
        }
        case LocalPacketFactory.INFORMATIONPACKET: {
            serverHandler.getSession().newState(INFORMATION);
            serverHandler.information(ctx.channel(), (InformationPacket) packet);
            break;
        }
        case LocalPacketFactory.ENDREQUESTPACKET: {
            serverHandler.endRequest(ctx.channel(), (EndRequestPacket) packet);
            break;
        }
        case LocalPacketFactory.BUSINESSREQUESTPACKET: {
            serverHandler.businessRequest(ctx.channel(), (BusinessRequestPacket) packet);
            break;
        }
        case LocalPacketFactory.BLOCKREQUESTPACKET: {
            serverHandler.blockRequest(ctx.channel(), (BlockRequestPacket) packet);
            break;
        }
        case LocalPacketFactory.JSONREQUESTPACKET: {
            if (!serverHandler.getSession().isAuthenticated()) {
                logger.warn("JsonCommand packet received while not authenticated: {} {}", packet,
                        serverHandler.getSession());
                serverHandler.getSession().newState(ERROR);
                throw new OpenR66ProtocolNotAuthenticatedException("Not authenticated while Valid received");
            }
            JsonPacket json = ((JsonCommandPacket) packet).getJsonRequest();
            if (json == null) {
                ErrorCode code = ErrorCode.CommandNotFound;
                R66Result resulttest = new R66Result(serverHandler.getSession(), true, code,
                        serverHandler.getSession().getRunner());
                json = new JsonPacket();
                json.setComment("Invalid command");
                json.setRequestUserPacket(((JsonCommandPacket) packet).getTypeValid());
                JsonCommandPacket valid = new JsonCommandPacket(json, resulttest.getCode().getCode(),
                        LocalPacketFactory.REQUESTUSERPACKET);
                resulttest.setOther(packet);
                serverHandler.getLocalChannelReference().validateRequest(resulttest);
                try {
                    ChannelUtils.writeAbstractLocalPacket(serverHandler.getLocalChannelReference(), valid,
                            true);
                } catch (OpenR66ProtocolPacketException e2) {
                }
                serverHandler.getSession().setStatus(99);
                ctx.channel().close();
                return;
            }
            json.setRequestUserPacket(((JsonCommandPacket) packet).getTypeValid());
            if (((JsonCommandPacket) packet).getTypeValid() == LocalPacketFactory.REQUESTPACKET) {
                RequestJsonPacket node = (RequestJsonPacket) json;
                String newfilename = node.getFilename();
                if (newfilename == null) {
                    // error so ignore
                    return;
                }
                long newSize = node.getFilesize();
                String newFileInfo = node.getFileInfo();
                logger.debug("NewSize " + newSize + " NewName " + newfilename);
                // potential fileInfo changed
                if (newFileInfo != null
                        && !newFileInfo.equals(serverHandler.session.getRunner().getFileInformation())) {
                    logger.debug(
                            "NewSize " + newSize + " NewName " + newfilename + " newFileInfo: " + newFileInfo);
                    serverHandler.requestChangeFileInfo(ctx.channel(), newFileInfo);
                }
                // potential file size changed
                serverHandler.requestChangeNameSize(ctx.channel(), newfilename, newSize);
            } else {
                serverHandler.jsonCommand(ctx.channel(), (JsonCommandPacket) packet);
            }
            break;
        }
        default: {
            logger.error("Unknown Mesg: " + packet.getClass().getName());
            serverHandler.getSession().newState(ERROR);
            serverHandler.getLocalChannelReference()
                    .invalidateRequest(new R66Result(new OpenR66ProtocolSystemException("Unknown Message"),
                            serverHandler.getSession(), true, ErrorCode.Unimplemented, null));
            final ErrorPacket errorPacket = new ErrorPacket("Unkown Mesg: " + packet.getClass().getName(),
                    ErrorCode.Unimplemented.getCode(), ErrorPacket.FORWARDCLOSECODE);
            ChannelUtils.writeAbstractLocalPacket(serverHandler.getLocalChannelReference(), errorPacket, true)
                    .addListener(new GenericFutureListener<Future<? super Void>>() {
                        public void operationComplete(Future<? super Void> future) throws Exception {
                            ctx.close();
                        }
                    });
            packet.clear();
        }
        }
    }
}

From source file:org.waarp.openr66.protocol.networkhandler.ssl.NetworkSslServerHandler.java

License:Open Source License

@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
    Channel networkChannel = ctx.channel();
    logger.debug("Add channel to ssl");
    WaarpSslUtility.addSslOpenedChannel(networkChannel);
    isSSL = true;//  w  w  w .j a  va2 s .  c  o  m
    // Check first if allowed
    if (NetworkTransaction.isBlacklisted(networkChannel)) {
        logger.warn("Connection refused since Partner is in BlackListed from "
                + networkChannel.remoteAddress().toString());
        isBlackListed = true;
        if (Configuration.configuration.getR66Mib() != null) {
            Configuration.configuration.getR66Mib().notifyError("Black Listed connection temptative",
                    "During Handshake");
        }
        // close immediately the connection
        WaarpSslUtility.closingSslChannel(networkChannel);
        return;
    }
    // Get the SslHandler in the current pipeline.
    // We added it in NetworkSslServerInitializer.
    final ChannelHandler handler = ctx.pipeline().first();
    if (handler instanceof SslHandler) {
        final SslHandler sslHandler = (SslHandler) handler;
        sslHandler.handshakeFuture().addListener(new GenericFutureListener<Future<? super Channel>>() {
            public void operationComplete(Future<? super Channel> future) throws Exception {
                if (!future.isSuccess()) {
                    if (Configuration.configuration.getR66Mib() != null) {
                        Configuration.configuration.getR66Mib().notifyError("SSL Connection Error",
                                "During Handshake");
                    }
                }
            }
        });
    } else {
        logger.error("SSL Not found");
    }
    super.channelActive(ctx);
}

From source file:org.waarp.openr66.proxy.network.ssl.NetworkSslServerHandler.java

License:Open Source License

@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
    Channel channel = ctx.channel();
    logger.debug("Add channel to ssl");
    WaarpSslUtility.addSslOpenedChannel(channel);
    isSSL = true;/*w  w w.  ja  va  2s.  c  om*/
    // Get the SslHandler in the current pipeline.
    // We added it in NetworkSslServerInitializer.
    final ChannelHandler handler = ctx.pipeline().first();
    if (handler instanceof SslHandler) {
        final SslHandler sslHandler = (SslHandler) handler;
        sslHandler.handshakeFuture().addListener(new GenericFutureListener<Future<? super Channel>>() {
            public void operationComplete(Future<? super Channel> future) throws Exception {
                if (!future.isSuccess()) {
                    if (Configuration.configuration.getR66Mib() != null) {
                        Configuration.configuration.getR66Mib().notifyError("SSL Connection Error",
                                "During Handshake");
                    }
                }
            }
        });
    } else {
        logger.error("SSL Not found");
    }
    super.channelActive(ctx);
}

From source file:org.wso2.carbon.http2.transport.util.Http2ConnectionFactory.java

License:Open Source License

/**
 * Create new connection and return client handler
 *
 * @param uri/*from  w w  w  . j  av a  2 s  .c  o  m*/
 * @return Http2ClientHandler
 * @throws AxisFault
 */
private Http2ClientHandler cacheNewConnection(HttpHost uri) throws AxisFault {

    final SslContext sslCtx;
    final boolean SSL;
    if (uri.getSchemeName().equalsIgnoreCase("https")) {
        SSL = true;
    } else
        SSL = false;
    try {
        // Handling SSL
        if (SSL) {
            Parameter trustParam = trasportOut.getParameter(Http2Constants.TRUST_STORE_CONFIG_ELEMENT);
            OMElement tsEle = null;
            if (trustParam != null) {
                tsEle = trustParam.getParameterElement();
            }
            final String location = tsEle.getFirstChildWithName(new QName(Http2Constants.TRUST_STORE_LOCATION))
                    .getText();
            final String storePassword = tsEle
                    .getFirstChildWithName(new QName(Http2Constants.TRUST_STORE_PASSWORD)).getText();

            SslProvider provider = OpenSsl.isAlpnSupported() ? SslProvider.OPENSSL : SslProvider.JDK;
            sslCtx = SslContextBuilder.forClient()
                    .trustManager(SSLUtil.createTrustmanager(location, storePassword)).sslProvider(provider)
                    .ciphers(Http2SecurityUtil.CIPHERS, SupportedCipherSuiteFilter.INSTANCE)
                    .trustManager(InsecureTrustManagerFactory.INSTANCE)
                    .applicationProtocolConfig(
                            new ApplicationProtocolConfig(ApplicationProtocolConfig.Protocol.ALPN,
                                    ApplicationProtocolConfig.SelectorFailureBehavior.NO_ADVERTISE,
                                    ApplicationProtocolConfig.SelectedListenerFailureBehavior.ACCEPT,
                                    ApplicationProtocolNames.HTTP_2, ApplicationProtocolNames.HTTP_1_1))
                    .build();
        } else {
            sslCtx = null;
        }
        Http2ClientInitializer initializer = new Http2ClientInitializer(sslCtx, Integer.MAX_VALUE);

        String HOST = uri.getHostName();
        Integer PORT = uri.getPort();
        // Configure the client.
        Bootstrap b = new Bootstrap();
        b.group(workerGroup);
        b.channel(NioSocketChannel.class);
        b.option(ChannelOption.SO_KEEPALIVE, true);
        b.remoteAddress(HOST, PORT);
        b.handler(initializer);
        // Start the client.
        Channel channel = b.connect().syncUninterruptibly().channel();

        log.debug("Connected to [" + HOST + ':' + PORT + ']');

        Http2SettingsHandler http2SettingsHandler = initializer.settingsHandler();
        http2SettingsHandler.awaitSettings(5, TimeUnit.SECONDS);

        final String key = generateKey(URI.create(uri.toURI()));
        Http2ClientHandler handler = initializer.responseHandler();

        clientConnections.put(key, handler);

        channel.closeFuture().addListener(new GenericFutureListener<Future<? super Void>>() {
            @Override
            public void operationComplete(Future<? super Void> future) throws Exception {
                clientConnections.remove(key);
            }
        });
        return initializer.responseHandler();
    } catch (SSLException e) {
        throw new AxisFault("Error while connection establishment:", e);
    } catch (Exception e) {
        throw new AxisFault("Error while connection establishment:" + e);
    }
}

From source file:org.wso2.carbon.transport.http.netty.contractimpl.websocket.message.WebSocketInitMessageImpl.java

License:Open Source License

private HandshakeFuture handleHandshake(WebSocketServerHandshaker handshaker, int idleTimeout) {
    HandshakeFutureImpl handshakeFuture = new HandshakeFutureImpl();

    if (isCancelled) {
        Throwable e = new IllegalAccessException("Handshake is already cancelled!");
        handshakeFuture.notifyError(e);/*from  w w  w .j  av a 2  s  . c om*/
        return handshakeFuture;
    }

    try {
        ChannelFuture future = handshaker.handshake(ctx.channel(), httpRequest);
        handshakeFuture.setChannelFuture(future);
        future.addListener(new GenericFutureListener<Future<? super Void>>() {
            @Override
            public void operationComplete(Future<? super Void> future) throws Exception {
                String selectedSubProtocol = handshaker.selectedSubprotocol();
                webSocketSourceHandler.setNegotiatedSubProtocol(selectedSubProtocol);
                setSubProtocol(selectedSubProtocol);
                WebSocketSessionImpl session = (WebSocketSessionImpl) getChannelSession();
                session.setIsOpen(true);
                session.setNegotiatedSubProtocol(selectedSubProtocol);

                //Replace HTTP handlers  with  new Handlers for WebSocket in the pipeline
                ChannelPipeline pipeline = ctx.pipeline();

                if (idleTimeout > 0) {
                    pipeline.replace(Constants.IDLE_STATE_HANDLER, Constants.IDLE_STATE_HANDLER,
                            new IdleStateHandler(idleTimeout, idleTimeout, idleTimeout, TimeUnit.MILLISECONDS));
                } else {
                    pipeline.remove(Constants.IDLE_STATE_HANDLER);
                }
                pipeline.addLast(Constants.WEBSOCKET_SOURCE_HANDLER, webSocketSourceHandler);
                pipeline.remove(Constants.HTTP_SOURCE_HANDLER);
                setProperty(Constants.SRC_HANDLER, webSocketSourceHandler);
                handshakeFuture.notifySuccess(webSocketSourceHandler.getChannelSession());
            }
        });
        return handshakeFuture;
    } catch (Exception e) {
        /*
        Code 1002 : indicates that an endpoint is terminating the connection
        due to a protocol error.
         */
        handshaker.close(ctx.channel(),
                new CloseWebSocketFrame(1002, "Terminating the connection due to a protocol error."));
        handshakeFuture.notifyError(e);
        return handshakeFuture;
    }
}

From source file:org.wso2.carbon.transport.http.netty.listener.NettyListener.java

License:Open Source License

private void shutdownEventLoops() {
    Future<?> f = workerGroup.shutdownGracefully();
    f.addListener(new GenericFutureListener<Future<Object>>() {
        @Override/*from  w w  w .  j a  v a  2 s  . c  o  m*/
        public void operationComplete(Future<Object> future) throws Exception {
            Future f = bossGroup.shutdownGracefully();
            f.addListener(new GenericFutureListener<Future<Object>>() {
                @Override
                public void operationComplete(Future<Object> future) throws Exception {
                    log.info("Netty transport " + id + " on port " + nettyConfig.getPort()
                            + " stopped successfully");
                }
            });
        }
    });
}

From source file:org.wyb.sows.client.SocksServerConnectHandler.java

License:Apache License

@Override
public void channelRead0(final ChannelHandlerContext ctx, final SocksCmdRequest request) throws Exception {
    if (request.host().equals("127.0.0.1") || request.host().equals("localhost")) {
        System.err.println("Not able to establish bridge. Inform proxy client.");
        ctx.channel().writeAndFlush(new SocksCmdResponse(SocksCmdStatus.FAILURE, request.addressType()));
        SocksServerUtils.closeOnFlush(ctx.channel());
    }//from w w w.  ja v  a  2s .  co  m

    Promise<Channel> promise = ctx.executor().newPromise();
    promise.addListener(new GenericFutureListener<Future<Channel>>() {
        @Override
        public void operationComplete(final Future<Channel> future) throws Exception {
            final Channel outboundChannel = future.getNow();
            if (future.isSuccess()) {
                if (SocksServer.isDebug) {
                    System.out.println("Bridge is established. Inform proxy client.");
                }
                SocksCmdResponse resp = new SocksCmdResponse(SocksCmdStatus.SUCCESS, request.addressType());
                resp.setProtocolVersion(request.protocolVersion());
                ctx.channel().writeAndFlush(resp).addListener(new ChannelFutureListener() {
                    @Override
                    public void operationComplete(ChannelFuture channelFuture) {
                        ChannelPipeline pipeline = ctx.pipeline();
                        pipeline.remove(SocksServerConnectHandler.this);
                        // ctx.pipeline().addLast(new StringByteCodec());
                        pipeline.addLast(new WebSocketRelayHandler(outboundChannel));
                    }
                });
            } else {
                System.err.println("Not able to establish bridge. Inform proxy client.");
                ctx.channel()
                        .writeAndFlush(new SocksCmdResponse(SocksCmdStatus.FAILURE, request.addressType()));
                SocksServerUtils.closeOnFlush(ctx.channel());
            }
        }
    });
    final Channel inboundChannel = ctx.channel();

    // Add authentication headers
    HttpHeaders authHeader = new DefaultHttpHeaders();
    authHeader.add(SowsAuthHelper.HEADER_SOWS_USER, this.userName);
    byte[] nonce = SowsAuthHelper.randomBytes(16);
    String seed = SowsAuthHelper.base64(nonce);
    authHeader.add(SowsAuthHelper.HEADER_SOWS_SEED, seed);
    byte[] sha1 = SowsAuthHelper.sha1((this.passcode + seed).getBytes(CharsetUtil.US_ASCII));
    String token = SowsAuthHelper.base64(sha1);
    authHeader.add(SowsAuthHelper.HEADER_SOWS_TOKEN, token);

    // initiating websocket client handler
    final WebSocketClientHandler handler = new WebSocketClientHandler(WebSocketClientHandshakerFactory
            .newHandshaker(bridgeServiceUri, WebSocketVersion.V13, null, false, authHeader), promise,
            request.host(), request.port(), inboundChannel);
    b.group(inboundChannel.eventLoop()).channel(NioSocketChannel.class)
            .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 10000).option(ChannelOption.SO_KEEPALIVE, true)
            .handler(new ChannelInitializer<SocketChannel>() {
                @Override
                protected void initChannel(SocketChannel ch) {
                    ChannelPipeline p = ch.pipeline();
                    p.addLast(new HttpClientCodec(), new HttpObjectAggregator(8192), handler);
                }
            });
    if (SocksServer.isDebug) {
        System.out.println("Try to connect to bridge service.");
    }
    b.connect(bridgeServiceUri.getHost(), bridgeServiceUri.getPort()).addListener(new ChannelFutureListener() {
        @Override
        public void operationComplete(ChannelFuture future) throws Exception {
            if (future.isSuccess()) {
                // Connection established use handler provided results
                if (SocksServer.isDebug) {
                    System.out.printf("Brige service connection is established. host=%s,port=%d \r\n",
                            bridgeServiceUri.getHost(), bridgeServiceUri.getPort());
                }
            } else {
                // Close the connection if the connection attempt has
                // failed.
                System.err.printf("Not able to connect bridge service! host=%s,port=%d \r\n",
                        bridgeServiceUri.getHost(), bridgeServiceUri.getPort());
                ctx.channel()
                        .writeAndFlush(new SocksCmdResponse(SocksCmdStatus.FAILURE, request.addressType()));
                SocksServerUtils.closeOnFlush(ctx.channel());
            }
        }
    });

}

From source file:org.wyb.sows.client.WebSocketClientHandler.java

License:Apache License

@Override
public void handlerAdded(ChannelHandlerContext ctx) {
    handshakeFuture = ctx.newPromise();//from   www.j  a va2s.c  o  m
    handshakeFuture.addListener(new GenericFutureListener<Future<Void>>() {
        @Override
        public void operationComplete(Future<Void> future) throws Exception {
            // send out target host and port to remote service.
            if (future.isSuccess()) {
                SowsConnectCmd cmd = new SowsConnectCmd();
                cmd.setHost(targetHost);
                cmd.setPort(targetPort);
                if (SocksServer.isDebug) {
                    System.out.printf("Send remote connection request: %s \r\n", cmd);
                }
                WebSocketFrame frame = new TextWebSocketFrame(cmd.encode());
                ctx.writeAndFlush(frame);
            } else {
                promise.setFailure(new Exception("Bridge service handshake failed!"));
            }
        }

    });
}

From source file:org.xwiki.contrib.websocket.internal.NettyWebSocketService.java

License:Open Source License

private void initialize0() throws Exception {
    final SslContext sslCtx;
    if (this.conf.sslEnabled()) {
        if (this.conf.getCertChainFilename() != null) {
            // They provided a cert chain filename (and ostensibly a private key)
            // ssl w/ CA signed certificate.
            final File certChain = new File(this.conf.getCertChainFilename());
            final File privKey = new File(this.conf.getPrivateKeyFilename());
            checkCertChainAndPrivKey(certChain, privKey);
            sslCtx = SslContext.newServerContext(certChain, privKey);
        } else {// w w w . j a v a 2s . c o m
            // SSL enabled but no certificate specified, lets use a selfie
            this.logger.warn("websocket.ssl.enable = true but websocket.ssl.certChainFile "
                    + "is unspecified, generating a Self Signed Certificate.");
            SelfSignedCertificate ssc = new SelfSignedCertificate();
            sslCtx = SslContext.newServerContext(ssc.certificate(), ssc.privateKey());
        }
    } else {
        sslCtx = null;
    }

    final EventLoopGroup bossGroup = new NioEventLoopGroup(1);
    final EventLoopGroup workerGroup = new NioEventLoopGroup();

    ServerBootstrap b = new ServerBootstrap();

    // get rid of silly lag
    b.childOption(ChannelOption.TCP_NODELAY, Boolean.TRUE);

    b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
            .handler(new LoggingHandler(LogLevel.INFO))
            .childHandler(new WebSocketServerInitializer(sslCtx, this));

    Channel ch = b.bind(this.conf.getBindTo(), this.conf.getPort()).sync().channel();

    ch.closeFuture().addListener(new GenericFutureListener<ChannelFuture>() {
        public void operationComplete(ChannelFuture f) {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    });
}