selectOneRadio component and Long value - java

Well, I should create an survey application amd the value of the answers is a Long with value from 1 to 6.
I tried many different things but the result is every time:
java.lang.String cannot be cast to java.lang.Long
At the moment this my code:
java class:
...
private HashMap<Questions,Long> itemsHash= new HashMap<Questions,Long>();
private static Map<Long,Long> valutazioni;
static{
valutazioni = new LinkedHashMap<Long,Long>();
valutazioni.put(new Long("1"), new Long("1"));
valutazioni.put(new Long("2"), new Long("2"));
valutazioni.put(new Long("3"), new Long("3"));
valutazioni.put(new Long("4"), new Long("4"));
valutazioni.put(new Long("5"), new Long("5"));
valutazioni.put(new Long("6"), new Long("6"));
}
public Map getValutazioni()
{
return valutazioni;
}
...
public String prepareCreate() {
itemsHash=new HashMap<Questions,Long>();
//-- retrieve all questions from db
List<Questions> qList= getQEjb().findByQuery("select q from Question q order by q.description");
Iterator<Questions> iter=qList.iterator();
Questions q;
//--- initiliazing itemsHash with 1 as default value
while (iter.hasNext())
{
q=iter.next();
itemsHash.put(q,(new Long("1")));
}
selectedItemIndex = -1;
return "Create";
}
public String create() {
try {
List<Questions> qList= getQEjb().findByQuery("select q from Questions q order by q.description");
Iterator<Questions> iter=qList.iterator();
Questions q;
while (iter.hasNext())
{
q=iter.next();
current=new Answers();
current.setAllievo(findAllievo);
current.setData(findData);
current.setIdQuestion(q);
current.setLivello(itemsHash.get(q));
getFacade().create(current);
}
JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/Bundle").getString("ProgettiQualificaCreated"));
return pqc.prepareList();
} catch (Exception e) {
JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured"));
e.printStackTrace();
return "List";
}
}
the xhtml page is:
<h:outputLabel value="#{bundle.AnswersLabel_data}" for="data" />
<h:inputText id="data" value="#{answersController.findData}" title="#{bundle.AnswersTitle_data}" >
<f:convertDateTime pattern="dd/MM/yyyy HH:mm:ss" />
</h:inputText>
<h:outputLabel value="#{bundle.AnswersLabel_allievo}" for="allievo" />
<h:inputText id="allievo" value="#{answersController.findAllievo}" title="#{bundle.AnswersTitle_allievo}" />
<h:outputLabel value="#{bundle.AnswersLabel_numScheda}" for="numScheda" />
<h:inputText id="numScheda" value="#{answersController.findNumScheda}" title="#{bundle.AnswersTitle_numScheda}" required="true" requiredMessage="#{bundle.AnswersRequiredMessage_numScheda}"/>
<h:outputText value="#{bundle.AnswersLabel_idProgetto}"/>
<h:outputText value="#{answersController.findProgetto}" title="#{bundle.AnswersTitle_idProgetto}"/>
<h:dataTable value="#{questionsController.items}" var="car" rules="all" >
<h:column>
<f:facet name="header">
<h:outputText value="#{bundle.AnswersTitle_idQuestion}"/>
</f:facet>
<h:outputText value="#{car.descrizione}"/>
</h:column>
<h:column>
<f:facet name="header">
<h:outputText value="#{bundle.AnswersTitle_livello}"/>
</f:facet>
<h:selectOneRadio value="#{answersController.itemsHash[car]}" title="#{bundle.AnswersTitle_idQuestion}" >
<f:selectItems value="#{answersController.getValutazioni()}" />
</h:selectOneRadio>
</h:column>
</h:dataTable>
Where is my error?
error log:
[#|2012-03-20T15:52:17.656+0100|SEVERE|glassfish3.1.1|javax.enterprise.system.std.com.sun.enterprise.server.logging|_ThreadID=97;_ThreadName=Thread-2;|java.lang.ClassCastException: java.lang.String cannot be cast to java.lang.Long
at it.cyborg.cdg.jsfClasses.AnswersController.create(AnswersController.java:187)
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:234)
at com.sun.el.MethodExpressionImpl.invoke(MethodExpressionImpl.java:297)
at org.jboss.weld.util.el.ForwardingMethodExpression.invoke(ForwardingMethodExpression.java:43)
at org.jboss.weld.el.WeldMethodExpression.invoke(WeldMethodExpression.java:56)
at com.sun.faces.facelets.el.TagMethodExpression.invoke(TagMethodExpression.java:105)
at javax.faces.component.MethodBindingMethodExpressionAdapter.invoke(MethodBindingMethodExpressionAdapter.java:88)
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:794)
at javax.faces.component.UIViewRoot.processApplication(UIViewRoot.java:1259)
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:118)
at javax.faces.webapp.FacesServlet.service(FacesServlet.java:593)
at org.apache.catalina.core.StandardWrapper.service(StandardWrapper.java:1539)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:343)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:217)
at it.cyborg.cdg.jsfClasses.util.MultipartFilter.doFilter(MultipartFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:256)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:217)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:279)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:175)
at org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:655)
at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:595)
at com.sun.enterprise.web.WebPipeline.invoke(WebPipeline.java:98)
at com.sun.enterprise.web.PESessionLockingStandardPipeline.invoke(PESessionLockingStandardPipeline.java:91)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:162)
at org.apache.catalina.connector.CoyoteAdapter.doService(CoyoteAdapter.java:330)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:231)
at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:174)
at com.sun.grizzly.http.ProcessorTask.invokeAdapter(ProcessorTask.java:828)
at com.sun.grizzly.http.ProcessorTask.doProcess(ProcessorTask.java:725)
at com.sun.grizzly.http.ProcessorTask.process(ProcessorTask.java:1019)
at com.sun.grizzly.http.DefaultProtocolFilter.execute(DefaultProtocolFilter.java:225)
at com.sun.grizzly.DefaultProtocolChain.executeProtocolFilter(DefaultProtocolChain.java:137)
at com.sun.grizzly.DefaultProtocolChain.execute(DefaultProtocolChain.java:104)
at com.sun.grizzly.DefaultProtocolChain.execute(DefaultProtocolChain.java:90)
at com.sun.grizzly.http.HttpProtocolChain.execute(HttpProtocolChain.java:79)
at com.sun.grizzly.ProtocolChainContextTask.doCall(ProtocolChainContextTask.java:54)
at com.sun.grizzly.SelectionKeyContextTask.call(SelectionKeyContextTask.java:59)
at com.sun.grizzly.ContextTask.run(ContextTask.java:71)
at com.sun.grizzly.util.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:532)
at com.sun.grizzly.util.AbstractThreadPool$Worker.run(AbstractThreadPool.java:513)
at java.lang.Thread.run(Thread.java:722)
My application runs on Glassfish 3.1 and support JSF2.0 and PrimeFaces 3.2 RC1

The problem is that you've bound a generic Map as value of <h:selectOneRadio> as follows
<h:selectOneRadio value="#{answersController.itemsHash[car]}">
But JSF/EL doesn't support generic types. This information is namely not available during runtime. Unless you explicitly specify a converter, EL will not convert/coerce the submitted String value before setting it as Map value.
You need to explicitly specify the default JSF Long converter javax.faces.Long here:
<h:selectOneRadio value="#{answersController.itemsHash[car]}" converter="javax.faces.Long">

