Redirect a page from a button - jsf

Hi i'm trying to develop a login page using oracle jdeveloper 12c and. I'm working with JEE technology and JSF pages.
I want to redirect to the main page after pressing authentification button but it doesn't work and I get this excpetion:
javax.servlet.ServletException: ADF_FACES-60101:Code de statut d''erreur HTTP : 404."
This is my authentification function in the ejb part
public String authentification(String login, String pwd) {
try{
Query query;
query = em.createQuery("select o from UserEntity o where "
+ " o.login = :LOGIN AND o.pwd = :PWD");
query.setParameter("LOGIN",login);
query.setParameter("PWD",pwd);
query.getSingleResult();
return ("success") ;
}
catch(Exception e){
e.printStackTrace();
return null;
}
}
this is my loginaction in the managed bean
public String loginaction() {
FacesContext ctx = FacesContext.getCurrentInstance();
HttpServletRequest request =
(HttpServletRequest)ctx.getExternalContext().getRequest();
String Url =
"/adfAuthentication?success_url=/faces/Main.jsf";
HttpServletResponse response;
response = (HttpServletResponse) ctx.getExternalContext().getResponse();
RequestDispatcher dispatcher =
request.getRequestDispatcher(Url);
try {
dispatcher.forward(request, response);
} catch (IOException e) {
FacesMessage msg = new FacesMessage(FacesMessage.SEVERITY_ERROR, "Invalid Username or Password", "Invalid Username or Password");
ctx.addMessage(null, msg);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
ad this is my jsf
<af:panelFormLayout id="pfl1">
<af:inputText value="#{bindings.login.inputValue}" label="#{bindings.login.hints.label}"
required="#{bindings.login.hints.mandatory}"
columns="#{bindings.login.hints.displayWidth}"
maximumLength="#{bindings.login.hints.precision}"
shortDesc="#{bindings.login.hints.tooltip}" id="it1">
<f:validator binding="#{bindings.login.validator}"/>
</af:inputText>
<af:inputText value="#{bindings.pwd.inputValue}" label="#{bindings.pwd.hints.label}"
required="#{bindings.pwd.hints.mandatory}"
columns="#{bindings.pwd.hints.displayWidth}"
maximumLength="#{bindings.pwd.hints.precision}"
shortDesc="#{bindings.pwd.hints.tooltip}" id="it2">
<f:validator binding="#{bindings.pwd.validator}"/>
</af:inputText>
<af:button actionListener="#{bindings.authentification.execute}" text="authentification"
disabled="#{!bindings.authentification.enabled}" id="b1"
action="#{Login2.loginaction}"/>
</af:panelFormLayout>
this is what i get in the server dashboard
javax.servlet.ServletException: ADF_FACES-60101:Code de statut d''erreur HTTP : 404."
at oracle.adfinternal.view.faces.config.rich.XmlHttpServletResponse._logException(XmlHttpServletResponse.java:141)
at oracle.adfinternal.view.faces.config.rich.XmlHttpServletResponse.sendError(XmlHttpServletResponse.java:107)
at oracle.adfinternal.view.faces.config.rich.XmlHttpServletResponse.sendError(XmlHttpServletResponse.java:101)
at weblogic.servlet.FileServlet.findSource(FileServlet.java:267)
at weblogic.servlet.FileServlet.doGetHeadPost(FileServlet.java:178)
at weblogic.servlet.FileServlet.service(FileServlet.java:160)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:844)
at weblogic.servlet.internal.StubSecurityHelper$ServletServiceAction.run(StubSecurityHelper.java:280)
at weblogic.servlet.internal.StubSecurityHelper$ServletServiceAction.run(StubSecurityHelper.java:254)
at weblogic.servlet.internal.StubSecurityHelper.invokeServlet(StubSecurityHelper.java:136)
at weblogic.servlet.internal.ServletStubImpl.execute(ServletStubImpl.java:341)
at weblogic.servlet.internal.ServletStubImpl.execute(ServletStubImpl.java:238)
at weblogic.servlet.internal.RequestDispatcherImpl.invokeServlet(RequestDispatcherImpl.java:573)
at weblogic.servlet.internal.RequestDispatcherImpl.forward(RequestDispatcherImpl.java:272)
at view.Login2.loginaction(Login2.java:54)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:601)
at com.sun.el.parser.AstValue.invoke(AstValue.java:254)
at com.sun.el.MethodExpressionImpl.invoke(MethodExpressionImpl.java:302)
at com.sun.faces.facelets.el.TagMethodExpression.invoke(TagMethodExpression.java:105)
at org.apache.myfaces.trinidad.component.MethodExpressionMethodBinding.invoke(MethodExpressionMethodBinding.java:46)
at com.sun.faces.application.ActionListenerImpl.processAction(ActionListenerImpl.java:102)
at org.apache.myfaces.trinidad.component.UIXCommand.broadcast(UIXCommand.java:190)
at javax.faces.component.UIViewRoot.broadcastEvents(UIViewRoot.java:794)
at javax.faces.component.UIViewRoot.processApplication(UIViewRoot.java:1259)
at oracle.adfinternal.view.faces.lifecycle.LifecycleImpl._invokeApplication(LifecycleImpl.java:1083)
at oracle.adfinternal.view.faces.lifecycle.LifecycleImpl._executePhase(LifecycleImpl.java:402)
at oracle.adfinternal.view.faces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:225)
at javax.faces.webapp.FacesServlet.service(FacesServlet.java:593)
at weblogic.servlet.internal.StubSecurityHelper$ServletServiceAction.run(StubSecurityHelper.java:280)
at weblogic.servlet.internal.StubSecurityHelper$ServletServiceAction.run(StubSecurityHelper.java:254)
at weblogic.servlet.internal.StubSecurityHelper.invokeServlet(StubSecurityHelper.java:136)
at weblogic.servlet.internal.ServletStubImpl.execute(ServletStubImpl.java:341)
at weblogic.servlet.internal.TailFilter.doFilter(TailFilter.java:25)
at weblogic.servlet.internal.FilterChainImpl.doFilter(FilterChainImpl.java:79)
at oracle.adf.model.servlet.ADFBindingFilter.doFilter(ADFBindingFilter.java:192)
at weblogic.servlet.internal.FilterChainImpl.doFilter(FilterChainImpl.java:79)
at oracle.adfinternal.view.faces.webapp.rich.RegistrationFilter.doFilter(RegistrationFilter.java:106)
at org.apache.myfaces.trinidadinternal.webapp.TrinidadFilterImpl$FilterListChain.doFilter(TrinidadFilterImpl.java:478)
at oracle.adfinternal.view.faces.activedata.AdsFilter.doFilter(AdsFilter.java:60)
at org.apache.myfaces.trinidadinternal.webapp.TrinidadFilterImpl$FilterListChain.doFilter(TrinidadFilterImpl.java:478)
at org.apache.myfaces.trinidadinternal.webapp.TrinidadFilterImpl._doFilterImpl(TrinidadFilterImpl.java:303)
at org.apache.myfaces.trinidadinternal.webapp.TrinidadFilterImpl.doFilter(TrinidadFilterImpl.java:208)
at org.apache.myfaces.trinidad.webapp.TrinidadFilter.doFilter(TrinidadFilter.java:92)
at weblogic.servlet.internal.FilterChainImpl.doFilter(FilterChainImpl.java:79)
at oracle.security.jps.ee.http.JpsAbsFilter$1.run(JpsAbsFilter.java:137)
at java.security.AccessController.doPrivileged(Native Method)
at oracle.security.jps.util.JpsSubject.doAsPrivileged(JpsSubject.java:315)
at oracle.security.jps.ee.util.JpsPlatformUtil.runJaasMode(JpsPlatformUtil.java:460)
at oracle.security.jps.ee.http.JpsAbsFilter.runJaasMode(JpsAbsFilter.java:120)
at oracle.security.jps.ee.http.JpsAbsFilter.doFilter(JpsAbsFilter.java:217)
at oracle.security.jps.ee.http.JpsFilter.doFilter(JpsFilter.java:81)
at weblogic.servlet.internal.FilterChainImpl.doFilter(FilterChainImpl.java:79)
at oracle.dms.servlet.DMSServletFilter.doFilter(DMSServletFilter.java:225)
at weblogic.servlet.internal.FilterChainImpl.doFilter(FilterChainImpl.java:79)
at weblogic.servlet.internal.RequestEventsFilter.doFilter(RequestEventsFilter.java:27)
at weblogic.servlet.internal.FilterChainImpl.doFilter(FilterChainImpl.java:79)
at weblogic.servlet.internal.WebAppServletContext$ServletInvocationAction.wrapRun(WebAppServletContext.java:3367)
at weblogic.servlet.internal.WebAppServletContext$ServletInvocationAction.run(WebAppServletContext.java:3333)
at weblogic.security.acl.internal.AuthenticatedSubject.doAs(AuthenticatedSubject.java:321)
at weblogic.security.service.SecurityManager.runAs(SecurityManager.java:120)
at weblogic.servlet.provider.WlsSubjectHandle.run(WlsSubjectHandle.java:57)
at weblogic.servlet.internal.WebAppServletContext.doSecuredExecute(WebAppServletContext.java:2220)
at weblogic.servlet.internal.WebAppServletContext.securedExecute(WebAppServletContext.java:2146)
at weblogic.servlet.internal.WebAppServletContext.execute(WebAppServletContext.java:2124)
at weblogic.servlet.internal.ServletRequestImpl.run(ServletRequestImpl.java:1564)
at weblogic.servlet.provider.ContainerSupportProviderImpl$WlsRequestExecutor.run(ContainerSupportProviderImpl.java:254)
at weblogic.work.ExecuteThread.execute(ExecuteThread.java:295)
at weblogic.work.ExecuteThread.run(ExecuteThread.java:254)

