Example usage for io.netty.channel ChannelFutureListener ChannelFutureListener

List of usage examples for io.netty.channel ChannelFutureListener ChannelFutureListener

Introduction

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

Prototype

ChannelFutureListener

Source Link

Usage

From source file:com.vmware.xenon.common.http.netty.NettyWebSocketRequestHandler.java

License:Open Source License

private void performWebsocketHandshake(final ChannelHandlerContext ctx, FullHttpRequest nettyRequest) {
    WebSocketServerHandshakerFactory factory = new WebSocketServerHandshakerFactory(this.handshakePath, null,
            false);/* ww w.ja  v a2s .co m*/
    this.handshaker = factory.newHandshaker(nettyRequest);
    if (this.handshaker == null) {
        WebSocketServerHandshakerFactory.sendUnsupportedVersionResponse(ctx.channel());
    } else {
        ChannelPromise promise = new DefaultChannelPromise(ctx.channel());
        promise.addListener(new ChannelFutureListener() {
            @Override
            public void operationComplete(ChannelFuture future) throws Exception {
                if (!future.isSuccess()) {
                    ctx.channel().close();
                }
                ctx.channel().closeFuture().addListener(f -> {
                    for (java.util.Map.Entry<URI, Set<String>> e : NettyWebSocketRequestHandler.this.serviceSubscriptions
                            .entrySet()) {
                        WebSocketService svc = NettyWebSocketRequestHandler.this.webSocketServices
                                .get(e.getKey());
                        if (svc != null) {
                            deleteServiceSubscriptions(svc);
                        }
                        NettyWebSocketRequestHandler.this.host.stopService(svc);
                    }
                });
            }
        });
        DefaultHttpHeaders responseHeaders = new DefaultHttpHeaders();
        CharSequence token = nettyRequest.headers().get(Operation.REQUEST_AUTH_TOKEN_HEADER, null);
        if (token == null) {
            String cookie = nettyRequest.headers().get(HttpHeaderNames.COOKIE);
            if (cookie != null) {
                token = CookieJar.decodeCookies(cookie).get(AuthenticationConstants.REQUEST_AUTH_TOKEN_COOKIE);
            }

        }
        this.authToken = token == null ? null : token.toString();
        this.handshaker.handshake(ctx.channel(), nettyRequest, responseHeaders, promise);
    }
}

From source file:com.vmware.xenon.common.test.websockets.JsWebSocket.java

License:Open Source License

/**
 * Standard constructor WebSocket(uri) available in JavaScript API
 *
 * @param endpointUri Websocket endpoint URI
 *///from ww w  . j a  v  a  2  s  .c  o  m
