JSF bean from database not shown - jsf

I have the following bean:
import java.util.List;
import javax.faces.bean.RequestScoped;
import javax.annotations.ManagedBean;
import javax.persistence.EntityManager;
import listener.EMF;
import model.CustomerOrder;
#MangedBean
#RequestScoped
public class OrderBean {
private List<CustomerOrder> orderList;
/**
* Creates a new instance of OrderBean
*/
public OrderBean() {
EntityManager em = EMF.createEntityManager();
this.orderList = em.createNamedQuery("CustomerOrder.findAll").getResultList();
System.out.println("=== Orderlist ===");
for (CustomerOrder order : orderList) {
System.out.println(order.getNumber());
}
em.close();
}
public List<CustomerOrder> getOrderList() {
System.out.println("=== In getOrderList ===");
return orderList;
}
public void setOrderList(List<CustomerOrder> orderList) {
this.orderList = orderList;
}
}
The CustomerOrder class is a JPA class:
import java.io.Serializable;
import java.math.BigDecimal;
import java.util.*;
import java.util.regex.*;
import javax.persistence.*;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import listener.EMF;
import regex.AttachmentAnalyzer;
#Entity
#Table(name = "customerorder")
#NamedQueries({
#NamedQuery(name = "CustomerOrder.findAll", query = "SELECT c FROM CustomerOrder c"),
#NamedQuery(name = "CustomerOrder.findById", query = "SELECT c FROM CustomerOrder c WHERE c.id = :id"),
#NamedQuery(name = "CustomerOrder.findByNumber", query = "SELECT c FROM CustomerOrder c WHERE c.number = :number"),
#NamedQuery(name = "CustomerOrder.findByCalculationparameter", query = "SELECT c FROM CustomerOrder c WHERE c.calculationparameter = :calculationparameter"),
#NamedQuery(name = "CustomerOrder.findByActive", query = "SELECT c FROM CustomerOrder c WHERE c.active = :active"),
#NamedQuery(name = "CustomerOrder.findByLastupdate", query = "SELECT c FROM CustomerOrder c WHERE c.lastupdate = :lastupdate")})
public class CustomerOrder implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Basic(optional = false)
#Column(name = "id")
private Integer id;
#Size(max = 255)
#Column(name = "number")
private String number;
#Column(name = "calculationparameter")
private BigDecimal calculationparameter;
#Column(name = "active")
private Short active;
#Basic(optional = false)
#NotNull
#Column(name = "lastupdate")
#Temporal(TemporalType.TIMESTAMP)
private Date lastupdate;
#OneToMany(cascade = CascadeType.ALL, mappedBy = "customerorderId")
private List<Orderline> orderlineList;
#OneToMany(cascade = CascadeType.ALL, mappedBy = "customerorderId")
private List<Attachment> attachmentList;
#JoinColumn(name = "lastupdateby", referencedColumnName = "id")
#ManyToOne(optional = false)
private User lastupdateby;
#JoinColumn(name = "customer_id", referencedColumnName = "id")
#ManyToOne
private Customer customerId;
#Transient
private boolean validOrder;
public CustomerOrder() {
}
public CustomerOrder(Email email) {
this.attachmentList = email.getAttachments();
EntityManager em = EMF.createEntityManager();
List<Customer> customers = em.createNamedQuery("Customer.findAll").getResultList();
User systemUser = (User) em.createNamedQuery("User.findByName").setParameter("name", "system").getSingleResult();
em.close();
for (Customer customer : customers) {
String fromAddressFilter = customer.getEmailaddressfilter();
String subjectFilter = customer.getEmailsubjectfilter();
String subject = email.getSubject();
String content = email.getContent();
if (isMatch(email.getSubject(), subjectFilter)
&& isMatch(email.getFromAddress(), fromAddressFilter)) {
this.validOrder = true;
this.active = 1;
AttachmentAnalyzer analyzer = new AttachmentAnalyzer(customer, subject, content, attachmentList);
this.number = analyzer.getNumber();
this.calculationparameter = analyzer.getCalculationParameter();
this.orderlineList = analyzer.getOrderlineList();
this.customerId = customer;
this.lastupdateby = systemUser;
for (Attachment a : attachmentList) {
a.setCustomerorderId(this);
}
for (Orderline o : orderlineList) {
o.setCustomerorderId(this);
o.setLastupdateby(systemUser);
}
} else {
this.validOrder = false;
}
}
}
private boolean isMatch(String string, String filter) {
Pattern pattern;
pattern = Pattern.compile(filter);
Matcher matcher = pattern.matcher(string);
boolean isMatch = matcher.find();
return isMatch;
}
// getters, setters and overrided hashCode, equal and toString methods omitted
}
The JPA class constructor CustomerOrder(Email email) is called by Quartz when a new email message is received. I tested this and this works. I have some customerorder records in my database.
Finally my JSF 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://xmlns.jcp.org/jsf/html">
<h:head>
<title>Test page</title>
</h:head>
<h:body>
<h:dataTable var="order" value="#{orderBean.orderList}" >
<h:column>
#{order.customerId}
</h:column>
</h:dataTable>
</h:body>
</html>
I am expecting this to output the customerId fields from thetable with customerorders in the database. However, it just returns an empty table.
I would at least expect that in my server terminal the Sysout messages from the bean are shown, but even these are not shown.
Question: What is wrong with my code, why are my database entry's not shown? How can I debug this problem?

