public static Channel remoteCapiConnect(InetSocketAddress remoteAddress, ChannelHandler handler) {

    ChannelFuture connectFuture = null;

    // configure client bootstrap
    final ClientBootstrap bootstrap =
        new ClientBootstrap(
            new NioClientSocketChannelFactory(
                Executors.newCachedThreadPool(), Executors.newCachedThreadPool()));

    try {

      // use Request-Response handler business logic
      bootstrap.setPipelineFactory(new RemoteCapiPipelineFactory(handler));

      // start the connection attempt
      connectFuture = bootstrap.connect(remoteAddress);

      connectFuture.await(CONNECT_TIMEOUT_SECONDS, TimeUnit.SECONDS);

    } catch (InterruptedException e) {
      return null;
    } finally {
      if (connectFuture.isSuccess()) {
        // shut down thread pools on channelClosed
        connectFuture
            .getChannel()
            .getCloseFuture()
            .addListener(
                new ChannelFutureListener() {
                  public void operationComplete(ChannelFuture closeFuture) throws Exception {
                    new Thread() {
                      @Override
                      public void run() {
                        bootstrap.releaseExternalResources();
                      }
                    }.start();
                  }
                });
      } else {
        // shut down thread pools due to connection failure
        bootstrap.releaseExternalResources();

        return null;
      }
    }

    return connectFuture.getChannel();
  }
Ejemplo n.º 2
0
  protected void init() {
    // Configure the client.
    bootstrap =
        new ClientBootstrap(
            new NioClientSocketChannelFactory(
                Executors.newCachedThreadPool(), Executors.newCachedThreadPool()));

    // Set up the event pipeline factory.
    bootstrap.setPipelineFactory(new FileClientPipelineFactory());
    // Options for a new channel
    bootstrap.setOption("tcpNoDelay", true);
    bootstrap.setOption("receiveBufferSize", 1048576);
    ChannelFuture future = bootstrap.connect(new InetSocketAddress("localhost", 8022));
    // Wait until the connection is made successfully.
    future.awaitUninterruptibly(timeout);
    future.addListener(
        new ChannelFutureListener() {

          @Override
          public void operationComplete(ChannelFuture future) throws Exception {
            System.out.println("Connected.");
          }
        });
    if (!future.isSuccess()) {
      future.getCause().printStackTrace();
      bootstrap.releaseExternalResources();
      return;
    }
    channel = future.getChannel();
  }
Ejemplo n.º 3
0
  public void sendRequest(MetaInfo meta) {
    System.out.println(Thread.currentThread().getId() + " start sendRequest");
    URI uri = null;
    try {
      System.out.println(meta.getParams());
      uri = new URI(meta.getUrl());
    } catch (URISyntaxException e) {
      e.printStackTrace(); // To change body of catch statement use File | Settings | File
      // Templates.
    }
    String host = uri.getHost();
    int port = 80;

    HttpRequest request =
        new DefaultHttpRequest(
            HttpVersion.HTTP_1_1, HttpMethod.valueOf(meta.getMethod()), uri.toASCIIString());
    meta.buildHttpRequestHeader(request);

    ChannelFuture future = bootstrap.connect(new InetSocketAddress(host, port));
    Channel channel = future.getChannel();
    channel.getPipeline().addLast("handler", new DownloaderHandler());
    GlobalVar.metaInfoVar.set(channel, meta);

    future.addListener(new ConnectOk(request));
    channel.getCloseFuture().awaitUninterruptibly().addListener(new ConnectClose());
    System.out.println(Thread.currentThread().getId() + " end sendRequest");
  }
