Search in sources :

Example 1 with CloseDetails

use of io.crossbar.autobahn.wamp.types.CloseDetails in project autobahn-java by crossbario.

the class Session method onPreSessionMessage.

private void onPreSessionMessage(IMessage message) throws Exception {
    if (message instanceof Welcome) {
        Welcome msg = (Welcome) message;
        mState = STATE_JOINED;
        mSessionID = msg.session;
        SessionDetails details = new SessionDetails(msg.realm, msg.session);
        mJoinFuture.complete(details);
        List<CompletableFuture<?>> futures = new ArrayList<>();
        for (OnJoinListener listener : mOnJoinListeners) {
            futures.add(runAsync(() -> listener.onJoin(this, details), mExecutor));
        }
        CompletableFuture d = combineFutures(futures);
        d.thenRunAsync(() -> {
            mState = STATE_READY;
            for (OnReadyListener listener : mOnReadyListeners) {
                listener.onReady(this);
            }
        }, mExecutor);
    } else if (message instanceof Abort) {
        Abort abortMessage = (Abort) message;
        CloseDetails details = new CloseDetails(abortMessage.reason, abortMessage.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");
            mState = STATE_DISCONNECTED;
            if (mTransport != null && mTransport.isOpen()) {
                try {
                    mTransport.close();
                } catch (Exception e) {
                    throw new CompletionException(e);
                }
            }
        }, mExecutor);
    } else if (message instanceof Challenge) {
        Challenge msg = (Challenge) message;
        io.crossbar.autobahn.wamp.types.Challenge challenge = new io.crossbar.autobahn.wamp.types.Challenge(msg.method, msg.extra);
        if (mAuthenticators != null) {
            if (msg.method.equals(TicketAuth.authmethod)) {
                for (IAuthenticator authenticator : mAuthenticators) {
                    if (authenticator.getAuthMethod().equals(TicketAuth.authmethod)) {
                        TicketAuth auth = (TicketAuth) authenticator;
                        auth.onChallenge(this, challenge).whenCompleteAsync((response, throwable) -> send(new Authenticate(response.signature, response.extra)), mExecutor);
                        break;
                    }
                }
            } else if (msg.method.equals(ChallengeResponseAuth.authmethod)) {
                for (IAuthenticator authenticator : mAuthenticators) {
                    if (authenticator.getAuthMethod().equals(ChallengeResponseAuth.authmethod)) {
                        ChallengeResponseAuth auth = (ChallengeResponseAuth) authenticator;
                        auth.onChallenge(this, challenge).whenCompleteAsync((response, throwable) -> send(new Authenticate(response.signature, response.extra)), mExecutor);
                        break;
                    }
                }
            } else if (msg.method.equals(CryptosignAuth.authmethod)) {
                for (IAuthenticator authenticator : mAuthenticators) {
                    if (authenticator.getAuthMethod().equals(CryptosignAuth.authmethod)) {
                        CryptosignAuth auth = (CryptosignAuth) authenticator;
                        auth.onChallenge(this, challenge).whenCompleteAsync((response, throwable) -> send(new Authenticate(response.signature, response.extra)), mExecutor);
                        break;
                    }
                }
            }
        }
    }
}
Also used : Result(io.crossbar.autobahn.wamp.messages.Result) Arrays(java.util.Arrays) Event(io.crossbar.autobahn.wamp.messages.Event) BiFunction(java.util.function.BiFunction) ChallengeResponseAuth(io.crossbar.autobahn.wamp.auth.ChallengeResponseAuth) EventDetails(io.crossbar.autobahn.wamp.types.EventDetails) Subscription(io.crossbar.autobahn.wamp.types.Subscription) Published(io.crossbar.autobahn.wamp.messages.Published) UnregisterRequest(io.crossbar.autobahn.wamp.requests.UnregisterRequest) TriConsumer(io.crossbar.autobahn.wamp.interfaces.TriConsumer) Unsubscribe(io.crossbar.autobahn.wamp.messages.Unsubscribe) Registration(io.crossbar.autobahn.wamp.types.Registration) IInvocationHandler(io.crossbar.autobahn.wamp.interfaces.IInvocationHandler) Publish(io.crossbar.autobahn.wamp.messages.Publish) CryptosignAuth(io.crossbar.autobahn.wamp.auth.CryptosignAuth) CallResult(io.crossbar.autobahn.wamp.types.CallResult) Subscribe(io.crossbar.autobahn.wamp.messages.Subscribe) ITransport(io.crossbar.autobahn.wamp.interfaces.ITransport) Error(io.crossbar.autobahn.wamp.messages.Error) Map(java.util.Map) Register(io.crossbar.autobahn.wamp.messages.Register) IMessage(io.crossbar.autobahn.wamp.interfaces.IMessage) Challenge(io.crossbar.autobahn.wamp.messages.Challenge) TicketAuth(io.crossbar.autobahn.wamp.auth.TicketAuth) SubscribeRequest(io.crossbar.autobahn.wamp.requests.SubscribeRequest) TypeReference(com.fasterxml.jackson.core.type.TypeReference) CallOptions(io.crossbar.autobahn.wamp.types.CallOptions) Invocation(io.crossbar.autobahn.wamp.messages.Invocation) InvocationDetails(io.crossbar.autobahn.wamp.types.InvocationDetails) Unsubscribed(io.crossbar.autobahn.wamp.messages.Unsubscribed) IABLogger(io.crossbar.autobahn.utils.IABLogger) Registered(io.crossbar.autobahn.wamp.messages.Registered) Shortcuts.getOrDefault(io.crossbar.autobahn.wamp.utils.Shortcuts.getOrDefault) CallRequest(io.crossbar.autobahn.wamp.requests.CallRequest) IDGenerator(io.crossbar.autobahn.wamp.utils.IDGenerator) CompletionException(java.util.concurrent.CompletionException) ABLogger(io.crossbar.autobahn.utils.ABLogger) Call(io.crossbar.autobahn.wamp.messages.Call) Authenticate(io.crossbar.autobahn.wamp.messages.Authenticate) Unregister(io.crossbar.autobahn.wamp.messages.Unregister) ProtocolError(io.crossbar.autobahn.wamp.exceptions.ProtocolError) Hello(io.crossbar.autobahn.wamp.messages.Hello) MESSAGE_TYPE_MAP(io.crossbar.autobahn.wamp.messages.MessageMap.MESSAGE_TYPE_MAP) List(java.util.List) SessionDetails(io.crossbar.autobahn.wamp.types.SessionDetails) WampException(io.crossbar.autobahn.wamp.reflectionRoles.WampException) CloseDetails(io.crossbar.autobahn.wamp.types.CloseDetails) ITransportHandler(io.crossbar.autobahn.wamp.interfaces.ITransportHandler) Goodbye(io.crossbar.autobahn.wamp.messages.Goodbye) Abort(io.crossbar.autobahn.wamp.messages.Abort) Unregistered(io.crossbar.autobahn.wamp.messages.Unregistered) IAuthenticator(io.crossbar.autobahn.wamp.interfaces.IAuthenticator) Subscribed(io.crossbar.autobahn.wamp.messages.Subscribed) Welcome(io.crossbar.autobahn.wamp.messages.Welcome) ISession(io.crossbar.autobahn.wamp.interfaces.ISession) PublishRequest(io.crossbar.autobahn.wamp.requests.PublishRequest) ReflectionServices(io.crossbar.autobahn.wamp.reflectionRoles.ReflectionServices) HashMap(java.util.HashMap) CompletableFuture(java.util.concurrent.CompletableFuture) Function(java.util.function.Function) Supplier(java.util.function.Supplier) ArrayList(java.util.ArrayList) BiConsumer(java.util.function.BiConsumer) TriFunction(io.crossbar.autobahn.wamp.interfaces.TriFunction) InvocationResult(io.crossbar.autobahn.wamp.types.InvocationResult) CompletableFuture.runAsync(java.util.concurrent.CompletableFuture.runAsync) ReceptionResult(io.crossbar.autobahn.wamp.types.ReceptionResult) Executor(java.util.concurrent.Executor) RegisterOptions(io.crossbar.autobahn.wamp.types.RegisterOptions) SubscribeOptions(io.crossbar.autobahn.wamp.types.SubscribeOptions) Platform(io.crossbar.autobahn.wamp.utils.Platform) Yield(io.crossbar.autobahn.wamp.messages.Yield) Consumer(java.util.function.Consumer) RegisterRequest(io.crossbar.autobahn.wamp.requests.RegisterRequest) PublishOptions(io.crossbar.autobahn.wamp.types.PublishOptions) ISerializer(io.crossbar.autobahn.wamp.interfaces.ISerializer) UnsubscribeRequest(io.crossbar.autobahn.wamp.requests.UnsubscribeRequest) Publication(io.crossbar.autobahn.wamp.types.Publication) ApplicationError(io.crossbar.autobahn.wamp.exceptions.ApplicationError) CryptosignAuth(io.crossbar.autobahn.wamp.auth.CryptosignAuth) ArrayList(java.util.ArrayList) Challenge(io.crossbar.autobahn.wamp.messages.Challenge) CompletableFuture(java.util.concurrent.CompletableFuture) Abort(io.crossbar.autobahn.wamp.messages.Abort) Authenticate(io.crossbar.autobahn.wamp.messages.Authenticate) List(java.util.List) ArrayList(java.util.ArrayList) TicketAuth(io.crossbar.autobahn.wamp.auth.TicketAuth) IAuthenticator(io.crossbar.autobahn.wamp.interfaces.IAuthenticator) SessionDetails(io.crossbar.autobahn.wamp.types.SessionDetails) CompletionException(java.util.concurrent.CompletionException) WampException(io.crossbar.autobahn.wamp.reflectionRoles.WampException) ChallengeResponseAuth(io.crossbar.autobahn.wamp.auth.ChallengeResponseAuth) CompletionException(java.util.concurrent.CompletionException) Welcome(io.crossbar.autobahn.wamp.messages.Welcome) CloseDetails(io.crossbar.autobahn.wamp.types.CloseDetails)

