Search in sources :

Example 11 with ProtonClientOptions

use of io.vertx.proton.ProtonClientOptions in project hono by eclipse.

the class ConnectionFactoryImplTest method testConnectAddsSaslPlainForNonEmptyUsernameAndPassword.

/**
 * Verifies that the factory enables SASL_PLAIN if the username and password are non-empty
 * strings.
 *
 * @param ctx The vert.x test context.
 */
@SuppressWarnings("unchecked")
@Test
public void testConnectAddsSaslPlainForNonEmptyUsernameAndPassword(final TestContext ctx) {
    // 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
    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"));
}
Also used : Handler(io.vertx.core.Handler) ProtonClientOptions(io.vertx.proton.ProtonClientOptions) ProtonClient(io.vertx.proton.ProtonClient) Test(org.junit.Test)

Example 12 with ProtonClientOptions

use of io.vertx.proton.ProtonClientOptions in project hono by eclipse.

the class HonoClientImpl method connect.

private void connect(final ProtonClientOptions options, final Handler<AsyncResult<HonoClient>> connectionHandler, final Handler<ProtonConnection> disconnectHandler) {
    context.runOnContext(connect -> {
        if (isConnectedInternal()) {
            LOG.debug("already connected to server [{}:{}]", connectionFactory.getHost(), connectionFactory.getPort());
            connectionHandler.handle(Future.succeededFuture(this));
        } else if (connecting.compareAndSet(false, true)) {
            if (options == null) {
                // by default, try to re-connect forever
                clientOptions = new ProtonClientOptions().setConnectTimeout(200).setReconnectAttempts(-1).setReconnectInterval(Constants.DEFAULT_RECONNECT_INTERVAL_MILLIS);
            } else {
                clientOptions = options;
            }
            connectionFactory.connect(clientOptions, remoteClose -> onRemoteClose(remoteClose, disconnectHandler), failedConnection -> onRemoteDisconnect(failedConnection, disconnectHandler), conAttempt -> {
                connecting.compareAndSet(true, false);
                if (conAttempt.failed()) {
                    if (conAttempt.cause() instanceof SecurityException) {
                        // SASL handshake has failed
                        connectionHandler.handle(Future.failedFuture(new ClientErrorException(HttpURLConnection.HTTP_UNAUTHORIZED, "failed to authenticate with server")));
                    } else {
                        reconnect(conAttempt.cause(), connectionHandler, disconnectHandler);
                    }
                } else {
                    // make sure we try to re-connect as often as we tried to connect initially
                    reconnectAttempts = new AtomicInteger(0);
                    final ProtonConnection newConnection = conAttempt.result();
                    if (shuttingDown.get()) {
                        // if client was shut down in the meantime, we need to immediately
                        // close again the newly created connection
                        newConnection.closeHandler(null);
                        newConnection.disconnectHandler(null);
                        newConnection.close();
                        connectionHandler.handle(Future.failedFuture(new ClientErrorException(HttpURLConnection.HTTP_CONFLICT, "client is already shut down")));
                    } else {
                        setConnection(newConnection);
                        connectionHandler.handle(Future.succeededFuture(this));
                    }
                }
            });
        } else {
            LOG.debug("already trying to connect to server ...");
            connectionHandler.handle(Future.failedFuture(new ClientErrorException(HttpURLConnection.HTTP_CONFLICT, "already connecting to server")));
        }
    });
}
Also used : HttpURLConnection(java.net.HttpURLConnection) RequestResponseClient(org.eclipse.hono.client.RequestResponseClient) ProtonConnection(io.vertx.proton.ProtonConnection) ProtonDelivery(io.vertx.proton.ProtonDelivery) LoggerFactory(org.slf4j.LoggerFactory) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) HashMap(java.util.HashMap) MessageConsumer(org.eclipse.hono.client.MessageConsumer) ClientErrorException(org.eclipse.hono.client.ClientErrorException) Supplier(java.util.function.Supplier) Constants(org.eclipse.hono.util.Constants) Context(io.vertx.core.Context) ArrayList(java.util.ArrayList) ConnectionFactory(org.eclipse.hono.connection.ConnectionFactory) CredentialsClient(org.eclipse.hono.client.CredentialsClient) ProtonClientOptions(io.vertx.proton.ProtonClientOptions) TenantClient(org.eclipse.hono.client.TenantClient) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) ConnectionFactoryBuilder(org.eclipse.hono.connection.ConnectionFactoryImpl.ConnectionFactoryBuilder) Map(java.util.Map) MessageSender(org.eclipse.hono.client.MessageSender) BiConsumer(java.util.function.BiConsumer) Message(org.apache.qpid.proton.message.Message) RegistrationClient(org.eclipse.hono.client.RegistrationClient) AsyncResult(io.vertx.core.AsyncResult) HonoClient(org.eclipse.hono.client.HonoClient) ClientConfigProperties(org.eclipse.hono.config.ClientConfigProperties) Logger(org.slf4j.Logger) Iterator(java.util.Iterator) Vertx(io.vertx.core.Vertx) ServerErrorException(org.eclipse.hono.client.ServerErrorException) CacheProvider(org.eclipse.hono.cache.CacheProvider) Future(io.vertx.core.Future) Objects(java.util.Objects) TimeUnit(java.util.concurrent.TimeUnit) Consumer(java.util.function.Consumer) CountDownLatch(java.util.concurrent.CountDownLatch) List(java.util.List) Handler(io.vertx.core.Handler) ProtonConnection(io.vertx.proton.ProtonConnection) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) ClientErrorException(org.eclipse.hono.client.ClientErrorException) ProtonClientOptions(io.vertx.proton.ProtonClientOptions)

