Search in sources :

Example 1 with BufferSerializer

use of io.vertx.kafka.client.serialization.BufferSerializer in project hono by eclipse.

the class KafkaBasedCommandSenderTest method sendCommandAndReceiveResponse.

private void sendCommandAndReceiveResponse(final VertxTestContext ctx, final String correlationId, final Integer responseStatus, final String responsePayload, final boolean expectSuccess, final int expectedStatusCode) {
    final Context context = vertx.getOrCreateContext();
    final Promise<Void> onProducerRecordSentPromise = Promise.promise();
    mockProducer = new MockProducer<>(true, new StringSerializer(), new BufferSerializer()) {

        @Override
        public synchronized java.util.concurrent.Future<RecordMetadata> send(final ProducerRecord<String, Buffer> record, final Callback callback) {
            return super.send(record, (metadata, exception) -> {
                callback.onCompletion(metadata, exception);
                context.runOnContext(v -> {
                    // decouple from current execution in order to run after the "send" result handler
                    onProducerRecordSentPromise.complete();
                });
            });
        }
    };
    final var producerFactory = CachingKafkaProducerFactory.testFactory(vertx, (n, c) -> KafkaClientUnitTestHelper.newKafkaProducer(mockProducer));
    commandSender = new KafkaBasedCommandSender(vertx, consumerConfig, producerFactory, producerConfig, NoopTracerFactory.create());
    final Map<String, Object> headerProperties = new HashMap<>();
    headerProperties.put("appKey", "appValue");
    final String command = "setVolume";
    final ConsumerRecord<String, Buffer> commandResponseRecord = commandResponseRecord(tenantId, deviceId, correlationId, responseStatus, Buffer.buffer(responsePayload));
    final String responseTopic = new HonoTopic(HonoTopic.Type.COMMAND_RESPONSE, tenantId).toString();
    final TopicPartition responseTopicPartition = new TopicPartition(responseTopic, 0);
    mockConsumer.setRebalancePartitionAssignmentAfterSubscribe(List.of(responseTopicPartition));
    mockConsumer.updatePartitions(responseTopicPartition, KafkaMockConsumer.DEFAULT_NODE);
    mockConsumer.updateBeginningOffsets(Map.of(responseTopicPartition, 0L));
    mockConsumer.updateEndOffsets(Map.of(responseTopicPartition, 0L));
    onProducerRecordSentPromise.future().onComplete(ar -> {
        LOG.debug("producer record sent, add command response record to mockConsumer");
        // Send a command response with the same correlation id as that of the command
        mockConsumer.addRecord(commandResponseRecord);
    });
    // This correlation id is used for both command and its response.
    commandSender.setCorrelationIdSupplier(() -> correlationId);
    commandSender.setKafkaConsumerSupplier(() -> mockConsumer);
    context.runOnContext(v -> {
        // Send a command to the device
        commandSender.sendCommand(tenantId, deviceId, command, "text/plain", Buffer.buffer("test"), headerProperties).onComplete(ar -> {
            ctx.verify(() -> {
                if (expectSuccess) {
                    // assert that send operation succeeded
                    assertThat(ar.succeeded()).isTrue();
                    // Verify the command response that has been received
                    final DownstreamMessage<KafkaMessageContext> response = ar.result();
                    assertThat(response.getDeviceId()).isEqualTo(deviceId);
                    assertThat(response.getStatus()).isEqualTo(responseStatus);
                    assertThat(response.getPayload().toString()).isEqualTo(responsePayload);
                } else {
                    // assert that send operation failed
                    assertThat(ar.succeeded()).isFalse();
                    assertThat(ar.cause()).isInstanceOf(ServiceInvocationException.class);
                    assertThat(((ServiceInvocationException) ar.cause()).getErrorCode()).isEqualTo(expectedStatusCode);
                    assertThat(ar.cause().getMessage()).isEqualTo(responsePayload);
                }
            });
            ctx.completeNow();
            mockConsumer.close();
            commandSender.stop();
        });
    });
}
Also used : HttpURLConnection(java.net.HttpURLConnection) BeforeEach(org.junit.jupiter.api.BeforeEach) MessagingKafkaConsumerConfigProperties(org.eclipse.hono.client.kafka.consumer.MessagingKafkaConsumerConfigProperties) DownstreamMessage(org.eclipse.hono.application.client.DownstreamMessage) MessagingKafkaProducerConfigProperties(org.eclipse.hono.client.kafka.producer.MessagingKafkaProducerConfigProperties) KafkaMessageContext(org.eclipse.hono.application.client.kafka.KafkaMessageContext) LoggerFactory(org.slf4j.LoggerFactory) OffsetResetStrategy(org.apache.kafka.clients.consumer.OffsetResetStrategy) Context(io.vertx.core.Context) Timeout(io.vertx.junit5.Timeout) ExtendWith(org.junit.jupiter.api.extension.ExtendWith) Duration(java.time.Duration) Map(java.util.Map) StringSerializer(org.apache.kafka.common.serialization.StringSerializer) TracingMockSupport(org.eclipse.hono.test.TracingMockSupport) JsonObject(io.vertx.core.json.JsonObject) TimestampType(org.apache.kafka.common.record.TimestampType) TopicPartition(org.apache.kafka.common.TopicPartition) KafkaMockConsumer(org.eclipse.hono.kafka.test.KafkaMockConsumer) CachingKafkaProducerFactory(org.eclipse.hono.client.kafka.producer.CachingKafkaProducerFactory) UUID(java.util.UUID) RecordMetadata(org.apache.kafka.clients.producer.RecordMetadata) MessageHelper(org.eclipse.hono.util.MessageHelper) VertxExtension(io.vertx.junit5.VertxExtension) Test(org.junit.jupiter.api.Test) List(java.util.List) Buffer(io.vertx.core.buffer.Buffer) Header(org.apache.kafka.common.header.Header) ConsumerRecord(org.apache.kafka.clients.consumer.ConsumerRecord) Span(io.opentracing.Span) Callback(org.apache.kafka.clients.producer.Callback) VertxTestContext(io.vertx.junit5.VertxTestContext) ProducerRecord(org.apache.kafka.clients.producer.ProducerRecord) BufferSerializer(io.vertx.kafka.client.serialization.BufferSerializer) HashMap(java.util.HashMap) RecordHeader(org.apache.kafka.common.header.internals.RecordHeader) ServiceInvocationException(org.eclipse.hono.client.ServiceInvocationException) ArrayList(java.util.ArrayList) RecordHeaders(org.apache.kafka.common.header.internals.RecordHeaders) KafkaClientUnitTestHelper(org.eclipse.hono.kafka.test.KafkaClientUnitTestHelper) Logger(org.slf4j.Logger) Tracer(io.opentracing.Tracer) NoopTracerFactory(io.opentracing.noop.NoopTracerFactory) Promise(io.vertx.core.Promise) Vertx(io.vertx.core.Vertx) Truth.assertThat(com.google.common.truth.Truth.assertThat) Mockito.verify(org.mockito.Mockito.verify) TimeUnit(java.util.concurrent.TimeUnit) HonoTopic(org.eclipse.hono.client.kafka.HonoTopic) AfterEach(org.junit.jupiter.api.AfterEach) SendMessageTimeoutException(org.eclipse.hono.client.SendMessageTimeoutException) NoopSpan(io.opentracing.noop.NoopSpan) MockProducer(org.apache.kafka.clients.producer.MockProducer) KafkaMessageContext(org.eclipse.hono.application.client.kafka.KafkaMessageContext) BufferSerializer(io.vertx.kafka.client.serialization.BufferSerializer) HashMap(java.util.HashMap) ServiceInvocationException(org.eclipse.hono.client.ServiceInvocationException) StringSerializer(org.apache.kafka.common.serialization.StringSerializer) KafkaMessageContext(org.eclipse.hono.application.client.kafka.KafkaMessageContext) Context(io.vertx.core.Context) VertxTestContext(io.vertx.junit5.VertxTestContext) Buffer(io.vertx.core.buffer.Buffer) HonoTopic(org.eclipse.hono.client.kafka.HonoTopic) Callback(org.apache.kafka.clients.producer.Callback) TopicPartition(org.apache.kafka.common.TopicPartition) JsonObject(io.vertx.core.json.JsonObject)

