IoFuture<Connection> connect(FutureResult<Connection> orig) {
   AtomicReference<FutureResult<Connection>> futureConnectionRef = this.futureConnectionRef;
   FutureResult<Connection> oldVal;
   oldVal = futureConnectionRef.get();
   if (oldVal != orig) {
     return oldVal.getIoFuture();
   }
   final FutureResult<Connection> futureResult = new FutureResult<>();
   while (!futureConnectionRef.compareAndSet(oldVal, futureResult)) {
     oldVal = futureConnectionRef.get();
     if (oldVal != orig) {
       // discard our new one
       return oldVal.getIoFuture();
     }
   }
   IoFuture<Connection> realFuture;
   try {
     realFuture = endpoint.connect(uri);
   } catch (IOException e) {
     realFuture = new FailedIoFuture<>(e);
   }
   splice(futureResult, realFuture);
   final IoFuture<Connection> ioFuture = futureResult.getIoFuture();
   ioFuture.addNotifier(HANDLER, this);
   return ioFuture;
 }
  @Test
  public void testClosePrepared() throws Exception {
    final BlockingOperationListener listener = new BlockingOperationListener();
    final TestOperationHandler handler =
        new TestOperationHandler() {
          @Override
          public void execute(
              ModelNode operation,
              OperationMessageHandler handler,
              OperationAttachments attachments)
              throws Exception {
            //
          }
        };
    final TestUpdateWrapper wrapper = createTestClient(0, handler);
    final Future<OperationResponse> futureResult = wrapper.execute(listener);
    listener.retrievePreparedOperation();

    futureConnection.get().close();

    try {
      futureResult.get();
      Assert.fail();
    } catch (CancellationException expected) {
      //
    }
  }
 @After
 public void stopChannels() throws Exception {
   for (final Channel channel : channels) {
     channel.close();
   }
   futureConnection.get().close();
   channelServer.close();
   channelServer = null;
 }
