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:com.liferay.sync.engine.lan.server.discovery.LanDiscoveryBroadcaster.java

License:Open Source License

public void broadcast(int port) throws Exception {
    if ((_channel == null) || !_channel.isActive()) {
        _initialize();//w  w w . j a  v a2  s . c o  m
    }

    byte[] bytes = JSONUtil.writeValueAsBytes(LanClientUtil.createSyncLanClient(port));

    DatagramPacket datagramPacket = new DatagramPacket(Unpooled.copiedBuffer(bytes),
            new InetSocketAddress("255.255.255.255", PropsValues.SYNC_LAN_SERVER_PORT));

    ChannelFuture channelFuture = _channel.writeAndFlush(datagramPacket);

    channelFuture.sync();
}

From source file:com.liferay.sync.engine.lan.server.discovery.LanDiscoveryBroadcaster.java

License:Open Source License

private void _initialize() throws Exception {
    _eventLoopGroup = new NioEventLoopGroup();

    Bootstrap bootstrap = new Bootstrap();

    bootstrap.channel(NioDatagramChannel.class);
    bootstrap.group(_eventLoopGroup);//from   www. j  a  v  a2s .c  o  m
    bootstrap.handler(new LanDiscoveryBroadcasterHandler());
    bootstrap.option(ChannelOption.SO_BROADCAST, true);

    ChannelFuture channelFuture = bootstrap.bind(0);

    try {
        channelFuture = channelFuture.sync();

        _channel = channelFuture.channel();
    } catch (InterruptedException ie) {
        _eventLoopGroup.shutdownGracefully();

        throw ie;
    }
}

From source file:com.liferay.sync.engine.lan.server.discovery.LanDiscoveryListener.java

License:Open Source License

public void listen() throws Exception {
    _eventLoopGroup = new NioEventLoopGroup();

    Bootstrap bootstrap = new Bootstrap();

    bootstrap.channel(NioDatagramChannel.class);
    bootstrap.group(_eventLoopGroup);// www  . ja v a  2 s . c  o m
    bootstrap.handler(new LanDiscoveryListenerHandler());
    bootstrap.option(ChannelOption.SO_REUSEADDR, true);

    ChannelFuture channelFuture = bootstrap.bind(PropsValues.SYNC_LAN_SERVER_PORT);

    channelFuture.sync();
}

From source file:com.liferay.sync.engine.lan.server.file.LanFileServer.java

License:Open Source License

public void start() throws Exception {
    _childEventLoopGroup = new NioEventLoopGroup();
    _parentEventLoopGroup = new NioEventLoopGroup(1);

    ServerBootstrap serverBootstrap = new ServerBootstrap();

    serverBootstrap.group(_parentEventLoopGroup, _childEventLoopGroup);
    serverBootstrap.channel(NioServerSocketChannel.class);

    _syncTrafficShapingHandler = new SyncTrafficShapingHandler(_childEventLoopGroup);

    _lanFileServerInitializer = new LanFileServerInitializer(_syncTrafficShapingHandler);

    serverBootstrap.childHandler(_lanFileServerInitializer);

    serverBootstrap.childOption(ChannelOption.SO_KEEPALIVE, true);

    ChannelFuture channelFuture = serverBootstrap.bind(PropsValues.SYNC_LAN_SERVER_PORT);

    try {//from  w  ww.j  a  v  a2  s.  c  o  m
        channelFuture.sync();
    } catch (Exception e) {

        // Compiling fails when directly catching BindException. Netty seems
        // to throw an undeclared exception.

        if (e instanceof BindException) {
            channelFuture = serverBootstrap.bind(0);

            channelFuture.sync();
        } else {
            throw e;
        }
    }

    Channel channel = channelFuture.channel();

    InetSocketAddress inetSocketAddress = (InetSocketAddress) channel.localAddress();

    _port = inetSocketAddress.getPort();

    channelFuture.sync();

    Runnable runnable = new Runnable() {

        @Override
        public void run() {
            long count = SyncFileService.getSyncFilesCount(SyncFile.UI_EVENT_DOWNLOADING,
                    SyncFile.UI_EVENT_UPLOADING);

            long writeDelay = 0;

            if (count > 0) {
                _syncTrafficShapingHandler.setWriteDelay(PropsValues.SYNC_LAN_SERVER_WRITE_DELAY);
            }

            _syncTrafficShapingHandler.setWriteDelay(writeDelay);
        }

    };

    ScheduledExecutorService scheduledExecutorService = LanEngine.getScheduledExecutorService();

    scheduledExecutorService.scheduleWithFixedDelay(runnable, 0, 500, TimeUnit.MILLISECONDS);
}

From source file:com.mastfrog.scamper.SctpClient.java

License:Open Source License

