io.vertx.proton.ProtonConnection Java Examples

The following examples show how to use io.vertx.proton.ProtonConnection. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: HonoConnectionImpl.java    From hono with Eclipse Public License 2.0 6 votes vote down vote up
private void onRemoteClose(final AsyncResult<ProtonConnection> remoteClose,
        final Handler<ProtonConnection> connectionLossHandler) {

    if (remoteClose.failed()) {
        log.info("remote server [{}:{}, role: {}] closed connection with error condition: {}",
                connectionFactory.getHost(),
                connectionFactory.getPort(),
                connectionFactory.getServerRole(),
                remoteClose.cause().getMessage());
    } else {
        log.info("remote server [{}:{}, role: {}] closed connection",
                connectionFactory.getHost(),
                connectionFactory.getPort(),
                connectionFactory.getServerRole());
    }
    connection.disconnectHandler(null);
    connection.close();
    handleConnectionLoss(connectionLossHandler);
}
 
Example #2
Source File: AbstractSender.java    From enmasse with Apache License 2.0 6 votes vote down vote up
@Override
public void connectionOpened(ProtonConnection connection) {
    ProtonSender sender = connection.createSender(linkOptions.getTarget().getAddress());
    sender.setTarget(linkOptions.getTarget());
    sender.setQoS(clientOptions.getQos());
    sender.openHandler(result -> {
        if (result.succeeded()) {
            log.info("Sender link '" + sender.getTarget().getAddress() + "' opened, sending messages");
            connectPromise.complete(null);
            sendMessages(connection, sender);
        } else {
            handleError(connection, sender.getRemoteCondition());
        }
    });
    sender.closeHandler(result -> handleError(connection, sender.getRemoteCondition()));
    sender.open();
}
 
Example #3
Source File: HonoConnectionImplTest.java    From hono with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Sets up fixture.
 */
@BeforeEach
public void setUp() {
    vertx = mock(Vertx.class);
    final Context context = HonoClientUnitTestHelper.mockContext(vertx);
    when(vertx.getOrCreateContext()).thenReturn(context);
    // run any timer immediately
    when(vertx.setTimer(anyLong(), VertxMockSupport.anyHandler())).thenAnswer(invocation -> {
        final Handler<Void> handler = invocation.getArgument(1);
        handler.handle(null);
        return 0L;
    });
    con = mock(ProtonConnection.class);
    when(con.getRemoteContainer()).thenReturn("server");
    connectionFactory = new DisconnectHandlerProvidingConnectionFactory(con);
    props = new ClientConfigProperties();
    honoConnection = new HonoConnectionImpl(vertx, connectionFactory, props);
}
 
Example #4
Source File: AmqpAdapterTestBase.java    From hono with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Connects to the AMQP protocol adapter using a username and password.
 *
 *
 * @param username The username to use for authentication.
 * @param password The password to use for authentication.
 * @return A succeeded future containing the established connection.
 */
protected Future<ProtonConnection> connectToAdapter(final String username, final String password) {

    final Promise<ProtonConnection> result = Promise.promise();
    final ProtonClient client = ProtonClient.create(VERTX);

    final ProtonClientOptions options = new ProtonClientOptions(defaultOptions);
    options.addEnabledSaslMechanism(ProtonSaslPlainImpl.MECH_NAME);
    client.connect(
            options,
            IntegrationTestSupport.AMQP_HOST,
            IntegrationTestSupport.AMQPS_PORT,
            username,
            password,
            result);
    return result.future().compose(this::handleConnectAttempt);
}
 
Example #5
Source File: HonoSaslAuthenticator.java    From hono with Eclipse Public License 2.0 6 votes vote down vote up
@Override
public void init(final NetSocket socket, final ProtonConnection protonConnection, final Transport transport) {

    LOG.debug("initializing SASL authenticator");
    this.protonConnection = protonConnection;
    this.sasl = transport.sasl();
    sasl.server();
    sasl.allowSkip(false);
    sasl.setMechanisms(authenticationService.getSupportedSaslMechanisms());
    if (socket.isSsl() && Arrays.asList(authenticationService.getSupportedSaslMechanisms())
            .contains(AuthenticationConstants.MECHANISM_EXTERNAL)) {
        LOG.debug("client connected using TLS, extracting client certificate chain");
        try {
            final Certificate cert = socket.sslSession().getPeerCertificates()[0];
            if (cert instanceof X509Certificate) {
                clientCertificate = (X509Certificate) cert;
            }
        } catch (final SSLPeerUnverifiedException e) {
            LOG.debug("could not extract client certificate chain, maybe client uses other mechanism than SASL EXTERNAL");
        }
    }
}
 