using java 8, eclipse luna, tomcat 8 and mojarra 2.2.7;
after importing #ManagedBean from javax.faces.bean.ManagedBean instead of javax.annotations.ManagedBean, it works just fine.

Related

java.lang.TypeNotPresentException: Type bookingSessionBean.Plot not present

I want to show the list of the plot from the database. I have created plot.java in package bookingSessionBean and viewPlot.java in package viewBean, but it doesn't work.
index.xhtml code:
<h:body>
<h1><h:outputText value="Selected Plot" /></h1>
<h:form>
<f:view>
<h:dataTable value="#{viewPlot.plots}" var="item">
<h:column>
<h:outputText value="#{item.plotno}" />
</h:column>
</h:dataTable>
</f:view>
</h:form>
</h:body>
viewPlot.java code
#ManagedBean
#Named(value = "viewPlot")
#SessionScoped
public class viewPlot implements Serializable {
#PersistenceContext(unitName = "2day4uPU")
private EntityManager em;
public viewPlot() {
}
public List<Plot> getPlots()
{
return em.createNamedQuery("Plot.findAll").getResultList();
}
}
Plot.java code
#Entity
#Table(name = "PLOT")
#XmlRootElement
#NamedQueries({
#NamedQuery(name = "Plot.findAll", query = "SELECT p FROM Plot p"),
#NamedQuery(name = "Plot.findByPlotno", query = "SELECT p FROM Plot p WHERE p.plotno = :plotno"),
#NamedQuery(name = "Plot.findByStartdate", query = "SELECT p FROM Plot p WHERE p.startdate = :startdate"),
#NamedQuery(name = "Plot.findByEnddate", query = "SELECT p FROM Plot p WHERE p.enddate = :enddate"),
#NamedQuery(name = "Plot.findByAvailableplot", query = "SELECT p FROM Plot p WHERE p.availableplot = :availableplot")})
public class Plot implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#Basic(optional = false)
#NotNull
#Column(name = "PLOTNO")
private Integer plotno;
#Basic(optional = false)
#NotNull
#Column(name = "STARTDATE")
#Temporal(TemporalType.DATE)
private Date startdate;
#Basic(optional = false)
#NotNull
#Column(name = "ENDDATE")
#Temporal(TemporalType.DATE)
private Date enddate;
#Column(name = "AVAILABLEPLOT")
private Integer availableplot;
#JoinColumn(name = "ACCOMNO", referencedColumnName = "ACCOMNO")
#ManyToOne(optional = false)
private Accomodation accomno;
#JoinColumn(name = "SITENO", referencedColumnName = "SITENO")
#ManyToOne(optional = false)
private Site siteno;
#OneToMany(cascade = CascadeType.ALL, mappedBy = "plotno")
private Collection<Booking> bookingCollection;
public Plot() {
}
public Plot(Integer plotno) {
this.plotno = plotno;
}
public Plot(Integer plotno, Date startdate, Date enddate) {
this.plotno = plotno;
this.startdate = startdate;
this.enddate = enddate;
}
public Integer getPlotno() {
return plotno;
}
public void setPlotno(Integer plotno) {
this.plotno = plotno;
}
public Date getStartdate() {
return startdate;
}
public void setStartdate(Date startdate) {
this.startdate = startdate;
}
public Date getEnddate() {
return enddate;
}
public void setEnddate(Date enddate) {
this.enddate = enddate;
}
public Integer getAvailableplot() {
return availableplot;
}
public void setAvailableplot(Integer availableplot) {
this.availableplot = availableplot;
}
public Accomodation getAccomno() {
return accomno;
}
public void setAccomno(Accomodation accomno) {
this.accomno = accomno;
}
public Site getSiteno() {
return siteno;
}
public void setSiteno(Site siteno) {
this.siteno = siteno;
}
#XmlTransient
public Collection<Booking> getBookingCollection() {
return bookingCollection;
}
public void setBookingCollection(Collection<Booking> bookingCollection) {
this.bookingCollection = bookingCollection;
}
#Override
public int hashCode() {
int hash = 0;
hash += (plotno != null ? plotno.hashCode() : 0);
return hash;
}
#Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof Plot)) {
return false;
}
Plot other = (Plot) object;
if ((this.plotno == null && other.plotno != null) || (this.plotno != null && !this.plotno.equals(other.plotno))) {
return false;
}
return true;
}
#Override
public String toString() {
return "bookingSessionBean.Plot[ plotno=" + plotno + " ]";
}
}
[ how can I solve this error? ]

