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