Example #6
Source File: ProtonConnectionImpl.java    From vertx-proton with Apache License 2.0 6 votes vote down vote up
private ProtonSession getDefaultSession() {
  if (defaultSession == null) {
    defaultSession = createSession();
    defaultSession.closeHandler(result -> {
      String msg = "The connections default session closed unexpectedly";
      if (!result.succeeded()) {
        msg += ": ";
        msg += ": " + String.valueOf(result.cause());
      }
      Future<ProtonConnection> failure = Future.failedFuture(msg);
      Handler<AsyncResult<ProtonConnection>> connCloseHandler = closeHandler;
      if (connCloseHandler != null) {
        connCloseHandler.handle(failure);
      }
    });

    defaultSession.open();
    // Deliberately not flushing, the sender/receiver open
    // call will do that (if it doesn't happen otherwise).
  }
  return defaultSession;
}
 
Example #7
Source File: SingleSender.java    From enmasse with Apache License 2.0 6 votes vote down vote up
@Override
protected void sendMessages(final ProtonConnection connection, final ProtonSender sender) {
    this.state = "ready to send";

    switch (sender.getQoS()) {
        case AT_MOST_ONCE:
            sender.send(this.message);
            this.state = "message sent";
            this.resultPromise.complete(Collections.emptyList());
            break;
        case AT_LEAST_ONCE:
            sender.send(this.message, del -> {
                this.state = "message disposition received";
                this.deliveries.add(del);
                if (del.remotelySettled()) {
                    this.state = "message settled";
                    // complete, sending a copy
                    this.resultPromise.complete(new ArrayList<>(this.deliveries));
                }
            });
            this.state = "message sent";
            break;
    }
}
 
Example #8
Source File: BlockingClient.java    From enmasse with Apache License 2.0 6 votes vote down vote up
public void send(String address, List<Message> messages, long timeout, TimeUnit timeUnit) throws InterruptedException {
    ProtonClient client = ProtonClient.create(vertx);
    CountDownLatch latch = new CountDownLatch(1);
    Queue<Message> messageQueue = new ArrayDeque<>(messages);
    client.connect(host, port, connectEvent -> {
        if (connectEvent.succeeded()) {
            ProtonConnection connection = connectEvent.result();
            connection.open();

            ProtonSender sender = connection.createSender(address);
            sender.openHandler(senderOpenEvent -> {
                if (senderOpenEvent.succeeded()) {
                    sendNext(connection, sender, messageQueue, latch);
                }
            });
            sender.open();
        }
    });
    boolean ok = latch.await(timeout, timeUnit);
    if (!ok) {
        throw new RuntimeException("Sending messages timed out, " + messageQueue.size() + " messages unsent");
    }
}
 
Example #9
Source File: ProtonTransport.java    From vertx-proton with Apache License 2.0 6 votes vote down vote up
ProtonTransport(Connection connection, Vertx vertx, NetClient netClient, NetSocket socket,
                ProtonSaslAuthenticator authenticator, ProtonTransportOptions options) {
  this.connection = connection;
  this.vertx = vertx;
  this.netClient = netClient;
  this.socket = socket;
  int maxFrameSize = options.getMaxFrameSize() == 0 ? DEFAULT_MAX_FRAME_SIZE : options.getMaxFrameSize();
  transport.setMaxFrameSize(maxFrameSize);
  transport.setOutboundFrameSizeLimit(maxFrameSize);
  transport.setEmitFlowEventOnSend(false); // TODO: make configurable
  transport.setIdleTimeout(2 * options.getHeartbeat());
  ((TransportInternal) transport).setUseReadOnlyOutputBuffer(false);
  if (authenticator != null) {
    authenticator.init(this.socket, (ProtonConnection) this.connection.getContext(), transport);
  }
  this.authenticator = authenticator;
  transport.bind(connection);
  connection.collect(collector);
  socket.endHandler(this::handleSocketEnd);
  socket.handler(this::handleSocketBuffer);
}
 
