Search in sources :

Example 1 with ServerErrorException

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

the class CredentialsApiAuthProviderTest method testAuthenticateFailsWithExceptionReportedByCredentialsClient.

/**
 * Verifies that the auth provider propagates the exception reported by a failed invocation
 * of the credentials service.
 *
 * @param ctx The vert.x test context.
 */
@Test
public void testAuthenticateFailsWithExceptionReportedByCredentialsClient(final TestContext ctx) {
    final ServerErrorException reportedException = new ServerErrorException(503);
    when(credentialsClient.isOpen()).thenReturn(Boolean.TRUE);
    when(credentialsClient.get(anyString(), anyString())).thenReturn(Future.failedFuture(reportedException));
    provider.authenticate(UsernamePasswordCredentials.create("user@TENANT", "pwd", false), ctx.asyncAssertFailure(t -> {
        ctx.assertEquals(t, reportedException);
    }));
}
Also used : HttpURLConnection(java.net.HttpURLConnection) TestContext(io.vertx.ext.unit.TestContext) RunWith(org.junit.runner.RunWith) Vertx(io.vertx.core.Vertx) ServerErrorException(org.eclipse.hono.client.ServerErrorException) Test(org.junit.Test) ClientErrorException(org.eclipse.hono.client.ClientErrorException) VertxUnitRunner(io.vertx.ext.unit.junit.VertxUnitRunner) Future(io.vertx.core.Future) TimeUnit(java.util.concurrent.TimeUnit) Mockito(org.mockito.Mockito) CredentialsClient(org.eclipse.hono.client.CredentialsClient) Rule(org.junit.Rule) Timeout(org.junit.rules.Timeout) JsonObject(io.vertx.core.json.JsonObject) HonoClient(org.eclipse.hono.client.HonoClient) Before(org.junit.Before) ServerErrorException(org.eclipse.hono.client.ServerErrorException) Test(org.junit.Test)

Example 2 with ServerErrorException

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

the class HonoAuthHandlerImplTest method testHandleFailsWithStatusCodeFromAuthProvider.

/**
 * Verifies that the handler returns the status code conveyed in a
 * failed @{@code AuthProvider} invocation in the response.
 */
@SuppressWarnings({ "unchecked", "rawtypes" })
@Test
public void testHandleFailsWithStatusCodeFromAuthProvider() {
    // GIVEN an auth handler configured with an auth provider that
    // fails with a 503 error code during authentication
    final int EXPECTED_ERROR_CODE = 503;
    doAnswer(invocation -> {
        Handler handler = invocation.getArgument(1);
        handler.handle(Future.failedFuture(new ServerErrorException(EXPECTED_ERROR_CODE)));
        return null;
    }).when(authProvider).authenticate(any(JsonObject.class), any(Handler.class));
    // WHEN trying to authenticate a request using the HTTP BASIC scheme
    final String authorization = new StringBuffer().append("BASIC ").append(Base64.getEncoder().encodeToString("user:password".getBytes(StandardCharsets.UTF_8))).toString();
    MultiMap headers = mock(MultiMap.class);
    when(headers.get(eq(HttpHeaders.AUTHORIZATION))).thenReturn(authorization);
    HttpServerRequest req = mock(HttpServerRequest.class);
    when(req.headers()).thenReturn(headers);
    HttpServerResponse resp = mock(HttpServerResponse.class);
    RoutingContext ctx = mock(RoutingContext.class);
    when(ctx.request()).thenReturn(req);
    when(ctx.response()).thenReturn(resp);
    authHandler.handle(ctx);
    // THEN the request context is failed with the 503 error code
    ArgumentCaptor<Throwable> failureCaptor = ArgumentCaptor.forClass(Throwable.class);
    verify(ctx).fail(failureCaptor.capture());
    ServerErrorException ex = (ServerErrorException) failureCaptor.getValue();
    assertThat(ex.getErrorCode(), is(EXPECTED_ERROR_CODE));
}
Also used : MultiMap(io.vertx.core.MultiMap) RoutingContext(io.vertx.ext.web.RoutingContext) HttpServerRequest(io.vertx.core.http.HttpServerRequest) HttpServerResponse(io.vertx.core.http.HttpServerResponse) Handler(io.vertx.core.Handler) JsonObject(io.vertx.core.json.JsonObject) ServerErrorException(org.eclipse.hono.client.ServerErrorException) Test(org.junit.Test)

Example 3 with ServerErrorException

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

the class AbstractRequestResponseClient method createAndSendRequest.

