use of org.alfresco.repo.rendition2.RenditionDefinition2.TIMEOUT in project hono by eclipse.
the class HttpTestBase method testUploadFailsForCredentialsWithNonExistingTenant.
/**
* Verifies that the adapter fails to authenticate a device that is providing
* credentials that contain a non-existing tenant.
*
* @param ctx The vert.x test context.
* @throws InterruptedException if the test fails.
*/
@Test
@Timeout(timeUnit = TimeUnit.SECONDS, value = 20)
public void testUploadFailsForCredentialsWithNonExistingTenant(final VertxTestContext ctx) throws InterruptedException {
final VertxTestContext setup = new VertxTestContext();
final Tenant tenant = new Tenant();
final MultiMap requestHeaders = MultiMap.caseInsensitiveMultiMap().add(HttpHeaders.CONTENT_TYPE, "text/plain").add(HttpHeaders.AUTHORIZATION, getBasicAuth("nonExistingTenant", deviceId, PWD)).add(HttpHeaders.ORIGIN, ORIGIN_URI);
// GIVEN a device
helper.registry.addDeviceForTenant(tenantId, tenant, deviceId, PWD).onComplete(setup.succeedingThenComplete());
assertThat(setup.awaitCompletion(5, TimeUnit.SECONDS)).isTrue();
if (setup.failed()) {
ctx.failNow(setup.causeOfFailure());
return;
}
// WHEN a device tries to upload data and authenticate using wrong credentials
httpClient.create(getEndpointUri(), Buffer.buffer("hello"), requestHeaders, ResponsePredicate.status(HttpURLConnection.HTTP_UNAUTHORIZED)).onComplete(ctx.succeedingThenComplete());
}
use of org.alfresco.repo.rendition2.RenditionDefinition2.TIMEOUT in project hono by eclipse.
the class HttpTestBase method testUploadMessageFailsForDisabledTenant.
/**
* Verifies that the HTTP adapter rejects messages from a device that belongs to a tenant for which the HTTP adapter
* has been disabled with a 403.
*
* @param ctx The test context
*/
@Test
@Timeout(timeUnit = TimeUnit.SECONDS, value = 20)
public void testUploadMessageFailsForDisabledTenant(final VertxTestContext ctx) {
// GIVEN a tenant for which the HTTP adapter is disabled
final Tenant tenant = new Tenant();
tenant.addAdapterConfig(new Adapter(Constants.PROTOCOL_ADAPTER_TYPE_HTTP).setEnabled(false));
helper.registry.addDeviceForTenant(tenantId, tenant, deviceId, PWD).compose(ok -> {
// WHEN a device that belongs to the tenant uploads a message
final MultiMap requestHeaders = MultiMap.caseInsensitiveMultiMap().add(HttpHeaders.CONTENT_TYPE, "text/plain").add(HttpHeaders.AUTHORIZATION, authorization);
return httpClient.create(getEndpointUri(), Buffer.buffer("hello"), requestHeaders, ResponsePredicate.status(HttpURLConnection.HTTP_FORBIDDEN));
}).onComplete(ctx.succeedingThenComplete());
}
use of org.alfresco.repo.rendition2.RenditionDefinition2.TIMEOUT in project hono by eclipse.
the class HttpTestBase method testUploadMessageFailsForUnauthorizedGateway.
/**
* Verifies that the HTTP adapter rejects messages from a gateway for an device that it is not authorized for with a
* 403.
*
* @param ctx The test context
*/
@Test
@Timeout(timeUnit = TimeUnit.SECONDS, value = 20)
public void testUploadMessageFailsForUnauthorizedGateway(final VertxTestContext ctx) {
// GIVEN a device that is connected via gateway "not-the-created-gateway"
final Tenant tenant = new Tenant();
final String gatewayId = helper.getRandomDeviceId(tenantId);
final Device deviceData = new Device();
deviceData.setVia(Collections.singletonList("not-the-created-gateway"));
helper.registry.addDeviceForTenant(tenantId, tenant, gatewayId, PWD).compose(ok -> helper.registry.registerDevice(tenantId, deviceId, deviceData)).compose(ok -> {
// WHEN another gateway tries to upload a message for the device
final MultiMap requestHeaders = MultiMap.caseInsensitiveMultiMap().add(HttpHeaders.CONTENT_TYPE, "text/plain").add(HttpHeaders.AUTHORIZATION, getBasicAuth(tenantId, gatewayId, PWD));
return httpClient.update(String.format("%s/%s/%s", getEndpointUri(), tenantId, deviceId), Buffer.buffer("hello"), requestHeaders, ResponsePredicate.status(HttpURLConnection.HTTP_FORBIDDEN));
}).onComplete(ctx.succeedingThenComplete());
}
use of org.alfresco.repo.rendition2.RenditionDefinition2.TIMEOUT in project hono by eclipse.
the class HttpTestBase method testHandleConcurrentUploadWithTtd.
/**
* Verifies that for two consecutive upload requests containing a TTD, sent in close succession so that the command
* triggered by the first request isn't sent before the adapter has received the second upload request, the HTTP
* adapter returns the command as response to the second upload request.
*
* @param ctx The test context.
* @throws InterruptedException if the test is interrupted before having completed.
*/
@Test
@Timeout(timeUnit = TimeUnit.SECONDS, value = 20)
public void testHandleConcurrentUploadWithTtd(final VertxTestContext ctx) throws InterruptedException {
final Tenant tenant = new Tenant();
final CountDownLatch firstMessageReceived = new CountDownLatch(1);
final CountDownLatch secondMessageReceived = new CountDownLatch(1);
// GIVEN a registered device
final VertxTestContext setup = new VertxTestContext();
helper.registry.addDeviceForTenant(tenantId, tenant, deviceId, PWD).compose(ok -> createConsumer(tenantId, msg -> {
logger.trace("received message: {}", msg);
msg.getTimeUntilDisconnectNotification().ifPresent(notification -> {
logger.debug("processing piggy backed message [ttd: {}]", notification.getTtd());
ctx.verify(() -> {
assertThat(notification.getTenantId()).isEqualTo(tenantId);
assertThat(notification.getDeviceId()).isEqualTo(deviceId);
});
});
switch(msg.getContentType()) {
case "text/msg1":
logger.debug("received first message");
firstMessageReceived.countDown();
break;
case "text/msg2":
logger.debug("received second message");
secondMessageReceived.countDown();
break;
default:
}
})).compose(c -> {
// might fail immediately because the link has not been established yet.
return httpClient.create(getEndpointUri(), Buffer.buffer("trigger msg"), MultiMap.caseInsensitiveMultiMap().add(HttpHeaders.CONTENT_TYPE, "application/trigger").add(HttpHeaders.AUTHORIZATION, authorization).add(HttpHeaders.ORIGIN, ORIGIN_URI).add(Constants.HEADER_QOS_LEVEL, "1"), ResponsePredicate.status(200, 300));
}).onComplete(setup.succeedingThenComplete());
assertThat(setup.awaitCompletion(5, TimeUnit.SECONDS)).isTrue();
if (setup.failed()) {
ctx.failNow(setup.causeOfFailure());
return;
}
// WHEN the device sends a first upload request
MultiMap requestHeaders = MultiMap.caseInsensitiveMultiMap().add(HttpHeaders.CONTENT_TYPE, "text/msg1").add(HttpHeaders.AUTHORIZATION, authorization).add(HttpHeaders.ORIGIN, ORIGIN_URI).add(Constants.HEADER_TIME_TILL_DISCONNECT, "10");
final Future<HttpResponse<Buffer>> firstRequest = httpClient.create(getEndpointUri(), Buffer.buffer("hello one"), requestHeaders, ResponsePredicate.status(200, 300)).map(httpResponse -> {
logger.info("received response to first request");
return httpResponse;
});
logger.info("sent first request");
if (!firstMessageReceived.await(5, TimeUnit.SECONDS)) {
ctx.failNow(new IllegalStateException("first message not received in time"));
}
// followed by a second request
requestHeaders = MultiMap.caseInsensitiveMultiMap().add(HttpHeaders.CONTENT_TYPE, "text/msg2").add(HttpHeaders.AUTHORIZATION, authorization).add(HttpHeaders.ORIGIN, ORIGIN_URI).add(Constants.HEADER_TIME_TILL_DISCONNECT, "5");
final Future<HttpResponse<Buffer>> secondRequest = httpClient.create(getEndpointUri(), Buffer.buffer("hello two"), requestHeaders, ResponsePredicate.status(200, 300)).map(httpResponse -> {
logger.info("received response to second request");
return httpResponse;
});
logger.info("sent second request");
// wait for messages having been received
if (!secondMessageReceived.await(5, TimeUnit.SECONDS)) {
ctx.failNow(new IllegalStateException("second message not received in time"));
}
// send command
final JsonObject inputData = new JsonObject().put(COMMAND_JSON_KEY, (int) (Math.random() * 100));
final Future<Void> commandSent = helper.sendOneWayCommand(tenantId, deviceId, COMMAND_TO_SEND, "application/json", inputData.toBuffer(), 3000);
logger.info("sent one-way command to device");
// THEN both requests succeed
CompositeFuture.all(commandSent, firstRequest, secondRequest).onComplete(ctx.succeeding(ok -> {
ctx.verify(() -> {
// and the response to the second request contains a command
assertThat(secondRequest.result().getHeader(Constants.HEADER_COMMAND)).isEqualTo(COMMAND_TO_SEND);
// while the response to the first request is empty
assertThat(firstRequest.result().getHeader(Constants.HEADER_COMMAND)).isNull();
});
ctx.completeNow();
}));
}
use of org.alfresco.repo.rendition2.RenditionDefinition2.TIMEOUT in project hono by eclipse.
the class CommandAndControlMqttIT method testSendCommandViaKafkaFailsForMalformedMessage.
/**
* Verifies that the adapter rejects malformed command messages sent by applications.
* <p>
* This test is applicable only if the messaging network type is Kafka.
*
* @param endpointConfig The endpoints to use for sending/receiving commands.
* @param ctx The vert.x test context.
* @throws InterruptedException if not all commands and responses are exchanged in time.
*/
@ParameterizedTest(name = IntegrationTestSupport.PARAMETERIZED_TEST_NAME_PATTERN)
@MethodSource("allCombinations")
@Timeout(timeUnit = TimeUnit.SECONDS, value = 20)
@AssumeMessagingSystem(type = MessagingType.kafka)
public void testSendCommandViaKafkaFailsForMalformedMessage(final MqttCommandEndpointConfiguration endpointConfig, final VertxTestContext ctx) throws InterruptedException {
final String commandTargetDeviceId = endpointConfig.isSubscribeAsGateway() ? helper.setupGatewayDeviceBlocking(tenantId, deviceId, 5) : deviceId;
final AtomicReference<GenericKafkaSender> kafkaSenderRef = new AtomicReference<>();
final CountDownLatch expectedCommandResponses = new CountDownLatch(1);
final VertxTestContext setup = new VertxTestContext();
final Checkpoint ready = setup.checkpoint(2);
final Future<MessageConsumer> kafkaAsyncErrorResponseConsumer = helper.createDeliveryFailureCommandResponseConsumer(ctx, tenantId, HttpURLConnection.HTTP_BAD_REQUEST, response -> expectedCommandResponses.countDown(), null);
createConsumer(tenantId, msg -> {
// expect empty notification with TTD -1
setup.verify(() -> assertThat(msg.getContentType()).isEqualTo(EventConstants.CONTENT_TYPE_EMPTY_NOTIFICATION));
final TimeUntilDisconnectNotification notification = msg.getTimeUntilDisconnectNotification().orElse(null);
LOGGER.info("received notification [{}]", notification);
if (notification.getTtd() == -1) {
ready.flag();
}
}).compose(consumer -> helper.registry.addDeviceToTenant(tenantId, deviceId, password)).compose(ok -> connectToAdapter(IntegrationTestSupport.getUsername(deviceId, tenantId), password)).compose(conAck -> subscribeToCommands(commandTargetDeviceId, msg -> {
// all commands should get rejected because they fail to pass the validity check
ctx.failNow(new IllegalStateException("should not have received command"));
}, endpointConfig, MqttQoS.AT_MOST_ONCE)).compose(ok -> helper.createGenericKafkaSender().onSuccess(kafkaSenderRef::set).mapEmpty()).compose(ok -> kafkaAsyncErrorResponseConsumer).onComplete(setup.succeeding(v -> ready.flag()));
assertWithMessage("setup of adapter finished within %s seconds", IntegrationTestSupport.getTestSetupTimeout()).that(setup.awaitCompletion(IntegrationTestSupport.getTestSetupTimeout(), TimeUnit.SECONDS)).isTrue();
if (setup.failed()) {
ctx.failNow(setup.causeOfFailure());
return;
}
final String commandTopic = new HonoTopic(HonoTopic.Type.COMMAND, tenantId).toString();
LOGGER.debug("sending command message lacking subject and correlation ID - no failure response expected here");
final Map<String, Object> properties1 = Map.of(MessageHelper.APP_PROPERTY_DEVICE_ID, deviceId, MessageHelper.SYS_PROPERTY_CONTENT_TYPE, MessageHelper.CONTENT_TYPE_OCTET_STREAM, KafkaRecordHelper.HEADER_RESPONSE_REQUIRED, true);
kafkaSenderRef.get().sendAndWaitForOutcome(commandTopic, tenantId, deviceId, Buffer.buffer(), properties1).onComplete(ctx.succeeding(ok -> {
}));
LOGGER.debug("sending command message lacking subject");
final String correlationId = "1";
final Map<String, Object> properties2 = Map.of(MessageHelper.SYS_PROPERTY_CORRELATION_ID, correlationId, MessageHelper.APP_PROPERTY_DEVICE_ID, deviceId, MessageHelper.SYS_PROPERTY_CONTENT_TYPE, MessageHelper.CONTENT_TYPE_OCTET_STREAM, KafkaRecordHelper.HEADER_RESPONSE_REQUIRED, true);
kafkaSenderRef.get().sendAndWaitForOutcome(commandTopic, tenantId, deviceId, Buffer.buffer(), properties2).onComplete(ctx.succeeding(ok -> {
}));
final long timeToWait = 2500;
if (!expectedCommandResponses.await(timeToWait, TimeUnit.MILLISECONDS)) {
LOGGER.info("Timeout of {} milliseconds reached, stop waiting for command response", timeToWait);
}
kafkaAsyncErrorResponseConsumer.result().close().onComplete(ar -> {
if (expectedCommandResponses.getCount() == 0) {
ctx.completeNow();
} else {
ctx.failNow(new java.lang.IllegalStateException("did not receive command response"));
}
});
}
Aggregations