Example #10
Source File: VertxBasedAmqpProtocolAdapterTest.java    From hono with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Verifies that the connection is rejected as the adapter is disabled.
 */
@Test
public void testConnectionFailsIfAdapterIsDisabled() {
    // GIVEN an AMQP adapter that requires devices to authenticate
    config.setAuthenticationRequired(true);
    final VertxBasedAmqpProtocolAdapter adapter = givenAnAmqpAdapter();
    // AND given a tenant for which the AMQP Adapter is disabled
    givenAConfiguredTenant(TEST_TENANT_ID, false);
    // WHEN a device connects
    final Device authenticatedDevice = new Device(TEST_TENANT_ID, TEST_DEVICE);
    final Record record = new RecordImpl();
    record.set(AmqpAdapterConstants.KEY_CLIENT_DEVICE, Device.class, authenticatedDevice);
    final ProtonConnection deviceConnection = mock(ProtonConnection.class);
    when(deviceConnection.attachments()).thenReturn(record);
    adapter.onConnectRequest(deviceConnection);
    @SuppressWarnings("unchecked")
    final ArgumentCaptor<Handler<AsyncResult<ProtonConnection>>> openHandler = ArgumentCaptor
            .forClass(Handler.class);
    verify(deviceConnection).openHandler(openHandler.capture());
    openHandler.getValue().handle(Future.succeededFuture(deviceConnection));
    // THEN the adapter does not accept the incoming connection request. 
    final ArgumentCaptor<ErrorCondition> errorConditionCaptor = ArgumentCaptor.forClass(ErrorCondition.class);
    verify(deviceConnection).setCondition(errorConditionCaptor.capture());
    assertEquals(AmqpError.UNAUTHORIZED_ACCESS, errorConditionCaptor.getValue().getCondition());
}
 
Example #11
Source File: AmqpServiceBaseTest.java    From hono with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Verifies that the service invokes the <em>publishConnectionClosedEvent</em>
 * method when a client disconnects.
 */
@Test
@SuppressWarnings({"rawtypes", "unchecked"})
public void testServerCallsPublishEventOnClientDisconnect() {

    // GIVEN a server to which a client is connected
    final Handler<ProtonConnection> publishConnectionClosedEvent = mock(Handler.class);
    final AmqpServiceBase<ServiceConfigProperties> server = createServer(null, publishConnectionClosedEvent);
    final ProtonConnection con = newConnection(Constants.PRINCIPAL_ANONYMOUS);
    server.onRemoteConnectionOpen(con);
    final ArgumentCaptor<Handler> closeHandlerCaptor = ArgumentCaptor.forClass(Handler.class);
    verify(con).disconnectHandler(closeHandlerCaptor.capture());

    // WHEN the client disconnects from the service
    closeHandlerCaptor.getValue().handle(con);

    // THEN the publishConnectionClosedEvent method is invoked
    verify(publishConnectionClosedEvent).handle(any(ProtonConnection.class));
}
 
Example #12
Source File: VertxBasedAmqpProtocolAdapterTest.java    From hono with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Verifies that the connection is rejected as the connection limit for 
 * the given tenant is exceeded.
 */