/**
 * Start the client, returning a ChannelFuture which can be waited on to
 * keep the client running (the returned future is the client SCTP socket's
 * channel's <code>closeFuture()</code> - call its <code>sync()</code>
 * method to block the current thread until the connection is closed.
 *
 * @return The close future for this client's connection
 * @throws InterruptedException if the connect process is interrupted
 *//*w w  w. ja  va2  s.co  m*/
public ChannelFuture start() throws InterruptedException {
    // Configure the client.
    Bootstrap b = new Bootstrap();

    configurer.init(b).handler(new LoggingHandler(LogLevel.INFO));

    logger.log(Level.INFO, "Start for {0} on {1}", new Object[] { host, port });
    // Start the client.
    ChannelFuture f = b.connect(host, port);
    if (logger.isLoggable(Level.FINE)) {
        f.addListener(new ChannelFutureListener() {

            @Override
            public void operationComplete(ChannelFuture future) throws Exception {
                logger.log(Level.FINE, "Connect to {0}:{1}", new Object[] { host, port });
            }

        });
    }
    f.sync();
    // Caller can until the connection is closed.
    return f.channel().closeFuture();
}

From source file:com.mastfrog.scamper.SctpServer.java

License:Open Source License

@Inject
SctpServer(@Named(SETTINGS_KEY_SCTP_PORT) int port, Provider<ChannelHandlerAdapter> handler,
        ChannelConfigurer config, ShutdownHookRegistry reg) {
    this.port = port;
    this.config = config;
    reg.add(new Runnable() {

        @Override/*from   ww  w  .j a  va 2 s  .  co  m*/
        public void run() {
            ChannelFuture f = stop();
            if (f != null) {
                try {
                    f.sync();
                } catch (InterruptedException ex) {
                    logger.log(Level.SEVERE, null, ex);
                }
            }
        }
    });
}

From source file:com.mastfrog.scamper.SctpServer.java

License:Open Source License

public ChannelFuture start(AtomicReference<ChannelFuture> connectFutureReceiver) throws InterruptedException {
    // Configure the server.
    ServerBootstrap b = new ServerBootstrap();
    config.init(b);//from w  w w. j  a  v a  2 s  .co  m
    b.handler(new LoggingHandler(LogLevel.INFO));

    logger.log(Level.FINE, "Start server on {0}", port);
    // Start the server.
    ChannelFuture f = b.bind(port);
    if (logger.isLoggable(Level.FINE)) {
        f.addListener(new ChannelFutureListener() {

            @Override
            public void operationComplete(ChannelFuture future) throws Exception {
                logger.log(Level.FINE, "Listening for connections on {0}", port);
            }

        });
    }
    f.sync();
    logger.log(Level.FINER, "Thread proceeding", Thread.currentThread());
    // For tests and things that need to delay execution until a connection
    // has been opened
    if (connectFutureReceiver != null) {
        connectFutureReceiver.set(f);
    }
    synchronized (this) {
        return future = f.channel().closeFuture();
    }
}

From source file:com.netty.file.HttpUploadClient.java

License:Apache License

/**
 * Standard post without multipart but already support on Factory (memory management)
 *
 * @return the list of HttpData object (attribute and file) to be reused on next post
 *//*  w ww  .  j  av  a2 s.  c  o m*/
private static List<InterfaceHttpData> formpost(Bootstrap bootstrap, String host, int port, URI uriSimple,
        File file, HttpDataFactory factory, List<Entry<String, String>> headers) throws Exception {
    // XXX /formpost
    // Start the connection attempt.
    ChannelFuture future = bootstrap.connect(new InetSocketAddress(host, port));
    // Wait until the connection attempt succeeds or fails.
    Channel channel = future.sync().channel();

    // Prepare the HTTP request.
    HttpRequest request = new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.POST,
            uriSimple.toASCIIString());

    // Use the PostBody encoder
    HttpPostRequestEncoder bodyRequestEncoder = new HttpPostRequestEncoder(factory, request, false); // false => not multipart

    // it is legal to add directly header or cookie into the request until finalize
    for (Entry<String, String> entry : headers) {
        request.headers().set(entry.getKey(), entry.getValue());
    }

    // add Form attribute
    bodyRequestEncoder.addBodyAttribute("getform", "POST");
    bodyRequestEncoder.addBodyAttribute("info", "first value");
    bodyRequestEncoder.addBodyAttribute("secondinfo", "secondvalue &");
    bodyRequestEncoder.addBodyAttribute("thirdinfo", textArea);
    bodyRequestEncoder.addBodyFileUpload("myfile", file, "application/x-zip-compressed", false);

    // finalize request
    request = bodyRequestEncoder.finalizeRequest();

    // Create the bodylist to be reused on the last version with Multipart support
    List<InterfaceHttpData> bodylist = bodyRequestEncoder.getBodyListAttributes();

    // send request
    channel.write(request);

    // test if request was chunked and if so, finish the write
    if (bodyRequestEncoder.isChunked()) { // could do either request.isChunked()
        // either do it through ChunkedWriteHandler
        channel.write(bodyRequestEncoder);
    }
    channel.flush();

    // Do not clear here since we will reuse the InterfaceHttpData on the next request
    // for the example (limit action on client side). Take this as a broadcast of the same
    // request on both Post actions.
    //
    // On standard program, it is clearly recommended to clean all files after each request
    // bodyRequestEncoder.cleanFiles();

    // Wait for the server to close the connection.
    channel.closeFuture().sync();
    return bodylist;
}

