Search in sources :

Example 1 with EventBusMessage

use of org.eclipse.hono.util.EventBusMessage in project hono by eclipse.

the class BaseTenantServiceTest method testAddFailsForEmptyAdapterArray.

/**
 * Verifies that the base service fails for a payload that defines an empty adapter array (must be null or has to
 * contain at least one element).
 *
 * @param ctx The vert.x test context.
 */
@Test
public void testAddFailsForEmptyAdapterArray(final TestContext ctx) {
    final JsonObject testPayload = createValidTenantPayload();
    testPayload.put(TenantConstants.FIELD_ADAPTERS, new JsonArray());
    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 2 with EventBusMessage

use of org.eclipse.hono.util.EventBusMessage in project hono by eclipse.

the class BaseTenantServiceTest method testAddFailsForIncompleteMessage.

/**
 * Verifies that the base service fails for an incomplete message that does not contain mandatory fields.
 *
 * @param ctx The vert.x test context.
 */
@Test
public void testAddFailsForIncompleteMessage(final TestContext ctx) {
    final EventBusMessage msg = EventBusMessage.forOperation(TenantConstants.TenantAction.add.toString());
    tenantService.processRequest(msg).setHandler(ctx.asyncAssertFailure(t -> {
        ctx.assertEquals(HttpURLConnection.HTTP_BAD_REQUEST, ((ServiceInvocationException) t).getErrorCode());
    }));
}
Also used : 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) ServiceInvocationException(org.eclipse.hono.client.ServiceInvocationException) Test(org.junit.Test)

Example 3 with EventBusMessage

use of org.eclipse.hono.util.EventBusMessage in project hono by eclipse.

the class FileBasedRegistrationServiceTest method testDuplicateRegistrationFails.

/**
 * Verifies that the registry returns 409 when trying to register a device twice.
 *
 * @param ctx The vert.x test context.
 */
@Test
public void testDuplicateRegistrationFails(final TestContext ctx) {
    final EventBusMessage createRequest = newRequest(RegistrationConstants.ACTION_REGISTER, TENANT);
    registrationService.processRequest(createRequest).map(response -> {
        ctx.assertEquals(HttpURLConnection.HTTP_CREATED, response.getStatus());
        return response;
    }).compose(ok -> registrationService.processRequest(createRequest)).setHandler(ctx.asyncAssertSuccess(response -> {
        ctx.assertEquals(HttpURLConnection.HTTP_CONFLICT, response.getStatus());
    }));
}
Also used : CoreMatchers.is(org.hamcrest.CoreMatchers.is) HttpURLConnection(java.net.HttpURLConnection) TestContext(io.vertx.ext.unit.TestContext) Async(io.vertx.ext.unit.Async) ArgumentMatchers(org.mockito.ArgumentMatchers) RunWith(org.junit.runner.RunWith) EventBusMessage(org.eclipse.hono.util.EventBusMessage) ServiceInvocationException(org.eclipse.hono.client.ServiceInvocationException) Constants(org.eclipse.hono.util.Constants) Context(io.vertx.core.Context) Assert.assertThat(org.junit.Assert.assertThat) EventBus(io.vertx.core.eventbus.EventBus) RegistrationResult(org.eclipse.hono.util.RegistrationResult) Timeout(org.junit.rules.Timeout) JsonObject(io.vertx.core.json.JsonObject) Before(org.junit.Before) Vertx(io.vertx.core.Vertx) RegistrationConstants(org.eclipse.hono.util.RegistrationConstants) Test(org.junit.Test) VertxUnitRunner(io.vertx.ext.unit.junit.VertxUnitRunner) Future(io.vertx.core.Future) StandardCharsets(java.nio.charset.StandardCharsets) Mockito(org.mockito.Mockito) Rule(org.junit.Rule) Buffer(io.vertx.core.buffer.Buffer) Assert.assertFalse(org.junit.Assert.assertFalse) FileSystem(io.vertx.core.file.FileSystem) Handler(io.vertx.core.Handler) EventBusMessage(org.eclipse.hono.util.EventBusMessage) Test(org.junit.Test)

Example 4 with EventBusMessage

use of org.eclipse.hono.util.EventBusMessage in project hono by eclipse.

the class RequestResponseEndpoint method onLinkAttach.

