Search in sources :

Example 11 with ServiceInvocationException

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

the class HttpTestBase method testUploadMessages.

/**
 * Verifies that a number of messages uploaded to Hono's HTTP adapter can be successfully
 * consumed via the AMQP Messaging Network.
 *
 * @param ctx The test context.
 * @throws InterruptedException if the test fails.
 */
@Test
public void testUploadMessages(final TestContext ctx) throws InterruptedException {
    final int messagesToSend = 100;
    final CountDownLatch received = new CountDownLatch(messagesToSend);
    final Async setup = ctx.async();
    final String tenantId = helper.getRandomTenantId();
    final String deviceId = helper.getRandomDeviceId(tenantId);
    final TenantObject tenant = TenantObject.from(tenantId, true);
    helper.registry.addTenant(JsonObject.mapFrom(tenant)).compose(ok -> helper.registry.registerDevice(tenantId, deviceId)).compose(ok -> createConsumer(tenantId, msg -> {
        LOGGER.trace("received {}", msg);
        assertMessageProperties(ctx, msg);
        assertAdditionalMessageProperties(ctx, msg);
        received.countDown();
        if (received.getCount() % 20 == 0) {
            LOGGER.info("messages received: {}", messagesToSend - received.getCount());
        }
    })).setHandler(ctx.asyncAssertSuccess(ok -> setup.complete()));
    setup.await();
    final long start = System.currentTimeMillis();
    final AtomicInteger messageCount = new AtomicInteger(0);
    while (messageCount.get() < messagesToSend) {
        final Async sending = ctx.async();
        send(tenantId, deviceId, Buffer.buffer("hello " + messageCount.getAndIncrement())).setHandler(attempt -> {
            if (attempt.succeeded()) {
                LOGGER.debug("sent message {} [status code: 202]", messageCount.get());
            } else {
                LOGGER.debug("sent message {} [status code: {}]", messageCount.get(), ((ServiceInvocationException) attempt.cause()).getErrorCode());
            }
            sending.complete();
        });
        if (messageCount.get() % 20 == 0) {
            LOGGER.info("messages sent: " + messageCount.get());
        }
        sending.await();
    }
    long timeToWait = Math.max(TEST_TIMEOUT - 1000, Math.round(messagesToSend * 1.2));
    if (!received.await(timeToWait, TimeUnit.MILLISECONDS)) {
        LOGGER.info("sent {} and received {} messages after {} milliseconds", messageCount, messagesToSend - received.getCount(), System.currentTimeMillis() - start);
        ctx.fail("did not receive all messages sent");
    } else {
        LOGGER.info("sent {} and received {} messages after {} milliseconds", messageCount, messagesToSend - received.getCount(), System.currentTimeMillis() - start);
    }
}
Also used : HttpURLConnection(java.net.HttpURLConnection) TestContext(io.vertx.ext.unit.TestContext) Async(io.vertx.ext.unit.Async) BeforeClass(org.junit.BeforeClass) TenantConstants(org.eclipse.hono.util.TenantConstants) LoggerFactory(org.slf4j.LoggerFactory) MessageConsumer(org.eclipse.hono.client.MessageConsumer) ServiceInvocationException(org.eclipse.hono.client.ServiceInvocationException) Constants(org.eclipse.hono.util.Constants) IntegrationTestSupport(org.eclipse.hono.tests.IntegrationTestSupport) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) After(org.junit.After) Timeout(org.junit.rules.Timeout) Message(org.apache.qpid.proton.message.Message) JsonObject(io.vertx.core.json.JsonObject) AfterClass(org.junit.AfterClass) Logger(org.slf4j.Logger) Vertx(io.vertx.core.Vertx) Test(org.junit.Test) MessageHelper(org.eclipse.hono.util.MessageHelper) Future(io.vertx.core.Future) TenantObject(org.eclipse.hono.util.TenantObject) TimeUnit(java.util.concurrent.TimeUnit) Consumer(java.util.function.Consumer) CountDownLatch(java.util.concurrent.CountDownLatch) Rule(org.junit.Rule) Buffer(io.vertx.core.buffer.Buffer) CrudHttpClient(org.eclipse.hono.tests.CrudHttpClient) TenantObject(org.eclipse.hono.util.TenantObject) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Async(io.vertx.ext.unit.Async) CountDownLatch(java.util.concurrent.CountDownLatch) Test(org.junit.Test)

Example 12 with ServiceInvocationException

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

the class BaseTenantServiceTest method testAddFailsForAdapterConfigWithoutType.

/**
 * Verifies that the base service fails for a payload that defines an adapter entry, but does not provide the
 * mandatory field {@link TenantConstants#FIELD_ADAPTERS_TYPE}.
 *
 * @param ctx The vert.x test context.
 */
