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;
  }
 public synchronized void close() {
   try {
     if (connection != null) {
       connection.close();
     }
   } catch (IOException e) {
     AppClientLogger.ROOT_LOGGER.exceptionClosingConnection(e);
   }
   try {
     if (endpoint != null) {
       endpoint.close();
     }
   } catch (IOException e) {
     AppClientLogger.ROOT_LOGGER.exceptionClosingConnection(e);
   }
 }
 private EJBClientContext getContext(final Connection connection) {
   synchronized (contextByConnection) {
     EJBClientContext ret = contextByConnection.get(connection);
     if (ret == null) {
       ret = EJBClientContext.create();
       ret.registerConnection(connection);
       contextByConnection.put(connection, ret);
       connection.addCloseHandler(
           new CloseHandler<Connection>() {
             @Override
             public void handleClose(final Connection connection, final IOException e) {
               synchronized (contextByConnection) {
                 contextByConnection.remove(connection);
               }
             }
           });
     }
     return ret;
   }
 }
  @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 NamingProvider createProvider(
      final URI providerUri, final FastHashtable<String, Object> env) throws NamingException {
    // Legacy naming constants
    final Endpoint endpoint = getEndpoint(env);
    final String callbackClass = getStringProperty(CALLBACK_HANDLER_KEY, env);
    final String userName = getStringProperty(Context.SECURITY_PRINCIPAL, env);
    final String password = getStringProperty(Context.SECURITY_CREDENTIALS, env);
    final String passwordBase64 = getStringProperty(PASSWORD_BASE64_KEY, env);
    final String realm = getStringProperty(REALM_KEY, env);

    boolean useSeparateConnection =
        Boolean.parseBoolean(String.valueOf(env.get(USE_SEPARATE_CONNECTION)));

    AuthenticationContext captured = AuthenticationContext.captureCurrent();
    AuthenticationConfiguration mergedConfiguration =
        AUTH_CONFIGURATION_CLIENT.getAuthenticationConfiguration(providerUri, captured);
    if (callbackClass != null && (userName != null || password != null)) {
      throw Messages.log.callbackHandlerAndUsernameAndPasswordSpecified();
    }
    if (callbackClass != null) {
      final ClassLoader classLoader = secureGetContextClassLoader();
      try {
        final Class<?> clazz = Class.forName(callbackClass, true, classLoader);
        final CallbackHandler callbackHandler = (CallbackHandler) clazz.newInstance();
        if (callbackHandler != null) {
          mergedConfiguration = mergedConfiguration.useCallbackHandler(callbackHandler);
        }
      } catch (ClassNotFoundException e) {
        throw Messages.log.failedToLoadCallbackHandlerClass(e, callbackClass);
      } catch (Exception e) {
        throw Messages.log.failedToInstantiateCallbackHandlerInstance(e, callbackClass);
      }
    } else if (userName != null) {
      if (password != null && passwordBase64 != null) {
        throw Messages.log.plainTextAndBase64PasswordSpecified();
      }
      final String decodedPassword =
          passwordBase64 != null
              ? CodePointIterator.ofString(passwordBase64)
                  .base64Decode()
                  .asUtf8String()
                  .drainToString()
              : password;
      mergedConfiguration =
          mergedConfiguration.useName(userName).usePassword(decodedPassword).useRealm(realm);
    }
    final AuthenticationContext context =
        AuthenticationContext.empty().with(MatchRule.ALL, mergedConfiguration);

    if (useSeparateConnection) {
      // create a brand new connection - if there is authentication info in the env, use it
      final Connection connection;
      try {
        connection = endpoint.connect(providerUri, OptionMap.EMPTY, context).get();
      } catch (IOException e) {
        throw Messages.log.connectFailed(e);
      }
      final RemoteNamingProvider provider = new RemoteNamingProvider(connection, context, env);
      connection.getAttachments().attach(PROVIDER_KEY, provider);
      return provider;
    } else if (env.containsKey(CONNECTION)) {
      final Connection connection = (Connection) env.get(CONNECTION);
      final RemoteNamingProvider provider = new RemoteNamingProvider(connection, context, env);
      connection.getAttachments().attach(PROVIDER_KEY, provider);
      return provider;
    } else {
      final Attachments attachments = endpoint.getAttachments();
      ProviderMap map = attachments.getAttachment(PROVIDER_MAP_KEY);
      if (map == null) {
        ProviderMap appearing =
            attachments.attachIfAbsent(PROVIDER_MAP_KEY, map = new ProviderMap());
        if (appearing != null) {
          map = appearing;
        }
      }
      final URIKey key =
          new URIKey(
              providerUri.getScheme(),
              providerUri.getUserInfo(),
              providerUri.getHost(),
              providerUri.getPort());
      RemoteNamingProvider provider = map.get(key);
      if (provider == null) {
        RemoteNamingProvider appearing =
            map.putIfAbsent(
                key, provider = new RemoteNamingProvider(endpoint, providerUri, context, env));
        if (appearing != null) {
          provider = appearing;
        }
      }
      return provider;
    }
  }
 /**
  * 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());
 }