@Test
public void testConnectionFailsIfTenantLevelConnectionLimitIsExceeded() {
    // GIVEN an AMQP adapter that requires devices to authenticate
    config.setAuthenticationRequired(true);
    final VertxBasedAmqpProtocolAdapter adapter = givenAnAmqpAdapter();
    // WHEN the connection limit for the given tenant exceeds
    when(resourceLimitChecks.isConnectionLimitReached(any(TenantObject.class), any(SpanContext.class)))
            .thenReturn(Future.succeededFuture(Boolean.TRUE));
    // WHEN a device connects
    final Device authenticatedDevice = new Device(TEST_TENANT_ID, TEST_DEVICE);
    final Record record = new RecordImpl();
    record.set(AmqpAdapterConstants.KEY_CLIENT_DEVICE, Device.class, authenticatedDevice);
    final ProtonConnection deviceConnection = mock(ProtonConnection.class);
    when(deviceConnection.attachments()).thenReturn(record);
    adapter.onConnectRequest(deviceConnection);
    @SuppressWarnings("unchecked")
    final ArgumentCaptor<Handler<AsyncResult<ProtonConnection>>> openHandler = ArgumentCaptor
            .forClass(Handler.class);
    verify(deviceConnection).openHandler(openHandler.capture());
    openHandler.getValue().handle(Future.succeededFuture(deviceConnection));
    // THEN the adapter does not accept the incoming connection request. 
    final ArgumentCaptor<ErrorCondition> errorConditionCaptor = ArgumentCaptor.forClass(ErrorCondition.class);
    verify(deviceConnection).setCondition(errorConditionCaptor.capture());
    assertEquals(AmqpError.UNAUTHORIZED_ACCESS, errorConditionCaptor.getValue().getCondition());
}
 
Example #13
Source File: SimpleAuthenticationServer.java    From hono with Eclipse Public License 2.0 6 votes vote down vote up
@Override
protected void setRemoteConnectionOpenHandler(final ProtonConnection connection) {
    connection.sessionOpenHandler(remoteOpenSession -> handleSessionOpen(connection, remoteOpenSession));
    connection.senderOpenHandler(remoteOpenSender -> handleSenderOpen(connection, remoteOpenSender));
    // no receiverOpenHandler set here
    connection.disconnectHandler(con -> {
        con.close();
        con.disconnect();
    });
    connection.closeHandler(remoteClose -> {
        connection.close();
        connection.disconnect();
    });
    connection.openHandler(remoteOpen -> {
        if (remoteOpen.failed()) {
            LOG.debug("ignoring peer's open frame containing error", remoteOpen.cause());
        } else {
            processRemoteOpen(remoteOpen.result());
        }
    });
}
 
Example #14
Source File: AbstractRequestResponseEndpoint.java    From hono with Eclipse Public License 2.0 5 votes vote down vote up
private Future<ProtonSender> getSenderForConnection(final ProtonConnection con, final String replytoAddress) {

        final Promise<ProtonSender> result = Promise.promise();
        final ProtonSender sender = replyToSenderMap.get(replytoAddress);
        if (sender != null && sender.isOpen() && sender.getSession().getConnection() == con) {
            result.complete(sender);
        } else {
            result.fail(new ClientErrorException(
                    HttpURLConnection.HTTP_PRECON_FAILED,
                    "must open receiver link for reply-to address first"));
        }
        return result.future();
    }
 
Example #15
Source File: SimpleAuthenticationServer.java    From hono with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Handles a request from a client to establish a link for receiving messages from this server.
 *
 * @param con the connection to the client.
 * @param sender the sender created for the link.
 */
@Override
protected void handleSenderOpen(final ProtonConnection con, final ProtonSender sender) {

    final Source remoteSource = sender.getRemoteSource();
    LOG.debug("client [{}] wants to open a link for receiving messages [address: {}]",
            con.getRemoteContainer(), remoteSource);
    try {
        final ResourceIdentifier targetResource = getResourceIdentifier(remoteSource.getAddress());
        final AmqpEndpoint endpoint = getEndpoint(targetResource);

        if (endpoint == null) {
            LOG.debug("no endpoint registered for node [{}]", targetResource);
            con.setCondition(ProtonHelper.condition(AmqpError.NOT_FOUND, "no such node")).close();
        } else {
            final HonoUser user = Constants.getClientPrincipal(con);
            if (Constants.SUBJECT_ANONYMOUS.equals(user.getName())) {
                con.setCondition(ProtonHelper.condition(AmqpError.UNAUTHORIZED_ACCESS, "client must authenticate using SASL")).close();
            } else {
                Constants.copyProperties(con, sender);
                sender.setSource(sender.getRemoteSource());
                endpoint.onLinkAttach(con, sender, targetResource);
            }
        }
    } catch (final IllegalArgumentException e) {
        LOG.debug("client has provided invalid resource identifier as source address", e);
        con.setCondition(ProtonHelper.condition(AmqpError.INVALID_FIELD, "malformed source address")).close();
    }
}
 
