I've been trying to cache and handle viewExpiredexception where if a `viewExpiredexceptionviewExpiredexception is throw, i have written a custom viewExpiredexception Handler which is suppose to redirect back to the page where the Exception is thrown, i also insert a boolean into session which is used in the redicted page to show "page was refreshed" message.
Below is the relevant part of my ViewExpiredException Handler:
public void handle() throws FacesException {
for (Iterator<ExceptionQueuedEvent> i = getUnhandledExceptionQueuedEvents().iterator(); i.hasNext();) {
ExceptionQueuedEvent event = i.next();
ExceptionQueuedEventContext context = (ExceptionQueuedEventContext) event.getSource();
Throwable t = context.getException();
if (t instanceof ViewExpiredException) {
ViewExpiredException vee = (ViewExpiredException) t;
FacesContext fc = FacesContext.getCurrentInstance();
Map<String, Object> requestMap = fc.getExternalContext().getRequestMap();
NavigationHandler nav = fc.getApplication().getNavigationHandler();
try {
requestMap.put("currentViewId", vee.getViewId());
HttpServletRequest orgRequest = (HttpServletRequest) fc.getExternalContext().getRequest();
fc.getExternalContext().redirect(orgRequest.getRequestURI());
Map<String, Object> sessionMap = FacesContext.getCurrentInstance().getExternalContext().getSessionMap();
sessionMap.put("refreshedMaxSesion",true);
fc.renderResponse();
}
catch(IOException e){ }
finally { i.remove(); }
}
}
// here queue will not contain any ViewExpiredEvents, let the parent handle them.
getWrapped().handle();
}
and the Navigation case
<navigation-rule>
<navigation-case>
<from-outcome>/app/ord1</from-outcome>
<to-view-id>/jsp/orderHist.jsp</to-view-id>
<redirect />
</navigation-case>
</navigation-rule>
I had limited success with the above, it would work in some cases but in other cases the page wouldn't redirect at all. It works mostly in chrome but in IE it didn't work at all.
I tried making few changes such as using
HttpServletResponse response = (HttpServletResponse) fc.getExternalContext().getResponse();
response.sendRedirect(vee.getViewId());
but i was getting the 500 error pages with exception saying View must Exists... so i stopped experimenting to find out what i am doing wrong first. How can this goal of cahcing a ViewExpiredException, and Redirectign back to the page where the error was thrown be archived?
I'm on myFaces (2.1.7) and richFaces (3.3.3). Thanks
There is some work already done inside MyFaces Community to deal with ViewExpiredException in a graceful way. Some issues has been solved in MyFaces Core (see MYFACES-3530 and MYFACES-3531) Maybe you should try the latest snapshot HERE.
Related
I am trying to create standard error page for zuul server so that I can redirect exception to this page?
Currently, I have created a zuul filter to catch zuul exception as below:
code snippets
#Override
public Object run() {
try {
RequestContext ctx = RequestContext.getCurrentContext();
Object e = ctx.get("error.exception");
if (e != null && e instanceof ZuulException) {
ZuulException zuulException = (ZuulException)e;
LOG.error("Zuul failure detected: " + zuulException.getMessage(), zuulException);
// Remove error code to prevent further error handling in follow up filters
ctx.remove("error.status_code");
// Populate context with new response values
ctx.setResponseBody("Internal Server Error : Please contact Phoenix Admin");
ctx.getResponse().setContentType("application/json");
ctx.setResponseStatusCode(500); //Can set any error code as excepted
}
}
catch (Exception ex) {
LOG.error("Exception filtering in custom error filter", ex);
ReflectionUtils.rethrowRuntimeException(ex);
}
return null;
}
appreciate for any advice?
I will have to spend some time to see how you can read from the error page I am traveling right now. But setting the response body by reading content might not be a bad option definitely might not be perfect.
Checkout the below code if it helps.
Also add some code that you might be trying and is not working its easier that way to answer and help.
You need to make sure the filter runs after the predecoration filter.
#Override
public Object run() {
RequestContext ctx = RequestContext.getCurrentContext();
HttpServletRequest request = ctx.getRequest();
String url = UriComponentsBuilder.fromHttpUrl("http://localhost:8082").path("/outage").build()
.toUriString();
ctx.set("requestURI", url);
return null;
}
Check this out for more information:- https://github.com/spring-cloud/spring-cloud-netflix/issues/1754
Hope this helps you.
Using mojarra 2.1.27 and richfaces 4.3.6 on tomcat7, I was trying to implement my own exception handler for the ajax requests (Following all your advices) but I never get access to the render exception.
I have normal postback exceptions handled through web.xml <error-page> directives, which works fine, and ajax request should go through my custom handler. This seems to work when updating values and invoking the actions, but not with exceptions during rendering phase.
Having this simple ajax command button
<a4j:commandButton execute="#this" action="#{testController.actionButton4}"
render="#form" value="Ajax Post + Render Error"/>
which (amongst others) renders a div with a result
<div id="result">
#{testController.result}
</div>
Is backed by a simple action in my TestController
public String actionButton4() {
result = "action4";
inError = true;
return null;
}
And a simple getter which is used during the render.
public String getResult() {
if (inError) {
inError = false;
throw new RuntimeException("Render error in " + result);
}
return result;
}
My handler does more or less the default behaviour
public void handle() throws FacesException {
dohandle();
getWrapped().handle();
}
public void dohandle() throws FacesException {
FacesContext fc = FacesContext.getCurrentInstance();
PhaseId phaseId = fc.getCurrentPhaseId();
boolean partialRequest = fc.getPartialViewContext().isPartialRequest();
boolean ajaxRequest = fc.getPartialViewContext().isAjaxRequest();
Iterator<ExceptionQueuedEvent> iterator = getUnhandledExceptionQueuedEvents().iterator();
log.trace("Phase id ({})", phaseId);
while (iterator.hasNext()) {
log.trace("Request is partial ({}). Request is ajax ({})", partialRequest, ajaxRequest);
if (!ajaxRequest) {
return;
}
...
}
}
What I see during rendering is a logging exception in the ExtendedPartialViewcontextImpl of richfaces
Jun 25, 2014 10:18:44 AM org.richfaces.context.ExtendedPartialViewContextImpl$RenderVisitCallback logException
SEVERE: /test2.xhtml: Error reading 'result' on type c.n.g.w.controller.TestController
...
Then I see the phase ends and the exception handler is consulted
10:18:44.336 {http-bio-8080-exec-2} TRACE c.n.g.w.generic.LifeCycleListener - END PHASE RENDER_RESPONSE 6
10:18:44.336 {http-bio-8080-exec-2} TRACE c.n.g.w.generic.ExceptionHandler - Phase id (RENDER_RESPONSE 6)
But for some reason there is no unhandled exception in the queue.
I couldn't find anything stating that the RF rendering should react any different that others, but I suspect it could be. Does anyone know more than me here?
UPDATE:
I notice from the client side log that the rendered output is clipped right at the EL tag, so the rendering breaks and commits the partial result for some reason.
I don't redirect or forward my user to another page. So when the my SessionExpiredExceptionHandler (extends ExceptionHandlerWrapper) handles the ViewExireException. I want the user to stay on the same page and display a PrimeFaces Dialog. For notifying that the session has expired and that the user needs to login again (dialog based). I am use Servlet 3.1 functions to login/logout user and Basic/file for auth-method to map the users to different system roles.
What is happening now is that the View/page get refreshed after 2 min, but the session doesn't get invalidated. That only happens the second time when the page refreshes, after 4 min.
<session-config>
<session-timeout>2</session-timeout>
</session-config>
Edit:
Which is refreshed by the meta tag:
<meta http-equiv="refresh" content="#{session.maxInactiveInterval}" />
How can I make SessionExpiredExceptionHandlerinvalidate the session object (Servlet logout) when the Exceptions occur the first time, and how can I invoke a JavaScript (expireDlg.show()) on the client to display a PrimeFaces dialog ?
I have looked at some other threads but not found a viable solution.
Session time-out
SessionExpiredExceptionHandler
#Override
public void handle() throws FacesException {
for (Iterator<ExceptionQueuedEvent> i = getUnhandledExceptionQueuedEvents().iterator(); i.hasNext();) {
ExceptionQueuedEvent event = i.next();
ExceptionQueuedEventContext context = (ExceptionQueuedEventContext) event.getSource();
Throwable t = context.getException();
if (t instanceof ViewExpiredException) {
ViewExpiredException vee = (ViewExpiredException) t;
FacesContext fc = FacesContext.getCurrentInstance();
Map<String, Object> requestMap = fc.getExternalContext().getRequestMap();
NavigationHandler nav = fc.getApplication().getNavigationHandler();
try {
requestMap.put("currentViewId", vee.getViewId());
nav.handleNavigation(fc, null, "Home");
fc.renderResponse();
} finally {
i.remove();
}
}
}
// At this point, the queue will not contain any ViewExpiredEvents.
// Therefore, let the parent handle them.
getWrapped().handle();
}
web.xml
<exception-type>javax.faces.application.ViewExpiredException</exception-type>
<location>/home.xhtml</location>
</error-page>
How can I make SessionExpiredExceptionHandler invalidate the session object (Servlet logout) when the Exceptions occur the first time
The session is supposedly to be already invalidated/expired (otherwise a ViewExpiredException wouldn't be thrown at all), so I don't see how it's useful to manually invalidate/expire it yourself. But for the case that, you can invalidate it as follows:
externalContext.invalidateSession();
and how can I invoke a JavaScript (expireDlg.show()) on the client to display a PrimeFaces dialog ?
You can use the PrimeFaces RequestContext API to programmatically instruct PrimeFaces to execute some JS code on complete of ajax response.
RequestContext.getCurrentInstance().execute("expireDlg.show()");
Don't forget to remove the navigation handler block from the exception handler if you actually don't want to navigate.
This solution worked for my case. It seams that Primefaces (3.3) is swallowing the ExceptionQueuedEvent. There are no Exception to handle when my ViewExceptionHandler gets called. So instead I used the p:idleMonitor component with event listner. I also removed the meta refresh tag.
<p:idleMonitor timeout="#{(session.maxInactiveInterval-60)*1000}">
<p:ajax event="idle" process="#this" update="sessionMsg" listener="#{userController.userIdleSession()}" />
<p:ajax event="active" process="#this" update="sessionMsg" listener="#{userController.userActiveSession()}"/>
</p:idleMonitor>
One weird thing is if the timeoutis excatly the same as the web.xmlsession time-out parameter, the listener won't be invoked.
Bean functions
public void userIdleSession() {
if (!userIdleMsgVisable) {
userIdleMsgVisable = true;
JsfUtil.addWarningMessage(JsfUtil.getResourceMessage("session_expire_title"), JsfUtil.getResourceMessage("session_expire_content"));
}
}
public void userActiveSession() {
if (!userSessionDlgVisable) {
userSessionDlgVisable = true;
RequestContext.getCurrentInstance().execute("sessionExipreDlg.show()");
}
}
The dialog (sessionExipreDlg) called the redirect instead of using navigation handler to get new scope and refresh the page.
public void userInactiveRedirect() {
FacesContext fc = FacesContext.getCurrentInstance();
userIdleMsgVisable = false;
userSessionDlgVisable = false;
sessionUser = null;
HttpServletRequest request = (HttpServletRequest) fc.getExternalContext().getRequest();
JsfUtil.findBean("homeController", HomeController.class).clearCurrentValues();
try {
fc.getExternalContext().redirect(JsfUtil.getApplicationPath(request, false, null));
} catch (IOException ex) {
BeanUtil.severe(ex.getLocalizedMessage());
}
}
I'm trying to use the authenticate() in a preRenderView listener method, in order to trigger authentication conditionally, depending on view parameters in the page. I tried adding a simple method:
#Named
#RequestScoped
public class PermissionBean implements java.io.Serializable {
public void preRender() {
System.out.println("IN PRERENDER");
HttpServletRequest request = (HttpServletRequest)FacesContext.getCurrentInstance().getExternalContext().getRequest();
HttpServletResponse response = (HttpServletResponse)FacesContext.getCurrentInstance().getExternalContext().getResponse();
try {
request.authenticate(response);
} catch (Exception e) { // may throw ServletException or IOException
e.printStackTrace();
}
}
The authenticate method itself doesn't throw an exception, it triggers the redirect to Login.xhtml as expected. However, I'm getting in my server log, I get this exception:
enter code here
INFO: IN PRERENDER
FINEST: GET /Login.xhtml previous[3]
INFO: Exception when handling error trying to reset the response.
java.lang.NullPointerException
at com.sun.faces.facelets.tag.jsf.core.DeclarativeSystemEventListener.processEvent(EventHandler.java:126)
at javax.faces.component.UIComponent$ComponentSystemEventListenerAdapter.processEvent(UIComponent.java:2508)
at javax.faces.event.SystemEvent.processListener(SystemEvent.java:106)
at com.sun.faces.application.ApplicationImpl.processListeners(ApplicationImpl.java:2129)
at com.sun.faces.application.ApplicationImpl.invokeComponentListenersFor(ApplicationImpl.java:2077)
at com.sun.faces.application.ApplicationImpl.publishEvent(ApplicationImpl.java:286)
at com.sun.faces.application.ApplicationImpl.publishEvent(ApplicationImpl.java:244)
at javax.faces.application.ApplicationWrapper.publishEvent(ApplicationWrapper.java:670)
at com.sun.faces.lifecycle.RenderResponsePhase.execute(RenderResponsePhase.java:108)
at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101)
at com.sun.faces.lifecycle.LifecycleImpl.render(LifecycleImpl.java:139)
at javax.faces.webapp.FacesServlet.service(FacesServlet.java:594)
So my request is not redirected to Login.xhtml.
My question is - is this something that should work within a JSF managed bean, or is it only legal outside of JSF request lifecycle? I tried calling authenticate() from a WebFilter, and it works as exptected.
Thanks,
Ellen
You need to tell JSF to not render the response which it was initially asked to do, whenever the request has been redirected. You can do that by checking if HttpServletRequest#authenticate() returns false and then invoke FacesContext#responseComplete() accordingly.
if (!request.authenticate(response)) {
FacesContext.getCurrentInstance().responseComplete();
}
I have following two methods in my backing bean -
public String validateUser() {
FacesContext facesCtx = FacesContext.getCurrentInstance();
if(userName.equals("user1") && password.equals("pass1")) {
User user = new User();
user.setUserName(userName);
HttpSession session = (HttpSession) facesCtx.getExternalContext().getSession(false);
session.setAttribute(User.SESSION_ATTRIBUTE, user);
return "secured/home.jsf?faces-redirect=true";
}
if(!userName.equals(LoginBean.USERNAME)) {
FacesMessage msgForUserName = new FacesMessage(FacesMessage.SEVERITY_ERROR, "Username did not match.", null);
facesCtx.addMessage("loginForm:userName", msgForUserName);
}
if(!password.equals(LoginBean.PASSWORD)) {
FacesMessage msgForPassword = new FacesMessage(FacesMessage.SEVERITY_ERROR, "Password did not match.", null);
facesCtx.addMessage("loginForm:password", msgForPassword);
}
return null;
}
public String logout() {
logger.info("Logging out .........................................");
FacesContext facesCtx = FacesContext.getCurrentInstance();
HttpSession session = (HttpSession) facesCtx.getExternalContext().getSession(false);
session.invalidate();
return "login.jsf?faces-redirect=true";
}
I don't know why the redirection is working in the first method (i.e. validateUser()), but it's not working in the second method (i.e. logout()).
The code inside the logout method is actually executed, the session also gets invalidated,but somehow the browser stays on the same page.
And, I am using PrimeFaces p:commandButton and the ajax is enabled on both of them.
Any one, any idea?
Thank you.
but somehow the browser stays on the same page. And, I am using PrimeFaces p:commandButton and the ajax is enabled on both of them
I wouldn't expect it to fail. I suspect that this has something to do with the invalidated session. Try it with ajax="false" on the <p:commandButton>.
Unrelated to the problem, you should try to minimize the javax.servlet imports in your JSF managed beans. They often indicate that you're doing things in the wrong place or the clumsy way. In pure JSF2, you can invalidate the session as follows:
FacesContext.getCurrentInstance().getExternalContext().invalidateSession();
You can get/set objects in the session by the session Map.
Map<String, Object> sessionMap = FacesContext.getCurrentInstance().getExternalContext().getSessionMap();
// ...
Or just make it a managed bean (property).
See also:
How can I create a new session with a new User login on the application?