Load checked checkbox from database in JSF based on boolean - jsf

I am having dynamic Checkboxes from database and I need them to be checked on page load based on a boolean true or false:
My xhtml:
<h:selectManyCheckbox value="#{report.reports}">
<f:selectItems value="#{report.allreports}" />
</h:selectManyCheckbox>
My Boolean:
public boolean checkedBox(String workclass, String reportname) {
Connection conn;
int count = 0;
try {
conn = db.getDbConnection();
String sql = "select count(*)NUM from rep_access where user_work_class = ? and rep_name = ?";
PreparedStatement ps = conn.prepareStatement(sql);
ps.setString(1, workclass);
ps.setString(2, reportname);
ResultSet rs = ps.executeQuery();
while (rs.next()) {
count = rs.getInt(1);
}
DBConnection.closeConn(conn);
} catch (SQLException asd) {
System.out.println(asd.getMessage());
} catch (IOException asd) {
System.out.println(asd.getMessage());
}
return count > 0;
}
How can I get My check boxes to be checked if the boolean return true. reportname is the value of the check box and workclass value is in the session.

Related

Recover dynamic form data in Java PrimeFaces Extension

my job consists in recovering from a web service a form already filled; modify it with the transmit, the problem that the loop that I made gets the model before the modification I want to know how to recover the form after the modification
List<ModeleForm> modeles = new ArrayList<ModeleForm>();
for (DynaFormControl dynaFormControl : model.getControls()) {
System.out.println("recup");
modeles.add((ModeleForm) dynaFormControl.getData());
}
I tried this loop but it retrieves only the initial values.
model = new DynaFormModel();
try {
String url = "http://localhost:8080/activiti-rest/service/form/form-data?taskId=" + idTask + "";
Representation respons = getClientResource(url).get(MediaType.APPLICATION_JSON);
JSONObject object = new JSONObject(respons.getText());
if (object != null) {
JSONArray formProperties = object.getJSONArray("formProperties");
DynaFormLabel labels[] = new DynaFormLabel[0];
DynaFormControl labels2[] = new DynaFormControl[0];
labels = new DynaFormLabel[formProperties.length()];
labels2 = new DynaFormControl[formProperties.length()];
for (int i = 0; i < (formProperties.length()); i++) {
DynaFormRow row = model.createRegularRow();
boolean required = Boolean.valueOf(formProperties.getJSONObject(i).getString("required"));
labels[i] = row.addLabel(formProperties.getJSONObject(i).getString("name"));
labels2[i] = row.addControl(new ModeleForm(formProperties.getJSONObject(i).getString("name"), formProperties.getJSONObject(i).getString("id"), formProperties.getJSONObject(i).getString("value"), required), getType(formProperties.getJSONObject(i).getString("type")));
labels[i].setForControl(labels2[i]);
}
labels = null;
labels2 = null;
}
object = null;
} catch (MalformedURLException ex) {
Logger.getLogger(DemandeGeneraleController.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(DemandeGeneraleController.class.getName()).log(Level.SEVERE, null, ex);
} catch (JSONException ex) {
Logger.getLogger(DemandeGeneraleController.class.getName()).log(Level.SEVERE, null, ex);
}
System.out.println("apres la fct create");
return model;
}
this code create the modele
<h:panelGroup id="dynaFormGroup">
<pe:dynaForm id="dynaForm" value="#{tachesController.createForm()}" var="data"
autoSubmit="true" widgetVar="dynaForm" >
<ui:include src="colsAddM2.xhtml"/>
</pe:dynaForm>
</h:panelGroup>
my page .xhtml which displays the dynamic form

Filter for JSF table

I would like to add filter for JSF table and limit the values based on filter value.
<h:inputText id="search" value="#{accounts.searchString}"></h:inputText>
<h:commandButton value="Search" action="#{accounts.search()}">
<f:ajax execute="search" render="output"></f:ajax>
</h:commandButton>
I suppose that the best way will be to add the filter value into the SQL query:
SELECT * FROM CUSTOMERS ORDER BY %S %S offset ? limit ?
Full code: http://pastebin.com/eEeTWEqK
How I can implement this for the code into the link?
PS. I modified the code this way:
<div class="div_input_style">
<h:inputText id="search" class="input_style" value="#{accounts.searchString}"></h:inputText>
<h:commandButton class="theSpan" value="Search by title">
<f:ajax execute="search" render="output"></f:ajax>
</h:commandButton>
</div>
public List<AccountsObj> list(int firstRow, int rowCount, String sortField, boolean sortAscending) throws SQLException
{
String SqlStatement = null;
if (ds == null)
{
throw new SQLException();
}
Connection conn = ds.getConnection();
if (conn == null)
{
throw new SQLException();
}
String sortDirection = sortAscending ? "ASC" : "DESC";
SqlStatement = "SELECT * FROM ACCOUNT "
+ " WHERE ? IS NULL OR ? IN (USER_NAME, FIRST_NAME, LAST_NAME)"
+ " ORDER BY %S %S offset ? limit ? ";
String sql = String.format(SqlStatement, sortField, sortDirection);
PreparedStatement ps = null;
ResultSet resultSet = null;
List<AccountsObj> resultList = new ArrayList<>();
try
{
conn.setAutoCommit(false);
boolean committed = false;
ps = conn.prepareStatement(sql);
ps.setString(1, searchString);
ps.setString(2, searchString);
ps.setInt(3, firstRow);
ps.setInt(4, rowCount);
resultSet = ps.executeQuery();
resultList = ProcessorArrayList(resultSet);
conn.commit();
committed = true;
}
finally
{
ps.close();
conn.close();
}
return resultList;
}

