Search in sources :

Example 1 with HonoClient

use of org.eclipse.hono.client.HonoClient in project hono by eclipse.

the class ClientTestBase method connect.

/**
 * Sets up the environment:
 * <ol>
 * <li>connect to the AMQP messaging network</li>
 * <li>connects to the Hono Server</li>
 * <li>connects to the Hono Device Registry</li>
 * <li>creates a RegistrationClient for TEST_TENANT_ID</li>
 * <li>creates a MessageSender for TEST_TENANT_ID</li>
 * </ul>
 *
 * @param ctx The test context
 */
@Before
public void connect(final TestContext ctx) {
    final ClientConfigProperties downstreamProps = new ClientConfigProperties();
    downstreamProps.setHost(IntegrationTestSupport.DOWNSTREAM_HOST);
    downstreamProps.setPort(IntegrationTestSupport.DOWNSTREAM_PORT);
    downstreamProps.setPathSeparator(IntegrationTestSupport.PATH_SEPARATOR);
    downstreamProps.setUsername(IntegrationTestSupport.RESTRICTED_CONSUMER_NAME);
    downstreamProps.setPassword(IntegrationTestSupport.RESTRICTED_CONSUMER_PWD);
    downstreamClient = new HonoClientImpl(vertx, ConnectionFactoryBuilder.newBuilder(downstreamProps).vertx(vertx).build(), downstreamProps);
    final ClientConfigProperties honoProps = new ClientConfigProperties();
    honoProps.setHost(IntegrationTestSupport.HONO_HOST);
    honoProps.setPort(IntegrationTestSupport.HONO_PORT);
    honoProps.setUsername(IntegrationTestSupport.HONO_USER);
    honoProps.setPassword(IntegrationTestSupport.HONO_PWD);
    honoClient = new HonoClientImpl(vertx, ConnectionFactoryBuilder.newBuilder(honoProps).vertx(vertx).build(), honoProps);
    final ClientConfigProperties registryProps = new ClientConfigProperties();
    registryProps.setHost(IntegrationTestSupport.HONO_DEVICEREGISTRY_HOST);
    registryProps.setPort(IntegrationTestSupport.HONO_DEVICEREGISTRY_AMQP_PORT);
    registryProps.setUsername(IntegrationTestSupport.HONO_USER);
    registryProps.setPassword(IntegrationTestSupport.HONO_PWD);
    honoDeviceRegistryClient = new HonoClientImpl(vertx, ConnectionFactoryBuilder.newBuilder(registryProps).vertx(vertx).build(), registryProps);
    final ProtonClientOptions options = new ProtonClientOptions();
    // connect to AMQP messaging network
    final Future<HonoClient> downstreamTracker = downstreamClient.connect(options);
    // create sender
    final Future<MessageSender> senderTracker = honoClient.connect(options).compose(connectedClient -> createProducer(TEST_TENANT_ID)).map(s -> {
        sender = s;
        return s;
    });
    // create registration client
    final Future<RegistrationClient> registrationClientTracker = honoDeviceRegistryClient.connect(options).compose(connectedClient -> connectedClient.getOrCreateRegistrationClient(TEST_TENANT_ID)).map(c -> {
        registrationClient = c;
        return c;
    });
    CompositeFuture.all(downstreamTracker, senderTracker, registrationClientTracker).setHandler(ctx.asyncAssertSuccess(s -> {
        LOGGER.info("connections to Hono server, Hono device registry and AMQP messaging network established");
    }));
}
Also used : TestContext(io.vertx.ext.unit.TestContext) Async(io.vertx.ext.unit.Async) LoggerFactory(org.slf4j.LoggerFactory) MessageConsumer(org.eclipse.hono.client.MessageConsumer) AtomicReference(java.util.concurrent.atomic.AtomicReference) Constants(org.eclipse.hono.util.Constants) CompositeFuture(io.vertx.core.CompositeFuture) ProtonClientOptions(io.vertx.proton.ProtonClientOptions) IntegrationTestSupport(org.eclipse.hono.tests.IntegrationTestSupport) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) ConnectionFactoryBuilder(org.eclipse.hono.connection.ConnectionFactoryImpl.ConnectionFactoryBuilder) MessageSender(org.eclipse.hono.client.MessageSender) After(org.junit.After) Message(org.apache.qpid.proton.message.Message) RegistrationClient(org.eclipse.hono.client.RegistrationClient) HonoClient(org.eclipse.hono.client.HonoClient) ClientConfigProperties(org.eclipse.hono.config.ClientConfigProperties) Before(org.junit.Before) Logger(org.slf4j.Logger) Vertx(io.vertx.core.Vertx) RegistrationConstants(org.eclipse.hono.util.RegistrationConstants) Test(org.junit.Test) HonoClientImpl(org.eclipse.hono.client.impl.HonoClientImpl) MessageHelper(org.eclipse.hono.util.MessageHelper) Future(io.vertx.core.Future) TimeUnit(java.util.concurrent.TimeUnit) Consumer(java.util.function.Consumer) CountDownLatch(java.util.concurrent.CountDownLatch) HonoClientImpl(org.eclipse.hono.client.impl.HonoClientImpl) HonoClient(org.eclipse.hono.client.HonoClient) MessageSender(org.eclipse.hono.client.MessageSender) RegistrationClient(org.eclipse.hono.client.RegistrationClient) ClientConfigProperties(org.eclipse.hono.config.ClientConfigProperties) ProtonClientOptions(io.vertx.proton.ProtonClientOptions) Before(org.junit.Before)

