Search in sources :

Example 16 with ProtonClient

use of io.vertx.proton.ProtonClient in project vertx-proton by vert-x3.

the class MessageSubscriberWhiteboxVerificationTckTest method createSubscriber.

@Override
public Subscriber<Message> createSubscriber(WhiteboxSubscriberProbe<Message> probe) {
    int actualPort = server.actualPort();
    ProtonClient client = ProtonClient.create(vertx);
    AtomicReference<Subscriber<Message>> ref = new AtomicReference<>();
    CountDownLatch latch = new CountDownLatch(1);
    client.connect("localhost", actualPort, result -> {
        if (result.succeeded()) {
            ProtonConnection conn = result.result();
            conn.open();
            // Modified stream impl, overriding methods to add test probe instrumentation
            ProtonSubscriberImpl subscriber = new ProtonSubscriberImpl("myAddress", (ProtonConnectionImpl) conn);
            ProtonSubscriber<Message> stream = new ProtonSubscriberWrapperImpl(subscriber) {

                @Override
                public void onSubscribe(final Subscription s) {
                    super.onSubscribe(s);
                    probe.registerOnSubscribe(new SubscriberPuppet() {

                        @Override
                        public void triggerRequest(long n) {
                            s.request(n);
                        }

                        @Override
                        public void signalCancel() {
                            s.cancel();
                        }
                    });
                }

                @Override
                public void onNext(Message value) {
                    probe.registerOnNext(value);
                    super.onNext(value);
                }

                @Override
                public void onError(Throwable t) {
                    probe.registerOnError(t);
                    super.onError(t);
                }

                @Override
                public void onComplete() {
                    probe.registerOnComplete();
                    super.onComplete();
                }
            };
            ref.set(stream);
        } else {
            LOG.error("Connection failed");
        }
        latch.countDown();
    });
    try {
        LOG.trace("Awaiting connection");
        boolean res = latch.await(2, TimeUnit.SECONDS);
        LOG.trace("Client connected: " + res);
    } catch (InterruptedException e) {
        throw new RuntimeException("Interrupted while creating subscriber", e);
    }
    return ref.get();
}
Also used : Message(org.apache.qpid.proton.message.Message) AtomicReference(java.util.concurrent.atomic.AtomicReference) ProtonClient(io.vertx.proton.ProtonClient) CountDownLatch(java.util.concurrent.CountDownLatch) ProtonConnection(io.vertx.proton.ProtonConnection) Subscriber(org.reactivestreams.Subscriber) ProtonSubscriber(io.vertx.proton.streams.ProtonSubscriber) ProtonSubscriberImpl(io.vertx.proton.streams.impl.ProtonSubscriberImpl) ProtonSubscriberWrapperImpl(io.vertx.proton.streams.impl.ProtonSubscriberWrapperImpl) Subscription(org.reactivestreams.Subscription)

Example 17 with ProtonClient

use of io.vertx.proton.ProtonClient in project vertx-proton by vert-x3.

the class HelloWorld method main.

public static void main(String[] args) {
    // Create the Vert.x instance
    Vertx vertx = Vertx.vertx();
    // Create the Vert.x AMQP client instance
    ProtonClient client = ProtonClient.create(vertx);
    // Connect, then use the event loop thread to process the connection
    client.connect("localhost", 5672, res -> {
        if (res.succeeded()) {
            System.out.println("We're connected");
            ProtonConnection connection = res.result();
            helloWorldSendAndConsumeExample(connection);
        } else {
            res.cause().printStackTrace();
        }
    });
    // Just stop main() from exiting
    try {
        System.in.read();
    } catch (Exception ignore) {
    }
}
Also used : ProtonConnection(io.vertx.proton.ProtonConnection) Vertx(io.vertx.core.Vertx) ProtonClient(io.vertx.proton.ProtonClient)

Example 18 with ProtonClient

use of io.vertx.proton.ProtonClient in project vertx-proton by vert-x3.

the class TrackerSubscriberWhiteboxVerificationTckTest method createSubscriber.

