io.vertx.proton.ProtonClientOptions Java Examples

The following examples show how to use io.vertx.proton.ProtonClientOptions. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: AmqpAdapterTestBase.java    From hono with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Connects to the AMQP protocol adapter using a username and password.
 *
 *
 * @param username The username to use for authentication.
 * @param password The password to use for authentication.
 * @return A succeeded future containing the established connection.
 */
protected Future<ProtonConnection> connectToAdapter(final String username, final String password) {

    final Promise<ProtonConnection> result = Promise.promise();
    final ProtonClient client = ProtonClient.create(VERTX);

    final ProtonClientOptions options = new ProtonClientOptions(defaultOptions);
    options.addEnabledSaslMechanism(ProtonSaslPlainImpl.MECH_NAME);
    client.connect(
            options,
            IntegrationTestSupport.AMQP_HOST,
            IntegrationTestSupport.AMQPS_PORT,
            username,
            password,
            result);
    return result.future().compose(this::handleConnectAttempt);
}
 
Example #2
Source File: ConnectionFactoryImpl.java    From hono with Eclipse Public License 2.0 6 votes vote down vote up
private void handleTimedOutConnectionAttemptResult(final AsyncResult<ProtonConnection> conAttempt, final ProtonClientOptions clientOptions) {
    if (conAttempt.succeeded()) {
        logger.debug("ignoring successful connection attempt to AMQP 1.0 container [{}://{}:{}, role: {}]: attempt already timed out",
                clientOptions.isSsl() ? "amqps" : "amqp",
                config.getHost(),
                config.getPort(),
                config.getServerRole());
        final ProtonConnection downstreamConnection = conAttempt.result();
        downstreamConnection.disconnect();
    } else {
        logger.debug("ignoring failed connection attempt to AMQP 1.0 container [{}://{}:{}, role: {}]: attempt already timed out",
                clientOptions.isSsl() ? "amqps" : "amqp",
                config.getHost(),
                config.getPort(),
                config.getServerRole(),
                conAttempt.cause());
    }
}
 
Example #3
Source File: ConnectionFactoryImplTest.java    From hono with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Verifies that the factory does not enable SASL_PLAIN if the username and password are empty
 * strings.
 */
@SuppressWarnings("unchecked")
@Test
public void testConnectDoesNotUseSaslPlainForEmptyUsernameAndPassword() {

    // GIVEN a factory configured to connect to a server
    final ProtonClientOptions options = new ProtonClientOptions();
    final ProtonClient client = mock(ProtonClient.class);
    final ConnectionFactoryImpl factory = new ConnectionFactoryImpl(vertx, props);
    factory.setProtonClient(client);

    // WHEN connecting to the server using empty strings for username and password
    factory.connect(options, "", "", null, null, c -> {});

    // THEN the factory does not enable the SASL_PLAIN mechanism when establishing
    // the connection
    final ArgumentCaptor<ProtonClientOptions> optionsCaptor = ArgumentCaptor.forClass(ProtonClientOptions.class);
    verify(client).connect(optionsCaptor.capture(), anyString(), anyInt(), eq(""), eq(""), any(Handler.class));
    assertFalse(optionsCaptor.getValue().getEnabledSaslMechanisms().contains("PLAIN"));
}
 
Example #4
Source File: ConnectionFactoryImplTest.java    From hono with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Verifies that the factory enables SASL_PLAIN if the username and password are non-empty
 * strings.
 */
@SuppressWarnings("unchecked")
@Test
public void testConnectAddsSaslPlainForNonEmptyUsernameAndPassword() {

    // GIVEN a factory configured to connect to a server
    final ProtonClientOptions options = new ProtonClientOptions();
    final ProtonClient client = mock(ProtonClient.class);
    final ConnectionFactoryImpl factory = new ConnectionFactoryImpl(vertx, props);
    factory.setProtonClient(client);

    // WHEN connecting to the server using non-empty strings for username and password
    factory.connect(options, "user", "pw", null, null, c -> {});

    // THEN the factory uses SASL_PLAIN when establishing the connection
    final ArgumentCaptor<ProtonClientOptions> optionsCaptor = ArgumentCaptor.forClass(ProtonClientOptions.class);
    verify(client).connect(optionsCaptor.capture(), anyString(), anyInt(), eq("user"), eq("pw"), any(Handler.class));
    assertTrue(optionsCaptor.getValue().getEnabledSaslMechanisms().contains("PLAIN"));
}
 
