org.apache.qpid.proton.engine.Record Java Examples

The following examples show how to use org.apache.qpid.proton.engine.Record. 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: VertxBasedAmqpProtocolAdapterTest.java    From hono with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Verifies that the adapter offers the ANONYMOUS-RELAY capability
 * in its open frame when a device connects.
 */
@Test
public void testAdapterSupportsAnonymousRelay() {

    // GIVEN an AMQP adapter with a configured server.
    final ProtonServer server = getAmqpServer();
    final VertxBasedAmqpProtocolAdapter adapter = getAdapter(server);

    // 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);
    when(deviceConnection.getRemoteContainer()).thenReturn("deviceContainer");

    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's open frame contains the ANONYMOUS-RELAY capability
    verify(deviceConnection).setOfferedCapabilities(argThat(caps -> Arrays.stream(caps).anyMatch(cap -> Constants.CAP_ANONYMOUS_RELAY.equals(cap))));
}
 
Example #2
Source File: ReactorImpl.java    From qpid-proton-j with Apache License 2.0 6 votes vote down vote up
@Override
public void setConnectionHost(Connection connection,
                              String host, int port) {
    Record r = connection.attachments();
    // cannot set the address on an incoming connection
    if (r.get(AcceptorImpl.CONNECTION_ACCEPTOR_KEY, Acceptor.class) == null) {
        Address addr = new Address();
        addr.setHost(host);
        if (port == 0) {
            port = 5672;
        }
        addr.setPort(Integer.toString(port));
        r.set(CONNECTION_PEER_ADDRESS_KEY, Address.class, addr);
    } else {
        throw new IllegalStateException("Cannot set the host address on an incoming Connection");
    }
}
 
Example #3
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 #4
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 #5
Source File: AmqpServiceBaseTest.java    From hono with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Verifies that the service notifies a registered endpoint about a client
 * that has established a link.
 */
@Test
public void testHandleReceiverOpenForwardsToEndpoint() {

    // GIVEN a server with an endpoint
    final ResourceIdentifier targetAddress = ResourceIdentifier.from(ENDPOINT, Constants.DEFAULT_TENANT, null);
    final AmqpEndpoint endpoint = mock(AmqpEndpoint.class);
    when(endpoint.getName()).thenReturn(ENDPOINT);
    final AuthorizationService authService = mock(AuthorizationService.class);
    when(authService.isAuthorized(Constants.PRINCIPAL_ANONYMOUS, targetAddress, Activity.WRITE))
        .thenReturn(Future.succeededFuture(Boolean.TRUE));
    final AmqpServiceBase<ServiceConfigProperties> server = createServer(endpoint);
    server.setAuthorizationService(authService);

    // WHEN a client connects to the server using this endpoint
    final Target target = getTarget(targetAddress);
    final ProtonReceiver receiver = mock(ProtonReceiver.class);
    when(receiver.getRemoteTarget()).thenReturn(target);
    when(receiver.attachments()).thenReturn(mock(Record.class));
    server.handleReceiverOpen(newConnection(Constants.PRINCIPAL_ANONYMOUS), receiver);

    // THEN the server delegates link establishment to the endpoint
    verify(endpoint).onLinkAttach(any(ProtonConnection.class), eq(receiver), eq(targetAddress));
}
 
Example #6
Source File: VertxBasedAmqpProtocolAdapterTest.java    From hono with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Verifies that if a client device opens a receiver link to receive commands, then the AMQP adapter opens a link
 * for sending commands to the device and notifies the downstream application by sending an
 * <em>EventConstants.CONTENT_TYPE_EMPTY_NOTIFICATION</em> event a with TTD -1. An unauthenticated device is used in
 * this test setup to simulate the client device.
 */
