Composite Component editableValueHolder inconsistency with Bean Validation - validation

I have the following composite component:
<!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:composite="http://java.sun.com/jsf/composite"
>
<composite:interface>
<composite:attribute name="value"/>
<composite:editableValueHolder name="value" targets="#{cc.clientId}:value"/>
</composite:interface>
<composite:implementation>
<h:inputText id="value" />
<h:message for="#{cc.clientId}:value"/>
</composite:implementation>
</html>
And the following managed bean
import java.util.Date;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import javax.validation.constraints.NotNull;
#ViewScoped
#ManagedBean
public class TestMB {
#NotNull
private Date value;
public String action1() {
System.out.println("The value is: " + value);
return null;
}
public Date getValue() {
return value;
}
public void setValue(Date value) {
this.value = value;
}
}
And the following custom converter:
import java.util.Date;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.FacesConverter;
#FacesConverter("myCustomConverter")
public class MyCustomConverter implements Converter {
#Override
public Object getAsObject(FacesContext arg0, UIComponent arg1, String value) {
if (value == null || "".equals(value)) {
return null;
}
return new Date();
}
#Override
public String getAsString(FacesContext arg0, UIComponent arg1, Object obj) {
if (obj == null) {
return null;
}
return obj.toString();
}
}
And the following test page:
<h:body>
<h:form>
Enter value:
<wui:test value="#{testMB.value}" id="myID">
<f:converter converterId="myCustomConverter" for="value"/>
</wui:test>
<h:commandLink action="#{testMB.action1}" value="submit"/>
</h:form>
</h:body>
When I run the web application and leave the text field empty and hit the submit button no validation errors are raised and I get the following on the Java console:
The value is: null
To make things more complicated, If I modify my composite component as follows (I added the value="#{cc.attrs.value}" to the h:inputText
<!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:composite="http://java.sun.com/jsf/composite"
>
<composite:interface>
<composite:attribute name="value"/>
<composite:editableValueHolder name="value" targets="#{cc.clientId}:value"/>
</composite:interface>
<composite:implementation>
<h:inputText id="value" value="#{cc.attrs.value}"/>
<h:message for="#{cc.clientId}:value"/>
</composite:implementation>
</html>
And try again to submit the form when NO value is set, I don't get any validation errors displayed on the page, but I get the following warning in the console:
INFO: WARNING: FacesMessage(s) have been enqueued, but may not have been displayed.
sourceId=myID:value[severity=(ERROR 2), summary=(may not be null), detail=(may not be null)]
Then if I try to re-submit the form again the action is submitted even if the field is empty. And I get the following in the console:
The value is: null
However if I remove the id="myID" everything is OK!
Finally: If I set prependId="false" on my form, everything is OK.
But I don't want to set prependId="false" and I do need to set an ID :(

Related

Primefaces chart doesn't appear

I am trying this example of primefaces piechart https://www.primefaces.org/showcase/ui/chart/pie.xhtml
But i got a blank page i tried many solution like adding but still not working .. Any help please !!
Bean :
package com.levelup;
import javax.annotation.PostConstruct;
import java.io.Serializable;
import javax.faces.bean.ManagedBean;
import org.primefaces.model.chart.PieChartModel;
#ManagedBean
public class ChartView implements Serializable {
private static final long serialVersionUID = 1L;
private PieChartModel pieModel1;
private PieChartModel pieModel2;
#PostConstruct
public void init() {
createPieModels();
}
public PieChartModel getPieModel1() {
return pieModel1;
}
public PieChartModel getPieModel2() {
return pieModel2;
}
private void createPieModels() {
createPieModel1();
createPieModel2();
}
private void createPieModel1() {
pieModel1 = new PieChartModel();
pieModel1.set("Brand 1", 540);
pieModel1.set("Brand 2", 325);
pieModel1.set("Brand 3", 702);
pieModel1.set("Brand 4", 421);
pieModel1.setTitle("Simple Pie");
pieModel1.setLegendPosition("w");
}
private void createPieModel2() {
pieModel2 = new PieChartModel();
pieModel2.set("Brand 1", 540);
pieModel2.set("Brand 2", 325);
pieModel2.set("Brand 3", 702);
pieModel2.set("Brand 4", 421);
pieModel2.setTitle("Custom Pie");
pieModel2.setLegendPosition("e");
pieModel2.setFill(false);
pieModel2.setShowDataLabels(true);
pieModel2.setDiameter(150);
}
}
xhtml :
<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:p="http://primefaces.org/ui">
<h:head>
</h:head>
<h:body>
<div>
<p:panel>
<p:chart type="pie" model="#{ChartView.pieModel1}" style="width:400px;height:300px" />
<p:chart type="pie" model="#{ChartView.pieModel2}" style="width:400px;height:300px" />
</p:panel>
</div>
</h:body>
<script> $.noConflict(); </script>
</html>
1) You can check if the models have data at the end of create methods.
2) You can try to put the chart component in a form element.