Related

how to load dynamic images in datatable using primefaces from database? images not showing in datatable

I am using primfaces 5 version to show images from my database in datatable, but unfortunately instead of actual images "image" is getting written in column, here is my xhtml file.
I have a list of objects with a StreamedContent property and I need to show it in the component.
i throw the showcase primefaces with no result
<p:dataTable id="dta" value="#{UtilisateurComponent.listUtilisateurs()}" var="current" rows="15" paginator="true" paginatorPosition="bottom" rowKey="current.iduser">
<p:column>
<f:facet name="header">
<h:outputText value="id User" />
</f:facet>
<h:outputText value="#{current.iuser}" />
</p:column>
<p:column >
<f:facet name="header">
<h:outputText value="Photo" />
</f:facet>
<p:graphicImage value="#{UtilisateurComponent.content}" height="100" width="150">
<f:param name="id" value="#{current.iduser}" />
</p:graphicImage>
</p:column>
</p:dataTable>
here is my managed bean :
enter code here
#Scope("session")
#Component("UtilisateurComponent")
public class UtilisateurComponentImpl implements UtilisateurComponent {
private Utilisateur utilisateur;
byte[] f;
private UploadedFile file;
private StreamedContent content;
#Autowired
private UtilisateurDAO utilisateurDAO;
#Autowired
private UtilisateurService utilisateurService;
public StreamedContent getContent() {
FacesContext context = FacesContext.getCurrentInstance();
if (context.getCurrentPhaseId() == PhaseId.RENDER_RESPONSE) {
return new DefaultStreamedContent();
}
else{
String imageId = context.getExternalContext().getRequestParameterMap().get("id");
Utilisateur u = utilisateurDAO.findUtilisateurByIduser(Integer.parseInt(imageId));
return new DefaultStreamedContent(new ByteArrayInputStream(u.getPhoto())); //the line that throw the Error
}
}
public void setContent(StreamedContent content) {
this.content = content;
}
#PostConstruct
public void init() {
//initialize the data here
this.utilisateur = new Utilisateur();
}
public UploadedFile getFile() {
return file;
}
public void setFile(UploadedFile file) {
this.file = file;
}
#Transactional
public String saveUtilisateurTest(Utilisateur utilisateur) {
try{
utilisateur.setPhoto(getFile().getContents());
utilisateurService.saveUtilisateur(utilisateur);
file=null;
}
catch(Exception ex){
ex.printStackTrace();
}
return "/jsf/utilisateur/listUtilisateurs.xhtml";
}
f = new byte[event.getFile().getContents().length];
System.arraycopy(event.getFile().getContents(),0,f,0,event.getFile().getContents().length);
FacesMessage message = new FacesMessage("Succesful", event.getFile().getFileName() + " is uploaded.");
FacesContext.getCurrentInstance().addMessage(null, message);
}
}
According to my stack trace,
Grave: Error in streaming dynamic resource. Error reading 'content' on type $Proxy16
juin 17, 2014 10:56:03 PM org.apache.catalina.core.StandardWrapperValve invoke
Grave: "Servlet.service()" pour la servlet Faces Servlet a généré une exception
java.io.IOException: javax.el.ELException: Error reading 'content' on type $Proxy16
at org.primefaces.application.PrimeResourceHandler.handleResourceRequest(PrimeResourceHandler.java:122)
at javax.faces.webapp.FacesServlet.service(FacesServlet.java:306)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.primefaces.webapp.filter.FileUploadFilter.doFilter(FileUploadFilter.java:98)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
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 org.springframework.orm.jpa.support.OpenEntityManagerInViewFilter.doFilterInternal(OpenEntityManagerInViewFilter.java:113)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:76)
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:220)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:122)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:501)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:170)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:98)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:950)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1040)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:607)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:315)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
Caused by: javax.el.ELException: Error reading 'content' on type $Proxy16
at javax.el.BeanELResolver.getValue(BeanELResolver.java:110)
at javax.el.CompositeELResolver.getValue(CompositeELResolver.java:67)
at com.sun.faces.el.FacesCompositeELResolver.getValue(FacesCompositeELResolver.java:71)
at com.sun.el.parser.AstValue.getValue(AstValue.java:116)
at com.sun.el.parser.AstValue.getValue(AstValue.java:163)
at com.sun.el.ValueExpressionImpl.getValue(ValueExpressionImpl.java:219)
at org.primefaces.application.PrimeResourceHandler.handleResourceRequest(PrimeResourceHandler.java:85)
... 27 more
Caused by: java.lang.NullPointerException
at java.io.ByteArrayInputStream.<init>(Unknown Source)
at com.gestion.projet.web.jsf.UtilisateurComponentImpl.getContent(UtilisateurComponentImpl.java:119)
at sun.reflect.GeneratedMethodAccessor38.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
the line (UtilisateurComponentImpl.java:119) is commented on the managedbean Method
StreamedContent getMyContent()
return new DefaultStreamedContent(new ByteArrayInputStream(u.getPhoto()));
In the line above u is null, The problem is that you don't bring him back from DataBase or you imageId is not receivied in the bean.
You can do this
<p:graphicImage value="#{UtilisateurComponent.getContent(current.iduser)}" height="100" width="150"/>
And in the function of yours just get your user id
public StreamedContent getContent(Integer userId){...}
Hope this will help
The problem is with the param passed, you have a dataTable with multiple rows then you send params with the same id.

Error java.lang.InstantiationException

