Search in sources :

Example 11 with ServerErrorException

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

the class HonoClientImpl method getOrCreateSender.

Future<MessageSender> getOrCreateSender(final String key, final Supplier<Future<MessageSender>> newSenderSupplier) {
    final Future<MessageSender> result = Future.future();
    context.runOnContext(get -> {
        final MessageSender sender = activeSenders.get(key);
        if (sender != null && sender.isOpen()) {
            LOG.debug("reusing existing message sender [target: {}, credit: {}]", key, sender.getCredit());
            result.complete(sender);
        } else if (!creationLocks.computeIfAbsent(key, k -> Boolean.FALSE)) {
            // register a handler to be notified if the underlying connection to the server fails
            // so that we can fail the result handler passed in
            final Handler<Void> connectionFailureHandler = connectionLost -> {
                // remove lock so that next attempt to open a sender doesn't fail
                creationLocks.remove(key);
                result.tryFail(new ServerErrorException(HttpURLConnection.HTTP_UNAVAILABLE, "no connection to service"));
            };
            creationRequests.add(connectionFailureHandler);
            creationLocks.put(key, Boolean.TRUE);
            LOG.debug("creating new message sender for {}", key);
            newSenderSupplier.get().setHandler(creationAttempt -> {
                creationLocks.remove(key);
                creationRequests.remove(connectionFailureHandler);
                if (creationAttempt.succeeded()) {
                    MessageSender newSender = creationAttempt.result();
                    LOG.debug("successfully created new message sender for {}", key);
                    activeSenders.put(key, newSender);
                    result.tryComplete(newSender);
                } else {
                    LOG.debug("failed to create new message sender for {}", key, creationAttempt.cause());
                    activeSenders.remove(key);
                    result.tryFail(creationAttempt.cause());
                }
            });
        } else {
            LOG.debug("already trying to create a message sender for {}", key);
            result.fail(new ServerErrorException(HttpURLConnection.HTTP_UNAVAILABLE, "no connection to service"));
        }
    });
    return result;
}
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) MessageSender(org.eclipse.hono.client.MessageSender) Handler(io.vertx.core.Handler) ServerErrorException(org.eclipse.hono.client.ServerErrorException)

Example 12 with ServerErrorException

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

the class HonoClientImpl method isConnected.

/**
 * {@inheritDoc}
 */
@Override
public final Future<Void> isConnected() {
    final Future<Void> result = Future.future();
    context.runOnContext(check -> {
        if (isConnectedInternal()) {
            result.complete();
        } else {
            result.fail(new ServerErrorException(HttpURLConnection.HTTP_UNAVAILABLE));
        }
    });
    return result;
}
Also used : ServerErrorException(org.eclipse.hono.client.ServerErrorException)

Example 13 with ServerErrorException

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

the class AbstractRequestResponseClientTest method testCancelRequestFailsResponseHandler.

/**
 * Verifies that the client cancels and fails a request for which no response
 * has been received after a certain amount of time. The request is then
 * failed with a {@link ServerErrorException}.
 *
 * @param ctx The vert.x test context.
 */
@SuppressWarnings("unchecked")
@Test
public void testCancelRequestFailsResponseHandler(final TestContext ctx) {
    // GIVEN a request-response client which times out requests after 200 ms
    client.setRequestTimeout(200);
    // WHEN no response is received for a request sent to the peer
    doAnswer(invocation -> {
        // do not wait 200ms before running the timeout task but instead
        // run it immediately
        Handler<Long> task = invocation.getArgument(1);
        task.handle(1L);
        return null;
    }).when(vertx).setTimer(anyLong(), any(Handler.class));
    final Async requestFailure = ctx.async();
    client.createAndSendRequest("request", null, (JsonObject) null, ctx.asyncAssertFailure(t -> {
        ctx.assertTrue(ServerErrorException.class.isInstance(t));
        requestFailure.complete();
    }));
    // THEN the request handler is failed
    requestFailure.await();
}
Also used : ArgumentMatchers.any(org.mockito.ArgumentMatchers.any) HttpURLConnection(java.net.HttpURLConnection) CacheDirective(org.eclipse.hono.util.CacheDirective) TestContext(io.vertx.ext.unit.TestContext) ProtonReceiver(io.vertx.proton.ProtonReceiver) CoreMatchers(org.hamcrest.CoreMatchers) Async(io.vertx.ext.unit.Async) ArgumentMatchers.anyLong(org.mockito.ArgumentMatchers.anyLong) ProtonDelivery(io.vertx.proton.ProtonDelivery) Rejected(org.apache.qpid.proton.amqp.messaging.Rejected) ArgumentMatchers.eq(org.mockito.ArgumentMatchers.eq) RunWith(org.junit.runner.RunWith) ExpiringValueCache(org.eclipse.hono.cache.ExpiringValueCache) Context(io.vertx.core.Context) Assert.assertThat(org.junit.Assert.assertThat) ArgumentCaptor(org.mockito.ArgumentCaptor) AmqpValue(org.apache.qpid.proton.amqp.messaging.AmqpValue) Target(org.apache.qpid.proton.amqp.transport.Target) Duration(java.time.Duration) Map(java.util.Map) Timeout(org.junit.rules.Timeout) Message(org.apache.qpid.proton.message.Message) JsonObject(io.vertx.core.json.JsonObject) ClientConfigProperties(org.eclipse.hono.config.ClientConfigProperties) RequestResponseClientConfigProperties(org.eclipse.hono.client.RequestResponseClientConfigProperties) Before(org.junit.Before) Vertx(io.vertx.core.Vertx) ServerErrorException(org.eclipse.hono.client.ServerErrorException) Test(org.junit.Test) ProtonHelper(io.vertx.proton.ProtonHelper) VertxUnitRunner(io.vertx.ext.unit.junit.VertxUnitRunner) MessageHelper(org.eclipse.hono.util.MessageHelper) Mockito(org.mockito.Mockito) Rule(org.junit.Rule) ProtonSender(io.vertx.proton.ProtonSender) Handler(io.vertx.core.Handler) Collections(java.util.Collections) Async(io.vertx.ext.unit.Async) ArgumentMatchers.anyLong(org.mockito.ArgumentMatchers.anyLong) Handler(io.vertx.core.Handler) Test(org.junit.Test)

