Class UIWebsocket
- All Implemented Interfaces:
ClientBehaviorHolder, PartialStateHolder, StateHolder, TransientStateHolder, ComponentSystemEventListener, FacesListener, SystemEventListenerHolder, EventListener
The <f:websocket> tag opens an one-way (server to client) websocket 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.
By default, the rendererType property must be set to "jakarta.faces.Websocket". This value
can be changed by calling the setRendererType() method.
For detailed usage instructions, see @Push javadoc.
- Since:
- 2.3
- See Also:
-
Field Summary
FieldsModifier and TypeFieldDescriptionstatic final StringThe standard component family for this component.static final StringThe standard component type for this component.Fields inherited from class UIComponent
ATTRS_WITH_DECLARED_DEFAULT_VALUES, BEANINFO_KEY, COMPOSITE_COMPONENT_TYPE_KEY, COMPOSITE_FACET_NAME, FACETS_KEY, VIEW_LOCATION_KEYModifier and TypeFieldDescriptionstatic final StringThis constant enables one to quickly discover the names of the declared composite component attributes that have been given default values by the composite component author.static final StringThe value of this constant is used as the key in the component attribute map, the value for which is ajava.beans.BeanInfoimplementation describing the composite component.static final StringThe value of this constant is used as the key in the composite component BeanDescriptor for aValueExpressionthat evaluates to thecomponent-typeof the composite component rootUIComponentfor this composite component, if one was declared by the composite component author.static final StringThe value of this constant is used as the key in theMapreturned as described inUIComponent.FACETS_KEYfor thePropertyDescriptordescribing the composite component facet.static final StringThe value of this constant is used as the key in the composite component BeanDescriptor for theMap<PropertyDescriptor>that contains meta-information for the declared facets for this composite component.static final StringThe value of this constant is used as the key in the component attributesMapfor theLocationin the view at which this component instance resides. -
Constructor Summary
Constructors -
Method Summary
Modifier and TypeMethodDescriptionReturns the name of the websocket channel.Returns a non-null, empty, unmodifiableCollectionwhich returnstrueon anyCollection#contains()invocation, indicating that all client behavior event names are acceptable.ReturnsCOMPONENT_FAMILY.Returns the JavaScript event handler function that is invoked when the websocket is closed and will not anymore attempt to reconnect.Returns the JavaScript event handler function that is invoked when a connection error has occurred and the websocket will attempt to reconnect.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 the websocket is opened.getScope()Returns the scope of the websocket channel.getUser()Returns the user identifier of the websocket channel.booleanReturns whether to (auto)connect the websocket or not.voidsetChannel(String channel) Sets the name of the websocket channel.voidsetConnected(boolean connected) Sets whether to (auto)connect the websocket or not.voidsetOnclose(String onclose) Sets the JavaScript event handler function that is invoked when the websocket is closed and will not anymore attempt to reconnect.voidsetOnerror(String onerror) Sets the JavaScript event handler function that is invoked when a connection error has occurred and the websocket will attempt to reconnect.voidsetOnmessage(String onmessage) Sets the JavaScript event handler function that is invoked when a push message is received from the server.voidSets the JavaScript event handler function that is invoked when the websocket is opened.voidSets the scope of the websocket channel.voidsetUser(Serializable user) Sets the user identifier of the websocket channel, so that user-targeted push messages can be sent.voidsetValueExpression(String name, jakarta.el.ValueExpression binding) Set theValueExpressionused to calculate the value for the specified attribute or property name, if any.Methods inherited from class UIComponentBase
addClientBehavior, addFacesListener, broadcast, clearInitialState, decode, encodeBegin, encodeChildren, encodeEnd, findComponent, getAttributes, getChildCount, getChildren, getClientBehaviors, getClientId, getDefaultEventName, getFacesContext, getFacesListeners, getFacet, getFacetCount, getFacets, getFacetsAndChildren, getId, getListenersForEventClass, getParent, getPassThroughAttributes, getRenderer, getRendererType, getRendersChildren, invokeOnComponent, isRendered, isTransient, markInitialState, processDecodes, processRestoreState, processSaveState, processUpdates, processValidators, queueEvent, removeFacesListener, restoreAttachedState, restoreState, saveAttachedState, saveState, setId, setParent, setRendered, setRendererType, setTransient, subscribeToEvent, unsubscribeFromEventModifier and TypeMethodDescriptionvoidaddClientBehavior(String eventName, ClientBehavior behavior) This is a default implementation ofClientBehaviorHolder.addClientBehavior(String, ClientBehavior).protected voidaddFacesListener(FacesListener listener) Add the specifiedFacesListenerto the set of listeners registered to receive event notifications from thisUIComponent.voidbroadcast(FacesEvent event) Broadcast the specifiedFacesEventto all registered event listeners who have expressed an interest in events of this type.voidFor each of the attached objects on this instance that implementPartialStateHolder, callPartialStateHolder.clearInitialState()on the attached object.voiddecode(FacesContext context) Decode any new state of thisUIComponentfrom the request contained in the specifiedFacesContext, and store this state as needed.voidencodeBegin(FacesContext context) If ourrenderedproperty istrue, render the beginning of the current state of thisUIComponentto the response contained in the specifiedFacesContext.voidencodeChildren(FacesContext context) voidencodeEnd(FacesContext context) findComponent(String expression) Search for and return theUIComponentwith anidthat matches the specified search expression (if any), according to the algorithm described below.Return a mutableMaprepresenting the attributes (and properties, see below) associated wth thisUIComponent, keyed by attribute name (which must be a String).intReturn the number of childUIComponents that are associated with thisUIComponent.This is a default implementation ofClientBehaviorHolder.getClientBehaviors().getClientId(FacesContext context) Return a client-side identifier for this component, generating one if necessary.This is a default implementation ofClientBehaviorHolder.getDefaultEventName().protected FacesContextConvenience method to return theFacesContextinstance for the current request.protected FacesListener[]getFacesListeners(Class clazz) Return an array of registeredFacesListeners that are instances of the specified class.Convenience method to return the named facet, if it exists, ornullotherwise.intReturn the number of facetUIComponents that are associated with thisUIComponent.Return a mutableMaprepresenting the facetUIComponents associated with thisUIComponent, keyed by facet name (which must be a String).getId()Return the component identifier of thisUIComponent.getListenersForEventClass(Class<? extends SystemEvent> eventClass) Return theSystemEventListenerinstances registered on thisUIComponentinstance that are interested in events of typeeventClass.Return the parentUIComponentof thisUIComponent, if any.getPassThroughAttributes(boolean create) This method has the same specification asUIComponent.getPassThroughAttributes()except that it is allowed to returnnullif and only if the argumentcreateisfalseand no pass through attribute data structure exists for this instance.protected RenderergetRenderer(FacesContext context) Convenience method to return theRendererinstance associated with this component, if any; otherwise, returnnull.Return theRenderertype for thisUIComponent(if any).booleanReturn a flag indicating whether this component is responsible for rendering its child components.booleaninvokeOnComponent(FacesContext context, String clientId, ContextCallback callback) Starting at this component in the View hierarchy, search for a component with aclientIdequal to the argumentclientIdand, if found, call theContextCallback.invokeContextCallback(FacesContext, UIComponent)method on the argumentcallback, passing the currentFacesContextand the found component as arguments.booleanReturntrueif this component (and its children) should be rendered during the Render Response phase of the request processing lifecycle.booleanIf true, the Object implementing this interface must not participate in state saving or restoring.voidFor each of the attached objects on this instance that implementPartialStateHolder, callPartialStateHolder.markInitialState()on the attached object.voidprocessDecodes(FacesContext context) Perform the component tree processing required by the Apply Request Values phase of the request processing lifecycle for all facets of this component, all children of this component, and this component itself, as follows.voidprocessRestoreState(FacesContext context, Object state) Perform the component tree processing required by the Restore View phase of the request processing lifecycle for all facets of this component, all children of this component, and this component itself, as follows.processSaveState(FacesContext context) Perform the component tree processing required by the state saving portion of the Render Response phase of the request processing lifecycle for all facets of this component, all children of this component, and this component itself, as follows.voidprocessUpdates(FacesContext context) Perform the component tree processing required by the Update Model Values phase of the request processing lifecycle for all facets of this component, all children of this component, and this component itself, as follows.voidprocessValidators(FacesContext context) Perform the component tree processing required by the Process Validations phase of the request processing lifecycle for all facets of this component, all children of this component, and this component itself, as follows.voidqueueEvent(FacesEvent event) Queue an event for broadcast at the end of the current request processing lifecycle phase.protected voidremoveFacesListener(FacesListener listener) Remove the specifiedFacesListenerfrom the set of listeners registered to receive event notifications from thisUIComponent.static ObjectrestoreAttachedState(FacesContext context, Object stateObj) This method is called byUIComponentsubclasses that need to restore the objects they saved usingUIComponentBase.saveAttachedState(FacesContext, Object).voidrestoreState(FacesContext context, Object state) Perform any processing required to restore the state from the entries in the state Object.static ObjectsaveAttachedState(FacesContext context, Object attachedObject) This method is called byUIComponentsubclasses that want to save one or more attached objects.saveState(FacesContext context) Gets the state of the instance as aSerializableObject.voidSet the component identifier of thisUIComponent(if any).voidsetParent(UIComponent parent) Set the parentUIComponentof thisUIComponent.voidsetRendered(boolean rendered) Set therenderedproperty of thisUIComponent.voidsetRendererType(String rendererType) voidsetTransient(boolean transientFlag) Denotes whether or not the Object implementing this interface must or must not participate in state saving or restoring.voidsubscribeToEvent(Class<? extends SystemEvent> eventClass, ComponentSystemEventListener componentListener) Install the listener instance referenced by argumentcomponentListeneras a listener for events of typeeventClassoriginating from this specific instance ofUIComponent.voidunsubscribeFromEvent(Class<? extends SystemEvent> eventClass, ComponentSystemEventListener componentListener) Remove the listener instance referenced by argumentcomponentListeneras a listener for events of typeeventClassoriginating from this specific instance ofUIComponent.Methods inherited from class UIComponent
encodeAll, getClientId, getCompositeComponentParent, getContainerClientId, getCurrentComponent, getCurrentCompositeComponent, getFacet, getNamingContainer, getPassThroughAttributes, getResourceBundleMap, getStateHelper, getStateHelper, getTransientStateHelper, getTransientStateHelper, getValueExpression, initialStateMarked, isCompositeComponent, isInView, isVisitable, popComponentFromEL, processEvent, pushComponentToEL, restoreTransientState, saveTransientState, setInView, visitTreeModifier and TypeMethodDescriptionvoidencodeAll(FacesContext context) If this component returnstruefromUIComponent.isRendered(), take the following action.Enable Jakarta Expression Language to access theclientIdof a component.static UIComponentgetCompositeComponentParent(UIComponent component) Finds the nearest composite component parent of the specified component.getContainerClientId(FacesContext context) Allow components that implementNamingContainerto selectively disable prepending their clientId to their descendent's clientIds by breaking the prepending logic into a separately callable method.static UIComponentgetCurrentComponent(FacesContext context) Return theUIComponentinstance that is currently processing.static UIComponentgetCurrentCompositeComponent(FacesContext context) Return the closest ancestor component, relative to the component returned fromUIComponent.getCurrentComponent(FacesContext), that is a composite component, ornullif no such component exists.Convenience method to return the named facet using an enum identifier, if it exists, ornullotherwise.Starting with "this", return the closest component in the ancestry that is aNamingContainerornullif none can be found.This is a convenience method that simply callsUIComponent.getPassThroughAttributes(boolean), passingtrueas the argument.Return aMap<String,String>of theResourceBundlefor this component.protected StateHelperReturn theStateHelperinstance used to help this component implementPartialStateHolder.protected StateHelpergetStateHelper(boolean create) LikeUIComponent.getStateHelper(), but only create a state helper instance if the argumentcreatistrue.Return theTransientStateHelperinstance for thisUIComponentinstance.getTransientStateHelper(boolean create) Return theTransientStateHelperinstance for thisUIComponentinstance.jakarta.el.ValueExpressiongetValueExpression(String name) Return theValueExpressionused to calculate the value for the specified attribute or property name, if any.booleanAn implementation ofPartialStateHolder.initialStateMarked(), this method is called by the runtime to test if thePartialStateHolder.markInitialState()method was called.static booleanisCompositeComponent(UIComponent component) Returntrueifcomponentis a composite component, otherwisefalse.booleanisInView()Returntrueif this component is within the view hierarchy otherwisefalseprotected booleanisVisitable(VisitContext context) Returntrueif this component should be visited,falseotherwise.voidpopComponentFromEL(FacesContext context) Pop the currentUIComponentfrom theFacesContextattributes map so that the previousUIComponent, if any, becomes the current component.voidprocessEvent(ComponentSystemEvent event) The default implementation performs the following action.voidpushComponentToEL(FacesContext context, UIComponent component) Push the currentUIComponentthisto theFacesContextattribute map saving the previousUIComponentfor a subsequent call toUIComponent.popComponentFromEL(FacesContext).voidrestoreTransientState(FacesContext context, Object state) For components that need to support the concept of transient state, this method will restore any state saved on a prior call toUIComponent.saveTransientState(FacesContext).saveTransientState(FacesContext context) For components that need to support the concept of transient state, this method will save any state that is known to be transient in nature.voidsetInView(boolean isInView) Updates the status as to whether or not this component is currently within the view hierarchy.booleanvisitTree(VisitContext visitContext, VisitCallback callback) Perform a tree visit starting at this node in the tree.Methods inherited from class Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, waitMethods inherited from interface ClientBehaviorHolder
addClientBehavior, getClientBehaviors, getDefaultEventNameModifier and TypeMethodDescriptionvoidaddClientBehavior(String eventName, ClientBehavior behavior) Attaches aClientBehaviorto the component implementing this interface for the specified event.Returns a non-null, unmodifiableMapthat contains the theClientBehaviors that have been attached to the component implementing this interface.Returns the default event name for thisClientBehaviorHolderimplementation.
-
Field Details
-
COMPONENT_TYPE
-
COMPONENT_FAMILY
The standard component family for this component.
- See Also:
-
-
Constructor Details
-
UIWebsocket
public UIWebsocket()Create a new
UIWebsocketinstance with default property values.- Throws:
IllegalStateException- When Websocket endpoint is not enabled.
-
-
Method Details
-
getFamily
Returns
COMPONENT_FAMILY.- Specified by:
getFamilyin classUIComponent- Returns:
- the component family (not null).
-
setValueExpression
Set the
ValueExpressionused to calculate the value for the specified attribute or property name, if any. If aValueExpressionis set for thechannelorscopeproperty, regardless of the value, throw an illegal argument exception. If aValueExpressionis set for theuserproperty, and the non-null value is not an instance ofSerializable, throw an illegal argument exception.- Overrides:
setValueExpressionin classUIComponent- Parameters:
name- Name of the attribute or property for which to set aValueExpressionbinding- TheValueExpressionto set, ornullto remove any currently setValueExpression- Throws:
IllegalArgumentException- Ifnameis one ofid,parent,channelorscope, or itnameisuserand the non-null value is not an instance ofSerializable.NullPointerException- Ifnameisnull.
-
getEventNames
Returns a non-null, empty, unmodifiable
Collectionwhich returnstrueon anyCollection#contains()invocation, indicating that all client behavior event names are acceptable.- Specified by:
getEventNamesin interfaceClientBehaviorHolder- Overrides:
getEventNamesin classUIComponentBase- Returns:
- the collection of event names.
-
getChannel
Returns the name of the websocket channel.- Returns:
- The name of the websocket channel.
-
setChannel
Sets the name of the websocket channel. It may not be an Jakarta Expression Language 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 websocket channel.- Throws:
IllegalArgumentException- When the value does not represent a valid channel name.
-
getScope
Returns the scope of the websocket channel.- Returns:
- The scope of the websocket channel.
-
setScope
Sets the scope of the websocket channel. It may not be an Jakarta Expression Language expression and allowed values areapplication,sessionandview, case insensitive. When the value isapplication, then all channels with the same name throughout the application will receive the same push message. When the value issession, then only the channels with the same name in the current user session will receive the same push message. When the value isview, then only the channel in the current view will receive the push message. The default scope isapplication. When theuserattribute is specified, then the default scope issession.- Parameters:
scope- The scope of the websocket channel.
-
getUser
Returns the user identifier of the websocket channel.- Returns:
- The user identifier of the websocket channel.
-
setUser
Sets the user identifier of the websocket 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 implementSerializableand preferably have low memory footprint. Suggestion: use#{request.remoteUser}or#{someLoggedInUser.id}.- Parameters:
user- The user identifier of the websocket channel.
-
getOnopen
Returns the JavaScript event handler function that is invoked when the websocket is opened.- Returns:
- The JavaScript event handler function that is invoked when the websocket is opened.
-
setOnopen
Sets the JavaScript event handler function that is invoked when the websocket 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 websocket is opened.
-
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
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
Returns the JavaScript event handler function that is invoked when a connection error has occurred and the websocket will attempt to reconnect.- Returns:
- The JavaScript event handler function that is invoked when a connection error has occurred and the websocket will attempt to reconnect.
- Since:
- 4.0
-
setOnerror
Sets the JavaScript event handler function that is invoked when a connection error has occurred and the websocket will attempt to reconnect. The function will be invoked with three arguments: the error reason code, the channel name and the rawCloseEventitself. Note that this will not be invoked on final close of the websocket, even when the final close is caused by an error. See also RFC 6455 section 7.4.1 andCloseReason.CloseCodesAPI 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:
- 4.0
-
getOnclose
Returns the JavaScript event handler function that is invoked when the websocket is closed and will not anymore attempt to reconnect.- Returns:
- The JavaScript event handler function that is invoked when the websocket is closed and will not anymore attempt to reconnect.
-
setOnclose
Sets the JavaScript event handler function that is invoked when the websocket 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 rawCloseEventitself. 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 andCloseReason.CloseCodesAPI for an elaborate list of all close codes.- Parameters:
onclose- The JavaScript event handler function that is invoked when the websocket is closed.
-
isConnected
public boolean isConnected()Returns whether to (auto)connect the websocket or not.- Returns:
- Whether to (auto)connect the websocket or not.
-
setConnected
public void setConnected(boolean connected) Sets whether to (auto)connect the websocket or not. Defaults totrue. It's interpreted as a JavaScript instruction whether to open or close the websocket push connection. Note that this attribute is re-evaluated on every ajax request. You can also explicitly set it tofalseand then manually control in JavaScript byfaces.push.open("channelName")andfaces.push.close("channelName").- Parameters:
connected- Whether to (auto)connect the websocket or not.
-