@Override
public Subscriber<Tracker> createSubscriber(WhiteboxSubscriberProbe<Tracker> probe) {
    int actualPort = server.actualPort();
    ProtonClient client = ProtonClient.create(vertx);
    AtomicReference<Subscriber<Tracker>> ref = new AtomicReference<>();
    CountDownLatch latch = new CountDownLatch(1);
    client.connect("localhost", actualPort, result -> {
        if (result.succeeded()) {
            ProtonConnection conn = result.result();
            conn.open();
            // Modified stream impl, overriding methods to add test probe instrumentation
            ProtonSubscriber<Tracker> stream = new ProtonSubscriberImpl("myAddress", (ProtonConnectionImpl) conn) {

                @Override
                public void onSubscribe(final Subscription s) {
                    super.onSubscribe(s);
                    probe.registerOnSubscribe(new SubscriberPuppet() {

                        @Override
                        public void triggerRequest(long n) {
                            s.request(n);
                        }

                        @Override
                        public void signalCancel() {
                            s.cancel();
                        }
                    });
                }

                @Override
                public void onNext(Tracker value) {
                    probe.registerOnNext(value);
                    super.onNext(value);
                }

                @Override
                public void onError(Throwable t) {
                    probe.registerOnError(t);
                    super.onError(t);
                }

                @Override
                public void onComplete() {
                    probe.registerOnComplete();
                    super.onComplete();
                }
            };
            ref.set(stream);
        } else {
            LOG.error("Connection failed");
        }
        latch.countDown();
    });
    try {
        LOG.trace("Awaiting connection");
        boolean res = latch.await(2, TimeUnit.SECONDS);
        LOG.trace("Client connected: " + res);
    } catch (InterruptedException e) {
        throw new RuntimeException("Interrupted while creating subscriber", e);
    }
    return ref.get();
}
Also used : Tracker(io.vertx.proton.streams.Tracker) AtomicReference(java.util.concurrent.atomic.AtomicReference) ProtonClient(io.vertx.proton.ProtonClient) CountDownLatch(java.util.concurrent.CountDownLatch) ProtonConnection(io.vertx.proton.ProtonConnection) Subscriber(org.reactivestreams.Subscriber) ProtonSubscriber(io.vertx.proton.streams.ProtonSubscriber) ProtonSubscriberImpl(io.vertx.proton.streams.impl.ProtonSubscriberImpl) Subscription(org.reactivestreams.Subscription)

Example 19 with ProtonClient

use of io.vertx.proton.ProtonClient in project hono by eclipse.

the class ConnectionFactoryImplTest method testConnectIgnoresSuccessfulOpenAfterTimeout.

/**
 * Verifies that a connection attempt is failed if there is a timeout opening the connection
 * and verifies that a subsequently received 'open' frame is ignored.
 *
 * @param ctx The vert.x test context.
 */