Example #5
Source File: ConnectionFactoryImplTest.java    From hono with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Verifies that the factory uses TLS when connecting to the peer if no trust store
 * is configured but TLS has been enabled explicitly.
 */
@SuppressWarnings("unchecked")
@Test
public void testConnectEnablesSslIfExplicitlyConfigured() {

    // GIVEN a factory configured to connect to a server using TLS
    final ClientConfigProperties config = new ClientConfigProperties();
    config.setHost("remote.host");
    config.setTlsEnabled(true);
    final ProtonClient client = mock(ProtonClient.class);
    final ConnectionFactoryImpl factory = new ConnectionFactoryImpl(vertx, config);
    factory.setProtonClient(client);

    // WHEN connecting to the server
    factory.connect(null, null, null, c -> {});

    // THEN the factory uses TLS when establishing the connection
    final ArgumentCaptor<ProtonClientOptions> optionsCaptor = ArgumentCaptor.forClass(ProtonClientOptions.class);
    verify(client).connect(optionsCaptor.capture(), eq("remote.host"), anyInt(), any(), any(), any(Handler.class));
    assertTrue(optionsCaptor.getValue().isSsl());
}
 
Example #6
Source File: ConnectionFactoryImplTest.java    From hono with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Verifies that the factory uses TLS when connecting to the peer if a trust store
 * is configured but TLS has not been enabled explicitly.
 */
@SuppressWarnings("unchecked")
@Test
public void testConnectEnablesSslIfTrustStoreIsConfigured() {

    // GIVEN a factory configured to use a specific trust store
    final ClientConfigProperties config = new ClientConfigProperties();
    config.setHost("remote.host");
    config.setTrustStorePath(PREFIX_KEY_PATH + "trusted-certs.pem");
    final ProtonClient client = mock(ProtonClient.class);
    final ConnectionFactoryImpl factory = new ConnectionFactoryImpl(vertx, config);
    factory.setProtonClient(client);

    // WHEN connecting to the server
    factory.connect(null, null, null, c -> {});

    // THEN the factory uses TLS when establishing the connection
    final ArgumentCaptor<ProtonClientOptions> optionsCaptor = ArgumentCaptor.forClass(ProtonClientOptions.class);
    verify(client).connect(optionsCaptor.capture(), eq("remote.host"), anyInt(), any(), any(), any(Handler.class));
    assertTrue(optionsCaptor.getValue().isSsl());
}
 
Example #7
Source File: AmqpCliClient.java    From hono with Eclipse Public License 2.0 6 votes vote down vote up
private void addTlsTrustOptions(final ProtonClientOptions clientOptions, final ClientConfigProperties config) {

        if (config.isTlsEnabled()) {
            clientOptions.setSsl(true);
        }

        final TrustOptions trustOptions = config.getTrustOptions();
        if (trustOptions != null) {
            clientOptions.setSsl(true).setTrustOptions(trustOptions);
        }

        if (clientOptions.isSsl()) {
            if (config.isHostnameVerificationRequired()) {
                clientOptions.setHostnameVerificationAlgorithm("HTTPS");
            } else {
                clientOptions.setHostnameVerificationAlgorithm("");
            }
        }
    }
 
Example #8
Source File: AmqpBridge.java    From strimzi-kafka-bridge with Apache License 2.0 6 votes vote down vote up
/**
 * Create an options instance for the ProtonClient
 *
 * @return ProtonClient options instance
 */
private ProtonClientOptions createClientOptions() {

    ProtonClientOptions options = new ProtonClientOptions();
    options.setConnectTimeout(1000);
    options.setReconnectAttempts(-1).setReconnectInterval(1000); // reconnect forever, every 1000 millisecs

    if (this.bridgeConfig.getAmqpConfig().getCertDir() != null && this.bridgeConfig.getAmqpConfig().getCertDir().length() > 0) {
        String certDir = this.bridgeConfig.getAmqpConfig().getCertDir();
        log.info("Enabling SSL configuration for AMQP with TLS certificates from {}", certDir);
        options.setSsl(true)
                .addEnabledSaslMechanism("EXTERNAL")
                .setHostnameVerificationAlgorithm("")
                .setPemTrustOptions(new PemTrustOptions()
                        .addCertPath(new File(certDir, "ca.crt").getAbsolutePath()))
                .setPemKeyCertOptions(new PemKeyCertOptions()
                        .addCertPath(new File(certDir, "tls.crt").getAbsolutePath())
                        .addKeyPath(new File(certDir, "tls.key").getAbsolutePath()));
    }

    return options;
}
 
