- socket
Available since OmniFaces 2.3
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 rawMessageEvent
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 <h: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 andCloseReason.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 rawCloseEvent
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 is1000
, then it was normally closed due to an expired session or view. Else if this is not1000
, then there may be an error. See also RFC 6455 section 7.4.1 andCloseReason.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 rawCloseEvent
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 FunctionalInterface
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 <h:commandScript>
. E.g.
<h:panelGroup id="foo">
... (some complex UI here) ...
</h:panelGroup>
<o:socket channel="someChannel" scope="view" onmessage="someCommandScript" />
<h:form>
<h: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}
.
Global counter
Below is a static counter which has the same value application wide.
55
Realtime stats
You can find here another example of push:
realtime stats.
This example makes use of CDI events with BeanManager#fireEvent()
and @Observes
.
The custom PageView
event is fired in getPage()
method of
App
class.
Scopes and users
You can find here a generic test page of push: scopes and users. This example opens three web sockets of which one is an user-targeted session scoped socket. If you open the same page in a new tab/window in current browser, then you can test application/session/view scoped push. If you open the same page in an incognito window or a different browser, then you can test application scoped push and user-targeted push.
- Demo
- PushBean
- push-stats.xhtml
- PushStatsBean
- push-stats-pageView.xhtml
- PageView
- push-test.xhtml
- PushTestBean
<h3>Global counter</h3>
<p>
Below is a static counter which has the same value application wide.
</p>
<h1><h:panelGroup id="count">#{pushBean.count}</h:panelGroup></h1>
<h:form>
<p>
If you enable the push, then a websocket will be opened.
Note that it's by default always auto-connected when included in the page, but for demo purposes we're initially disabling it.
</p>
<p>
<h:panelGroup id="toggle">
Push is #{pushBean.connected ? 'connected' : 'disconnected'}
<h:commandButton value="#{pushBean.connected ? 'disconnect' : 'connect'} it" action="#{pushBean.toggle}">
<f:ajax render="toggle increment :count"/>
</h:commandButton>
</h:panelGroup>
</p>
<p>
If push is connected and you press the "increment!" button, then the static counter will increment in bean and the push will send out the new value to the same channel in all connected clients.
To see it yourself, open the same page in multiple tabs/windows/browsers/machines and trigger the push in only one of it.
Note that the counter also won't increment from other side if push is still disconnected on current page.
</p>
<p>
<h:commandButton id="increment" value="increment!" action="#{pushBean.increment}" disabled="#{not pushBean.connected}">
<f:ajax />
</h:commandButton>
</p>
</h:form>
<!-- NOTE: having inline script in XHTML like below is bad practice. -->
<!-- It's included directly in XHTML just for sake of demo. -->
<!-- In real world code, put it in a JS file :) -->
<script>
function updateCounter(newvalue) {
$("#count").text(newvalue);
}
function onclosePush(code) {
if (code == -1) {
alert("Oops! Your browser doesn't seem to support web sockets. The push functionality won't work.")
}
else if (code != 1000) {
alert("Oops! Push has stopped working with error code " + code + "! Reload the page.")
}
}
</script>
<!-- End of bad practice ;) -->
<o:socket channel="counter" onmessage="updateCounter" onclose="onclosePush" connected="#{pushBean.connected}" />
<h3>Realtime stats</h3>
<p>
You can find here another example of push:
<h:link value="realtime stats" outcome="/push-stats" />.
This example makes use of CDI events with <code>BeanManager#fireEvent()</code> and <code>@Observes</code>.
The custom <code>PageView</code> event is fired in <code>getPage()</code> method of
<a href="https://github.com/omnifaces/showcase/blob/master/src/main/java/org/omnifaces/showcase/App.java"><code>App</code></a>
class.
</p>
<h3>Scopes and users</h3>
<p>
You can find here a generic test page of push:
<h:link value="scopes and users" outcome="/push-test" />.
This example opens three web sockets of which one is an user-targeted session scoped socket.
If you open the same page in a new tab/window in current browser, then you can test application/session/view scoped push.
If you open the same page in an incognito window or a different browser, then you can test application scoped push and user-targeted push.
</p>
package org.omnifaces.showcase.push;
import java.io.Serializable;
import java.util.concurrent.atomic.AtomicLong;
import jakarta.inject.Inject;
import jakarta.inject.Named;
import org.omnifaces.cdi.Push;
import org.omnifaces.cdi.PushContext;
import org.omnifaces.cdi.ViewScoped;
@Named
@ViewScoped
public class PushBean implements Serializable {
private static AtomicLong counter = new AtomicLong();
private boolean connected;
@Inject @Push(channel="counter")
private PushContext push;
public void toggle() {
connected = !connected;
}
public void increment() {
long newvalue = counter.incrementAndGet();
push.send(newvalue);
}
public boolean isConnected() {
return connected;
}
public Long getCount() {
return counter.get();
}
}
<ui:composition template="/WEB-INF/templates/layout.xhtml"
xmlns="http://www.w3.org/1999/xhtml"
xmlns:f="jakarta.faces.core"
xmlns:h="jakarta.faces.html"
xmlns:ui="jakarta.faces.facelets"
xmlns:o="http://omnifaces.org/ui"
>
<ui:define name="contentTitle">Push - Stats</ui:define>
<ui:define name="content">
<p>
This demo page shows last #{pushStatsBean.maxLastPageViews} page views (on current server node; only requests with a valid referrer).
Every new page view will be pushed to top of below list and oldest (bottom) entry will be removed.
Source code of this page can be found in <h:link value="o:socket showcase page" outcome="/push/socket" />.
</p>
<!-- NOTE: having inline script and style in XHTML like below is bad practice. -->
<!-- They're included directly in XHTML just for sake of demo. -->
<!-- In real world code, put them in a JS and CSS file :) -->
<style>
#stats {
list-style-type: none;
padding: .5em;
font-size: .8em;
background: #fff;
}
#stats li {
padding: .5em;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
#stats:not(.inversed) li:nth-child(odd),
#stats.inversed li:nth-child(even) {
background: #eee;
}
</style>
<script>
function updateStats(pageView) {
var $pageViewTemplate = $($("#pageViewTemplate").html());
$pageViewTemplate.find(".timestamp").text(pageView.timestamp);
$pageViewTemplate.find(".uri").text(pageView.uri).attr("href", pageView.uri);
$pageViewTemplate.find(".userHash").text(pageView.userHash);
$pageViewTemplate.find(".userAgent").text(pageView.userAgent);
$pageViewTemplate.find(".referrer").text(pageView.referrer);
var $stats = $("#stats");
$pageViewTemplate.hide().prependTo($stats.toggleClass("inversed")).slideDown();
$stats.children().slice($stats.data("max")).slideUp(function() { $(this).remove(); });
}
</script>
<!-- End of bad practice ;) -->
<ul id="stats" data-max="#{pushStatsBean.maxLastPageViews}">
<ui:repeat value="#{lastPageViews}" var="pageView">
<ui:include src="/WEB-INF/includes/demo/push-stats-pageView.xhtml" />
</ui:repeat>
</ul>
<script id="pageViewTemplate" type="text/html">
<ui:include src="/WEB-INF/includes/demo/push-stats-pageView.xhtml" />
</script>
<o:socket channel="stats" onmessage="updateStats" />
</ui:define>
</ui:composition>
package org.omnifaces.showcase.push;
import java.util.ArrayList;
import java.util.Deque;
import java.util.List;
import java.util.concurrent.LinkedBlockingDeque;
import jakarta.annotation.PostConstruct;
import jakarta.enterprise.event.Observes;
import jakarta.enterprise.inject.Model;
import jakarta.enterprise.inject.Produces;
import jakarta.inject.Inject;
import jakarta.inject.Named;
import org.omnifaces.cdi.Push;
import org.omnifaces.cdi.PushContext;
import org.omnifaces.cdi.Startup;
import org.omnifaces.showcase.PageView;
@Named
@Startup
public class PushStatsBean {
private static final int MAX_LAST_PAGE_VIEWS = 20;
private Deque<PageView> lastPageViews;
@Inject @Push
private PushContext stats;
@PostConstruct
public void init() {
lastPageViews = new LinkedBlockingDeque<>(MAX_LAST_PAGE_VIEWS);
}
public void onPageView(@Observes PageView pageView) {
while (!lastPageViews.offerFirst(pageView)) {
lastPageViews.pollLast();
}
stats.send(pageView);
}
public int getMaxLastPageViews() {
return MAX_LAST_PAGE_VIEWS;
}
@Produces @Model
public List<PageView> getLastPageViews() {
return new ArrayList<>(lastPageViews);
}
}
<ui:composition
xmlns="http://www.w3.org/1999/xhtml"
xmlns:ui="jakarta.faces.facelets"
>
<li>
Timestamp: <span class="timestamp">#{pageView.timestamp}</span><br/>
Page URI: <a class="uri" href="#{pageView.uri}">#{pageView.uri}</a><br/>
User hash: <span class="userHash">#{pageView.userHash}</span><br/>
User agent: <span class="userAgent">#{pageView.userAgent}</span><br/>
Referrer: <span class="referrer">#{pageView.referrer}</span><br/>
</li>
</ui:composition>
/*
* Copyright 2020 OmniFaces.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*/
package org.omnifaces.showcase;
import static org.omnifaces.util.Servlets.getRequestURI;
import java.time.LocalDateTime;
import jakarta.servlet.http.HttpServletRequest;
public final class PageView {
private final String timestamp;
private final String uri;
private final String userHash;
private final String userAgent;
private final String referrer;
public PageView(HttpServletRequest request) {
timestamp = LocalDateTime.now().toString();
uri = getRequestURI(request).split(";")[0];
String sessionId = request.getSession().getId();
userHash = Integer.toHexString(sessionId.substring(0, sessionId.length() / 2).hashCode());
userAgent = request.getHeader("user-agent");
referrer = request.getHeader("referer").split(";")[0];
}
public String getTimestamp() {
return timestamp;
}
public String getUri() {
return uri;
}
public String getUserHash() {
return userHash;
}
public String getUserAgent() {
return userAgent;
}
public String getReferrer() {
return referrer;
}
}
<ui:composition template="/WEB-INF/templates/layout.xhtml"
xmlns="http://www.w3.org/1999/xhtml"
xmlns:f="jakarta.faces.core"
xmlns:h="jakarta.faces.html"
xmlns:ui="jakarta.faces.facelets"
xmlns:a="jakarta.faces.passthrough"
xmlns:c="jakarta.tags.core"
xmlns:o="http://omnifaces.org/ui"
>
<ui:define name="contentTitle">Push - Test</ui:define>
<ui:define name="content">
<p>
Here you can test various push scopes and users.
Source code of this page can be found in <h:link value="o:socket showcase page" outcome="/push/socket" />.
</p>
<!-- NOTE: having inline script in XHTML like below is bad practice. -->
<!-- It's included directly in XHTML just for sake of demo. -->
<!-- In real world code, put it in a JS file :) -->
<script>
function pushListener(message, channel) {
$("#" + channel + "-message").text(message).stop(true, true).effect("highlight");
}
function sessionCloseListener(code) {
if (code == 1000) {
alert("Session has expired! Page will be reloaded.");
window.location.reload(true);
}
}
</script>
<!-- End of bad practice ;) -->
<c:if test="#{empty pushTestUser}">
<h:form>
<p>
Pressing <h:commandButton value="this button" action="#{pushTestBean.open}" /> will open three web sockets and generate an user ID.
</p>
</h:form>
</c:if>
<c:if test="#{not empty pushTestUser}">
<p>The following web sockets are opened and any push message will be printed directly thereafter:</p>
<ul>
<li>Application scoped socket <strong><span id="app-message" /></strong></li>
<li>Session scoped socket with user <strong><span id="sess-message" /></strong></li>
<li>View scoped socket <strong><span id="view-message" /></strong></li>
</ul>
<o:socket channel="app" scope="application" onmessage="pushListener" />
<o:socket channel="sess" scope="session" user="#{pushTestUser}" onmessage="pushListener" onclose="sessionCloseListener" />
<o:socket channel="view" scope="view" onmessage="pushListener" />
<p>
You can use the below buttons to send the current server side timestamp to those sockets.
If you open the same page in a new tab/window in current browser, then you can test application/session/view scoped push.
If you open the same page in an incognito window or a different browser, then you can test application scoped push.
</p>
<h:form>
<f:ajax>
<ul>
<li><h:commandButton action="#{pushTestBean.pushApp}" value="push application scoped socket" /></li>
<li><h:commandButton action="#{pushTestBean.pushSess}" value="push session scoped socket" /></li>
<li><h:commandButton action="#{pushTestBean.pushView}" value="push view scoped socket" /></li>
</ul>
</f:ajax>
</h:form>
<p>
The generated user ID of the current session is <h:inputText value="#{pushTestUser}" size="32" readonly="true" onmouseup="$(this).select()" />.
Open this page in an incognito tab or a different browser to simulate a different user and test user-targeted push.
Use the above user ID to target the current page over there in below form.
It will send the current timestamp to the session scoped socket of the given user.
</p>
<h:form>
<h:inputText binding="#{recipientUser}" a:placeholder="Paste generated user ID of other user here" size="32"
required="true" requiredMessage="Seriously, paste generated user ID of other user in that input field" />
<h:commandButton action="#{pushTestBean.pushUser(recipientUser.value)}" value="push session scoped socket of given user">
<f:ajax execute="@form" render="@form" />
</h:commandButton>
<h:messages />
</h:form>
<p>
Additionally, when the session scoped push socket is closed with reason code 1000,
an annoying 90's JavaScript alert will show up telling you this fact after which the page will be reloaded.
</p>
</c:if>
</ui:define>
</ui:composition>
package org.omnifaces.showcase.push;
import static org.omnifaces.util.Faces.refresh;
import static org.omnifaces.util.Faces.setSessionAttribute;
import static org.omnifaces.util.Messages.addGlobalError;
import static org.omnifaces.util.Messages.addGlobalInfo;
import java.io.IOException;
import java.io.Serializable;
import java.time.LocalDateTime;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.Future;
import jakarta.inject.Inject;
import jakarta.inject.Named;
import org.omnifaces.cdi.Push;
import org.omnifaces.cdi.PushContext;
import org.omnifaces.cdi.ViewScoped;
@Named
@ViewScoped
public class PushTestBean implements Serializable {
@Inject @Push
private PushContext app;
@Inject @Push
private PushContext sess;
@Inject @Push
private PushContext view;
public void open() throws IOException {
setSessionAttribute("pushTestUser", UUID.randomUUID().toString());
refresh();
}
public void pushApp() {
app.send(LocalDateTime.now().toString());
}
public void pushSess() {
sess.send(LocalDateTime.now().toString());
}
public void pushView() {
view.send(LocalDateTime.now().toString());
}
public void pushUser(String recipientUser) {
Set<Future<Void>> sent = sess.send(LocalDateTime.now().toString(), recipientUser);
if (sent.isEmpty()) {
addGlobalError("This user does not exist!");
}
else {
addGlobalInfo("Sent to {0} sockets", sent.size());
}
}
}
VDL documentation
API documentation
Java source code
org.omnifaces.cdi.push.SocketPushContext
org.omnifaces.cdi.push.SocketSessionManager
org.omnifaces.cdi.push.SocketEvent
org.omnifaces.cdi.Push
org.omnifaces.cdi.push.SocketPushContextProducer
org.omnifaces.cdi.push.SocketEndpoint
org.omnifaces.cdi.PushContext
org.omnifaces.cdi.push.SocketChannelManager
org.omnifaces.cdi.push.SocketUserManager
org.omnifaces.cdi.push.Socket