/**
 * Handles a client's request to establish a link for receiving responses
 * to service invocations.
 * <p>
 * This method registers a consumer on the vert.x event bus for the given reply-to address.
 * Response messages received over the event bus are transformed into AMQP messages using
 * the {@link #getAmqpReply(EventBusMessage)} method and sent to the client over the established
 * link.
 *
 * @param con The AMQP connection that the link is part of.
 * @param sender The link to establish.
 * @param replyToAddress The reply-to address to create a consumer on the event bus for.
 */
@Override
public final void onLinkAttach(final ProtonConnection con, final ProtonSender sender, final ResourceIdentifier replyToAddress) {
    if (isValidReplyToAddress(replyToAddress)) {
        logger.debug("establishing sender link with client [{}]", sender.getName());
        final MessageConsumer<JsonObject> replyConsumer = vertx.eventBus().consumer(replyToAddress.toString(), message -> {
            // TODO check for correct session here...?
            if (logger.isTraceEnabled()) {
                logger.trace("forwarding reply to client [{}]: {}", sender.getName(), message.body().encodePrettily());
            }
            final EventBusMessage response = EventBusMessage.fromJson(message.body());
            filterResponse(Constants.getClientPrincipal(con), response).recover(t -> {
                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(response.getResponse(status));
            }).map(filteredResponse -> {
                final Message amqpReply = getAmqpReply(filteredResponse);
                sender.send(amqpReply);
                return null;
            });
        });
        sender.setQoS(ProtonQoS.AT_LEAST_ONCE);
        sender.closeHandler(senderClosed -> {
            logger.debug("client [{}] closed sender link, removing associated event bus consumer [{}]", sender.getName(), replyConsumer.address());
            replyConsumer.unregister();
            if (senderClosed.succeeded()) {
                senderClosed.result().close();
            }
        });
        sender.open();
    } else {
        logger.debug("client [{}] provided invalid reply-to address", sender.getName());
        sender.setCondition(ProtonHelper.condition(AmqpError.INVALID_FIELD, String.format("reply-to address must have the following format %s/<tenant>/<reply-address>", getName())));
        sender.close();
    }
}
Also used : HttpURLConnection(java.net.HttpURLConnection) ProtonConnection(io.vertx.proton.ProtonConnection) ProtonReceiver(io.vertx.proton.ProtonReceiver) AmqpErrorException(org.eclipse.hono.util.AmqpErrorException) ProtonDelivery(io.vertx.proton.ProtonDelivery) DecodeException(io.vertx.core.json.DecodeException) Autowired(org.springframework.beans.factory.annotation.Autowired) EventBusMessage(org.eclipse.hono.util.EventBusMessage) HonoUser(org.eclipse.hono.auth.HonoUser) ServiceInvocationException(org.eclipse.hono.client.ServiceInvocationException) ServiceConfigProperties(org.eclipse.hono.config.ServiceConfigProperties) Constants(org.eclipse.hono.util.Constants) Message(org.apache.qpid.proton.message.Message) ResourceIdentifier(org.eclipse.hono.util.ResourceIdentifier) JsonObject(io.vertx.core.json.JsonObject) AmqpError(org.apache.qpid.proton.amqp.transport.AmqpError) Vertx(io.vertx.core.Vertx) ProtonHelper(io.vertx.proton.ProtonHelper) ProtonQoS(io.vertx.proton.ProtonQoS) MessageHelper(org.eclipse.hono.util.MessageHelper) Future(io.vertx.core.Future) Objects(java.util.Objects) Optional(java.util.Optional) ProtonSender(io.vertx.proton.ProtonSender) ClaimsBasedAuthorizationService(org.eclipse.hono.service.auth.ClaimsBasedAuthorizationService) MessageConsumer(io.vertx.core.eventbus.MessageConsumer) AuthorizationService(org.eclipse.hono.service.auth.AuthorizationService) EventBusMessage(org.eclipse.hono.util.EventBusMessage) Message(org.apache.qpid.proton.message.Message) EventBusMessage(org.eclipse.hono.util.EventBusMessage) JsonObject(io.vertx.core.json.JsonObject) ServiceInvocationException(org.eclipse.hono.client.ServiceInvocationException)

Example 5 with EventBusMessage

use of org.eclipse.hono.util.EventBusMessage in project hono by eclipse.

the class BaseCredentialsService method processRemoveRequest.