Example #9
Source File: AmqpAdapterTestBase.java    From hono with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Connects to the AMQP protocol adapter using a client certificate.
 *
 * @param clientCertificate The certificate to use for authentication.
 * @return A succeeded future containing the established connection.
 */
protected Future<ProtonConnection> connectToAdapter(final SelfSignedCertificate clientCertificate) {

    final Promise<ProtonConnection> result = Promise.promise();
    final ProtonClient client = ProtonClient.create(VERTX);

    final ProtonClientOptions secureOptions = new ProtonClientOptions(defaultOptions);
    secureOptions.setKeyCertOptions(clientCertificate.keyCertOptions());
    secureOptions.addEnabledSaslMechanism(ProtonSaslExternalImpl.MECH_NAME);
    client.connect(
            secureOptions,
            IntegrationTestSupport.AMQP_HOST,
            IntegrationTestSupport.AMQPS_PORT,
            result);
    return result.future().compose(this::handleConnectAttempt);
}
 
Example #10
Source File: DisconnectHandlerProvidingConnectionFactory.java    From hono with Eclipse Public License 2.0 6 votes vote down vote up
@Override
public void connect(
        final ProtonClientOptions options,
        final String username,
        final String password,
        final String containerId,
        final Handler<AsyncResult<ProtonConnection>> closeHandler,
        final Handler<ProtonConnection> disconnectHandler,
        final Handler<AsyncResult<ProtonConnection>> connectionResultHandler) {

    this.closeHandler = closeHandler;
    this.disconnectHandler = disconnectHandler;
    if (expectedFailingConnectionAttempts.getCount() > 0) {
        expectedFailingConnectionAttempts.countDown();
        connectionResultHandler.handle(Future.failedFuture(causeForFailure));
    } else {
        expectedSucceedingConnectionAttempts.countDown();
        connectionResultHandler.handle(Future.succeededFuture(connectionToCreate));
    }
}
 
Example #11
Source File: AmqpClientFactory.java    From enmasse with Apache License 2.0 6 votes vote down vote up
public AmqpClient createClient(TerminusFactory terminusFactory, ProtonQoS qos, AddressSpace addressSpace) throws Exception {
    assertNotNull(addressSpace, "Address space is null");
    Endpoint messagingEndpoint = AddressSpaceUtils.getEndpointByServiceName(addressSpace, "messaging");
    if (messagingEndpoint == null) {
        String externalEndpointName = AddressSpaceUtils.getExternalEndpointName(addressSpace, "messaging");
        messagingEndpoint = Kubernetes.getInstance().getExternalEndpoint(externalEndpointName + "-" + AddressSpaceUtils.getAddressSpaceInfraUuid(addressSpace));
    }
    Endpoint clientEndpoint;
    ProtonClientOptions clientOptions = new ProtonClientOptions();
    clientOptions.setSsl(true);
    clientOptions.setTrustAll(true);
    clientOptions.setHostnameVerificationAlgorithm("");

    if (TestUtils.resolvable(messagingEndpoint)) {
        clientEndpoint = messagingEndpoint;
    } else {
        clientEndpoint = new Endpoint("localhost", 443);
        clientOptions.setSniServerName(messagingEndpoint.getHost());
    }
    log.info("External endpoint: " + clientEndpoint + ", internal: " + messagingEndpoint);
    probeEndpoint(messagingEndpoint);

    return createClient(terminusFactory, clientEndpoint, clientOptions, qos);
}
 
