Search in sources :

Example 96 with Promise

use of io.vertx.core.Promise in project hono by eclipse.

the class KafkaClientUnitTestHelper method newKafkaProducer.

/**
 * Returns a new {@link KafkaProducer}.
 *
 * @param producer The mock producer to wrap.
 * @param <K> The type of the key.
 * @param <V> The type of the value.
 * @return The new Kafka producer.
 */
public static <K, V> KafkaProducer<K, V> newKafkaProducer(final MockProducer<K, V> producer) {
    final VertxInternal vertxMock = mock(VertxInternal.class);
    final ContextInternal context = VertxMockSupport.mockContextInternal(vertxMock);
    doAnswer(invocation -> Promise.promise()).when(context).promise();
    doAnswer(invocation -> {
        final Promise<RecordMetadata> result = Promise.promise();
        final Handler<Promise<RecordMetadata>> handler = invocation.getArgument(0);
        handler.handle(result);
        return result.future();
    }).when(context).executeBlocking(VertxMockSupport.anyHandler());
    VertxMockSupport.executeBlockingCodeImmediately(vertxMock, context);
    return KafkaProducer.create(vertxMock, producer);
}
Also used : RecordMetadata(io.vertx.kafka.client.producer.RecordMetadata) Promise(io.vertx.core.Promise) VertxInternal(io.vertx.core.impl.VertxInternal) ContextInternal(io.vertx.core.impl.ContextInternal)

Example 97 with Promise

use of io.vertx.core.Promise in project hono by eclipse.

the class VertxBasedAmqpProtocolAdapter method checkAuthorizationAndResourceLimits.