From the log i see that it's not just a simple JSF , but an ADF based application. I can think of two ways to achieve the redirection to a page:
1. You could define a navigation rule in the adfc-config.xml (or even faces-config.xml) file and then, simply put the name of this defined rule as the button's action property value.
2. If you wish a programmatically approach, then you could call a code returning this kind of string, "mainPage.jsf?faces-redirect=true" , since adf adds its own context. For example:
public String loginaction() {
........
return "mainPage.jsf" + "?faces-redirect=true";
}
NOTE: You might need to add "/faces/mainPage.jsf" or "/faces/.../mainPage.jsf" instead. It really depends on the location of the two pages participating in the navigation.
As per the dispatcher part, that was used with JSP. It is not needed nor advisable to use it anymore.

Related

Primefaces Push causes IllegalStateException

Currently im working on primefaces push function. actually, the push function is working properly.
This is my push flow:
I have two application with share same database, admin dashboard(primefaces + spring) and webapi (spring mvc). when there are data inserted to database via webapi, then web api will call the admin url that will trigger to push notification for all logged in user. and its working fine, as expected.
my problems is, when there are push notification, and then user do logout at the same time (at least notification growl not gone) it will throw java.lang.IllegalStateException: Cannot call sendRedirect() after the response has been committed and sometime Cannot create a session after the response has been committed.
i have try to change Login Controller to ViewScope, and put this context-param to web xml, but still not working.
<context-param>
<param-name>javax.faces.STATE_SAVING_METHOD</param-name>
<param-value>client</param-value>
</context-param>
Please Help,
this is the full stack trace:
SEVERE: Servlet.service() for servlet [facesServlet] in context with path [/WebAdmin] threw exception [java.lang.IllegalStateException: Cannot call sendRedirect() after the response has been committed] with root cause
java.lang.IllegalStateException: Cannot call sendRedirect() after the response has been committed
at org.apache.catalina.connector.ResponseFacade.sendRedirect(ResponseFacade.java:482)
at com.sun.faces.context.ExternalContextImpl.redirect(ExternalContextImpl.java:678)
at org.omnifaces.util.FacesLocal.redirect(FacesLocal.java:882)
at org.omnifaces.util.Faces.redirect(Faces.java:1170)
at com.sepakbole.web.controller.LoginController.doLogout(LoginController.java:84)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at org.apache.el.parser.AstValue.invoke(AstValue.java:279)
at org.apache.el.MethodExpressionImpl.invoke(MethodExpressionImpl.java:273)
at com.sun.faces.facelets.el.TagMethodExpression.invoke(TagMethodExpression.java:105)
at javax.faces.component.MethodBindingMethodExpressionAdapter.invoke(MethodBindingMethodExpressionAdapter.java:87)
at com.sun.faces.application.ActionListenerImpl.processAction(ActionListenerImpl.java:102)
at javax.faces.component.UICommand.broadcast(UICommand.java:315)
at javax.faces.component.UIViewRoot.broadcastEvents(UIViewRoot.java:790)
at javax.faces.component.UIViewRoot.processApplication(UIViewRoot.java:1282)
at com.sun.faces.lifecycle.InvokeApplicationPhase.execute(InvokeApplicationPhase.java:81)
at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101)
at com.sun.faces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:198)
at javax.faces.webapp.FacesServlet.service(FacesServlet.java:658)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at com.sepakbole.web.filter.AuthorizationFilter.doFilter(AuthorizationFilter.java:51)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.apache.logging.log4j.web.Log4jServletFilter.doFilter(Log4jServletFilter.java:71)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:218)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:122)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:505)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:169)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:956)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:442)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1082)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:623)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:316)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Thread.java:745)
Update:
This is my Controller:
import java.io.Serializable;
import javax.faces.bean.ApplicationScoped;
import javax.faces.bean.ManagedBean;
import org.primefaces.push.EventBus;
import org.primefaces.push.EventBusFactory;
#ManagedBean
#ApplicationScoped
public class PushMessageController implements Serializable {
private static final long serialVersionUID = 1L;
private String data;
public String getData() {
return data;
}
public void setData(String data) {
this.data = data;
}
public void execute(){
EventBus eventBus = EventBusFactory.getDefault().eventBus();
eventBus.publish("/receive-message", data);
}
}
And Below is the PushEndPoint:
import org.primefaces.push.annotation.OnMessage;
import org.primefaces.push.annotation.PushEndpoint;
import org.primefaces.push.annotation.Singleton;
import org.primefaces.push.impl.JSONEncoder;
#PushEndpoint("/receive-message")
#Singleton
public class MessageResource {
#OnMessage(encoders = {JSONEncoder.class})
public String onMessage(String data) {
return data;
}
}
and this this is placed on my template:
<p:socket channel="/receive-message" onMessage="handleMessage"></p:socket>
<p:growl widgetVar="growl-msg" globalOnly="true" id="growl-msg" life="2000" />
<script type="text/javascript">
function handleMessage(facesmessage) {
PF('growl-msg').renderMessage({"summary":"New Message",
"detail":facesmessage,
"severity":"info"})
}
</script>
to trigger the notification, i call this url. Where the data parameter is dynamic message that will showed into growl.
http://localhost:5050/WebAdmin/primepushpage/receive-message.jsf?data=Testing123
and this is my receive-message.xhtml
<ui:composition xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://xmlns.jcp.org/jsf/html"
xmlns:f="http://xmlns.jcp.org/jsf/core"
xmlns:ui="http://xmlns.jcp.org/jsf/facelets"
xmlns:p="http://primefaces.org/ui"
template="../pages/template.xhtml">
<ui:define name="content">
<f:metadata>
<f:viewParam name="data" value="#{pushMessageController.data}" />
</f:metadata>
<h:form>
<p:remoteCommand name="remoteCommand" actionListener="#{pushMessageController.execute}" autoRun="true" />
</h:form>
</ui:define>
</ui:composition>
and this is doFilter method on my Authorization Filter:
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws ServletException, IOException {
HttpServletRequest request = (HttpServletRequest) req;
HttpServletResponse response = (HttpServletResponse) res;
HttpSession session = request.getSession(false);
String loginURL = request.getContextPath() + "/pages/index.jsf";
boolean loggedIn = (session != null) && (session.getAttribute("user") != null);
boolean loginRequest = request.getRequestURI().equals(loginURL);
boolean resourceRequest = request.getRequestURI().startsWith(request.getContextPath() + ResourceHandler.RESOURCE_IDENTIFIER + "/");
boolean ajaxRequest = "partial/ajax".equals(request.getHeader("Faces-Request"));
boolean pushRequest = request.getRequestURI().contains("primepush");
if (loggedIn || loginRequest || resourceRequest || pushRequest) {
if (!resourceRequest) { // Prevent browser from caching restricted resources. See also http://stackoverflow.com/q/4194207/157882
response.setHeader("Cache-Control", "no-cache, no-store, must-revalidate"); // HTTP 1.1.
response.setHeader("Pragma", "no-cache"); // HTTP 1.0.
response.setDateHeader("Expires", 0); // Proxies.
}
chain.doFilter(request, response); // So, just continue request.
}
else if (ajaxRequest) {
response.setContentType("text/xml");
response.setCharacterEncoding("UTF-8");
response.getWriter().printf(AJAX_REDIRECT_XML, loginURL); // So, return special XML response instructing JSF ajax to send a redirect.
}
else {
if(!response.isCommitted()){
response.sendRedirect(loginURL); // So, just perform standard synchronous redirect.
return;
}
}
}
and i have add push servlet mapping on my web.xml, also my pom.xml already have atmosphere-runtime dependency. and i use Tomcat 7 for the container.
I had a same issue. After page was refresh via ajax and user manualy refreshed page I got from ocpsoft rewrite following warning:
Response has already been committed, and further write operations are not permitted. This may result in an IllegalStateException being triggered by the underlying application.
And after that the page was in invalid state and second refresh was needed. I have spent many hours trying to solve this issue and as last thing I tried to use different versions of atmosphere runtime (at first I have used the latest 2.4.9) and found out that it works correctly with versions 2.4.0 until 2.4.2.
Primefaces manual says that you can use version 2.3.RC6 and newest, but with versions below 2.4.0 I got nasty exceptions during application startup.
I use Primefaces 6.0 and application is deployed on Tomcat 8.0.39