From source file:com.netty.fileTest.http.upload.HttpUploadClient.java

License:Apache License

public static void main(String[] args) throws Exception {
    String postFile;// ww w . ja  va 2s.  c o m
    // postFile = BASE_URL + "formpost";
    postFile = BASE_URL + "formpostmultipart";
    URI uriFile = new URI(postFile);
    File file = new File(FILE);
    if (!file.canRead()) {
        throw new FileNotFoundException(FILE);
    }

    // Configure the client.
    EventLoopGroup group = new NioEventLoopGroup();
    Bootstrap bootstrap = new Bootstrap();
    bootstrap.group(group).channel(NioSocketChannel.class).handler(new HttpUploadClientIntializer(null));

    HttpDataFactory factory = new DefaultHttpDataFactory(DefaultHttpDataFactory.MINSIZE);
    // Disk if MINSIZE exceed

    DiskFileUpload.deleteOnExitTemporaryFile = true; // should delete file on exit (in normal exit)
    DiskFileUpload.baseDirectory = null; // system temp directory
    DiskAttribute.deleteOnExitTemporaryFile = true; // should delete file on exit (in normal exit)
    DiskAttribute.baseDirectory = null; // system temp directory

    try {
        ChannelFuture future = bootstrap.connect(new InetSocketAddress("127.0.0.1", 8080));
        // Wait until the connection attempt succeeds or fails.
        Channel channel = future.sync().channel();

        // Prepare the HTTP request.
        HttpRequest request = new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.POST,
                uriFile.toASCIIString());
        // Use the PostBody encoder
        HttpPostRequestEncoder bodyRequestEncoder = new HttpPostRequestEncoder(factory, request, false);
        // add Form attribute
        bodyRequestEncoder.addBodyFileUpload("myfile", file, "application/x-zip-compressed", false);

        // finalize request
        request = bodyRequestEncoder.finalizeRequest();

        // Create the bodylist to be reused on the last version with Multipart support
        List<InterfaceHttpData> bodylist = bodyRequestEncoder.getBodyListAttributes();

        // send request
        channel.write(request);

        // test if request was chunked and if so, finish the write
        if (bodyRequestEncoder.isChunked()) { // could do either request.isChunked()
            channel.write(bodyRequestEncoder);
        }
        channel.flush();
        channel.closeFuture().sync();
    } finally {
        // Shut down executor threads to exit.
        group.shutdownGracefully();

        // Really clean all temporary files if they still exist
        factory.cleanAllHttpDatas();
    }
}

From source file:com.phei.netty.nio.http.upload.HttpUploadClient.java

License:Apache License

/**
 * Multipart example//from w w  w.  ja va  2s  .com
 */
private static void formpostmultipart(Bootstrap bootstrap, String host, int port, URI uriFile,
        HttpDataFactory factory, List<Entry<String, String>> headers, List<InterfaceHttpData> bodylist)
        throws Exception {
    // XXX /formpostmultipart
    // Start the connection attempt.
    ChannelFuture future = bootstrap.connect(new InetSocketAddress(host, port));
    // Wait until the connection attempt succeeds or fails.
    Channel channel = future.sync().channel();

    // Prepare the HTTP request.
    HttpRequest request = new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.POST,
            uriFile.toASCIIString());

    // Use the PostBody encoder
    HttpPostRequestEncoder bodyRequestEncoder = new HttpPostRequestEncoder(factory, request, true); // true => multipart

    // it is legal to add directly header or cookie into the request until finalize
    for (Entry<String, String> entry : headers) {
        request.headers().set(entry.getKey(), entry.getValue());
    }

    // add Form attribute from previous request in formpost()
    bodyRequestEncoder.setBodyHttpDatas(bodylist);

    // finalize request
    bodyRequestEncoder.finalizeRequest();

    // send request
    channel.write(request);

    // test if request was chunked and if so, finish the write
    if (bodyRequestEncoder.isChunked()) {
        channel.write(bodyRequestEncoder);
    }
    channel.flush();

    // Now no more use of file representation (and list of HttpData)
    bodyRequestEncoder.cleanFiles();

    // Wait for the server to close the connection.
    channel.closeFuture().sync();
}