private Future<Void> checkAuthorizationAndResourceLimits(final Device authenticatedDevice, final ProtonConnection con, final Span span) {
    final Promise<Void> connectAuthorizationCheck = Promise.promise();
    if (getConfig().isAuthenticationRequired()) {
        if (authenticatedDevice == null) {
            connectAuthorizationCheck.fail(new ClientErrorException(HttpURLConnection.HTTP_UNAUTHORIZED, "anonymous devices not supported"));
        } else {
            log.trace("received connection request from {}", authenticatedDevice);
            // the SASL handshake will already have authenticated the device
            // we still need to verify that
            // the adapter is enabled for the tenant,
            // the device/gateway exists and is enabled and
            // that the connection limit for the tenant is not exceeded.
            CompositeFuture.all(checkDeviceRegistration(authenticatedDevice, span.context()), getTenantConfiguration(authenticatedDevice.getTenantId(), span.context()).compose(tenantConfig -> CompositeFuture.all(isAdapterEnabled(tenantConfig), checkConnectionLimit(tenantConfig, span.context())))).map(ok -> {
                log.debug("{} is registered and enabled", authenticatedDevice);
                span.log(String.format("device [%s] is registered and enabled", authenticatedDevice));
                return (Void) null;
            }).onComplete(connectAuthorizationCheck);
        }
    } else {
        log.trace("received connection request from anonymous device [container: {}]", con.getRemoteContainer());
        connectAuthorizationCheck.complete();
    }
    return connectAuthorizationCheck.future();
}
Also used : HttpURLConnection(java.net.HttpURLConnection) ProtonConnection(io.vertx.proton.ProtonConnection) ProtonReceiver(io.vertx.proton.ProtonReceiver) LifecycleChange(org.eclipse.hono.notification.deviceregistry.LifecycleChange) DeviceChangeNotification(org.eclipse.hono.notification.deviceregistry.DeviceChangeNotification) Tags(io.opentracing.tag.Tags) ProtonServer(io.vertx.proton.ProtonServer) HonoProtonHelper(org.eclipse.hono.util.HonoProtonHelper) ProcessingOutcome(org.eclipse.hono.service.metric.MetricsTags.ProcessingOutcome) EndpointType(org.eclipse.hono.service.metric.MetricsTags.EndpointType) Modified(org.apache.qpid.proton.amqp.messaging.Modified) DeviceCredentials(org.eclipse.hono.adapter.auth.device.DeviceCredentials) Map(java.util.Map) DeliveryState(org.apache.qpid.proton.amqp.transport.DeliveryState) AuthorizationException(org.eclipse.hono.adapter.AuthorizationException) ResourceIdentifier(org.eclipse.hono.util.ResourceIdentifier) Fields(io.opentracing.log.Fields) AmqpError(org.apache.qpid.proton.amqp.transport.AmqpError) TracingHelper(org.eclipse.hono.tracing.TracingHelper) ProtonSaslAuthenticatorFactory(io.vertx.proton.sasl.ProtonSaslAuthenticatorFactory) AllDevicesOfTenantDeletedNotification(org.eclipse.hono.notification.deviceregistry.AllDevicesOfTenantDeletedNotification) TenantServiceBasedX509Authentication(org.eclipse.hono.adapter.auth.device.TenantServiceBasedX509Authentication) Predicate(java.util.function.Predicate) Collection(java.util.Collection) CommandContext(org.eclipse.hono.client.command.CommandContext) RegistrationAssertion(org.eclipse.hono.util.RegistrationAssertion) ProtonQoS(io.vertx.proton.ProtonQoS) MessageHelper(org.eclipse.hono.util.MessageHelper) Collectors(java.util.stream.Collectors) Future(io.vertx.core.Future) Device(org.eclipse.hono.auth.Device) Objects(java.util.Objects) ErrorCondition(org.apache.qpid.proton.amqp.transport.ErrorCondition) List(java.util.List) QoS(org.eclipse.hono.service.metric.MetricsTags.QoS) TenantTraceSamplingHelper(org.eclipse.hono.tracing.TenantTraceSamplingHelper) CommandConsumer(org.eclipse.hono.client.command.CommandConsumer) Optional(java.util.Optional) Span(io.opentracing.Span) ProtonSender(io.vertx.proton.ProtonSender) NotificationEventBusSupport(org.eclipse.hono.notification.NotificationEventBusSupport) ProtonLink(io.vertx.proton.ProtonLink) Accepted(org.apache.qpid.proton.amqp.messaging.Accepted) ProtonServerOptions(io.vertx.proton.ProtonServerOptions) Rejected(org.apache.qpid.proton.amqp.messaging.Rejected) ConnectionLimitManager(org.eclipse.hono.adapter.limiting.ConnectionLimitManager) Command(org.eclipse.hono.client.command.Command) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) HashMap(java.util.HashMap) ClientErrorException(org.eclipse.hono.client.ClientErrorException) AdapterDisabledException(org.eclipse.hono.adapter.AdapterDisabledException) ServiceInvocationException(org.eclipse.hono.client.ServiceInvocationException) OptionalInt(java.util.OptionalInt) AtomicReference(java.util.concurrent.atomic.AtomicReference) Function(java.util.function.Function) Commands(org.eclipse.hono.client.command.Commands) Constants(org.eclipse.hono.util.Constants) CompositeFuture(io.vertx.core.CompositeFuture) ProtonSession(io.vertx.proton.ProtonSession) Symbol(org.apache.qpid.proton.amqp.Symbol) AdapterConnectionsExceededException(org.eclipse.hono.adapter.AdapterConnectionsExceededException) Target(org.apache.qpid.proton.amqp.transport.Target) UnsignedLong(org.apache.qpid.proton.amqp.UnsignedLong) Message(org.apache.qpid.proton.message.Message) HttpUtils(org.eclipse.hono.service.http.HttpUtils) AsyncResult(io.vertx.core.AsyncResult) CommandConstants(org.eclipse.hono.util.CommandConstants) TenantChangeNotification(org.eclipse.hono.notification.deviceregistry.TenantChangeNotification) Strings(org.eclipse.hono.util.Strings) UsernamePasswordAuthProvider(org.eclipse.hono.adapter.auth.device.UsernamePasswordAuthProvider) CredentialsApiAuthProvider(org.eclipse.hono.adapter.auth.device.CredentialsApiAuthProvider) AbstractProtocolAdapterBase(org.eclipse.hono.adapter.AbstractProtocolAdapterBase) Direction(org.eclipse.hono.service.metric.MetricsTags.Direction) Promise(io.vertx.core.Promise) ServerErrorException(org.eclipse.hono.client.ServerErrorException) ProtonHelper(io.vertx.proton.ProtonHelper) Sample(io.micrometer.core.instrument.Timer.Sample) Released(org.apache.qpid.proton.amqp.messaging.Released) CommandResponse(org.eclipse.hono.client.command.CommandResponse) TenantObject(org.eclipse.hono.util.TenantObject) SpanContext(io.opentracing.SpanContext) Source(org.apache.qpid.proton.amqp.transport.Source) ConnectionAttemptOutcome(org.eclipse.hono.service.metric.MetricsTags.ConnectionAttemptOutcome) MemoryBasedConnectionLimitStrategy(org.eclipse.hono.adapter.limiting.MemoryBasedConnectionLimitStrategy) X509AuthProvider(org.eclipse.hono.adapter.auth.device.X509AuthProvider) Handler(io.vertx.core.Handler) Collections(java.util.Collections) DefaultConnectionLimitManager(org.eclipse.hono.adapter.limiting.DefaultConnectionLimitManager) ClientErrorException(org.eclipse.hono.client.ClientErrorException)