@SuppressWarnings("unchecked")
@Test
public void testAdapterOpensSenderLinkAndNotifyDownstreamApplication() {
    // GIVEN an AMQP adapter configured to use a user-defined server
    final VertxBasedAmqpProtocolAdapter adapter = givenAnAmqpAdapter();
    final Promise<ProtonDelivery> outcome = Promise.promise();
    final DownstreamSender eventSender = givenAnEventSender(outcome);

    // WHEN an unauthenticated device opens a receiver link with a valid source address
    final ProtonConnection deviceConnection = mock(ProtonConnection.class);
    when(deviceConnection.attachments()).thenReturn(mock(Record.class));
    when(commandConsumerFactory.createCommandConsumer(eq(TEST_TENANT_ID), eq(TEST_DEVICE), any(Handler.class), any(), any()))
        .thenReturn(Future.succeededFuture(mock(ProtocolAdapterCommandConsumer.class)));
    final String sourceAddress = String.format("%s/%s/%s", getCommandEndpoint(), TEST_TENANT_ID, TEST_DEVICE);
    final ProtonSender sender = getSender(sourceAddress);

    adapter.handleRemoteSenderOpenForCommands(deviceConnection, sender);

    // THEN the adapter opens the link upon success
    verify(sender).open();

    // AND sends an empty notification downstream (with a TTD of -1)
    final ArgumentCaptor<Message> messageCaptor = ArgumentCaptor.forClass(Message.class);
    verify(eventSender).sendAndWaitForOutcome(messageCaptor.capture(), any());
    assertThat(messageCaptor.getValue().getContentType()).isEqualTo(EventConstants.CONTENT_TYPE_EMPTY_NOTIFICATION);
    assertThat(MessageHelper.getTimeUntilDisconnect(messageCaptor.getValue())).isEqualTo(-1);
}
 
Example #7
Source File: ProtonConnectionImplTest.java    From vertx-proton with Apache License 2.0 5 votes vote down vote up
@Test
public void testAttachments() {
  ProtonConnectionImpl conn = new ProtonConnectionImpl(vertx, "hostname", null);

  Record attachments = conn.attachments();
  assertNotNull("Expected attachments but got null", attachments);
  assertSame("Got different attachments on subsequent call", attachments, conn.attachments());

  String key = "My-Vertx-Key";

  assertNull("Expected attachment to be null", attachments.get(key, Vertx.class));
  attachments.set(key, Vertx.class, vertx);
  assertNotNull("Expected attachment to be returned", attachments.get(key, Vertx.class));
  assertSame("Expected attachment to be given object", vertx, attachments.get(key, Vertx.class));
}
 
Example #8
Source File: DeliveryImplTest.java    From qpid-proton-j with Apache License 2.0 5 votes vote down vote up
@Test
public void testAttachmentsReturnsSameRecordOnSuccessiveCalls() throws Exception
{
    DeliveryImpl delivery = new DeliveryImpl(null, Mockito.mock(LinkImpl.class), null);

    Record attachments = delivery.attachments();
    Record attachments2 = delivery.attachments();
    assertSame("Expected to get the same attachments", attachments, attachments2);
}
 
Example #9
Source File: ReactorImpl.java    From qpid-proton-j with Apache License 2.0 5 votes vote down vote up
@Override
public String getConnectionAddress(Connection connection) {
    Record r = connection.attachments();
    Address addr = r.get(CONNECTION_PEER_ADDRESS_KEY, Address.class);
    if (addr != null) {
        StringBuilder sb = new StringBuilder(addr.getHost());
        if (addr.getPort() != null)
            sb.append(":" + addr.getPort());
        return sb.toString();
    }
    return null;
}
 
Example #10
Source File: DeliveryImpl.java    From qpid-proton-j with Apache License 2.0 5 votes vote down vote up
@Override
public Record attachments()
{
    if(_attachments == null)
    {
        _attachments = new RecordImpl();
    }

    return _attachments;
}
 
