Search in sources :

Example 6 with ServiceInvocationException

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

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

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

the class BaseCredentialsServiceTest method testGetFailsForMissingType.

/**
 * Verifies that the base service fails a request for getting credentials
 * with a 400 error code if the type is missing.
 *
 * @param ctx The vert.x test context.
 */
@Test
public void testGetFailsForMissingType(final TestContext ctx) {
    // GIVEN a request for getting credentials that does not specify a type
    final CredentialsObject malformedPayload = new CredentialsObject().setAuthId("bumlux").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)

Example 9 with ServiceInvocationException

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

the class CrudHttpClient method get.

/**
 * Retrieves a resource representation using HTTP GET.
 *
 * @param uri The resource to retrieve.
 * @param successPredicate A predicate on the returned HTTP status code for determining success.
 * @return A future that will succeed if the predicate evaluates to {@code true}. In that case the
 *         future will contain the response body.
 */
public Future<Buffer> get(final String uri, final Predicate<Integer> successPredicate) {
    final Future<Buffer> result = Future.future();
    vertx.createHttpClient().get(port, host, uri).handler(response -> {
        if (successPredicate.test(response.statusCode())) {
            response.bodyHandler(body -> result.complete(body));
        } else {
            result.fail(new ServiceInvocationException(response.statusCode()));
        }
    }).exceptionHandler(result::fail).end();
    return result;
}
Also used : Buffer(io.vertx.core.buffer.Buffer) ServiceInvocationException(org.eclipse.hono.client.ServiceInvocationException)

Example 10 with ServiceInvocationException

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

the class DeviceRegistryHttpClient method registerDevice.

/**
 * Adds registration information for a device.
 * <p>
 * The device will be enabled by default if not specified otherwise
 * in the additional data.
 *
 * @param tenantId The tenant that the device belongs to.
 * @param deviceId The identifier of the device.
 * @param data Additional properties to register with the device.
 * @param contentType The content type to set on the request.
 * @param expectedStatus The status code indicating a successful outcome.
 * @return A future indicating the outcome of the operation.
 *         The future will succeed if the response contained the expected status code.
 *         Otherwise the future will fail with a {@link ServiceInvocationException}.
 * @throws NullPointerException if the tenant is {@code null}.
 */
public Future<Void> registerDevice(final String tenantId, final String deviceId, final JsonObject data, final String contentType, int expectedStatus) {
    Objects.requireNonNull(tenantId);
    final JsonObject requestJson = Optional.ofNullable(data).map(json -> json.copy()).orElse(null);
    if (deviceId != null && requestJson != null) {
        requestJson.put(RegistrationConstants.FIELD_PAYLOAD_DEVICE_ID, deviceId);
    }
    final String uri = String.format("/%s/%s", RegistrationConstants.REGISTRATION_ENDPOINT, tenantId);
    return httpClient.create(uri, requestJson, contentType, response -> response.statusCode() == expectedStatus);
}
Also used : HttpURLConnection(java.net.HttpURLConnection) TenantConstants(org.eclipse.hono.util.TenantConstants) Vertx(io.vertx.core.Vertx) RegistrationConstants(org.eclipse.hono.util.RegistrationConstants) ServiceInvocationException(org.eclipse.hono.client.ServiceInvocationException) Future(io.vertx.core.Future) CredentialsConstants(org.eclipse.hono.util.CredentialsConstants) TenantObject(org.eclipse.hono.util.TenantObject) Objects(java.util.Objects) Buffer(io.vertx.core.buffer.Buffer) Optional(java.util.Optional) JsonObject(io.vertx.core.json.JsonObject) CredentialsObject(org.eclipse.hono.util.CredentialsObject) JsonObject(io.vertx.core.json.JsonObject)

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