I'm trying to create a project with glassfish JSF and JPA, but I'm having trouble with the persistence unit in the persistence.xml file.
The error is the following:
GlassFish 3.1 at localhost
2014-05-06T12:47:52.326-0300|INFO: Initializing Mojarra 2.1.6
(SNAPSHOT 20111206) for context '/K19-Integracao-JSF-JPA'
2014-05-06T12:47:52.649-0300|SEVERE:
WebModule[/K19-Integracao-JSF-JPA]PWC1270: Exception starting filter
br.com.k19.filters.JPAFilter java.lang.InstantiationException at
org.apache.catalina.core.ApplicationFilterConfig.(ApplicationFilterConfig.java:124)
at
org.apache.catalina.core.StandardContext.filterStart(StandardContext.java:4685)
at
org.apache.catalina.core.StandardContext.start(StandardContext.java:5377)
at com.sun.enterprise.web.WebModule.start(WebModule.java:498) at
org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:917)
at
org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:901)
at
org.apache.catalina.core.StandardHost.addChild(StandardHost.java:733)
at
com.sun.enterprise.web.WebContainer.loadWebModule(WebContainer.java:2018)
at
com.sun.enterprise.web.WebContainer.loadWebModule(WebContainer.java:1669)
at
com.sun.enterprise.web.WebApplication.start(WebApplication.java:109)
at org.glassfish.internal.data.EngineRef.start(EngineRef.java:130)
at org.glassfish.internal.data.ModuleInfo.start(ModuleInfo.java:269)
at
org.glassfish.internal.data.ApplicationInfo.start(ApplicationInfo.java:301)
at
com.sun.enterprise.v3.server.ApplicationLifecycle.deploy(ApplicationLifecycle.java:461)
at
com.sun.enterprise.v3.server.ApplicationLifecycle.deploy(ApplicationLifecycle.java:240)
at
org.glassfish.deployment.admin.DeployCommand.execute(DeployCommand.java:389)
at
com.sun.enterprise.v3.admin.CommandRunnerImpl$1.execute(CommandRunnerImpl.java:348)
at
com.sun.enterprise.v3.admin.CommandRunnerImpl.doCommand(CommandRunnerImpl.java:363)
at
com.sun.enterprise.v3.admin.CommandRunnerImpl.doCommand(CommandRunnerImpl.java:1085)
at
com.sun.enterprise.v3.admin.CommandRunnerImpl.access$1200(CommandRunnerImpl.java:95)
at
com.sun.enterprise.v3.admin.CommandRunnerImpl$ExecutionContext.execute(CommandRunnerImpl.java:1291)
at
com.sun.enterprise.v3.admin.CommandRunnerImpl$ExecutionContext.execute(CommandRunnerImpl.java:1259)
at
com.sun.enterprise.v3.admin.AdminAdapter.doCommand(AdminAdapter.java:461)
at
com.sun.enterprise.v3.admin.AdminAdapter.service(AdminAdapter.java:212)
at
com.sun.grizzly.tcp.http11.GrizzlyAdapter.service(GrizzlyAdapter.java:179)
at
com.sun.enterprise.v3.server.HK2Dispatcher.dispath(HK2Dispatcher.java:117)
at
com.sun.enterprise.v3.services.impl.ContainerMapper$Hk2DispatcherCallable.call(ContainerMapper.java:354)
at
com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:195)
at
com.sun.grizzly.http.ProcessorTask.invokeAdapter(ProcessorTask.java:849)
at
com.sun.grizzly.http.ProcessorTask.doProcess(ProcessorTask.java:746)
at
com.sun.grizzly.http.ProcessorTask.process(ProcessorTask.java:1045)
at
com.sun.grizzly.http.DefaultProtocolFilter.execute(DefaultProtocolFilter.java:228)
at
com.sun.grizzly.DefaultProtocolChain.executeProtocolFilter(DefaultProtocolChain.java:137)
at
com.sun.grizzly.DefaultProtocolChain.execute(DefaultProtocolChain.java:104)
at
com.sun.grizzly.DefaultProtocolChain.execute(DefaultProtocolChain.java:90)
at
com.sun.grizzly.http.HttpProtocolChain.execute(HttpProtocolChain.java:79)
at
com.sun.grizzly.ProtocolChainContextTask.doCall(ProtocolChainContextTask.java:54)
at
com.sun.grizzly.SelectionKeyContextTask.call(SelectionKeyContextTask.java:59)
at com.sun.grizzly.ContextTask.run(ContextTask.java:71) at
com.sun.grizzly.util.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:532)
at
com.sun.grizzly.util.AbstractThreadPool$Worker.run(AbstractThreadPool.java:513)
at java.lang.Thread.run(Thread.java:744) Caused by:
javax.persistence.PersistenceException: No Persistence provider for
EntityManager named k19pu at
javax.persistence.Persistence.createEntityManagerFactory(Unknown
Source) at
javax.persistence.Persistence.createEntityManagerFactory(Unknown
Source) at br.com.k19.filters.JPAFilter.init(JPAFilter.java:57) at
org.apache.catalina.core.ApplicationFilterConfig.getFilter(ApplicationFilterConfig.java:264)
at
org.apache.catalina.core.ApplicationFilterConfig.(ApplicationFilterConfig.java:120)
... 41 more
2014-05-06T12:47:52.662-0300|INFO: WEB0671: Loading application
[K19-Integracao-JSF-JPA] at [/K19-Integracao-JSF-JPA]
2014-05-06T12:47:52.693-0300|INFO: K19-Integracao-JSF-JPA was
successfully deployed in 774 milliseconds.
2014-05-06T12:47:53.049-0300|SEVERE: Error Rendering
View[/carros.xhtml] javax.el.ELException: /carros.xhtml #24,58
rendered="#{not empty carroBean.carros}":
java.lang.NullPointerException at
com.sun.faces.facelets.el.TagValueExpression.getValue(TagValueExpression.java:114)
at
javax.faces.component.ComponentStateHelper.eval(ComponentStateHelper.java:194)
at
javax.faces.component.UIComponentBase.isRendered(UIComponentBase.java:413)
at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1751)
at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1760)
at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1760)
at
com.sun.faces.application.view.FaceletViewHandlingStrategy.renderView(FaceletViewHandlingStrategy.java:402)
at
com.sun.faces.application.view.MultiViewHandler.renderView(MultiViewHandler.java:131)
at
com.sun.faces.lifecycle.RenderResponsePhase.execute(RenderResponsePhase.java:121)
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) at
org.apache.catalina.core.StandardWrapper.service(StandardWrapper.java:1542)
at
org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:281)
at
org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:175)
at
org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:655)
at
org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:595)
at
org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:161)
at
org.apache.catalina.connector.CoyoteAdapter.doService(CoyoteAdapter.java:331)
at
org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:231)
at
com.sun.enterprise.v3.services.impl.ContainerMapper$AdapterCallable.call(ContainerMapper.java:317)
at
com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:195)
at
com.sun.grizzly.http.ProcessorTask.invokeAdapter(ProcessorTask.java:849)
at
com.sun.grizzly.http.ProcessorTask.doProcess(ProcessorTask.java:746)
at
com.sun.grizzly.http.ProcessorTask.process(ProcessorTask.java:1045)
at
com.sun.grizzly.http.DefaultProtocolFilter.execute(DefaultProtocolFilter.java:228)
at
com.sun.grizzly.DefaultProtocolChain.executeProtocolFilter(DefaultProtocolChain.java:137)
at
com.sun.grizzly.DefaultProtocolChain.execute(DefaultProtocolChain.java:104)
at
com.sun.grizzly.DefaultProtocolChain.execute(DefaultProtocolChain.java:90)
at
com.sun.grizzly.http.HttpProtocolChain.execute(HttpProtocolChain.java:79)
at
com.sun.grizzly.ProtocolChainContextTask.doCall(ProtocolChainContextTask.java:54)
at
com.sun.grizzly.SelectionKeyContextTask.call(SelectionKeyContextTask.java:59)
at com.sun.grizzly.ContextTask.run(ContextTask.java:71) at
com.sun.grizzly.util.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:532)
at
com.sun.grizzly.util.AbstractThreadPool$Worker.run(AbstractThreadPool.java:513)
at java.lang.Thread.run(Thread.java:744) Caused by:
java.lang.NullPointerException at
br.com.k19.modelo.CarroRepository.buscaTodos(CarroRepository.java:21)
at br.com.k19.controle.CarroBean.getCarros(CarroBean.java:30) 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.BeanELResolver.getValue(BeanELResolver.java:363) at
com.sun.faces.el.DemuxCompositeELResolver._getValue(DemuxCompositeELResolver.java:176)
at
com.sun.faces.el.DemuxCompositeELResolver.getValue(DemuxCompositeELResolver.java:203)
at com.sun.el.parser.AstValue.getValue(AstValue.java:138) at
com.sun.el.parser.AstValue.getValue(AstValue.java:183) at
com.sun.el.parser.AstEmpty.getValue(AstEmpty.java:66) at
com.sun.el.parser.AstNot.getValue(AstNot.java:63) at
com.sun.el.ValueExpressionImpl.getValue(ValueExpressionImpl.java:224)
at
com.sun.faces.facelets.el.TagValueExpression.getValue(TagValueExpression.java:109)
... 35 more
2014-05-06T12:47:53.053-0300|WARNING: StandardWrapperValve[Faces
Servlet]: PWC1406: Servlet.service() for servlet Faces Servlet threw
exception java.lang.NullPointerException at
br.com.k19.modelo.CarroRepository.buscaTodos(CarroRepository.java:21)
at br.com.k19.controle.CarroBean.getCarros(CarroBean.java:30) 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.BeanELResolver.getValue(BeanELResolver.java:363) at
com.sun.faces.el.DemuxCompositeELResolver._getValue(DemuxCompositeELResolver.java:176)
at
com.sun.faces.el.DemuxCompositeELResolver.getValue(DemuxCompositeELResolver.java:203)
at com.sun.el.parser.AstValue.getValue(AstValue.java:138) at
com.sun.el.parser.AstValue.getValue(AstValue.java:183) at
com.sun.el.parser.AstEmpty.getValue(AstEmpty.java:66) at
com.sun.el.parser.AstNot.getValue(AstNot.java:63) at
com.sun.el.ValueExpressionImpl.getValue(ValueExpressionImpl.java:224)
at
com.sun.faces.facelets.el.TagValueExpression.getValue(TagValueExpression.java:109)
at
javax.faces.component.ComponentStateHelper.eval(ComponentStateHelper.java:194)
at
javax.faces.component.UIComponentBase.isRendered(UIComponentBase.java:413)
at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1751)
at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1760)
at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1760)
at
com.sun.faces.application.view.FaceletViewHandlingStrategy.renderView(FaceletViewHandlingStrategy.java:402)
at
com.sun.faces.application.view.MultiViewHandler.renderView(MultiViewHandler.java:131)
at
com.sun.faces.lifecycle.RenderResponsePhase.execute(RenderResponsePhase.java:121)
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) at
org.apache.catalina.core.StandardWrapper.service(StandardWrapper.java:1542)
at
org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:281)
at
org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:175)
at
org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:655)
at
org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:595)
at
org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:161)
at
org.apache.catalina.connector.CoyoteAdapter.doService(CoyoteAdapter.java:331)
at
org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:231)
at
com.sun.enterprise.v3.services.impl.ContainerMapper$AdapterCallable.call(ContainerMapper.java:317)
at
com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:195)
at
com.sun.grizzly.http.ProcessorTask.invokeAdapter(ProcessorTask.java:849)
at
com.sun.grizzly.http.ProcessorTask.doProcess(ProcessorTask.java:746)
at
com.sun.grizzly.http.ProcessorTask.process(ProcessorTask.java:1045)
at
com.sun.grizzly.http.DefaultProtocolFilter.execute(DefaultProtocolFilter.java:228)
at
com.sun.grizzly.DefaultProtocolChain.executeProtocolFilter(DefaultProtocolChain.java:137)
at
com.sun.grizzly.DefaultProtocolChain.execute(DefaultProtocolChain.java:104)
at
com.sun.grizzly.DefaultProtocolChain.execute(DefaultProtocolChain.java:90)
at
com.sun.grizzly.http.HttpProtocolChain.execute(HttpProtocolChain.java:79)
at
com.sun.grizzly.ProtocolChainContextTask.doCall(ProtocolChainContextTask.java:54)
at
com.sun.grizzly.SelectionKeyContextTask.call(SelectionKeyContextTask.java:59)
at com.sun.grizzly.ContextTask.run(ContextTask.java:71) at
com.sun.grizzly.util.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:532)
at
com.sun.grizzly.util.AbstractThreadPool$Worker.run(AbstractThreadPool.java:513)
at java.lang.Thread.run(Thread.java:744)
And the classes I am using are as follows:
package br.com.k19.modelo;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.Query;
public class CarroRepository {
private EntityManager manager;
public CarroRepository(EntityManager manager) {
this.manager = manager;
}
public void adiciona(Carro carro) {
this.manager.persist(carro);
}
public List<Carro> buscaTodos() {
Query query = this.manager.createQuery("select x from Carro x");
return query.getResultList();
}
}
package br.com.k19.modelo;
import java.io.Serializable;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
#Entity
public class Carro implements Serializable {
/**
*
*/
private static final long serialVersionUID = 4209908627808946183L;
#Id #GeneratedValue
private Long id;
private String marca;
private String modelo;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getMarca() {
return marca;
}
public void setMarca(String marca) {
this.marca = marca;
}
public String getModelo() {
return modelo;
}
public void setModelo(String modelo) {
this.modelo = modelo;
}
public static long getSerialversionuid() {
return serialVersionUID;
}
}
package br.com.k19.filters;
import java.io.IOException;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
#WebFilter(servletNames={"Faces Servlet"})
public class JPAFilter implements Filter {
private EntityManagerFactory factory;
#Override
public void destroy() {
this.factory.close();
}
#Override
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
// Chegada
EntityManager manager = factory.createEntityManager();
request.setAttribute("EntityManager", manager);
manager.getTransaction().begin();
// Chegada
// Faces Servelet
chain.doFilter(request, response);
// Faces Servelet
// Saída
try {
manager.getTransaction().commit();
} catch(Exception e) {
manager.getTransaction().rollback();
} finally {
manager.close();
}
// Saída
}
#Override
public void init(FilterConfig filterConfig) throws ServletException {
this.factory = Persistence.createEntityManagerFactory("K19-PU");
}
}
package br.com.k19.controle;
import java.util.List;
import javax.faces.bean.ManagedBean;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import javax.persistence.EntityManager;
import javax.servlet.http.HttpServletRequest;
import br.com.k19.modelo.Carro;
import br.com.k19.modelo.CarroRepository;
#ManagedBean
public class CarroBean {
private Carro carro = new Carro();
public void adicionaCarro() {
EntityManager manager = this.getEntityManager();
CarroRepository repository = new CarroRepository(manager);
repository.adiciona(carro);
carro = new Carro();
}
public List<Carro> getCarros() {
EntityManager manager = this.getEntityManager();
CarroRepository repository = new CarroRepository(manager);
return repository.buscaTodos();
}
private EntityManager getEntityManager() {
FacesContext fc = FacesContext.getCurrentInstance();
ExternalContext ec = fc.getExternalContext();
HttpServletRequest request = (HttpServletRequest) ec.getRequest();
EntityManager manager = (EntityManager) request.getAttribute("EntityManager");
return manager;
}
public Carro getCarro() {
return carro;
}
public void setCarro(Carro carro) {
this.carro = carro;
}
}
And the file carro.xhtml
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:ui="http://java.sun.com/jsf/facelets">
<h:head>
<title>K19 treinamentos</title>
</h:head>
<h:body>
<h:form>
<h:panelGrid columns="2">
<h:outputLabel value="Marca: " for="campo-marca" />
<h:inputText value="#{carroBean.carro.marca}" id="campo-marca" />
<h:outputLabel value="Modelo: " for="campo-modelo" />
<h:inputText value="#{carroBean.carro.modelo}" id="campo-modelo" />
<h:commandButton action="#{carroBean.adicionaCarro}" value="Adicionar" />
</h:panelGrid>
</h:form>
<h:panelGroup rendered="#{not empty carroBean.carros}" >
<h1>Lista de Carros</h1>
<ul>
<ui:repeat value="#{carroBean.carros}" var="carro">
<li> <h:outputText value="#{carro.marca} #{carro.modelo}" /> </li>
</ui:repeat>
</ul>
</h:panelGroup>
</h:body>
</html>
My persistence.xml looks like this:
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.0"
xmlns="http://java.sun.com/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence
http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd">
<persistence-unit name="K19-PU" transaction-type="RESOURCE_LOCAL">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<properties>
<property name="hibernate.dialect" value="org.hibernate.dialect.MySQL5InnoDBDialect" />
<property name="hibernate.hbm2ddl.auto" value="create" />
<property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver" />
<property name="javax.persistence.jdbc.user" value="root" />
<property name="javax.persistence.jdbc.password" value="admin" />
<property name="javax.persistence.jdbc.url" value="jdbc:mysql://localhost:3306/K19DB"/>
</properties>
</persistence-unit>
</persistence>
My persistence.xml in this folder: ~/workspace/K19-Integracao-JSF-JPA/src/META-INF/persistence.xml
I put the mysql connector jar in the glassfish directory:
/opt/glassfish3/glassfish/lib/mysql-connector-java-5.1.30-bin.jar
I'm sorry for posting so much, is that I'm already crazy with this error.
I already searched a lot on the internet and can not resolve the problem, please can someone help me?
I think should always look at the root cause of exception. In your case
Caused by: javax.persistence.PersistenceException:
No Persistence provider for EntityManager named k19pu at javax.persistence.Persistence.createEntityManagerFactory
Your persistence.xml is not valid that's why EntityManagerFactory can't be get created.
due this you are also getting NLP at CarroRepository#buscaTodos method
Caused by: java.lang.NullPointerException at br.com.k19.modelo.CarroRepository.buscaTodos
So Please correct your Persistence.xml and make sure same PU. hope this will solve your problem
Here's the problem:
2014-05-06T12:47:53.049-0300|SEVERE: Error Rendering View[/carros.xhtml] javax.el.ELException: /carros.xhtml #24,58 rendered="#{not empty carroBean.carros}": java.lang.NullPointerException
...
Caused by: java.lang.NullPointerException at br.com.k19.modelo.CarroRepository.buscaTodos(CarroRepository.java:21) at br.com.k19.controle.CarroBean.getCarros(CarroBean.java:30)
Looking until CarroRepository#buscaTodos, line 21 of CarroRepository.java: file, we get this line:
Query query = this.manager.createQuery("select x from Carro x");
The NullPointerException means that EntityManager manager is null.
You have to check why the EntityManagerFactory cannot create a new instance of EntityManager in your JPAFilter servlet filter.