Example 98 with Promise

use of io.vertx.core.Promise in project hono by eclipse.

the class ConfigBasedCoapEndpointFactory method getSecureEndpoint.

/**
 * {@inheritDoc}
 */
@Override
public Future<Endpoint> getSecureEndpoint() {
    final Promise<Endpoint> result = Promise.promise();
    if (isSecurePortEnabled()) {
        final int securePort = config.getPort(CoAP.DEFAULT_COAP_SECURE_PORT);
        final int insecurePort = config.isInsecurePortEnabled() ? config.getInsecurePort(CoAP.DEFAULT_COAP_PORT) : Constants.PORT_UNCONFIGURED;
        if (config.isInsecurePortEnabled() && insecurePort == securePort) {
            LOG.error("secure and insecure ports must be configured to bind to different port numbers");
            result.fail("secure and insecure ports configured to bind to same port number");
        } else {
            getSecureNetworkConfig().compose(secureNetworkConfig -> createSecureEndpoint(securePort, secureNetworkConfig)).onComplete(result);
        }
    } else if (!config.isInsecurePortEnabled()) {
        result.fail(new IllegalStateException("neither secure nor insecure port configured"));
    } else {
        LOG.info("neither key/cert nor secure port are configured, won't create secure endpoint");
        result.fail(new IllegalStateException("neither key/cert nor secure port are configured"));
    }
    return result.future();
}
Also used : AdvancedPskStore(org.eclipse.californium.scandium.dtls.pskstore.AdvancedPskStore) ObservationStore(org.eclipse.californium.core.observe.ObservationStore) LoggerFactory(org.slf4j.LoggerFactory) KeyLoader(org.eclipse.hono.config.KeyLoader) Constants(org.eclipse.hono.util.Constants) CoapEndpoint(org.eclipse.californium.core.network.CoapEndpoint) Keys(org.eclipse.californium.core.network.config.NetworkConfig.Keys) NetworkConfig(org.eclipse.californium.core.network.config.NetworkConfig) DTLSConnector(org.eclipse.californium.scandium.DTLSConnector) ByteArrayInputStream(java.io.ByteArrayInputStream) DeviceInfoSupplier(org.eclipse.hono.adapter.coap.DeviceInfoSupplier) CoapEndpointFactory(org.eclipse.hono.adapter.coap.CoapEndpointFactory) NewAdvancedCertificateVerifier(org.eclipse.californium.scandium.dtls.x509.NewAdvancedCertificateVerifier) Strings(org.eclipse.hono.util.Strings) DtlsConnectorConfig(org.eclipse.californium.scandium.config.DtlsConnectorConfig) Logger(org.slf4j.Logger) Promise(io.vertx.core.Promise) Vertx(io.vertx.core.Vertx) IOException(java.io.IOException) CoapAdapterProperties(org.eclipse.hono.adapter.coap.CoapAdapterProperties) InetSocketAddress(java.net.InetSocketAddress) Collectors(java.util.stream.Collectors) Future(io.vertx.core.Future) Objects(java.util.Objects) Certificate(java.security.cert.Certificate) MemoryBasedConnectionLimitStrategy(org.eclipse.hono.adapter.limiting.MemoryBasedConnectionLimitStrategy) PrivateKey(java.security.PrivateKey) CoAP(org.eclipse.californium.core.coap.CoAP) Endpoint(org.eclipse.californium.core.network.Endpoint) Optional(java.util.Optional) ApplicationLevelInfoSupplier(org.eclipse.californium.scandium.auth.ApplicationLevelInfoSupplier) InputStream(java.io.InputStream) CoapEndpoint(org.eclipse.californium.core.network.CoapEndpoint) Endpoint(org.eclipse.californium.core.network.Endpoint) CoapEndpoint(org.eclipse.californium.core.network.CoapEndpoint) Endpoint(org.eclipse.californium.core.network.Endpoint)

Example 99 with Promise

use of io.vertx.core.Promise in project hono by eclipse.

the class AbstractVertxBasedCoapAdapterTest method testStartRegistersResources.

/**
 * Verifies that the adapter registers resources as part of the start-up process.
 *
 * @param ctx The helper to use for running async tests on vertx.
 */