Beispiel #4
0
  private boolean connectUsingRemoting(
      CommandContext cmdCtx, RemotingMBeanServerConnection rmtMBeanSvrConn)
      throws IOException, CliInitializationException {
    Connection conn = rmtMBeanSvrConn.getConnection();
    Channel channel;
    final IoFuture<Channel> futureChannel = conn.openChannel("management", OptionMap.EMPTY);
    IoFuture.Status result = futureChannel.await(5, TimeUnit.SECONDS);
    if (result == IoFuture.Status.DONE) {
      channel = futureChannel.get();
    } else {
      return false;
    }

    ModelControllerClient modelCtlrClient =
        ExistingChannelModelControllerClient.createReceiving(channel, createExecutor());
    cmdCtx.bindClient(modelCtlrClient);

    return true;
  }
  static VersionedConnection createVersionedConnection(
      final Channel channel, final Map<String, ?> environment, final JMXServiceURL serviceURL)
      throws IOException {
    // We don't want to start chaining the use of IoFutures otherwise multiple threads are tied up
    // for a single negotiation process so negotiate the connection sequentially.

    IoFuture<InitialHeader> futureHeader = ClientVersionReceiver.getInitialHeader(channel);
    IoFuture.Status result = futureHeader.await(5, TimeUnit.SECONDS);
    switch (result) {
      case DONE:
        break;
      case FAILED:
        throw futureHeader.getException();
      default:
        throw new IOException("Timeout out waiting for header, status=" + result.toString());
    }

    InitialHeader header = futureHeader.get();

    Versions versions = new Versions(environment);
    Set<Byte> supportedVersions =
        versions.getSupportedVersions(getRequiredCapabilities(serviceURL));

    // Find the highest version. - By this point the exceptional handling of version 0x00 will have
    // completed.
    byte highest = 0x00;
    for (byte current : header.versions) {
      // Only accept it if it is one of the supported versions otherwise ignore as noise.
      if (supportedVersions.contains(current) && current > highest) {
        highest = current;
      }
    }

    if (highest == 0x00) {
      throw new IllegalStateException("No matching supported protocol version found.");
    }

    // getVersionedConnection may also make use of an IoFuture but our previous use of one has
    // ended.
    return versions.getVersionedConnection(highest, channel, serviceURL);
  }
  @Before
  public void testStart() throws IOException, URISyntaxException, InterruptedException {
    System.gc();
    System.runFinalization();
    Logger.getLogger("TEST").infof("Running test %s", name.getMethodName());
    final FutureResult<Channel> passer = new FutureResult<Channel>();
    serviceRegistration =
        endpoint.registerService(
            "org.jboss.test",
            new OpenListener() {
              public void channelOpened(final Channel channel) {
                passer.setResult(channel);
              }

              public void registrationTerminated() {}
            },
            OptionMap.EMPTY);
    IoFuture<Connection> futureConnection =
        AuthenticationContext.empty()
            .with(
                MatchRule.ALL,
                AuthenticationConfiguration.EMPTY
                    .useName("bob")
                    .usePassword("pass")
                    .allowSaslMechanisms("SCRAM-SHA-256"))
            .run(
                new PrivilegedAction<IoFuture<Connection>>() {
                  public IoFuture<Connection> run() {
                    try {
                      return endpoint.connect(new URI("remote://localhost:30123"), OptionMap.EMPTY);
                    } catch (IOException | URISyntaxException e) {
                      throw new RuntimeException(e);
                    }
                  }
                });
    connection = futureConnection.get();
    IoFuture<Channel> futureChannel = connection.openChannel("org.jboss.test", OptionMap.EMPTY);
    clientChannel = futureChannel.get();
    serverChannel = passer.getIoFuture().get();
    assertNotNull(serverChannel);
  }
  public Connection connectSync(
      CallbackHandler handler, Map<String, String> saslOptions, SSLContext sslContext)
      throws IOException {
    CallbackHandler actualHandler = handler != null ? handler : new AnonymousCallbackHandler();
    WrapperCallbackHandler wrapperHandler = new WrapperCallbackHandler(actualHandler);
    final IoFuture<Connection> future = connect(wrapperHandler, saslOptions, sslContext);
    long timeoutMillis = configuration.getConnectionTimeout();
    IoFuture.Status status = future.await(timeoutMillis, TimeUnit.MILLISECONDS);
    while (status == IoFuture.Status.WAITING) {
      if (wrapperHandler.isInCall()) {
        // If there is currently an interaction with the user just wait again.
        status = future.await(timeoutMillis, TimeUnit.MILLISECONDS);
      } else {
        long lastInteraction = wrapperHandler.getCallFinished();
        if (lastInteraction > 0) {
          long now = System.currentTimeMillis();
          long timeSinceLast = now - lastInteraction;
          if (timeSinceLast < timeoutMillis) {
            // As this point we are setting the timeout based on the time of the last interaction
            // with the user, if there is any time left we will wait for that time but dont wait for
            // a full timeout.
            status = future.await(timeoutMillis - timeSinceLast, TimeUnit.MILLISECONDS);
          } else {
            status = null;
          }
        } else {
          status = null; // Just terminate status processing.
        }
      }
    }

    if (status == IoFuture.Status.DONE) {
      return future.get();
    }
    if (status == IoFuture.Status.FAILED) {
      throw ProtocolMessages.MESSAGES.failedToConnect(uri, future.getException());
    }
    throw ProtocolMessages.MESSAGES.couldNotConnect(uri);
  }
 void splice(FutureResult<Connection> futureResult, IoFuture<Connection> realFuture) {
   // always add in this order
   futureResult.addCancelHandler(realFuture);
   realFuture.addNotifier(IoUtils.resultNotifier(), futureResult);
 }
 /**
  * Create the protocol client to talk to the remote controller.
  *
  * @return the client
  * @throws Exception
  */
 TransactionalProtocolClient createClient() throws Exception {
   final Connection connection = futureConnection.get();
   final IoFuture<Channel> channelIoFuture = connection.openChannel(TEST_CHANNEL, OptionMap.EMPTY);
   return createClient(channelIoFuture.get());
 }