How to create a thumbnail link to OmniFaces graphicImage method

I was wondering if and how it is possible to display an <o:graphicImage> as thumbnail inside a <p:lightbox>. To be more precise, I wanted to achieve something like this:
<p:dataTable id="articles" var="article"
value="#{articleMB.articles}" selectionMode="single"
rowKey="#{articles.id}"
selection="#{articleMB.selectedArticle}">
<p:column>
<p:lightBox styleClass="imagebox" id="lighbox">
<h:outputLink value="#{imageBean.getFirstImage(article, true)}">
<o:graphicImage value="#{imageBean.getFirstImage(article, true)}" dataURI="true" height="80" />
</h:outputLink>
</p:lightBox>
</p:column>
</p:dataTable>
Which isn't working obviously, since there's no proper URL passed to the lightbox.
imageBean.getFirstImage(Article article, boolean thumbnail) returns a byte[] of the image, since the images I want to access are stored on an external source.
Edit: So I've done as BalusC mentioned and it seems to be the proper approach. But now I'm getting the following exception:
Caused by: java.lang.IllegalArgumentException: java.lang.ClassCastException#2eae887c
at sun.reflect.GeneratedMethodAccessor307.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:497)
at org.omnifaces.resourcehandler.GraphicResource.getInputStream(GraphicResource.java:259)
at com.sun.faces.application.resource.ResourceHandlerImpl.handleResourceRequest(ResourceHandlerImpl.java:335)
at javax.faces.application.ResourceHandlerWrapper.handleResourceRequest(ResourceHandlerWrapper.java:153)
at org.primefaces.application.resource.PrimeResourceHandler.handleResourceRequest(PrimeResourceHandler.java:87)
at javax.faces.application.ResourceHandlerWrapper.handleResourceRequest(ResourceHandlerWrapper.java:153)
at javax.faces.application.ResourceHandlerWrapper.handleResourceRequest(ResourceHandlerWrapper.java:153)
at javax.faces.webapp.FacesServlet.service(FacesServlet.java:655)
... 32 more
This is the method that actually returns the image. It is working fine in every other context:
public byte[] getFirstImage(final Article article, boolean thumbnail)
{
try
{
File dir = new File(getImageFolder(article.getImageFolder(), thumbnail));
File[] files = dir.listFiles(new FilenameFilter()
{
#Override
public boolean accept(File dir, String name)
{
return name.startsWith(String.valueOf(article.getArticleId()));
}
});
Arrays.sort(files);
return Files.readAllBytes(files[0].toPath());
}
catch (Exception e)
{
return new byte[1];
}
}
Edit 2: As mentioned in the comments, I'm facing another weird behaviour. It runs perfectly fine on my local machine but on the server it throws following exception:
Caused by: java.lang.IllegalArgumentException: argument type mismatch
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at org.omnifaces.resourcehandler.GraphicResource.getInputStream(GraphicResource.java:259)
at com.sun.faces.application.resource.ResourceHandlerImpl.handleResourceRequest(ResourceHandlerImpl.java:335)
at javax.faces.application.ResourceHandlerWrapper.handleResourceRequest(ResourceHandlerWrapper.java:153)
at org.primefaces.application.resource.PrimeResourceHandler.handleResourceRequest(PrimeResourceHandler.java:87)
at javax.faces.application.ResourceHandlerWrapper.handleResourceRequest(ResourceHandlerWrapper.java:153)
at javax.faces.application.ResourceHandlerWrapper.handleResourceRequest(ResourceHandlerWrapper.java:153)
at javax.faces.webapp.FacesServlet.service(FacesServlet.java:655)
... 32 more
For exactly this reason, OmniFaces 2.5 introduced the #{of:graphicImageURL()} EL function. This works only if your ImageBean is annotated with #GraphicImageBean.
import org.omnifaces.cdi.GraphicImageBean;
#GraphicImageBean
public class ImageBean {
// ...
}
<h:outputLink value="#{of:graphicImageURL('imageBean.getFirstImage(article, false)')}">
<o:graphicImage value="#{imageBean.getFirstImage(article, true)}" dataURI="true" height="80" />
</h:outputLink>
See also the #GraphicImageBean showcase.
Update: to be clear, you need a converter for non-standard types such as Article. Why such a converter is needed and how to create it is detailed in Conversion Error setting value for 'null Converter'. If you create a #FacesConverter(forClass=Article.class), then the OmniFaces GraphicImage will automatically pickup it.
In your particular case it's however more efficient to just pass the identifier to the image streamer method right away, this saves an additional conversion step. Provided that your Article object has an id property, here's how:
<h:outputLink value="#{of:graphicImageURL('imageBean.getFirstImage(article.id, false)')}">
<o:graphicImage value="#{imageBean.getFirstImage(article.id, true)}" dataURI="true" height="80" />
</h:outputLink>
public byte[] getFirstImage(Long articleId, boolean thumbnail) {
// ...
}
Namely, JSF already has builtin converters for standard types such as Long and boolean.