Example #16
Source File: ProtonServerImplTest.java    From vertx-proton with Apache License 2.0 5 votes vote down vote up
@Override
public void init(NetSocket socket, ProtonConnection protonConnection, Transport transport) {
  this.protonConnection = protonConnection;
  this.sasl = transport.sasl();
  sasl.server();
  sasl.allowSkip(false);
  sasl.setMechanisms(PLAIN);
}
 
Example #17
Source File: HonoConnectionImpl.java    From hono with Eclipse Public License 2.0 5 votes vote down vote up
private void onRemoteDisconnect(final ProtonConnection con, final Handler<ProtonConnection> connectionLossHandler) {

        if (con != connection) {
            log.warn("cannot handle failure of unknown connection");
        } else {
            log.debug("lost connection to server [{}:{}, role: {}]",
                    connectionFactory.getHost(),
                    connectionFactory.getPort(),
                    connectionFactory.getServerRole());
            handleConnectionLoss(connectionLossHandler);
        }
    }
 
Example #18
Source File: DeliveryPublisherVerificationTckTest.java    From vertx-proton with Apache License 2.0 5 votes vote down vote up
@Override
public Publisher<Delivery> createPublisher(long elements) {
  int actualPort = server.actualPort();

  ProtonClient client = ProtonClient.create(vertx);

  AtomicReference<Publisher<Delivery>> ref = new AtomicReference<>();
  CountDownLatch latch = new CountDownLatch(1);
  client.connect("localhost", actualPort, result -> {
    if (result.succeeded()) {
      ProtonConnection conn = result.result();
      conn.open();

      ProtonPublisher<Delivery> stream = ProtonStreams.createDeliveryConsumer(conn, testName);
      ((ProtonPublisherImpl) stream).setEmitOnConnectionEnd(false);
      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 publisher", e);
  }

  return ref.get();
}
 
Example #19
Source File: DisconnectHandlerProvidingConnectionFactory.java    From hono with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public void connect(
        final ProtonClientOptions options,
        final Handler<AsyncResult<ProtonConnection>> closeHandler,
        final Handler<ProtonConnection> disconnectHandler,
        final Handler<AsyncResult<ProtonConnection>> connectionResultHandler) {
    connect(options, null, null, closeHandler, disconnectHandler, connectionResultHandler);
}
 
Example #20
Source File: ProtonSubscriberIntTest.java    From vertx-proton with Apache License 2.0 5 votes vote down vote up
private ProtonServer createServer(Handler<ProtonConnection> serverConnHandler) throws InterruptedException,
                                                                               ExecutionException {
  ProtonServer server = ProtonServer.create(vertx);

  server.connectHandler(serverConnHandler);

  FutureHandler<ProtonServer, AsyncResult<ProtonServer>> handler = FutureHandler.asyncResult();
  server.listen(0, handler);
  handler.get();

  return server;
}
 
Example #21
Source File: AuthenticationServerClient.java    From hono with Eclipse Public License 2.0 5 votes vote down vote up
private static Future<ProtonReceiver> openReceiver(final ProtonConnection openConnection, final ProtonMessageHandler messageHandler) {

        final Promise<ProtonReceiver> result = Promise.promise();
        final ProtonReceiver recv = openConnection.createReceiver(AuthenticationConstants.ENDPOINT_NAME_AUTHENTICATION);
        recv.openHandler(result);
        recv.handler(messageHandler);
        recv.open();
        return result.future();
    }
 
Example #22
Source File: MessagePublisherVerificationTckTest.java    From vertx-proton with Apache License 2.0 5 votes vote down vote up
@Override
public Publisher<Message> createPublisher(long elements) {
  int actualPort = server.actualPort();

  ProtonClient client = ProtonClient.create(vertx);

  AtomicReference<Publisher<Message>> ref = new AtomicReference<>();
  CountDownLatch latch = new CountDownLatch(1);
  client.connect("localhost", actualPort, result -> {
    if (result.succeeded()) {
      ProtonConnection conn = result.result();
      conn.open();

      ProtonPublisher<Message> stream = ProtonStreams.createConsumer(conn, testName);
      ((ProtonPublisherWrapperImpl) stream).setEmitOnConnectionEnd(false);
      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 publisher", e);
  }

  return ref.get();
}
 
Example #23
Source File: TrackerSubscriberBlackboxVerificationTckTest.java    From vertx-proton with Apache License 2.0 5 votes vote down vote up
@Override
public Subscriber<Tracker> createSubscriber() {
  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();

      ProtonSubscriber<Tracker> stream = ProtonStreams.createTrackerProducer(conn, "myAddress");
      ((ProtonSubscriberImpl) stream).setEmitOnConnectionEnd(false);
      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();
}
 
Example #24
Source File: AmqpBridge.java    From strimzi-kafka-bridge with Apache License 2.0 5 votes vote down vote up
/**
 * Connect to an AMQP server/router
 *
 * @param startPromise
 */
private void connectAmqpClient(Promise<Void> startPromise) {

    this.client = ProtonClient.create(this.vertx);

    String host = this.bridgeConfig.getAmqpConfig().getHost();
    int port = this.bridgeConfig.getAmqpConfig().getPort();

    ProtonClientOptions options = this.createClientOptions();

    this.client.connect(options, host, port, ar -> {

        if (ar.succeeded()) {

            ProtonConnection connection = ar.result();
            connection.setContainer(CONTAINER_ID);

            this.processConnection(connection);

            log.info("AMQP-Kafka Bridge started and connected in client mode to {}:{}", host, port);
            log.info("AMQP-Kafka Bridge bootstrap servers {}",
                    this.bridgeConfig.getKafkaConfig().getConfig()
                            .get(CommonClientConfigs.BOOTSTRAP_SERVERS_CONFIG)
            );

            this.isReady = true;

            startPromise.complete();

        } else {
            log.error("Error connecting AMQP-Kafka Bridge as client", ar.cause());
            startPromise.fail(ar.cause());
        }
    });
}
 
Example #25
Source File: AmqpServiceBaseTest.java    From hono with Eclipse Public License 2.0 5 votes vote down vote up
private AmqpServiceBase<ServiceConfigProperties> createServer(final AmqpEndpoint amqpEndpoint, final Handler<ProtonConnection> onClientDisconnect) {

        final AmqpServiceBase<ServiceConfigProperties> server = new AmqpServiceBase<>() {

            @Override
            protected String getServiceName() {
                return "AmqpServiceBase";
            }

            @Override
            public void setConfig(final ServiceConfigProperties configuration) {
                setSpecificConfig(configuration);
            }

            @Override
            protected void publishConnectionClosedEvent(final ProtonConnection con) {
                if (onClientDisconnect != null) {
                    onClientDisconnect.handle(con);
                }
            }
        };
        server.setConfig(new ServiceConfigProperties());
        if (amqpEndpoint != null) {
            server.addEndpoint(amqpEndpoint);
        }
        server.init(vertx, mock(Context.class));
        return server;
    }
 
Example #26
Source File: VertxProtonExamples.java    From vertx-proton with Apache License 2.0 5 votes vote down vote up
public void example3(ProtonConnection connection) {
  connection.createReceiver("myQueue").handler((delivery, msg) -> {
    Section body = msg.getBody();
    if (body instanceof AmqpValue) {
      System.out.println("Received message with content: " + ((AmqpValue) body).getValue());
    }
    // By default, the receiver automatically accepts (and settles) the delivery
    // when the handler returns if no other disposition has already been applied.
  }).open();
}
 
Example #27
Source File: VertxBasedAmqpProtocolAdapterTest.java    From hono with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Verifies that the adapter closes a corresponding command consumer if
 * the connection to a device fails unexpectedly.
 *
 * @param ctx The vert.x test context.
 * @throws InterruptedException if the test execution gets interrupted.
 */
@Test
public void testAdapterClosesCommandConsumerWhenConnectionToDeviceIsLost(final VertxTestContext ctx) throws InterruptedException {

    final Handler<ProtonConnection> trigger = deviceConnection -> {
        @SuppressWarnings("unchecked")
        final ArgumentCaptor<Handler<ProtonConnection>> disconnectHandler = ArgumentCaptor.forClass(Handler.class);
        verify(deviceConnection).disconnectHandler(disconnectHandler.capture());
        disconnectHandler.getValue().handle(deviceConnection);
    };
    testAdapterClosesCommandConsumer(ctx, trigger);
}
 
Example #28
Source File: VertxBasedAmqpProtocolAdapter.java    From hono with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * This method is called when an AMQP BEGIN frame is received from a remote client. This method sets the incoming
 * capacity in its BEGIN Frame to be communicated to the remote peer
 *
 */
private void handleSessionOpen(final ProtonConnection conn, final ProtonSession session) {
    log.debug("opening new session with client [container: {}, session window size: {}]",
            conn.getRemoteContainer(), getConfig().getMaxSessionWindowSize());
    session.setIncomingCapacity(getConfig().getMaxSessionWindowSize());
    session.open();
}
 
Example #29
Source File: VertxBasedAmqpProtocolAdapter.java    From hono with Eclipse Public License 2.0 5 votes vote down vote up
private Future<ProtocolAdapterCommandConsumer> openCommandSenderLink(
        final ProtonConnection connection,
        final ProtonSender sender,
        final ResourceIdentifier address,
        final Device authenticatedDevice,
        final Span span,
        final OptionalInt traceSamplingPriority) {

    return createCommandConsumer(sender, address, authenticatedDevice, span).map(consumer -> {

        final String tenantId = address.getTenantId();
        final String deviceId = address.getResourceId();
        sender.setSource(sender.getRemoteSource());
        sender.setTarget(sender.getRemoteTarget());

        sender.setQoS(ProtonQoS.AT_LEAST_ONCE);
        final Handler<AsyncResult<ProtonSender>> detachHandler = link -> {
            final Span detachHandlerSpan = newSpan("detach Command receiver", authenticatedDevice,
                    traceSamplingPriority);
            removeConnectionLossHandler(connection, address.toString());
            sendDisconnectedTtdEvent(tenantId, deviceId, authenticatedDevice, detachHandlerSpan.context());
            onLinkDetach(sender);
            consumer.close(detachHandlerSpan.context())
                    .onComplete(v -> detachHandlerSpan.finish());
        };
        HonoProtonHelper.setCloseHandler(sender, detachHandler);
        HonoProtonHelper.setDetachHandler(sender, detachHandler);
        sender.open();

        // At this point, the remote peer's receiver link is successfully opened and is ready to receive
        // commands. Send "device ready for command" notification downstream.
        log.debug("established link [address: {}] for sending commands to device", address);

        sendConnectedTtdEvent(tenantId, deviceId, authenticatedDevice, span.context());
        return consumer;
    }).recover(t -> Future.failedFuture(
            new ServerErrorException(HttpURLConnection.HTTP_UNAVAILABLE, "cannot create command consumer")));
}
 
Example #30
Source File: ClientHandlerBase.java    From enmasse with Apache License 2.0 5 votes vote down vote up
@Override
public void start() {
    log.info("Starting verticle: {}", this);

    ProtonClient client = ProtonClient.create(vertx);
    Endpoint endpoint = clientOptions.getEndpoint();
    client.connect(clientOptions.getProtonClientOptions(), endpoint.getHost(), endpoint.getPort(), clientOptions.getUsername(), clientOptions.getPassword(), connection -> {
        if (connection.succeeded()) {
            ProtonConnection conn = connection.result();
            conn.setContainer(containerId);
            conn.openHandler(result -> {
                if (result.failed()) {
                    conn.close();
                    resultPromise.completeExceptionally(result.cause());
                    connectPromise.completeExceptionally(result.cause());
                } else {
                    connectionOpened(conn);
                }
            });
            conn.closeHandler(result -> {
                if (result.failed()) {
                    conn.close();
                    resultPromise.completeExceptionally(result.cause());
                } else {
                    connectionClosed(conn);
                }
            });
            conn.disconnectHandler(result -> connectionDisconnected(conn));
            conn.open();
        } else {
            log.info("Connection to {}:{} failed: {}", endpoint.getHost(), endpoint.getPort(), connection.cause().getMessage(), connection.cause());
            resultPromise.completeExceptionally(connection.cause());
            connectPromise.completeExceptionally(connection.cause());
        }
    });
}