Ejemplo n.º 4
0
  public void stop() {
    log.info("Shutting down proxy");
    if (stopped.get()) {
      log.info("Already stopped");
      return;
    }
    stopped.set(true);

    log.info("Closing all channels...");

    // See http://static.netty.io/3.5/guide/#start.12

    final ChannelGroupFuture future = allChannels.close();
    future.awaitUninterruptibly(10 * 1000);

    if (!future.isCompleteSuccess()) {
      final Iterator<ChannelFuture> iter = future.iterator();
      while (iter.hasNext()) {
        final ChannelFuture cf = iter.next();
        if (!cf.isSuccess()) {
          log.warn("Cause of failure for {} is {}", cf.getChannel(), cf.getCause());
        }
      }
    }
    log.info("Stopping timer");
    timer.stop();
    serverChannelFactory.releaseExternalResources();
    clientChannelFactory.releaseExternalResources();

    log.info("Done shutting down proxy");
  }
  @Override
  public void channelOpen(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception {
    // Suspend incoming traffic until connected to the remote host.
    final Channel inboundChannel = e.getChannel();
    inboundChannel.setReadable(false);

    // Start the connection attempt.
    ClientBootstrap cb = new ClientBootstrap(cf);
    cb.getPipeline().addLast("handler", new OutboundHandler(e.getChannel()));
    ChannelFuture f = cb.connect(new InetSocketAddress(remoteHost, remotePort));

    outboundChannel = f.getChannel();
    f.addListener(
        new ChannelFutureListener() {
          public void operationComplete(ChannelFuture future) throws Exception {
            if (future.isSuccess()) {
              // Connection attempt succeeded:
              // Begin to accept incoming traffic.
              inboundChannel.setReadable(true);
            } else {
              // Close the connection if the connection attempt has failed.
              inboundChannel.close();
            }
          }
        });
  }
Ejemplo n.º 6
0
  public static void main(String[] args) throws Exception {
    String host = "localhost";
    int port = Integer.parseInt("8080");

    ChannelFactory factory =
        new NioClientSocketChannelFactory(
            Executors.newCachedThreadPool(), Executors.newCachedThreadPool());

    ClientBootstrap bootstrap = new ClientBootstrap(factory);

    bootstrap.setPipelineFactory(
        new ChannelPipelineFactory() {
          public ChannelPipeline getPipeline() {
            return Channels.pipeline(new TimeDecoder(), new TimeClientHandler());
          }
        });

    bootstrap.setOption("tcpNoDelay", true);
    bootstrap.setOption("keepAlive", true);

    ChannelFuture future = bootstrap.connect(new InetSocketAddress(host, port));
    future.awaitUninterruptibly();
    if (!future.isSuccess()) {
      future.getCause().printStackTrace();
    }
    future.getChannel().getCloseFuture().awaitUninterruptibly();
    factory.releaseExternalResources();
  }
Ejemplo n.º 7
0
    public void operationComplete(ChannelFuture future) throws Exception {
      if (future.isSuccess()) {
        // Once session is secured, send a greeting.
        //                future.getChannel().write(
        //                        "Welcome to " + InetAddress.getLocalHost().getHostName() +
        //                        " secure chat service!\n");
        //                future.getChannel().write(
        //                        "Your session is protected by " +
        //                        sslHandler.getEngine().getSession().getCipherSuite() +
        //                        " cipher suite.\n");

        // Register the channel to the global channel list
        // so the channel received the messages from others.
        ServerContant.allChannels.add(future.getChannel()); // 将接入的连接加入ChannelGroup
      } else {
        future.getChannel().close();
      }
    }
Ejemplo n.º 8
0
 @Override
 public void operationComplete(ChannelFuture channelFuture) throws Exception {
   if (channelFuture.isSuccess()) {
     channel = channelFuture.getChannel();
     channelWriteFuture = channelFuture.getChannel().write(httpRequest);
     channelWriteFuture.addListener(ChannelFutureListener.CLOSE);
     LOG.debug("Sending configuration info to: " + channel.getRemoteAddress());
     LOG.info("Greetings to: " + channel.getRemoteAddress());
   } else {
     LOG.warn(
         "Failed to connect to heartbeat service at "
             + remoteAddr
             + ": "
             + channelFuture.getCause().getMessage());
     if (channel != null) {
       channel.close();
     }
   }
 }
Ejemplo n.º 9
0
  private void connectClient(ClientBootstrapResolver clientResolver) throws Exception {
    final RegionInfo regionInfo = clientResolver.getRegionInfo();
    ClientBootstrap client = clientResolver.resolve();

    if (LOGGER.isDebugEnabled()) {
      LOGGER.debug("[id:           ] connect " + client.getOption("remoteAddress"));
    }

    ChannelFuture connectFuture = client.connect();
    connectFutures.add(connectFuture);
    clientChannels.add(connectFuture.getChannel());
    connectFuture.addListener(createConnectCompleteListener(regionInfo));
  }
Ejemplo n.º 10
0
  private ChannelFuture prepareServers() throws Exception {

    /* Accept's ... Robot acting as a server */
    for (ServerBootstrapResolver serverResolver : configuration.getServerResolvers()) {
      ServerBootstrap server = serverResolver.resolve();
      if (LOGGER.isDebugEnabled()) {
        LOGGER.debug("Binding to address " + server.getOption("localAddress"));
      }

      /* Keep track of the client channels */
      server.setParentHandler(
          new SimpleChannelHandler() {
            @Override
            public void childChannelOpen(ChannelHandlerContext ctx, ChildChannelStateEvent e)
                throws Exception {
              clientChannels.add(e.getChildChannel());
            }

            @Override
            public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e)
                throws Exception {
              Channel channel = ctx.getChannel();
              channel.close();
            }
          });

      // Bind Asynchronously
      ChannelFuture bindFuture = server.bindAsync();

      // Add to out serverChannel Group
      serverChannels.add(bindFuture.getChannel());

      // Add to our list of bindFutures so we can cancel them later on a possible abort
      bindFutures.add(bindFuture);

      // Listen for the bindFuture.
      RegionInfo regionInfo = (RegionInfo) server.getOption("regionInfo");
      bindFuture.addListener(
          createBindCompleteListener(regionInfo, serverResolver.getNotifyBarrier()));
    }

    return new CompositeChannelFuture<>(channel, bindFutures);
  }
