Search in sources :

Example 1 with ProtonClient

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

the class TestSupport method openConnection.

public static ProtonConnection openConnection(final TestContext ctx, final Vertx vertx, final String host, final int port) {
    final Async connected = ctx.async();
    final AtomicReference<ProtonConnection> protonConnection = new AtomicReference<>();
    final ProtonClient client = ProtonClient.create(vertx);
    client.connect(host, port, ar -> {
        if (ar.succeeded()) {
            protonConnection.set(ar.result());
            protonConnection.get().setContainer(CLIENT_CONTAINER).open();
            connected.complete();
        } else {
            ctx.fail(ar.cause());
        }
    });
    connected.awaitSuccess(2000);
    return protonConnection.get();
}
Also used : ProtonConnection(io.vertx.proton.ProtonConnection) Async(io.vertx.ext.unit.Async) AtomicReference(java.util.concurrent.atomic.AtomicReference) ProtonClient(io.vertx.proton.ProtonClient)

Example 2 with ProtonClient

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

the class ConnectionFactoryImpl method connect.

@Override
public void connect(final ProtonClientOptions options, final String username, final String password, final Handler<AsyncResult<ProtonConnection>> closeHandler, final Handler<ProtonConnection> disconnectHandler, final Handler<AsyncResult<ProtonConnection>> connectionResultHandler) {
    if (vertx == null) {
        throw new IllegalStateException("Vert.x instance must be set");
    } else if (config == null) {
        throw new IllegalStateException("Client configuration must be set");
    }
    Objects.requireNonNull(connectionResultHandler);
    final ProtonClientOptions clientOptions = options != null ? options : createClientOptions();
    final String effectiveUsername = username == null ? config.getUsername() : username;
    final String effectivePassword = password == null ? config.getPassword() : password;
    addOptions(clientOptions, effectiveUsername, effectivePassword);
    final ProtonClient client = protonClient != null ? protonClient : ProtonClient.create(vertx);
    logger.debug("connecting to AMQP 1.0 container [{}://{}:{}]", clientOptions.isSsl() ? "amqps" : "amqp", config.getHost(), config.getPort());
    client.connect(clientOptions, config.getHost(), config.getPort(), effectiveUsername, effectivePassword, conAttempt -> handleConnectionAttemptResult(conAttempt, clientOptions, closeHandler, disconnectHandler, connectionResultHandler));
}
Also used : ProtonClientOptions(io.vertx.proton.ProtonClientOptions) ProtonClient(io.vertx.proton.ProtonClient)

Example 3 with ProtonClient

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

the class ConnectionFactoryImplTest method testConnectEnablesSslIfExplicitlyConfigured.

/**
 * Verifies that the factory uses TLS when connecting to the peer if no trust store
 * is configured but TLS has been enabled explicitly.
 */
@SuppressWarnings("unchecked")
@Test
public void testConnectEnablesSslIfExplicitlyConfigured() {
    // GIVEN a factory configured to connect to a server using TLS
    final ClientConfigProperties config = new ClientConfigProperties();
    config.setHost("remote.host");
    config.setTlsEnabled(true);
    final ProtonClient client = mock(ProtonClient.class);
    final ConnectionFactoryImpl factory = new ConnectionFactoryImpl(vertx, config);
    factory.setProtonClient(client);
    // WHEN connecting to the server
    factory.connect(null, null, null, c -> {
    });
    // THEN the factory uses TLS when establishing the connection
    final ArgumentCaptor<ProtonClientOptions> optionsCaptor = ArgumentCaptor.forClass(ProtonClientOptions.class);
    verify(client).connect(optionsCaptor.capture(), eq("remote.host"), anyInt(), any(), any(), any(Handler.class));
    assertTrue(optionsCaptor.getValue().isSsl());
}
Also used : Handler(io.vertx.core.Handler) ClientConfigProperties(org.eclipse.hono.config.ClientConfigProperties) ProtonClientOptions(io.vertx.proton.ProtonClientOptions) ProtonClient(io.vertx.proton.ProtonClient) Test(org.junit.Test)

Example 4 with ProtonClient

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

the class ConnectionFactoryImplTest method testConnectAddsSaslPlainForNonEmptyUsernameAndPassword.

/**
 * Verifies that the factory enables SASL_PLAIN if the username and password are non-empty
 * strings.
 *
 * @param ctx The vert.x test context.
 */
@SuppressWarnings("unchecked")
@Test
public void testConnectAddsSaslPlainForNonEmptyUsernameAndPassword(final TestContext ctx) {
    // GIVEN a factory configured to connect to a server
    final ProtonClientOptions options = new ProtonClientOptions();
    final ProtonClient client = mock(ProtonClient.class);
    final ConnectionFactoryImpl factory = new ConnectionFactoryImpl(vertx, props);
    factory.setProtonClient(client);
    // WHEN connecting to the server using non-empty strings for username and password
    factory.connect(options, "user", "pw", null, null, c -> {
    });
    // THEN the factory uses SASL_PLAIN when establishing the connection
    ArgumentCaptor<ProtonClientOptions> optionsCaptor = ArgumentCaptor.forClass(ProtonClientOptions.class);
    verify(client).connect(optionsCaptor.capture(), anyString(), anyInt(), eq("user"), eq("pw"), any(Handler.class));
    assertTrue(optionsCaptor.getValue().getEnabledSaslMechanisms().contains("PLAIN"));
}
Also used : Handler(io.vertx.core.Handler) ProtonClientOptions(io.vertx.proton.ProtonClientOptions) ProtonClient(io.vertx.proton.ProtonClient) Test(org.junit.Test)