Managed Bean injection failure?

I have a bean that is supposed to retrieve people from a database and then put them in a list which is displayed on the webpage. I keep getting a managed bean injection failure though and it seems to be caused by some sort of link between the database and server getting screwed up.
here is the stack trace.
https://gist.github.com/blaxened/85a6861faf2373c26506
Here is the last part of the server log though it looks very similar to the stack trace.
https://gist.github.com/blaxened/f0bc6028d27cabcbd325
I know for a fact that the database/table is there
Here is my persistence.xml
<?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="com.jsfprohtml5_AIM_war_1.0PU" transaction-type="JTA">
<jta-data-source>jdbc/__default</jta-data-source>
<exclude-unlisted-classes>false</exclude-unlisted-classes>
<properties/>
</persistence-unit>
</persistence>
This is the java class that connects to the database
package com.jsfprohtml5.firstapplication.model;
import java.io.Serializable;
import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.Table;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
/**
*
* #author Black
*/
#Entity
#Table(name = "MYTABLE")
#NamedQueries({
#NamedQuery(name = "AimStaff.findAll", query = "SELECT a FROM AimStaff a"),
#NamedQuery(name = "AimStaff.findById", query = "SELECT a FROM AimStaff a WHERE a.id = :id"),
#NamedQuery(name = "AimStaff.findBySname", query = "SELECT a FROM AimStaff a WHERE a.sname = :sname"),
#NamedQuery(name = "AimStaff.findByDatejoined", query = "SELECT a FROM AimStaff a WHERE a.datejoined = :datejoined"),
#NamedQuery(name = "AimStaff.findByLocale", query = "SELECT a FROM AimStaff a WHERE a.locale = :locale"),
#NamedQuery(name = "AimStaff.findByPhone", query = "SELECT a FROM AimStaff a WHERE a.phone = :phone")})
public class AimStaff implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#Basic(optional = false)
#NotNull
#Column(name = "ID")
private Integer id;
#Size(max = 255)
#Column(name = "SNAME")
private String sname;
#Size(max = 255)
#Column(name = "DATEJOINED")
private String datejoined;
#Size(max = 255)
#Column(name = "LOCALE")
private String locale;
// #Pattern(regexp="^\\(?(\\d{3})\\)?[- ]?(\\d{3})[- ]?(\\d{4})$", message="Invalid phone/fax format, should be as xxx-xxx-xxxx")//if the field contains phone or fax number consider using this annotation to enforce field validation
#Size(max = 100)
#Column(name = "PHONE")
private String phone;
public AimStaff() {
}
public AimStaff(Integer id) {
this.id = id;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getSname() {
return sname;
}
public void setSname(String sname) {
this.sname = sname;
}
public String getDatejoined() {
return datejoined;
}
public void setDatejoined(String datejoined) {
this.datejoined = datejoined;
}
public String getLocale() {
return locale;
}
public void setLocale(String locale) {
this.locale = locale;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
#Override
public int hashCode() {
int hash = 0;
hash += (id != null ? id.hashCode() : 0);
return hash;
}
#Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof AimStaff)) {
return false;
}
AimStaff other = (AimStaff) object;
if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) {
return false;
}
return true;
}
#Override
public String toString() {
return "com.jsfprohtml5.firstapplication.model.AimStaff[ id=" + id + " ]";
}
}
so I am unsure what is wrong. Let me know what other files need to be uploaded if any.
Your Table MYTABLE cannot be found by the Applicationserver. Can you verify that the server is able to connect and find the Table inside the configured datasource?
Can you post your persistence.xml?