Ejemplo n.º 11
0
  @Override
  public void connect() throws NntpClientConnectionError {
    // We'll be waiting for the connection message.
    NntpFuture<GenericResponse> welcomeFuture = new NntpFuture<>(Response.ResponseType.WELCOME);
    this.pipeline.add(welcomeFuture);

    // Connect to the server now.
    ChannelFuture future = this.initializeChannel(new InetSocketAddress(this.host, this.port));
    if (!future.isSuccess()) {
      throw new NntpClientConnectionError(future.getCause());
    }
    this.channel = future.getChannel();

    if (this.ssl) {
      ChannelFuture handshakeFuture =
          this.channel.getPipeline().get(SslHandler.class).handshake().awaitUninterruptibly();
      if (!handshakeFuture.isSuccess()) {
        throw new NntpClientConnectionError(handshakeFuture.getCause());
      }
    }

    GenericResponse response = Futures.getUnchecked(welcomeFuture);
    boolean temporarilyUnavailable = false;
    switch (response.getCode()) {
      case 200:
        this.canPost = true;
      case 201:
        return;
      case 400:
        temporarilyUnavailable = true;
      case 502:
        throw new NntpClientConnectionError(
            new NntpServerUnavailableException(temporarilyUnavailable));
      default:
        // FIXME: typed exception here mebbe?
        throw new NntpClientConnectionError(
            new RuntimeException(
                "Unexpected status code "
                    + response.getCode()
                    + " returned on initial connection."));
    }
  }
    @Override
    public void operationComplete(ChannelFuture cf) throws Exception {
      if (!cf.isSuccess()) {
        synchronized (connections) {
          NodeConnection c = connections.remove(node.getNodeId());
          if (c != null) c.nuke();
          cf.getChannel().close();
        }

        String message = "[unknown error]";
        if (cf.isCancelled()) message = "Timed out on connect";
        if (cf.getCause() != null) message = cf.getCause().getMessage();
        logger.debug(
            "[{}->{}] Could not connect to RPC " + "node: {}",
            new Object[] {syncManager.getLocalNodeId(), node.getNodeId(), message});
      } else {
        logger.trace(
            "[{}->{}] Channel future successful", syncManager.getLocalNodeId(), node.getNodeId());
      }
    }
Ejemplo n.º 13
0
  @Override
  public void connect() throws NetworkException {
    connectLock.lock();
    try {
      if (isAvaliable()) {
        logger.info("[connect] is connected to remote " + remoteAddress + ".");
        return;
      }

      ChannelFuture future = bootstrap.connect(remoteAddress);

      try {
        if (future.awaitUninterruptibly(timeout, TimeUnit.MILLISECONDS)) {

          if (future.isSuccess()) {
            disConnect();
            this.channel = future.getChannel();
            localAddress = (InetSocketAddress) this.channel.getLocalAddress();
          } else {
            logger.info("[connect] connected to remote " + remoteAddress + " failed.");
            throw new NetworkException("connected to remote " + remoteAddress + " failed.");
          }

        } else {
          logger.info("[connect] timeout connecting to remote " + remoteAddress + ".");
          throw new NetworkException("timeout connecting to remote " + remoteAddress + ".");
        }

      } catch (Throwable e) {
        logger.info("[connect] error connecting to remote " + remoteAddress + ".", e);

        throw new NetworkException("error connecting to remote " + remoteAddress + ".", e);
      } finally {
        if (!isConnected()) {
          future.cancel();
        }
      }
    } finally {
      connectLock.unlock();
    }
  }
Ejemplo n.º 14
0
        @Override
        protected Triplet<Channel, ChannelBuffer, ByteBuffer> create() {
          ChannelFuture channelFuture = bootstrap.connect(address);
          channelFuture.awaitUninterruptibly(5, TimeUnit.SECONDS);
          Triplet<Channel, ChannelBuffer, ByteBuffer> channel = null;
          if (channelFuture.isSuccess()) {
            channel =
                Triplet.of(
                    channelFuture.getChannel(),
                    ChannelBuffers.dynamicBuffer(),
                    ByteBuffer.allocateDirect(1024 * 1024));
            msgLog.logMessage("Opened a new channel to " + address, true);
            return channel;
          }

          // TODO Here it would be neat if we could ask the db to find us a new master
          // and if this still will be a slave then retry to connect.

          String msg = "MasterClient could not connect to " + address;
          msgLog.logMessage(msg, true);
          throw new HaCommunicationException(msg);
        }