JSF 1.2: java.util.ConcurrentModificationException

I have a DataTable with a <h:column> as <h:selectBooleanCheckbox>. Both the facet header and the DataTable rows content for that <h:column> are <h:selectBooleanCheckbox>. Below is the code I used:
<h:form>
<h:dataTable
value="#{employeeService.employeeList }"
var="empl"
binding="#{employeeService.dataTablebinding }">
......
......
......
<h:column>
<f:facet name="header">
<h:selectBooleanCheckbox id="chkBoxAll" value="#{empl.checked }" valueChangeListener="#{employeeService.checkAll }" onclick="submit()"></h:selectBooleanCheckbox>
</f:facet>
<h:selectBooleanCheckbox id="tableChkBox" value="#{empl.checked }" valueChangeListener="#{employeeService.getCheckChanged }" onclick="submit()"></h:selectBooleanCheckbox>
</h:column>
</h:dataTable>
</h:form>
When I click the facet header checkbox, I want all the rows checkbox to be checked and the same for unchecked also. This is the code I have for the ValueChangeListener of that facet header checkbox:
public void checkAll(ValueChangeEvent event){
for(Employee empl : employeeList){
employeeList.remove(empl);
empl.setChecked(true);
employeeList.add(empl);
}
}
I am getting the below excception:
SEVERE: AbortProcessingException thrown when processing event of type 'javax.faces.component.WrapperEvent' during phase 'PROCESS_VALIDATIONS 3' for component with ID or Client ID of 'j_id7'
27 Apr, 2013 8:20:38 PM javax.faces.component.UIViewRoot broadcastEvents
SEVERE: javax.faces.event.AbortProcessingException: java.util.ConcurrentModificationException
javax.faces.event.AbortProcessingException: java.util.ConcurrentModificationException
at javax.faces.event.MethodExpressionValueChangeListener.processValueChange(MethodExpressionValueChangeListener.java:93)
at javax.faces.event.ValueChangeEvent.processListener(ValueChangeEvent.java:134)
at javax.faces.component.UIComponentBase.broadcast(UIComponentBase.java:771)
at javax.faces.component.UIData.broadcast(UIData.java:943)
at javax.faces.component.UIViewRoot.broadcastEvents(UIViewRoot.java:444)
at javax.faces.component.UIViewRoot.processValidators(UIViewRoot.java:701)
at com.sun.faces.lifecycle.ProcessValidationsPhase.execute(ProcessValidationsPhase.java:76)
at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:100)
at com.sun.faces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:118)
at com.icesoft.faces.webapp.http.core.JsfLifecycleExecutor.apply(JsfLifecycleExecutor.java:18)
at com.icesoft.faces.webapp.http.core.ReceiveSendUpdates.renderCycle(ReceiveSendUpdates.java:132)
at com.icesoft.faces.webapp.http.core.ReceiveSendUpdates.service(ReceiveSendUpdates.java:74)
at com.icesoft.faces.webapp.http.core.RequestVerifier.service(RequestVerifier.java:31)
at com.icesoft.faces.webapp.http.common.standard.PathDispatcherServer.service(PathDispatcherServer.java:24)
at com.icesoft.faces.webapp.http.servlet.BasicAdaptingServlet.service(BasicAdaptingServlet.java:16)
at com.icesoft.faces.webapp.http.servlet.PathDispatcher.service(PathDispatcher.java:23)
at com.icesoft.faces.webapp.http.servlet.SessionDispatcher.service(SessionDispatcher.java:53)
at com.icesoft.faces.webapp.http.servlet.SessionVerifier.service(SessionVerifier.java:26)
at com.icesoft.faces.webapp.http.servlet.PathDispatcher.service(PathDispatcher.java:23)
at com.icesoft.faces.webapp.http.servlet.MainServlet.service(MainServlet.java:131)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
at com.icesoft.faces.webapp.xmlhttp.BlockingServlet.service(BlockingServlet.java:56)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:233)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:127)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:291)
at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:859)
at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:602)
at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:489)
at java.lang.Thread.run(Thread.java:662)
Caused by: java.util.ConcurrentModificationException
at java.util.AbstractList$Itr.checkForComodification(AbstractList.java:372)
at java.util.AbstractList$Itr.next(AbstractList.java:343)
at com.infy.service.DataTableService.checkAll(DataTableService.java:66)
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 org.apache.el.parser.AstValue.invoke(AstValue.java:191)
at org.apache.el.MethodExpressionImpl.invoke(MethodExpressionImpl.java:276)
at javax.faces.event.MethodExpressionValueChangeListener.processValueChange(MethodExpressionValueChangeListener.java:91)
... 33 more
Please let me know the reason for this ConcurrentModificationException.
for(Employee empl : employeeList){
empl.setChecked(true);
}
As Luigi stated, you don't need to remove the employee from the list.
It is because while looping over the list you are modifying it:
for(Employee empl : employeeList){
employeeList.remove(empl);
empl.setChecked(true);
employeeList.add(empl);
}
You need to use iterator.
for(Employee empl : employeeList){
// employeeList.remove(empl); //Not required
empl.setChecked(true);
//employeeList.add(empl); //Not required
}
Update As mentioned by Luiggi Mendoza, you don't need to remove and add the element back to the list to alter it. Just take the reference and modify it.
It's not a problem about jsf 1.2. The problem here is that you can't modify a Collection while you are iterating over it.
I think you get the same behaviour doing this:
public void checkAll(ValueChangeEvent event){
for(Employee empl : employeeList){
empl.setChecked(true);
}
}