Error in streaming dynamic resource. null

Important Notice : This issue has been fixed as of PrimeFaces 5.2 final (Community Release) released on April 8, 2015. As such if you happened to use that version or newer, you would not need to fiddle around with a temporary workaround.
The earlier given example can now safely be modified as follows.
public StreamedContent getImage() throws IOException {
FacesContext context = FacesContext.getCurrentInstance();
if (context.getCurrentPhaseId() == PhaseId.RENDER_RESPONSE) {
return new DefaultStreamedContent();
} else {
String id = context.getExternalContext().getRequestParameterMap().get("id");
byte[] bytes = Utils.isNumber(id) ? service.findImageById(Long.parseLong(id)) : null;
return bytes == null ? null : new DefaultStreamedContent(new ByteArrayInputStream(bytes));
}
}
I have moved images to the database (MySQL) in the form of BLOB (LONGBLOB) after I got tired of manipulating/managing images stored in the disk file system.
Accordingly, I'm displaying images in <p:dataTable> as follows (blatantly copied from here :) ).
<p:column headerText="Header">
<p:graphicImage value="#{bannerBean.image}" height="200" width="200">
<f:param name="id" value="#{row.bannerId}"/>
</p:graphicImage>
<p:column>
The bean that retrieves images is as follows.
#ManagedBean
#ApplicationScoped
public final class BannerBean
{
#EJB
private final BannerBeanLocal service=null;
public BannerBean() {}
public StreamedContent getImage() throws IOException {
FacesContext context = FacesContext.getCurrentInstance();
if (context.getCurrentPhaseId() == PhaseId.RENDER_RESPONSE) {
return new DefaultStreamedContent();
}
else {
String id = context.getExternalContext().getRequestParameterMap().get("id");
byte[] bytes = service.findImageById(Long.parseLong(id));
return bytes==null? new DefaultStreamedContent():new DefaultStreamedContent(new ByteArrayInputStream(bytes));
}
}
}
This works fine as long as there are images in each row of the underlying database table.
The BLOB type column in the database is however, optional in some cases and hence, it can contain null values as well.
If this column in any row/s in the database is null then, the following exception is thrown.
SEVERE: Error in streaming dynamic resource. null
WARNING: StandardWrapperValve[Faces Servlet]: Servlet.service() for servlet Faces Servlet threw exception
java.lang.NullPointerException
at org.primefaces.application.PrimeResourceHandler.handleResourceRequest(PrimeResourceHandler.java:127)
at javax.faces.application.ResourceHandlerWrapper.handleResourceRequest(ResourceHandlerWrapper.java:153)
at javax.faces.webapp.FacesServlet.service(FacesServlet.java:643)
at org.apache.catalina.core.StandardWrapper.service(StandardWrapper.java:1682)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:344)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:214)
at org.primefaces.webapp.filter.FileUploadFilter.doFilter(FileUploadFilter.java:70)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:256)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:214)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:316)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:160)
at org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:734)
at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:673)
at com.sun.enterprise.web.WebPipeline.invoke(WebPipeline.java:99)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:174)
at org.apache.catalina.connector.CoyoteAdapter.doService(CoyoteAdapter.java:357)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:260)
at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:188)
at org.glassfish.grizzly.http.server.HttpHandler.runService(HttpHandler.java:191)
at org.glassfish.grizzly.http.server.HttpHandler.doHandle(HttpHandler.java:168)
at org.glassfish.grizzly.http.server.HttpServerFilter.handleRead(HttpServerFilter.java:189)
at org.glassfish.grizzly.filterchain.ExecutorResolver$9.execute(ExecutorResolver.java:119)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeFilter(DefaultFilterChain.java:288)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeChainPart(DefaultFilterChain.java:206)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.execute(DefaultFilterChain.java:136)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.process(DefaultFilterChain.java:114)
at org.glassfish.grizzly.ProcessorExecutor.execute(ProcessorExecutor.java:77)
at org.glassfish.grizzly.nio.transport.TCPNIOTransport.fireIOEvent(TCPNIOTransport.java:838)
at org.glassfish.grizzly.strategies.AbstractIOStrategy.fireIOEvent(AbstractIOStrategy.java:113)
at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.run0(WorkerThreadIOStrategy.java:115)
at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.access$100(WorkerThreadIOStrategy.java:55)
at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy$WorkerThreadRunnable.run(WorkerThreadIOStrategy.java:135)
at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:564)
at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.run(AbstractThreadPool.java:544)
at java.lang.Thread.run(Thread.java:722)
So how to manage null BLOBs so that this exception disappears?
Returning new DefaultStreamedContent(new ByteArrayInputStream(new byte[0])), in case, the byte array in the managed bean is null would suppress the exception but this after all, should not be a solution. Is this a desired solution?
The EJB method that returns a byte array though completely unnecessary, in this case.
public byte[] findImageById(Long id)
{
CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
CriteriaQuery<byte[]>criteriaQuery=criteriaBuilder.createQuery(byte[].class);
Root<BannerImages> root = criteriaQuery.from(BannerImages.class);
criteriaQuery.multiselect(root.get(BannerImages_.bannerImage));
ParameterExpression<Long>parameterExpression=criteriaBuilder.parameter(Long.class);
criteriaQuery.where(criteriaBuilder.equal(root.get(BannerImages_.bannerId), parameterExpression));
List<byte[]> list = entityManager.createQuery(criteriaQuery).setParameter(parameterExpression, id).getResultList();
return list!=null&&!list.isEmpty()?list.get(0):null;
}
This is a bug (at least, a functional/technical design mistake) in PrimeResourceHandler. It shouldn't have assumed the dynamic resource or its content to be never null. It should have conditionally checked if that was the case and then simply have returned a HTTP 404 "Not Found" response.
In other words, instead of
85 streamedContent = (StreamedContent) ve.getValue(eLContext);
86
87 externalContext.setResponseStatus(200);
88 externalContext.setResponseContentType(streamedContent.getContentType());
they should have done
85 streamedContent = (StreamedContent) ve.getValue(eLContext);
86
87 if (streamedContent == null || streamedContent.getStream() == null) {
88 externalContext.responseSendError(HttpServletResponse.SC_NOT_FOUND, ((HttpServletRequest) externalContext.getRequest()).getRequestURI());
89 return;
90 }
91
92 externalContext.setResponseStatus(200);
93 externalContext.setResponseContentType(streamedContent.getContentType());
This way you can just return null or an empty StreamedContent from the getImage() method in order to generate a decent 404.
Well, what can you do?
Report it to them and hope that they'll fix it. Update They fixed it in version 5.2.
And/or, put a copy of PrimeResourceHandler class in the Java source folder of your webapp project, in exactly its own org.primefaces.application package and then just edit it to include the mentioned change and finally just build/deploy your webapp project as WAR as usual. Classes in /WEB-INF/classes have higher classloading precedence over those in JARs in /WEB-INF/lib, so the modified one will be used instead.
I would suggest to include an attribute in the object the <p:dataTable> is iterating on to signify if an image exists. That way, there are no unnecessary (or null return) calls to BannerBean.getImage().
Example:
<p:column headerText="Header">
<p:graphicImage value="#{bannerBean.image}" height="200" width="200"
rendered="#{row.hasImage}">
<f:param name="id" value="#{row.bannerId}"/>
</p:graphicImage>
<p:column>
Another option is to grab the Primefaces source code, edit PrimeResourceHandler.java, and build it. (see the wiki)
An alternative solution would be to setup your own Serlvet to provide the images.
Main benefit is that browsers can cache the image (you can specify cache timeout if wanted).
Be aware of SQL Injection & other security attacks.
Attach some sort of login/permission check for additional security. (if needed)
Example:
<p:column headerText="Header">
<p:graphicImage value="#{request.contextPath}/images/banner/?id=#{row.bannerId}"
height="200" width="200" />
<p:column>
#WebServlet(name = "Retrieve Banner Images", urlPatterns = "/images/banner/*")
public class BannerImageServlet extends HttpServlet
{
#EJB
private final BannerBeanLocal service;
protected void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
String[] ids = req.getParameterValues("id");
if(ids != null && ids.length == 1) {
byte[] bytes = service.findImageById(Long.parseLong(ids[0]));
if(bytes != null) {
// see link #3 below
}
}
}
}
Sources / useful links:
#{request.contextPath}
#WebServlet tutorial
how to send byte stream back to the client