Example 2 with HonoClient

use of org.eclipse.hono.client.HonoClient in project hono by eclipse.

the class AbstractProtocolAdapterBaseTest method setup.

/**
 * Sets up the fixture.
 */
@Before
public void setup() {
    registrationClient = mock(RegistrationClient.class);
    HonoClient honoClient = mock(HonoClient.class);
    when(honoClient.getOrCreateRegistrationClient(anyString())).thenReturn(Future.succeededFuture(registrationClient));
    properties = new ProtocolAdapterProperties();
    adapter = newProtocolAdapter(properties);
    adapter.setRegistrationServiceClient(honoClient);
}
Also used : ProtocolAdapterProperties(org.eclipse.hono.config.ProtocolAdapterProperties) HonoClient(org.eclipse.hono.client.HonoClient) RegistrationClient(org.eclipse.hono.client.RegistrationClient) Before(org.junit.Before)

Example 3 with HonoClient

use of org.eclipse.hono.client.HonoClient 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 4 with HonoClient

use of org.eclipse.hono.client.HonoClient in project hono by eclipse.

the class HonoConsumerBase method consumeData.

/**
 * Initiate the connection and set the message handling method to treat data that is received.
 *
 * @throws Exception Thrown if the latch is interrupted during waiting or if the read from System.in throws an IOException.
 */
protected void consumeData() throws Exception {
    final CountDownLatch latch = new CountDownLatch(1);
    final Future<MessageConsumer> consumerFuture = Future.future();
    consumerFuture.setHandler(result -> {
        if (!result.succeeded()) {
            System.err.println("honoClient could not create telemetry consumer for " + HonoExampleConstants.HONO_AMQP_CONSUMER_HOST + ":" + HonoExampleConstants.HONO_AMQP_CONSUMER_PORT + " : " + result.cause());
        }
        latch.countDown();
    });
    honoClient.connect(new ProtonClientOptions()).compose(connectedClient -> {
        if (eventMode) {
            return connectedClient.createEventConsumer(HonoExampleConstants.TENANT_ID, this::handleMessage, closeHook -> System.err.println("remotely detached consumer link"));
        } else {
            return connectedClient.createTelemetryConsumer(HonoExampleConstants.TENANT_ID, this::handleMessage, closeHook -> System.err.println("remotely detached consumer link"));
        }
    }).setHandler(consumerFuture.completer());
    latch.await();
    if (consumerFuture.succeeded()) {
        System.in.read();
    }
    vertx.close();
}
Also used : Data(org.apache.qpid.proton.amqp.messaging.Data) CountDownLatch(java.util.concurrent.CountDownLatch) Section(org.apache.qpid.proton.amqp.messaging.Section) ProtonClientOptions(io.vertx.proton.ProtonClientOptions) Vertx(io.vertx.core.Vertx) Message(org.apache.qpid.proton.message.Message) MessageConsumer(org.eclipse.hono.client.MessageConsumer) HonoClientImpl(org.eclipse.hono.client.impl.HonoClientImpl) MessageHelper(org.eclipse.hono.util.MessageHelper) HonoClient(org.eclipse.hono.client.HonoClient) ClientConfigProperties(org.eclipse.hono.config.ClientConfigProperties) Future(io.vertx.core.Future) MessageConsumer(org.eclipse.hono.client.MessageConsumer) ProtonClientOptions(io.vertx.proton.ProtonClientOptions) CountDownLatch(java.util.concurrent.CountDownLatch)

Example 5 with HonoClient

use of org.eclipse.hono.client.HonoClient in project hono by eclipse.

the class AbstractProtocolAdapterBaseTest method testStartInternalConnectsToServices.

/**
 * Verifies that the adapter connects to required services during
 * startup and invokes the <em>doStart</em> method.
 *
 * @param ctx The vert.x test context.
 */