Example 13 with ProtonClientOptions

use of io.vertx.proton.ProtonClientOptions in project hono by eclipse.

the class StandaloneTelemetryApiTest method prepareHonoServer.

/**
 * Sets up the fixture common to all test cases.
 *
 * @param ctx The vert.x test context.
 */
@BeforeClass
public static void prepareHonoServer(final TestContext ctx) {
    vertx = Vertx.vertx();
    downstreamAdapter = new MessageDiscardingDownstreamAdapter(vertx);
    final HonoMessagingConfigProperties configProperties = new HonoMessagingConfigProperties();
    configProperties.setInsecurePort(0);
    final TelemetryEndpoint telemetryEndpoint = new TelemetryEndpoint(vertx);
    telemetryEndpoint.setMetrics(mock(MessagingMetrics.class));
    telemetryEndpoint.setTelemetryAdapter(downstreamAdapter);
    telemetryEndpoint.setRegistrationAssertionValidator(assertionHelper);
    telemetryEndpoint.setConfiguration(configProperties);
    server = new HonoMessaging();
    server.setSaslAuthenticatorFactory(new HonoSaslAuthenticatorFactory(TestSupport.createAuthenticationService(createUser())));
    server.setConfig(configProperties);
    server.addEndpoint(telemetryEndpoint);
    final Future<String> serverTracker = Future.future();
    vertx.deployVerticle(server, serverTracker.completer());
    serverTracker.compose(s -> {
        final ClientConfigProperties clientProps = new ClientConfigProperties();
        clientProps.setName("test");
        clientProps.setHost(server.getInsecurePortBindAddress());
        clientProps.setPort(server.getInsecurePort());
        clientProps.setUsername(USER);
        clientProps.setPassword(PWD);
        client = new HonoClientImpl(vertx, clientProps);
        return client.connect(new ProtonClientOptions());
    }).setHandler(ctx.asyncAssertSuccess());
}
Also used : HonoSaslAuthenticatorFactory(org.eclipse.hono.service.auth.HonoSaslAuthenticatorFactory) TestContext(io.vertx.ext.unit.TestContext) AuthoritiesImpl(org.eclipse.hono.auth.AuthoritiesImpl) HonoUserAdapter(org.eclipse.hono.auth.HonoUserAdapter) BeforeClass(org.junit.BeforeClass) RunWith(org.junit.runner.RunWith) Vertx(io.vertx.core.Vertx) VertxUnitRunner(io.vertx.ext.unit.junit.VertxUnitRunner) Activity(org.eclipse.hono.auth.Activity) HonoUser(org.eclipse.hono.auth.HonoUser) HonoClientImpl(org.eclipse.hono.client.impl.HonoClientImpl) Future(io.vertx.core.Future) TelemetryEndpoint(org.eclipse.hono.telemetry.impl.TelemetryEndpoint) TelemetryConstants(org.eclipse.hono.util.TelemetryConstants) TestSupport(org.eclipse.hono.TestSupport) ProtonClientOptions(io.vertx.proton.ProtonClientOptions) MessageSender(org.eclipse.hono.client.MessageSender) Authorities(org.eclipse.hono.auth.Authorities) ClientConfigProperties(org.eclipse.hono.config.ClientConfigProperties) HonoSaslAuthenticatorFactory(org.eclipse.hono.service.auth.HonoSaslAuthenticatorFactory) Mockito.mock(org.mockito.Mockito.mock) HonoClientImpl(org.eclipse.hono.client.impl.HonoClientImpl) TelemetryEndpoint(org.eclipse.hono.telemetry.impl.TelemetryEndpoint) ClientConfigProperties(org.eclipse.hono.config.ClientConfigProperties) ProtonClientOptions(io.vertx.proton.ProtonClientOptions) BeforeClass(org.junit.BeforeClass)