javax.validation.ConstraintViolationException

I am using JSF+JPA iam not fix this error:
javax.validation.ConstraintViolationException: Bean Validation
constraint(s) violated while executing Automatic Bean Validation on
callback event:'prePersist'. Please refer to embedded
ConstraintViolations for details.
#ManagedBean(name = "clientCon")
public class ClientController {
#PostConstruct
public void init() {
System.out.println("Salam");
clients = new Clients();
}
private EntityManagerFactory emf = null;
public ClientController() {
emf = Persistence.createEntityManagerFactory("ClinicProjectPU");
}
private List<Clients> clientList;
private Clients clients;
public EntityManager getEntityManager() {
return emf.createEntityManager();
}
public Clients getClients() {
return clients;
}
public void setClients(Clients clients) {
this.clients = clients;
}
public List<Clients> getClientList() {
this.clientList = getEntityManager().createNamedQuery("Clients.findAll").getResultList();
return clientList;
}
public void createClient() {
EntityManager em = null;
try {
em = getEntityManager();
em.getTransaction().begin();
em.persist(clients); // the only interesting method
em.flush();
em.getTransaction().commit();
System.out.println("created");
} catch (Exception ex) {
ex.printStackTrace();
} finally {
if (em != null) {
em.close();
}
}
}
}
<h:form>
<fieldset>
<h:panelGrid columns="2">
<h:outputText value="Ad" style="color: #0099cc"/>
<h:inputText class="form-client" value="#{clientCon.clients.name}" />
<h:outputText value="Soyad" style="color: #0099cc" />
<h:inputText class="form-client" value="#{clientCon.clients.surname}" />
<h:outputText value="Telefon" style="color: #0099cc" />
<h:inputText class="form-client" value="#{clientCon.clients.phone}" />
</h:panelGrid>
<div class="btns">
<center><h:commandButton action="#{clientCon.createClient()}" value="Saxla" style="width: 60%;margin-top: 5%;border-radius: 5px;color: #ffffff;background-color: #0099cc" /></center>
</div>
</fieldset>
</h:form>
javax.validation.ConstraintViolationException: Bean Validation constraint(s) violated while executing Automatic Bean Validation on callback event:'prePersist'. Please refer to embedded ConstraintViolations for details.
at org.eclipse.persistence.internal.jpa.metadata.listeners.BeanValidationListener.validateOnCallbackEvent(BeanValidationListener.java:90)
at org.eclipse.persistence.internal.jpa.metadata.listeners.BeanValidationListener.prePersist(BeanValidationListener.java:62)
at org.eclipse.persistence.descriptors.DescriptorEventManager.notifyListener(DescriptorEventManager.java:748)
at org.eclipse.persistence.descriptors.DescriptorEventManager.notifyEJB30Listeners(DescriptorEventManager.java:691)
at org.eclipse.persistence.descriptors.DescriptorEventManager.executeEvent(DescriptorEventManager.java:229)
at org.eclipse.persistence.internal.sessions.UnitOfWorkImpl.registerNewObjectClone(UnitOfWorkImpl.java:4310)
at org.eclipse.persistence.internal.sessions.UnitOfWorkImpl.registerNotRegisteredNewObjectForPersist(UnitOfWorkImpl.java:4287)
at org.eclipse.persistence.internal.sessions.RepeatableWriteUnitOfWork.registerNotRegisteredNewObjectForPersist(RepeatableWriteUnitOfWork.java:518)
at org.eclipse.persistence.internal.sessions.UnitOfWorkImpl.registerNewObjectForPersist(UnitOfWorkImpl.java:4229)
at org.eclipse.persistence.internal.jpa.EntityManagerImpl.persist(EntityManagerImpl.java:496)
at controller.ClientController.createClient(ClientController.java:69)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at javax.el.ELUtil.invokeMethod(ELUtil.java:326)
at javax.el.BeanELResolver.invoke(BeanELResolver.java:536)
at javax.el.CompositeELResolver.invoke(CompositeELResolver.java:256)
at com.sun.el.parser.AstValue.invoke(AstValue.java:269)
at com.sun.el.MethodExpressionImpl.invoke(MethodExpressionImpl.java:304)
at com.sun.faces.facelets.el.TagMethodExpression.invoke(TagMethodExpression.java:105)
at javax.faces.component.MethodBindingMethodExpressionAdapter.invoke(MethodBindingMethodExpressionAdapter.java:87)
at com.sun.faces.application.ActionListenerImpl.processAction(ActionListenerImpl.java:102)
at javax.faces.component.UICommand.broadcast(UICommand.java:315)
at javax.faces.component.UIViewRoot.broadcastEvents(UIViewRoot.java:790)
at javax.faces.component.UIViewRoot.processApplication(UIViewRoot.java:1282)
at com.sun.faces.lifecycle.InvokeApplicationPhase.execute(InvokeApplicationPhase.java:81)
at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101)
at com.sun.faces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:198)
at javax.faces.webapp.FacesServlet.service(FacesServlet.java:646)
at org.apache.catalina.core.StandardWrapper.service(StandardWrapper.java:1682)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:318)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:160)
at org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:734)
at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:673)
at com.sun.enterprise.web.WebPipeline.invoke(WebPipeline.java:99)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:174)
at org.apache.catalina.connector.CoyoteAdapter.doService(CoyoteAdapter.java:357)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:260)
at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:188)
at org.glassfish.grizzly.http.server.HttpHandler.runService(HttpHandler.java:191)
at org.glassfish.grizzly.http.server.HttpHandler.doHandle(HttpHandler.java:168)
at org.glassfish.grizzly.http.server.HttpServerFilter.handleRead(HttpServerFilter.java:189)
at org.glassfish.grizzly.filterchain.ExecutorResolver$9.execute(ExecutorResolver.java:119)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeFilter(DefaultFilterChain.java:288)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeChainPart(DefaultFilterChain.java:206)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.execute(DefaultFilterChain.java:136)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.process(DefaultFilterChain.java:114)
at org.glassfish.grizzly.ProcessorExecutor.execute(ProcessorExecutor.java:77)
at org.glassfish.grizzly.nio.transport.TCPNIOTransport.fireIOEvent(TCPNIOTransport.java:838)
at org.glassfish.grizzly.strategies.AbstractIOStrategy.fireIOEvent(AbstractIOStrategy.java:113)
at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.run0(WorkerThreadIOStrategy.java:115)
at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.access$100(WorkerThreadIOStrategy.java:55)
at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy$WorkerThreadRunnable.run(WorkerThreadIOStrategy.java:135)
at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:564)
at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.run(AbstractThreadPool.java:544)
at java.lang.Thread.run(Thread.java:724)
To know what caused the constraint violation, you can use the following validator and logger.
ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
Validator validator = factory.getValidator();
Set<ConstraintViolation<Clients>> constraintViolations = validator.validate(clients);
if (constraintViolations.size() > 0 ) {
System.out.println("Constraint Violations occurred..");
for (ConstraintViolation<Clients> contraints : constraintViolations) {
System.out.println(contraints.getRootBeanClass().getSimpleName()+
"." + contraints.getPropertyPath() + " " + contraints.getMessage());
}
}
Put the logger before persisting the entity. So between
em.getTransaction().begin();
//here goes the validator
em.persist(clients);
Compile and run. The console will show you, just before the exception stack trace, which element(s) caused the violation(s).
You can but should catch your try block containing any persistence method with ConstraintViolationException (to avoid further problems and/or inform the user an error occurred and its reason). However, in a well built system there shouldn't be any constraint violation exception during persistence. In JSF, and other MVC framework, the validation step must be totally or partially done at the client side before submit/persistence. That's a good practice I would say.
This is another way from correct answer on Sujan Sivagurunathan, i wrote not in comment because i dont have 50 reputation.
If you have AbstractFacade.java write this on create method
public void create(T entity) {
ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
javax.validation.Validator validator = factory.getValidator();
Set<ConstraintViolation<T>> constraintViolations = validator.validate(entity);
if (constraintViolations.size() > 0 ) {
System.out.println("Constraint Violations occurred..");
for (ConstraintViolation<T> contraints : constraintViolations) {
System.out.println(contraints.getRootBeanClass().getSimpleName()+
"." + contraints.getPropertyPath() + " " + contraints.getMessage());
}
getEntityManager().persist(entity);
}
}