JSF Ajax call not updating dynamic list correctly in backing bean

I have the following problem. I have a list that consists of dynamically generated checkboxes. When I click once on one of those checkboxes, the value of the backing bean is ok for this call. When clicking on another checkbox, this one is fine, but the others fall back to false, even the checkmark is shown in the front-end. The same problem, when I click on a final submit button. All values in the backing bean become the state false.
Here is the JSF:
<?xml version="1.0"?>
<f:view
xmlns="http://www.w3.org/1999/xhtml"
xmlns:c="http://java.sun.com/jsp/jstl/core"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:ui="http://java.sun.com/jsf/facelets">
<h:head />
<h:body>
<h:form>
<h:messages/>
<h:dataTable value="#{registration.registrationlist}" var="entry">
<h:column>
<f:facet name="header">Name</f:facet>
#{entry.me.name}
</h:column>
<h:column>
<f:facet name="header">Status</f:facet>
<h:selectBooleanCheckbox value="#{entry.checked}">
</h:selectBooleanCheckbox>
</h:column>
</h:dataTable>
<h:commandButton value="Submit">
<f:ajax listener="#{registration.listener}" />
</h:commandButton>
</h:form>
</h:body>
</f:view>
This is my backing bean:
package de.rwd.mm.beans;
import java.util.ArrayList;
import java.util.List;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import javax.faces.event.AjaxBehaviorEvent;
#ManagedBean
#ViewScoped
public class Registration {
private List<RegistrationEntry> registrationlist;
public Registration() {
// Populating the registrationlist from database and initialize it with false
List<MarketingEvent> me_list;
me_list = MarketingEventLocalServiceUtil.getAllMarketingevents();
registrationlist = new ArrayList<RegistrationEntry>();
for (MarketingEvent me : me_list) {
RegistrationEntry re = new RegistrationEntry(me, false);
registrationlist.add(re);
}
}
public List<RegistrationEntry> getRegistrationlist() {
return registrationlist;
}
public void setRegistrationlist(List<RegistrationEntry> registrationlist) {
this.registrationlist = registrationlist;
}
public void listener(AjaxBehaviorEvent event) {
System.out.println("listener");
System.out.println("called by " + event.getComponent().getClass().getName());
for (RegistrationEntry entry : registrationlist) {
String me = entry.getMe().getName();
boolean value = entry.isChecked();
System.out.println(me + " " + value);
}
}
}
My RegistrationEntry class that holds the database values and the boolean for the checkbox.
package de.rwd.mm.beans;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import de.rwd.mm.services.model.MarketingEvent;
#ManagedBean
#ViewScoped
public class RegistrationEntry {
private MarketingEvent me;
private boolean checked;
public RegistrationEntry() {
}
public RegistrationEntry(MarketingEvent me, boolean checked) {
this.me = me;
this.checked = checked;
}
public MarketingEvent getMe() {
return me;
}
public void setMe(MarketingEvent me) {
this.me = me;
}
public boolean isChecked() {
return checked;
}
public void setChecked(boolean checked) {
this.checked = checked;
}
}
Is #ViewScoped the right scope? Or is there anything completly wrong?
The non-ajax version works, but this is no option for me. This "portlet" is placed in several pages with much content and a page refresh looks extremly ugly. This JSF runs as portlet in Liferay 6.2.
Thanks for any help and suggestions.
PS: My Liferay 6.2.0-ce-ga1 runs in Tomcat 7.0.42
Use the <f:ajax execute="#form"> setting just like this example code (it uses Lombok #Data annotation to avoid typing getter/setter methods):
The sample facet:
<?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://xmlns.jcp.org/jsf/html"
xmlns:f="http://xmlns.jcp.org/jsf/core">
<h:head>
<title>Facelet Title</title>
</h:head>
<h:body>
<h:form>
<h:dataTable value="#{myBean.records}" var="record">
<h:column>
<f:facet name="header">Name</f:facet>
#{record.name}
</h:column>
<h:column>
<f:facet name="header">Selected</f:facet>
<h:selectBooleanCheckbox value="#{record.checked}"/>
</h:column>
</h:dataTable>
<h:commandButton value="Submit">
<f:ajax listener="#{myBean.onSubmit}" execute="#form"/>
</h:commandButton>
</h:form>
</h:body>
</html>
The managed bean:
package x;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import javax.annotation.PostConstruct;
import javax.faces.event.AjaxBehaviorEvent;
import javax.inject.Named;
import javax.faces.view.ViewScoped;
import lombok.Data;
#Data
#Named( value = "myBean" )
#ViewScoped
public class MyBean implements Serializable
{
private List<MyRecord> records;
//#EJB
//private RecordDAO recordDAO;
#PostConstruct
public void init()
{
System.out.println( "MyBean.ini() called");
records = new ArrayList<>();
records.add( new MyRecord( "Name 1", false ) );
records.add( new MyRecord( "Name 2", false ) );
records.add( new MyRecord( "Name 3", false ) );
records.add( new MyRecord( "Name 4", false ) );
records.add( new MyRecord( "Name 5", false ) );
}
public void onSubmit( AjaxBehaviorEvent abe_ )
{
System.out.println( "MyBeam.onSubmit() called! Values : " + getRecordValues() );
// You should take care about persisting data here
//recordDAO.persistRecords( records );
}
protected String getRecordValues()
{
String s = "";
for ( MyRecord mr : records)
s += "( name=" + mr.getName() + ", checked= " + mr.isChecked() + " ); ";
return s;
}
public MyBean()
{
}
}
The test DB record:
package x;
import java.io.Serializable;
import lombok.Data;
#Data
public class MyRecord implements Serializable
{
private String name;
private boolean checked;
public MyRecord( String name_, boolean checked_ )
{
name = name_;
checked = checked_;
}
}

OrderList <p:ajax> Unable to attach behavior to non-ClientBehaviorHolder parent

I got stuck with a problem which seems to have been solved here.
I want to use order list as it's in an example here.
But it doesn't work at all. I have nested <p:ajax> in order list like in an example.
Namely, I have got an error:
javax.servlet.ServletException: /resources/abc/rankingAnswer.xhtml #21,85<p:ajax> Unable to attach behavior to non-ClientBehaviorHolder parent
My Primefaces config in pom.xml is
<!-- prime faces -->
<primefaces.version>5.1</primefaces.version>
<primefaces.themes.version>1.0.10</primefaces.themes.version>
My view is
<?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:composite="http://java.sun.com/jsf/composite"
xmlns:p="http://primefaces.org/ui"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:h="http://java.sun.com/jsf/html">
<composite:interface>
<composite:attribute name="question" />
</composite:interface>
<composite:implementation>
<ui:decorate template="answerDecorator.xhtml">
<ui:define name="component">
<p:orderList value="#{cc.attrs.question.possibleAnswers}" var="answer" itemLabel="#{answer.text}" itemValue="#{answer}" controlsLocation="left" editable="true" >
<f:facet name="caption">#{msg['survey.default.makeOrder']}</f:facet>
<p:ajax event="reorder" listener="#{cc.attrs.question.onReorder}" />
<p:column>
<h:outputText value="#{answer.text}" />
</p:column>
</p:orderList>
</ui:define>
</ui:decorate>
</composite:implementation>
</html>
My model is
public class RankingQuestionDTO extends AbstractQuestionDTO implements Serializable {
private ArrayList<RankingAnswerDTO> possibleAnswers;
private boolean randomizeAnswers;
private String text;
public RankingQuestionDTO() {
super(QuestionType.RANKING);
this.text = MessageUtils.getBundle("survey.default.text");
this.possibleAnswers = new ArrayList<>();
this.possibleAnswers.add(new RankingAnswerDTO(MessageUtils.getBundle("survey.default.text")));
this.possibleAnswers.add(new RankingAnswerDTO(MessageUtils.getBundle("survey.default.text")));
this.randomizeAnswers = true;
}
public void onSelect(SelectEvent event) {
System.out.print(event.getObject().toString());
}
public void onUnselect(UnselectEvent event) {
System.out.print(event.getObject().toString());
}
public void onReorder() {
}
public void addEmptyPossibleAnswer()
{
this.possibleAnswers.add(new RankingAnswerDTO(MessageUtils.getBundle("survey.default.text")));
}
public ArrayList<RankingAnswerDTO> getPossibleAnswers() {
return possibleAnswers;
}
public String getText() {
return text;
}
public void setPossibleAnswers(ArrayList<RankingAnswerDTO> possibleAnswers) {
this.possibleAnswers = possibleAnswers;
}
public void setRandomizeAnswers(boolean randomizeAnswers) {
this.randomizeAnswers = randomizeAnswers;
}
public boolean getRandomizeAnswers() {
return randomizeAnswers;
}
public void setText(String text) {
this.text = text;
}
}
The PrimeFaces Showcase has the answer (emphasis mine):
Pojo Support with Clip Effect, Captions, Custom Content, Reorder Controls and Events (since v5.1.5)
As does issue 4501 (emphasis mine):
Added
select
unselect
reorder
Target is 5.1.5 Elite and 5.2 Community.

polling using f:ajax:: Hi Have been using setInterval and f:ajax to poll below is the code kindly advise what is wrong here:

Have used setInterval to call ajax method which will render the value on page or probably keep updating the page. But in debug the control does not comes to ajax method in bean. please advise the issue in below code
<?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:f="http://java.sun.com/jsf/core"
xmlns:h="http://java.sun.com/jsf/html">
<h:body>
<script>
setInterval(function() {
document.getElementById("changeme").click();
}, 3000);
</script>
<h3>JSF 2.0 + Ajax Hello World Example</h3>
<h:form>
<h:inputText id="name" value="#{helloBean.name}"></h:inputText>
<h:commandButton value="Welcome Me">
<f:ajax execute="name" render="output" />
</h:commandButton>
<h2><h:outputText id="output" value="#{helloBean.sayWelcome}" /></h2>
<h2><h:outputText id="countsee" value="#{helloBean.name}" /></h2>
<h:commandButton id="changeme" style="display:none">
<f:ajax execute="#this" listener="#{helloBean.updates}" render="countsee" ></f:ajax>
</h:commandButton>
</h:form>
</h:body>
</html>
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.event.AjaxBehaviorEvent;
import java.io.Serializable;
#ManagedBean
#SessionScoped
public class HelloBean implements Serializable {
private static final long serialVersionUID = 1L;
private String name;
private static int count;
public int getCount() {
return count;
}
public void setCount(int count) {
this.count = count;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSayWelcome(){
//check if null?
if("".equals(name) || name ==null){
return "";
}else{
return "Ajax message : Welcome " + name;
}
}
public void getUpdates(ActionBehaviorEvent event){
System.out.println("Printing"+count);
this.name=name+"agdam";
}
}
Try giving the below:
public void updates(ActionBehaviorEvent event)
The method name and name given in the listener should be same.

How to get data from the database?

I am having problem with getting data from the database (JavaDB).
Exactly, I think the error is in the UserBean class in the method GetAllUsersFromTable.
It is maybe bc I get entities incorrectly from the database. I have tried to write method
GetAllUsersFromTable in few different ways but it doesn't work well.
My project works well until I don't try to get the data from the database. index page is displayed correctly, usersForm also display correctly and when I click submit button it display error. On the page were the error is displayed I should see table with all users.
I use the Glassfish 4.0 and JavaDB is build in. I don't use any IDE's like Eclipse or Netbeans. My project is managed by Maven.I use also JSF CDI ManagedBeans and JPA.
Please ask me any question. I would really love to solve this issue.
I get this error:
javax.faces.el.EvaluationException: java.lang.NullPointerException
at
javax.faces.component.MethodBindingMethodExpressionAdapter.invoke
(MethodBindingMethodExpressionAdapter.java:101)
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:744)
Caused by: java.lang.NullPointerException
at com.test.UserBean.getAllUsersFromTable(UserBean.java:119)
at com.test.UserBean$Proxy$_$$_WeldClientProxy.getAllUsersFromTable(Unknown Source)
at com.test.AllUsersBean.add(AllUsersBean.java:43)
at com.test.AllUsersBean$Proxy$_$$_WeldClientProxy.add(Unknown Source)
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 org.jboss.weld.util.el.ForwardingMethodExpression.invoke(ForwardingMethodExpression.java:40)
at org.jboss.weld.el.WeldMethodExpression.invoke(WeldMethodExpression.java:50)
at com.sun.faces.facelets.el.TagMethodExpression.invoke(TagMethodExpression.java:105)
at
javax.faces.component.MethodBindingMethodExpressionAdapter.invoke
(MethodBindingMethodExpressionAdapter.java:87)
... 35 more
Line 119 in the UserBean.java file is
user.setId(v.getId());
package com.test;
/*Importing required java libraries */
import java.io.Serializable;
import javax.inject.Named;
import javax.inject.Inject;
import javax.enterprise.context.ApplicationScoped;
import java.util.ArrayList;
import java.util.List;
#Named("appBean")
#ApplicationScoped
public class AllUserssBean implements Serializable {
private List<UserBean> users;
private int id;
#Inject
private UserBean subBean;
public AllUsersBean(){
users = new ArrayList<UserBean>();
id = 0;
}
public String add() throws Exception {
subBean.addUserToTable();
++id;
users.add(subBean.getAllUsersFromTable(id));
subBean.reset();
return "submit";
}
/*Get total number of users */
public int getTotal(){ return users.size(); }
public List<UserBean> getUsers() { return users; }
public void setUsers(List<UserBean> users) { this.users = users; }
}
package com.test;
/*Importing required java libraries */
import java.io.Serializable;
import javax.inject.Named;
import javax.enterprise.context.SessionScoped;
import java.sql.*;
import javax.annotation.Resource;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.PersistenceUnit;
import javax.transaction.UserTransaction;
import javax.transaction.RollbackException;
import javax.persistence.*;
import java.util.List;
import java.util.*;
#Named("subBean")
#SessionScoped
public class UserBean implements Serializable{
#PersistenceUnit(unitName="testMe")
private EntityManagerFactory emf;
#Resource
private UserTransaction transaction;
private int id;
private String fname;
private String lname;
public UserBean() {
this.fname = "";
this.lname = "";
}
public int getId() { return id; }
public void setId(int id) { this.id = id; }
public String getFname() { return fname; }
public void setFname(String fname) { this.fname = fname; }
public String getLname() { return lname; }
public void setLname(String lname) { this.lname = lname; }
public UserTransaction getTransaction() { return transaction; }
public void setTransaction(UserTransaction transaction) { this.transaction = transaction; }
public void addUserToTable() throws Exception
{
EntityManager manager = emf.createEntityManager();
boolean commit;
try{
transaction.begin();
manager.joinTransaction();
commit = false;
try {
User v = null;
v.setFname(fname);
v.setLname(lname);
manager.persist(v);
transaction.commit();
commit = true;
}finally {
if(commit==false){
transaction.rollback();
}
}
} catch(Exception e) {
e.printStackTrace();
}finally {
manager.close();
}
}
public UserBean getAllUsersFromTable(int id) {
EntityManager manager = emf.createEntityManager();
User v = null;
UserBean user = new UserBean();
try {
v = manager.find(User.class, id);
user.setId(v.getId());
user.setFname(v.getFname());
user.setLname(v.getLname());
}finally {
manager.close();
}
return user;
}
/*
public List getAllUsersFromTable() throws javax.transaction.SystemException,
javax.transaction.NotSupportedException {
EntityManager manager = emf.createEntityManager();
User v = null;
List<User> results;
try {
TypedQuery<User> query =
manager.createQuery("SELECT * FROM User", User.class);
results = query.getResultList();
}finally {
manager.close();
}
return results;
} */
/*reset method is used to set all the parameters to null and
to 0. This method is called after user was added to the
list of users */
public void reset(){
setFname("");
setLname("");
}
}
package com.test;
/*Importing required java libraries */
import java.io.Serializable;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.EntityManager;
import javax.persistence.Entity;
import javax.persistence.Column;
import javax.persistence.Id;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
#Entity
public class User implements Serializable{
#Id
#GeneratedValue
private int id;
private String fname;
private String lname;
public User() {}
public int getId() { return id; }
public void setId(int id) { this.id = id; }
public String getFname() { return fname; }
public void setFname(String fname) { this.fname = fname; }
public String getLname() { return lname; }
public void setLname(String lname) { this.lname = lname;}
}
index.xhtml
<!DOCTYPE html
PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xml:lang="en" lang="en"
xmlns="http://www.w3.org/1999/xhtml"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:ui="http://java.sun.com/jsf/facelets">
<h:head><title></title></h:head>
<h:body>
<div style="text-align:center">
<h1>Hello</h1>
<p><h:link value="User Form" outcome="userForm"/></p>
<p><h:link value="All users List" outcome="allUsersList"/></p>
</div>
</h:body>
</html>
userForm.xhtml
<!DOCTYPE html
PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xml:lang="en" lang="en"
xmlns="http://www.w3.org/1999/xhtml"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:ui="http://java.sun.com/jsf/facelets">
<h:head>
<h:outputStylesheet library="css" name="template.css"/>
<title>User Form page</title>
</h:head>
<h:body>
<h:form id="submissionForm">
<table border="0">
<tr>
<td><h:outputLabel for="fname" value="First name:"></h:outputLabel></td>
<td><h:inputText id="firstName" value="#{subBean.fname}" maxlength="30"
requiredMessage="Please enter first name!" validatorMessage="First
name can include only letters. You can't live it empty!" >
<f:validateRegex pattern="[a-zA-Z]{1,30}"></f:validateRegex>
</h:inputText></td>
<td><h:message for="firstName" style="color:red;"></h:message></td>
</tr>
<tr>
<td><h:outputLabel for="lname" value="Last name:"></h:outputLabel></td>
<td><h:inputText id="lastName" value="#{subBean.lname}" maxlength="30"
requiredMessage="Please enter last name!" validatorMessage="Last
name can include only letters. You can't live it empty!" >
<f:validateRegex pattern="[a-zA-Z]{1,60}"></f:validateRegex>
</h:inputText></td>
<td><h:message for="lastName" style="color:red;"></h:message></td>
</tr>
<tr>
<td colspan="3">
<h:commandButton id="submit" value="Submit" action="#{appBean.add()}"
style="float:right;margin-right:10px;"/>
</td>
</tr>
</table>
</h:form>
</h:body>
</html>
allUsersForm.xhtml
<!DOCTYPE html
PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xml:lang="en" lang="en"
xmlns="http://www.w3.org/1999/xhtml"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:ui="http://java.sun.com/jsf/facelets">
<h:head>
<title>List of All Users page</title>
</h:head>
<h:body>
<h:form id="AllUsersListForm">
<h2><h:outputText value="The next election date: #{msgs.date}"/></h2><p></p>
<h:dataTable value="#{appBean.users}" var="v">
<h:column>
<f:facet name="header"><h:outputText value="Id"></h:outputText></f:facet>
<h:outputText value="#{v.id}"></h:outputText>
</h:column>
<h:column>
<f:facet name="header"><h:outputText value="First Name"></h:outputText></f:facet>
<h:outputText value="#{v.fname}"></h:outputText>
</h:column>
<h:column>
<f:facet name="header"><h:outputText value="Last Name"></h:outputText></f:facet>
<h:outputText value="#{v.lname}"></h:outputText>
</h:column>
<f:facet name="footer"><h:outputText
value="The total number of users: #{appBean.getTotal()}"></h:outputText>
</f:facet>
</h:dataTable>
<p></p>
<p><h:link value="Home page" outcome="index"/></p>
</h:form>
</h:body>
</html>
persistence.xml (It is placed under main/resources/META-iNF/perssitence.xml)
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="1.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_1_0.xsd">
<persistence-unit name="test1" transaction-type="JTA">
<provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
<jta-data-source>jdbc/username</jta-data-source>
<exclude-unlisted-classes>false</exclude-unlisted-classes>
<properties>
<property name="javax.persistence.schema-generation.database.action"
value="drop-and-create"/>
<property name="javax.persistence.schema-generation.create-source"
value="metadata"/>
<property name="javax.persistence.schema-generation.drop-source"
value="metadata"/>
<property name="javax.persistence.jdbc.user" value="Us"/>
<property name="javax.persistence.jdbc.password" value="Us"/>
</properties>
</persistence-unit>
</persistence>
When I go to (localhost:4848/common/index.jsf)
I create JDBC Connection Pool and everything is correct. When I Ping I get success response
I also create JDBC Connection Resource and everything is set up correctly
This is what we could use us an example to add data do database
public class AddingDatabase
{
#PersistenceUnit(unitName="test_db”) private EntityManagerFactory emf;
#Resource private UserTransaction utx;
void doDML(MyEntity e) throws SystemException, NotSupportedException,
javax.transaction.RollbackException,HeuristicMixedException,HeuristicRollbackException
{
EntityManager em = emf.createEntityManager();
utx.begin();
em.joinTransaction();
try {
boolean committed = false;
try {
em.persist(e);
utx.commit();
committed = true;
} finally {
if (!committed) utx.rollback();
}
}
finally {
em.close();
}
}
}
This might not be the answer, but I need full formatting.
What are you doing in the following code?
User v = null;
v.setFname(fname);
v.setLname(lname);
manager.persist(v);
How can it possibly not produce NPE?

Resources