PrimeFaces Chart From Database

I already have a CRUD webApp (JSF+EJB+JPA) and I'm trying to develop a chartBean class so I can use it in the View layer.
The data to be rendered (through Primefaces-4 BarChart) should be read from a database.
In the Chart, I have 2 chartSeries to be displayed:
chartSeries1: the employeeGoal -> the 'valor' float column mapped in the Orc entity class below;
chartSeries2: the employeeAccomplished -> the 'Realizado' integer column mapped in the hr_capacit30h entity class below.
The X-Axis should display the Hours (based on the 'chartSeries2' values above).
The Y-axis should display the employeeName (the 'nome' string field in the hr_capacit30h entity class below).
Does anyone knows how to develop the createCartesianChartModel() method below to be used in a jsf page?
The ChartBean class:
//imports ommited
#ManagedBean
#RequestScoped
public class hrCapacitChart {
private Map<Integer, Map<String, Number>> HrCapacitFuncis = new HashMap<Integer, Map<String, Number>>();
private double totalHoras;
private CartesianChartModel cartesianChartModel;
#EJB
private HrCapacit30hFacade hcf;
public hrCapacitChart() {
}
#PostConstruct
private void initialize() {
cartesianChartModel = new CartesianChartModel();
createCartesianChartModel();
}
public CartesianChartModel getCartesianChartModel() {
return cartesianChartModel;
}
private void createCartesianChartModel() {
List<HrCapacit30h> hrCapacit30h = hcf.findAll();
// THIS IS THE METHOD/(Managed Bean property) TO BE DEVELOPED
}
}
The HrCapacit30h entity class (related to chartSeries2 an Y-axis / see description above):
#Entity
#Table(name = "hr_capacit30h", catalog = "DIAGE", schema = "atb")
#XmlRootElement
#NamedQueries({
#NamedQuery(name = "HrCapacit30h.findAll", query = "SELECT h FROM HrCapacit30h h"),
#NamedQuery(name = "HrCapacit30h.findByMatricula", query = "SELECT h FROM HrCapacit30h h WHERE h.hrCapacit30hPK.matricula = :matricula"),
#NamedQuery(name = "HrCapacit30h.findByNome", query = "SELECT h FROM HrCapacit30h h WHERE h.nome = :nome"),
#NamedQuery(name = "HrCapacit30h.findByRealizado", query = "SELECT h FROM HrCapacit30h h WHERE h.realizado = :realizado"),
#NamedQuery(name = "HrCapacit30h.findByDtMov", query = "SELECT h FROM HrCapacit30h h WHERE h.hrCapacit30hPK.dtMov = :dtMov")})
public class HrCapacit30h implements Serializable {
private static final long serialVersionUID = 1L;
#EmbeddedId
protected HrCapacit30hPK hrCapacit30hPK;
#Size(max = 100)
#Column(name = "Nome")
private String nome;
#Column(name = "Realizado")
private Integer realizado;
#JoinColumn(name = "codUOR", referencedColumnName = "cod_UOR")
#ManyToOne(optional = false)
private UpbDeps codUOR;
#JoinColumn(name = "status", referencedColumnName = "id")
#ManyToOne(optional = false)
private Status status;
#JoinColumn(name = "idOrc", referencedColumnName = "id")
#ManyToOne
private Orc idOrc;
#JoinColumn(name = "idDiv", referencedColumnName = "id")
#ManyToOne(optional = false)
private DivDeps idDiv;
public HrCapacit30h() {
}
//getters/setters/equals/hashCode ommited
}
The Entity Orc class (related to chartSeries1 / see description above)::
//imports ommited
#Entity
#Table(name = "orc", catalog = "DIAGE", schema = "atb")
#XmlRootElement
#NamedQueries({
#NamedQuery(name = "Orc.findAll", query = "SELECT o FROM Orc o"),
#NamedQuery(name = "Orc.findById", query = "SELECT o FROM Orc o WHERE o.id = :id"),
#NamedQuery(name = "Orc.findByNomeItem", query = "SELECT o FROM Orc o WHERE o.nomeItem = :nomeItem"),
#NamedQuery(name = "Orc.findByDescItem", query = "SELECT o FROM Orc o WHERE o.descItem = :descItem"),
#NamedQuery(name = "Orc.findByValor", query = "SELECT o FROM Orc o WHERE o.valor = :valor"),
#NamedQuery(name = "Orc.findByDtRef", query = "SELECT o FROM Orc o WHERE o.dtRef = :dtRef")})
public class Orc implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#Basic(optional = false)
#NotNull
#Column(name = "id")
private Integer id;
#Size(max = 100)
#Column(name = "NomeItem")
private String nomeItem;
#Size(max = 255)
#Column(name = "DescItem")
private String descItem;
// #Max(value=?) #Min(value=?)//to enforce field validation to known decimal range values
#Column(name = "valor")
private Double valor;
#Column(name = "DtRef")
#Temporal(TemporalType.TIMESTAMP)
private Date dtRef;
#OneToMany(mappedBy = "idOrc")
private Collection<HrCapacit30h> hrCapacit30hCollection;
//getters/setters/equals/hashCode ommited
}
The EJB (an abstract facade):
//imports ommited
public abstract class AbstractFacade<T> {
private Class<T> entityClass;
public AbstractFacade(Class<T> entityClass) {
this.entityClass = entityClass;
}
protected abstract EntityManager getEntityManager();
public void create(T entity) {
getEntityManager().persist(entity);
}
public void edit(T entity) {
getEntityManager().merge(entity);
}
public void remove(T entity) {
getEntityManager().remove(getEntityManager().merge(entity));
}
public T find(Object id) {
return getEntityManager().find(entityClass, id);
}
public List<T> findAll() {
javax.persistence.criteria.CriteriaQuery cq = getEntityManager().getCriteriaBuilder().createQuery();
cq.select(cq.from(entityClass));
return getEntityManager().createQuery(cq).getResultList();
}
public List<T> findRange(int[] range) {
javax.persistence.criteria.CriteriaQuery cq = getEntityManager().getCriteriaBuilder().createQuery();
cq.select(cq.from(entityClass));
javax.persistence.Query q = getEntityManager().createQuery(cq);
q.setMaxResults(range[1] - range[0] + 1);
q.setFirstResult(range[0]);
return q.getResultList();
}
public int count() {
javax.persistence.criteria.CriteriaQuery cq = getEntityManager().getCriteriaBuilder().createQuery();
javax.persistence.criteria.Root<T> rt = cq.from(entityClass);
cq.select(getEntityManager().getCriteriaBuilder().count(rt));
javax.persistence.Query q = getEntityManager().createQuery(cq);
return ((Long) q.getSingleResult()).intValue();
}
}
The hr_capacit30h EJB facade:
//imports ommited
#Stateless
public class HrCapacit30hFacade extends AbstractFacade<HrCapacit30h> {
#PersistenceContext(unitName = "atb-hrCapacit30PU")
private EntityManager em;
#Override
protected EntityManager getEntityManager() {
return em;
}
public HrCapacit30hFacade() {
super(HrCapacit30h.class);
}
}
The Orc EJB facade:
//imports ommited
#Stateless
public class OrcFacade extends AbstractFacade<Orc> {
#PersistenceContext(unitName = "atb-hrCapacit30PU")
private EntityManager em;
#Override
protected EntityManager getEntityManager() {
return em;
}
public OrcFacade() {
super(Orc.class);
}
}
Thanks in advance.
After a long way studying it:
/**
*
* #author jMarcel
*/
#ManagedBean
#RequestScoped
public class ChartBean {
public ChartBean() {
}
private final Map<Integer, Map<String, Number>> HorasRealizadasPorFunci = new HashMap<>();
private final Map<Integer, Map<String, Number>> HorasOrcadasPorFunci = new HashMap<>();
private CartesianChartModel cartesianChartModel;
#EJB
private OrcFacade of;
#PostConstruct
private void initialize() {
cartesianChartModel = new CartesianChartModel();
createCartesianChartModel();
}
private void createCartesianChartModel() {
List<Orc> orcado = of.findAll();
List<Integer> orcadoList = new ArrayList<>();
List<Integer> realizadoList = new ArrayList<>();
//rlz Series
for (Orc o : orcado) {
int horasRlz = 0;
for (HrCapacit30h r : o.getHrCapacit30hCollection()) {
horasRlz = r.getRealizado();
addOrUpdateRlz(r.getHrCapacit30hPK().getMatricula(), r.getNome(), horasRlz);
realizadoList.add(r.getHrCapacit30hPK().getMatricula());
}
}
//orc Series
for (Orc o : orcado) {
int horasOrc = 0;
for (HrCapacit30h r : o.getHrCapacit30hCollection()) {
horasOrc = r.getIdOrc().getValor().intValue();
addOrUpdateOrc(r.getHrCapacit30hPK().getMatricula(), r.getNome(), horasOrc);
orcadoList.add(r.getHrCapacit30hPK().getMatricula());
}
}
Map<Object, Number> orcMap = new HashMap<>();
Map<Object, Number> rlzMap = new HashMap<>();
for (Integer i : realizadoList) {
populateMap(rlzMap, HorasRealizadasPorFunci.get(i));
}
for (Integer i : orcadoList) {
populateMap(orcMap, HorasOrcadasPorFunci.get(i));
}
ChartSeries orcadoSeries = new ChartSeries("Orçado");
orcadoSeries.setData(orcMap);
ChartSeries realizadoSeries = new ChartSeries("Realizado");
realizadoSeries.setData(rlzMap);
cartesianChartModel.addSeries(orcadoSeries);
cartesianChartModel.addSeries(realizadoSeries);
}
private void addOrUpdateRlz(Integer matricula, String funci, Number horas) {
Map<String, Number> map = HorasRealizadasPorFunci.get(matricula);
if (map == null) {
map = new HashMap<>();
HorasRealizadasPorFunci.put(matricula, map);
}
Number n = map.get(funci);
if (n == null) {
map.put(funci.toUpperCase(), horas);
} else {
map.put(funci.toUpperCase(), horas.intValue());
}
}
private void addOrUpdateOrc(Integer matricula, String funci, Number horas) {
Map<String, Number> map = HorasOrcadasPorFunci.get(matricula);
if (map == null) {
map = new HashMap<>();
HorasOrcadasPorFunci.put(matricula, map);
}
Number n = map.get(funci);
if (n == null) {
map.put(funci.toUpperCase(), horas);
} else {
map.put(funci.toUpperCase(), horas.intValue());
}
}
private void populateMap(Map<Object, Number> map, Map<String, Number> data) {
if (data == null) {
return;
}
for (String key : data.keySet()) {
Number n = map.get((Object) key);
if (n == null) {
map.put((Object) key, data.get(key));
} else {
map.put((Object) key, n.intValue() + data.get(key).intValue());
}
}
}
public CartesianChartModel getCartesianChartModel() {
return cartesianChartModel;
}
public void setCartesianChartModel(CartesianChartModel cartesianChartModel) {
this.cartesianChartModel = cartesianChartModel;
}
}
You need to create a ChartSeries (for category chart) or LineChartSeries (for linear chart) object, fill it with your values, and finally add the object to the Cartesian Model. That's all.
Have a look at the official example
private void createCategoryModel() { // category chart
categoryModel = new CartesianChartModel();
ChartSeries boys = new ChartSeries();
boys.setLabel("Boys");
boys.set("2004", 120);
boys.set("2005", 100);
boys.set("2006", 44);
boys.set("2007", 150);
boys.set("2008", 25);
ChartSeries girls = new ChartSeries();
girls.setLabel("Girls");
girls.set("2004", 52);
girls.set("2005", 60);
girls.set("2006", 110);
girls.set("2007", 135);
girls.set("2008", 120);
categoryModel.addSeries(boys);
categoryModel.addSeries(girls);
}
private void createLinearModel() { //linear chart
linearModel = new CartesianChartModel();
LineChartSeries series1 = new LineChartSeries();
series1.setLabel("Series 1");
series1.set(1, 2);
series1.set(2, 1);
series1.set(3, 3);
series1.set(4, 6);
series1.set(5, 8);
LineChartSeries series2 = new LineChartSeries();
series2.setLabel("Series 2");
series2.setMarkerStyle("diamond");
series2.set(1, 6);
series2.set(2, 3);
series2.set(3, 2);
series2.set(4, 7);
series2.set(5, 9);
linearModel.addSeries(series1);
linearModel.addSeries(series2);
}
Edit :
Create and initialize two ChartSeries objects. Then fill them while iterating through the list. Something like this should work :
ChartSeries a = new ChartSeries();
ChartSeries b = new ChartSeries();
HrCapacit30h tmp = null;
for(int i =0; i<hrCapacit30h.size();i++){
tmp=hrCapacit30h.get(i);
a.set(tmp.getRealizado(), tmp.getNome());
b.set(tmp.getOcr().getValor(), tmp.getNome());
}
cartesianChartModel.addSeries(a);
cartesianChartModel.addSeries(b);
Hope it helps.

