Java Code Examples for org.apache.qpid.proton.engine.Record#set()

The following examples show how to use org.apache.qpid.proton.engine.Record#set() . 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: 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 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 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 4
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 5
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 6
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 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: 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 9
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 10
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 11
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.
 * @param principal The principal representing the authenticated client.
 * @throws NullPointerException if any of the parameters is {@code null}.
 */
public static void setClientPrincipal(final ProtonConnection con, final HonoUser principal) {
    Objects.requireNonNull(principal);
    final Record attachments = Objects.requireNonNull(con).attachments();
    attachments.set(KEY_CLIENT_PRINCIPAL, HonoUser.class, principal);
}