Example #11
Source File: Constants.java    From hono with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Gets the principal representing an authenticated peer.
 *
 * @param record The attachments to retrieve the principal from.
 * @return The principal representing the authenticated client or {@link Constants#PRINCIPAL_ANONYMOUS}
 *         if the client has not been authenticated or record is {@code null}.
 */
public static HonoUser getClientPrincipal(final Record record) {

    if (record != null) {
        final HonoUser client = record.get(KEY_CLIENT_PRINCIPAL, HonoUser.class);
        return client != null ? client : PRINCIPAL_ANONYMOUS;
    } else {
        return PRINCIPAL_ANONYMOUS;
    }
}
 
Example #12
Source File: VertxBasedAmqpProtocolAdapterTest.java    From hono with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Verifies that the adapter increments the connection count when
 * a device connects and decrement the count when the device disconnects.
 */
@SuppressWarnings("unchecked")
@Test
public void testConnectionCountForAnonymousDevice() {

    // GIVEN an AMQP adapter that does not require devices to authenticate
    config.setAuthenticationRequired(false);
    final VertxBasedAmqpProtocolAdapter adapter = givenAnAmqpAdapter();

    // WHEN a device connects
    final ProtonConnection deviceConnection = mock(ProtonConnection.class);
    when(deviceConnection.attachments()).thenReturn(mock(Record.class));
    adapter.onConnectRequest(deviceConnection);
    final ArgumentCaptor<Handler<AsyncResult<ProtonConnection>>> openHandler = ArgumentCaptor.forClass(Handler.class);
    verify(deviceConnection).openHandler(openHandler.capture());
    openHandler.getValue().handle(Future.succeededFuture(deviceConnection));

    // THEN the connection count is incremented
    verify(metrics).incrementUnauthenticatedConnections();

    // WHEN the connection to the device is lost
    final ArgumentCaptor<Handler<ProtonConnection>> disconnectHandler = ArgumentCaptor.forClass(Handler.class);
    verify(deviceConnection).disconnectHandler(disconnectHandler.capture());
    disconnectHandler.getValue().handle(deviceConnection);

    // THEN the connection count is decremented
    verify(metrics).decrementUnauthenticatedConnections();

    // WHEN the device closes its connection to the adapter
    final ArgumentCaptor<Handler<AsyncResult<ProtonConnection>>> closeHandler = ArgumentCaptor.forClass(Handler.class);
    verify(deviceConnection).closeHandler(closeHandler.capture());
    closeHandler.getValue().handle(Future.succeededFuture());

    // THEN the connection count is decremented
    verify(metrics, times(2)).decrementUnauthenticatedConnections();
}
 
Example #13
Source File: VertxBasedAmqpProtocolAdapterTest.java    From hono with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Verify that if a client device closes the link for receiving commands, then the AMQP
 * adapter sends an empty notification downstream with TTD 0 and closes the command
 * consumer.
 */
@SuppressWarnings("unchecked")
@Test
public void testAdapterClosesCommandConsumerWhenDeviceClosesReceiverLink() {

    // GIVEN an AMQP adapter
    final VertxBasedAmqpProtocolAdapter adapter = givenAnAmqpAdapter();
    final Promise<ProtonDelivery> outcome = Promise.promise();
    final DownstreamSender eventSender = givenAnEventSender(outcome);

    // and a device that wants to receive commands
    final ProtocolAdapterCommandConsumer commandConsumer = mock(ProtocolAdapterCommandConsumer.class);
    when(commandConsumer.close(any())).thenReturn(Future.succeededFuture());
    when(commandConsumerFactory.createCommandConsumer(eq(TEST_TENANT_ID), eq(TEST_DEVICE), any(Handler.class), any(), any()))
        .thenReturn(Future.succeededFuture(commandConsumer));
    final String sourceAddress = String.format("%s", getCommandEndpoint());
    final ProtonSender sender = getSender(sourceAddress);
    final Device authenticatedDevice = new Device(TEST_TENANT_ID, TEST_DEVICE);
    final ProtonConnection deviceConnection = mock(ProtonConnection.class);
    final Record attachments = mock(Record.class);
    when(attachments.get(AmqpAdapterConstants.KEY_CLIENT_DEVICE, Device.class)).thenReturn(authenticatedDevice);
    when(deviceConnection.attachments()).thenReturn(attachments);
    adapter.handleRemoteSenderOpenForCommands(deviceConnection, sender);

    // WHEN the client device closes its receiver link (unsubscribe)
    final ArgumentCaptor<Handler<AsyncResult<ProtonSender>>> closeHookCaptor = ArgumentCaptor.forClass(Handler.class);
    verify(sender).closeHandler(closeHookCaptor.capture());
    closeHookCaptor.getValue().handle(null);

    // THEN the adapter closes the command consumer
    verify(commandConsumer).close(any());

    // AND sends an empty notification downstream
    final ArgumentCaptor<Message> messageCaptor = ArgumentCaptor.forClass(Message.class);
    verify(eventSender, times(2)).sendAndWaitForOutcome(messageCaptor.capture(), any());
    assertThat(messageCaptor.getValue().getContentType()).isEqualTo(EventConstants.CONTENT_TYPE_EMPTY_NOTIFICATION);
    assertThat(MessageHelper.getTimeUntilDisconnect(messageCaptor.getValue())).isEqualTo(0);
}
 
Example #14
Source File: AmqpServiceBaseTest.java    From hono with Eclipse Public License 2.0 5 votes vote down vote up
private static ProtonConnection newConnection(final HonoUser user) {
    final Record attachments = new RecordImpl();
    attachments.set(Constants.KEY_CONNECTION_ID, String.class, CON_ID);
    attachments.set(Constants.KEY_CLIENT_PRINCIPAL, HonoUser.class, user);
    final ProtonConnection con = mock(ProtonConnection.class);
    when(con.attachments()).thenReturn(attachments);
    when(con.getRemoteContainer()).thenReturn("test-client");
    return con;
}
 
Example #15
Source File: VertxBasedAmqpProtocolAdapterTest.java    From hono with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Verifies that the connection is rejected as the connection limit for 
 * the adapter is exceeded.
 */
@Test
public void testConnectionFailsIfAdapterLevelConnectionLimitIsExceeded() {
    // GIVEN an AMQP adapter that requires devices to authenticate
    config.setAuthenticationRequired(true);
    final VertxBasedAmqpProtocolAdapter adapter = givenAnAmqpAdapter();
    // WHEN the adapter's connection limit exceeds
    when(connectionLimitManager.isLimitExceeded()).thenReturn(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 connection count should be incremented when the connection is opened
    final InOrder metricsInOrderVerifier = inOrder(metrics);
    metricsInOrderVerifier.verify(metrics).incrementConnections(TEST_TENANT_ID);
    // AND the adapter should close the connection right after it opened it
    final ArgumentCaptor<Handler<AsyncResult<ProtonConnection>>> closeHandler = ArgumentCaptor.forClass(Handler.class);
    verify(deviceConnection).closeHandler(closeHandler.capture());
    closeHandler.getValue().handle(Future.succeededFuture());
    final ArgumentCaptor<ErrorCondition> errorConditionCaptor = ArgumentCaptor.forClass(ErrorCondition.class);
    verify(deviceConnection).setCondition(errorConditionCaptor.capture());
    assertEquals(AmqpError.UNAUTHORIZED_ACCESS, errorConditionCaptor.getValue().getCondition());
    // AND the connection count should be decremented accordingly when the connection is closed
    metricsInOrderVerifier.verify(metrics).decrementConnections(TEST_TENANT_ID);
    verify(metrics).reportConnectionAttempt(ConnectionAttemptOutcome.ADAPTER_CONNECTION_LIMIT_EXCEEDED);
}
 
Example #16
Source File: VertxBasedAmqpProtocolAdapterTest.java    From hono with Eclipse Public License 2.0 5 votes vote down vote up
private ProtonConnection getConnection(final Device device) {
    final ProtonConnection conn = mock(ProtonConnection.class);
    final Record record = mock(Record.class);
    when(record.get(anyString(), eq(Device.class))).thenReturn(device);
    when(conn.attachments()).thenReturn(record);
    return conn;
}
 
Example #17
Source File: TaskImpl.java    From qpid-proton-j with Apache License 2.0 4 votes vote down vote up
@Override
public Record attachments() {
    return attachments;
}
 
Example #18
Source File: ProtonSessionImpl.java    From vertx-proton with Apache License 2.0 4 votes vote down vote up
@Override
public Record attachments() {
  return session.attachments();
}
 
Example #19
Source File: ProtonConnectionImpl.java    From vertx-proton with Apache License 2.0 4 votes vote down vote up
@Override
public Record attachments() {
  return connection.attachments();
}
 
Example #20
Source File: ProtonLinkImpl.java    From vertx-proton with Apache License 2.0 4 votes vote down vote up
@Override
public Record attachments() {
  return link.attachments();
}
 
Example #21
Source File: ProtonDeliveryImpl.java    From vertx-proton with Apache License 2.0 4 votes vote down vote up
@Override
public Record attachments() {
  return delivery.attachments();
}
 
Example #22
Source File: VertxBasedAmqpProtocolAdapterTest.java    From hono with Eclipse Public License 2.0 4 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.
 */
@SuppressWarnings("unchecked")
private void testAdapterClosesCommandConsumer(
        final VertxTestContext ctx,
        final Handler<ProtonConnection> connectionLossTrigger) throws InterruptedException {

    // GIVEN an AMQP adapter
    final Promise<ProtonDelivery> outcome = Promise.promise();
    outcome.complete();
    final DownstreamSender downstreamEventSender = givenAnEventSender(outcome);
    final ProtonServer server = getAmqpServer();
    final VertxBasedAmqpProtocolAdapter adapter = getAdapter(server);

    final Promise<Void> startupTracker = Promise.promise();
    startupTracker.future().onComplete(ctx.completing());
    adapter.start(startupTracker);
    assertThat(ctx.awaitCompletion(2, TimeUnit.SECONDS)).isTrue();

    // to which a device is connected
    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);
    final ArgumentCaptor<Handler<ProtonConnection>> connectHandler = ArgumentCaptor.forClass(Handler.class);
    verify(server).connectHandler(connectHandler.capture());
    connectHandler.getValue().handle(deviceConnection);

    // that wants to receive commands
    final ProtocolAdapterCommandConsumer commandConsumer = mock(ProtocolAdapterCommandConsumer.class);
    when(commandConsumer.close(any())).thenReturn(Future.succeededFuture());
    when(commandConsumerFactory.createCommandConsumer(eq(TEST_TENANT_ID), eq(TEST_DEVICE), any(Handler.class), any(), any()))
        .thenReturn(Future.succeededFuture(commandConsumer));
    final String sourceAddress = getCommandEndpoint();
    final ProtonSender sender = getSender(sourceAddress);

    adapter.handleRemoteSenderOpenForCommands(deviceConnection, sender);

    // WHEN the connection to the device is lost
    connectionLossTrigger.handle(deviceConnection);

    // THEN the adapter closes the command consumer
    verify(commandConsumer).close(any());
    // and sends an empty event with TTD = 0 downstream
    final ArgumentCaptor<Message> messageCaptor = ArgumentCaptor.forClass(Message.class);
    verify(downstreamEventSender, times(2)).sendAndWaitForOutcome(messageCaptor.capture(), any());
    assertThat(messageCaptor.getValue().getContentType()).isEqualTo(EventConstants.CONTENT_TYPE_EMPTY_NOTIFICATION);
    assertThat(MessageHelper.getTimeUntilDisconnect(messageCaptor.getValue())).isEqualTo(0);
}
 
Example #23
Source File: VertxBasedAmqpProtocolAdapterTest.java    From hono with Eclipse Public License 2.0 4 votes vote down vote up
/**
 * Verifies that the adapter increments the connection count when
 * a device connects and decrement the count when the device disconnects.
 */
@SuppressWarnings("unchecked")
@Test
public void testConnectionCount() {

    // GIVEN an AMQP adapter
    final ConnectionEventProducer connectionEventProducer = mock(ConnectionEventProducer.class);
    when(connectionEventProducer.connected(
            any(ConnectionEventProducer.Context.class),
            anyString(),
            anyString(),
            any(),
            any())).thenReturn(Future.succeededFuture());
    when(connectionEventProducer.disconnected(
            any(ConnectionEventProducer.Context.class),
            anyString(),
            anyString(),
            any(),
            any())).thenReturn(Future.succeededFuture());
    final VertxBasedAmqpProtocolAdapter adapter = givenAnAmqpAdapter();
    adapter.setConnectionEventProducer(connectionEventProducer);

    // 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);
    when(deviceConnection.getRemoteContainer()).thenReturn("deviceContainer");
    adapter.onConnectRequest(deviceConnection);
    final ArgumentCaptor<Handler<AsyncResult<ProtonConnection>>> openHandler = ArgumentCaptor.forClass(Handler.class);
    verify(deviceConnection).openHandler(openHandler.capture());
    openHandler.getValue().handle(Future.succeededFuture(deviceConnection));

    // THEN the connection count is incremented
    verify(metrics).incrementConnections(TEST_TENANT_ID);
    // and a connected event has been fired
    verify(connectionEventProducer).connected(
            any(ConnectionEventProducer.Context.class),
            anyString(),
            eq(adapter.getTypeName()),
            eq(authenticatedDevice),
            any());

    // WHEN the connection to the device is lost
    final ArgumentCaptor<Handler<ProtonConnection>> disconnectHandler = ArgumentCaptor.forClass(Handler.class);
    verify(deviceConnection).disconnectHandler(disconnectHandler.capture());
    disconnectHandler.getValue().handle(deviceConnection);

    // THEN the connection count is decremented
    verify(metrics).decrementConnections(TEST_TENANT_ID);
    // and a disconnected event has been fired
    verify(connectionEventProducer).disconnected(
            any(ConnectionEventProducer.Context.class),
            eq("deviceContainer"),
            eq(adapter.getTypeName()),
            eq(authenticatedDevice),
            any());

    // WHEN the device closes its connection to the adapter
    final ArgumentCaptor<Handler<AsyncResult<ProtonConnection>>> closeHandler = ArgumentCaptor.forClass(Handler.class);
    verify(deviceConnection).closeHandler(closeHandler.capture());
    closeHandler.getValue().handle(Future.succeededFuture());

    // THEN the connection count is decremented
    verify(metrics, times(2)).decrementConnections(TEST_TENANT_ID);
    // and a disconnected event has been fired
    verify(connectionEventProducer, times(2)).disconnected(
            any(ConnectionEventProducer.Context.class),
            eq("deviceContainer"),
            eq(adapter.getTypeName()),
            eq(authenticatedDevice),
            any());
}
 
Example #24
Source File: ReactorImpl.java    From qpid-proton-j with Apache License 2.0 4 votes vote down vote up
@Override
public Record attachments() {
    return attachments;
}
 
Example #25
Source File: SelectableImpl.java    From qpid-proton-j with Apache License 2.0 4 votes vote down vote up
@Override
public Record attachments() {
    return attachments;
}
 
Example #26
Source File: AcceptorImpl.java    From qpid-proton-j with Apache License 2.0 4 votes vote down vote up
@Override
public Record attachments() {
    return attachments;
}
 
Example #27
Source File: AcceptorImpl.java    From qpid-proton-j with Apache License 2.0 4 votes vote down vote up
@Override
public void run(Selectable selectable) {
    Reactor reactor = selectable.getReactor();
    try {
        SocketChannel socketChannel = ((ServerSocketChannel)selectable.getChannel()).accept();
        if (socketChannel == null) {
            throw new ReactorInternalException("Selectable readable, but no socket to accept");
        }
        Handler handler = BaseHandler.getHandler(AcceptorImpl.this);
        if (handler == null) {
            handler = reactor.getHandler();
        }
        Connection conn = reactor.connection(handler);
        Record conn_recs = conn.attachments();
        conn_recs.set(CONNECTION_ACCEPTOR_KEY, Acceptor.class, AcceptorImpl.this);
        InetSocketAddress peerAddr = (InetSocketAddress)socketChannel.getRemoteAddress();
        if (peerAddr != null) {
            Address addr = new Address();
            addr.setHost(peerAddr.getHostString());
            addr.setPort(Integer.toString(peerAddr.getPort()));
            conn_recs.set(ReactorImpl.CONNECTION_PEER_ADDRESS_KEY, Address.class, addr);
        }
        Transport trans = Proton.transport();

        int maxFrameSizeOption = reactor.getOptions().getMaxFrameSize();
        if (maxFrameSizeOption != 0) {
            trans.setMaxFrameSize(maxFrameSizeOption);
        }

        if(reactor.getOptions().isEnableSaslByDefault()) {
            Sasl sasl = trans.sasl();
            sasl.server();
            sasl.setMechanisms("ANONYMOUS");
            sasl.done(SaslOutcome.PN_SASL_OK);
        }
        trans.bind(conn);
        IOHandler.selectableTransport(reactor, socketChannel.socket(), trans);
    } catch(IOException ioException) {
        sel.error();
    }
}
 
Example #28
Source File: EventImpl.java    From qpid-proton-j with Apache License 2.0 4 votes vote down vote up
@Override
public Record attachments() {
    return attachments;
}
 
Example #29
Source File: EndpointImpl.java    From qpid-proton-j with Apache License 2.0 4 votes vote down vote up
@Override
public Record attachments()
{
    return _attachments;
}
 
Example #30
Source File: Constants.java    From hono with Eclipse Public License 2.0 2 votes vote down vote up
/**
 * Gets the principal representing a connection's client.
 *
 * @param con The connection to get the principal for.
 * @return The principal representing the authenticated client or {@link Constants#PRINCIPAL_ANONYMOUS}
 *         if the client has not been authenticated.
 * @throws NullPointerException if the connection is {@code null}.
 */
public static HonoUser getClientPrincipal(final ProtonConnection con) {
    final Record attachments = Objects.requireNonNull(con).attachments();
    return getClientPrincipal(attachments);
}