Ejemplo n.º 15
0
 public synchronized void connect() {
   if (this.connected) {
     return;
   }
   logger.info("client is connecting to " + this.host + ":" + this.port);
   ChannelFuture future = null;
   try {
     future = bootstrap.connect(new InetSocketAddress(host, port));
     if (future.awaitUninterruptibly(connectTimeout, TimeUnit.MILLISECONDS)) {
       if (future.isSuccess()) {
         Channel newChannel = future.getChannel();
         try {
           // 关闭旧的连接
           Channel oldChannel = this.channel;
           if (oldChannel != null) {
             logger.info("close old netty channel " + oldChannel);
             try {
               oldChannel.close();
             } catch (Throwable t) {
             }
           }
         } finally {
           this.channel = newChannel;
         }
         logger.info("client is connected to " + this.host + ":" + this.port);
         this.connected = true;
       } else {
         logger.info("client is not connected to " + this.host + ":" + this.port);
       }
     } else {
       logger.info("timeout while connecting to " + this.host + ":" + this.port);
     }
   } catch (Throwable e) {
     logger.info("error while connecting to " + this.host + ":" + this.port, e);
   }
 }
  @Override
  public void operationComplete(ChannelFuture future) throws Exception {
    // if it was not a success then thrown an exception
    if (!future.isSuccess()) {
      Exception e =
          new CamelExchangeException(
              "Cannot write response to " + remoteAddress, exchange, future.getCause());
      consumer.getExceptionHandler().handleException(e);
    }

    // should channel be closed after complete?
    Boolean close;
    if (exchange.hasOut()) {
      close =
          exchange
              .getOut()
              .getHeader(NettyConstants.NETTY_CLOSE_CHANNEL_WHEN_COMPLETE, Boolean.class);
    } else {
      close =
          exchange
              .getIn()
              .getHeader(NettyConstants.NETTY_CLOSE_CHANNEL_WHEN_COMPLETE, Boolean.class);
    }

    // should we disconnect, the header can override the configuration
    boolean disconnect = consumer.getConfiguration().isDisconnect();
    if (close != null) {
      disconnect = close;
    }
    if (disconnect) {
      if (LOG.isTraceEnabled()) {
        LOG.trace("Closing channel when complete at address: {}", remoteAddress);
      }
      NettyHelper.close(future.getChannel());
    }
  }
  public static ControlMessage capiInvoke(RemoteCapi remoteCapi, ControlMessage request)
      throws CapiException {

    InOutClientHandler inOut = null;
    ClientBootstrap bootstrap = null;

    try {
      // configure client bootstrap
      Executor executor = Executors.newCachedThreadPool();
      bootstrap = new ClientBootstrap(new NioClientSocketChannelFactory(executor, executor));

      // use Request-Response handler business logic
      inOut = new InOutClientHandler(request);
      bootstrap.setPipelineFactory(new RemoteCapiPipelineFactory(inOut));

      // start the connection attempt
      ChannelFuture future = bootstrap.connect(remoteCapi.getRemoteAddress());

      // wait until the connection is closed or the connection attempt
      // fails
      future.getChannel().getCloseFuture().await(IN_OUT_TIMEOUT_SECONDS, TimeUnit.SECONDS);

      // in event of connection failure, throw an exception
      if (future.getCause() != null) {
        throw new CapiException(Info.EXCHANGE_RESOURCE_ERROR, future.getCause().getMessage());
      }

    } catch (InterruptedException e) {
      return null;
    } finally {
      // shut down thread pools to exit
      bootstrap.releaseExternalResources();
    }

    return inOut.getOut();
  }
Ejemplo n.º 18
0
 public void testClient() {
   // 创建客户端channel的辅助类,发起connection请求
   ClientBootstrap bootstrap =
       new ClientBootstrap(
           new NioClientSocketChannelFactory(
               Executors.newCachedThreadPool(), Executors.newCachedThreadPool()));
   // It means one same HelloWorldClientHandler instance is going to handle multiple Channels and
   // consequently the data will be corrupted.
   // 基于上面这个描述,必须用到ChannelPipelineFactory每次创建一个pipeline
   bootstrap.setPipelineFactory(
       new ChannelPipelineFactory() {
         public ChannelPipeline getPipeline() {
           ChannelPipeline pipeline = Channels.pipeline();
           pipeline.addLast("decoder", new StringDecoder());
           pipeline.addLast("encoder", new StringEncoder());
           pipeline.addLast("handler", new HelloWorldClientHandler());
           return pipeline;
         }
       });
   // 创建无连接传输channel的辅助类(UDP),包括client和server
   ChannelFuture future = bootstrap.connect(new InetSocketAddress("localhost", 8080));
   future.getChannel().getCloseFuture().awaitUninterruptibly();
   bootstrap.releaseExternalResources();
 }
