Class TyrusSession

  • All Implemented Interfaces:
    Session, java.io.Closeable, java.lang.AutoCloseable, DistributedSession

    public class TyrusSession
    extends java.lang.Object
    implements DistributedSession
    Implementation of the Session.
    Author:
    Danny Coward, Stepan Kopriva, Martin Matula, Pavel Bucek
    • Method Summary

      All Methods Instance Methods Concrete Methods Deprecated Methods 
      Modifier and Type Method Description
      void addMessageHandler​(MessageHandler handler)
      <T> void addMessageHandler​(java.lang.Class<T> clazz, MessageHandler.Partial<T> handler)
      Register to handle to incoming messages in this conversation.
      <T> void addMessageHandler​(java.lang.Class<T> clazz, MessageHandler.Whole<T> handler)
      Register to handle to incoming messages in this conversation.
      java.util.Map<Session,​java.util.concurrent.Future<?>> broadcast​(java.lang.String message)
      Broadcasts text message to all connected clients.
      java.util.Map<Session,​java.util.concurrent.Future<?>> broadcast​(java.nio.ByteBuffer message)
      Broadcasts binary message to all connected clients, including remote sessions (if any).
      void close()
      Close the current conversation with a normal status code and no reason phrase.
      void close​(CloseReason closeReason)
      Close the current conversation, giving a reason for the closure.
      java.util.Set<DistributedSession> getAllSessions()
      Get set of all sessions opened to the same endpoint.
      RemoteEndpoint.Async getAsyncRemote()
      Return a reference a RemoteEndpoint object representing the peer of this conversation that is able to send messages asynchronously to the peer.
      RemoteEndpoint.Basic getBasicRemote()
      Return a reference a RemoteEndpoint object representing the peer of this conversation that is able to send messages synchronously to the peer.
      WebSocketContainer getContainer()
      Return the container that this session is part of.
      java.util.Map<java.lang.String,​java.lang.Object> getDistributedProperties()
      Get distributed properties.
      long getHeartbeatInterval()
      Return an interval in milliseconds between scheduled periodic Pong messages.
      java.lang.String getId()
      Returns a string containing the unique identifier assigned to this session.
      int getMaxBinaryMessageBufferSize()
      The maximum length of incoming binary messages that this Session can buffer.
      long getMaxIdleTimeout()
      Return the number of milliseconds before this session will be closed by the container if it is inactive, i.e.
      int getMaxTextMessageBufferSize()
      The maximum length of incoming text messages that this Session can buffer.
      java.util.Set<MessageHandler> getMessageHandlers()
      Return an unmodifiable copy of the set of MessageHandlers for this Session.
      java.util.List<Extension> getNegotiatedExtensions()
      Return the list of extensions currently in use for this conversation.
      java.lang.String getNegotiatedSubprotocol()
      Return the sub protocol agreed during the websocket handshake for this conversation.
      java.util.Set<Session> getOpenSessions()
      Return a copy of the Set of all the open web socket sessions that represent connections to the same endpoint to which this session represents a connection.
      java.util.Map<java.lang.String,​java.lang.String> getPathParameters()
      Return a map of the path parameter names and values used associated with the request this session was opened under.
      java.lang.String getProtocolVersion()
      Returns the version of the websocket protocol currently being used.
      java.lang.String getQueryString()
      Return the query string associated with the request this session was opened under.
      java.lang.String getRemoteAddr()
      Get the Internet Protocol (IP) address of the client or last proxy that sent the request.
      java.util.Set<RemoteSession> getRemoteSessions()
      Get set of remote sessions.
      java.util.Map<java.lang.String,​java.util.List<java.lang.String>> getRequestParameterMap()
      Return the request parameters associated with the request this session was opened under.
      java.net.URI getRequestURI()
      Return the complete URI under which this session was opened, from protocol to query string (if present).
      java.security.Principal getUserPrincipal()
      Return the authenticated user for this Session or null if no user is authenticated for this session.
      java.util.Map<java.lang.String,​java.lang.Object> getUserProperties()
      While the session is open, this method returns a Map that the developer may use to store application specific information relating to this session instance.
      boolean isOpen()
      Return true if and only if the underlying socket is open.
      boolean isSecure()
      Return true if and only if the underlying socket is using a secure transport.
      void removeMessageHandler​(MessageHandler handler)
      Remove the given MessageHandler from the set belonging to this session.
      void setHeartbeatInterval​(long heartbeatInterval)
      Set an interval in milliseconds between scheduled periodic Pong messages.
      void setMaxBinaryMessageBufferSize​(int maxBinaryMessageBufferSize)
      Sets the maximum length of incoming binary messages that this Session can buffer.
      void setMaxIdleTimeout​(long maxIdleTimeout)
      Set the number of milliseconds before this session will be closed by the container if it is inactive, i.e.
      void setMaxTextMessageBufferSize​(int maxTextMessageBufferSize)
      Sets the maximum length of incoming text messages that this Session can buffer.
      java.lang.String toString()  
      • Methods inherited from class java.lang.Object

        clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait
    • Method Detail

      • getProtocolVersion

        public java.lang.String getProtocolVersion()
        Description copied from interface: Session
        Returns the version of the websocket protocol currently being used. This is taken as the value of the Sec-WebSocket-Version header used in the opening handshake. i.e. "13".
        Specified by:
        getProtocolVersion in interface Session
        Returns:
        the protocol version.
      • getNegotiatedSubprotocol

        public java.lang.String getNegotiatedSubprotocol()
        Description copied from interface: Session
        Return the sub protocol agreed during the websocket handshake for this conversation.
        Specified by:
        getNegotiatedSubprotocol in interface Session
        Returns:
        the negotiated subprotocol, or the empty string if there isn't one.
      • getAsyncRemote

        public RemoteEndpoint.Async getAsyncRemote()
        Description copied from interface: Session
        Return a reference a RemoteEndpoint object representing the peer of this conversation that is able to send messages asynchronously to the peer.
        Specified by:
        getAsyncRemote in interface Session
        Returns:
        the remote endpoint.
      • getBasicRemote

        public RemoteEndpoint.Basic getBasicRemote()
        Description copied from interface: Session
        Return a reference a RemoteEndpoint object representing the peer of this conversation that is able to send messages synchronously to the peer.
        Specified by:
        getBasicRemote in interface Session
        Returns:
        the remote endpoint.
      • isOpen

        public boolean isOpen()
        Description copied from interface: Session
        Return true if and only if the underlying socket is open.
        Specified by:
        isOpen in interface Session
        Returns:
        whether the session is active.
      • close

        public void close()
                   throws java.io.IOException
        Description copied from interface: Session
        Close the current conversation with a normal status code and no reason phrase.
        Specified by:
        close in interface java.lang.AutoCloseable
        Specified by:
        close in interface java.io.Closeable
        Specified by:
        close in interface Session
        Throws:
        java.io.IOException - if there was a connection error closing the connection.
      • close

        public void close​(CloseReason closeReason)
                   throws java.io.IOException
        Description copied from interface: Session
        Close the current conversation, giving a reason for the closure. The close call causes the implementation to attempt notify the client of the close as soon as it can. This may cause the sending of unsent messages immediately prior to the close notification. After the close notification has been sent the implementation notifies the endpoint's onClose method. Note the websocket specification defines the acceptable uses of status codes and reason phrases. If the application cannot determine a suitable close code to use for the closeReason, it is recommended to use CloseReason.CloseCodes.NO_STATUS_CODE.
        Specified by:
        close in interface Session
        Parameters:
        closeReason - the reason for the closure.
        Throws:
        java.io.IOException - if there was a connection error closing the connection
      • getMaxBinaryMessageBufferSize

        public int getMaxBinaryMessageBufferSize()
        Description copied from interface: Session
        The maximum length of incoming binary messages that this Session can buffer. If the implementation receives a binary message that it cannot buffer because it is too large, it must close the session with a close code of CloseReason.CloseCodes.TOO_BIG.
        Specified by:
        getMaxBinaryMessageBufferSize in interface Session
        Returns:
        the maximum binary message size that can be buffered.
      • setMaxBinaryMessageBufferSize

        public void setMaxBinaryMessageBufferSize​(int maxBinaryMessageBufferSize)
        Description copied from interface: Session
        Sets the maximum length of incoming binary messages that this Session can buffer.
        Specified by:
        setMaxBinaryMessageBufferSize in interface Session
        Parameters:
        maxBinaryMessageBufferSize - the maximum length.
      • getMaxTextMessageBufferSize

        public int getMaxTextMessageBufferSize()
        Description copied from interface: Session
        The maximum length of incoming text messages that this Session can buffer. If the implementation receives a text message that it cannot buffer because it is too large, it must close the session with a close code of CloseReason.CloseCodes.TOO_BIG.
        Specified by:
        getMaxTextMessageBufferSize in interface Session
        Returns:
        the maximum text message size that can be buffered.
      • setMaxTextMessageBufferSize

        public void setMaxTextMessageBufferSize​(int maxTextMessageBufferSize)
        Description copied from interface: Session
        Sets the maximum length of incoming text messages that this Session can buffer.
        Specified by:
        setMaxTextMessageBufferSize in interface Session
        Parameters:
        maxTextMessageBufferSize - the maximum length.
      • getOpenSessions

        public java.util.Set<Session> getOpenSessions()
        Description copied from interface: Session
        Return a copy of the Set of all the open web socket sessions that represent connections to the same endpoint to which this session represents a connection. The Set includes the session this method is called on. These sessions may not still be open at any point after the return of this method. For example, iterating over the set at a later time may yield one or more closed sessions. Developers should use session.isOpen() to check.
        Specified by:
        getOpenSessions in interface Session
        Returns:
        the set of sessions, open at the time of return.
      • getRemoteSessions

        public java.util.Set<RemoteSession> getRemoteSessions()
        Get set of remote sessions.

        Remote sessions are websocket sessions which are bound to another node in the cluster.

        Returns:
        set of remote sessions or empty set, when not running in cluster environment.
      • getAllSessions

        public java.util.Set<DistributedSession> getAllSessions()
        Get set of all sessions opened to the same endpoint.

        Set returned from this method contains all "local" and remote sessions (if any).

        Returns:
        set of distributed sessions.
        See Also:
        RemoteSession
      • getNegotiatedExtensions

        public java.util.List<Extension> getNegotiatedExtensions()
        Description copied from interface: Session
        Return the list of extensions currently in use for this conversation.
        Specified by:
        getNegotiatedExtensions in interface Session
        Returns:
        the negotiated extensions.
      • getMaxIdleTimeout

        public long getMaxIdleTimeout()
        Description copied from interface: Session
        Return the number of milliseconds before this session will be closed by the container if it is inactive, i.e. no messages are either sent or received in that time. A value that is zero or negative indicates that this timeout will not be used.
        Specified by:
        getMaxIdleTimeout in interface Session
        Returns:
        the timeout in milliseconds.
      • setMaxIdleTimeout

        public void setMaxIdleTimeout​(long maxIdleTimeout)
        Description copied from interface: Session
        Set the number of milliseconds before this session will be closed by the container if it is inactive, i.e. no messages are either sent or received in that time. A value that is zero or negative indicates that this timeout will not be used.
        Specified by:
        setMaxIdleTimeout in interface Session
        Parameters:
        maxIdleTimeout - the number of milliseconds.
      • isSecure

        public boolean isSecure()
        Description copied from interface: Session
        Return true if and only if the underlying socket is using a secure transport.
        Specified by:
        isSecure in interface Session
        Returns:
        whether its using a secure transport.
      • getContainer

        public WebSocketContainer getContainer()
        Description copied from interface: Session
        Return the container that this session is part of.
        Specified by:
        getContainer in interface Session
        Returns:
        the container.
      • addMessageHandler

        public <T> void addMessageHandler​(java.lang.Class<T> clazz,
                                          MessageHandler.Whole<T> handler)
        Register to handle to incoming messages in this conversation. A maximum of one message handler per native websocket message type (text, binary, pong) may be added to each Session. I.e. a maximum of one message handler to handle incoming text messages a maximum of one message handler for handling incoming binary messages, and a maximum of one for handling incoming pong messages. For further details of which message handlers handle which of the native websocket message types please see MessageHandler.Whole and MessageHandler.Partial. Adding more than one of any one type will result in a runtime exception.

        See Endpoint for a usage example.

        Specified by:
        addMessageHandler in interface Session
        Type Parameters:
        T - type of message that the given handler is intended for.
        Parameters:
        clazz - type of the message processed by message handler to be registered.
        handler - the MessageHandler to be added.
        Throws:
        java.lang.IllegalStateException - if there is already a MessageHandler registered for the same native websocket message type as this handler.
      • addMessageHandler

        public <T> void addMessageHandler​(java.lang.Class<T> clazz,
                                          MessageHandler.Partial<T> handler)
        Register to handle to incoming messages in this conversation. A maximum of one message handler per native websocket message type (text, binary, pong) may be added to each Session. I.e. a maximum of one message handler to handle incoming text messages a maximum of one message handler for handling incoming binary messages, and a maximum of one for handling incoming pong messages. For further details of which message handlers handle which of the native websocket message types please see MessageHandler.Whole and MessageHandler.Partial. Adding more than one of any one type will result in a runtime exception.

        See Endpoint for a usage example.

        Specified by:
        addMessageHandler in interface Session
        Type Parameters:
        T - type of message that the given handler is intended for.
        Parameters:
        clazz - type of the message processed by message handler to be registered.
        handler - the MessageHandler to be added.
        Throws:
        java.lang.IllegalStateException - if there is already a MessageHandler registered for the same native websocket message type as this handler.
      • getMessageHandlers

        public java.util.Set<MessageHandler> getMessageHandlers()
        Description copied from interface: Session
        Return an unmodifiable copy of the set of MessageHandlers for this Session.
        Specified by:
        getMessageHandlers in interface Session
        Returns:
        the set of message handlers.
      • removeMessageHandler

        public void removeMessageHandler​(MessageHandler handler)
        Description copied from interface: Session
        Remove the given MessageHandler from the set belonging to this session. This method may block if the given handler is processing a message until it is no longer in use.

        Once the container has identified a MessageHandler for a message, the MessageHandler is used for the entirety of the message irrespective of any subsequent changes to the MessageHandlers configured for the Session.

        Specified by:
        removeMessageHandler in interface Session
        Parameters:
        handler - the handler to be removed.
      • getRequestURI

        public java.net.URI getRequestURI()
        Description copied from interface: Session
        Return the complete URI under which this session was opened, from protocol to query string (if present). The URI should be identical to the complete URI used for the HTTP request that was upgraded to WebSocket apart from the protocol which should be changed to ws or wss as appropriate. It is the URI associated with the HTTP request that received the 101 Switching Protocols response that is used as the basis for this value - not an earlier, redirected request - if any.
        Specified by:
        getRequestURI in interface Session
        Returns:
        the request URI.
      • getRequestParameterMap

        public java.util.Map<java.lang.String,​java.util.List<java.lang.String>> getRequestParameterMap()
        Description copied from interface: Session
        Return the request parameters associated with the request this session was opened under. The request parameters will have been part of the HTTP upgrade request which is limited by RFC 6455 to only use the HTTP GET method. Therefore, the parameters in the returned Map will be a representation of the parameters contained in the query string.
        Specified by:
        getRequestParameterMap in interface Session
        Returns:
        the unmodifiable map of the request parameters.
      • getPathParameters

        public java.util.Map<java.lang.String,​java.lang.String> getPathParameters()
        Description copied from interface: Session
        Return a map of the path parameter names and values used associated with the request this session was opened under.
        Specified by:
        getPathParameters in interface Session
        Returns:
        the unmodifiable map of path parameters. The key of the map is the parameter name, the values in the map are the parameter values.
      • getUserProperties

        public java.util.Map<java.lang.String,​java.lang.Object> getUserProperties()
        Description copied from interface: Session
        While the session is open, this method returns a Map that the developer may use to store application specific information relating to this session instance. The developer may retrieve information from this Map at any time between the opening of the session and during the onClose() method. But outside that time, any information stored using this Map may no longer be kept by the container. Web socket applications running on distributed implementations of the web container should make any application specific objects stored here java.io.Serializable, or the object may not be recreated after a failover.

        For server sessions, the initial contents of this Map must be a shallow copy of the user properties map returned from jakarta.websocket.server.ServerEndpointConfig#getUserProperties() at the point the jakarta.websocket.server.ServerEndpointConfig.Configurator#modifyHandshake() method exits.

        For client sessions, the initial contents of this Map must be a shallow copy of the user properties map returned from EndpointConfig.getUserProperties() for the ClientEndpointConfig passed to WebSocketContainer.connectToServer(Class, ClientEndpointConfig, URI) or WebSocketContainer.connectToServer(Endpoint, ClientEndpointConfig, URI).

        Specified by:
        getUserProperties in interface Session
        Returns:
        an editable Map of application data.
      • getDistributedProperties

        public java.util.Map<java.lang.String,​java.lang.Object> getDistributedProperties()
        Description copied from interface: DistributedSession
        Get distributed properties.

        Values put into this map must be Serializable or serializable by other, implementation-dependent alternative.

        Content of this map is synchronized among all cluster nodes, so putting an entry on any of the nodes will be visible on all other nodes which have reference to current session (in form of TyrusSession or RemoteSession).

        Please note that when not running in the distributed environment, this map behaves similarly to Session.getUserProperties(), so no serialization or deserialization is performed when values are read from or stored to the returned map.

        Specified by:
        getDistributedProperties in interface DistributedSession
        Returns:
        map of distributed properties.
        See Also:
        TyrusSession, RemoteSession
      • getQueryString

        public java.lang.String getQueryString()
        Description copied from interface: Session
        Return the query string associated with the request this session was opened under.
        Specified by:
        getQueryString in interface Session
        Returns:
        the query string
      • getId

        public java.lang.String getId()
        Description copied from interface: Session
        Returns a string containing the unique identifier assigned to this session. The identifier is assigned by the web socket implementation and is implementation dependent.
        Specified by:
        getId in interface Session
        Returns:
        the unique identifier for this session instance.
      • getUserPrincipal

        public java.security.Principal getUserPrincipal()
        Description copied from interface: Session
        Return the authenticated user for this Session or null if no user is authenticated for this session.
        Specified by:
        getUserPrincipal in interface Session
        Returns:
        the user principal.
      • broadcast

        public java.util.Map<Session,​java.util.concurrent.Future<?>> broadcast​(java.lang.String message)
        Broadcasts text message to all connected clients.

        The broadcast can be executed in parallel, which can be enabled by setting TyrusWebSocketEngine.PARALLEL_BROADCAST_ENABLED to true in server properties.

        Parameters:
        message - message to be broadcasted.
        Returns:
        map of local sessions and futures for user to get the information about status of the message.
      • broadcast

        public java.util.Map<Session,​java.util.concurrent.Future<?>> broadcast​(java.nio.ByteBuffer message)
        Broadcasts binary message to all connected clients, including remote sessions (if any).

        The broadcast can be executed in parallel, which can be enabled by setting TyrusWebSocketEngine.PARALLEL_BROADCAST_ENABLED to true in server properties.

        Parameters:
        message - message to be broadcasted.
        Returns:
        map of local sessions and futures for user to get the information about status of the message.
      • getHeartbeatInterval

        public long getHeartbeatInterval()
        Return an interval in milliseconds between scheduled periodic Pong messages. A negative value or 0 means that sending of periodic Pong messages is not turned on.
        Returns:
        heartbeatInterval interval between periodic pong messages in milliseconds.
      • setHeartbeatInterval

        public void setHeartbeatInterval​(long heartbeatInterval)
        Set an interval in milliseconds between scheduled periodic Pong messages. Setting the interval to a negative value or 0 will cancel sending of periodic Pong messages.
        Parameters:
        heartbeatInterval - interval between periodic Pong messages in milliseconds.
      • toString

        public java.lang.String toString()
        Overrides:
        toString in class java.lang.Object
      • getRemoteAddr

        public java.lang.String getRemoteAddr()
        Get the Internet Protocol (IP) address of the client or last proxy that sent the request.
        Returns:
        a String containing the IP address of the client that sent the request or null when method is called on client-side.