Search in sources :

Example 11 with ProtonConnection

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

the class AmqpServiceBase method setRemoteConnectionOpenHandler.

private void setRemoteConnectionOpenHandler(final ProtonConnection connection) {
    connection.sessionOpenHandler(remoteOpenSession -> handleSessionOpen(connection, remoteOpenSession));
    connection.receiverOpenHandler(remoteOpenReceiver -> handleReceiverOpen(connection, remoteOpenReceiver));
    connection.senderOpenHandler(remoteOpenSender -> handleSenderOpen(connection, remoteOpenSender));
    connection.disconnectHandler(this::handleRemoteDisconnect);
    connection.closeHandler(remoteClose -> handleRemoteConnectionClose(connection, remoteClose));
    connection.openHandler(remoteOpen -> {
        final HonoUser clientPrincipal = Constants.getClientPrincipal(connection);
        LOG.debug("client [container: {}, user: {}] connected", connection.getRemoteContainer(), clientPrincipal.getName());
        // attach an ID so that we can later inform downstream components when connection is closed
        connection.attachments().set(Constants.KEY_CONNECTION_ID, String.class, UUID.randomUUID().toString());
        final Duration delay = Duration.between(Instant.now(), clientPrincipal.getExpirationTime());
        final WeakReference<ProtonConnection> conRef = new WeakReference<>(connection);
        vertx.setTimer(delay.toMillis(), timerId -> {
            if (conRef.get() != null) {
                closeExpiredConnection(conRef.get());
            }
        });
        connection.open();
    });
}
Also used : ProtonConnection(io.vertx.proton.ProtonConnection) HonoUser(org.eclipse.hono.auth.HonoUser) WeakReference(java.lang.ref.WeakReference) Duration(java.time.Duration)

Example 12 with ProtonConnection

use of io.vertx.proton.ProtonConnection 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)

Example 13 with ProtonConnection

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

the class ProtonServerImpl method connectHandler.

@Override
public ProtonServerImpl connectHandler(Handler<ProtonConnection> handler) {
    this.handler = handler;
    server.connectHandler(netSocket -> {
        String hostname = null;
        try {
            hostname = InetAddress.getLocalHost().getHostName();
        } catch (UnknownHostException e) {
        // ignore
        }
        final ProtonConnectionImpl connection = new ProtonConnectionImpl(vertx, hostname, (ContextInternal) Vertx.currentContext());
        if (advertiseAnonymousRelayCapability) {
            connection.setOfferedCapabilities(new Symbol[] { ProtonConnectionImpl.ANONYMOUS_RELAY });
        }
        final ProtonSaslAuthenticator authenticator = authenticatorFactory.create();
        ProtonTransportOptions transportOptions = new ProtonTransportOptions();
        transportOptions.setHeartbeat(this.options.getHeartbeat());
        transportOptions.setMaxFrameSize(this.options.getMaxFrameSize());
        connection.bindServer(netSocket, new ProtonSaslAuthenticator() {

            @Override
            public void init(NetSocket socket, ProtonConnection protonConnection, Transport transport) {
                authenticator.init(socket, protonConnection, transport);
            }

            @Override
            public void process(Handler<Boolean> completionHandler) {
                final Context context = Vertx.currentContext();
                authenticator.process(complete -> {
                    final Context callbackContext = vertx.getOrCreateContext();
                    if (context != callbackContext) {
                        throw new IllegalStateException("Callback was not made on the original context");
                    }
                    if (complete) {
                        // The authenticator completed, now check success, do required post processing
                        if (succeeded()) {
                            handler.handle(connection);
                            connection.flush();
                        } else {
                            // auth failed, flush any pending data and disconnect client
                            connection.flush();
                            connection.disconnect();
                        }
                    }
                    completionHandler.handle(complete);
                });
            }

            @Override
            public boolean succeeded() {
                return authenticator.succeeded();
            }
        }, transportOptions);
    });
    return this;
}
Also used : NetSocket(io.vertx.core.net.NetSocket) Context(io.vertx.core.Context) ProtonConnection(io.vertx.proton.ProtonConnection) ProtonServerOptions(io.vertx.proton.ProtonServerOptions) ProtonSaslAuthenticator(io.vertx.proton.sasl.ProtonSaslAuthenticator) Vertx(io.vertx.core.Vertx) ContextInternal(io.vertx.core.impl.ContextInternal) Context(io.vertx.core.Context) Future(io.vertx.core.Future) ProtonServer(io.vertx.proton.ProtonServer) ProtonTransportOptions(io.vertx.proton.ProtonTransportOptions) UnknownHostException(java.net.UnknownHostException) Transport(org.apache.qpid.proton.engine.Transport) InetAddress(java.net.InetAddress) NetServer(io.vertx.core.net.NetServer) Symbol(org.apache.qpid.proton.amqp.Symbol) AsyncResult(io.vertx.core.AsyncResult) Handler(io.vertx.core.Handler) ProtonSaslAuthenticatorFactory(io.vertx.proton.sasl.ProtonSaslAuthenticatorFactory) NetSocket(io.vertx.core.net.NetSocket) UnknownHostException(java.net.UnknownHostException) ProtonSaslAuthenticator(io.vertx.proton.sasl.ProtonSaslAuthenticator) ProtonConnection(io.vertx.proton.ProtonConnection) ProtonTransportOptions(io.vertx.proton.ProtonTransportOptions) Transport(org.apache.qpid.proton.engine.Transport)