@Test
public void testAddFailsForAdapterConfigWithoutType(final TestContext ctx) {
    final JsonObject testPayload = createValidTenantPayload();
    final JsonArray adapterArray = new JsonArray();
    // no type specified (which is a violation of the API)
    adapterArray.add(new JsonObject());
    testPayload.put(TenantConstants.FIELD_ADAPTERS, adapterArray);
    final EventBusMessage msg = createRequest(TenantConstants.TenantAction.add, testPayload);
    tenantService.processRequest(msg).setHandler(ctx.asyncAssertFailure(t -> {
        ctx.assertEquals(HttpURLConnection.HTTP_BAD_REQUEST, ((ServiceInvocationException) t).getErrorCode());
    }));
}
Also used : JsonArray(io.vertx.core.json.JsonArray) HttpURLConnection(java.net.HttpURLConnection) TestContext(io.vertx.ext.unit.TestContext) TenantResult(org.eclipse.hono.util.TenantResult) BeforeClass(org.junit.BeforeClass) TenantConstants(org.eclipse.hono.util.TenantConstants) RunWith(org.junit.runner.RunWith) Test(org.junit.Test) EventBusMessage(org.eclipse.hono.util.EventBusMessage) VertxUnitRunner(io.vertx.ext.unit.junit.VertxUnitRunner) ServiceInvocationException(org.eclipse.hono.client.ServiceInvocationException) ServiceConfigProperties(org.eclipse.hono.config.ServiceConfigProperties) Future(io.vertx.core.Future) JsonArray(io.vertx.core.json.JsonArray) Timeout(org.junit.rules.Timeout) JsonObject(io.vertx.core.json.JsonObject) AsyncResult(io.vertx.core.AsyncResult) Handler(io.vertx.core.Handler) EventBusMessage(org.eclipse.hono.util.EventBusMessage) JsonObject(io.vertx.core.json.JsonObject) ServiceInvocationException(org.eclipse.hono.client.ServiceInvocationException) Test(org.junit.Test)

Example 13 with ServiceInvocationException

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

the class EventBusService method processRequestMessage.

private void processRequestMessage(final Message<JsonObject> msg) {
    if (log.isTraceEnabled()) {
        log.trace("received request message: {}", msg.body().encodePrettily());
    }
    final EventBusMessage request = EventBusMessage.fromJson(msg.body());
    processRequest(request).recover(t -> {
        log.debug("cannot process request [operation: {}]: {}", request.getOperation(), t.getMessage());
        final int status = Optional.of(t).map(cause -> {
            if (cause instanceof ServiceInvocationException) {
                return ((ServiceInvocationException) cause).getErrorCode();
            } else {
                return null;
            }
        }).orElse(HttpURLConnection.HTTP_INTERNAL_ERROR);
        return Future.succeededFuture(request.getResponse(status));
    }).map(response -> {
        if (response.getReplyToAddress() == null) {
            log.debug("sending response as direct reply to request [operation: {}]", request.getOperation());
            msg.reply(response.toJson());
        } else if (response.hasResponseProperties()) {
            log.debug("sending response [operation: {}, reply-to: {}]", request.getOperation(), request.getReplyToAddress());
            vertx.eventBus().send(request.getReplyToAddress(), response.toJson());
        } else {
            log.warn("discarding response lacking correlation ID or operation");
        }
        return null;
    });
}
Also used : HttpURLConnection(java.net.HttpURLConnection) Logger(org.slf4j.Logger) LoggerFactory(org.slf4j.LoggerFactory) Message(io.vertx.core.eventbus.Message) EventBusMessage(org.eclipse.hono.util.EventBusMessage) ServiceInvocationException(org.eclipse.hono.client.ServiceInvocationException) RequestResponseApiConstants(org.eclipse.hono.util.RequestResponseApiConstants) ConfigurationSupportingVerticle(org.eclipse.hono.util.ConfigurationSupportingVerticle) Future(io.vertx.core.Future) Objects(java.util.Objects) Optional(java.util.Optional) JsonObject(io.vertx.core.json.JsonObject) MessageConsumer(io.vertx.core.eventbus.MessageConsumer) EventBusMessage(org.eclipse.hono.util.EventBusMessage) ServiceInvocationException(org.eclipse.hono.client.ServiceInvocationException)

Example 14 with ServiceInvocationException

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

the class CredentialsApiAuthProvider method authenticate.

