use of io.crossbar.autobahn.wamp.types.Publication in project autobahn-java by crossbario.
the class CIService method producer.
private void producer(Session session) {
RegisterOptions options = new RegisterOptions(null, "roundrobin");
CompletableFuture<Registration> regFuture = session.register("io.crossbar.example.client2.stop_producing", this::stopProducing, options);
regFuture.whenComplete((registration, throwable) -> {
if (throwable == null) {
System.out.println("----------------------------");
System.out.println("procedure registered: io.crossbar.example.client2.add2");
}
});
final int[] counter = { 0 };
final PublishOptions publishOptions = new PublishOptions(true, true);
ScheduledExecutorService executorService = Executors.newSingleThreadScheduledExecutor();
executorService.scheduleAtFixedRate(() -> {
CompletableFuture<Publication> pubFuture = session.publish("io.crossbar.example.client2.oncounter", publishOptions, counter[0]);
pubFuture.whenComplete((publication, throwable) -> {
if (throwable == null) {
LOGGER.i("published to 'oncounter' with counter " + counter[0]);
counter[0] += 1;
} else {
LOGGER.i(String.format("ERROR - pub failed: %s", throwable.getMessage()));
}
});
if (!mProduce) {
executorService.shutdown();
try {
POJOCalls();
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
System.exit(1);
}
}
}, 0, 2, TimeUnit.SECONDS);
}
use of io.crossbar.autobahn.wamp.types.Publication in project autobahn-java by crossbario.
the class Session method onMessage.
private void onMessage(IMessage message) throws Exception {
if (message instanceof Result) {
Result msg = (Result) message;
CallRequest request = getOrDefault(mCallRequests, msg.request, null);
if (request == null) {
throw new ProtocolError(String.format("RESULT received for non-pending request ID %s", msg.request));
}
mCallRequests.remove(msg.request);
if (request.resultTypeRef != null) {
// FIXME: check args length > 1 and == 0, and kwargs != null
// we cannot currently POJO automap these cases!
request.onReply.complete(mSerializer.convertValue(msg.args.get(0), request.resultTypeRef));
} else if (request.resultTypeClass != null) {
request.onReply.complete(mSerializer.convertValue(msg.args.get(0), request.resultTypeClass));
} else {
request.onReply.complete(new CallResult(msg.args, msg.kwargs));
}
} else if (message instanceof Subscribed) {
Subscribed msg = (Subscribed) message;
SubscribeRequest request = getOrDefault(mSubscribeRequests, msg.request, null);
if (request == null) {
throw new ProtocolError(String.format("SUBSCRIBED received for non-pending request ID %s", msg.request));
}
mSubscribeRequests.remove(msg.request);
if (!mSubscriptions.containsKey(msg.subscription)) {
mSubscriptions.put(msg.subscription, new ArrayList<>());
}
Subscription subscription = new Subscription(msg.subscription, request.topic, request.resultTypeRef, request.resultTypeClass, request.handler, this);
mSubscriptions.get(msg.subscription).add(subscription);
request.onReply.complete(subscription);
} else if (message instanceof Event) {
Event msg = (Event) message;
List<Subscription> subscriptions = getOrDefault(mSubscriptions, msg.subscription, null);
if (subscriptions == null) {
throw new ProtocolError(String.format("EVENT received for non-subscribed subscription ID %s", msg.subscription));
}
List<CompletableFuture<?>> futures = new ArrayList<>();
for (Subscription subscription : subscriptions) {
EventDetails details = new EventDetails(subscription, msg.publication, msg.topic != null ? msg.topic : subscription.topic, msg.retained, -1, null, null, this);
CompletableFuture future = null;
// Check if we expect a POJO.
Object arg;
if (subscription.resultTypeRef != null) {
arg = mSerializer.convertValue(msg.args.get(0), subscription.resultTypeRef);
} else if (subscription.resultTypeClass != null) {
arg = mSerializer.convertValue(msg.args.get(0), subscription.resultTypeClass);
} else {
arg = msg.args;
}
if (subscription.handler instanceof Consumer) {
Consumer handler = (Consumer) subscription.handler;
future = runAsync(() -> handler.accept(arg), mExecutor);
} else if (subscription.handler instanceof Function) {
Function handler = (Function) subscription.handler;
future = runAsync(() -> handler.apply(arg), mExecutor);
} else if (subscription.handler instanceof BiConsumer) {
BiConsumer handler = (BiConsumer) subscription.handler;
future = runAsync(() -> handler.accept(arg, details), mExecutor);
} else if (subscription.handler instanceof BiFunction) {
BiFunction handler = (BiFunction) subscription.handler;
future = runAsync(() -> handler.apply(arg, details), mExecutor);
} else if (subscription.handler instanceof TriConsumer) {
TriConsumer handler = (TriConsumer) subscription.handler;
future = runAsync(() -> handler.accept(arg, msg.kwargs, details), mExecutor);
} else if (subscription.handler instanceof TriFunction) {
TriFunction handler = (TriFunction) subscription.handler;
future = runAsync(() -> handler.apply(arg, msg.kwargs, details), mExecutor);
} else {
// FIXME: never going to reach here, though would be better to throw.
}
futures.add(future);
}
// Not really doing anything with the combined futures.
combineFutures(futures);
} else if (message instanceof Published) {
Published msg = (Published) message;
PublishRequest request = getOrDefault(mPublishRequests, msg.request, null);
if (request == null) {
throw new ProtocolError(String.format("PUBLISHED received for non-pending request ID %s", msg.request));
}
mPublishRequests.remove(msg.request);
Publication publication = new Publication(msg.publication);
request.onReply.complete(publication);
} else if (message instanceof Registered) {
Registered msg = (Registered) message;
RegisterRequest request = getOrDefault(mRegisterRequest, msg.request, null);
if (request == null) {
throw new ProtocolError(String.format("REGISTERED received for already existing registration ID %s", msg.request));
}
mRegisterRequest.remove(msg.request);
Registration registration = new Registration(msg.registration, request.procedure, request.endpoint, this);
mRegistrations.put(msg.registration, registration);
request.onReply.complete(registration);
} else if (message instanceof Invocation) {
Invocation msg = (Invocation) message;
Registration registration = getOrDefault(mRegistrations, msg.registration, null);
if (registration == null) {
throw new ProtocolError(String.format("INVOCATION received for non-registered registration ID %s", msg.registration));
}
InvocationDetails details = new InvocationDetails(registration, registration.procedure, -1, null, null, this);
runAsync(() -> {
Object result;
if (registration.endpoint instanceof Supplier) {
Supplier endpoint = (Supplier) registration.endpoint;
result = endpoint.get();
} else if (registration.endpoint instanceof Function) {
Function endpoint = (Function) registration.endpoint;
result = endpoint.apply(msg.args);
} else if (registration.endpoint instanceof BiFunction) {
BiFunction endpoint = (BiFunction) registration.endpoint;
result = endpoint.apply(msg.args, details);
} else if (registration.endpoint instanceof TriFunction) {
TriFunction endpoint = (TriFunction) registration.endpoint;
result = endpoint.apply(msg.args, msg.kwargs, details);
} else {
IInvocationHandler endpoint = (IInvocationHandler) registration.endpoint;
result = endpoint.apply(msg.args, msg.kwargs, details);
}
if (result instanceof CompletableFuture) {
CompletableFuture<InvocationResult> fResult = (CompletableFuture<InvocationResult>) result;
fResult.whenCompleteAsync((invocRes, throwable) -> {
if (throwable != null) {
if (throwable instanceof WampException) {
WampException casted = (WampException) throwable;
send(new Error(Invocation.MESSAGE_TYPE, msg.request, casted.getErrorUri(), casted.getArguments(), casted.getKwArguments()));
} else {
List<Object> args = new ArrayList<>();
args.add(throwable.getMessage());
send(new Error(Invocation.MESSAGE_TYPE, msg.request, "wamp.error.runtime_error", args, null));
}
} else {
send(new Yield(msg.request, invocRes.results, invocRes.kwresults));
}
}, mExecutor);
} else if (result instanceof InvocationResult) {
InvocationResult res = (InvocationResult) result;
send(new Yield(msg.request, res.results, res.kwresults));
} else if (result instanceof List) {
send(new Yield(msg.request, (List) result, null));
} else if (result instanceof Map) {
send(new Yield(msg.request, null, (Map) result));
} else if (result instanceof Void) {
send(new Yield(msg.request, null, null));
} else {
List<Object> item = new ArrayList<>();
item.add(result);
send(new Yield(msg.request, item, null));
}
}, mExecutor).whenCompleteAsync((aVoid, throwable) -> {
// FIXME: implement better errors
if (throwable != null) {
if (throwable instanceof WampException) {
WampException casted = (WampException) throwable;
send(new Error(Invocation.MESSAGE_TYPE, msg.request, casted.getErrorUri(), casted.getArguments(), casted.getKwArguments()));
} else {
List<Object> args = new ArrayList<>();
args.add(throwable.getMessage());
send(new Error(Invocation.MESSAGE_TYPE, msg.request, "wamp.error.runtime_error", args, null));
}
}
});
} else if (message instanceof Goodbye) {
Goodbye msg = (Goodbye) message;
CloseDetails details = new CloseDetails(msg.reason, msg.message);
List<CompletableFuture<?>> futures = new ArrayList<>();
for (OnLeaveListener listener : mOnLeaveListeners) {
futures.add(runAsync(() -> listener.onLeave(this, details), mExecutor));
}
CompletableFuture d = combineFutures(futures);
d.thenRunAsync(() -> {
LOGGER.d("Notified Session.onLeave listeners, now closing transport");
if (mTransport != null && mTransport.isOpen()) {
try {
mTransport.close();
} catch (Exception e) {
throw new CompletionException(e);
}
}
mState = STATE_DISCONNECTED;
}, mExecutor);
} else if (message instanceof Unregistered) {
Unregistered msg = (Unregistered) message;
UnregisterRequest request = getOrDefault(mUnregisterRequests, msg.request, null);
if (request == null) {
throw new ProtocolError(String.format("UNREGISTERED received for already unregistered registration ID %s", msg.registration));
}
if (mRegistrations.containsKey(request.registrationID)) {
mRegistrations.remove(request.registrationID);
}
request.onReply.complete(0);
} else if (message instanceof Unsubscribed) {
Unsubscribed msg = (Unsubscribed) message;
UnsubscribeRequest request = getOrDefault(mUnsubscribeRequests, msg.request, null);
List<Subscription> subscriptions = mSubscriptions.get(request.subscriptionID);
request.onReply.complete(subscriptions.size());
} else if (message instanceof Error) {
Error msg = (Error) message;
CompletableFuture<?> onReply = null;
if (msg.requestType == Call.MESSAGE_TYPE && mCallRequests.containsKey(msg.request)) {
onReply = mCallRequests.get(msg.request).onReply;
mCallRequests.remove(msg.request);
} else if (msg.requestType == Publish.MESSAGE_TYPE && mPublishRequests.containsKey(msg.request)) {
onReply = mPublishRequests.get(msg.request).onReply;
mPublishRequests.remove(msg.request);
} else if (msg.requestType == Subscribe.MESSAGE_TYPE && mSubscribeRequests.containsKey(msg.request)) {
onReply = mSubscribeRequests.get(msg.request).onReply;
mSubscribeRequests.remove(msg.request);
} else if (msg.requestType == Register.MESSAGE_TYPE && mRegisterRequest.containsKey(msg.request)) {
onReply = mRegisterRequest.get(msg.request).onReply;
mRegisterRequest.remove(msg.request);
}
if (onReply != null) {
onReply.completeExceptionally(new ApplicationError(msg.error, msg.args, msg.kwargs));
} else {
throw new ProtocolError(String.format("ERROR received for non-pending request_type: %s and request ID %s", msg.requestType, msg.request));
}
} else {
throw new ProtocolError(String.format("Unexpected message %s", message.getClass().getName()));
}
}
use of io.crossbar.autobahn.wamp.types.Publication in project autobahn-java by crossbario.
the class Session method reallyPublish.
private CompletableFuture<Publication> reallyPublish(String topic, List<Object> args, Map<String, Object> kwargs, PublishOptions options) {
throwIfNotConnected();
CompletableFuture<Publication> future = new CompletableFuture<>();
long requestID = mIDGenerator.next();
mPublishRequests.put(requestID, new PublishRequest(requestID, future));
if (options != null) {
send(new Publish(requestID, topic, args, kwargs, options.acknowledge, options.excludeMe, options.retain));
} else {
send(new Publish(requestID, topic, args, kwargs, true, true, false));
}
return future;
}
use of io.crossbar.autobahn.wamp.types.Publication in project autobahn-java by crossbario.
the class ExampleClient method onJoinCallback.
private void onJoinCallback(Session session, SessionDetails details) {
CompletableFuture<Registration> regFuture = session.register(PROC_ADD2, this::add2);
regFuture.thenAccept(reg -> LOGGER.info("Registered procedure: com.example.add2"));
CompletableFuture<Subscription> subFuture = session.subscribe(TOPIC_COUNTER, this::onCounter);
subFuture.thenAccept(subscription -> LOGGER.info(String.format("Subscribed to topic: %s", subscription.topic)));
final int[] x = { 0 };
final int[] counter = { 0 };
final PublishOptions publishOptions = new PublishOptions(true, false);
ScheduledExecutorService executorService = Executors.newSingleThreadScheduledExecutor();
executorService.scheduleAtFixedRate(() -> {
// here we CALL every second
CompletableFuture<CallResult> f = session.call(PROC_ADD2, x[0], 3);
f.whenComplete((callResult, throwable) -> {
if (throwable == null) {
LOGGER.info(String.format("Got result: %s, ", callResult.results.get(0)));
x[0] += 1;
} else {
LOGGER.info(String.format("ERROR - call failed: %s", throwable.getMessage()));
}
});
CompletableFuture<Publication> p = session.publish(TOPIC_COUNTER, publishOptions, counter[0], session.getID(), "Java");
p.whenComplete((publication, throwable) -> {
if (throwable == null) {
LOGGER.info("published to 'oncounter' with counter " + counter[0]);
counter[0] += 1;
} else {
LOGGER.info(String.format("ERROR - pub failed: %s", throwable.getMessage()));
}
});
}, 0, 2, TimeUnit.SECONDS);
}
Aggregations