Ejemplo n.º 19
0
  @Override
  protected void get(HttpServletRequest req, HttpServletResponse resp)
      throws ServletException, IOException {
    // String uri = req.getParameter("uri");
    String host = req.getParameter("host");
    String appName = req.getParameter("app");
    String streamName = req.getParameter("stream");
    String scheme = req.getParameter("scheme");
    String swfUri = req.getParameter("swfUri");
    String pageUrl = req.getParameter("pageUrl");
    logger.log(LogService.LOG_INFO, "StreamBridge params: " + req.getParameterMap());

    resp.setContentType("video");

    // add a filename
    int lastSlash = streamName.lastIndexOf('/');
    String filename = lastSlash > 0 ? streamName.substring(lastSlash + 1) : streamName;
    resp.addHeader("Content-disposition", "attachment; filename=\"" + filename + ".flv\"");

    ClientOptions co;
    if ("rtmpe".equals(scheme)) {
      logger.log(LogService.LOG_INFO, "Trying to establish encrypted connection over rtmpe");
      co = new ClientOptions(host, 1935, appName, streamName, "/tmp/dummy", true, null);
    } else {
      co = new ClientOptions(host, appName, streamName, "/tmp/dummy");
    }
    if (swfUri != null) {
      try {
        RTMP.initSwfVerification(co, new URI(swfUri));
        logger.log(LogService.LOG_INFO, "SWF verification initialized");
      } catch (Exception e) {
        logger.log(LogService.LOG_ERROR, "Couldn't initialize SWF verification", e);
      }
    }
    if (pageUrl != null) {
      Map<String, Object> params = co.getParams();
      if (params == null) {
        params = new HashMap<String, Object>();
        co.setParams(params);
      }
      params.put("pageUrl", pageUrl);
    }

    OutputStreamFlvWriter writer =
        new OutputStreamFlvWriter(
            0,
            resp.getOutputStream(),
            new DownloadListener() {
              @Override
              public void setProgress(int percent) {}

              @Override
              public void downloadFailed(Exception e) {}

              @Override
              public void downloadFinished() {}

              @Override
              public void downloadStarted() {}
            });

    co.setWriterToSave(writer);
    logger.log(
        LogService.LOG_INFO,
        "Starting streaming: " + scheme + " " + host + " " + appName + " " + streamName);
    final ClientBootstrap bootstrap =
        RtmpDownload.getBootstrap(Executors.newCachedThreadPool(), new BandwidthMeterHandler(), co);
    final ChannelFuture future =
        bootstrap.connect(new InetSocketAddress(co.getHost(), co.getPort()));
    future.awaitUninterruptibly();
    if (!future.isSuccess()) {
      logger.log(LogService.LOG_ERROR, "Error creating client connection", future.getCause());
      throw new ServletException(new IOException("Error creating client connection"));
    }
    future.getChannel();
    future.getChannel().getCloseFuture().awaitUninterruptibly();
    bootstrap.getFactory().releaseExternalResources();
  }
Ejemplo n.º 20
0
 /** The write operation has completed. */
 @Override
 public void operationComplete(ChannelFuture future) throws Exception {
   // Try closing the channel so that we don't leak descriptors.
   future.getChannel().close();
 }
  @Test
  @SuppressWarnings("deprecation")
  public void testCompatibleObjectEcho() throws Throwable {
    ServerBootstrap sb = new ServerBootstrap(newServerSocketChannelFactory(executor));
    ClientBootstrap cb = new ClientBootstrap(newClientSocketChannelFactory(executor));

    EchoHandler sh = new EchoHandler();
    EchoHandler ch = new EchoHandler();

    sb.getPipeline().addLast("decoder", new CompatibleObjectDecoder());
    sb.getPipeline().addLast("encoder", new CompatibleObjectEncoder());
    sb.getPipeline().addLast("handler", sh);

    cb.getPipeline().addLast("decoder", new CompatibleObjectDecoder());
    cb.getPipeline().addLast("encoder", new CompatibleObjectEncoder());
    cb.getPipeline().addLast("handler", ch);

    Channel sc = sb.bind(new InetSocketAddress(0));
    int port = ((InetSocketAddress) sc.getLocalAddress()).getPort();

    ChannelFuture ccf = cb.connect(new InetSocketAddress(TestUtil.getLocalHost(), port));
    assertTrue(ccf.awaitUninterruptibly().isSuccess());

    Channel cc = ccf.getChannel();
    for (String element : data) {
      cc.write(element);
    }

    while (ch.counter < data.length) {
      if (sh.exception.get() != null) {
        break;
      }
      if (ch.exception.get() != null) {
        break;
      }

      try {
        Thread.sleep(1);
      } catch (InterruptedException e) {
        // Ignore.
      }
    }

    while (sh.counter < data.length) {
      if (sh.exception.get() != null) {
        break;
      }
      if (ch.exception.get() != null) {
        break;
      }

      try {
        Thread.sleep(1);
      } catch (InterruptedException e) {
        // Ignore.
      }
    }

    sh.channel.close().awaitUninterruptibly();
    ch.channel.close().awaitUninterruptibly();
    sc.close().awaitUninterruptibly();

    if (sh.exception.get() != null && !(sh.exception.get() instanceof IOException)) {
      throw sh.exception.get();
    }
    if (ch.exception.get() != null && !(ch.exception.get() instanceof IOException)) {
      throw ch.exception.get();
    }
    if (sh.exception.get() != null) {
      throw sh.exception.get();
    }
    if (ch.exception.get() != null) {
      throw ch.exception.get();
    }
  }