/**
 * Creates a request message for a payload and headers and sends it to the peer.
 * <p>
 * This method first checks if the sender has any credit left. If not, the result handler is failed immediately.
 * Otherwise, the request message is sent and a timer is started which fails the result handler,
 * if no response is received within <em>requestTimeout</em> milliseconds.
 *
 * @param action The operation that the request is supposed to trigger/invoke.
 * @param properties The headers to include in the request message as AMQP application properties.
 * @param payload The payload to include in the request message as a an AMQP Value section.
 * @param resultHandler The handler to notify about the outcome of the request. The handler is failed with
 *                      a {@link ServerErrorException} if the request cannot be sent to the remote service,
 *                      e.g. because there is no connection to the service or there are no credits available
 *                      for sending the request or the request timed out.
 * @param cacheKey The key to use for caching the response (if the service allows caching).
 * @throws NullPointerException if action or result handler are {@code null}.
 * @throws IllegalArgumentException if the properties contain any non-primitive typed values.
 * @see AbstractHonoClient#setApplicationProperties(Message, Map)
 */
protected final void createAndSendRequest(final String action, final Map<String, Object> properties, final JsonObject payload, final Handler<AsyncResult<R>> resultHandler, final Object cacheKey) {
    Objects.requireNonNull(action);
    Objects.requireNonNull(resultHandler);
    if (isOpen()) {
        final Message request = createMessage(action, properties);
        if (payload != null) {
            request.setContentType(RequestResponseApiConstants.CONTENT_TYPE_APPLICATION_JSON);
            request.setBody(new AmqpValue(payload.encode()));
        }
        sendRequest(request, resultHandler, cacheKey);
    } else {
        resultHandler.handle(Future.failedFuture(new ServerErrorException(HttpURLConnection.HTTP_UNAVAILABLE, "sender and/or receiver link is not open")));
    }
}
Also used : Message(org.apache.qpid.proton.message.Message) ServerErrorException(org.eclipse.hono.client.ServerErrorException) AmqpValue(org.apache.qpid.proton.amqp.messaging.AmqpValue)

Example 4 with ServerErrorException

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

the class AbstractSender method send.

@Override
public final Future<ProtonDelivery> send(final Message rawMessage) {
    Objects.requireNonNull(rawMessage);
    final Future<ProtonDelivery> result = Future.future();
    context.runOnContext(send -> {
        if (sender.sendQueueFull()) {
            result.fail(new ServerErrorException(HttpURLConnection.HTTP_UNAVAILABLE, "no credit available"));
        } else {
            sendMessage(rawMessage).setHandler(result.completer());
        }
    });
    return result;
}
Also used : ProtonDelivery(io.vertx.proton.ProtonDelivery) ServerErrorException(org.eclipse.hono.client.ServerErrorException)

Example 5 with ServerErrorException

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

the class EventSenderImpl method sendMessage.

@Override
protected Future<ProtonDelivery> sendMessage(final Message message) {
    Objects.requireNonNull(message);
    final Future<ProtonDelivery> result = Future.future();
    final String messageId = String.format("%s-%d", getClass().getSimpleName(), MESSAGE_COUNTER.getAndIncrement());
    message.setMessageId(messageId);
    sender.send(message, deliveryUpdated -> {
        if (deliveryUpdated.remotelySettled()) {
            if (Accepted.class.isInstance(deliveryUpdated.getRemoteState())) {
                LOG.trace("event [message ID: {}] accepted by peer", messageId);
                result.complete(deliveryUpdated);
            } else if (Rejected.class.isInstance(deliveryUpdated.getRemoteState())) {
                Rejected rejected = (Rejected) deliveryUpdated.getRemoteState();
                if (rejected.getError() == null) {
                    LOG.debug("event [message ID: {}] rejected by peer", messageId);
                    result.fail(new ClientErrorException(HttpURLConnection.HTTP_BAD_REQUEST));
                } else {
                    LOG.debug("event [message ID: {}] rejected by peer: {}, {}", messageId, rejected.getError().getCondition(), rejected.getError().getDescription());
                    result.fail(new ClientErrorException(HttpURLConnection.HTTP_BAD_REQUEST, rejected.getError().getDescription()));
                }
            } else {
                LOG.debug("event [message ID: {}] not accepted by peer: {}", messageId, deliveryUpdated.getRemoteState());
                result.fail(new ClientErrorException(HttpURLConnection.HTTP_BAD_REQUEST));
            }
        } else {
            LOG.warn("peer did not settle event, failing delivery [new remote state: {}]", deliveryUpdated.getRemoteState());
            result.fail(new ServerErrorException(HttpURLConnection.HTTP_INTERNAL_ERROR));
        }
    });
    LOG.trace("sent event [ID: {}], remaining credit: {}, queued messages: {}", messageId, sender.getCredit(), sender.getQueued());
    return result;
}
Also used : ProtonDelivery(io.vertx.proton.ProtonDelivery) ClientErrorException(org.eclipse.hono.client.ClientErrorException) Rejected(org.apache.qpid.proton.amqp.messaging.Rejected) ServerErrorException(org.eclipse.hono.client.ServerErrorException)

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