JSF Target Unreachable, ''0'' returned null: javax.el.PropertyNotFoundException

a list of Objects :
private ArrayList<LegBeanForInsert> listOfLegs;
I show this array by using the notation with arrays: 0 , 1 , .... positional for example:
<p:selectOneMenu value="#{otcdEventsBean.listOfLegs[0].fixvar}"
effect="fade" style="width:100px; height:25px"
panelStyle="width:80px" >
<f:selectItem itemLabel="Select" itemValue="" />
<f:selectItems value="#{otcdEventsBean.fixedVariableCodes}"
itemValue="#{otcdEventsBean.listOfLegs[0].fixvar}" />
<p:ajax listener="#{otcdEventsBean.fixvarchange}" event="change" update="panelUpdate"/>
</p:selectOneMenu>
ERROR:
value="#{otcdEventsBean.listOfLegs[0].fixvar}": Target Unreachable, ''0'' returned null: javax.el.PropertyNotFoundException
in the constructor of the bean i do:
public void initLeg(){
for(int i=0;i<8;i++){
LegBeanForInsert beanLeg = new LegBeanForInsert();
beanLeg.setCallamount(new BigDecimal(0));
beanLeg.setFixvar("");
this.listOfLegs.add(beanLeg);
}
}
this method is called by another page and when the page is renderd dose not have problem the page:
public void setProduct(Object product1, Object product2) {
System.out.println("BEGIN::setProduct: " + (String) product2);
if (product1 instanceof EqdProduct) {
this.eqdProdToedit = (EqdProduct) product1;
} else if (product1 instanceof CURROPTRBTProduct) {
this.rbtProdType = (CURROPTRBTProduct) product1;
} else if (product1 instanceof COMAsianProduct) {
this.comAsianProd = (COMAsianProduct) product1;
} else if (product1 instanceof CRDProductType) {
this.crdProduct = (CRDProductType) product1;
} else if (product1 instanceof ComSwapProduct) {
firstLegComSw = (ComSwapProduct) product1;
if (product2 instanceof ComSwapProduct) {
System.out.println("Com Sawp second prod");
secondLegComSw = (ComSwapProduct) product2;
}
} else if (product1 instanceof List) {
// bisogna settare LegBeanForInsert, LE GAMBE SONO 8 !!
List<?> legs = (List<?>) product1;
String s = (String) product2;
System.out.println("setProduct 2nd arg: " + product2);
if (s.equals("Legs")) {
for (int i = 0; i < legs.size(); i++) {
Leg leg = (Leg) legs.get(i);
LegBeanForInsert beanLeg = new LegBeanForInsert();
beanLeg.setCallamount(new BigDecimal(leg.getCallamount()));
beanLeg.setCallcurrency(leg.getCallcurrency());
beanLeg.setCallmaturity(leg.getCallmaturityNumber());
beanLeg.setCodintord(leg.getCodintord());
beanLeg.setDayconvention(leg.getDayconvention());
beanLeg.setEnddate(leg.getEnddate());
beanLeg.setEventcode(leg.getEventcode());
beanLeg.setEventtype(leg.getEventtype());
beanLeg.setExercisemode(leg.getExercisemode());
beanLeg.setFixvar(leg.getFixvar());
beanLeg.setEndDate(leg.getFmtenddate());
beanLeg.setStartDate(leg.getFmtstartdate());
beanLeg.setFrequency(leg.getFrequency());
beanLeg.setFrequencymultiplier(leg.getFrequencymultiplier());
beanLeg.setFrequencyunit(leg.getFrequencyunit());
beanLeg.setInareas(leg.getInareas());
beanLeg.setIndexname(leg.getIndexname());
beanLeg.setMargin(leg.getMargin());
beanLeg.setNotional(leg.getNotional());
beanLeg.setNumber(leg.getNumber());
beanLeg.setOptioncashdelivery(leg.getOptioncashdelivery());
beanLeg.setOptionmaturity(leg.getOptionMatirityNumber());
beanLeg.setOptiontype(leg.getOptiontype());
beanLeg.setPaycurrency(leg.getPaycurrency());
beanLeg.setPutamount(leg.getPutamount());
beanLeg.setPutcurrency(leg.getPutcurrency());
beanLeg.setPutmaturity(leg.getPutMatirityNumber());
beanLeg.setQuantityunit(leg.getQuantityunit());
beanLeg.setRate(leg.getRate());
beanLeg.setRateconvention(leg.getRateconvention());
beanLeg.setSign(leg.getSign());
beanLeg.setStartdate(leg.getStartdate());
beanLeg.setStrike(leg.getStrike());
this.listOfLegs.add(beanLeg);
}
} else {
System.out.println("MoneyD 2nd arg: " + product2);
for (int i = 0; i < legs.size(); i++) {
LegMoneyDeal leg = (LegMoneyDeal) legs.get(i);
this.legMoneyD.add(leg);
}
}
} else {
// non nè nessuno di quelli bisogna settare a null tutto quanto
otcdEvents = new OtcdEvents();
crdProduct = new CRDProductType();
firstLegComSw = new ComSwapProduct();
secondLegComSw = new ComSwapProduct();
comAsianProd = new COMAsianProduct();
rbtProdType = new CURROPTRBTProduct();
listOfLegs = new ArrayList<LegBeanForInsert>();
legMoneyD = new ArrayList<LegMoneyDeal>();
eqdProdToedit = new EqdProduct();
}
}
the constructor :
public OtcdEventsBean() {
try {
Context ctx = new InitialContext();
otcdEvents = new OtcdEvents();
crdProduct = new CRDProductType();
firstLegComSw = new ComSwapProduct();
secondLegComSw = new ComSwapProduct();
comAsianProd = new COMAsianProduct();
rbtProdType = new CURROPTRBTProduct();
ds = (DataSource) ctx.lookup("java:comp/env/jdbc/myoracleDS");
rederField = true;
listOfLegs = new ArrayList<LegBeanForInsert>();
initLeg();
eqdProdToedit = new EqdProduct();
legMoneyD = new ArrayList<LegMoneyDeal>();
legMoneyD.add(new LegMoneyDeal());
legMoneyD.add(new LegMoneyDeal());
fieldsEditingDisabled = false;
loginBean = (LoginBean) FacesContext.getCurrentInstance().getApplication().evaluateExpressionGet(FacesContext.getCurrentInstance(), "#{loginBean}", LoginBean.class);
setFixedVariableCodes(new String[2]);
getFixedVariableCodes()[0] = "Fixed";
getFixedVariableCodes()[1] = "Variable";
setSignPremiumCodes(new String[2]);
signPremiumCodes[0] = "Pay";
signPremiumCodes[1] = "Receive";
setFrequencyUnitCodes(new String[4]);
frequencyUnitCodes[0] = "day";
frequencyUnitCodes[1] = "week";
frequencyUnitCodes[2] = "month";
frequencyUnitCodes[3] = "year";
setCashDeliveryCodes(new String[2]);
cashDeliveryCodes[0] = "C";
cashDeliveryCodes[1] = "D";
setOptionTypeCodes(new String[2]);
optionTypeCodes[0] = "CALL";
optionTypeCodes[1] = "PUT";
} catch (NamingException e) {
e.printStackTrace();
}
}
full bean code:
http://pastebin.com/EbfuSwHN
How is the init method called. Maybe that is not getting called? I do not see a new ArrayList on the definition. When do you call new on ArrayList? You should be getting a null pointer exception in the init method. You could add the new ArrayList to the beginning of the init method before the loop. Remember also that set methods get called multiple times in JSF so you should limit the code in the set method.