Example 14 with ProtonConnection

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

the class HelloWorldServer method helloProcessConnection.

private static void helloProcessConnection(Vertx vertx, ProtonConnection connection) {
    connection.openHandler(res -> {
        System.out.println("Client connected: " + connection.getRemoteContainer());
        connection.open();
    }).closeHandler(c -> {
        System.out.println("Client closing amqp connection: " + connection.getRemoteContainer());
        connection.close();
        connection.disconnect();
    }).disconnectHandler(c -> {
        System.out.println("Client socket disconnected: " + connection.getRemoteContainer());
        connection.disconnect();
    }).sessionOpenHandler(session -> session.open());
    connection.receiverOpenHandler(receiver -> {
        // This is rather naive, for example use only, proper
        receiver.setTarget(receiver.getRemoteTarget()).handler((delivery, msg) -> {
            String address = msg.getAddress();
            if (address == null) {
                address = receiver.getRemoteTarget().getAddress();
            }
            Section body = msg.getBody();
            if (body instanceof AmqpValue) {
                String content = (String) ((AmqpValue) body).getValue();
                System.out.println("message to:" + address + ", body: " + content);
            }
        }).open();
    });
    connection.senderOpenHandler(sender -> {
        System.out.println("Sending to client from: " + sender.getRemoteSource().getAddress());
        // This is rather naive, for example use only, proper
        sender.setSource(sender.getRemoteSource());
        // servers should ensure that they advertise their own
        // Source settings that actually reflect what is in place.
        // The request may have also been for a dynamic address.
        sender.open();
        vertx.setPeriodic(1000, timer -> {
            if (connection.isDisconnected()) {
                vertx.cancelTimer(timer);
            } else {
                System.out.println("Sending message to client");
                Message m = message("Hello World from Server!");
                sender.send(m, delivery -> {
                    System.out.println("The message was received by the client.");
                });
            }
        });
    });
}
Also used : ProtonConnection(io.vertx.proton.ProtonConnection) Section(org.apache.qpid.proton.amqp.messaging.Section) AmqpValue(org.apache.qpid.proton.amqp.messaging.AmqpValue) ProtonHelper.message(io.vertx.proton.ProtonHelper.message) Vertx(io.vertx.core.Vertx) Message(org.apache.qpid.proton.message.Message) ProtonServer(io.vertx.proton.ProtonServer) Message(org.apache.qpid.proton.message.Message) Section(org.apache.qpid.proton.amqp.messaging.Section) AmqpValue(org.apache.qpid.proton.amqp.messaging.AmqpValue)