Beispiel #10
0
  public void testAcceptor() throws Exception {
    threadFactory.clear();
    log.info("Test: testAcceptor");
    final CountDownLatch ioLatch = new CountDownLatch(4);
    final CountDownLatch closeLatch = new CountDownLatch(2);
    final AtomicBoolean clientOpened = new AtomicBoolean();
    final AtomicBoolean clientReadOnceOK = new AtomicBoolean();
    final AtomicBoolean clientReadDoneOK = new AtomicBoolean();
    final AtomicBoolean clientReadTooMuch = new AtomicBoolean();
    final AtomicBoolean clientWriteOK = new AtomicBoolean();
    final AtomicBoolean serverOpened = new AtomicBoolean();
    final AtomicBoolean serverReadOnceOK = new AtomicBoolean();
    final AtomicBoolean serverReadDoneOK = new AtomicBoolean();
    final AtomicBoolean serverReadTooMuch = new AtomicBoolean();
    final AtomicBoolean serverWriteOK = new AtomicBoolean();
    final byte[] bytes = "Ummagumma!".getBytes("UTF-8");
    final Xnio xnio = Xnio.getInstance("nio");
    final ReadChannelThread readChannelThread = xnio.createReadChannelThread(threadFactory);
    final ReadChannelThread clientReadChannelThread = xnio.createReadChannelThread(threadFactory);
    final WriteChannelThread writeChannelThread = xnio.createWriteChannelThread(threadFactory);
    final WriteChannelThread clientWriteChannelThread =
        xnio.createWriteChannelThread(threadFactory);
    final ConnectionChannelThread connectionChannelThread =
        xnio.createConnectionChannelThread(threadFactory);
    try {
      final FutureResult<InetSocketAddress> futureAddressResult =
          new FutureResult<InetSocketAddress>();
      final IoFuture<InetSocketAddress> futureAddress = futureAddressResult.getIoFuture();
      final IoFuture<? extends ConnectedStreamChannel> futureConnection =
          xnio.acceptStream(
              new InetSocketAddress(Inet4Address.getByAddress(new byte[] {127, 0, 0, 1}), 0),
              connectionChannelThread,
              clientReadChannelThread,
              clientWriteChannelThread,
              new ChannelListener<ConnectedStreamChannel>() {
                private final ByteBuffer inboundBuf = ByteBuffer.allocate(512);
                private int readCnt = 0;
                private final ByteBuffer outboundBuf = ByteBuffer.wrap(bytes);

                public void handleEvent(final ConnectedStreamChannel channel) {
                  channel
                      .getCloseSetter()
                      .set(
                          new ChannelListener<ConnectedStreamChannel>() {
                            public void handleEvent(final ConnectedStreamChannel channel) {
                              closeLatch.countDown();
                            }
                          });
                  channel
                      .getReadSetter()
                      .set(
                          new ChannelListener<ConnectedStreamChannel>() {
                            public void handleEvent(final ConnectedStreamChannel channel) {
                              try {
                                final int res = channel.read(inboundBuf);
                                if (res == 0) {
                                  channel.resumeReads();
                                } else if (res == -1) {
                                  serverReadDoneOK.set(true);
                                  ioLatch.countDown();
                                  channel.shutdownReads();
                                } else {
                                  final int ttl = readCnt += res;
                                  if (ttl == bytes.length) {
                                    serverReadOnceOK.set(true);
                                  } else if (ttl > bytes.length) {
                                    serverReadTooMuch.set(true);
                                    IoUtils.safeClose(channel);
                                    return;
                                  }
                                  channel.resumeReads();
                                }
                              } catch (IOException e) {
                                log.errorf(e, "Server read failed");
                                IoUtils.safeClose(channel);
                              }
                            }
                          });
                  channel
                      .getWriteSetter()
                      .set(
                          new ChannelListener<ConnectedStreamChannel>() {
                            public void handleEvent(final ConnectedStreamChannel channel) {
                              try {
                                channel.write(outboundBuf);
                                if (!outboundBuf.hasRemaining()) {
                                  serverWriteOK.set(true);
                                  Channels.shutdownWritesBlocking(channel);
                                  ioLatch.countDown();
                                }
                              } catch (IOException e) {
                                log.errorf(e, "Server write failed");
                                IoUtils.safeClose(channel);
                              }
                            }
                          });
                  channel.resumeReads();
                  channel.resumeWrites();
                  serverOpened.set(true);
                }
              },
              new ChannelListener<BoundChannel>() {
                public void handleEvent(final BoundChannel channel) {
                  futureAddressResult.setResult(channel.getLocalAddress(InetSocketAddress.class));
                }
              },
              OptionMap.create(Options.REUSE_ADDRESSES, Boolean.TRUE));
      final InetSocketAddress localAddress = futureAddress.get();
      final IoFuture<? extends ConnectedStreamChannel> ioFuture =
          xnio.connectStream(
              localAddress,
              connectionChannelThread,
              readChannelThread,
              writeChannelThread,
              new ChannelListener<ConnectedStreamChannel>() {
                private final ByteBuffer inboundBuf = ByteBuffer.allocate(512);
                private int readCnt = 0;
                private final ByteBuffer outboundBuf = ByteBuffer.wrap(bytes);

                public void handleEvent(final ConnectedStreamChannel channel) {
                  channel
                      .getCloseSetter()
                      .set(
                          new ChannelListener<ConnectedStreamChannel>() {
                            public void handleEvent(final ConnectedStreamChannel channel) {
                              closeLatch.countDown();
                            }
                          });
                  channel
                      .getReadSetter()
                      .set(
                          new ChannelListener<ConnectedStreamChannel>() {
                            public void handleEvent(final ConnectedStreamChannel channel) {
                              try {
                                final int res = channel.read(inboundBuf);
                                if (res == 0) {
                                  channel.resumeReads();
                                } else if (res == -1) {
                                  channel.shutdownReads();
                                  clientReadDoneOK.set(true);
                                  ioLatch.countDown();
                                } else {
                                  final int ttl = readCnt += res;
                                  if (ttl == bytes.length) {
                                    clientReadOnceOK.set(true);
                                  } else if (ttl > bytes.length) {
                                    clientReadTooMuch.set(true);
                                    IoUtils.safeClose(channel);
                                    return;
                                  }
                                  channel.resumeReads();
                                }
                              } catch (IOException e) {
                                log.errorf(e, "Client read failed");
                                IoUtils.safeClose(channel);
                              }
                            }
                          });
                  channel
                      .getWriteSetter()
                      .set(
                          new ChannelListener<ConnectedStreamChannel>() {
                            public void handleEvent(final ConnectedStreamChannel channel) {
                              try {
                                channel.write(outboundBuf);
                                if (!outboundBuf.hasRemaining()) {
                                  clientWriteOK.set(true);
                                  Channels.shutdownWritesBlocking(channel);
                                  ioLatch.countDown();
                                }
                              } catch (IOException e) {
                                log.errorf(e, "Client write failed");
                                IoUtils.safeClose(channel);
                              }
                            }
                          });
                  channel.resumeReads();
                  channel.resumeWrites();
                  clientOpened.set(true);
                }
              },
              null,
              OptionMap.EMPTY);
      assertTrue("Read timed out", ioLatch.await(500L, TimeUnit.MILLISECONDS));
      assertTrue("Close timed out", closeLatch.await(500L, TimeUnit.MILLISECONDS));
      assertFalse("Client read too much", clientReadTooMuch.get());
      assertTrue("Client read OK", clientReadOnceOK.get());
      assertTrue("Client read done", clientReadDoneOK.get());
      assertTrue("Client write OK", clientWriteOK.get());
      assertFalse("Server read too much", serverReadTooMuch.get());
      assertTrue("Server read OK", serverReadOnceOK.get());
      assertTrue("Server read done", serverReadDoneOK.get());
      assertTrue("Server write OK", serverWriteOK.get());
    } finally {
      readChannelThread.shutdown();
      writeChannelThread.shutdown();
      clientReadChannelThread.shutdown();
      clientWriteChannelThread.shutdown();
      connectionChannelThread.shutdown();
    }
    threadFactory.await();
  }