MethodNotFoundException in command button action

I'm having a problem here, when i've started work with JSF and JPA. I can't make a jsf "request" using a commandButton to a method in my EJB. Let me show the code:
//.xhtml page
<?xml version='1.0' encoding='UTF-8' ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://java.sun.com/jsf/html">
<h:head>
<title>Facelet Title</title>
</h:head>
<h:body>
<h1 align="center">Bem vindo ao site do Restaurante Trabalho Final</h1>
<h:form>
Numero da mesa: <h:inputText id="numero" value="#{indexBean.mesa.numero}"></h:inputText>
<h:commandButton id="insertTable" value="OK" action="#{indexBean.insereMesa(mesa)}">
</h:commandButton>
</h:form>
</h:body>
</html>
Here is my EJB:
package negocio;
import java.util.List;
import javax.ejb.LocalBean;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.EntityTransaction;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import persistence.Mesa;
#Stateless
#LocalBean
public class MapaDeMesas {
#PersistenceContext
EntityManager em;
public MapaDeMesas(){
}
public void insereMesa(Mesa m){
EntityTransaction et = em.getTransaction();
et.begin();
em.persist(m);
et.commit();
}
public List<Mesa> listarMesasDisponiveis() {
EntityTransaction et = em.getTransaction();
et.begin();
Query selectAll = em.createQuery("SELECT m FROM Mesa m");
List<Mesa> rs = selectAll.getResultList();
et.commit();
return rs;
}
}
This is the stack:
javax.faces.el.MethodNotFoundException: javax.el.MethodNotFoundException: /HomePage.xhtml #14,97 action="#{indexBean.insereMesa(mesa)}": Method insereMesa not found
at javax.faces.component.MethodBindingMethodExpressionAdapter.invoke(MethodBindingMethodExpressionAdapter.java:92)
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:794)
at javax.faces.component.UIViewRoot.processApplication(UIViewRoot.java:1259)
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:118)
at javax.faces.webapp.FacesServlet.service(FacesServlet.java:593)
at org.apache.catalina.core.StandardWrapper.service(StandardWrapper.java:1550)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:281)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:175)
at org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:655)
at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:595)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:161)
at org.apache.catalina.connector.CoyoteAdapter.doService(CoyoteAdapter.java:331)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:231)
at com.sun.enterprise.v3.services.impl.ContainerMapper$AdapterCallable.call(ContainerMapper.java:317)
at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:195)
at com.sun.grizzly.http.ProcessorTask.invokeAdapter(ProcessorTask.java:860)
at com.sun.grizzly.http.ProcessorTask.doProcess(ProcessorTask.java:757)
at com.sun.grizzly.http.ProcessorTask.process(ProcessorTask.java:1056)
at com.sun.grizzly.http.DefaultProtocolFilter.execute(DefaultProtocolFilter.java:229)
at com.sun.grizzly.DefaultProtocolChain.executeProtocolFilter(DefaultProtocolChain.java:137)
at com.sun.grizzly.DefaultProtocolChain.execute(DefaultProtocolChain.java:104)
at com.sun.grizzly.DefaultProtocolChain.execute(DefaultProtocolChain.java:90)
at com.sun.grizzly.http.HttpProtocolChain.execute(HttpProtocolChain.java:79)
at com.sun.grizzly.ProtocolChainContextTask.doCall(ProtocolChainContextTask.java:54)
at com.sun.grizzly.SelectionKeyContextTask.call(SelectionKeyContextTask.java:59)
at com.sun.grizzly.ContextTask.run(ContextTask.java:71)
at com.sun.grizzly.util.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:532)
at com.sun.grizzly.util.AbstractThreadPool$Worker.run(AbstractThreadPool.java:513)
at java.lang.Thread.run(Thread.java:679)
Caused by: javax.el.MethodNotFoundException: /HomePage.xhtml #14,97 action="#{indexBean.insereMesa(mesa)}": Method insereMesa not found
at com.sun.faces.facelets.el.TagMethodExpression.invoke(TagMethodExpression.java:109)
at javax.faces.component.MethodBindingMethodExpressionAdapter.invoke(MethodBindingMethodExpressionAdapter.java:88)
... 32 more
I won't paste the persistence code, to keep the post clean, the problem is not in this tier.
Thanks in advance!
EDIT:
Sorry! I didn't paste the ManagedBean, here it is:
package model;
import javax.ejb.EJB;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
import negocio.MapaDeMesas;
import persistence.Mesa;
#ManagedBean
#RequestScoped
public class IndexBean {
#EJB
private MapaDeMesas mp;
private Mesa mesa;
public IndexBean() {
mesa = new Mesa();
}
public void insereMesa(){
mp.insereMesa(mesa);
}
public void setMesa(Mesa mesa) {
this.mesa = mesa;
}
public Mesa getMesa() {
return mesa;
}
}
But now i got another problem the new stacktrace is this one, i can't find the problem with my "getTransaction()" ideas?
javax.faces.el.EvaluationException: javax.ejb.EJBException
at javax.faces.component.MethodBindingMethodExpressionAdapter.invoke(MethodBindingMethodExpressionAdapter.java:102)
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:794)
at javax.faces.component.UIViewRoot.processApplication(UIViewRoot.java:1259)
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:118)
at javax.faces.webapp.FacesServlet.service(FacesServlet.java:593)
at org.apache.catalina.core.StandardWrapper.service(StandardWrapper.java:1550)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:281)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:175)
at org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:655)
at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:595)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:161)
at org.apache.catalina.connector.CoyoteAdapter.doService(CoyoteAdapter.java:331)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:231)
at com.sun.enterprise.v3.services.impl.ContainerMapper$AdapterCallable.call(ContainerMapper.java:317)
at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:195)
at com.sun.grizzly.http.ProcessorTask.invokeAdapter(ProcessorTask.java:860)
at com.sun.grizzly.http.ProcessorTask.doProcess(ProcessorTask.java:757)
at com.sun.grizzly.http.ProcessorTask.process(ProcessorTask.java:1056)
at com.sun.grizzly.http.DefaultProtocolFilter.execute(DefaultProtocolFilter.java:229)
at com.sun.grizzly.DefaultProtocolChain.executeProtocolFilter(DefaultProtocolChain.java:137)
at com.sun.grizzly.DefaultProtocolChain.execute(DefaultProtocolChain.java:104)
at com.sun.grizzly.DefaultProtocolChain.execute(DefaultProtocolChain.java:90)
at com.sun.grizzly.http.HttpProtocolChain.execute(HttpProtocolChain.java:79)
at com.sun.grizzly.ProtocolChainContextTask.doCall(ProtocolChainContextTask.java:54)
at com.sun.grizzly.SelectionKeyContextTask.call(SelectionKeyContextTask.java:59)
at com.sun.grizzly.ContextTask.run(ContextTask.java:71)
at com.sun.grizzly.util.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:532)
at com.sun.grizzly.util.AbstractThreadPool$Worker.run(AbstractThreadPool.java:513)
at java.lang.Thread.run(Thread.java:679)
Caused by: javax.ejb.EJBException
at com.sun.ejb.containers.BaseContainer.processSystemException(BaseContainer.java:5215)
at com.sun.ejb.containers.BaseContainer.completeNewTx(BaseContainer.java:5113)
at com.sun.ejb.containers.BaseContainer.postInvokeTx(BaseContainer.java:4901)
at com.sun.ejb.containers.BaseContainer.postInvoke(BaseContainer.java:2045)
at com.sun.ejb.containers.BaseContainer.postInvoke(BaseContainer.java:1994)
at com.sun.ejb.containers.EJBLocalObjectInvocationHandler.invoke(EJBLocalObjectInvocationHandler.java:222)
at com.sun.ejb.containers.EJBLocalObjectInvocationHandlerDelegate.invoke(EJBLocalObjectInvocationHandlerDelegate.java:89)
at $Proxy186.insereMesa(Unknown Source)
at negocio.__EJB31_Generated__MapaDeMesas__Intf____Bean__.insereMesa(Unknown Source)
at model.IndexBean.insereMesa(IndexBean.java:22)
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:616)
at javax.el.BeanELResolver.invokeMethod(BeanELResolver.java:779)
at javax.el.BeanELResolver.invoke(BeanELResolver.java:528)
at javax.el.CompositeELResolver.invoke(CompositeELResolver.java:257)
at com.sun.el.parser.AstValue.invoke(AstValue.java:248)
at com.sun.el.MethodExpressionImpl.invoke(MethodExpressionImpl.java:302)
at com.sun.faces.facelets.el.TagMethodExpression.invoke(TagMethodExpression.java:105)
at javax.faces.component.MethodBindingMethodExpressionAdapter.invoke(MethodBindingMethodExpressionAdapter.java:88)
... 32 more
Caused by: java.lang.IllegalStateException: A JTA EntityManager cannot use getTransaction()
at org.hibernate.ejb.AbstractEntityManagerImpl.getTransaction(AbstractEntityManagerImpl.java:324)
at com.sun.enterprise.container.common.impl.EntityManagerWrapper.getTransaction(EntityManagerWrapper.java:857)
at negocio.MapaDeMesas.insereMesa(MapaDeMesas.java:26)
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:616)
at org.glassfish.ejb.security.application.EJBSecurityManager.runMethod(EJBSecurityManager.java:1052)
at org.glassfish.ejb.security.application.EJBSecurityManager.invoke(EJBSecurityManager.java:1124)
at com.sun.ejb.containers.BaseContainer.invokeBeanMethod(BaseContainer.java:5388)
at com.sun.ejb.EjbInvocation.invokeBeanMethod(EjbInvocation.java:619)
at com.sun.ejb.containers.interceptors.AroundInvokeChainImpl.invokeNext(InterceptorManager.java:800)
at com.sun.ejb.EjbInvocation.proceed(EjbInvocation.java:571)
at com.sun.ejb.containers.interceptors.SystemInterceptorProxy.doAround(SystemInterceptorProxy.java:162)
at com.sun.ejb.containers.interceptors.SystemInterceptorProxy.aroundInvoke(SystemInterceptorProxy.java:144)
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:616)
at com.sun.ejb.containers.interceptors.AroundInvokeInterceptor.intercept(InterceptorManager.java:861)
at com.sun.ejb.containers.interceptors.AroundInvokeChainImpl.invokeNext(InterceptorManager.java:800)
at com.sun.ejb.containers.interceptors.InterceptorManager.intercept(InterceptorManager.java:370)
at com.sun.ejb.containers.BaseContainer.__intercept(BaseContainer.java:5360)
at com.sun.ejb.containers.BaseContainer.intercept(BaseContainer.java:5348)
at com.sun.ejb.containers.EJBLocalObjectInvocationHandler.invoke(EJBLocalObjectInvocationHandler.java:214)
Sorry the loooong post!
The first error can be solved by changing the method signature in the facelet.
Change
<h:commandButton id="insertTable" value="OK"
action="#{indexBean.insereMesa(mesa)}">
to
<h:commandButton id="insertTable" value="OK"
action="#{indexBean.insereMesa()}">
The reason of the second error is that methods of an EJB are automatically wrapped in a transaction, so you don't need to call getTransaction(), begin() and commit().
Change
public void insereMesa(Mesa m){
EntityTransaction et = em.getTransaction();
et.begin();
em.persist(m);
et.commit();
}
to
public void insereMesa(Mesa m){
em.persist(m);
}
The same applies to your other EJB method.
Edit: ok you've just updated your post with the bean. Regarding your Transaction error - you can't do bean managed transactions if you're using container managed transactions. You'll have to update your persistence.xml file to not use JTA, or just remove your transaction management code and let the container handle it for you.
You'll need to wrap your EJB inside a JSF (or CDI) managed bean - it seems like you're halfway there by using #{indexBean} but I assume you haven't defined it?
If you update your facelets page (remove the method argument).
<h:commandButton id="insertTable" value="OK" action="#{indexBean.insereMesa()}">
And define a request-scoped managed bean (this one's a JSF one, not CDI) which injects your EJB and defines a method which can be called from your facelets page...
package negocio;
import javax.ejb.EJB;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
import persistence.Mesa;
#ManagedBean
#RequestScoped
public class IndexBean {
#EJB
private MapaDeMesas mapaDeMesas;
private Mesa mesa;
public Mesa getMesa() {
return mesa;
}
public void setMesa(Mesa mesa) {
this.mesa = mesa;
}
/**
* Called by the command button.
* #return outcome
*/
public String insereMesa(){
mapaDeMesas.insereMesa(mesa);
return null; // navigates to same page (change if required)
}
}
Hope this helps.

Returning JSONP for a Suspended Atmosphere request

I have a servlet that has a suspending method and a broadcasting one:
#GET
#Path("/notification")
#Produces( { "application/x-javascript", MediaType.APPLICATION_JSON })
#Suspend
public JSONWithPadding getNextNotification(
#QueryParam("callback") #DefaultValue("callback") String callback) {
Random random = new Random();
Notification n = new Notification();
n.setMessage("Message is " + Long.toHexString(random.nextLong()));
n.setMessage("S-" + Long.toHexString(random.nextLong()));
return new JSONWithPadding(n, callback);
}
I invoke this from a browser and see the following nice output in my browser:
<!-- ---------------------------------------------------------------- http://github.com/Atmosphere ------------------------------------------------------------------------ -->
<!-- Welcome to the Atmosphere Framework.....
<!-- --------------------------------------------------------------------------------------------------------------------------------------------------------------------- -->
<!-- EOD -->callback({"message":"S-c897404ad5703dcc","sender":null}
So my object is nicely serialized to JSONP.
Now I call my broadcaster method:
#Context Broadcaster bc;
#Broadcast({JsonpFilter.class})
#GET
#Path("/broadcast5")
public Broadcastable broadcast5() {
Random random = new Random();
Notification n = new Notification();
n.setMessage("Message is " + Long.toHexString(random.nextLong()));
n.setMessage("S-" + Long.toHexString(random.nextLong()));
return new Broadcastable(new JSONWithPadding(n, "callback111"), bc);
}
On the server side I get the following exception and nothing is broadcasted:
[#|2012-01-19T17:28:30.483+0100|WARNING|glassfish3.1.1|javax.enterprise.system.container.web.com.sun.enterprise.web|_Thr
eadID=20;_ThreadName=http-thread-pool-8080(5);|StandardWrapperValve[AtmosphereServlet]: PWC1406: Servlet.service() for s
ervlet AtmosphereServlet threw exception
java.lang.RuntimeException: javax.servlet.ServletException: Throwable
at org.atmosphere.handler.ReflectorServletProcessor.onRequest(ReflectorServletProcessor.java:154)
at org.atmosphere.cpr.AsynchronousProcessor.action(AsynchronousProcessor.java:219)
at org.atmosphere.cpr.AsynchronousProcessor.suspended(AsynchronousProcessor.java:154)
at org.atmosphere.container.GrizzlyCometSupport.service(GrizzlyCometSupport.java:103)
at org.atmosphere.container.GlassFishWebSocketSupport.service(GlassFishWebSocketSupport.java:101)
at org.atmosphere.cpr.AtmosphereServlet.doCometSupport(AtmosphereServlet.java:1212)
at org.atmosphere.cpr.AtmosphereServlet.doPost(AtmosphereServlet.java:1171)
at org.atmosphere.cpr.AtmosphereServlet.doGet(AtmosphereServlet.java:1157)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:734)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:847)
at org.apache.catalina.core.StandardWrapper.service(StandardWrapper.java:1539)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:281)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:175)
at org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:655)
at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:595)
at com.sun.enterprise.web.WebPipeline.invoke(WebPipeline.java:98)
at com.sun.enterprise.web.PESessionLockingStandardPipeline.invoke(PESessionLockingStandardPipeline.java:91)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:162)
at org.apache.catalina.connector.CoyoteAdapter.doService(CoyoteAdapter.java:330)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:231)
at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:174)
at com.sun.grizzly.http.ProcessorTask.invokeAdapter(ProcessorTask.java:828)
at com.sun.grizzly.comet.CometEngine.executeServlet(CometEngine.java:444)
at com.sun.grizzly.comet.CometEngine.handle(CometEngine.java:308)
at com.sun.grizzly.comet.CometAsyncFilter.doFilter(CometAsyncFilter.java:87)
at com.sun.grizzly.arp.DefaultAsyncExecutor.invokeFilters(DefaultAsyncExecutor.java:171)
at com.sun.grizzly.arp.DefaultAsyncExecutor.interrupt(DefaultAsyncExecutor.java:143)
at com.sun.grizzly.arp.AsyncProcessorTask.doTask(AsyncProcessorTask.java:94)
at com.sun.grizzly.http.TaskBase.run(TaskBase.java:193)
at com.sun.grizzly.http.TaskBase.execute(TaskBase.java:175)
at com.sun.grizzly.arp.DefaultAsyncHandler.handle(DefaultAsyncHandler.java:145)
at com.sun.grizzly.arp.AsyncProtocolFilter.execute(AsyncProtocolFilter.java:204)
at com.sun.grizzly.DefaultProtocolChain.executeProtocolFilter(DefaultProtocolChain.java:137)
at com.sun.grizzly.DefaultProtocolChain.execute(DefaultProtocolChain.java:104)
at com.sun.grizzly.DefaultProtocolChain.execute(DefaultProtocolChain.java:90)
at com.sun.grizzly.http.HttpProtocolChain.execute(HttpProtocolChain.java:79)
at com.sun.grizzly.ProtocolChainContextTask.doCall(ProtocolChainContextTask.java:54)
at com.sun.grizzly.SelectionKeyContextTask.call(SelectionKeyContextTask.java:59)
at com.sun.grizzly.ContextTask.run(ContextTask.java:71)
at com.sun.grizzly.util.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:532)
at com.sun.grizzly.util.AbstractThreadPool$Worker.run(AbstractThreadPool.java:513)
at java.lang.Thread.run(Thread.java:662)
Caused by: javax.servlet.ServletException: Throwable
at org.atmosphere.util.AtmosphereFilterChain.doFilter(AtmosphereFilterChain.java:165)
at org.atmosphere.util.AtmosphereFilterChain.invokeFilterChain(AtmosphereFilterChain.java:116)
at org.atmosphere.handler.ReflectorServletProcessor$FilterChainServletWrapper.service(ReflectorServletProcessor.
java:293)
at org.atmosphere.handler.ReflectorServletProcessor.onRequest(ReflectorServletProcessor.java:151)
... 41 more
Caused by: java.lang.AbstractMethodError: org.atmosphere.commons.jersey.JsonpFilter.filter(Ljava/lang/Object;Ljava/lang/
Object;)Lorg/atmosphere/cpr/BroadcastFilter$BroadcastAction;
at org.atmosphere.cpr.BroadcasterConfig.filter(BroadcasterConfig.java:447)
at org.atmosphere.cpr.DefaultBroadcaster.filter(DefaultBroadcaster.java:890)
at org.atmosphere.cpr.DefaultBroadcaster.broadcast(DefaultBroadcaster.java:875)
at org.atmosphere.jersey.AtmosphereFilter$Filter.broadcast(AtmosphereFilter.java:632)
at org.atmosphere.jersey.AtmosphereFilter$Filter.filter(AtmosphereFilter.java:468)
at com.sun.jersey.server.impl.application.WebApplicationImpl._handleRequest(WebApplicationImpl.java:1416)
at com.sun.jersey.server.impl.application.WebApplicationImpl.handleRequest(WebApplicationImpl.java:1349)
at com.sun.jersey.server.impl.application.WebApplicationImpl.handleRequest(WebApplicationImpl.java:1339)
at com.sun.jersey.spi.container.servlet.WebComponent.service(WebComponent.java:416)
at com.sun.jersey.spi.container.servlet.ServletContainer.service(ServletContainer.java:537)
at com.sun.jersey.spi.container.servlet.ServletContainer.service(ServletContainer.java:699)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:847)
at org.atmosphere.util.AtmosphereFilterChain.doFilter(AtmosphereFilterChain.java:155)
... 44 more
|#]
How could I make my broadcaster work? Do I need to return JSONWithPadding object or only the POJO?
You get an AbstractMethodError. Do you have atmosphere-commons on your classpath?

Categories

Resources