Example usage for io.netty.channel ChannelFuture sync

List of usage examples for io.netty.channel ChannelFuture sync

Introduction

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

Prototype

@Override
    ChannelFuture sync() throws InterruptedException;

Source Link

Usage

From source file:jgnash.engine.message.MessageBusServer.java

License:Open Source License

public boolean startServer(final DataStoreType dataStoreType, final String dataBasePath,
        final char[] password) {
    boolean result = false;

    logger.info("Starting message bus server");

    this.dataBasePath = dataBasePath;
    this.dataStoreType = dataStoreType.name();

    // If a password has been specified, create an EncryptionManager
    if (password != null && password.length > 0) {
        encryptionManager = new EncryptionManager(password);
    }/*from w  w  w . j  ava  2 s .  c  om*/

    eventLoopGroup = new NioEventLoopGroup();

    final ServerBootstrap bootstrap = new ServerBootstrap();

    try {
        bootstrap.group(eventLoopGroup).channel(NioServerSocketChannel.class)
                .childHandler(new MessageBusRemoteInitializer()).childOption(ChannelOption.SO_KEEPALIVE, true);

        final ChannelFuture future = bootstrap.bind(port);
        future.sync();

        if (future.isDone() && future.isSuccess()) {
            logger.info("Message Bus Server started successfully");
            result = true;
        } else {
            logger.info("Failed to start the Message Bus Server");
        }
    } catch (final InterruptedException e) {
        logger.log(Level.SEVERE, e.getLocalizedMessage(), e);
        stopServer();
    }

    return result;
}

From source file:localhost.apps.proxy.sensor.HttpSnoopClient.java

License:Apache License

public void run() {
    URI uri = this.uri;
    String scheme = uri.getScheme() == null ? "http" : uri.getScheme();
    String host = uri.getHost() == null ? "localhost" : uri.getHost();
    int port = uri.getPort();
    if (port == -1) {
        if ("http".equalsIgnoreCase(scheme)) {
            port = 80;//w ww  . j ava2s  .co m
        } else if ("https".equalsIgnoreCase(scheme)) {
            port = 443;
        }
    }

    if (!"http".equalsIgnoreCase(scheme) && !"https".equalsIgnoreCase(scheme)) {
        logger.error("Only HTTP(S) is supported.");
        return;
    }

    // Configure SSL context if necessary.
    final boolean ssl = "https".equalsIgnoreCase(scheme);
    // final SslContext sslCtx;
    // if (ssl) {
    // sslCtx = SslContextBuilder.forClient().trustManager(InsecureTrustManagerFactory.INSTANCE).build();
    // }
    // else {
    // sslCtx = null;
    // }

    // Configure the client.
    EventLoopGroup group = new NioEventLoopGroup();
    try {
        Bootstrap b = new Bootstrap();
        HttpSnoopClientInitializer initializer = new HttpSnoopClientInitializer();
        b.group(group).channel(NioSocketChannel.class).handler(initializer);

        //

        // Make the connection attempt.
        Channel ch = b.connect(host, port).sync().channel();

        // Prepare the HTTP request.
        // HttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, uri.getRawPath());

        // Set some example cookies.
        // request.headers().set(HttpHeaders.COOKIE, ClientCookieEncoder.STRICT.encode(new DefaultCookie("my-cookie", "foo"), new DefaultCookie("another-cookie", "bar")));

        ChannelFuture lastWriteFuture = null;

        for (;;) {

            if (this.request != null) {
                // Send the HTTP request.
                lastWriteFuture = ch.writeAndFlush(request);
                reset();
            }

            // Wait for the server to close the connection.
            if (isClosed()) {
                ch.closeFuture().sync();
                break;
            }
        }

        // Wait until all messages are flushed before closing the channel.
        if (lastWriteFuture != null) {
            lastWriteFuture.sync();
        }
    } catch (InterruptedException e) {
        logger.error(e.getMessage(), e);
    } finally {
        // Shut down executor threads to exit.
        group.shutdownGracefully();
    }
}

From source file:malcolm.HttpProxyServer.java

License:Open Source License

public void start() throws Exception {
    final EventLoopGroup bossGroup = new NioEventLoopGroup();
    final EventLoopGroup workerGroup = new NioEventLoopGroup();
    final ChannelFuture channelFuture = new ServerBootstrap().group(bossGroup, workerGroup)
            .channel(NioServerSocketChannel.class).handler(new LoggingHandler(LogLevel.DEBUG))
            .childHandler(new HttpProxyFrontendInitializer()).bind(port);
    try {//  w  w w  . j  a  va2 s.c o  m
        channelFuture.sync().channel().closeFuture().sync();
    } finally {
        workerGroup.shutdownGracefully();
        bossGroup.shutdownGracefully();
    }
}