Example 15 with ProtonConnection

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

the class ProtonServerImplTest method testCustomAuthenticatorHasInitCalled.

@Test(timeout = 20000)
public void testCustomAuthenticatorHasInitCalled(TestContext context) {
    Async initCalledAsync = context.async();
    ProtonServer.create(vertx).saslAuthenticatorFactory(new ProtonSaslAuthenticatorFactory() {

        @Override
        public ProtonSaslAuthenticator create() {
            return new ProtonSaslAuthenticator() {

                @Override
                public void init(NetSocket socket, ProtonConnection protonConnection, Transport transport) {
                    initCalledAsync.complete();
                }

                @Override
                public void process(Handler<Boolean> completionHandler) {
                    completionHandler.handle(false);
                }

                @Override
                public boolean succeeded() {
                    return false;
                }
            };
        }
    }).connectHandler(protonConnection -> {
    }).listen(server -> ProtonClient.create(vertx).connect("localhost", server.result().actualPort(), protonConnectionAsyncResult -> {
    }));
}
Also used : NetSocket(io.vertx.core.net.NetSocket) TestContext(io.vertx.ext.unit.TestContext) ProtonConnection(io.vertx.proton.ProtonConnection) Async(io.vertx.ext.unit.Async) ProtonSaslAuthenticator(io.vertx.proton.sasl.ProtonSaslAuthenticator) Vertx(io.vertx.core.Vertx) RunWith(org.junit.runner.RunWith) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) ProtonClient(io.vertx.proton.ProtonClient) Test(org.junit.Test) VertxUnitRunner(io.vertx.ext.unit.junit.VertxUnitRunner) Sasl(org.apache.qpid.proton.engine.Sasl) SaslOutcome(org.apache.qpid.proton.engine.Sasl.SaslOutcome) Context(io.vertx.core.Context) ProtonServer(io.vertx.proton.ProtonServer) StandardCharsets(java.nio.charset.StandardCharsets) Transport(org.apache.qpid.proton.engine.Transport) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) After(org.junit.After) Handler(io.vertx.core.Handler) ProtonSaslAuthenticatorFactory(io.vertx.proton.sasl.ProtonSaslAuthenticatorFactory) NetSocket(io.vertx.core.net.NetSocket) Before(org.junit.Before) ProtonSaslAuthenticatorFactory(io.vertx.proton.sasl.ProtonSaslAuthenticatorFactory) ProtonConnection(io.vertx.proton.ProtonConnection) Async(io.vertx.ext.unit.Async) Transport(org.apache.qpid.proton.engine.Transport) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) ProtonSaslAuthenticator(io.vertx.proton.sasl.ProtonSaslAuthenticator) Test(org.junit.Test)

Aggregations

ProtonConnection (io.vertx.proton.ProtonConnection)63 ProtonClient (io.vertx.proton.ProtonClient)37 Message (org.apache.qpid.proton.message.Message)36 Handler (io.vertx.core.Handler)35 Test (org.junit.Test)33 Async (io.vertx.ext.unit.Async)27 ProtonServer (io.vertx.proton.ProtonServer)25 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)25 AmqpValue (org.apache.qpid.proton.amqp.messaging.AmqpValue)25 AsyncResult (io.vertx.core.AsyncResult)24 TestContext (io.vertx.ext.unit.TestContext)24 VertxUnitRunner (io.vertx.ext.unit.junit.VertxUnitRunner)24 RunWith (org.junit.runner.RunWith)24 Section (org.apache.qpid.proton.amqp.messaging.Section)23 ProtonHelper.message (io.vertx.proton.ProtonHelper.message)21 Rejected (org.apache.qpid.proton.amqp.messaging.Rejected)21 ProtonStreams (io.vertx.proton.streams.ProtonStreams)20 Vertx (io.vertx.core.Vertx)19 Symbol (org.apache.qpid.proton.amqp.Symbol)19 Accepted (org.apache.qpid.proton.amqp.messaging.Accepted)19