Adding a Customer object to a database from a SelectOneMenu

I am trying to create a new order by selecting a customer name from a SelectOneMenu. I am getting a Conversion error setting value for 'null Converter'.
Order.java
#Entity
#Table(name = "order")
public class Order
{
#Id
#Column(name = "ORDER_ID", nullable = false)
#GeneratedValue(strategy = GenerationType.AUTO)
private long orderId;
#JoinColumn(name = "PRODUCT_ID", referencedColumnName = "PRODUCT_ID")
private Product product;
#Column(name = "QUANTITY")
private int quantity;
#Temporal(TemporalType.TIMESTAMP)
#Column(name = "ORDER_DATE")
private Date orderDate;
#ManyToOne(optional = false)
#JoinColumn(name = "CUSTOMER_ID", referencedColumnName = "CUSTOMER_ID")
private Customer customer;
// Getters & Setters
}
newOrder.xhtml
<h:outputLabel value="Customer: "/>
<h:selectOneMenu id="customer" value="#{solController.order.customer}" >
<f:selectItem itemLabel="" itemDisabled="true"/>
<f:selectItems value="#{solController.customerList}" var="customer" id="customerID" itemLabel="#{customer.customerName}" itemValue="#{customer.customerId}" />
</h:selectOneMenu>
SolController.java
#ManagedBean(name = "solController")
#SessionScoped
public class SolController implements Serializable
{
#EJB
private SolEJB solEJB;
private Order order = new Order();
private List<Order> orderList = new ArrayList<Order>();
public String doCreateOrder()
{
order = solEJB.createOrder(order);
orderList = solEJB.findOrders();
return "listOrders.xhtml";
}
// Getters & Setters
}
SolEJB.java
#Stateless
public class SolEJB
{
#PersistenceContext(unitName = "myPU")
private EntityManager em;
public Order createOrder(Order order)
{
em.persist(order);
return order;
}
}