From source file:me.ferrybig.javacoding.webmapper.MainServer.java

private synchronized Listener addListener0(String host, int port, SslContext sslCtx) throws ListenerException {
    try {/*from  w  w  w . j  av a2s.c  o  m*/
        Listener listener = new Listener(host, port, sslCtx != null);
        if (this.listeners.containsKey(listener)) {
            return listener;
        }

        WebServerInitializer init;
        if (sslCtx != null) {
            init = new WebSslServerInitializer(sslCtx, this, sessions, mapper, listener);
        } else {
            init = new WebServerInitializer(this, sessions, mapper, listener);
        }
        b.childHandler(init);
        ChannelFuture f;
        if (listener.getHost() == null)
            f = b.bind(port);
        else
            f = b.bind(host, port);
        Channel ch = f.sync().channel();
        if (f.cause() != null) {
            throw new ListenerException("Unable to bind listener", f.cause());
        }
        LOGGER.log(Level.INFO, "Started listener on: {0}", listener.toURL());
        this.listeners.put(listener, ch);
        return listener;
    } catch (InterruptedException ex) {
        Thread.currentThread().interrupt();
        throw new ListenerException(ex);
    }
}

From source file:monica.examples.MonicaClient.java

License:Apache License

public static void main(String args[]) throws FileNotFoundException, IOException {
    Properties pps = new Properties();
    File file = Utils.getPropertiesPath("path.properties");
    pps.load(new FileInputStream(file));
    String filePath = pps.getProperty("client.path");
    ClientStarter clientContainer = new ClientStarter();
    Channel ch;//from w w  w .  j  av  a 2  s. c o  m
    Executors.newSingleThreadExecutor().execute(new Runnable() {
        @Override
        public void run() {
            try {
                clientContainer.start();
            } catch (Exception e) {
                e.printStackTrace();
            }

        }
    });

    for (;;) {
        ch = clientContainer.getSocketChannel();
        if (null != ch) {
            break;
        }
    }
    try {

        File[] fileList = new File(filePath).listFiles();
        for (int i = 0; i < fileList.length; i++) {
            FileChannel channel = (new FileInputStream(fileList[i])).getChannel();
            ByteBuffer byteBuffer = ByteBuffer.allocate((int) channel.size());
            while (channel.read(byteBuffer) > 0)
                ;
            TransportFile transportFile = new TransportFile();
            transportFile.setContent(byteBuffer.array());
            transportFile.setFileName(fileList[i].getName());
            ChannelFuture f = ch.writeAndFlush(transportFile);
            // Wait until the connection is closed.
            f.sync();
            // Thread.sleep(10000);
        }
    } catch (Exception e) {
        e.printStackTrace();
    }

}

From source file:nenea.client.telnet.TelnetClient.java

License:Apache License

public void start() throws Exception {
    // Configure SSL.
    final SslContext sslCtx;
    if (SSL) {//from w  w  w . ja va 2s  .  c o m
        sslCtx = SslContextBuilder.forClient().trustManager(InsecureTrustManagerFactory.INSTANCE).build();
    } else {
        sslCtx = null;
    }

    EventLoopGroup group = new NioEventLoopGroup();
    try {
        Bootstrap b = new Bootstrap();
        b.group(group).channel(NioSocketChannel.class).handler(new TelnetClientInitializer(sslCtx));

        // Start the connection attempt.
        Channel ch = b.connect(HOST, PORT).sync().channel();

        // Read commands from the stdin.
        ChannelFuture lastWriteFuture = null;
        BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
        for (;;) {
            String line = in.readLine();
            if (line == null) {
                break;
            }

            // Sends the received line to the server.
            lastWriteFuture = ch.writeAndFlush(line + "\r\n");

            // If user typed the 'bye' command, wait until the server closes
            // the connection.
            if ("bye".equals(line.toLowerCase())) {
                ch.closeFuture().sync();
                break;
            }
        }

        // Wait until all messages are flushed before closing the channel.
        if (lastWriteFuture != null) {
            lastWriteFuture.sync();
        }
    } finally {
        group.shutdownGracefully();
    }
}

From source file:net.hasor.rsf.console.launcher.TelnetClient.java

License:Apache License

