Since PrimeFaces push is going to be discontinued, I started to migrate to OmniFaces push. For notification purposes it's all working as expected, but I have a chat on my application where I'm missing two things in OmniFaces:
1) Change the user of the socket on demand. I require this for private conversations. On PrimeFaces I create a channel for each conversation based on the logged users id, and I pass it to the connect method of their socket component. With OmniFaces I tried to place the socket component inside a PrimeFaces output panel, bind the user property to a view scoped bean, update the panel on a ajax request and on the oncomplete event call OmniFaces.Push.open('channelName'), but I can see on the SocketObserver class(from the showcase) that the user has not been updated. As a workaround I created the channel using the logged user id as user, and if someone different from the person that he is talking at the moment sends a message, I ignore it at the JavaScript callback instead of appending it.
2) When I don't specify the user on PushContext.send, I'd like that the message was sent to everyone connected on the channel, similar to "/channel/*" on PrimeFaces. My requirement with this is to update the list off online/offline users off this chat application. A a workaround I could create a separate channel for these notifications, but as the application don't require this to work, I preferred to check here first.
I'll add code if necessary, but first I'd like to check if these concepts are present in OmniFaces push.
Thanks
It was indeed not possible to change the <o:socket user="#{...}"> value while staying in the same JSF view (ajax updates, etc). As per issue 472, it has been improved in OmniFaces 3.2-SNAPSHOT.
Any dynamic change in value of <o:socket user="#{...}"> during any ajax request in the same JSF view will now be reflected in push behavior.
In other words, below construct will now be possible:
<h:form>
<h:selectOneMenu value="#{bean.chat}">
<f:selectItems value="#{bean.chats}" />
<f:ajax render="#form" />
<h:selectOneMenu>
...
<o:socket channel="chat" user="#{bean.chat.id}" />
</h:form>
If you start by using the user attribute on the o:socket like in the example
<o:socket channel="sess" scope="session" user="#{pushTestUser}" />
1) seems possible by using the 'user id' as can be seen in the showcase push test page
From http://showcase.omnifaces.org/push/socket:
#Inject #Push
private PushContext someChannel;
public void sendMessage(Object message, User recipientUser) {
Long recipientUserId = recipientUser.getId();
someChannel.send(message, recipientUserId);
}
In this example the pass the User which is an 'example' object that could be your own or whatever. In the showcase the user is passed on by binding the id to an input field, but that could be done server-side as well. Up to you
2) seems possible with sending messages to the generic channel or even groups as can be seen in http://showcase.omnifaces.org/push/socket.
#Inject #Push
private PushContext someChannel;
public void sendMessage(Object message, Group recipientGroup) {
Collection<Long> recipientUserIds = recipientGroup.getUserIds();
someChannel.send(message, recipientUserIds);
}
The group here is an example Object that could be your own, it could be passed from the 'frontend' or just read in the backend somewhere. It just needs to contain id's of users (can be mapped guids, does not need to be internal user id's) that are subscribed to the channel. All are just example methods.
So both seem possible in my opinion.
Related
I am trying to invoke a method annotated with #PreDestroy in a #ViewScoped bean when the user leaves the page associated with that bean in a rather large JSF powered web application.
After reading https://stackoverflow.com/a/15391453/5467214 and several other questions and answers on SO as well as https://showcase.omnifaces.org/cdi/ViewScoped, I came to the understanding that the OmniFaces ViewScoped annotation provides exactly that behavior by utilizing the unload page event as well as sendBeacon on modern browsers.
So I used the #ViewScoped annotation from OmniFaces in my bean:
import javax.annotation.PreDestroy;
import org.omnifaces.cdi.ViewScoped;
#Named("DesktopForm")
#ViewScoped
public class DesktopForm implements Serializable {
...
}
and annotated the method I want to invoke with the PreDestroy annotation:
#PreDestroy
public void close() {
System.out.println("Destroying view scoped desktop bean");
...
}
Unfortunately, this "close" method is not called when I click some link or leave the page
by entering an entirely new URL. Instead, the network analysis of my browser (a current Firefox) shows me that a POST request is send when leaving the page that returns with an 403 http error code:
As you can see in the screenshot, the "Initiator" of the POST request seems to be an unload.js.jsf script with a beacon mentioned in parentheses, which I assume is part of the OmniFaces library. So presumably the functionality described in the OmniFaces ViewScoped documentation is somehow triggered, but does not result in the expected behavior for me.
The browser still navigates to the new page, but the PreDestroy annotated method was not triggered. When I switch to the standard version of ViewScoped (javax.faces.view.ViewScoped instead of org.omnifaces.cdi.ViewScoped), naturally the method still does not get invoked, but there is also no POST method resulting in a 403 error status when leaving the page in the network analysis of my browser (because the standard ViewScoped annotation of Java does not try to invoke any bean side action on unload events, I guess)
I am using MyFaces 2.3.10 in combination with OmniFaces 2.7.18 (and PrimeFaces 8.0.5, I don't know if that is relevant), Spring Security 5.7.3 and Java 11.
Since "403" is the http status for "forbidden", could this have something to do with using "http" instead of "https" in my local development environment? Does this "send beacon" only work with secure connections?
Any help appreciated!
Edit: I also consulted the official documentation of the OmniFaces ViewScoped annotation under https://omnifaces.org/docs/javadoc/2.7/index.html?org/omnifaces/cdi/ViewScoped.html but could not find a reason for the problem I encounter.
With the help of BalusC's comment to my question above, I was able to solve my problem.
What it came down to was that unload events were not processed correctly by our filter chain. Specifically, they were denied access in the doFilter method of our class extending org.springframework.web.filter.GenericFilterBean.
Therefore I added
if (ViewScopeManager.isUnloadRequest(httpServletRequest)) {
chain.doFilter(request, response);
}
to the doFilter method of the mentioned class and then it worked.
On a side note, I had to update my OmniFaces library from 2.7.18 to 3.13.3, because the ViewScopeManager class of OmniFaces 2 only has one isUnloadRequest method that accepts an FacesContext as parameter, which I did not have available in the our GenericFilterBean extension. OmniFaces 3.1 on the other hand provides another method with the same name that works with an HttpServletRequest instance instead, which I had access to and therefore resolved the issue
In normal way to enter to flow or go from some page to next page in flow we use
<h:commandButton> or <h:commandLink>
But how is it possible to enter to flow or go to the next page in flow (if we currently are in flow) from backing bean?
I try to dispatch from faces context but it doesn't work. Do you know how to do it?
I use only viewnode pages. I configure a flow using a
#FlowDefinition
#Producent
#Flowdefinition
public Flow defineFlow(#FlowbuilderParameter FlowBuilder FlowBuilder){
flowBuilder.id("","registerFlow");
flowBuilder.viewNode("registerStart","/faces/start.xhtm").Markasstartnode();
flowBuilder.viewNode("step2","/faces/step2.xhtm");
…
}
And now i would enter to flow from backing bean. Something like
FacesContext.getCurrenInstance().getExternalContext().dispatch("registerFlow");
I think possible i have to use FlowHandler from context
FlowHandler handler = FacesContext.getApplication().getFlowHandler();
handler.transition(); // and what next?
how here i can redirect user to some viewnode of flow?
I´m new at JSF programming and got a problem with my login/session which gets lost after the login.
I want to implement an easy login where a user can type in username and password. So I wrote a LoginController:
#ManagedBean
#SessionScoped
public class LoginController extends AbstractController{
#PostConstruct
public void initialiseSession() {
FacesContext.getCurrentInstance().getExternalContext().getSession(true);
}
private String username = "null";
private String password;
private boolean loggedIn = false;
#Inject
private EmployeeService employeeService;
public static final String employeeSessionKey = "user";
public LoginController() {
}
public String login() {
//check username and password and if true redirect to "/"
}
My login.xhtml looks like:
<h:form id="loginForm">
<h:outputLabel style="font-size:24px" value="Bitte melden Sie sich an!"/>
<p:panelGrid columns="2">
<p:outputLabel id="userOutput" for="userInput" value="Benutzername"/>
<p:inputText id="userInput" value="#{loginController.username}"></p:inputText>
<p:outputLabel id="passwordOutput" for="passwordInput" value="Passwort"/>
<p:inputText id="passwordInput" type="password" value="#{loginController.password}"></p:inputText>
<h:outputText value="Logindaten merken?" id="outputRememberLogin">
<p:selectBooleanCheckbox id="loginCheckbox">
</p:selectBooleanCheckbox>
<p:spacer width="10" id="loginFormLittleSpacer"></p:spacer>
</h:outputText>
<p:commandButton id="loginButton" value="Anmelden" action="#{loginController.login()}" ajax="false" >
</p:commandButton>
</p:panelGrid>
</h:form>
So when I login the redirect works. But when I go to another .xhtml page the session gets lost.
To test this, I put
<p:outputLabel value="#{loginController.username}"/>
on my pages. After the login, the username becomes "null".
I´m going crazy on this problem.
Any ideas?
thanks before.
Your LoginController bean looks like its annotations are okay and the code looks like it should work. However, there's a couple other things that you may want to check. Some of this may be obvious but your question is missing a few details so I’m not sure what level of experience you may have and where to start in this answer. Therefore, I’m starting from the beginning (almost)…
1. Domain Name Configuration
To use sessions, you must use a qualified domain name. Sending a request to an IP address will not allow sessions to work since client browsers only send session information to a fully qualified domain name (http://example.com/). If you’re calling your web app with an IP (such as ‘http://127.0.0.1:8080/MyApp’), the session data will never be sent to your web app and you will have a new session created with each request. Make sure you’re using a fully qualified domain name and path with each request to your application, for example ‘http://localhost:8080/MyApp’.
2. Application Configuration
Check that your web application’s <session-config> configuration is setup correctly. The default config should allow your code to work without having to add anything specific, so if you didn’t add anything, don’t worry about this. However, you may want to make sure there’s nothing that may be preventing the sessions from being reused.
Session cookies should be enabled (<tracking-mode>COOKIE</tracking-mode>)
Timeout should be long enough to not expire before the second request (<session-timeout>60</session-timeout>)
The cookie path should be correctly set for your use (<path>/</path>)
The following is a common session config that I use…
<session-config>
<session-timeout>60</session-timeout>
<tracking-mode>COOKIE</tracking-mode>
<cookie-config>
<path>/</path>
<http-only>true</http-only>
<secure>false</secure>
</cookie-config>
</session-config>
3. Session Cookie Tracking on the Client
If the above points don’t resolve the issue, you can really start diving into the session tracking by monitoring the request and response traffic between your app and the client browser. The session info is passed back and forth by a cookie (or query string parameter if cookies are disabled) named ‘JSESSIONID’. Its value will be the ID of the unique session and must be the same for each request to ensure that your web application tracks the same session. The below highlights some of the things to look for…
Make sure the ‘JSESSIONID’ session cookie is sent to the client browser correctly and is being sent back with each subsequent request. You can do this with Chrome or Safari's web developer tools (under the 'Network' tab) or with a separate utility, such as Wireshark.
Make sure the 'JSESSIONID' cookie exists in the response from the first request… this will let you know that your web app is at least creating the session and response cookie.
Make sure the second request from the client browser is passing the 'JSESSIONID' cookie back... this is the only way your web app knows which existing session to use.
Make sure the 'JESSIONID' cookie has a path of '/' (which may display as 'N/A' in the browser) or the path of your web app ('/MyApp', for example)… the client browser will only send cookies to the domain(s) and path associated with each. For example, if your login page is 'http://example.com/MyApp/login', the 'JSESSIONID' cookie may have a path of '/MyApp' (by default), which will not be returned if the following request is made to 'http://example.com/' (without the '/MyApp' path). The default path is the name of your web app (‘/MyApp’) and can be changed using the <path> config item indicated above.
4. Session Management within the Bean (Additional Information)
In your initialiseSession() method, the session object returned by FacesContext.getCurrentInstance().getExternalContext().getSession(true); isn't being saved and this line is essentially doing nothing. The #SessionScoped annotation will have already created a session and added the ‘JSESSIONID’ cookie to the response before initialiseSession() is called. Therefore, the only reason to call getSession(true) is if you want to save the session to a private object within the bean, which would be like this...
#ManagedBean
#SessionScoped
public class LoginController extends AbstractController{
// Create a global, private member for storing the session data...
private HttpSession session;
#PostConstruct
public void initialiseSession() {
// Assign the session to the global member…
session = FacesContext.getCurrentInstance().getExternalContext().getSession(true);
}
…
Again, the call to the getSession(true) isn’t necessary in your example since the SessionScoped bean will have already created the session. The above code is only necessary if you intended to update or use the session object, for example add an attribute or modify a setting.
In summary
Double-check the above points 1 – 3. My assumption would be that the ‘JSESSIONID’ cookie isn’t being sent back in subsequent requests. If you can confirm that the ‘JSESSIONID’ cookie (with the same value) is being included in each request then the problem isn't related to the session and may be related to the code in your login() method.
i used cookies for repair this kind of problems, in my application. inside Faceutils doesn't work before servlet.
I'm developing a JSF 2.0 app that consumes a SOAP-based web service.
I want to use in the JSFs pages most of the generated client classes for the Web Service - but the client classes are not managed beans (nor CDI beans)... and as there are a lot of client classes I don't think is feasible to add #ManagedBean or #Named annotations to all classes...
Let me give you an example so things might get a bit clearer:
The User class is a generated client class - this class has only two attributes (login and password).
I want to be able to assign values to the attributes of a given user in the JSF page:
<h:inputText value="#{user.name}"/>
<h:inputText value="#{user.password}"/>
And then I want to call my UserService to authenticate the user:
<h:commandButton value="Login" action="#{userService.authenticate}"/>
The only way (AFAIK) to assign a value to the User object from the JSF page is by making the User object a managed bean (or a CDI bean).
As there are more than 100 client classes, I definitely don't want to add #ManagedBean or #Named annotations on all classes (I equally don't want to add message-bean element for each class in the faces-config.xml).
And even if annotating all classes were a feasible option, the solution would have a drawback: the service contract (WSDL) might change at any minute and I would be obligated to regenerate the client classes... I'd loose the annotated classes.
What is the best way to handle this (kind of) issue?
I've looked for a way to declare all classes of a package in the faces-config.xml (example below), but I could find neither a way to do that nor a feasible alternative.
<managed-beans>
<managed-beans-package>x.y.z.ws.client</managed-beans-package>
<managed-beans-scope>none</managed-beans-scope>
</managed-beans>
Just make the User a property of UserService. That's also more conform JSF's MVC ideology. The UserService is the controller and the User is the model.
Thus so,
#ManagedBean
#ViewScoped
public class UserService {
private User user;
// ... (don't forget to prepare user in (post)constructor if "new" user)
}
with
<h:inputText value="#{userService.user.name}" />
<h:inputText value="#{userService.user.password}" />
I'm new at Spring Security. I'm using jsf2 with spring security 3. Three questions:
How can I access, from a session managed bean, the user info (name,password,roles) of the user currently logged in?
In order to use it in a view, for example for rendering elements depending on the roles of the user.
How can I know if a user is logged in? In order to show in a view a "login link" if the user is not logged in, or a "logout link" if the user is logged in. Which property of Spring Security do I have to use in my managed bean to store this info and use it in the view?
The "login link" is just a GET request to the URL of the login page. But how can I show "logout link"? Do it have to be a POST request and use "h:commandLink" like this?:
<h:commandLink value="Logout" action="#{request.contextPath}/j_spring_security_logout" />
Or can it be a GET request?:
<h:link value="Logout" outcome="#{request.contextPath}/j_spring_security_logout" />
Thank you very much in advanced.
The object authentication is who save this properties, you can obtain with next line in your managedBean:
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
A user is logged if his Authentication is not a instace of AnonymousAuthenticationToken, in your spring-security-context.xml you must define the urls intercepted by Spring.
The first interceptor is not analyzed by Spring. In this case the Authentication object is an instance of AnonymousAuthenticationToken.
The second interceptor is analyzed by Spring and the user is redirected to login page declared in spring-security-context.xml
/* This is a example for to obtain the rol name for example for generate automatic menu */
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
String namePrincipalRol = null;
if (auth instanceof AnonymousAuthenticationToken) {
namePrincipalRol = "ROLE_ANONYMOUS";
} else {
namePrincipalRol = auth.getAuthorities().iterator().next().getAuthority();
}
Good question, I am not sure but I think I remember having read that it must be POST, would be interesting to try. I use h:outputLink
Kind regards.