NullPointerException Error when trying to get a value from Another Bean in JSF

I've two backing beans:
Login: a bean that validates the user login info (username and password) with database table.
Buss_Services: another bean that performs some business services.
I need to get the user ID from the Login bean and use it inside the Buss_Services. It's stored in a String property of Login and the Buss_Services needs this value to track the currently logged-in user and update the DB.
Here's the Login backing bean:
#ManagedBean(name="Login")
#SessionScoped
public class Login {
private String loggedUserID;
public Object logCB_action() {
try {
// ...
rs = stmt.executeQuery(SQL);
while (rs.next()) {
if (rs.getString("USER_NAME").equals(uname)) {
if (rs.getString("USER_PW").equals(pword)) {
// Here, the user ID is set.
loggedUserID=rs.getString("USER_ID");// This line ...
System.out.println("Logged User (ID): "+ userID);
return ("displayApp");
}
}
}
}
// ...
}
public String getLoggedID() {
// Here, the user ID is returned.
String id = loggedUserID;
return (id);
}
}
Here's the Buss_Services backing bean which calls the getLoggedID() method:
#ManagedBean(name="Buss_Services")
#SessionScoped
public class Buss_Services {
#ManagedProperty("#{Login}")
private Login login;
public void newEst_action() {
// The following line throws NullPointerException.
System.out.println("Logged User (ID): " + login.getLoggedID());
}
// Getters/setters.
}
This is the stack trace which I get when I try to access the bussiness services page:
javax.faces.el.EvaluationException:
//C:/Users/Sultan09/AppData/Roaming/JDeveloper/system11.1.2.0.38.60.17/o.j2ee/drs/TheOCES/OCES.ViewControllerWebApp.war/App_Business_SerivesPG.jsf #68,140 action="#{backingBeanScope.App_BServPG_Bean.newEst_action}": java.lang.NullPointerException
at org.apache.myfaces.trinidad.component.MethodExpressionMethodBinding.invoke(MethodExpressionMethodBinding.java:51)
at com.sun.faces.application.ActionListenerImpl.processAction(ActionListenerImpl.java:102)
at org.apache.myfaces.trinidad.component.UIXCommand.broadcast(UIXCommand.java:190)
at javax.faces.component.UIViewRoot.broadcastEvents(UIViewRoot.java:787)
at javax.faces.component.UIViewRoot.processApplication(UIViewRoot.java:1252)
at oracle.adfinternal.view.faces.lifecycle.LifecycleImpl._invokeApplication(LifecycleImpl.java:965)
at oracle.adfinternal.view.faces.lifecycle.LifecycleImpl._executePhase(LifecycleImpl.java:346)
at oracle.adfinternal.view.faces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:204)
at javax.faces.webapp.FacesServlet.service(FacesServlet.java:312)
at weblogic.servlet.internal.StubSecurityHelper$ServletServiceAction.run(StubSecurityHelper.java:227)
at weblogic.servlet.internal.StubSecurityHelper.invokeServlet(StubSecurityHelper.java:125)
at weblogic.servlet.internal.ServletStubImpl.execute(ServletStubImpl.java:300)
at weblogic.servlet.internal.TailFilter.doFilter(TailFilter.java:26)
at weblogic.servlet.internal.FilterChainImpl.doFilter(FilterChainImpl.java:56)
at oracle.adf.model.servlet.ADFBindingFilter.doFilter(ADFBindingFilter.java:173)
at weblogic.servlet.internal.FilterChainImpl.doFilter(FilterChainImpl.java:56)
at oracle.adfinternal.view.faces.webapp.rich.RegistrationFilter.doFilter(RegistrationFilter.java:121)
at org.apache.myfaces.trinidadinternal.webapp.TrinidadFilterImpl$FilterListChain.doFilter(TrinidadFilterImpl.java:468)
at oracle.adfinternal.view.faces.activedata.AdsFilter.doFilter(AdsFilter.java:60)
at org.apache.myfaces.trinidadinternal.webapp.TrinidadFilterImpl$FilterListChain.doFilter(TrinidadFilterImpl.java:468)
at org.apache.myfaces.trinidadinternal.webapp.TrinidadFilterImpl._doFilterImpl(TrinidadFilterImpl.java:293)
at org.apache.myfaces.trinidadinternal.webapp.TrinidadFilterImpl.doFilter(TrinidadFilterImpl.java:199)
at org.apache.myfaces.trinidad.webapp.TrinidadFilter.doFilter(TrinidadFilter.java:92)
at weblogic.servlet.internal.FilterChainImpl.doFilter(FilterChainImpl.java:56)
at oracle.security.jps.ee.http.JpsAbsFilter$1.run(JpsAbsFilter.java:111)
at java.security.AccessController.doPrivileged(Native Method)
at oracle.security.jps.util.JpsSubject.doAsPrivileged(JpsSubject.java:313)
at oracle.security.jps.ee.util.JpsPlatformUtil.runJaasMode(JpsPlatformUtil.java:413)
at oracle.security.jps.ee.http.JpsAbsFilter.runJaasMode(JpsAbsFilter.java:94)
at oracle.security.jps.ee.http.JpsAbsFilter.doFilter(JpsAbsFilter.java:161)
at oracle.security.jps.ee.http.JpsFilter.doFilter(JpsFilter.java:71)
at weblogic.servlet.internal.FilterChainImpl.doFilter(FilterChainImpl.java:56)
at oracle.dms.servlet.DMSServletFilter.doFilter(DMSServletFilter.java:136)
at weblogic.servlet.internal.FilterChainImpl.doFilter(FilterChainImpl.java:56)
at weblogic.servlet.internal.RequestEventsFilter.doFilter(RequestEventsFilter.java:27)
at weblogic.servlet.internal.FilterChainImpl.doFilter(FilterChainImpl.java:56)
at weblogic.servlet.internal.WebAppServletContext$ServletInvocationAction.wrapRun(WebAppServletContext.java:3715)
at weblogic.servlet.internal.WebAppServletContext$ServletInvocationAction.run(WebAppServletContext.java:3681)
at weblogic.security.acl.internal.AuthenticatedSubject.doAs(AuthenticatedSubject.java:321)
at weblogic.security.service.SecurityManager.runAs(SecurityManager.java:120)
at weblogic.servlet.internal.WebAppServletContext.securedExecute(WebAppServletContext.java:2277)
at weblogic.servlet.internal.WebAppServletContext.execute(WebAppServletContext.java:2183)
at weblogic.servlet.internal.ServletRequestImpl.run(ServletRequestImpl.java:1454)
at weblogic.work.ExecuteThread.execute(ExecuteThread.java:209)
at weblogic.work.ExecuteThread.run(ExecuteThread.java:178
Caused by: java.lang.NullPointerException
at JavaView.backing.Buss_Services.newEst_action(Buss_Services.java:172)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at com.sun.el.parser.AstValue.invoke(Unknown Source)
at com.sun.el.MethodExpressionImpl.invoke(Unknown Source)
at com.sun.faces.facelets.el.TagMethodExpression.invoke(TagMethodExpression.java:105)
at org.apache.myfaces.trinidad.component.MethodExpressionMethodBinding.invoke(MethodExpressionMethodBinding.java:46)
... 44 more
How is this caused and how can I solve it?
UPDATE :
As per comments here and personal search on similar issues to the one stated here, the Problem is Finally solved ,thank god.
The solution was that I had to:
add the <managed-property> of login to the adfc-config.xml file .
more importantly , obtain the loggedUserID inside a #PostConstruct anotated method init() . Thanx everyone.
System.out.println("Logged User (ID): " + login.get_final_logged_ID());
A NullPointerException on that line has as the only possible cause that login is null. Given the fact that the #ManagedProperty looks fine, this can have only one possible cause: the setter method setLogin() is broken. Make sure that it look exactly like this:
public void setLogin(Login login) {
this.login = login;
}
and thus not
public void setLogin(Login login) {
login = login;
}
or something else.
Update as per the comments:
As for the faces-config.xml , here's the thing , the Login and bussiness services beans,for their repective jsf pages , are defined as "backingBean" in the <managed-bean-scope>. In the java beans ,as u saw , I defined them sessionScoped.
Finally, there is the cause of your problem. Configuration in faces-config.xml overrides all JSF2 annotations on the bean in question. You have apparently not configured the <managed-property> in the faces-config.xml. You have 2 options:
Remove the whole <managed-bean> configuration in faces-config.xml. The whole point of new JSF 2.x annotations like #ManagedBean, #ManagedProperty, etc is to get rid of verbose JSF 1.x style XML configuration.
Add a <managed-property> value of #{Login} to the <managed-bean> of Buss_Services.
<managed-property>
<property-name>login</property-name>
<value>#{Login}</value>
</managed-property>
Unrelated to the concrete problem. You've several serious flaws in the design and code style.
You should not reference UIComponents as properties. Instead, you should reference its values. Keep the model as simple as possible and never use UIComponent unless you have a really valid reason. E.g.
private String username;
private String password;
private Long userID;
Your login validation method is inefficient. It seems to haul the entire users table from DB into Java's memory wherein you test every individual row. You should try to write and finetune the SQL query as much as possible so that it returns exactly the information you're looking for.
statement = connection.prepareStatement("SELECT id FROM Users WHERE username = ? AND password = MD5(?)");
statement.setString(1, username);
statement.setString(2, password);
resultSet = statement.executeQuery();
if (resultSet.next()) {
userID = resultSet.getLong("id");
}
Your PHP-like code style fully contradicts the Java Naming Conventions. It makes the code harder to read and maintain by all other Java developers, such as the ones from who you expect answers when you post the code on the Internet, like here. Package names should be all lowercase. Underscores are only valid in constants, for all other names CamelCase should be used. Instance names (like managed bean names) should start with lowercase. Etcetera.
Ok NullPointerException is a very general class of errors which have nothing to do with jsf or your db access layer etc in particular. And as far as i can see from the stacktrace it is being thrown from inside of newEst_action function for which you have not provided any code. Go to the specific line in that function i.e. 172 and see if you are doing something like
myObject.doSomething()
without checking that the object could be null,it could throw NPE if myObject is null, so do something like
if (myObject!=null)
myObject.doSomething()
Please check if your ManagedProperty login isnt null, when you print the id.
and try #ManagedProperty(value = "#{Login}") !

Resources