Ejemplo n.º 22
0
  private static boolean checkPort(final InetSocketAddress remoteAddress) {
    final ClientBootstrap bootstrap =
        new ClientBootstrap(new OioClientSocketChannelFactory(new PooledThreadExecutor()));
    bootstrap.setOption("child.tcpNoDelay", true);

    final AtomicBoolean result = new AtomicBoolean(false);
    final Semaphore semaphore = new Semaphore();
    semaphore.down(); // must call to down() here to ensure that down was called _before_ up()
    bootstrap.setPipeline(
        pipeline(
            new HttpResponseDecoder(),
            new HttpRequestEncoder(),
            new SimpleChannelUpstreamHandler() {
              @Override
              public void messageReceived(ChannelHandlerContext context, MessageEvent e)
                  throws Exception {
                try {
                  if (e.getMessage() instanceof HttpResponse) {
                    HttpResponse response = (HttpResponse) e.getMessage();
                    if (response.getStatus().equals(OK)
                        && response
                            .getContent()
                            .toString(CharsetUtil.US_ASCII)
                            .equals(getApplicationStartTime())) {
                      LOG.info("port check: current OS must be marked as normal");
                      result.set(true);
                    }
                  }
                } finally {
                  semaphore.up();
                }
              }

              @Override
              public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e)
                  throws Exception {
                try {
                  LOG.error(e.getCause());
                } finally {
                  semaphore.up();
                }
              }
            }));

    ChannelFuture connectFuture = null;
    try {
      connectFuture = bootstrap.connect(remoteAddress);
      if (!waitComplete(connectFuture, "connect")) {
        return false;
      }
      ChannelFuture writeFuture =
          connectFuture
              .getChannel()
              .write(new DefaultHttpRequest(HTTP_1_1, HttpMethod.GET, START_TIME_PATH));
      if (!waitComplete(writeFuture, "write")) {
        return false;
      }

      try {
        // yes, 30 seconds. I always get timeout in Linux in Parallels if I set to 2 seconds.
        // In any case all work is done in pooled thread (IDE init time isn't affected)
        if (!semaphore.waitForUnsafe(30000)) {
          LOG.info("port check: semaphore down timeout");
        }
      } catch (InterruptedException e) {
        LOG.info("port check: semaphore interrupted", e);
      }
    } finally {
      if (connectFuture != null) {
        connectFuture.getChannel().close().awaitUninterruptibly();
      }
      bootstrap.releaseExternalResources();
    }
    return result.get();
  }
  @Test
  public void testSslEcho() throws Throwable {
    ServerBootstrap sb =
        new ServerBootstrap(newServerSocketChannelFactory(Executors.newCachedThreadPool()));
    ClientBootstrap cb =
        new ClientBootstrap(newClientSocketChannelFactory(Executors.newCachedThreadPool()));

    EchoHandler sh = new EchoHandler(true);
    EchoHandler ch = new EchoHandler(false);

    SSLEngine sse = SecureChatSslContextFactory.getServerContext().createSSLEngine();
    SSLEngine cse = SecureChatSslContextFactory.getClientContext().createSSLEngine();
    sse.setUseClientMode(false);
    cse.setUseClientMode(true);

    // Workaround for blocking I/O transport write-write dead lock.
    sb.setOption("receiveBufferSize", 1048576);
    sb.setOption("receiveBufferSize", 1048576);

    sb.getPipeline().addFirst("ssl", new SslHandler(sse));
    sb.getPipeline().addLast("handler", sh);
    cb.getPipeline().addFirst("ssl", new SslHandler(cse));
    cb.getPipeline().addLast("handler", ch);
    ExecutorService eventExecutor = null;
    if (isExecutorRequired()) {
      eventExecutor = new OrderedMemoryAwareThreadPoolExecutor(16, 0, 0);
      sb.getPipeline().addFirst("executor", new ExecutionHandler(eventExecutor));
      cb.getPipeline().addFirst("executor", new ExecutionHandler(eventExecutor));
    }

    Channel sc = sb.bind(new InetSocketAddress(0));
    int port = ((InetSocketAddress) sc.getLocalAddress()).getPort();

    ChannelFuture ccf = cb.connect(new InetSocketAddress(TestUtil.getLocalHost(), port));
    ccf.awaitUninterruptibly();
    if (!ccf.isSuccess()) {
      logger.error("Connection attempt failed", ccf.getCause());
      sc.close().awaitUninterruptibly();
    }
    assertTrue(ccf.isSuccess());

    Channel cc = ccf.getChannel();
    ChannelFuture hf = cc.getPipeline().get(SslHandler.class).handshake();
    hf.awaitUninterruptibly();
    if (!hf.isSuccess()) {
      logger.error("Handshake failed", hf.getCause());
      sh.channel.close().awaitUninterruptibly();
      ch.channel.close().awaitUninterruptibly();
      sc.close().awaitUninterruptibly();
    }

    assertTrue(hf.isSuccess());

    for (int i = 0; i < data.length; ) {
      int length = Math.min(random.nextInt(1024 * 64), data.length - i);
      cc.write(ChannelBuffers.wrappedBuffer(data, i, length));
      i += length;
    }

    while (ch.counter < data.length) {
      if (sh.exception.get() != null) {
        break;
      }
      if (ch.exception.get() != null) {
        break;
      }

      try {
        Thread.sleep(1);
      } catch (InterruptedException e) {
        // Ignore.
      }
    }

    while (sh.counter < data.length) {
      if (sh.exception.get() != null) {
        break;
      }
      if (ch.exception.get() != null) {
        break;
      }

      try {
        Thread.sleep(1);
      } catch (InterruptedException e) {
        // Ignore.
      }
    }

    sh.channel.close().awaitUninterruptibly();
    ch.channel.close().awaitUninterruptibly();
    sc.close().awaitUninterruptibly();
    cb.shutdown();
    sb.shutdown();
    cb.releaseExternalResources();
    sb.releaseExternalResources();

    if (eventExecutor != null) {
      eventExecutor.shutdown();
    }
    if (sh.exception.get() != null && !(sh.exception.get() instanceof IOException)) {
      throw sh.exception.get();
    }
    if (ch.exception.get() != null && !(ch.exception.get() instanceof IOException)) {
      throw ch.exception.get();
    }
    if (sh.exception.get() != null) {
      throw sh.exception.get();
    }
    if (ch.exception.get() != null) {
      throw ch.exception.get();
    }
  }