NoSuchMethodException on eclipselink

I'm developing a javaEE project using Glassfish and EclipseLink.
ALthough, when i run my app i get the following exceptions:
Exception [EclipseLink-60] (Eclipse Persistence Services - 2.0.1.v20100213-r6600): org.eclipse.persistence.exceptions.DescriptorException
Exception Description: The method [_persistence_setjuego_vh] or [_persistence_getjuego_vh] is not defined in the object [model.ConcursosJuego].
Internal Exception: java.lang.NoSuchMethodException: model.ConcursosJuego._persistence_getjuego_vh()
i have no clue why i am getting this exception becuase the Entity "Juegos" has that methods, this is the Entity Code:
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package model;
import java.io.Serializable;
import java.math.BigInteger;
import java.util.List;
import javax.persistence.Basic;
import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.OneToMany;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
/**
*
* #author user
*/
#Entity
#NamedQueries({
#NamedQuery(name = "Juego.findAll", query = "SELECT j FROM Juego j"),
#NamedQuery(name = "Juego.findById", query = "SELECT j FROM Juego j WHERE j.id = :id"),
#NamedQuery(name = "Juego.findByNombre", query = "SELECT j FROM Juego j WHERE j.nombre = :nombre"),
#NamedQuery(name = "Juego.findByUrl", query = "SELECT j FROM Juego j WHERE j.url = :url"),
#NamedQuery(name = "Juego.findByMultijugador", query = "SELECT j FROM Juego j WHERE j.multijugador = :multijugador"),
#NamedQuery(name = "Juego.findByTopejugadores", query = "SELECT j FROM Juego j WHERE j.topejugadores = :topejugadores"),
#NamedQuery(name = "Juego.findByEstado", query = "SELECT j FROM Juego j WHERE j.estado = :estado")})
public class Juego implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#Basic(optional = false)
#NotNull
#Size(min = 1, max = 10)
private String id;
#Size(max = 255)
private String nombre;
#Size(max = 1000)
private String url;
private BigInteger multijugador;
private BigInteger topejugadores;
#Size(max = 1)
private String estado;
#OneToMany(cascade = CascadeType.ALL, mappedBy = "juego", fetch = FetchType.LAZY)
private List<Partida> partidaList;
#JoinColumn(name = "RANKING_ID", referencedColumnName = "ID")
#ManyToOne(optional = false, fetch = FetchType.LAZY)
private Ranking ranking;
#JoinColumn(name = "CATEGORIA_ID", referencedColumnName = "ID")
#ManyToOne(optional = false, fetch = FetchType.LAZY)
private Categoria categoria;
#OneToMany(cascade = CascadeType.ALL, mappedBy = "juego", fetch = FetchType.LAZY)
private List<InteraccionUsuarioJuego> interaccionUsuarioJuegoList;
#OneToMany(cascade = CascadeType.ALL, mappedBy = "juego", fetch = FetchType.LAZY)
private List<ConcursosJuego> concursosJuegoList;
public Juego() {
}
public Juego(String id) {
this.id = id;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getNombre() {
return nombre;
}
public void setNombre(String nombre) {
this.nombre = nombre;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public BigInteger getMultijugador() {
return multijugador;
}
public void setMultijugador(BigInteger multijugador) {
this.multijugador = multijugador;
}
public BigInteger getTopejugadores() {
return topejugadores;
}
public void setTopejugadores(BigInteger topejugadores) {
this.topejugadores = topejugadores;
}
public String getEstado() {
return estado;
}
public void setEstado(String estado) {
this.estado = estado;
}
public List<Partida> getPartidaList() {
return partidaList;
}
public void setPartidaList(List<Partida> partidaList) {
this.partidaList = partidaList;
}
public Categoria getCategoria() {
return categoria;
}
public void setCategoria(Categoria categoria) {
this.categoria = categoria;
}
public List<InteraccionUsuarioJuego> getInteraccionUsuarioJuegoList() {
return interaccionUsuarioJuegoList;
}
public void setInteraccionUsuarioJuegoList(List<InteraccionUsuarioJuego> interaccionUsuarioJuegoList) {
this.interaccionUsuarioJuegoList = interaccionUsuarioJuegoList;
}
public List<ConcursosJuego> getConcursosJuegoList() {
return concursosJuegoList;
}
public void setConcursosJuegoList(List<ConcursosJuego> concursosJuegoList) {
this.concursosJuegoList = concursosJuegoList;
}
#Override
public int hashCode() {
int hash = 0;
hash += (id != null ? id.hashCode() : 0);
return hash;
}
#Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof Juego)) {
return false;
}
Juego other = (Juego) object;
if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) {
return false;
}
return true;
}
#Override
public String toString() {
return "model.Juego[ id=" + id + " ]";
}
public Ranking getRanking() {
return ranking;
}
public void setRanking(Ranking ranking) {
this.ranking = ranking;
}
}
this is the application.xml
<?xml version="1.0" encoding="UTF-8"?>
<application xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:application="http://java.sun.com/xml/ns/javaee/application_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/application_6.xsd" id="Application_ID" version="6">
<display-name>p_ear</display-name>
<module>
<ejb>p.jar</ejb>
</module>
<module>
<web>
<web-uri>p_web.war</web-uri>
<context-root>p_web</context-root>
</web>
</module>
</application>
i have tried eclipse link persistance and methods in other entities and it does work.
(This is the first entity that have more than 1 relation)
thanks

Resources