@Override
public final void authenticate(final DeviceCredentials deviceCredentials, final Handler<AsyncResult<Device>> resultHandler) {
    Objects.requireNonNull(deviceCredentials);
    Objects.requireNonNull(resultHandler);
    Future<Device> validationResult = Future.future();
    validationResult.setHandler(resultHandler);
    getCredentialsForDevice(deviceCredentials).recover(t -> {
        final ServiceInvocationException e = (ServiceInvocationException) t;
        if (e.getErrorCode() == HttpURLConnection.HTTP_NOT_FOUND) {
            return Future.failedFuture(new ClientErrorException(HttpURLConnection.HTTP_UNAUTHORIZED, "bad credentials"));
        } else {
            return Future.failedFuture(t);
        }
    }).map(credentialsOnRecord -> {
        if (deviceCredentials.validate(credentialsOnRecord)) {
            return new Device(deviceCredentials.getTenantId(), credentialsOnRecord.getDeviceId());
        } else {
            throw new ClientErrorException(HttpURLConnection.HTTP_UNAUTHORIZED, "invalid credentials");
        }
    }).setHandler(resultHandler);
}
Also used : HttpURLConnection(java.net.HttpURLConnection) ProtonConnection(io.vertx.proton.ProtonConnection) Logger(org.slf4j.Logger) LoggerFactory(org.slf4j.LoggerFactory) Vertx(io.vertx.core.Vertx) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) Autowired(org.springframework.beans.factory.annotation.Autowired) ClientErrorException(org.eclipse.hono.client.ClientErrorException) ServiceInvocationException(org.eclipse.hono.client.ServiceInvocationException) Constants(org.eclipse.hono.util.Constants) Future(io.vertx.core.Future) CredentialsConstants(org.eclipse.hono.util.CredentialsConstants) Objects(java.util.Objects) Status(io.vertx.ext.healthchecks.Status) CredentialsClient(org.eclipse.hono.client.CredentialsClient) User(io.vertx.ext.auth.User) HealthCheckHandler(io.vertx.ext.healthchecks.HealthCheckHandler) Qualifier(org.springframework.beans.factory.annotation.Qualifier) Optional(java.util.Optional) JsonObject(io.vertx.core.json.JsonObject) AsyncResult(io.vertx.core.AsyncResult) Handler(io.vertx.core.Handler) HonoClient(org.eclipse.hono.client.HonoClient) CredentialsObject(org.eclipse.hono.util.CredentialsObject) ClientErrorException(org.eclipse.hono.client.ClientErrorException) ServiceInvocationException(org.eclipse.hono.client.ServiceInvocationException)

Example 15 with ServiceInvocationException

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

the class BaseCredentialsServiceTest method testGetFailsForMissingAuthId.

/**
 * Verifies that the base service fails a request for getting credentials
 * with a 400 error code if the authentication identifier is missing.
 *
 * @param ctx The vert.x test context.
 */
@Test
public void testGetFailsForMissingAuthId(final TestContext ctx) {
    // GIVEN a request for getting credentials that does not specify an auth ID
    final CredentialsObject malformedPayload = new CredentialsObject().setType("my-type").addSecret(CredentialsObject.emptySecret(null, null));
    final EventBusMessage request = createRequestForPayload(CredentialsConstants.CredentialsAction.get, JsonObject.mapFrom(malformedPayload));
    // WHEN processing the request
    service.processRequest(request).setHandler(ctx.asyncAssertFailure(t -> {
        // THEN the response contains a 400 error code
        ctx.assertEquals(HttpURLConnection.HTTP_BAD_REQUEST, ((ServiceInvocationException) t).getErrorCode());
    }));
}
Also used : HttpURLConnection(java.net.HttpURLConnection) TestContext(io.vertx.ext.unit.TestContext) BeforeClass(org.junit.BeforeClass) CredentialsResult(org.eclipse.hono.util.CredentialsResult) RunWith(org.junit.runner.RunWith) Test(org.junit.Test) EventBusMessage(org.eclipse.hono.util.EventBusMessage) VertxUnitRunner(io.vertx.ext.unit.junit.VertxUnitRunner) ServiceInvocationException(org.eclipse.hono.client.ServiceInvocationException) ServiceConfigProperties(org.eclipse.hono.config.ServiceConfigProperties) Future(io.vertx.core.Future) CredentialsConstants(org.eclipse.hono.util.CredentialsConstants) Timeout(org.junit.rules.Timeout) JsonObject(io.vertx.core.json.JsonObject) AsyncResult(io.vertx.core.AsyncResult) Handler(io.vertx.core.Handler) CredentialsObject(org.eclipse.hono.util.CredentialsObject) EventBusMessage(org.eclipse.hono.util.EventBusMessage) CredentialsObject(org.eclipse.hono.util.CredentialsObject) ServiceInvocationException(org.eclipse.hono.client.ServiceInvocationException) Test(org.junit.Test)

Aggregations

ServiceInvocationException (org.eclipse.hono.client.ServiceInvocationException)19 Future (io.vertx.core.Future)17 JsonObject (io.vertx.core.json.JsonObject)17 HttpURLConnection (java.net.HttpURLConnection)15 TestContext (io.vertx.ext.unit.TestContext)11 EventBusMessage (org.eclipse.hono.util.EventBusMessage)11 BeforeClass (org.junit.BeforeClass)11 Test (org.junit.Test)11 Timeout (org.junit.rules.Timeout)11 AsyncResult (io.vertx.core.AsyncResult)10 Handler (io.vertx.core.Handler)10 ServiceConfigProperties (org.eclipse.hono.config.ServiceConfigProperties)10 VertxUnitRunner (io.vertx.ext.unit.junit.VertxUnitRunner)9 RunWith (org.junit.runner.RunWith)9 Vertx (io.vertx.core.Vertx)7 CredentialsConstants (org.eclipse.hono.util.CredentialsConstants)7 CredentialsObject (org.eclipse.hono.util.CredentialsObject)7 Buffer (io.vertx.core.buffer.Buffer)6 Objects (java.util.Objects)6 Optional (java.util.Optional)6