Beispiel #11
0
 private void doConnectionTest(
     final Runnable body,
     final ChannelListener<? super ConnectedStreamChannel> clientHandler,
     final ChannelListener<? super ConnectedStreamChannel> serverHandler)
     throws Exception {
   Xnio xnio = Xnio.getInstance("nio", NioTcpTestCase.class.getClassLoader());
   final ConnectionChannelThread connectionChannelThread =
       xnio.createConnectionChannelThread(threadFactory);
   final ConnectionChannelThread serverChannelThread =
       xnio.createConnectionChannelThread(threadFactory);
   final ReadChannelThread readChannelThread = xnio.createReadChannelThread(threadFactory);
   final ReadChannelThread clientReadChannelThread = xnio.createReadChannelThread(threadFactory);
   final WriteChannelThread writeChannelThread = xnio.createWriteChannelThread(threadFactory);
   final WriteChannelThread clientWriteChannelThread =
       xnio.createWriteChannelThread(threadFactory);
   try {
     final AcceptingChannel<? extends ConnectedStreamChannel> server =
         xnio.createStreamServer(
             new InetSocketAddress(
                 Inet4Address.getByAddress(new byte[] {127, 0, 0, 1}), SERVER_PORT),
             serverChannelThread,
             ChannelListeners.<ConnectedStreamChannel>openListenerAdapter(
                 readChannelThread,
                 writeChannelThread,
                 new CatchingChannelListener<ConnectedStreamChannel>(
                     serverHandler, threadFactory)),
             OptionMap.create(Options.REUSE_ADDRESSES, Boolean.TRUE));
     server.resumeAccepts();
     try {
       final IoFuture<? extends ConnectedStreamChannel> ioFuture =
           xnio.connectStream(
               new InetSocketAddress(
                   Inet4Address.getByAddress(new byte[] {127, 0, 0, 1}), SERVER_PORT),
               connectionChannelThread,
               clientReadChannelThread,
               clientWriteChannelThread,
               new CatchingChannelListener<ConnectedStreamChannel>(clientHandler, threadFactory),
               null,
               OptionMap.EMPTY);
       final ConnectedStreamChannel channel = ioFuture.get();
       try {
         body.run();
         channel.close();
         server.close();
       } catch (Exception e) {
         log.errorf(e, "Error running body");
         throw e;
       } catch (Error e) {
         log.errorf(e, "Error running body");
         throw e;
       } finally {
         IoUtils.safeClose(channel);
       }
     } finally {
       IoUtils.safeClose(server);
     }
   } finally {
     connectionChannelThread.shutdown();
     serverChannelThread.shutdown();
     clientReadChannelThread.shutdown();
     clientWriteChannelThread.shutdown();
     readChannelThread.shutdown();
     writeChannelThread.shutdown();
   }
   connectionChannelThread.awaitTermination();
   serverChannelThread.awaitTermination();
   readChannelThread.awaitTermination();
   writeChannelThread.awaitTermination();
   clientReadChannelThread.awaitTermination();
   clientWriteChannelThread.awaitTermination();
 }