@Test
@Timeout(value = 5, timeUnit = TimeUnit.SECONDS)
public void testConnectIgnoresSuccessfulOpenAfterTimeout(final VertxTestContext ctx) {
    final long connectTimeout = 200L;
    // GIVEN a factory configured to connect to a server with a mocked ProtonClient that won't actually try to connect
    props.setConnectTimeout((int) connectTimeout);
    final AtomicReference<Handler<Long>> timeoutHandlerRef = new AtomicReference<>();
    when(vertx.setTimer(eq(connectTimeout), VertxMockSupport.anyHandler())).thenAnswer(invocation -> {
        timeoutHandlerRef.set(invocation.getArgument(1));
        return 1L;
    });
    final ConnectionFactoryImpl factory = new ConnectionFactoryImpl(vertx, props);
    final ProtonClient protonClientMock = mock(ProtonClient.class);
    final ProtonConnection protonConnectionMock = mock(ProtonConnection.class, Mockito.RETURNS_SELF);
    doAnswer(invocation -> {
        final Handler<AsyncResult<ProtonConnection>> resultHandler = invocation.getArgument(5);
        resultHandler.handle(Future.succeededFuture(protonConnectionMock));
        return null;
    }).when(protonClientMock).connect(any(ProtonClientOptions.class), any(), anyInt(), any(), any(), VertxMockSupport.anyHandler());
    factory.setProtonClient(protonClientMock);
    // WHEN trying to connect to the server
    factory.connect(null, null, null, ctx.failing(t -> {
        // THEN the connection attempt fails with a TimeoutException and the given handler is invoked
        ctx.verify(() -> assertTrue(t instanceof ConnectTimeoutException));
        ctx.completeNow();
    }));
    final ArgumentCaptor<Handler<AsyncResult<ProtonConnection>>> openHandlerCaptor = VertxMockSupport.argumentCaptorHandler();
    verify(protonConnectionMock).openHandler(openHandlerCaptor.capture());
    // trigger timeout
    timeoutHandlerRef.get().handle(1L);
    // call openHandler - that will be too late for the connect invocation to succeed
    openHandlerCaptor.getValue().handle(Future.succeededFuture(protonConnectionMock));
    // and the connection will be disconnected
    verify(protonConnectionMock).disconnect();
}
Also used : ArgumentMatchers.any(org.mockito.ArgumentMatchers.any) VertxTestContext(io.vertx.junit5.VertxTestContext) ProtonConnection(io.vertx.proton.ProtonConnection) BeforeEach(org.junit.jupiter.api.BeforeEach) Arrays(java.util.Arrays) ArgumentMatchers.eq(org.mockito.ArgumentMatchers.eq) AtomicReference(java.util.concurrent.atomic.AtomicReference) Constants(org.eclipse.hono.util.Constants) Timeout(io.vertx.junit5.Timeout) ConnectTimeoutException(org.eclipse.hono.connection.ConnectTimeoutException) ArgumentCaptor(org.mockito.ArgumentCaptor) ProtonClientOptions(io.vertx.proton.ProtonClientOptions) Assertions.assertFalse(org.junit.jupiter.api.Assertions.assertFalse) ExtendWith(org.junit.jupiter.api.extension.ExtendWith) Mockito.doAnswer(org.mockito.Mockito.doAnswer) AsyncResult(io.vertx.core.AsyncResult) ArgumentMatchers.anyInt(org.mockito.ArgumentMatchers.anyInt) ClientConfigProperties(org.eclipse.hono.config.ClientConfigProperties) Promise(io.vertx.core.Promise) Vertx(io.vertx.core.Vertx) ProtonClient(io.vertx.proton.ProtonClient) 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(org.mockito.Mockito) VertxMockSupport(org.eclipse.hono.test.VertxMockSupport) Assertions.assertTrue(org.junit.jupiter.api.Assertions.assertTrue) Handler(io.vertx.core.Handler) ArgumentMatchers.anyString(org.mockito.ArgumentMatchers.anyString) Mockito.mock(org.mockito.Mockito.mock) Handler(io.vertx.core.Handler) AtomicReference(java.util.concurrent.atomic.AtomicReference) ProtonClient(io.vertx.proton.ProtonClient) ProtonConnection(io.vertx.proton.ProtonConnection) ProtonClientOptions(io.vertx.proton.ProtonClientOptions) AsyncResult(io.vertx.core.AsyncResult) ConnectTimeoutException(org.eclipse.hono.connection.ConnectTimeoutException) Test(org.junit.jupiter.api.Test) Timeout(io.vertx.junit5.Timeout)

Example 20 with ProtonClient

use of io.vertx.proton.ProtonClient in project hono by eclipse.

the class ConnectionFactoryImplTest method testConnectIgnoresFailedOpenAfterTimeout.

/**
 * Verifies that a connection attempt is failed if there is a timeout opening the connection
 * and verifies that a subsequently triggered failed open handler is ignored.
 *
 * @param ctx The vert.x test context.
 */