Jsf datatable writes my data 3 times

I am trying to learn JSF and i have a problem with datatable.
I get datas from database and add them to my list and try to show them in my page. It write datas 3 times. Why is it? Here is my code...
here is related part of bean..
public ArrayList<videos> getVideoss() {
Connection con1 = null;
PreparedStatement pst1 = null;
ResultSet rs1 = null;
String url1 = "jdbc:postgresql://localhost:5432/db";
String user1 = "postgres";
String password11 = "123";
try {
Class.forName("org.postgresql.Driver");
con1 = DriverManager.getConnection(url1, user1, password11);
pst1 = con1
.prepareStatement("SELECT video_name FROM videos WHERE video_course = '"
+ selectedCourse + "';");
rs1 = pst1.executeQuery();
while (rs1.next()) {
videoss.add(new videos(rs1.getString(1)));
}
System.out.println(videoss.size());
.....
xhtml file
<h:dataTable value="#{videoSearch.videoss}" var="videos">
<h:column>
<f:facet name="header">Video Name</f:facet>
#{videos.videoName}
</h:column>
</h:dataTable>
when i look the size of the list it goes like 6 , 12 , 18.. but it should be 6..
Thanks for your support..
As I commented, you are recreting the list every time the getter is called, so the list is growing because you are not clearing it anywhere. Here is a better way to do it :
// Will be called only one time
#PostConstruct
public init()
{
Connection con1 = null;
PreparedStatement pst1 = null;
ResultSet rs1 = null;
String url1 = "jdbc:postgresql://localhost:5432/Thesis";
String user1 = "postgres";
String password11 = "123";
videoss = new ArrayList();
try
{
Class.forName("org.postgresql.Driver");
con1 = DriverManager.getConnection(url1, user1, password11);
pst1 = con1.prepareStatement("SELECT video_name FROM videos WHERE video_course = '" + selectedCourse + "';");
rs1 = pst1.executeQuery();
while (rs1.next())
{
videoss.add(new videos(rs1.getString(1)));
}
System.out.println(videoss.size());
//.....
}
catch(Excepption e)
{
e.printStackTrace();
}
}
public ArrayList<videos> getVideoss()
{
return videoss;
}

How to do filter in jsf datatable?

I need to do the filter in the datatable.
I have two dropdown and first is just static values..like filter by name,dob,age.Based on that open second dropdown and do the filter display the values.
<ice:selectOneMenu size="12" onchange="this.form.submit()"
partialSubmit="true" id="filterByPastDue"
valueChangeListener="#{details.filterByListener}">
<f:selectItem itemLabel="None" itemValue="1" />
<f:selectItem itemLabel="Name" itemValue="2" />
<f:selectItem itemLabel="Age" itemValue="3" />
<f:selectItem itemLabel="DOB" itemValue="4" />
<ice:selectOneMenu binding="#{person.selectFilterItems}" size="12" id="OpenFilterMenu" rendered="false">
In my mangebean have logic to get values in second drop down values.
public void filterByListener(ValueChangeEvent valueChangeEvent) {
int filterBy = Integer
.parseInt((String) valueChangeEvent.getNewValue());
switch (filterBy) {
case 1: {
filterItems = null;
filterItems = new HashSet<SelectItem>();
filterOptions = null;
filterOptions = new HashSet<String>();
outputTextFor = false;
selectFilterItems.setRendered(false);
break;
}
case 2: {
// clearing arraylist
filterItems = null;
filterItems = new HashSet<SelectItem>();
filterOptions = null;
filterOptions = new HashSet<String>();
// loading arrayList
for (int i = 0; i < person.size(); i++) {
filterOptions.add(person.get(i).getName()
.toString());
}
Iterator it = filterOptions.iterator();
while (it.hasNext()) {
String s = (String) it.next();
filterItems.add(new SelectItem(s, s));
}
// rendering components
outputTextFor = true;
selectFilterItems.setRendered(true);
break;
}
case 3: {
// clearing arraylist
filterItems = null;
filterItems = new HashSet<SelectItem>();
filterOptions = null;
filterOptions = new HashSet<String>();
// loading arrayList
for (int i = 0; i < person.size(); i++) {
filterOptions.add(person.get(i).getAge());
}
Iterator it = filterOptions.iterator();
while (it.hasNext()) {
String s = (String) it.next();
filterItems.add(new SelectItem(s, s));
}
// rendering components
outputTextFor = true;
selectFilterItems.setRendered(true);
break;
}
case 4: {
// clearing arraylist
filterItems = null;
filterItems = new HashSet<SelectItem>();
filterOptions = null;
filterOptions = new HashSet<String>();
// loading arrayList
for (int i = 0; i < person.size(); i++) {
filterOptions.add(person.get(i).getDOB());
}
Iterator it = filterOptions.iterator();
while (it.hasNext()) {
String s = (String) it.next();
filterItems.add(new SelectItem(s, s));
}
// rendering components
outputTextFor = true;
selectFilterItems.setRendered(true);
break;
}
default: {
// clearing arrayList
filterItems = null;
filterItems = new HashSet<SelectItem>();
filterOptions = null;
filterOptions = new HashSet<String>();
outputTextFor = false;
selectFilterItems.setRendered(false);
break;
}
}
}
Now i got the second drop down values what in my datatable.
Now, how to get the filter values display in the datatable.I having person object and need to display the datatables which ever selected in the second drop down.
You need to preset the property associated the value attribute of the h:dataTable with the desired datamodel. You could do that in the action method of the submit button or valueChangeListener method of the second dropdown. E.g.
public void submit() {
this.dataModel = getDataModelSomehow(filterBy, filterOption);
}

Resources