@Test
public void testStartRegistersResources(final VertxTestContext ctx) {
    // GIVEN an adapter
    givenAnAdapter(properties);
    // and a set of resources
    final Resource resource = mock(Resource.class);
    adapter.addResources(Set.of(resource));
    // WHEN starting the adapter
    final Promise<Void> startupTracker = Promise.promise();
    startupTracker.future().onComplete(ctx.succeeding(s -> {
        // THEN the resources have been registered with the server
        final ArgumentCaptor<VertxCoapResource> resourceCaptor = ArgumentCaptor.forClass(VertxCoapResource.class);
        ctx.verify(() -> {
            verify(server).add(resourceCaptor.capture());
            assertThat(resourceCaptor.getValue().getWrappedResource()).isEqualTo(resource);
        });
        ctx.completeNow();
    }));
    adapter.start(startupTracker);
}
Also used : ArgumentMatchers.any(org.mockito.ArgumentMatchers.any) VertxTestContext(io.vertx.junit5.VertxTestContext) CoapExchange(org.eclipse.californium.core.server.resources.CoapExchange) BeforeEach(org.junit.jupiter.api.BeforeEach) Exchange(org.eclipse.californium.core.network.Exchange) CoapResource(org.eclipse.californium.core.CoapResource) CoapServer(org.eclipse.californium.core.CoapServer) Constants(org.eclipse.hono.util.Constants) Context(io.vertx.core.Context) Timeout(io.vertx.junit5.Timeout) AfterAll(org.junit.jupiter.api.AfterAll) Mockito.doThrow(org.mockito.Mockito.doThrow) Origin(org.eclipse.californium.core.network.Exchange.Origin) ProtocolAdapterTestSupport(org.eclipse.hono.adapter.test.ProtocolAdapterTestSupport) Resource(org.eclipse.californium.core.server.resources.Resource) ArgumentCaptor(org.mockito.ArgumentCaptor) ExtendWith(org.junit.jupiter.api.extension.ExtendWith) Executor(java.util.concurrent.Executor) Promise(io.vertx.core.Promise) Vertx(io.vertx.core.Vertx) Set(java.util.Set) Mockito.doNothing(org.mockito.Mockito.doNothing) Mockito.when(org.mockito.Mockito.when) Truth.assertThat(com.google.common.truth.Truth.assertThat) VertxExtension(io.vertx.junit5.VertxExtension) Future(io.vertx.core.Future) Mockito.verify(org.mockito.Mockito.verify) TimeUnit(java.util.concurrent.TimeUnit) Test(org.junit.jupiter.api.Test) Mockito.never(org.mockito.Mockito.never) Code(org.eclipse.californium.core.coap.CoAP.Code) Request(org.eclipse.californium.core.coap.Request) CommandConsumer(org.eclipse.hono.client.command.CommandConsumer) VertxMockSupport(org.eclipse.hono.test.VertxMockSupport) Optional(java.util.Optional) ResourceLimitChecks(org.eclipse.hono.adapter.resourcelimits.ResourceLimitChecks) Handler(io.vertx.core.Handler) Mockito.mock(org.mockito.Mockito.mock) ArgumentCaptor(org.mockito.ArgumentCaptor) CoapResource(org.eclipse.californium.core.CoapResource) Resource(org.eclipse.californium.core.server.resources.Resource) Test(org.junit.jupiter.api.Test)

Example 100 with Promise

use of io.vertx.core.Promise in project hono by eclipse.

the class AbstractVertxBasedCoapAdapterTest method testResourcesAreRunOnVertxContext.

/**
 * Verifies that the resources registered with the adapter are always
 * executed on the adapter's vert.x context.
 *
 * @param ctx The helper to use for running async tests on vertx.
 */