@Test
@Timeout(value = 5, timeUnit = TimeUnit.SECONDS)
public void testConnectIgnoresFailedOpenAfterTimeout(final VertxTestContext ctx) {
    final long connectTimeout = 200L;
    // GIVEN a factory configured to connect to a server with a mocked ProtonClient that won't actually try to connect
    props.setConnectTimeout((int) connectTimeout);
    final AtomicReference<Handler<Long>> timeoutHandlerRef = new AtomicReference<>();
    when(vertx.setTimer(eq(connectTimeout), VertxMockSupport.anyHandler())).thenAnswer(invocation -> {
        timeoutHandlerRef.set(invocation.getArgument(1));
        return 1L;
    });
    final ConnectionFactoryImpl factory = new ConnectionFactoryImpl(vertx, props);
    final ProtonClient protonClientMock = mock(ProtonClient.class);
    final ProtonConnection protonConnectionMock = mock(ProtonConnection.class, Mockito.RETURNS_SELF);
    doAnswer(invocation -> {
        final Handler<AsyncResult<ProtonConnection>> resultHandler = invocation.getArgument(5);
        resultHandler.handle(Future.succeededFuture(protonConnectionMock));
        return null;
    }).when(protonClientMock).connect(any(ProtonClientOptions.class), any(), anyInt(), any(), any(), VertxMockSupport.anyHandler());
    factory.setProtonClient(protonClientMock);
    // WHEN trying to connect to the server
    factory.connect(null, null, null, ctx.failing(t -> {
        // THEN the connection attempt fails with a TimeoutException and the given handler is invoked
        ctx.verify(() -> assertTrue(t instanceof ConnectTimeoutException));
        ctx.completeNow();
    }));
    final ArgumentCaptor<Handler<AsyncResult<ProtonConnection>>> openHandlerCaptor = VertxMockSupport.argumentCaptorHandler();
    verify(protonConnectionMock).openHandler(openHandlerCaptor.capture());
    // trigger timeout
    timeoutHandlerRef.get().handle(1L);
    // call openHandler - that will be too late for the connect invocation to succeed
    openHandlerCaptor.getValue().handle(Future.failedFuture("amqp:resource-limit-exceeded -connection disallowed by local policy"));
    // and the connection will be disconnected
    verify(protonConnectionMock).disconnect();
}
Also used : ArgumentMatchers.any(org.mockito.ArgumentMatchers.any) VertxTestContext(io.vertx.junit5.VertxTestContext) ProtonConnection(io.vertx.proton.ProtonConnection) BeforeEach(org.junit.jupiter.api.BeforeEach) Arrays(java.util.Arrays) ArgumentMatchers.eq(org.mockito.ArgumentMatchers.eq) AtomicReference(java.util.concurrent.atomic.AtomicReference) Constants(org.eclipse.hono.util.Constants) Timeout(io.vertx.junit5.Timeout) ConnectTimeoutException(org.eclipse.hono.connection.ConnectTimeoutException) ArgumentCaptor(org.mockito.ArgumentCaptor) ProtonClientOptions(io.vertx.proton.ProtonClientOptions) Assertions.assertFalse(org.junit.jupiter.api.Assertions.assertFalse) ExtendWith(org.junit.jupiter.api.extension.ExtendWith) Mockito.doAnswer(org.mockito.Mockito.doAnswer) AsyncResult(io.vertx.core.AsyncResult) ArgumentMatchers.anyInt(org.mockito.ArgumentMatchers.anyInt) ClientConfigProperties(org.eclipse.hono.config.ClientConfigProperties) Promise(io.vertx.core.Promise) Vertx(io.vertx.core.Vertx) ProtonClient(io.vertx.proton.ProtonClient) 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(org.mockito.Mockito) VertxMockSupport(org.eclipse.hono.test.VertxMockSupport) Assertions.assertTrue(org.junit.jupiter.api.Assertions.assertTrue) Handler(io.vertx.core.Handler) ArgumentMatchers.anyString(org.mockito.ArgumentMatchers.anyString) Mockito.mock(org.mockito.Mockito.mock) Handler(io.vertx.core.Handler) AtomicReference(java.util.concurrent.atomic.AtomicReference) ProtonClient(io.vertx.proton.ProtonClient) ProtonConnection(io.vertx.proton.ProtonConnection) ProtonClientOptions(io.vertx.proton.ProtonClientOptions) AsyncResult(io.vertx.core.AsyncResult) ConnectTimeoutException(org.eclipse.hono.connection.ConnectTimeoutException) Test(org.junit.jupiter.api.Test) Timeout(io.vertx.junit5.Timeout)

Aggregations

ProtonClient (io.vertx.proton.ProtonClient)55 ProtonConnection (io.vertx.proton.ProtonConnection)42 Handler (io.vertx.core.Handler)27 Message (org.apache.qpid.proton.message.Message)27 AmqpValue (org.apache.qpid.proton.amqp.messaging.AmqpValue)24 AsyncResult (io.vertx.core.AsyncResult)23 Test (org.junit.Test)22 Arrays (java.util.Arrays)21 ProtonHelper.message (io.vertx.proton.ProtonHelper.message)20 ProtonStreams (io.vertx.proton.streams.ProtonStreams)20 Section (org.apache.qpid.proton.amqp.messaging.Section)20 Async (io.vertx.ext.unit.Async)19 ProtonClientOptions (io.vertx.proton.ProtonClientOptions)19 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)19 Logger (io.vertx.core.impl.logging.Logger)18 LoggerFactory (io.vertx.core.impl.logging.LoggerFactory)18 TestContext (io.vertx.ext.unit.TestContext)18 VertxUnitRunner (io.vertx.ext.unit.junit.VertxUnitRunner)18 FutureHandler (io.vertx.proton.FutureHandler)18 MockServerTestBase (io.vertx.proton.MockServerTestBase)18