Example #12
Source File: MessagingEndpointTest.java    From enmasse with Apache License 2.0 6 votes vote down vote up
void doTestSendReceiveOutsideCluster(String host, int port, String address, boolean tls, boolean verifyHost, String caCert) throws Exception {
    ProtonClientOptions protonClientOptions = new ProtonClientOptions();
    if (tls) {
        protonClientOptions.setSsl(true);
        if (!verifyHost) {
            protonClientOptions.setHostnameVerificationAlgorithm("");
        }
        if (caCert != null) {
            protonClientOptions.setTrustOptions(new PemTrustOptions()
                    .addCertValue(Buffer.buffer(caCert)));
        }
    }
    AmqpClient client = resourceManager.getAmqpClientFactory().createClient(new AmqpConnectOptions()
            .setSaslMechanism("ANONYMOUS")
            .setQos(ProtonQoS.AT_LEAST_ONCE)
            .setEndpoint(new Endpoint(host, port))
            .setProtonClientOptions(protonClientOptions)
            .setTerminusFactory(new QueueTerminusFactory()));

    assertEquals(1, client.sendMessages(address, Collections.singletonList("hello")).get(1, TimeUnit.MINUTES));
    var result = client.recvMessages(address, 1).get();
    assertEquals(1, result.size());
    assertEquals("hello", ((AmqpValue) result.get(0).getBody()).getValue());
}
 
Example #13
Source File: ClientFactory.java    From enmasse with Apache License 2.0 6 votes vote down vote up
public ClientFactory(Vertx vertx) {

        this.vertx = vertx;


        String path = System.getenv("HOME") + System.getenv("AMQ_NAME") + "/etc";

        JksOptions clientJksOptions = new JksOptions();
        clientJksOptions
            .setPath(path + "/enmasse-keystore.jks")
            .setPassword("enmasse");

        PfxOptions clientPfxOptions = new PfxOptions()
            .setPath(path + "/enmasse-truststore.jks")
            .setPassword("enmasse");

        this.protonClientOptions =  new ProtonClientOptions()
            .setSsl(true)
            .setHostnameVerificationAlgorithm("")
            .setKeyStoreOptions(clientJksOptions)
            .setPfxTrustOptions(clientPfxOptions);

    }
 
Example #14
Source File: HonoConnectionImplTest.java    From hono with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Verifies that if a client disconnects from the server, then an attempt to connect again will be successful.
 *
 * @param ctx The test execution context.
 */
@Test
public void testConnectSucceedsAfterDisconnect(final VertxTestContext ctx) {

    honoConnection.connect()
        .compose(ok -> {
            // GIVEN a client that is connected to a server
            final Promise<Void> disconnected = Promise.promise();
            // WHEN the client disconnects
            honoConnection.disconnect(disconnected);
            @SuppressWarnings("unchecked")
            final ArgumentCaptor<Handler<AsyncResult<ProtonConnection>>> closeHandler = ArgumentCaptor.forClass(Handler.class);
            ctx.verify(() -> verify(con).closeHandler(closeHandler.capture()));
            closeHandler.getValue().handle(Future.succeededFuture(con));
            return disconnected.future();
        })
        .compose(d -> {
            // AND tries to reconnect again
            return honoConnection.connect(new ProtonClientOptions());
        })
        // THEN the connection succeeds
        .onComplete(ctx.completing());
}
 
Example #15
Source File: ClientUtils.java    From enmasse with Apache License 2.0 5 votes vote down vote up
private boolean canConnectWithAmqpAddress(ResourceManager resourceManager, AddressSpace addressSpace, UserCredentials credentials, AddressType addressType, String address, boolean defaultValue) throws Exception {
    Set<AddressType> brokeredAddressTypes = new HashSet<>(Arrays.asList(AddressType.QUEUE, AddressType.TOPIC));
    if (AddressSpaceUtils.isBrokered(addressSpace) && !brokeredAddressTypes.contains(addressType)) {
        return defaultValue;
    }
    try (AmqpClient client = resourceManager.getAmqpClientFactory().createAddressClient(addressSpace, addressType)) {
        client.getConnectOptions().setCredentials(credentials);
        ProtonClientOptions protonClientOptions = client.getConnectOptions().getProtonClientOptions();
        protonClientOptions.setLogActivity(true);
        client.getConnectOptions().setProtonClientOptions(protonClientOptions);

        try {
            Future<List<Message>> received = client.recvMessages(address, 1);
            Future<Integer> sent = client.sendMessages(address, Collections.singletonList("msg1"));

            int numReceived = received.get(1, TimeUnit.MINUTES).size();
            int numSent = sent.get(1, TimeUnit.MINUTES);
            return (numSent == numReceived);
        } catch (ExecutionException | SecurityException | UnauthorizedAccessException ex) {
            Throwable cause = ex;
            if (ex instanceof ExecutionException) {
                cause = ex.getCause();
            }

            if (cause instanceof AuthenticationException || cause instanceof SaslSystemException || cause instanceof SecurityException || cause instanceof UnauthorizedAccessException || cause instanceof MechanismMismatchException) {
                LOGGER.info("canConnectWithAmqpAddress {} ({}): {}", address, addressType, ex.getMessage());
                return false;
            } else {
                LOGGER.warn("canConnectWithAmqpAddress {} ({}) exception", address, addressType, ex);
                throw ex;
            }
        }
    }
}
 