@Test
public void testResourcesAreRunOnVertxContext(final VertxTestContext ctx) {
    // GIVEN an adapter
    final Context context = vertx.getOrCreateContext();
    givenAnAdapter(properties);
    // with a resource
    final Promise<Void> resourceInvocation = Promise.promise();
    final Resource resource = new CoapResource("test") {

        @Override
        public void handleGET(final CoapExchange exchange) {
            ctx.verify(() -> assertThat(Vertx.currentContext()).isEqualTo(context));
            resourceInvocation.complete();
        }
    };
    adapter.addResources(Set.of(resource));
    adapter.init(vertx, context);
    final Promise<Void> startupTracker = Promise.promise();
    adapter.start(startupTracker);
    startupTracker.future().compose(ok -> {
        // WHEN the resource receives a GET request
        final Request request = new Request(Code.GET);
        final Exchange getExchange = new Exchange(request, Origin.REMOTE, mock(Executor.class));
        final ArgumentCaptor<VertxCoapResource> resourceCaptor = ArgumentCaptor.forClass(VertxCoapResource.class);
        verify(server).add(resourceCaptor.capture());
        resourceCaptor.getValue().handleRequest(getExchange);
        // THEN the resource's handler has been run on the adapter's vert.x event loop
        return resourceInvocation.future();
    }).onComplete(ctx.succeedingThenComplete());
}
Also used : VertxTestContext(io.vertx.junit5.VertxTestContext) Context(io.vertx.core.Context) ArgumentMatchers.any(org.mockito.ArgumentMatchers.any) VertxTestContext(io.vertx.junit5.VertxTestContext) CoapExchange(org.eclipse.californium.core.server.resources.CoapExchange) BeforeEach(org.junit.jupiter.api.BeforeEach) Exchange(org.eclipse.californium.core.network.Exchange) CoapResource(org.eclipse.californium.core.CoapResource) CoapServer(org.eclipse.californium.core.CoapServer) Constants(org.eclipse.hono.util.Constants) Context(io.vertx.core.Context) Timeout(io.vertx.junit5.Timeout) AfterAll(org.junit.jupiter.api.AfterAll) Mockito.doThrow(org.mockito.Mockito.doThrow) Origin(org.eclipse.californium.core.network.Exchange.Origin) ProtocolAdapterTestSupport(org.eclipse.hono.adapter.test.ProtocolAdapterTestSupport) Resource(org.eclipse.californium.core.server.resources.Resource) ArgumentCaptor(org.mockito.ArgumentCaptor) ExtendWith(org.junit.jupiter.api.extension.ExtendWith) Executor(java.util.concurrent.Executor) Promise(io.vertx.core.Promise) Vertx(io.vertx.core.Vertx) Set(java.util.Set) Mockito.doNothing(org.mockito.Mockito.doNothing) Mockito.when(org.mockito.Mockito.when) Truth.assertThat(com.google.common.truth.Truth.assertThat) VertxExtension(io.vertx.junit5.VertxExtension) Future(io.vertx.core.Future) Mockito.verify(org.mockito.Mockito.verify) TimeUnit(java.util.concurrent.TimeUnit) Test(org.junit.jupiter.api.Test) Mockito.never(org.mockito.Mockito.never) Code(org.eclipse.californium.core.coap.CoAP.Code) Request(org.eclipse.californium.core.coap.Request) CommandConsumer(org.eclipse.hono.client.command.CommandConsumer) VertxMockSupport(org.eclipse.hono.test.VertxMockSupport) Optional(java.util.Optional) ResourceLimitChecks(org.eclipse.hono.adapter.resourcelimits.ResourceLimitChecks) Handler(io.vertx.core.Handler) Mockito.mock(org.mockito.Mockito.mock) CoapExchange(org.eclipse.californium.core.server.resources.CoapExchange) Exchange(org.eclipse.californium.core.network.Exchange) ArgumentCaptor(org.mockito.ArgumentCaptor) CoapResource(org.eclipse.californium.core.CoapResource) Resource(org.eclipse.californium.core.server.resources.Resource) Request(org.eclipse.californium.core.coap.Request) CoapResource(org.eclipse.californium.core.CoapResource) CoapExchange(org.eclipse.californium.core.server.resources.CoapExchange) Test(org.junit.jupiter.api.Test)

Aggregations

Promise (io.vertx.core.Promise)155 Future (io.vertx.core.Future)122 Handler (io.vertx.core.Handler)95 List (java.util.List)86 Vertx (io.vertx.core.Vertx)85 Buffer (io.vertx.core.buffer.Buffer)83 TimeUnit (java.util.concurrent.TimeUnit)79 HttpURLConnection (java.net.HttpURLConnection)66 Logger (org.slf4j.Logger)63 LoggerFactory (org.slf4j.LoggerFactory)63 Optional (java.util.Optional)62 AsyncResult (io.vertx.core.AsyncResult)61 Truth.assertThat (com.google.common.truth.Truth.assertThat)60 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)60 VertxTestContext (io.vertx.junit5.VertxTestContext)59 Test (org.junit.jupiter.api.Test)58 Map (java.util.Map)54 UUID (java.util.UUID)52 ArrayList (java.util.ArrayList)51 JsonObject (io.vertx.core.json.JsonObject)50