Example 2 with CloseDetails

use of io.crossbar.autobahn.wamp.types.CloseDetails 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()));
    }
}
Also used : Result(io.crossbar.autobahn.wamp.messages.Result) Arrays(java.util.Arrays) Event(io.crossbar.autobahn.wamp.messages.Event) BiFunction(java.util.function.BiFunction) ChallengeResponseAuth(io.crossbar.autobahn.wamp.auth.ChallengeResponseAuth) EventDetails(io.crossbar.autobahn.wamp.types.EventDetails) Subscription(io.crossbar.autobahn.wamp.types.Subscription) Published(io.crossbar.autobahn.wamp.messages.Published) UnregisterRequest(io.crossbar.autobahn.wamp.requests.UnregisterRequest) TriConsumer(io.crossbar.autobahn.wamp.interfaces.TriConsumer) Unsubscribe(io.crossbar.autobahn.wamp.messages.Unsubscribe) Registration(io.crossbar.autobahn.wamp.types.Registration) IInvocationHandler(io.crossbar.autobahn.wamp.interfaces.IInvocationHandler) Publish(io.crossbar.autobahn.wamp.messages.Publish) CryptosignAuth(io.crossbar.autobahn.wamp.auth.CryptosignAuth) CallResult(io.crossbar.autobahn.wamp.types.CallResult) Subscribe(io.crossbar.autobahn.wamp.messages.Subscribe) ITransport(io.crossbar.autobahn.wamp.interfaces.ITransport) Error(io.crossbar.autobahn.wamp.messages.Error) Map(java.util.Map) Register(io.crossbar.autobahn.wamp.messages.Register) IMessage(io.crossbar.autobahn.wamp.interfaces.IMessage) Challenge(io.crossbar.autobahn.wamp.messages.Challenge) TicketAuth(io.crossbar.autobahn.wamp.auth.TicketAuth) SubscribeRequest(io.crossbar.autobahn.wamp.requests.SubscribeRequest) TypeReference(com.fasterxml.jackson.core.type.TypeReference) CallOptions(io.crossbar.autobahn.wamp.types.CallOptions) Invocation(io.crossbar.autobahn.wamp.messages.Invocation) InvocationDetails(io.crossbar.autobahn.wamp.types.InvocationDetails) Unsubscribed(io.crossbar.autobahn.wamp.messages.Unsubscribed) IABLogger(io.crossbar.autobahn.utils.IABLogger) Registered(io.crossbar.autobahn.wamp.messages.Registered) Shortcuts.getOrDefault(io.crossbar.autobahn.wamp.utils.Shortcuts.getOrDefault) CallRequest(io.crossbar.autobahn.wamp.requests.CallRequest) IDGenerator(io.crossbar.autobahn.wamp.utils.IDGenerator) CompletionException(java.util.concurrent.CompletionException) ABLogger(io.crossbar.autobahn.utils.ABLogger) Call(io.crossbar.autobahn.wamp.messages.Call) Authenticate(io.crossbar.autobahn.wamp.messages.Authenticate) Unregister(io.crossbar.autobahn.wamp.messages.Unregister) ProtocolError(io.crossbar.autobahn.wamp.exceptions.ProtocolError) Hello(io.crossbar.autobahn.wamp.messages.Hello) MESSAGE_TYPE_MAP(io.crossbar.autobahn.wamp.messages.MessageMap.MESSAGE_TYPE_MAP) List(java.util.List) SessionDetails(io.crossbar.autobahn.wamp.types.SessionDetails) WampException(io.crossbar.autobahn.wamp.reflectionRoles.WampException) CloseDetails(io.crossbar.autobahn.wamp.types.CloseDetails) ITransportHandler(io.crossbar.autobahn.wamp.interfaces.ITransportHandler) Goodbye(io.crossbar.autobahn.wamp.messages.Goodbye) Abort(io.crossbar.autobahn.wamp.messages.Abort) Unregistered(io.crossbar.autobahn.wamp.messages.Unregistered) IAuthenticator(io.crossbar.autobahn.wamp.interfaces.IAuthenticator) Subscribed(io.crossbar.autobahn.wamp.messages.Subscribed) Welcome(io.crossbar.autobahn.wamp.messages.Welcome) ISession(io.crossbar.autobahn.wamp.interfaces.ISession) PublishRequest(io.crossbar.autobahn.wamp.requests.PublishRequest) ReflectionServices(io.crossbar.autobahn.wamp.reflectionRoles.ReflectionServices) HashMap(java.util.HashMap) CompletableFuture(java.util.concurrent.CompletableFuture) Function(java.util.function.Function) Supplier(java.util.function.Supplier) ArrayList(java.util.ArrayList) BiConsumer(java.util.function.BiConsumer) TriFunction(io.crossbar.autobahn.wamp.interfaces.TriFunction) InvocationResult(io.crossbar.autobahn.wamp.types.InvocationResult) CompletableFuture.runAsync(java.util.concurrent.CompletableFuture.runAsync) ReceptionResult(io.crossbar.autobahn.wamp.types.ReceptionResult) Executor(java.util.concurrent.Executor) RegisterOptions(io.crossbar.autobahn.wamp.types.RegisterOptions) SubscribeOptions(io.crossbar.autobahn.wamp.types.SubscribeOptions) Platform(io.crossbar.autobahn.wamp.utils.Platform) Yield(io.crossbar.autobahn.wamp.messages.Yield) Consumer(java.util.function.Consumer) RegisterRequest(io.crossbar.autobahn.wamp.requests.RegisterRequest) PublishOptions(io.crossbar.autobahn.wamp.types.PublishOptions) ISerializer(io.crossbar.autobahn.wamp.interfaces.ISerializer) UnsubscribeRequest(io.crossbar.autobahn.wamp.requests.UnsubscribeRequest) Publication(io.crossbar.autobahn.wamp.types.Publication) ApplicationError(io.crossbar.autobahn.wamp.exceptions.ApplicationError) ArrayList(java.util.ArrayList) InvocationResult(io.crossbar.autobahn.wamp.types.InvocationResult) Result(io.crossbar.autobahn.wamp.messages.Result) CallResult(io.crossbar.autobahn.wamp.types.CallResult) InvocationResult(io.crossbar.autobahn.wamp.types.InvocationResult) ReceptionResult(io.crossbar.autobahn.wamp.types.ReceptionResult) TriConsumer(io.crossbar.autobahn.wamp.interfaces.TriConsumer) BiConsumer(java.util.function.BiConsumer) Consumer(java.util.function.Consumer) SubscribeRequest(io.crossbar.autobahn.wamp.requests.SubscribeRequest) Registration(io.crossbar.autobahn.wamp.types.Registration) List(java.util.List) ArrayList(java.util.ArrayList) Subscription(io.crossbar.autobahn.wamp.types.Subscription) CallRequest(io.crossbar.autobahn.wamp.requests.CallRequest) UnsubscribeRequest(io.crossbar.autobahn.wamp.requests.UnsubscribeRequest) Publication(io.crossbar.autobahn.wamp.types.Publication) PublishRequest(io.crossbar.autobahn.wamp.requests.PublishRequest) EventDetails(io.crossbar.autobahn.wamp.types.EventDetails) Unregistered(io.crossbar.autobahn.wamp.messages.Unregistered) UnregisterRequest(io.crossbar.autobahn.wamp.requests.UnregisterRequest) Map(java.util.Map) HashMap(java.util.HashMap) CloseDetails(io.crossbar.autobahn.wamp.types.CloseDetails) CallResult(io.crossbar.autobahn.wamp.types.CallResult) Invocation(io.crossbar.autobahn.wamp.messages.Invocation) BiFunction(java.util.function.BiFunction) Function(java.util.function.Function) TriFunction(io.crossbar.autobahn.wamp.interfaces.TriFunction) CompletableFuture(java.util.concurrent.CompletableFuture) InvocationDetails(io.crossbar.autobahn.wamp.types.InvocationDetails) WampException(io.crossbar.autobahn.wamp.reflectionRoles.WampException) ApplicationError(io.crossbar.autobahn.wamp.exceptions.ApplicationError) Supplier(java.util.function.Supplier) Unsubscribed(io.crossbar.autobahn.wamp.messages.Unsubscribed) IInvocationHandler(io.crossbar.autobahn.wamp.interfaces.IInvocationHandler) RegisterRequest(io.crossbar.autobahn.wamp.requests.RegisterRequest) Subscribed(io.crossbar.autobahn.wamp.messages.Subscribed) Error(io.crossbar.autobahn.wamp.messages.Error) ProtocolError(io.crossbar.autobahn.wamp.exceptions.ProtocolError) ApplicationError(io.crossbar.autobahn.wamp.exceptions.ApplicationError) CompletionException(java.util.concurrent.CompletionException) WampException(io.crossbar.autobahn.wamp.reflectionRoles.WampException) ProtocolError(io.crossbar.autobahn.wamp.exceptions.ProtocolError) TriConsumer(io.crossbar.autobahn.wamp.interfaces.TriConsumer) BiFunction(java.util.function.BiFunction) CompletionException(java.util.concurrent.CompletionException) Event(io.crossbar.autobahn.wamp.messages.Event) TriFunction(io.crossbar.autobahn.wamp.interfaces.TriFunction) Published(io.crossbar.autobahn.wamp.messages.Published) Yield(io.crossbar.autobahn.wamp.messages.Yield) BiConsumer(java.util.function.BiConsumer) Registered(io.crossbar.autobahn.wamp.messages.Registered) Goodbye(io.crossbar.autobahn.wamp.messages.Goodbye)