Example #16
Source File: HonoConnectionImpl.java    From hono with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public final Future<HonoConnection> connect(final ProtonClientOptions options) {
    final Promise<HonoConnection> result = Promise.promise();
    if (shuttingDown.get()) {
        result.fail(new ClientErrorException(HttpURLConnection.HTTP_CONFLICT, "client is already shut down"));
    } else {
        connect(options, result, null);
    }
    return result.future();
}
 
Example #17
Source File: AmqpClientFactory.java    From enmasse with Apache License 2.0 5 votes vote down vote up
protected AmqpClient createClient(TerminusFactory terminusFactory, Endpoint endpoint, ProtonClientOptions protonOptions, ProtonQoS qos) {
    AmqpConnectOptions connectOptions = new AmqpConnectOptions()
            .setTerminusFactory(terminusFactory)
            .setEndpoint(endpoint)
            .setProtonClientOptions(protonOptions)
            .setQos(qos)
            .setUsername(defaultUsername)
            .setPassword(defaultPassword);
    return createClient(connectOptions);
}
 
Example #18
Source File: AmqpBridge.java    From strimzi-kafka-bridge with Apache License 2.0 5 votes vote down vote up
/**
 * Connect to an AMQP server/router
 *
 * @param startPromise
 */
private void connectAmqpClient(Promise<Void> startPromise) {

    this.client = ProtonClient.create(this.vertx);

    String host = this.bridgeConfig.getAmqpConfig().getHost();
    int port = this.bridgeConfig.getAmqpConfig().getPort();

    ProtonClientOptions options = this.createClientOptions();

    this.client.connect(options, host, port, ar -> {

        if (ar.succeeded()) {

            ProtonConnection connection = ar.result();
            connection.setContainer(CONTAINER_ID);

            this.processConnection(connection);

            log.info("AMQP-Kafka Bridge started and connected in client mode to {}:{}", host, port);
            log.info("AMQP-Kafka Bridge bootstrap servers {}",
                    this.bridgeConfig.getKafkaConfig().getConfig()
                            .get(CommonClientConfigs.BOOTSTRAP_SERVERS_CONFIG)
            );

            this.isReady = true;

            startPromise.complete();

        } else {
            log.error("Error connecting AMQP-Kafka Bridge as client", ar.cause());
            startPromise.fail(ar.cause());
        }
    });
}
 
Example #19
Source File: RouterManagement.java    From enmasse with Apache License 2.0 5 votes vote down vote up
private RouterManagement(Vertx vertx, String containerId, ProtonClientOptions clientOptions, Duration connectTimeout, Duration queryTimeout) {
    this.vertx = vertx;
    this.containerId = containerId;
    this.clientOptions = clientOptions;
    this.connectTimeout = connectTimeout;
    this.queryTimeout = queryTimeout;
}
 
Example #20
Source File: RouterManagement.java    From enmasse with Apache License 2.0 5 votes vote down vote up
public static RouterManagement withCertsInDir(Vertx vertx, String containerId, Duration connectTimeout, Duration queryTimeout, String certDir) {
    ProtonClientOptions clientOptions = new ProtonClientOptions()
            .setSsl(true)
            .addEnabledSaslMechanism("EXTERNAL")
            .setHostnameVerificationAlgorithm("")
            .setPemTrustOptions(new PemTrustOptions()
                    .addCertPath(new File(certDir, "ca.crt").getAbsolutePath()))
            .setPemKeyCertOptions(new PemKeyCertOptions()
                    .setCertPath(new File(certDir, "tls.crt").getAbsolutePath())
                    .setKeyPath(new File(certDir, "tls.key").getAbsolutePath()));
    return new RouterManagement(vertx, containerId, clientOptions, connectTimeout, queryTimeout);
}
 