Example 14 with ProtonClientOptions

use of io.vertx.proton.ProtonClientOptions in project hono by eclipse.

the class CredentialsAmqpIT method prepareDeviceRegistry.

/**
 * Starts the device registry and connects a client.
 *
 * @param ctx The vert.x test context.
 */
@BeforeClass
public static void prepareDeviceRegistry(final TestContext ctx) {
    client = DeviceRegistryAmqpTestSupport.prepareDeviceRegistryClient(vertx);
    client.connect(new ProtonClientOptions()).compose(c -> c.getOrCreateCredentialsClient(Constants.DEFAULT_TENANT)).setHandler(ctx.asyncAssertSuccess(r -> {
        credentialsClient = r;
    }));
}
Also used : CoreMatchers.is(org.hamcrest.CoreMatchers.is) HttpURLConnection(java.net.HttpURLConnection) TestContext(io.vertx.ext.unit.TestContext) BeforeClass(org.junit.BeforeClass) LocalDateTime(java.time.LocalDateTime) RunWith(org.junit.runner.RunWith) ServiceInvocationException(org.eclipse.hono.client.ServiceInvocationException) Constants(org.eclipse.hono.util.Constants) CredentialsClient(org.eclipse.hono.client.CredentialsClient) ProtonClientOptions(io.vertx.proton.ProtonClientOptions) Timeout(org.junit.rules.Timeout) JsonObject(io.vertx.core.json.JsonObject) HonoClient(org.eclipse.hono.client.HonoClient) AfterClass(org.junit.AfterClass) Vertx(io.vertx.core.Vertx) Test(org.junit.Test) VertxUnitRunner(io.vertx.ext.unit.junit.VertxUnitRunner) StandardCharsets(java.nio.charset.StandardCharsets) CredentialsConstants(org.eclipse.hono.util.CredentialsConstants) TimeUnit(java.util.concurrent.TimeUnit) JsonArray(io.vertx.core.json.JsonArray) Base64(java.util.Base64) Rule(org.junit.Rule) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) DateTimeFormatter(java.time.format.DateTimeFormatter) Assert(org.junit.Assert) CredentialsObject(org.eclipse.hono.util.CredentialsObject) ProtonClientOptions(io.vertx.proton.ProtonClientOptions) BeforeClass(org.junit.BeforeClass)

Example 15 with ProtonClientOptions

use of io.vertx.proton.ProtonClientOptions in project hono by eclipse.

the class ForwardingDownstreamAdapter method reconnect.

private void reconnect(final Handler<AsyncResult<ProtonConnection>> resultHandler) {
    if (!running) {
        logger.info("adapter is stopped, will not re-connect to downstream container");
    } else {
        final ProtonClientOptions clientOptions = createClientOptions();
        if (clientOptions.getReconnectAttempts() != 0) {
            vertx.setTimer(Constants.DEFAULT_RECONNECT_INTERVAL_MILLIS, reconnect -> {
                logger.info("attempting to re-connect to downstream container");
                connectToDownstream(clientOptions, resultHandler);
            });
        }
    }
}
Also used : ProtonClientOptions(io.vertx.proton.ProtonClientOptions)

Aggregations

ProtonClientOptions (io.vertx.proton.ProtonClientOptions)27 Test (org.junit.Test)20 Vertx (io.vertx.core.Vertx)19 ClientConfigProperties (org.eclipse.hono.config.ClientConfigProperties)19 Handler (io.vertx.core.Handler)17 Future (io.vertx.core.Future)16 TestContext (io.vertx.ext.unit.TestContext)16 VertxUnitRunner (io.vertx.ext.unit.junit.VertxUnitRunner)15 Constants (org.eclipse.hono.util.Constants)15 RunWith (org.junit.runner.RunWith)15 TimeUnit (java.util.concurrent.TimeUnit)14 MessageSender (org.eclipse.hono.client.MessageSender)14 BeforeClass (org.junit.BeforeClass)14 ProtonConnection (io.vertx.proton.ProtonConnection)13 HttpURLConnection (java.net.HttpURLConnection)13 CountDownLatch (java.util.concurrent.CountDownLatch)13 AsyncResult (io.vertx.core.AsyncResult)12 Async (io.vertx.ext.unit.Async)12 ClientErrorException (org.eclipse.hono.client.ClientErrorException)12 RegistrationClient (org.eclipse.hono.client.RegistrationClient)12