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);
}));
}
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));
}
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")));
}
}
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;
}
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;
}
Aggregations