Example #21
Source File: RouterManagement.java    From enmasse with Apache License 2.0 5 votes vote down vote up
public static RouterManagement withCerts(Vertx vertx, String containerId, Duration connectTimeout, Duration queryTimeout, byte[] caCert, byte[] clientCert, byte[] clientKey) {
    ProtonClientOptions clientOptions = new ProtonClientOptions()
            .setSsl(true)
            .addEnabledSaslMechanism("EXTERNAL")
            .setHostnameVerificationAlgorithm("")
            .setPemTrustOptions(new PemTrustOptions()
                    .addCertValue(Buffer.buffer(caCert)))
            .setPemKeyCertOptions(new PemKeyCertOptions()
                    .addCertValue(Buffer.buffer(clientCert))
                    .addKeyValue(Buffer.buffer(clientKey)));
    return new RouterManagement(vertx, containerId, clientOptions, connectTimeout, queryTimeout);
}
 
Example #22
Source File: ConnectionFactoryImpl.java    From hono with Eclipse Public License 2.0 5 votes vote down vote up
private ProtonClientOptions createClientOptions() {
    final ProtonClientOptions options = new ProtonClientOptions();
    options.setConnectTimeout(config.getConnectTimeout());
    options.setHeartbeat(config.getHeartbeatInterval());
    options.setReconnectAttempts(0);
    return options;
}
 
Example #23
Source File: ConnectionFactoryImpl.java    From hono with Eclipse Public License 2.0 5 votes vote down vote up
private void addTlsKeyCertOptions(final ProtonClientOptions clientOptions) {

        if (clientOptions.getKeyCertOptions() == null) {
            final KeyCertOptions keyCertOptions = config.getKeyCertOptions();
            if (keyCertOptions != null) {
                clientOptions.setSsl(true).setKeyCertOptions(keyCertOptions);
                clientOptions.addEnabledSaslMechanism(ProtonSaslExternalImpl.MECH_NAME);
            }
        }
    }
 
Example #24
Source File: ConnectionFactoryImpl.java    From hono with Eclipse Public License 2.0 5 votes vote down vote up
private void addOptions(final ProtonClientOptions clientOptions, final String username, final String password) {

        addTlsTrustOptions(clientOptions);
        if (!Strings.isNullOrEmpty(username) && !Strings.isNullOrEmpty(password)) {
            clientOptions.addEnabledSaslMechanism(ProtonSaslPlainImpl.MECH_NAME);
        } else {
            addTlsKeyCertOptions(clientOptions);
        }
    }
 
Example #25
Source File: ProtonClientImpl.java    From vertx-proton with Apache License 2.0 5 votes vote down vote up
private void connectNetClient(NetClient netClient, String host, int port, String username, String password,
                              ConnectCompletionHandler connectHandler, ProtonClientOptions options) {

  String serverName = options.getSniServerName() != null ? options.getSniServerName() :
    (options.getVirtualHost() != null ? options.getVirtualHost() : null);

  netClient.connect(port, host, serverName, res -> {
    if (res.succeeded()) {
      String virtualHost = options.getVirtualHost() != null ? options.getVirtualHost() : host;
      ProtonConnectionImpl conn = new ProtonConnectionImpl(vertx, virtualHost, (ContextInternal) Vertx.currentContext());
      conn.disconnectHandler(h -> {
        LOG.trace("Connection disconnected");
        if(!connectHandler.isComplete()) {
          connectHandler.handle(Future.failedFuture(new VertxException("Disconnected")));
        }
      });

      ProtonSaslClientAuthenticatorImpl authenticator = new ProtonSaslClientAuthenticatorImpl(username, password,
              options.getEnabledSaslMechanisms(), connectHandler);

      ProtonTransportOptions transportOptions = new ProtonTransportOptions();
      transportOptions.setHeartbeat(options.getHeartbeat());
      transportOptions.setMaxFrameSize(options.getMaxFrameSize());

      conn.bindClient(netClient, res.result(), authenticator, transportOptions);

      // Need to flush here to get the SASL process going, or it will wait until calls on the connection are processed
      // later (e.g open()).
      conn.flush();
    } else {
      connectHandler.handle(Future.failedFuture(res.cause()));
    }
  });
}
 