public static void execCommand(String host, int port, final String command, Map<String, String> envMap)
        throws Exception {
    StringWriter commands = new StringWriter();
    if (envMap != null) {
        for (String key : envMap.keySet()) {
            String val = envMap.get(key);
            commands.write("set " + key + " = " + val + " \n");
        }// www. ja  va2s.  co  m
    }
    commands.write("set SESSION_AFTERCLOSE = true \n");
    commands.write(command + "\n");
    //
    EventLoopGroup group = new NioEventLoopGroup();
    final BasicFuture<Object> closeFuture = new BasicFuture<Object>();
    final AtomicBoolean atomicBoolean = new AtomicBoolean(true);
    try {
        Bootstrap b = new Bootstrap();
        b = b.group(group);
        b = b.channel(NioSocketChannel.class);
        b = b.handler(new ChannelInitializer<SocketChannel>() {
            public void initChannel(SocketChannel ch) {
                ChannelPipeline pipeline = ch.pipeline();
                pipeline.addLast(new DelimiterBasedFrameDecoder(8192, Delimiters.lineDelimiter()));
                pipeline.addLast(new StringDecoder());
                pipeline.addLast(new StringEncoder());
                pipeline.addLast(new TelnetClientHandler(closeFuture, atomicBoolean));
            }
        });
        Channel ch = b.connect(host, port).sync().channel();
        ChannelFuture lastWriteFuture = null;
        BufferedReader commandReader = new BufferedReader(new StringReader(commands.toString()));
        for (;;) {
            if (atomicBoolean.get()) {
                String line = commandReader.readLine();
                if (line == null) {
                    break;
                }
                if (ch.isActive()) {
                    atomicBoolean.set(false);
                    lastWriteFuture = ch.writeAndFlush(line + "\r\n");
                }
            } else {
                Thread.sleep(500);//?
            }
        }
        if (lastWriteFuture != null) {
            lastWriteFuture.sync();
        }
    } finally {
        closeFuture.get();
        group.shutdownGracefully();
    }
}

From source file:net.mms_projects.copy_it.server.Main.java

License:Open Source License

public static void main(String[] args) throws Exception {
    if (args.length > 0) {
        if ("generate-pages".equals(args[0])) {
            new Config(new File((args.length > 1 ? args[1] : "copyit.config")));
            System.exit(PageGenerator.generate() ? 0 : 1);
        } else//w  w  w  .  ja  v  a2 s. c o  m
            new Config(new File(args[0]));
    } else
        new Config(new File("copyit.config"));
    if (PageGenerator.checkPages()) {
        Messages.printWarning("Outdated pages detected! Updating them now!");
        PageGenerator.generate();
    }
    printPid();
    new DatabasePool(MySQL.class, Config.getMaxConnectionsDatabasePool());
    EventLoopGroup bossGroup = new NioEventLoopGroup();
    EventLoopGroup workerGroup = new NioEventLoopGroup();
    try {
        Signal.handle(new Signal("USR2"), new SignalHandler() {
            public void handle(Signal signal) {
                FileCache.clear();
                Messages.printOK("Cleared file cache.");
            }
        });
        ServerBootstrap b = new ServerBootstrap();
        b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class).childHandler(new Initializer());
        ChannelFuture channelFuture = b.bind(Config.getHTTPAPIPort());
        if (channelFuture.await().isSuccess()) {
            Messages.printOK("Bound to port " + Config.getHTTPAPIPort());
            Page.initPages();
            Channel channel = channelFuture.sync().channel();
            channel.closeFuture().sync();
        } else
            Messages.printError("Failed to listen on " + Config.getHTTPAPIPort());
    } finally {
        bossGroup.shutdownGracefully();
        workerGroup.shutdownGracefully();
    }
}

From source file:Netty.BeaconClient.java

License:Apache License

public static void main(String[] args) throws Exception {
    // Configure SSL.
    final SslContext sslCtx;
    if (SSL) {//from  w  ww .  j  a  v a  2  s.  com
        sslCtx = SslContext.newClientContext(InsecureTrustManagerFactory.INSTANCE);
    } else {
        sslCtx = null;
    }

    EventLoopGroup group = new NioEventLoopGroup();
    try {
        Bootstrap b = new Bootstrap();
        b.group(group).channel(NioSocketChannel.class).handler(new BeaconClientInitializer(sslCtx));

        // Start the connection attempt.
        Channel ch = b.connect(HOST, PORT).sync().channel();

        // Read commands from the stdin.
        ChannelFuture lastWriteFuture = null;
        BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
        for (;;) {
            String line = in.readLine();
            if (line == null) {
                break;
            }

            // Sends the received line to the server.
            lastWriteFuture = ch.writeAndFlush(line + "\r\n");

            // If user typed the 'bye' command, wait until the server closes
            // the connection.
            if ("bye".equals(line.toLowerCase())) {
                ch.closeFuture().sync();
                break;
            }
        }

        // Wait until all messages are flushed before closing the channel.
        if (lastWriteFuture != null) {
            lastWriteFuture.sync();
        }
    } finally {
        group.shutdownGracefully();
    }
}