Example 14 with ServerErrorException

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

the class HonoClientImplTest method testConnectFailsAfterMaxConnectionAttempts.

/**
 * Verifies that the client tries to connect a limited
 * number of times only.
 *
 * @param ctx The vert.x test client.
 */
@Test
public void testConnectFailsAfterMaxConnectionAttempts(final TestContext ctx) {
    // GIVEN a client that is configured to connect
    // to a peer that is not listening
    props.setHost(InetAddress.getLoopbackAddress().getHostAddress());
    props.setPort(45000);
    client = new HonoClientImpl(vertx, props);
    final ProtonClientOptions options = new ProtonClientOptions().setConnectTimeout(50).setReconnectAttempts(3).setReconnectInterval(50);
    // WHEN the client tries to connect
    client.connect(options).setHandler(ctx.asyncAssertFailure(t -> {
        // THEN the connection attempt fails
        ctx.assertEquals(HttpURLConnection.HTTP_UNAVAILABLE, ((ServerErrorException) t).getErrorCode());
    }));
}
Also used : HttpURLConnection(java.net.HttpURLConnection) RequestResponseClient(org.eclipse.hono.client.RequestResponseClient) TestContext(io.vertx.ext.unit.TestContext) ProtonConnection(io.vertx.proton.ProtonConnection) Async(io.vertx.ext.unit.Async) BeforeClass(org.junit.BeforeClass) RunWith(org.junit.runner.RunWith) ClientErrorException(org.eclipse.hono.client.ClientErrorException) Constants(org.eclipse.hono.util.Constants) InetAddress(java.net.InetAddress) ConnectionFactory(org.eclipse.hono.connection.ConnectionFactory) ProtonClientOptions(io.vertx.proton.ProtonClientOptions) MessageSender(org.eclipse.hono.client.MessageSender) Timeout(org.junit.rules.Timeout) RegistrationClient(org.eclipse.hono.client.RegistrationClient) AsyncResult(io.vertx.core.AsyncResult) ClientConfigProperties(org.eclipse.hono.config.ClientConfigProperties) Before(org.junit.Before) AfterClass(org.junit.AfterClass) Vertx(io.vertx.core.Vertx) Assert.assertTrue(org.junit.Assert.assertTrue) ServerErrorException(org.eclipse.hono.client.ServerErrorException) Test(org.junit.Test) VertxUnitRunner(io.vertx.ext.unit.junit.VertxUnitRunner) Future(io.vertx.core.Future) TimeUnit(java.util.concurrent.TimeUnit) Mockito(org.mockito.Mockito) CountDownLatch(java.util.concurrent.CountDownLatch) Rule(org.junit.Rule) Handler(io.vertx.core.Handler) ProtonClientOptions(io.vertx.proton.ProtonClientOptions) ServerErrorException(org.eclipse.hono.client.ServerErrorException) Test(org.junit.Test)

Aggregations

ServerErrorException (org.eclipse.hono.client.ServerErrorException)14 Handler (io.vertx.core.Handler)9 Vertx (io.vertx.core.Vertx)8 ProtonDelivery (io.vertx.proton.ProtonDelivery)8 HttpURLConnection (java.net.HttpURLConnection)8 JsonObject (io.vertx.core.json.JsonObject)7 Message (org.apache.qpid.proton.message.Message)7 ClientConfigProperties (org.eclipse.hono.config.ClientConfigProperties)7 Context (io.vertx.core.Context)6 TestContext (io.vertx.ext.unit.TestContext)6 VertxUnitRunner (io.vertx.ext.unit.junit.VertxUnitRunner)6 Map (java.util.Map)6 Rejected (org.apache.qpid.proton.amqp.messaging.Rejected)6 ClientErrorException (org.eclipse.hono.client.ClientErrorException)6 Async (io.vertx.ext.unit.Async)5 Test (org.junit.Test)5 Future (io.vertx.core.Future)4 AmqpValue (org.apache.qpid.proton.amqp.messaging.AmqpValue)4 Before (org.junit.Before)4 Rule (org.junit.Rule)4