Example 3 with CloseDetails

use of io.crossbar.autobahn.wamp.types.CloseDetails in project autobahn-java by crossbario.

the class AndroidWebSocket method connect.

@Override
public void connect(ITransportHandler transportHandler, TransportOptions options) throws Exception {
    WebSocketOptions webSocketOptions = new WebSocketOptions();
    webSocketOptions.setAutoPingInterval(options.getAutoPingInterval());
    webSocketOptions.setAutoPingTimeout(options.getAutoPingTimeout());
    webSocketOptions.setMaxFramePayloadSize(options.getMaxFramePayloadSize());
    mConnection.connect(mUri, getSerializers(), new WebSocketConnectionHandler() {

        @Override
        public void onConnect(ConnectionResponse response) {
            LOGGER.d(String.format("Negotiated serializer=%s", response.protocol));
            try {
                mSerializer = initializeSerializer(response.protocol);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        @Override
        public void onOpen() {
            try {
                transportHandler.onConnect(AndroidWebSocket.this, mSerializer);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        @Override
        public void onClose(int code, String reason) {
            switch(code) {
                case IWebSocketConnectionHandler.CLOSE_CONNECTION_LOST:
                    transportHandler.onLeave(new CloseDetails(CloseDetails.REASON_TRANSPORT_LOST, null));
                    break;
                default:
                    transportHandler.onLeave(new CloseDetails(CloseDetails.REASON_DEFAULT, null));
            }
            LOGGER.d(String.format("Disconnected, code=%s, reasons=%s", code, reason));
            transportHandler.onDisconnect(code == 1000);
        }

        @Override
        public void onMessage(String payload) {
            try {
                transportHandler.onMessage(payload.getBytes(), false);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        @Override
        public void onMessage(byte[] payload, boolean isBinary) {
            try {
                transportHandler.onMessage(payload, isBinary);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }, webSocketOptions, null);
}
Also used : WebSocketOptions(io.crossbar.autobahn.websocket.types.WebSocketOptions) IWebSocketConnectionHandler(io.crossbar.autobahn.websocket.interfaces.IWebSocketConnectionHandler) WebSocketConnectionHandler(io.crossbar.autobahn.websocket.WebSocketConnectionHandler) ConnectionResponse(io.crossbar.autobahn.websocket.types.ConnectionResponse) CloseDetails(io.crossbar.autobahn.wamp.types.CloseDetails)

Example 4 with CloseDetails

use of io.crossbar.autobahn.wamp.types.CloseDetails in project autobahn-java by crossbario.

the class NettyWebSocketClientHandler method channelRead0.

@Override
public void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception {
    Channel ch = ctx.channel();
    if (!mHandshaker.isHandshakeComplete()) {
        FullHttpResponse response = (FullHttpResponse) msg;
        String negotiatedSerializer = response.headers().get("Sec-WebSocket-Protocol");
        LOGGER.d(String.format("Negotiated serializer=%s", negotiatedSerializer));
        ISerializer serializer = initializeSerializer(negotiatedSerializer);
        mHandshaker.finishHandshake(ch, response);
        mHandshakeFuture.setSuccess();
        mTransportHandler.onConnect(mTransport, serializer);
    } else if (msg instanceof FullHttpResponse) {
        FullHttpResponse response = (FullHttpResponse) msg;
        throw new IllegalStateException("Unexpected FullHttpResponse (getStatus=" + response.status() + ", content=" + response.content().toString(CharsetUtil.UTF_8) + ')');
    } else if (msg instanceof BinaryWebSocketFrame) {
        BinaryWebSocketFrame binaryWebSocketFrame = (BinaryWebSocketFrame) msg;
        byte[] payload = new byte[binaryWebSocketFrame.content().readableBytes()];
        LOGGER.v(String.format("Received binary frame, content length=%s", payload.length));
        binaryWebSocketFrame.content().readBytes(payload);
        mTransportHandler.onMessage(payload, true);
    } else if (msg instanceof TextWebSocketFrame) {
        TextWebSocketFrame textWebSocketFrame = (TextWebSocketFrame) msg;
        byte[] payload = new byte[textWebSocketFrame.content().readableBytes()];
        LOGGER.v(String.format("Received Text frame, content length=%s", payload.length));
        textWebSocketFrame.content().readBytes(payload);
        mTransportHandler.onMessage(payload, false);
    } else if (msg instanceof PingWebSocketFrame) {
        PingWebSocketFrame pingWebSocketFrame = (PingWebSocketFrame) msg;
        ctx.writeAndFlush(new PongWebSocketFrame(pingWebSocketFrame.content().retain()));
    } else if (msg instanceof PongWebSocketFrame) {
        // Not really doing anything here.
        LOGGER.v("WebSocket Client received pong.");
    } else if (msg instanceof CloseWebSocketFrame) {
        CloseWebSocketFrame closeWebSocketFrame = (CloseWebSocketFrame) msg;
        LOGGER.d(String.format("Received Close frame, code=%s, reason=%s", closeWebSocketFrame.statusCode(), closeWebSocketFrame.reasonText()));
        close(ctx, closeWebSocketFrame.statusCode() == 1000, new CloseDetails(CloseDetails.REASON_DEFAULT, null));
    }
}
Also used : CloseWebSocketFrame(io.netty.handler.codec.http.websocketx.CloseWebSocketFrame) PongWebSocketFrame(io.netty.handler.codec.http.websocketx.PongWebSocketFrame) Channel(io.netty.channel.Channel) TextWebSocketFrame(io.netty.handler.codec.http.websocketx.TextWebSocketFrame) BinaryWebSocketFrame(io.netty.handler.codec.http.websocketx.BinaryWebSocketFrame) FullHttpResponse(io.netty.handler.codec.http.FullHttpResponse) PingWebSocketFrame(io.netty.handler.codec.http.websocketx.PingWebSocketFrame) CloseDetails(io.crossbar.autobahn.wamp.types.CloseDetails) ISerializer(io.crossbar.autobahn.wamp.interfaces.ISerializer)

Aggregations

ISerializer (io.crossbar.autobahn.wamp.interfaces.ISerializer)3 TypeReference (com.fasterxml.jackson.core.type.TypeReference)2 ABLogger (io.crossbar.autobahn.utils.ABLogger)2 IABLogger (io.crossbar.autobahn.utils.IABLogger)2 ChallengeResponseAuth (io.crossbar.autobahn.wamp.auth.ChallengeResponseAuth)2 CryptosignAuth (io.crossbar.autobahn.wamp.auth.CryptosignAuth)2 TicketAuth (io.crossbar.autobahn.wamp.auth.TicketAuth)2 ApplicationError (io.crossbar.autobahn.wamp.exceptions.ApplicationError)2 ProtocolError (io.crossbar.autobahn.wamp.exceptions.ProtocolError)2 IAuthenticator (io.crossbar.autobahn.wamp.interfaces.IAuthenticator)2 IInvocationHandler (io.crossbar.autobahn.wamp.interfaces.IInvocationHandler)2 IMessage (io.crossbar.autobahn.wamp.interfaces.IMessage)2 ISession (io.crossbar.autobahn.wamp.interfaces.ISession)2 ITransport (io.crossbar.autobahn.wamp.interfaces.ITransport)2 ITransportHandler (io.crossbar.autobahn.wamp.interfaces.ITransportHandler)2 TriConsumer (io.crossbar.autobahn.wamp.interfaces.TriConsumer)2 TriFunction (io.crossbar.autobahn.wamp.interfaces.TriFunction)2 Abort (io.crossbar.autobahn.wamp.messages.Abort)2 Authenticate (io.crossbar.autobahn.wamp.messages.Authenticate)2 Call (io.crossbar.autobahn.wamp.messages.Call)2