From source file:org.acmsl.katas.antlr4netty.InterpreterServer.java

License:Open Source License

/**
 * Wraps given {@link ChannelFuture} to ensure the event loops
 * shut down gracefully./* w  w  w.  ja v  a2  s.c o m*/
 * @param target the original channel future.
 * @param bossGroup the boss group.
 * @param workerGroup the worker group.
 * @return the wrapped future.
 */
@NotNull
protected ChannelFuture wrap(@NotNull final ChannelFuture target, @NotNull final NioEventLoopGroup bossGroup,
        @NotNull final NioEventLoopGroup workerGroup) {
    return new ChannelFuture() {
        @Override
        public Channel channel() {
            return target.channel();
        }

        /**
         * {@inheritDoc}
         */
        @Override
        public ChannelFuture addListener(
                @NotNull final GenericFutureListener<? extends Future<? super Void>> listener) {
            return target.addListener(listener);
        }

        /**
         * {@inheritDoc}
         */
        @Override
        public ChannelFuture addListeners(
                @NotNull final GenericFutureListener<? extends Future<? super Void>>... listeners) {
            return target.addListeners(listeners);
        }

        /**
         * {@inheritDoc}
         */
        @Override
        public ChannelFuture removeListener(
                @NotNull final GenericFutureListener<? extends Future<? super Void>> listener) {
            return target.removeListener(listener);
        }

        /**
         * {@inheritDoc}
         */
        @Override
        public ChannelFuture removeListeners(
                @NotNull final GenericFutureListener<? extends Future<? super Void>>... listeners) {
            return target.removeListeners(listeners);
        }

        /**
         * {@inheritDoc}
         */
        @Override
        public ChannelFuture sync() throws InterruptedException {
            ChannelFuture result = null;

            try {
                result = target.sync();
            } finally {
                workerGroup.shutdownGracefully();
                bossGroup.shutdownGracefully();
            }

            return result;
        }

        /**
         * {@inheritDoc}
         */
        @Override
        public ChannelFuture syncUninterruptibly() {
            return target.syncUninterruptibly();
        }

        /**
         * {@inheritDoc}
         */
        @Override
        public ChannelFuture await() throws InterruptedException {
            return target.await();
        }

        /**
         * {@inheritDoc}
         */
        @Override
        public ChannelFuture awaitUninterruptibly() {
            return target.awaitUninterruptibly();
        }

        /**
         * {@inheritDoc}
         */
        @Override
        public boolean isSuccess() {
            return target.isSuccess();
        }

        /**
         * {@inheritDoc}
         */
        @Override
        public boolean isCancellable() {
            return target.isCancellable();
        }

        /**
         * {@inheritDoc}
         */
        @Override
        public Throwable cause() {
            return target.cause();
        }

        /**
         * {@inheritDoc}
         */
        @Override
        public boolean await(final long timeout, @NotNull final TimeUnit unit) throws InterruptedException {
            return target.await(timeout, unit);
        }

        /**
         * {@inheritDoc}
         */
        @Override
        public boolean await(final long timeoutMillis) throws InterruptedException {
            return target.await(timeoutMillis);
        }

        /**
         * {@inheritDoc}
         */
        @Override
        public boolean awaitUninterruptibly(final long timeout, @NotNull final TimeUnit unit) {
            return target.awaitUninterruptibly(timeout, unit);
        }

        /**
         * {@inheritDoc}
         */
        @Override
        public boolean awaitUninterruptibly(final long timeoutMillis) {
            return target.awaitUninterruptibly(timeoutMillis);
        }

        /**
         * {@inheritDoc}
         */
        @Override
        public Void getNow() {
            return target.getNow();
        }

        /**
         * {@inheritDoc}
         */
        @Override
        public boolean cancel(final boolean mayInterruptIfRunning) {
            return target.cancel(mayInterruptIfRunning);
        }

        /**
         * {@inheritDoc}
         */
        @Override
        public boolean isCancelled() {
            return target.isCancelled();
        }

        /**
         * {@inheritDoc}
         */
        @Override
        public boolean isDone() {
            return target.isDone();
        }

        /**
         * {@inheritDoc}
         */
        @Override
        public Void get() throws InterruptedException, ExecutionException {
            return target.get();
        }

        /**
         * {@inheritDoc}
         */
        @Override
        public Void get(final long timeout, @NotNull final TimeUnit unit)
                throws InterruptedException, ExecutionException, TimeoutException {
            return target.get(timeout, unit);
        }
    };
}