public JsWebSocket(String endpointUri) throws Exception {
    URI uri = new URI(endpointUri);
    String scheme = uri.getScheme() == null ? WS_SCHEME : uri.getScheme();
    final String host = uri.getHost() == null ? ServiceHost.LOCAL_HOST : uri.getHost();
    final int port;
    if (uri.getPort() == -1) {
        if (WS_SCHEME.equalsIgnoreCase(scheme)) {
            port = 80;
        } else if (WSS_SCHEME.equalsIgnoreCase(scheme)) {
            port = 443;
        } else {
            port = -1;
        }
    } else {
        port = uri.getPort();
    }

    if (!WS_SCHEME.equalsIgnoreCase(scheme) && !WSS_SCHEME.equalsIgnoreCase(scheme)) {
        System.err.println("Only WS(S) is supported.");
        return;
    }

    final boolean ssl = WSS_SCHEME.equalsIgnoreCase(scheme);
    final SslContext sslCtx;
    if (ssl) {
        sslCtx = SslContextBuilder.forClient().trustManager(InsecureTrustManagerFactory.INSTANCE).build();
    } else {
        sslCtx = null;
    }

    this.group = new NioEventLoopGroup();

    // Connect with V13 (RFC 6455 aka HyBi-17). You can change it to V08 or V00.
    // If you change it to V00, ping is not supported and remember to change
    // HttpResponseDecoder to WebSocketHttpResponseDecoder in the pipeline.
    DefaultHttpHeaders headers = new DefaultHttpHeaders();
    if (OperationContext.getAuthorizationContext() != null
            && OperationContext.getAuthorizationContext().getToken() != null) {
        headers.add(HttpHeaderNames.COOKIE,
                CookieJar.encodeCookies(
                        Collections.singletonMap(AuthenticationConstants.REQUEST_AUTH_TOKEN_COOKIE,
                                OperationContext.getAuthorizationContext().getToken())));
    }
    final WebSocketClientHandler handler = new WebSocketClientHandler(
            WebSocketClientHandshakerFactory.newHandshaker(uri, WebSocketVersion.V13, null, false, headers));
    Bootstrap b = new Bootstrap();
    b.group(this.group).channel(NioSocketChannel.class).handler(new ChannelInitializer<SocketChannel>() {
        @Override
        protected void initChannel(SocketChannel ch) {
            ChannelPipeline p = ch.pipeline();
            if (sslCtx != null) {
                p.addLast(sslCtx.newHandler(ch.alloc(), host, port));
            }
            p.addLast(new HttpClientCodec(), new HttpObjectAggregator(8192), handler);
        }
    });

    this.channel = b.connect(uri.getHost(), port).sync().channel();
    handler.handshakeFuture.addListener(new ChannelFutureListener() {
        @Override
        public void operationComplete(ChannelFuture future) throws Exception {
            try {
                JsExecutor.executeSynchronously(() -> {
                    if (future.isSuccess()) {
                        if (JsWebSocket.this.onopen != null) {
                            JsWebSocket.this.onopen.call(Context.getCurrentContext(), getParentScope(),
                                    JsWebSocket.this, new Object[] { null });
                        }
                    } else {
                        throw new RuntimeException(future.cause());
                    }
                });
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    });
}

From source file:com.whizzosoftware.foscam.camera.discovery.FoscamCameraDiscovery.java

License:Open Source License

/**
 * Start the discovery process.//  ww w  .  j a  v a  2s .c  o m
 *
 * @throws IOException on failure
 */
public void start() throws IOException {
    searchRequestRunnable = new SearchRequestRunnable(this);

    // set up the inbound channel handler
    bootstrap.handler(new ChannelInitializer<Channel>() {
        @Override
        protected void initChannel(Channel channel) throws Exception {
            ChannelPipeline pipeline = channel.pipeline();
            pipeline.addLast(new DatagramToByteBufHandler()); // convert an incoming DatagramPacket into a ByteBuf
            pipeline.addLast(new OrderDecoder()); // convert an incoming ByteBuf into an Order
            pipeline.addLast(new InboundOrderHandler(listener)); // handle incoming Orders
        }
    });

    // bind to the address
    ChannelFuture cf = bootstrap.bind(new InetSocketAddress(0));
    cf.addListener(new ChannelFutureListener() {
        @Override
        public void operationComplete(ChannelFuture channelFuture) throws Exception {
            if (channelFuture.isSuccess()) {
                channel = (DatagramChannel) channelFuture.channel();

                // perform initial search request
                group.execute(searchRequestRunnable);

                // schedule two quick follow-up search requests to make sure a camera didn't miss the first request
                group.schedule(searchRequestRunnable, SEARCH_REQUEST_INITIAL_FREQUENCY_SECONDS,
                        TimeUnit.SECONDS);
                group.schedule(searchRequestRunnable, SEARCH_REQUEST_INITIAL_FREQUENCY_SECONDS * 2,
                        TimeUnit.SECONDS);

                // set up a recurring search request so we can keep track of cameras coming/going
                searchFuture = group.scheduleAtFixedRate(searchRequestRunnable,
                        SEARCH_REQUEST_INITIAL_FREQUENCY_SECONDS * 2 + getSearchRequestFrequencySeconds,
                        getSearchRequestFrequencySeconds, TimeUnit.SECONDS);
            } else {
                logger.error("Bind attempt failed", channelFuture.cause());
            }
        }
    });
}

From source file:com.whizzosoftware.hobson.api.plugin.channel.AbstractChannelObjectPlugin.java

License:Open Source License

/**
 * Connect the channel.//  www.  j  ava2s.c  om
 *
 * @param b a Netty Bootstrap object
 */
synchronized private void connect(Bootstrap b) {
    logger.debug("connect()");
    if (connectionState == State.NOT_CONNECTED) {
        logger.debug("Attempting to connect");
        connectionState = State.CONNECTING;
        b.connect(socketAddress).addListener(new ChannelFutureListener() {
            @Override
            public void operationComplete(ChannelFuture channelFuture) throws Exception {
                if (channelFuture.isSuccess()) {
                    logger.debug("Connection established");
                    connectionState = State.CONNECTED;

                    // save the channel
                    AbstractChannelObjectPlugin.this.channel = channelFuture.channel();

                    // set a close listener to notify the plugin subclass when the channel has closed
                    channel.closeFuture().addListener(new ChannelFutureListener() {
                        @Override
                        public void operationComplete(ChannelFuture channelFuture) throws Exception {
                            logger.info("Connection was closed");
                            channel = null;
                            connectionState = State.NOT_CONNECTED;
                            executeInEventLoop(new Runnable() {
                                @Override
                                public void run() {
                                    onChannelDisconnected();
                                }
                            });
                            if (isRunning) {
                                scheduleReconnect(channelFuture.channel().eventLoop());
                            }
                        }
                    });

                    executeInEventLoop(new Runnable() {
                        @Override
                        public void run() {
                            onChannelConnected();
                        }
                    });
                } else {
                    logger.warn("Connection attempt to " + socketAddress.toString() + " failed",
                            channelFuture.cause());
                    connectionState = State.NOT_CONNECTED;
                    if (isRunning) {
                        scheduleReconnect(channelFuture.channel().eventLoop());
                    }
                }
            }
        });
    } else {
        logger.debug("Ignoring connect request due to state: " + connectionState);
    }
}

From source file:com.whizzosoftware.hobson.ssdp.SSDPPlugin.java

License:Open Source License

public void createSockets() {
    try {//from w  w  w. j a va 2 s .  co m
        logger.debug("Using network interface: {}; local address: {}", nic, localAddress);

        if (nic == null) {
            logger.error("Unable to determine local NIC; discovery may not work properly");
        }

        if (nic != null) {
            Bootstrap clientBootstrap = new Bootstrap().group(eventLoopGroup)
                    .channelFactory(new ChannelFactory<Channel>() {
                        @Override
                        public Channel newChannel() {
                            return new NioDatagramChannel(InternetProtocolFamily.IPv4);
                        }
                    }).localAddress(groupAddress).option(ChannelOption.IP_MULTICAST_IF, nic)
                    .option(ChannelOption.SO_REUSEADDR, true).handler(new SSDPInboundHandler(this));

            clientBootstrap.bind().addListener(new ChannelFutureListener() {
                @Override
                public void operationComplete(ChannelFuture channelFuture) throws Exception {
                    multicastChannel = (NioDatagramChannel) channelFuture.channel();
                    multicastChannel.joinGroup(groupAddress, nic);
                }
            });
        }

        Bootstrap serverBootstrap = new Bootstrap().group(eventLoopGroup)
                .channelFactory(new ChannelFactory<Channel>() {
                    @Override
                    public Channel newChannel() {
                        return new NioDatagramChannel(InternetProtocolFamily.IPv4);
                    }
                }).localAddress(localAddress).option(ChannelOption.IP_MULTICAST_IF, nic)
                .option(ChannelOption.SO_REUSEADDR, true).handler(new SSDPInboundHandler(this));

        serverBootstrap.bind().addListener(new ChannelFutureListener() {
            @Override
            public void operationComplete(ChannelFuture channelFuture) throws Exception {
                localChannel = (NioDatagramChannel) channelFuture.channel();
                sendDiscoveryPacket();
            }
        });

    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:com.whizzosoftware.wzwave.controller.netty.NettyZWaveController.java

License:Open Source License

public void start() {
    if (channel == null) {
        // set up Netty bootstrap
        bootstrap = new Bootstrap();
        bootstrap.group(new OioEventLoopGroup());
        bootstrap.channel(RxtxChannel.class);
        bootstrap.handler(new ChannelInitializer<RxtxChannel>() {
            @Override// www.  j a  v  a  2 s . co  m
            protected void initChannel(RxtxChannel channel) throws Exception {
                NettyZWaveController.this.channel = channel;
                channel.config().setBaudrate(115200);
                channel.config().setDatabits(RxtxChannelConfig.Databits.DATABITS_8);
                channel.config().setParitybit(RxtxChannelConfig.Paritybit.NONE);
                channel.config().setStopbits(RxtxChannelConfig.Stopbits.STOPBITS_1);
                channel.pipeline().addLast("decoder", new ZWaveFrameDecoder());
                channel.pipeline().addLast("ack", new ACKInboundHandler());
                channel.pipeline().addLast("encoder", new ZWaveFrameEncoder());
                channel.pipeline().addLast("writeQueue", new FrameQueueHandler());
                channel.pipeline().addLast("transaction", new TransactionInboundHandler());
                channel.pipeline().addLast("handler", inboundHandler);
            }
        });

        bootstrap.connect(new RxtxDeviceAddress(serialPort)).addListener(new ChannelFutureListener() {
            @Override
            public void operationComplete(ChannelFuture future) throws Exception {
                if (future.isSuccess()) {
                    sendDataFrame(new Version());
                    sendDataFrame(new MemoryGetId());
                    sendDataFrame(new InitData());
                } else {
                    onZWaveConnectionFailure(future.cause());
                }
            }
        });
    }
}

From source file:com.wolfbe.configcenter.remoting.netty.NettyRemotingAbstract.java

License:Apache License

/**
 * ?????/*from   ww w  .  ja  va  2 s .c o  m*/
 * @param channel
 * @param request
 * @param timeoutMillis
 * @return
 * @throws InterruptedException
 * @throws RemotingSendRequestException
 * @throws RemotingTimeoutException
 */
public RemotingCommand invokeSyncImpl(final Channel channel, final RemotingCommand request,
        final long timeoutMillis)
        throws InterruptedException, RemotingSendRequestException, RemotingTimeoutException {
    final int opaque = request.getOpaque();

    try {
        final ResponseFuture responseFuture = new ResponseFuture(opaque, timeoutMillis, null, null);
        this.responseTable.put(opaque, responseFuture);
        final SocketAddress addr = channel.remoteAddress();
        channel.writeAndFlush(request).addListener(new ChannelFutureListener() {
            @Override
            public void operationComplete(ChannelFuture f) throws Exception {
                if (f.isSuccess()) {
                    responseFuture.setSendRequestOK(true);
                    return;
                } else {
                    responseFuture.setSendRequestOK(false);
                }

                responseTable.remove(opaque);
                responseFuture.setCause(f.cause());
                responseFuture.putResponse(null);
                plog.warn("send a request command to channel <" + addr + "> failed.");
            }
        });
        // ?responseFuture.putResponse
        RemotingCommand responseCommand = responseFuture.waitResponse(timeoutMillis);
        if (null == responseCommand) {
            if (responseFuture.isSendRequestOK()) {
                throw new RemotingTimeoutException(RemotingHelper.parseSocketAddressAddr(addr), timeoutMillis,
                        responseFuture.getCause());
            } else {
                throw new RemotingSendRequestException(RemotingHelper.parseSocketAddressAddr(addr),
                        responseFuture.getCause());
            }
        }

        return responseCommand;
    } finally {
        this.responseTable.remove(opaque);
    }
}

From source file:com.wolfbe.configcenter.remoting.netty.NettyRemotingAbstract.java

License:Apache License

/**
 * ????/*from  w  w  w  .  ja  va2 s.  com*/
 * @param channel
 * @param request
 * @param timeoutMillis
 * @param invokeCallback
 * @throws InterruptedException
 * @throws RemotingTooMuchRequestException
 * @throws RemotingTimeoutException
 * @throws RemotingSendRequestException
 */
public void invokeAsyncImpl(final Channel channel, final RemotingCommand request, final long timeoutMillis,
        final InvokeCallback invokeCallback) throws InterruptedException, RemotingTooMuchRequestException,
        RemotingTimeoutException, RemotingSendRequestException {
    final int opaque = request.getOpaque();
    boolean acquired = this.semaphoreAsync.tryAcquire(timeoutMillis, TimeUnit.MILLISECONDS);
    if (acquired) {
        final SemaphoreReleaseOnlyOnce once = new SemaphoreReleaseOnlyOnce(this.semaphoreAsync);

        final ResponseFuture responseFuture = new ResponseFuture(opaque, timeoutMillis, invokeCallback, once);
        this.responseTable.put(opaque, responseFuture);
        try {
            channel.writeAndFlush(request).addListener(new ChannelFutureListener() {
                @Override
                public void operationComplete(ChannelFuture f) throws Exception {
                    if (f.isSuccess()) {
                        responseFuture.setSendRequestOK(true);
                        return;
                    } else {
                        responseFuture.setSendRequestOK(false);
                    }

                    responseFuture.putResponse(null);
                    responseTable.remove(opaque);
                    try {
                        responseFuture.executeInvokeCallback();
                    } catch (Throwable e) {
                        plog.warn("excute callback in writeAndFlush addListener, and callback throw", e);
                    } finally {
                        responseFuture.release();
                    }

                    plog.warn("send a request command to channel <{}> failed.",
                            RemotingHelper.parseChannelRemoteAddr(channel));
                }
            });
        } catch (Exception e) {
            responseFuture.release();
            plog.warn("send a request command to channel <" + RemotingHelper.parseChannelRemoteAddr(channel)
                    + "> Exception", e);
            throw new RemotingSendRequestException(RemotingHelper.parseChannelRemoteAddr(channel), e);
        }
    } else {
        String info = String.format(
                "invokeAsyncImpl tryAcquire semaphore timeout, %dms, waiting thread nums: %d semaphoreAsyncValue: %d", //
                timeoutMillis, //
                this.semaphoreAsync.getQueueLength(), //
                this.semaphoreAsync.availablePermits()//
        );
        plog.warn(info);
        throw new RemotingTooMuchRequestException(info);
    }
}

From source file:com.wolfbe.configcenter.remoting.netty.NettyRemotingAbstract.java

License:Apache License

/**
 * ?????/*  w ww.  j av a2 s .  c om*/
 * @param channel
 * @param request
 * @param timeoutMillis
 * @throws InterruptedException
 * @throws RemotingTooMuchRequestException
 * @throws RemotingTimeoutException
 * @throws RemotingSendRequestException
 */
public void invokeOnewayImpl(final Channel channel, final RemotingCommand request, final long timeoutMillis)
        throws InterruptedException, RemotingTooMuchRequestException, RemotingTimeoutException,
        RemotingSendRequestException {
    request.markOnewayRPC();
    boolean acquired = this.semaphoreOneway.tryAcquire(timeoutMillis, TimeUnit.MILLISECONDS);
    if (acquired) {
        final SemaphoreReleaseOnlyOnce once = new SemaphoreReleaseOnlyOnce(this.semaphoreOneway);
        try {
            channel.writeAndFlush(request).addListener(new ChannelFutureListener() {
                @Override
                public void operationComplete(ChannelFuture f) throws Exception {
                    once.release();
                    if (!f.isSuccess()) {
                        plog.warn(
                                "send a request command to channel <" + channel.remoteAddress() + "> failed.");
                    }
                }
            });
        } catch (Exception e) {
            once.release();
            plog.warn("write send a request command to channel <" + channel.remoteAddress() + "> failed.");
            throw new RemotingSendRequestException(RemotingHelper.parseChannelRemoteAddr(channel), e);
        }
    } else {
        if (timeoutMillis <= 0) {
            throw new RemotingTooMuchRequestException("invokeOnewayImpl invoke too fast");
        } else {
            String info = String.format(
                    "invokeOnewayImpl tryAcquire semaphore timeout, %dms, waiting thread nums: %d semaphoreAsyncValue: %d", //
                    timeoutMillis, //
                    this.semaphoreOneway.getQueueLength(), //
                    this.semaphoreOneway.availablePermits()//
            );
            plog.warn(info);
            throw new RemotingTimeoutException(info);
        }
    }
}

From source file:com.wuma.file.uptime.UptimeClient.java

License:Apache License

static void connect(Bootstrap b) {
    b.connect().addListener(new ChannelFutureListener() {

        public void operationComplete(ChannelFuture future) throws Exception {
            if (future.cause() != null) {
                handler.startTime = -1;/*  w  ww. j av  a 2 s  . com*/
                handler.println("Failed to connect: " + future.cause());
            }
        }
    });
}