Example 5 with ProtonClient

use of io.vertx.proton.ProtonClient in project enmasse-workshop by EnMasseProject.

the class TemperatureAnalyzer method createStreamingContext.

private static JavaStreamingContext createStreamingContext() {
    SparkConf conf = new SparkConf().setAppName(APP_NAME);
    // conf.setMaster("local[2]");
    conf.set("spark.streaming.receiver.writeAheadLog.enable", "true");
    JavaStreamingContext ssc = new JavaStreamingContext(conf, BATCH_DURATION);
    ssc.checkpoint(CHECKPOINT_DIR);
    JavaReceiverInputDStream<DeviceTemperature> receiveStream = AMQPUtils.createStream(ssc, host, port, Option.apply(username), Option.apply(password), temperatureAddress, message -> {
        Section section = message.getBody();
        if (section instanceof AmqpValue) {
            Object value = ((AmqpValue) section).getValue();
            DeviceTemperature deviceTemperature = DeviceTemperature.fromJson(value.toString());
            return new Some<>(deviceTemperature);
        } else if (section instanceof Data) {
            Binary data = ((Data) section).getValue();
            DeviceTemperature deviceTemperature = DeviceTemperature.fromJson(new String(data.getArray(), "UTF-8"));
            return new Some<>(deviceTemperature);
        } else {
            return null;
        }
    }, StorageLevel.MEMORY_ONLY());
    // from a stream with DeviceTemperature instace to a pair stream with key = device-id, value = temperature
    JavaPairDStream<String, Integer> temperaturesByDevice = receiveStream.mapToPair(deviceTemperature -> {
        return new Tuple2<>(deviceTemperature.deviceId(), deviceTemperature.temperature());
    });
    // reducing the pair stream by key (device-id) for getting max temperature value
    JavaPairDStream<String, Integer> max = temperaturesByDevice.reduceByKeyAndWindow((a, b) -> {
        if (a > b)
            return a;
        else
            return b;
    }, new Duration(5000), new Duration(5000));
    // max.print();
    Broadcast<String> messagingHost = ssc.sparkContext().broadcast(host);
    Broadcast<Integer> messagingPort = ssc.sparkContext().broadcast(port);
    Broadcast<String> driverUsername = ssc.sparkContext().broadcast(username);
    Broadcast<String> driverPassword = ssc.sparkContext().broadcast(password);
    max.foreachRDD(rdd -> {
        rdd.foreach(record -> {
            // building a DeviceTemperature instance from the pair key = device-id, value = temperature
            DeviceTemperature deviceTemperature = new DeviceTemperature(record._1(), record._2());
            Vertx vertx = Vertx.vertx();
            ProtonClient client = ProtonClient.create(vertx);
            log.info("Connecting to messaging ...");
            client.connect(messagingHost.value(), messagingPort.value(), driverUsername.value(), driverPassword.value(), done -> {
                if (done.succeeded()) {
                    log.info("... connected to {}:{}", messagingHost.value(), messagingPort.getValue());
                    ProtonConnection connection = done.result();
                    connection.open();
                    ProtonSender maxSender = connection.createSender(maxAddress);
                    maxSender.open();
                    Message message = ProtonHelper.message();
                    message.setAddress(maxAddress);
                    message.setBody(new Data(new Binary(deviceTemperature.toJson().toString().getBytes())));
                    log.info("Sending {} to max address ...", deviceTemperature);
                    maxSender.send(message, maxDelivery -> {
                        log.info("... message sent");
                        maxSender.close();
                        connection.close();
                        vertx.close();
                    });
                } else {
                    log.error("Error on AMQP connection for sending", done.cause());
                    vertx.close();
                }
            });
        });
    });
    return ssc;
}
Also used : Message(org.apache.qpid.proton.message.Message) Data(org.apache.qpid.proton.amqp.messaging.Data) Duration(org.apache.spark.streaming.Duration) Vertx(io.vertx.core.Vertx) ProtonClient(io.vertx.proton.ProtonClient) Section(org.apache.qpid.proton.amqp.messaging.Section) AmqpValue(org.apache.qpid.proton.amqp.messaging.AmqpValue) JavaStreamingContext(org.apache.spark.streaming.api.java.JavaStreamingContext) ProtonConnection(io.vertx.proton.ProtonConnection) ProtonSender(io.vertx.proton.ProtonSender) Some(scala.Some) Tuple2(scala.Tuple2) Binary(org.apache.qpid.proton.amqp.Binary) SparkConf(org.apache.spark.SparkConf)

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