Example 2 with BufferSerializer

use of io.vertx.kafka.client.serialization.BufferSerializer in project hono by eclipse.

the class CachingKafkaProducerFactoryTest method setUp.

@BeforeEach
void setUp() {
    final VertxInternal vertxMock = mock(VertxInternal.class);
    final ContextInternal context = VertxMockSupport.mockContextInternal(vertxMock);
    final PromiseInternal<Void> promiseInternal = VertxMockSupport.promiseInternal();
    when(promiseInternal.future()).thenReturn(Future.succeededFuture());
    doAnswer(invocation -> {
        return promiseInternal;
    }).when(context).promise();
    when(vertxMock.getOrCreateContext()).thenReturn(context);
    doAnswer(invocation -> {
        final Promise<Object> result = Promise.promise();
        final Handler<Future<Object>> blockingCode = invocation.getArgument(0);
        final Handler<AsyncResult<Object>> resultHandler = invocation.getArgument(1);
        result.future().onComplete(resultHandler);
        blockingCode.handle(result.future());
        return null;
    }).when(context).executeBlocking(VertxMockSupport.anyHandler(), VertxMockSupport.anyHandler());
    final BiFunction<String, Map<String, String>, KafkaProducer<String, Buffer>> instanceSupplier = (n, c) -> {
        final MockProducer<String, Buffer> mockProducer = new MockProducer<>(true, new StringSerializer(), new BufferSerializer());
        return KafkaProducer.create(vertxMock, mockProducer);
    };
    factory = CachingKafkaProducerFactory.testFactory(vertxMock, instanceSupplier);
    configProperties.setProducerConfig(Map.of("bootstrap.servers", "localhost:9092"));
}
Also used : KafkaProducer(io.vertx.kafka.client.producer.KafkaProducer) BeforeEach(org.junit.jupiter.api.BeforeEach) BufferSerializer(io.vertx.kafka.client.serialization.BufferSerializer) BiFunction(java.util.function.BiFunction) KafkaException(org.apache.kafka.common.KafkaException) ContextInternal(io.vertx.core.impl.ContextInternal) KafkaProducer(io.vertx.kafka.client.producer.KafkaProducer) Mockito.doAnswer(org.mockito.Mockito.doAnswer) Map(java.util.Map) StringSerializer(org.apache.kafka.common.serialization.StringSerializer) AsyncResult(io.vertx.core.AsyncResult) VertxInternal(io.vertx.core.impl.VertxInternal) PromiseInternal(io.vertx.core.impl.future.PromiseInternal) AuthorizationException(org.apache.kafka.common.errors.AuthorizationException) Promise(io.vertx.core.Promise) OutOfOrderSequenceException(org.apache.kafka.common.errors.OutOfOrderSequenceException) Mockito.when(org.mockito.Mockito.when) Truth.assertThat(com.google.common.truth.Truth.assertThat) Future(io.vertx.core.Future) Test(org.junit.jupiter.api.Test) Buffer(io.vertx.core.buffer.Buffer) VertxMockSupport(org.eclipse.hono.test.VertxMockSupport) ProducerFencedException(org.apache.kafka.common.errors.ProducerFencedException) UnsupportedForMessageFormatException(org.apache.kafka.common.errors.UnsupportedForMessageFormatException) Optional(java.util.Optional) UnsupportedVersionException(org.apache.kafka.common.errors.UnsupportedVersionException) Handler(io.vertx.core.Handler) MockProducer(org.apache.kafka.clients.producer.MockProducer) Mockito.mock(org.mockito.Mockito.mock) BufferSerializer(io.vertx.kafka.client.serialization.BufferSerializer) VertxInternal(io.vertx.core.impl.VertxInternal) MockProducer(org.apache.kafka.clients.producer.MockProducer) ContextInternal(io.vertx.core.impl.ContextInternal) Future(io.vertx.core.Future) AsyncResult(io.vertx.core.AsyncResult) Map(java.util.Map) StringSerializer(org.apache.kafka.common.serialization.StringSerializer) BeforeEach(org.junit.jupiter.api.BeforeEach)

Aggregations

Truth.assertThat (com.google.common.truth.Truth.assertThat)2 Promise (io.vertx.core.Promise)2 Buffer (io.vertx.core.buffer.Buffer)2 BufferSerializer (io.vertx.kafka.client.serialization.BufferSerializer)2 Map (java.util.Map)2 MockProducer (org.apache.kafka.clients.producer.MockProducer)2 StringSerializer (org.apache.kafka.common.serialization.StringSerializer)2 Span (io.opentracing.Span)1 Tracer (io.opentracing.Tracer)1 NoopSpan (io.opentracing.noop.NoopSpan)1 NoopTracerFactory (io.opentracing.noop.NoopTracerFactory)1 AsyncResult (io.vertx.core.AsyncResult)1 Context (io.vertx.core.Context)1 Future (io.vertx.core.Future)1 Handler (io.vertx.core.Handler)1 Vertx (io.vertx.core.Vertx)1 ContextInternal (io.vertx.core.impl.ContextInternal)1 VertxInternal (io.vertx.core.impl.VertxInternal)1 PromiseInternal (io.vertx.core.impl.future.PromiseInternal)1 JsonObject (io.vertx.core.json.JsonObject)1