Class Socket

  • All Implemented Interfaces:
    ClientBehaviorHolder, PartialStateHolder, StateHolder, TransientStateHolder, ComponentSystemEventListener, FacesListener, SystemEventListenerHolder, EventListener

    public class Socket
    extends ScriptFamily
    implements ClientBehaviorHolder

    The <o:socket> is an UIComponent whith opens an one-way (server to client) web socket based push connection in client side which can be reached from server side via PushContext interface injected in any CDI/container managed artifact via @Push annotation.

    Configuration

    First enable the web socket endpoint by below boolean context parameter in web.xml:

     <context-param>
         <param-name>org.omnifaces.SOCKET_ENDPOINT_ENABLED</param-name>
         <param-value>true</param-value>
     </context-param>
     

    It will install the SocketEndpoint. Lazy initialization of the endpoint via component is unfortunately not possible across all containers (yet). See also WS spec issue 211.

    Usage (client)

    Declare <o:socket> tag in the Faces view with at least a channel name and an onmessage JavaScript listener function. The channel name may not be an EL expression and it may only contain alphanumeric characters, hyphens, underscores and periods.

    Here's an example which refers an existing JavaScript listener function (do not include the parentheses!).

     <o:socket channel="someChannel" onmessage="socketListener" />
     
     function socketListener(message, channel, event) {
         console.log(message);
     }
     

    Here's an example which declares an inline JavaScript listener function.

     <o:socket channel="someChannel" onmessage="function(message) { console.log(message); }" />
     

    The onmessage JavaScript listener function will be invoked with three arguments:

    • message: the push message as JSON object.
    • channel: the channel name, useful in case you intend to have a global listener, or want to manually control the close.
    • event: the raw MessageEvent instance, useful in case you intend to inspect it.

    In case your server is configured to run WS container on a different TCP port than the HTTP container, then you can use the optional port attribute to explicitly specify the port.

     <o:socket port="8000" ... />
     

    When successfully connected, the web socket is by default open as long as the document is open, and it will auto-reconnect at increasing intervals when the connection is closed/aborted as result of e.g. a network error or server restart. It will not auto-reconnect when the very first connection attempt already fails. The web socket will be implicitly closed once the document is unloaded (e.g. navigating away, close of browser window/tab, etc).

    In order to successfully reconnect after a server restart, or when switching to a new server node, you need to ensure that session persistence is enabled on the server.

    Usage (server)

    In WAR side, you can inject PushContext via @Push annotation on the given channel name in any CDI/container managed artifact such as @Named, @WebServlet, etc wherever you'd like to send a push message and then invoke PushContext.send(Object) with any Java object representing the push message.

     @Inject @Push
     private PushContext someChannel;
    
     public void sendMessage(Object message) {
         someChannel.send(message);
     }
     

    By default the name of the channel is taken from the name of the variable into which injection takes place. The channel name can be optionally specified via the channel attribute. The example below injects the push context for channel name foo into a variable named bar.

     @Inject @Push(channel="foo")
     private PushContext bar;
     

    The message object will be encoded as JSON and be delivered as message argument of the onmessage JavaScript listener function associated with the channel name. It can be a plain vanilla String, but it can also be a collection, map and even a javabean. For supported argument types, see also Json.encode(Object).

    Although web sockets support two-way communication, the <o:socket> push is designed for one-way communication, from server to client. In case you intend to send some data from client to server, just continue using Faces ajax the usual way, if necessary from JavaScript on with <o:commandScript> or perhaps <p:remoteCommand> or similar. This has among others the advantage of maintaining the Faces view state, the HTTP session and, importantingly, all security constraints on business service methods. Namely, those security constraints are not available during an incoming web socket message per se. See also a.o. WS spec issue 238.

    Scopes and users

    By default the web socket is application scoped, i.e. any view/session throughout the web application having the same web socket channel open will receive the same push message. The push message can be sent by all users and the application itself. This is useful for application-wide feedback triggered by site itself such as real time updates of a certain page (e.g. site-wide statistics, top100 lists, stock updates, etc).

    The optional scope attribute can be set to session to restrict the push messages to all views in the current user session only. The push message can only be sent by the user itself and not by the application. This is useful for session-wide feedback triggered by user itself (e.g. as result of asynchronous tasks triggered by user specific action).

     <o:socket channel="someChannel" scope="session" ... />
     

    The scope attribute can also be set to view to restrict the push messages to the current view only. The push message will not show up in other views in the same session even if it's the same URL. The push message can only be sent by the user itself and not by the application. This is useful for view-wide feedback triggered by user itself (e.g. progress bar tied to a user specific action on current view).

     <o:socket channel="someChannel" scope="view" ... />
     

    The scope attribute may not be an EL expression and allowed values are application, session and view, case insensitive.

    Additionally, the optional user attribute can be set to the unique identifier of the logged-in user, usually the login name or the user ID. This way the push message can be targeted to a specific user and can also be sent by other users and the application itself. The value of the user attribute must at least implement Serializable and have a low memory footprint, so putting entire user entity is not recommended.

    E.g. when you're using container managed authentication or a related framework/library:

     <o:socket channel="someChannel" user="#{request.remoteUser}" ... />
     

    Or when you have a custom user entity around in EL as #{someLoggedInUser} which has an id property representing its identifier:

     <o:socket channel="someChannel" user="#{someLoggedInUser.id}" ... />
     

    When the user attribute is specified, then the scope defaults to session and cannot be set to application. It can be set to view, but this is kind of unusual and should only be used if the logged-in user represented by user has a shorter lifetime than the HTTP session (e.g. when your application allows changing a logged-in user during same HTTP session without invaliding it — which is in turn poor security practice). If in such case a session scoped socket is reused, undefined behavior may occur when user-targeted push message is sent. It may target previously logged-in user only. This can be solved by setting the scope to view, but better is to fix the logout to invalidate the HTTP session altogether.

    When the user attribute is an EL expression and it changes during an ajax request, then the socket user will be actually switched, even though you did not cover the <o:socket> component in any ajax render/update. So make sure the value is tied to at least a view scoped property in case you intend to control it during the view scope.

    In the server side, the push message can be targeted to the user specified in the user attribute via PushContext.send(Object, Serializable). The push message can be sent by all users and the application itself. This is useful for user-specific feedback triggered by other users (e.g. chat, admin messages, etc) or by application's background tasks (e.g. notifications, event listeners, etc).

     @Inject @Push
     private PushContext someChannel;
    
     public void sendMessage(Object message, User recipientUser) {
         Long recipientUserId = recipientUser.getId();
         someChannel.send(message, recipientUserId);
     }
     

    Multiple users can be targeted by passing a Collection holding user identifiers to PushContext.send(Object, Collection).

     public void sendMessage(Object message, Group recipientGroup) {
         Collection<Long> recipientUserIds = recipientGroup.getUserIds();
         someChannel.send(message, recipientUserIds);
     }
     

    Channel design hints

    You can declare multiple push channels on different scopes with or without user target throughout the application. Be however aware that the same channel name can easily be reused across multiple views, even if it's view scoped. It's more efficient if you use as few different channel names as possible and tie the channel name to a specific push socket scope/user combination, not to a specific Faces view. In case you intend to have multiple view scoped channels for different purposes, best is to use only one view scoped channel and have a global JavaScript listener which can distinguish its task based on the delivered message. E.g. by sending the message in server as below:

     Map<String, Object> message = new HashMap<>();
     message.put("functionName", "someFunction");
     message.put("functionData", functionData); // Can be Map or Bean.
     someChannel.send(message);
     

    Which is processed in the onmessage JavaScript listener function as below:

     function someSocketListener(message) {
         window[message.functionName](message.functionData);
     }
    
     function someFunction(data) {
         // ...
     }
    
     function otherFunction(data) {
         // ...
     }
    
     // ...
     

    Conditionally connecting

    You can use the optional connected attribute to control whether to auto-connect the web socket or not.

     <o:socket ... connected="#{bean.pushable}" />
     

    It defaults to true and it's under the covers interpreted as a JavaScript instruction whether to open or close the web socket push connection. If the value of the connected or rendered attribute is an EL expression and it becomes false during an ajax request, then any opened push connection will explicitly be closed during oncomplete of that ajax request, even though you did not cover the <o:socket> component in ajax render/update. So make sure the value is tied to at least a view scoped property in case you intend to control it during the view scope.

    You can also explicitly set it to false and manually open the push connection in client side by invoking OmniFaces.Push.open(channel), passing the channel name, for example in an onclick listener function of a command button which initiates a long running asynchronous task in server side. This is particularly useful on view scoped sockets which doesn't necessarily need to immediately open on page load.

     <h:commandButton ... onclick="OmniFaces.Push.open('foo')">
         <f:ajax ... />
     </h:commandButton>
     <o:socket channel="foo" scope="view" ... connected="false" />
     

    In case you intend to have an one-time push and don't expect more messages, usually because you only wanted to present the result of an one-time asynchronous action in a manually opened view scoped push socket as in above example, you can optionally explicitly close the push connection from client side by invoking OmniFaces.Push.close(channel), passing the channel name. For example, in the onmessage JavaScript listener function as below:

     function someSocketListener(message, channel) {
         // ...
         OmniFaces.Push.close(channel);
     }
     

    Noted should be that both ways should not be mixed. Choose either the server side way of an EL expression in connected attribute, or the client side way of explicitly setting connected="false" and manually invoking OmniFaces.Push functions. Mixing them ends up in undefined behavior because the associated Faces view state in the server side can't be notified if a socket is manually opened in client side.

    Events (client)

    The optional onopen JavaScript listener function can be used to listen on open of a web socket in client side. This will be invoked on the very first connection attempt, regardless of whether it will be successful or not. This will not be invoked when the web socket auto-reconnects a broken connection after the first successful connection.

     <o:socket ... onopen="socketOpenListener" />
     
     function socketOpenListener(channel) {
         // ...
     }
     

    The onopen JavaScript listener function will be invoked with one argument:

    • channel: the channel name, useful in case you intend to have a global listener.

    The optional onerror JavaScript listener function can be used to listen on a connection error whereby the web socket will attempt to reconnect. This will be invoked when the web socket can make an auto-reconnect attempt on a broken connection after the first successful connection. This will be not invoked when the very first connection attempt fails, or the server has returned close reason code 1000 (normal closure) or 1008 (policy violated), or the maximum reconnect attempts has exceeded. Instead, the onclose will be invoked.

     <o:socket ... onerror="socketErrorListener" />
     
     function socketErrorListener(code, channel, event) {
         if (code == 1001) {
             // Server has returned an unexpected response code. E.g. 503, because it's shutting down.
         } else if (code == 1006) {
             // Server is not reachable anymore. I.e. it's not anymore listening on TCP/IP requests.
         } else {
             // Any other reason which is usually not -1, 1000 or 1008, as the onclose will be invoked instead.
         }
    
         // In any case, the web socket will attempt to reconnect. This function will be invoked again.
         // Once the web socket gives up reconnecting, the onclose will finally be invoked.
     }
     

    The onerror JavaScript listener function will be invoked with three arguments:

    • code: the close reason code as integer. See also RFC 6455 section 7.4.1 and CloseReason.CloseCodes API for an elaborate list of all close codes.
    • channel: the channel name, useful in case you intend to have a global listener.
    • event: the raw CloseEvent instance, useful in case you intend to inspect it.

    The optional onclose JavaScript listener function can be used to listen on (ab)normal close of a web socket. This will be invoked when the very first connection attempt fails, or the server has returned close reason code 1000 (normal closure) or 1008 (policy violated), or the maximum reconnect attempts has exceeded. This will not be invoked when the web socket can make an auto-reconnect attempt on a broken connection after the first successful connection. Instead, the onerror will be invoked.

     <o:socket ... onclose="socketCloseListener" />
     
     function socketCloseListener(code, channel, event) {
         if (code == -1) {
             // Web sockets not supported by client.
         } else if (code == 1000) {
             // Normal close (as result of expired session or view).
         } else {
             // Abnormal close reason (as result of an error).
         }
     }
     

    The onclose JavaScript listener function will be invoked with three arguments:

    • code: the close reason code as integer. If this is -1, then the web socket is simply not supported by the client. If this is 1000, then it was normally closed due to an expired session or view. Else if this is not 1000, then there may be an error. See also RFC 6455 section 7.4.1 and CloseReason.CloseCodes API for an elaborate list of all close codes.
    • channel: the channel name, useful in case you intend to have a global listener.
    • event: the raw CloseEvent instance, useful in case you intend to inspect it.

    When a session or view scoped socket is automatically closed with close reason code 1000 by the server (and thus not manually by the client via OmniFaces.Push.close(channel)), then it means that the session or view has expired. In case of a session scoped socket you could take the opportunity to let JavaScript show a "Session expired" message and/or immediately redirect to the login page via window.location. In case of a view scoped socket the handling depends on the reason of the view expiration. A view can be expired when the associated session has expired, but it can also be expired as result of (accidental) navigation or rebuild, or when the Faces "views per session" configuration setting is set relatively low and the client has many views (windows/tabs) open in the same session. You might take the opportunity to warn the client and/or let JavaScript reload the page as submitting any form in it would throw ViewExpiredException anyway.

    Events (server)

    When a web socket has been opened, a new CDI SocketEvent will be fired with @SocketEvent.Opened qualifier. When the user attribute of the <o:socket> changes, a new CDI SocketEvent will be fired with @SocketEvent.Switched qualifier. When a web socket has been closed, a new CDI SocketEvent will be fired with @SocketEvent.Closed qualifier. They can only be observed and collected in an application scoped CDI bean as below. Observing in a request/view/session scoped CDI bean is not possible as there's no means of a HTTP request anywhere at that moment.

     @ApplicationScoped
     public class SocketObserver {
    
         public void onOpen(@Observes @Opened SocketEvent event) {
             String channel = event.getChannel(); // Returns <o:socket channel>.
             Long userId = event.getUser(); // Returns <o:socket user>, if any.
             // Do your thing with it. E.g. collecting them in a concurrent/synchronized collection.
             // Do note that a single person can open multiple sockets on same channel/user.
         }
    
         public void onSwitch(@Observes @Switched SocketEvent event) {
             String channel = event.getChannel(); // Returns <o:socket channel>.
             Long currentUserId = event.getUser(); // Returns current <o:socket user>, if any.
             Long previousUserId = event.getPreviousUser(); // Returns previous <o:socket user>, if any.
             // Do your thing with it. E.g. updating in a concurrent/synchronized collection.
         }
    
         public void onClose(@Observes @Closed SocketEvent event) {
             String channel = event.getChannel(); // Returns <o:socket channel>.
             Long userId = event.getUser(); // Returns <o:socket user>, if any.
             CloseCode code = event.getCloseCode(); // Returns close reason code.
             // Do your thing with it. E.g. removing them from collection.
         }
    
     }
     

    You could take the opportunity to send another push message to an application scoped socket, e.g. "User X has been logged in" (or out) when a session scoped socket is opened (or closed).

    Security considerations

    If the socket is declared in a page which is only restricted to logged-in users with a specific role, then you may want to add the URL of the push handshake request URL to the set of restricted URLs.

    The push handshake request URL is composed of the URI prefix /omnifaces.push/, followed by channel name. So, in case of for example container managed security which has already restricted an example page /user/foo.xhtml to logged-in users with the example role USER on the example URL pattern /user/* in web.xml like below,

     <security-constraint>
         <web-resource-collection>
             <web-resource-name>Restrict access to role USER.</web-resource-name>
             <url-pattern>/user/*</url-pattern>
         </web-resource-collection>
         <auth-constraint>
             <role-name>USER</role-name>
         </auth-constraint>
     </security-constraint>
     

    .. and the page /user/foo.xhtml in turn contains a <o:socket channel="foo">, then you need to add a restriction on push handshake request URL pattern of /omnifaces.push/foo like below.

     <security-constraint>
         <web-resource-collection>
             <web-resource-name>Restrict access to role USER.</web-resource-name>
             <url-pattern>/user/*</url-pattern>
             <url-pattern>/omnifaces.push/foo</url-pattern>
         </web-resource-collection>
         <auth-constraint>
             <role-name>USER</role-name>
         </auth-constraint>
     </security-constraint>
     

    As extra security, particularly for those public channels which can't be restricted by security constraints, the <o:socket> will register all so far declared channels in the current HTTP session, and any incoming web socket open request will be checked whether they match the so far registered channels in the current HTTP session. In case the channel is unknown (e.g. randomly guessed or spoofed by endusers or manually reconnected after the session is expired), then the web socket will immediately be closed with close reason code 1008 (CloseReason.CloseCodes.VIOLATED_POLICY). Also, when the HTTP session gets destroyed, all session and view scoped channels which are still open will explicitly be closed from server side with close reason code 1000 (CloseReason.CloseCodes.NORMAL_CLOSURE). Only application scoped sockets remain open and are still reachable from server end even when the session or view associated with the page in client side is expired.

    EJB design hints

    In case you'd like to trigger a push from EAR/EJB side to an application scoped push socket, then you could make use of CDI events. First create a custom bean class representing the push event something like PushEvent below taking whatever you'd like to pass as push message.

     public final class PushEvent {
    
         private final String message;
    
         public PushEvent(String message) {
             this.message = message;
         }
    
         public String getMessage() {
             return message;
         }
     }
     

    Then use BeanManager.fireEvent(Object, java.lang.annotation.Annotation...) to fire the CDI event.

     @Inject
     private BeanManager beanManager;
    
     public void onSomeEntityChange(Entity entity) {
         beanManager.fireEvent(new PushEvent(entity.getSomeProperty()));
     }
     

    Note that OmniFaces own Beans.fireEvent(Object, java.lang.annotation.Annotation...) utility method is insuitable as it is not allowed to use WAR (front end) frameworks and libraries like Faces and OmniFaces in EAR/EJB (back end) side.

    Finally just @Observes it in some request or application scoped CDI managed bean in WAR and delegate to PushContext as below.

     @Inject @Push
     private PushContext someChannel;
    
     public void onPushEvent(@Observes PushEvent event) {
         someChannel.send(event.getMessage());
     }
     

    Note that a request scoped bean wouldn't be the same one as from the originating page for the simple reason that there's no means of a HTTP request anywhere at that moment. For exactly this reason a view and session scoped bean would not work (as they require respectively the Faces view state and HTTP session which can only be identified by a HTTP request). A view and session scoped push socket would also not work, so the push socket really needs to be application scoped. The FacesContext will also be unavailable in the above event listener method.

    In case the trigger in EAR/EJB side is an asynchronous service method which is in turn initiated in WAR side, then you could make use of callbacks from WAR side. Let the business service method take a callback instance as argument, e.g. the java.util.function.Consumer functional interface.

     @Asynchronous
     public void someAsyncServiceMethod(Entity entity, Consumer<Object> callback) {
         // ... (some long process)
         callback.accept(entity.getSomeProperty());
     }
     

    And invoke the asynchronous service method in WAR as below.

     @Inject
     private SomeService someService;
    
     @Inject @Push
     private PushContext someChannel;
    
     public void someAction() {
         someService.someAsyncServiceMethod(entity, message -> someChannel.send(message));
     }
     

    This would be the only way in case you intend to asynchronously send a message to a view or session scoped push socket, and/or want to pass something from FacesContext or the initial request/view/session scope along as (final) argument.

    In case you're not on Java 8 yet, then you can make use of Runnable as callback instance instead of the above Consumer functional interface example.

     @Asynchronous
     public void someAsyncServiceMethod(Entity entity, Runnable callback) {
         // ... (some long process)
         entity.setSomeProperty(someProperty);
         callback.run();
     }
     

    Which is invoked in WAR as below.

     public void someAction() {
         someService.someAsyncServiceMethod(entity, new Runnable() {
             public void run() {
                 someChannel.send(entity.getSomeProperty());
             }
         });
     }
     

    Note that OmniFaces own Callback interfaces are insuitable as it is not allowed to use WAR (front end) frameworks and libraries like Faces and OmniFaces in EAR/EJB (back end) side.

    Cluster design hints

    In case your web application is deployed to a server cluster with multiple nodes, and the push event could be triggered in a different node than where the client is connected to, then it won't reach the socket. One solution is to activate and configure a JMS topic in the server configuration, trigger the push event via JMS instead of CDI, and use a JMS listener (a message driven bean, MDB) to delegate the push event to CDI.

    Below is an example extending on the above given EJB example.

     @Singleton
     @TransactionAttribute(NOT_SUPPORTED)
     public class PushManager {
    
         @Resource(lookup = "java:/jms/topic/push")
         private Topic jmsTopic;
    
         @Inject
         private JMSContext jmsContext;
    
         public void fireEvent(PushEvent pushEvent) {
             try {
                 Message jmsMessage = jmsContext.createMessage();
                 jmsMessage.setStringProperty("message", pushEvent.getMessage());
                 jmsContext.createProducer().send(jmsTopic, jmsMessage);
             }
             catch (Exception e) {
                 // Handle.
             }
         }
     }
     
     @MessageDriven(activationConfig = {
         @ActivationConfigProperty(propertyName = "destination", propertyValue = "java:/jms/topic/push")
     })
     public class PushListener implements MessageListener {
    
         @Inject
         private BeanManager beanManager;
    
         @Override
         public void onMessage(Message jmsMessage) {
             try {
                 String message = jmsMessage.getStringProperty("message");
                 beanManager.fireEvent(new PushEvent(message));
             }
             catch (Exception e) {
                 // Handle.
             }
         }
     }
     

    Then, in your EJB, instead of using BeanManager#fireEvent() to fire the CDI event,

     @Inject
     private BeanManager beanManager;
    
     public void onSomeEntityChange(Entity entity) {
         beanManager.fireEvent(new PushEvent(entity.getSomeProperty()));
     }
     

    use the newly created PushManager#fireEvent() to fire the JMS event from one server node of the cluster, which in turn will fire the CDI event in all server nodes of the cluster.

     @Inject
     private PushManager pushManager;
    
     public void onSomeEntityChange(Entity entity) {
         pushManager.fireEvent(new PushEvent(entity.getSomeProperty()));
     }
     

    UI update design hints

    In case you'd like to perform complex UI updates, then easiest would be to put <f:ajax> inside <o:socket>. The support was added in OmniFaces 2.6. Here's an example:

     <h:panelGroup id="foo">
         ... (some complex UI here) ...
     </h:panelGroup>
    
     <h:form>
         <o:socket channel="someChannel" scope="view">
             <f:ajax event="someEvent" listener="#{bean.pushed}" render=":foo" />
         </o:socket>
     </h:form>
     

    Here, the push message simply represents the ajax event name. You can use any custom event name.

     someChannel.send("someEvent");
     

    An alternative is to combine <o:socket> with <o:commandScript>. E.g.

     <h:panelGroup id="foo">
         ... (some complex UI here) ...
     </h:panelGroup>
    
     <o:socket channel="someChannel" scope="view" onmessage="someCommandScript" />
     <h:form>
         <o:commandScript name="someCommandScript" action="#{bean.pushed}" render=":foo" />
     </h:form>
     

    If you pass a Map<String,V> or a JavaBean as push message object, then all entries/properties will transparently be available as request parameters in the command script method #{bean.pushed}.

    Since:
    2.3
    Author:
    Bauke Scholtz
    See Also:
    SocketEndpoint, SocketChannelManager, SocketUserManager, SocketSessionManager, SocketEvent, Push, PushContext, SocketPushContext, SocketPushContextProducer
    • Field Detail

      • COMPONENT_TYPE

        public static final String COMPONENT_TYPE
        The component type, which is "org.omnifaces.cdi.push.Socket".
        See Also:
        Constant Field Values
      • PARAM_SOCKET_ENDPOINT_ENABLED

        public static final String PARAM_SOCKET_ENDPOINT_ENABLED
        The boolean context parameter name to register web socket endpoint during startup.
        See Also:
        Constant Field Values
    • Constructor Detail

      • Socket

        public Socket()
    • Method Detail

      • setValueExpression

        public void setValueExpression​(String name,
                                       ValueExpression binding)
        An override which checks if this isn't been invoked on channel or scope attribute, and if the user attribute is Serializable. Finally it delegates to the super method.
        Overrides:
        setValueExpression in class UIComponent
        Throws:
        IllegalArgumentException - When this value expression is been set on channel or scope attribute, or when the user attribute is not Serializable.
      • encodeChildren

        public void encodeChildren​(FacesContext context)
                            throws IOException
        First check if the web socket endpoint is enabled in web.xml and the channel name and scope is valid, then register it in SocketChannelManager and get the channel ID, then render the init() script. This scripts will in turn hit SocketEndpoint.
        Overrides:
        encodeChildren in class UIComponentBase
        Throws:
        IllegalStateException - When the web socket endpoint is not enabled in web.xml.
        IllegalArgumentException - When the channel name, scope or user is invalid. The channel name may only contain alphanumeric characters, hyphens, underscores and periods. The allowed channel scope values are "application", "session" and "view", case insensitive. The channel name must be uniquely tied to the channel scope. The user, if any, must implement Serializable.
        IOException
      • getPort

        public Integer getPort()
        Returns the port number of the web socket host.
        Returns:
        The port number of the web socket host.
      • setPort

        public void setPort​(Integer port)
        Sets the port number of the web socket host, in case it is different from the port number in the request URI. Defaults to the port number of the request URI.
        Parameters:
        port - The port number of the web socket host.
      • getChannel

        public String getChannel()
        Returns the name of the web socket channel.
        Returns:
        The name of the web socket channel.
      • setChannel

        public void setChannel​(String channel)
        Sets the name of the web socket channel. It may not be an EL expression and it may only contain alphanumeric characters, hyphens, underscores and periods. All open websockets on the same channel will receive the same push message from the server.
        Parameters:
        channel - The name of the web socket channel.
      • getScope

        public String getScope()
        Returns the scope of the web socket channel.
        Returns:
        The scope of the web socket channel.
      • setScope

        public void setScope​(String scope)
        Sets the scope of the web socket channel. It may not be an EL expression and allowed values are application, session and view, case insensitive. When the value is application, then all channels with the same name throughout the application will receive the same push message. When the value is session, then only the channels with the same name in the current user session will receive the same push message. When the value is view, then only the channel in the current view will receive the push message. The default scope is application. When the user attribute is specified, then the default scope is session.
        Parameters:
        scope - The scope of the web socket channel.
      • getUser

        public Serializable getUser()
        Returns the user identifier of the web socket channel.
        Returns:
        The user identifier of the web socket channel.
      • setUser

        public void setUser​(Serializable user)
        Sets the user identifier of the web socket channel, so that user-targeted push messages can be sent. All open websockets on the same channel and user will receive the same push message from the server. It must implement Serializable and preferably have low memory footprint. Suggestion: use #{request.remoteUser} or #{someLoggedInUser.id}.
        Parameters:
        user - The user identifier of the web socket channel.
      • getOnopen

        public String getOnopen()
        Returns the JavaScript event handler function that is invoked when the web socket is opened.
        Returns:
        The JavaScript event handler function that is invoked when the web socket is opened.
      • setOnopen

        public void setOnopen​(String onopen)
        Sets the JavaScript event handler function that is invoked when the web socket is opened. The function will be invoked with one argument: the channel name.
        Parameters:
        onopen - The JavaScript event handler function that is invoked when the web socket is opened.
      • getOnmessage

        public String getOnmessage()
        Returns the JavaScript event handler function that is invoked when a push message is received from the server.
        Returns:
        The JavaScript event handler function that is invoked when a push message is received from the server.
      • setOnmessage

        public void setOnmessage​(String onmessage)
        Sets the JavaScript event handler function that is invoked when a push message is received from the server. The function will be invoked with three arguments: the push message, the channel name and the raw MessageEvent itself.
        Parameters:
        onmessage - The JavaScript event handler function that is invoked when a push message is received from the server.
      • getOnerror

        public String getOnerror()
        Returns the JavaScript event handler function that is invoked when a connection error has occurred and the web socket will attempt to reconnect.
        Returns:
        The JavaScript event handler function that is invoked when a connection error has occurred and the web socket will attempt to reconnect.
        Since:
        3.4
      • setOnerror

        public void setOnerror​(String onerror)
        Sets the JavaScript event handler function that is invoked when a connection error has occurred and the web socket will attempt to reconnect. The function will be invoked with three arguments: the error reason code, the channel name and the raw CloseEvent itself. Note that this will not be invoked on final close of the web socket, even when the final close is caused by an error. See also RFC 6455 section 7.4.1 and CloseReason.CloseCodes API for an elaborate list of all close codes.
        Parameters:
        onerror - The JavaScript event handler function that is invoked when a reconnection error has occurred.
        Since:
        3.4
      • getOnclose

        public String getOnclose()
        Returns the JavaScript event handler function that is invoked when the web socket is closed and will not anymore attempt to reconnect.
        Returns:
        The JavaScript event handler function that is invoked when the web socket is closed and will not anymore attempt to reconnect.
      • setOnclose

        public void setOnclose​(String onclose)
        Sets the JavaScript event handler function that is invoked when the web socket is closed and will not anymore attempt to reconnect. The function will be invoked with three arguments: the close reason code, the channel name and the raw CloseEvent itself. Note that this will also be invoked when the close is caused by an error and that you can inspect the close reason code if an actual connection error occurred and which one (i.e. when the code is not 1000 or 1008). See also RFC 6455 section 7.4.1 and CloseReason.CloseCodes API for an elaborate list of all close codes.
        Parameters:
        onclose - The JavaScript event handler function that is invoked when the web socket is closed.
      • isConnected

        public boolean isConnected()
        Returns whether to (auto)connect the web socket or not.
        Returns:
        Whether to (auto)connect the web socket or not.
      • setConnected

        public void setConnected​(boolean connected)
        Sets whether to (auto)connect the web socket or not. Defaults to true. It's interpreted as a JavaScript instruction whether to open or close the web socket push connection. Note that this attribute is re-evaluated on every ajax request. You can also explicitly set it to false and then manually control in JavaScript by OmniFaces.Push.open("channelName") and OmniFaces.Push.close("channelName").
        Parameters:
        connected - Whether to (auto)connect the web socket or not.
      • registerEndpointIfNecessary

        public static void registerEndpointIfNecessary​(ServletContext context)
        Register web socket endpoint if necessary, i.e. when it's enabled via context param and not already installed.
        Parameters:
        context - The involved servlet context.