private Future<EventBusMessage> processRemoveRequest(final EventBusMessage request) {
    final String tenantId = request.getTenant();
    final JsonObject payload = request.getJsonPayload();
    if (tenantId == null || payload == null) {
        return Future.failedFuture(new ClientErrorException(HttpURLConnection.HTTP_BAD_REQUEST));
    } else {
        final String type = getTypesafeValueForField(payload, CredentialsConstants.FIELD_TYPE);
        final String authId = getTypesafeValueForField(payload, CredentialsConstants.FIELD_AUTH_ID);
        final String deviceId = getTypesafeValueForField(payload, CredentialsConstants.FIELD_PAYLOAD_DEVICE_ID);
        if (type == null) {
            log.debug("remove credentials request does not contain mandatory type parameter");
            return Future.failedFuture(new ClientErrorException(HttpURLConnection.HTTP_BAD_REQUEST));
        } else if (!type.equals(CredentialsConstants.SPECIFIER_WILDCARD) && authId != null) {
            // delete a single credentials instance
            log.debug("removing specific credentials [tenant: {}, type: {}, auth-id: {}]", tenantId, type, authId);
            final Future<CredentialsResult<JsonObject>> result = Future.future();
            remove(tenantId, type, authId, result.completer());
            return result.map(res -> {
                return request.getResponse(res.getStatus()).setCacheDirective(res.getCacheDirective());
            });
        } else if (deviceId != null && type.equals(CredentialsConstants.SPECIFIER_WILDCARD)) {
            // delete all credentials for device
            log.debug("removing all credentials for device [tenant: {}, device-id: {}]", tenantId, deviceId);
            final Future<CredentialsResult<JsonObject>> result = Future.future();
            removeAll(tenantId, deviceId, result.completer());
            return result.map(res -> {
                return request.getResponse(res.getStatus()).setDeviceId(deviceId).setCacheDirective(res.getCacheDirective());
            });
        } else {
            log.debug("remove credentials request contains invalid search criteria [type: {}, device-id: {}, auth-id: {}]", type, deviceId, authId);
            return Future.failedFuture(new ClientErrorException(HttpURLConnection.HTTP_BAD_REQUEST));
        }
    }
}
Also used : HttpURLConnection(java.net.HttpURLConnection) CredentialsResult(org.eclipse.hono.util.CredentialsResult) TenantConstants(org.eclipse.hono.util.TenantConstants) ClientErrorException(org.eclipse.hono.client.ClientErrorException) EventBusMessage(org.eclipse.hono.util.EventBusMessage) Future(io.vertx.core.Future) CredentialsConstants(org.eclipse.hono.util.CredentialsConstants) Objects(java.util.Objects) EventBusService(org.eclipse.hono.service.EventBusService) Optional(java.util.Optional) JsonObject(io.vertx.core.json.JsonObject) AsyncResult(io.vertx.core.AsyncResult) Handler(io.vertx.core.Handler) CredentialsObject(org.eclipse.hono.util.CredentialsObject) JsonObject(io.vertx.core.json.JsonObject) ClientErrorException(org.eclipse.hono.client.ClientErrorException) Future(io.vertx.core.Future) CredentialsResult(org.eclipse.hono.util.CredentialsResult)

Aggregations

EventBusMessage (org.eclipse.hono.util.EventBusMessage)32 JsonObject (io.vertx.core.json.JsonObject)28 Future (io.vertx.core.Future)26 Handler (io.vertx.core.Handler)26 HttpURLConnection (java.net.HttpURLConnection)26 AsyncResult (io.vertx.core.AsyncResult)21 ServiceInvocationException (org.eclipse.hono.client.ServiceInvocationException)18 TestContext (io.vertx.ext.unit.TestContext)16 VertxUnitRunner (io.vertx.ext.unit.junit.VertxUnitRunner)16 ServiceConfigProperties (org.eclipse.hono.config.ServiceConfigProperties)16 Test (org.junit.Test)16 Timeout (org.junit.rules.Timeout)16 RunWith (org.junit.runner.RunWith)16 CredentialsConstants (org.eclipse.hono.util.CredentialsConstants)13 CredentialsObject (org.eclipse.hono.util.CredentialsObject)13 CredentialsResult (org.eclipse.hono.util.CredentialsResult)13 BeforeClass (org.junit.BeforeClass)13 Objects (java.util.Objects)12 TenantConstants (org.eclipse.hono.util.TenantConstants)11 ClientErrorException (org.eclipse.hono.client.ClientErrorException)8