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();
});
}
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;
}
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;
}
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.");
});
}
});
});
}
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 -> {
}));
}
Aggregations