Example #26
Source File: AuthenticationServerClient.java    From hono with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Verifies username/password credentials with a remote authentication server using SASL PLAIN.
 *
 * @param authzid The identity to act as.
 * @param authcid The username.
 * @param password The password.
 * @param authenticationResultHandler The handler to invoke with the authentication result. On successful authentication,
 *                                    the result contains a JWT with the authenticated user's claims.
 */
public void verifyPlain(final String authzid, final String authcid, final String password,
        final Handler<AsyncResult<HonoUser>> authenticationResultHandler) {

    final ProtonClientOptions options = new ProtonClientOptions();
    options.setReconnectAttempts(3).setReconnectInterval(50);
    options.addEnabledSaslMechanism(AuthenticationConstants.MECHANISM_PLAIN);

    final Promise<ProtonConnection> connectAttempt = Promise.promise();
    factory.connect(options, authcid, password, null, null, connectAttempt);

    connectAttempt.future()
    .compose(openCon -> getToken(openCon))
    .onComplete(s -> {
        if (s.succeeded()) {
            authenticationResultHandler.handle(Future.succeededFuture(s.result()));
        } else {
            authenticationResultHandler
            .handle(Future.failedFuture(mapConnectionFailureToServiceInvocationException(s.cause())));
        }
        Optional.ofNullable(connectAttempt.future().result())
        .ifPresent(con -> {
            LOG.debug("closing connection to Authentication service");
            con.close();
        });
    });
}
 
Example #27
Source File: DisconnectHandlerProvidingConnectionFactory.java    From hono with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public void connect(
        final ProtonClientOptions options,
        final Handler<AsyncResult<ProtonConnection>> closeHandler,
        final Handler<ProtonConnection> disconnectHandler,
        final Handler<AsyncResult<ProtonConnection>> connectionResultHandler) {
    connect(options, null, null, closeHandler, disconnectHandler, connectionResultHandler);
}
 
Example #28
Source File: DisconnectHandlerProvidingConnectionFactory.java    From hono with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public void connect(
        final ProtonClientOptions options,
        final String username,
        final String password,
        final Handler<AsyncResult<ProtonConnection>> closeHandler,
        final Handler<ProtonConnection> disconnectHandler,
        final Handler<AsyncResult<ProtonConnection>> connectionResultHandler) {
    connect(options, null, null, null, closeHandler, disconnectHandler, connectionResultHandler);
}
 
Example #29
Source File: AmqpAdapterTestBase.java    From hono with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Create a HTTP client for accessing the device registry (for registering devices and credentials) and
 * an AMQP 1.0 client for consuming messages from the messaging network.
 *
 * @param ctx The Vert.x test context.
 */
@BeforeAll
public static void setup(final VertxTestContext ctx) {

    VERTX = Vertx.vertx();

    defaultOptions = new ProtonClientOptions()
            .setTrustOptions(new PemTrustOptions().addCertPath(IntegrationTestSupport.TRUST_STORE_PATH))
            .setHostnameVerificationAlgorithm("")
            .setSsl(true);

    helper = new IntegrationTestSupport(VERTX);
    helper.init().onComplete(ctx.completing());

}
 
Example #30
Source File: HonoConnectionImplTest.java    From hono with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Verifies that the client tries to re-connect to a server instance if the
 * connection is closed by the peer.
 *
 * @param ctx The test context.
 *
 */
@Test
public void testOnRemoteCloseTriggersReconnection(final VertxTestContext ctx) {

    // GIVEN a client that is connected to a server
    final Promise<HonoConnection> connected = Promise.promise();
    @SuppressWarnings("unchecked")
    final DisconnectListener<HonoConnection> disconnectListener = mock(DisconnectListener.class);
    honoConnection.addDisconnectListener(disconnectListener);
    honoConnection.connect(new ProtonClientOptions().setReconnectAttempts(1))
        .onComplete(connected);
    connectionFactory.setExpectedSucceedingConnectionAttempts(1);

    connected.future().onComplete(ctx.succeeding(c -> {
        // WHEN the peer closes the connection
        connectionFactory.getCloseHandler().handle(Future.failedFuture("shutting down for maintenance"));

        ctx.verify(() -> {
            // THEN the client invokes the registered disconnect handler
            verify(disconnectListener).onDisconnect(honoConnection);
            // and the original connection has been closed locally
            verify(con).close();
            verify(con).disconnectHandler(null);
            // and the connection is re-established
            assertThat(connectionFactory.await()).isTrue();
        });
        ctx.completeNow();
    }));
}