@SuppressWarnings("unchecked")
@Test
public void testStartInternalConnectsToServices(final TestContext ctx) {
    // GIVEN an adapter configured with service clients
    final Handler<Void> startupHandler = mock(Handler.class);
    adapter = newProtocolAdapter(properties, "test", startupHandler);
    final HonoClient tenantService = mock(HonoClient.class);
    when(tenantService.connect(any(Handler.class))).thenReturn(Future.succeededFuture(tenantService));
    adapter.setTenantServiceClient(tenantService);
    final HonoClient registrationService = mock(HonoClient.class);
    when(registrationService.connect(any(Handler.class))).thenReturn(Future.succeededFuture(registrationService));
    adapter.setRegistrationServiceClient(registrationService);
    final HonoClient messagingService = mock(HonoClient.class);
    when(messagingService.connect(any(Handler.class))).thenReturn(Future.succeededFuture(messagingService));
    adapter.setHonoMessagingClient(messagingService);
    final HonoClientBasedAuthProvider authProvider = mock(HonoClientBasedAuthProvider.class);
    when(authProvider.start()).thenReturn(Future.succeededFuture());
    adapter.setCredentialsAuthProvider(authProvider);
    // WHEN starting the adapter
    adapter.startInternal().setHandler(ctx.asyncAssertSuccess(ok -> {
        // THEN the service clients have connected
        verify(tenantService).connect(any(Handler.class));
        verify(registrationService).connect(any(Handler.class));
        verify(messagingService).connect(any(Handler.class));
        verify(authProvider).start();
        // and the startup handler has been invoked
        verify(startupHandler).handle(null);
    }));
}
Also used : CoreMatchers.is(org.hamcrest.CoreMatchers.is) HttpURLConnection(java.net.HttpURLConnection) TestContext(io.vertx.ext.unit.TestContext) RunWith(org.junit.runner.RunWith) ClientErrorException(org.eclipse.hono.client.ClientErrorException) ServiceInvocationException(org.eclipse.hono.client.ServiceInvocationException) Assert.assertThat(org.junit.Assert.assertThat) Timeout(org.junit.rules.Timeout) Message(org.apache.qpid.proton.message.Message) RegistrationClient(org.eclipse.hono.client.RegistrationClient) JsonObject(io.vertx.core.json.JsonObject) HonoClient(org.eclipse.hono.client.HonoClient) Before(org.junit.Before) ProtocolAdapterProperties(org.eclipse.hono.config.ProtocolAdapterProperties) RegistrationConstants(org.eclipse.hono.util.RegistrationConstants) Test(org.junit.Test) ProtonHelper(io.vertx.proton.ProtonHelper) VertxUnitRunner(io.vertx.ext.unit.junit.VertxUnitRunner) MessageHelper(org.eclipse.hono.util.MessageHelper) Future(io.vertx.core.Future) Mockito(org.mockito.Mockito) HonoClientBasedAuthProvider(org.eclipse.hono.service.auth.device.HonoClientBasedAuthProvider) Rule(org.junit.Rule) Device(org.eclipse.hono.service.auth.device.Device) Handler(io.vertx.core.Handler) HonoClient(org.eclipse.hono.client.HonoClient) Handler(io.vertx.core.Handler) HonoClientBasedAuthProvider(org.eclipse.hono.service.auth.device.HonoClientBasedAuthProvider) Test(org.junit.Test)

Aggregations

HonoClient (org.eclipse.hono.client.HonoClient)5 Future (io.vertx.core.Future)4 Message (org.apache.qpid.proton.message.Message)4 RegistrationClient (org.eclipse.hono.client.RegistrationClient)4 Vertx (io.vertx.core.Vertx)3 ProtonClientOptions (io.vertx.proton.ProtonClientOptions)3 CountDownLatch (java.util.concurrent.CountDownLatch)3 MessageConsumer (org.eclipse.hono.client.MessageConsumer)3 ClientConfigProperties (org.eclipse.hono.config.ClientConfigProperties)3 MessageHelper (org.eclipse.hono.util.MessageHelper)3 Handler (io.vertx.core.Handler)2 TestContext (io.vertx.ext.unit.TestContext)2 HttpURLConnection (java.net.HttpURLConnection)2 TimeUnit (java.util.concurrent.TimeUnit)2 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)2 Consumer (java.util.function.Consumer)2 ClientErrorException (org.eclipse.hono.client.ClientErrorException)2 MessageSender (org.eclipse.hono.client.MessageSender)2 Before (org.junit.Before)2 AsyncResult (io.vertx.core.AsyncResult)1