Search in sources :

Example 91 with Handler

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");
}
Also used : TestContext(io.vertx.ext.unit.TestContext) ProtonConnection(io.vertx.proton.ProtonConnection) Async(io.vertx.ext.unit.Async) ProtonSaslAuthenticator(io.vertx.proton.sasl.ProtonSaslAuthenticator) Vertx(io.vertx.core.Vertx) RunWith(org.junit.runner.RunWith) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) ProtonClient(io.vertx.proton.ProtonClient) Test(org.junit.Test) VertxUnitRunner(io.vertx.ext.unit.junit.VertxUnitRunner) Sasl(org.apache.qpid.proton.engine.Sasl) SaslOutcome(org.apache.qpid.proton.engine.Sasl.SaslOutcome) Context(io.vertx.core.Context) ProtonServer(io.vertx.proton.ProtonServer) StandardCharsets(java.nio.charset.StandardCharsets) Transport(org.apache.qpid.proton.engine.Transport) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) After(org.junit.After) Handler(io.vertx.core.Handler) ProtonSaslAuthenticatorFactory(io.vertx.proton.sasl.ProtonSaslAuthenticatorFactory) NetSocket(io.vertx.core.net.NetSocket) Before(org.junit.Before) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) Async(io.vertx.ext.unit.Async)

Example 92 with Handler

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"));
        });
    }
}
Also used : ProtonReceiver(io.vertx.proton.ProtonReceiver) Proton(org.apache.qpid.proton.Proton) Delivery(org.apache.qpid.proton.engine.Delivery) ByteArrayOutputStream(java.io.ByteArrayOutputStream) ProtonMessageHandler(io.vertx.proton.ProtonMessageHandler) Vertx(io.vertx.core.Vertx) ProtonHelper.accepted(io.vertx.proton.ProtonHelper.accepted) Receiver(org.apache.qpid.proton.engine.Receiver) Message(org.apache.qpid.proton.message.Message) AsyncResult(io.vertx.core.AsyncResult) Handler(io.vertx.core.Handler) Future(io.vertx.core.Future) Vertx(io.vertx.core.Vertx)

Example 93 with Handler

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));
}
Also used : ProtocolAdapterProperties(org.eclipse.hono.config.ProtocolAdapterProperties) MqttEndpoint(io.vertx.mqtt.MqttEndpoint) Device(org.eclipse.hono.service.auth.device.Device) MqttServer(io.vertx.mqtt.MqttServer) Handler(io.vertx.core.Handler) DeviceCredentials(org.eclipse.hono.service.auth.device.DeviceCredentials) AsyncResult(io.vertx.core.AsyncResult) Test(org.junit.Test)

Example 94 with Handler

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;
}
Also used : MqttServer(io.vertx.mqtt.MqttServer) Handler(io.vertx.core.Handler) AsyncResult(io.vertx.core.AsyncResult)

Example 95 with Handler

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);
                }
            }
        }
    });
}
Also used : Handler(io.vertx.core.Handler) ClientErrorException(org.eclipse.hono.client.ClientErrorException) JsonObject(io.vertx.core.json.JsonObject) ServerErrorException(org.eclipse.hono.client.ServerErrorException) Rejected(org.apache.qpid.proton.amqp.messaging.Rejected) Accepted(org.apache.qpid.proton.amqp.messaging.Accepted)

Aggregations

Handler (io.vertx.core.Handler)119 Test (org.junit.Test)78 Future (io.vertx.core.Future)67 Vertx (io.vertx.core.Vertx)59 AsyncResult (io.vertx.core.AsyncResult)57 Context (io.vertx.core.Context)52 Buffer (io.vertx.core.buffer.Buffer)48 Async (io.vertx.ext.unit.Async)41 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)39 Map (java.util.Map)38 TestContext (io.vertx.ext.unit.TestContext)37 VertxUnitRunner (io.vertx.ext.unit.junit.VertxUnitRunner)36 RunWith (org.junit.runner.RunWith)36 AtomicBoolean (java.util.concurrent.atomic.AtomicBoolean)34 Collections (java.util.Collections)33 JsonObject (io.vertx.core.json.JsonObject)31 HttpURLConnection (java.net.HttpURLConnection)31 Before (org.junit.Before)31 StandardCharsets (java.nio.charset.StandardCharsets)29 TimeUnit (java.util.concurrent.TimeUnit)29