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();
  }
  @Override
  public DatabusRequest process(DatabusRequest request)
      throws IOException, RequestProcessingException {
    // Close the channel

    LOG.debug("Waiting for raw channel to close");

    ChannelFuture future =
        request.getResponseContent().getRawChannel().close().awaitUninterruptibly();

    try {
      future.await();
    } catch (InterruptedException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }

    LOG.debug("Done waiting for raw channel to close");

    return request;
  }
Exemple #3
0
  private <K, V, T extends RedisAsyncConnection<K, V>> T connect(
      CommandHandler<K, V> handler, T connection) {
    try {
      ConnectionWatchdog watchdog = new ConnectionWatchdog(bootstrap, channels, timer);
      ChannelPipeline pipeline = Channels.pipeline(watchdog, handler, connection);
      Channel channel = bootstrap.getFactory().newChannel(pipeline);

      ChannelFuture future = channel.connect((SocketAddress) bootstrap.getOption("remoteAddress"));
      future.await();

      if (!future.isSuccess()) {
        throw future.getCause();
      }

      watchdog.setReconnect(true);

      return connection;
    } catch (Throwable e) {
      throw new RedisException("Unable to connect", e);
    }
  }
 /**
  * Wait for the client to be connected (Passive) or Wait for the server to be connected to the
  * client (Active)
  *
  * @return True if the connection is OK
  * @throws Reply425Exception
  */
 public boolean openDataConnection() throws Reply425Exception {
   // Prepare this Data channel to be closed ;-)
   // In fact, prepare the future close op which should occur since it is
   // now opened
   closedDataChannel = new WaarpFuture(true);
   FtpDataAsyncConn dataAsyncConn = session.getDataConn();
   if (!dataAsyncConn.isStreamFile()) {
     // FIXME isConnected or isDNHReady ?
     if (dataAsyncConn.isConnected()) {
       // Already connected
       // logger.debug("Connection already open");
       session.setReplyCode(
           ReplyCode.REPLY_125_DATA_CONNECTION_ALREADY_OPEN,
           dataAsyncConn.getType().name() + " mode data connection already open");
       return true;
     }
   } else {
     // Stream, Data Connection should not be opened
     if (dataAsyncConn.isConnected()) {
       logger.error("Connection already open but should not since in Stream mode");
       setTransferAbortedFromInternal(false);
       throw new Reply425Exception("Connection already open but should not since in Stream mode");
     }
   }
   // Need to open connection
   session.setReplyCode(
       ReplyCode.REPLY_150_FILE_STATUS_OKAY,
       "Opening " + dataAsyncConn.getType().name() + " mode data connection");
   if (dataAsyncConn.isPassiveMode()) {
     if (!dataAsyncConn.isBind()) {
       // No passive connection prepared
       throw new Reply425Exception("No passive data connection prepared");
     }
     // Wait for the connection to be done by the client
     // logger.debug("Passive mode standby");
     try {
       dataChannel = waitForOpenedDataChannel();
       dataAsyncConn.setNewOpenedDataChannel(dataChannel);
     } catch (InterruptedException e) {
       logger.warn("Connection abort in passive mode", e);
       // Cannot open connection
       throw new Reply425Exception("Cannot open passive data connection");
     }
     // logger.debug("Passive mode connected");
   } else {
     // Wait for the server to be connected to the client
     InetAddress inetAddress = dataAsyncConn.getLocalAddress().getAddress();
     InetSocketAddress inetSocketAddress = dataAsyncConn.getRemoteAddress();
     if (session
         .getConfiguration()
         .getFtpInternalConfiguration()
         .hasFtpSession(inetAddress, inetSocketAddress)) {
       throw new Reply425Exception(
           "Cannot open active data connection since remote address is already in use: "
               + inetSocketAddress);
     }
     // logger.debug("Active mode standby");
     ClientBootstrap clientBootstrap =
         session
             .getConfiguration()
             .getFtpInternalConfiguration()
             .getActiveBootstrap(session.isDataSsl());
     session.getConfiguration().setNewFtpSession(inetAddress, inetSocketAddress, session);
     // Set the session for the future dataChannel
     String mylog = session.toString();
     logger.debug(
         "DataConn for: "
             + session.getCurrentCommand().getCommand()
             + " to "
             + inetSocketAddress.toString());
     ChannelFuture future =
         clientBootstrap.connect(inetSocketAddress, dataAsyncConn.getLocalAddress());
     try {
       future.await();
     } catch (InterruptedException e1) {
     }
     if (!future.isSuccess()) {
       logger.warn(
           "Connection abort in active mode from future while session: "
               + session.toString()
               + "\nTrying connect to: "
               + inetSocketAddress.toString()
               + "\nWas: "
               + mylog,
           future.getCause());
       // Cannot open connection
       session.getConfiguration().delFtpSession(inetAddress, inetSocketAddress);
       throw new Reply425Exception("Cannot open active data connection");
     }
     try {
       dataChannel = waitForOpenedDataChannel();
       dataAsyncConn.setNewOpenedDataChannel(dataChannel);
     } catch (InterruptedException e) {
       logger.warn("Connection abort in active mode", e);
       // Cannot open connection
       session.getConfiguration().delFtpSession(inetAddress, inetSocketAddress);
       throw new Reply425Exception("Cannot open active data connection");
     }
     // logger.debug("Active mode connected");
   }
   if (dataChannel == null) {
     // Cannot have a new Data connection since shutdown
     if (!dataAsyncConn.isPassiveMode()) {
       session
           .getConfiguration()
           .getFtpInternalConfiguration()
           .delFtpSession(
               dataAsyncConn.getLocalAddress().getAddress(), dataAsyncConn.getRemoteAddress());
     }
     throw new Reply425Exception("Cannot open data connection, shuting down");
   }
   return true;
 }
 public boolean sendFile() {
   R66File r66file = localChannelReference.getSession().getFile();
   boolean retrieveDone = false;
   try {
     DataBlock block = null;
     try {
       block = r66file.readDataBlock();
     } catch (FileEndOfTransferException e) {
       // Last block (in fact, no data to read)
       retrieveDone = true;
       return retrieveDone;
     }
     if (block == null) {
       // Last block (in fact, no data to read)
       retrieveDone = true;
       return retrieveDone;
     }
     ChannelFuture future1 = null, future2 = null;
     if (block != null) {
       future1 = this.writeWhenPossible(block);
     }
     // While not last block
     while (block != null && !block.isEOF()) {
       try {
         block = r66file.readDataBlock();
       } catch (FileEndOfTransferException e) {
         // Wait for last write
         retrieveDone = true;
         try {
           future1.await();
         } catch (InterruptedException e1) {
         }
         return future1.isSuccess();
       }
       future2 = this.writeWhenPossible(block);
       try {
         future1.await();
       } catch (InterruptedException e) {
       }
       if (!future1.isSuccess()) {
         return false;
       }
       future1 = future2;
     }
     // Wait for last write
     if (future1 != null) {
       try {
         future1.await();
       } catch (InterruptedException e) {
       }
       return future1.isSuccess();
     }
     retrieveDone = true;
     return retrieveDone;
   } catch (FileTransferException e) {
     // An error occurs!
     this.transferInError(new OpenR66ProtocolSystemException(e));
     return false;
   } catch (OpenR66ProtocolPacketException e) {
     // An error occurs!
     this.transferInError(e);
     return false;
   } catch (OpenR66RunnerErrorException e) {
     // An error occurs!
     this.transferInError(e);
     return false;
   } catch (OpenR66ProtocolSystemException e) {
     // An error occurs!
     this.transferInError(e);
     return false;
   }
 }
  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);
        }
      }
    }
  }