use of io.vertx.core.Handler in project vertx-proton by vert-x3.
the class ProtonServerImplTest method doTestAsyncServerAuthenticatorTestImpl.
private void doTestAsyncServerAuthenticatorTestImpl(TestContext context, boolean passAuthentication) {
Async connectAsync = context.async();
AtomicBoolean connectedServer = new AtomicBoolean();
final long delay = 750;
TestAsyncAuthenticator testAsyncAuthenticator = new TestAsyncAuthenticator(delay, passAuthentication);
TestAsyncAuthenticatorFactory authenticatorFactory = new TestAsyncAuthenticatorFactory(testAsyncAuthenticator);
ProtonServer.create(vertx).saslAuthenticatorFactory(authenticatorFactory).connectHandler(protonConnection -> {
connectedServer.set(true);
}).listen(server -> {
final long startTime = System.currentTimeMillis();
ProtonClient.create(vertx).connect("localhost", server.result().actualPort(), GOOD_USER, PASSWD, conResult -> {
// Verify the process took expected time from auth delay.
long actual = System.currentTimeMillis() - startTime;
context.assertTrue(actual >= delay, "Connect completed before expected time delay elapsed! " + actual);
if (passAuthentication) {
context.assertTrue(conResult.succeeded(), "Expected connect to succeed");
conResult.result().disconnect();
} else {
context.assertFalse(conResult.succeeded(), "Expected connect to fail");
}
connectAsync.complete();
});
});
connectAsync.awaitSuccess();
if (passAuthentication) {
context.assertTrue(connectedServer.get(), "Server handler should have been called");
} else {
context.assertFalse(connectedServer.get(), "Server handler should not have been called");
}
context.assertEquals(1, authenticatorFactory.getCreateCount(), "unexpected authenticator creation count");
}
use of io.vertx.core.Handler in project vertx-proton by vert-x3.
the class ProtonReceiverImpl method setDrainHandlerAndTimeoutTask.
private void setDrainHandlerAndTimeoutTask(long delay, Handler<AsyncResult<Void>> completionHandler) {
drainCompleteHandler = completionHandler;
if (delay > 0) {
Vertx vertx = Vertx.currentContext().owner();
drainTimeoutTaskId = vertx.setTimer(delay, x -> {
drainTimeoutTaskId = null;
drainCompleteHandler = null;
completionHandler.handle(Future.failedFuture("Drain attempt timed out"));
});
}
}
use of io.vertx.core.Handler in project hono by eclipse.
the class AbstractVertxBasedMqttProtocolAdapterTest method testAuthenticatedMqttAdapterCreatesMessageHandlersForAuthenticatedDevices.
/**
* Verifies that on successful authentication the adapter sets appropriate message and close
* handlers on the client endpoint.
*/
@SuppressWarnings({ "unchecked" })
@Test
public void testAuthenticatedMqttAdapterCreatesMessageHandlersForAuthenticatedDevices() {
// GIVEN an adapter
final MqttServer server = getMqttServer(false);
final AbstractVertxBasedMqttProtocolAdapter<ProtocolAdapterProperties> adapter = getAdapter(server);
forceClientMocksToConnected();
doAnswer(invocation -> {
Handler<AsyncResult<Device>> resultHandler = invocation.getArgument(1);
resultHandler.handle(Future.succeededFuture(new Device("DEFAULT_TENANT", "4711")));
return null;
}).when(credentialsAuthProvider).authenticate(any(DeviceCredentials.class), any(Handler.class));
// WHEN a device tries to connect with valid credentials
final MqttEndpoint endpoint = getMqttEndpointAuthenticated();
adapter.handleEndpointConnection(endpoint);
// THEN the device's logical ID is successfully established and corresponding handlers
// are registered
final ArgumentCaptor<DeviceCredentials> credentialsCaptor = ArgumentCaptor.forClass(DeviceCredentials.class);
verify(credentialsAuthProvider).authenticate(credentialsCaptor.capture(), any(Handler.class));
assertThat(credentialsCaptor.getValue().getAuthId(), is("sensor1"));
verify(endpoint).accept(false);
verify(endpoint).publishHandler(any(Handler.class));
verify(endpoint).closeHandler(any(Handler.class));
}
use of io.vertx.core.Handler in project hono by eclipse.
the class AbstractVertxBasedMqttProtocolAdapterTest method getMqttServer.
@SuppressWarnings("unchecked")
private static MqttServer getMqttServer(final boolean startupShouldFail) {
final MqttServer server = mock(MqttServer.class);
when(server.actualPort()).thenReturn(0, 1883);
when(server.endpointHandler(any(Handler.class))).thenReturn(server);
when(server.listen(any(Handler.class))).then(invocation -> {
Handler<AsyncResult<MqttServer>> handler = (Handler<AsyncResult<MqttServer>>) invocation.getArgument(0);
if (startupShouldFail) {
handler.handle(Future.failedFuture("MQTT server intentionally failed to start"));
} else {
handler.handle(Future.succeededFuture(server));
}
return server;
});
return server;
}
use of io.vertx.core.Handler in project hono by eclipse.
the class AbstractRequestResponseClient method sendRequest.
/**
* Sends a request message via this client's sender link 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>requestTimeoutMillis</em> milliseconds.
*
* @param request The message to send.
* @param resultHandler The handler to notify about the outcome of the request.
* @param cacheKey The key to use for caching the response (if the service allows caching).
*/
private final void sendRequest(final Message request, final Handler<AsyncResult<R>> resultHandler, final Object cacheKey) {
context.runOnContext(req -> {
if (sender.sendQueueFull()) {
LOG.debug("cannot send request to peer, no credit left for link [target: {}]", targetAddress);
resultHandler.handle(Future.failedFuture(new ServerErrorException(HttpURLConnection.HTTP_UNAVAILABLE, "no credit available for sending request")));
} else {
final Object correlationId = Optional.ofNullable(request.getCorrelationId()).orElse(request.getMessageId());
final TriTuple<Handler<AsyncResult<R>>, Object, Object> handler = TriTuple.of(resultHandler, cacheKey, null);
replyMap.put(correlationId, handler);
sender.send(request, deliveryUpdated -> {
if (Rejected.class.isInstance(deliveryUpdated.getRemoteState())) {
final Rejected rejected = (Rejected) deliveryUpdated.getRemoteState();
if (rejected.getError() != null) {
LOG.debug("service did not accept request [target address: {}, subject: {}, correlation ID: {}]: {}", targetAddress, request.getSubject(), correlationId, rejected.getError());
cancelRequest(correlationId, Future.failedFuture(StatusCodeMapper.from(rejected.getError())));
} else {
LOG.debug("service did not accept request [target address: {}, subject: {}, correlation ID: {}]", targetAddress, request.getSubject(), correlationId);
cancelRequest(correlationId, Future.failedFuture(new ClientErrorException(HttpURLConnection.HTTP_BAD_REQUEST)));
}
} else if (Accepted.class.isInstance(deliveryUpdated.getRemoteState())) {
LOG.trace("service has accepted request [target address: {}, subject: {}, correlation ID: {}]", targetAddress, request.getSubject(), correlationId);
} else {
LOG.debug("service did not accept request [target address: {}, subject: {}, correlation ID: {}]: {}", targetAddress, request.getSubject(), correlationId, deliveryUpdated.getRemoteState());
cancelRequest(correlationId, Future.failedFuture(new ServerErrorException(HttpURLConnection.HTTP_UNAVAILABLE)));
}
});
if (requestTimeoutMillis > 0) {
context.owner().setTimer(requestTimeoutMillis, tid -> {
cancelRequest(correlationId, Future.failedFuture(new ServerErrorException(HttpURLConnection.HTTP_UNAVAILABLE, "request timed out after " + requestTimeoutMillis + "ms")));
});
}
if (LOG.isDebugEnabled()) {
final String deviceId = MessageHelper.getDeviceId(request);
if (deviceId == null) {
LOG.debug("sent request [target address: {}, subject: {}, correlation ID: {}] to service", targetAddress, request.getSubject(), correlationId);
} else {
LOG.debug("sent request [target address: {}, subject: {}, correlation ID: {}, device ID: {}] to service", targetAddress, request.getSubject(), correlationId, deviceId);
}
}
}
});
}
Aggregations