Ejemplo n.º 24
0
  public static void main(String[] args) {
    final int payloadSize = 100;
    int CYCLE_SIZE = 50000;
    final long NUMBER_OF_ITERATIONS = 500000;

    ChannelBuffer message = ChannelBuffers.buffer(100);
    for (int i = 0; i < message.capacity(); i++) {
      message.writeByte((byte) i);
    }

    // Configure the server.
    ServerBootstrap serverBootstrap =
        new ServerBootstrap(
            new NioServerSocketChannelFactory(
                Executors.newCachedThreadPool(), Executors.newCachedThreadPool()));

    // Set up the pipeline factory.
    serverBootstrap.setPipelineFactory(
        new ChannelPipelineFactory() {
          @Override
          public ChannelPipeline getPipeline() throws Exception {
            return Channels.pipeline(new EchoServerHandler());
          }
        });

    // Bind and start to accept incoming connections.
    serverBootstrap.bind(new InetSocketAddress(9000));

    ClientBootstrap clientBootstrap =
        new ClientBootstrap(
            new NioClientSocketChannelFactory(
                Executors.newCachedThreadPool(), Executors.newCachedThreadPool()));

    //        ClientBootstrap clientBootstrap = new ClientBootstrap(
    //                new OioClientSocketChannelFactory(Executors.newCachedThreadPool()));

    // Set up the pipeline factory.
    final EchoClientHandler clientHandler = new EchoClientHandler();
    clientBootstrap.setPipelineFactory(
        new ChannelPipelineFactory() {
          @Override
          public ChannelPipeline getPipeline() throws Exception {
            return Channels.pipeline(clientHandler);
          }
        });

    // Start the connection attempt.
    ChannelFuture future = clientBootstrap.connect(new InetSocketAddress("localhost", 9000));
    future.awaitUninterruptibly();
    Channel clientChannel = future.getChannel();

    System.out.println("Warming up...");
    for (long i = 0; i < 10000; i++) {
      clientHandler.latch = new CountDownLatch(1);
      clientChannel.write(message);
      try {
        clientHandler.latch.await();
      } catch (InterruptedException e) {
        e.printStackTrace();
      }
    }
    System.out.println("Warmed up");

    long start = System.currentTimeMillis();
    long cycleStart = System.currentTimeMillis();
    for (long i = 1; i < NUMBER_OF_ITERATIONS; i++) {
      clientHandler.latch = new CountDownLatch(1);
      clientChannel.write(message);
      try {
        clientHandler.latch.await();
      } catch (InterruptedException e) {
        e.printStackTrace();
      }
      if ((i % CYCLE_SIZE) == 0) {
        long cycleEnd = System.currentTimeMillis();
        System.out.println(
            "Ran 50000, TPS " + (CYCLE_SIZE / ((double) (cycleEnd - cycleStart) / 1000)));
        cycleStart = cycleEnd;
      }
    }
    long end = System.currentTimeMillis();
    long seconds = (end - start) / 1000;
    System.out.println(
        "Ran ["
            + NUMBER_OF_ITERATIONS
            + "] iterations, payload ["
            + payloadSize
            + "]: took ["
            + seconds
            + "], TPS: "
            + ((double) NUMBER_OF_ITERATIONS) / seconds);

    clientChannel.close().awaitUninterruptibly();
    clientBootstrap.releaseExternalResources();
    serverBootstrap.releaseExternalResources();
  }
  public void run() throws IOException {
    String scheme = uri.getScheme() == null ? "http" : uri.getScheme();

    // Configure the client.
    ClientBootstrap b =
        new ClientBootstrap(
            new HttpTunnelingClientSocketChannelFactory(
                new OioClientSocketChannelFactory(Executors.newCachedThreadPool())));

    b.setPipelineFactory(
        new ChannelPipelineFactory() {
          public ChannelPipeline getPipeline() throws Exception {
            return Channels.pipeline(
                new StringDecoder(),
                new StringEncoder(),
                new LoggingHandler(InternalLogLevel.INFO));
          }
        });

    // Set additional options required by the HTTP tunneling transport.
    b.setOption("serverName", uri.getHost());
    b.setOption("serverPath", uri.getRawPath());

    // Configure SSL if necessary
    if ("https".equals(scheme)) {
      b.setOption("sslContext", SecureChatSslContextFactory.getClientContext());
    } else if (!"http".equals(scheme)) {
      // Only HTTP and HTTPS are supported.
      System.err.println("Only HTTP(S) is supported.");
      return;
    }

    // Make the connection attempt.
    ChannelFuture channelFuture = b.connect(new InetSocketAddress(uri.getHost(), uri.getPort()));
    channelFuture.awaitUninterruptibly();

    // Read commands from the stdin.
    System.out.println("Enter text ('quit' to exit)");
    ChannelFuture lastWriteFuture = null;
    BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
    for (; ; ) {
      String line = in.readLine();
      if (line == null || "quit".equalsIgnoreCase(line)) {
        break;
      }

      // Sends the received line to the server.
      lastWriteFuture = channelFuture.getChannel().write(line);
    }

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

    channelFuture.getChannel().close();
    // Wait until the connection is closed or the connection attempt fails.
    channelFuture.getChannel().getCloseFuture().awaitUninterruptibly();

    // Shut down all threads.
    b.releaseExternalResources();
  }
Ejemplo n.º 26
0
  private static void updateHosts() {
    boolean changed = false;
    synchronized (hosts) {
      for (Host host : hosts.getObjectList()) {
        AsyncServiceManagerServer proxy = proxies.get(host.getName());
        boolean connected = false;
        if (proxy != null) {
          try {
            connected =
                ((Boolean) ((Future) proxy.isServiceManager()).get(10, TimeUnit.SECONDS))
                    .booleanValue();
          } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
          }
        } else {
          ClientBootstrap bootstrap =
              new ClientBootstrap(new NioClientSocketChannelFactory(executor, executor));

          HessianProxyFactory factory =
              new HessianProxyFactory(executor, host.getName() + ":" + host.getPort());
          bootstrap.setPipelineFactory(new RPCClientPipelineFactory(executor, factory));

          // Start the connection attempt.
          ChannelFuture future =
              bootstrap.connect(new InetSocketAddress(host.getName(), host.getPort()));
          try {
            future.await(10000);
            connected = future.isSuccess();

            if (connected) {
              Map options = new HashMap();
              proxy =
                  (AsyncServiceManagerServer)
                      factory.create(
                          AsyncServiceManagerServer.class,
                          ClientMain.class.getClassLoader(),
                          options);
              connected =
                  ((Boolean) ((Future) proxy.isServiceManager()).get(10, TimeUnit.SECONDS))
                      .booleanValue();
              if (connected) {
                proxies.put(host.getName(), proxy);
                Host newHost = new Host(host.getName(), host.getPort());
                newHost.setIncluded(host.isIncluded());
                newHost.setState("CONNECTED");
                hosts.updateObject(newHost);
                if (host.isIncluded()) servicesTable.addService(host.getName(), proxy);
              } else future.getChannel().close();
            }
          } catch (Exception e) {
            System.out.println("error accessing " + host.getName());
            connected = false;
            if (future != null) future.getChannel().close();
          }
        }

        if (!connected) {
          disconnect(host, proxies.remove(host.getName()));
          changed = true;
        } else if (proxy == null && !"DISCONNECTED".equals(host.getState())) {
          Host newHost = new Host(host.getName(), host.getPort());
          newHost.setIncluded(host.isIncluded());
          newHost.setState("DISCONNECTED");
          hosts.updateObject(newHost);
        }
      }
    }
  }