I´m trying to use the Primefaces component: p:selectOneListbox
I would like to use the grouping function.
Currently I´m getting only a String instead the POJO. I´m already using a converter, but I don´t know what is currently wrong. If I´m returning only the List then it´s working fine and I´ve get the values as expected...
Here is my JSF code:
<p:selectOneListbox id="diagramElementList" value="#{myBean.selectedDiagramElementFromList}"
converter="diagramElementConverter" style="width: 100%"
var="diagramElement" filter="true" filterMatchMode="contains">
<f:selectItems
value="#{availableAutomationComponentControllerView.generateListAvailableElements()}"
var="diagramElement" itemLabel="#{diagramElement.name}"
itemValue="#{diagramElement}" />
<p:column style="width: 10px;">
<h:outputText value="#{diagramElement.icon}" />
</p:column>
Here my backend bean:
public List<SelectItem> generateListAvailableElements() {
try {
List<SelectItem> list = new ArrayList<SelectItem>();
SelectItemGroup g1 = new SelectItemGroup("Workflow");
List<DiagramElement> workflowList = automationElementService.generateListAvailableElements(
loginBean.getCurrentEmployee(), localeBean.getLanguage(),
AutomationElementCategory.WORKFLOW.toString());
g1.setSelectItems(createItemList(workflowList));
list.add(g1);
return list;
} catch (Exception e) {
LOGGER.error(ExceptionUtils.getFullStackTrace(e));
ErrorMessage.showErrorMessage();
}
return null;
}
private SelectItem[] createItemList(List<DiagramElement> list) {
List<SelectItem> newlist = new ArrayList<SelectItem>();
for (DiagramElement e : list) {
newlist.add(new SelectItem(e, e.getName()));
}
SelectItem[] arr = new SelectItem[newlist.size()];
arr = newlist.toArray(arr);
return arr;
}
And here my converter:
#FacesConverter("diagramElementConverter")
public class DiagramElementConverter implements Converter {
#Inject
private AutomationElementService automationElementService;
#Inject
private LoginBean loginBean;
#Inject
private LocaleBean localeBean;
public String getAsString(FacesContext context, UIComponent component, Object object) {
String field = (object instanceof DiagramElement) ? ((DiagramElement) object).getId() : null;
return (field != null) ? String.valueOf(field) : null;
}
public Object getAsObject(FacesContext context, UIComponent component, String submittedValue) {
try {
if (submittedValue == null) {
return null;
}
if (submittedValue.trim().equals("")) {
return null;
} else {
for (DiagramElement diagramElement : automationElementService.generateListAvailableElements(
loginBean.getCurrentEmployee(), localeBean.getLanguage(), null)) {
if (diagramElement.getId().equals(submittedValue)) {
return diagramElement;
}
}
}
} catch (Exception e) {
}
return null;
}
}
This question already has answers here:
Conversion Error setting value for 'null Converter' - Why do I need a Converter in JSF?
(2 answers)
Closed 7 years ago.
I'm getting this conversion error message. I'm trying to get a cliente from the selectOneMenu list, then add a bonus to him.
I implemented the converter and the equals/hashcode methods.
Can you see anything wrong?
My XHTML:
<h:body>
<h:form>
<p:panel id="panel" header="Cadastro de bônus">
<p:panelGrid columns="2">
<p:outputLabel value="Cliente: " />
<p:selectOneMenu value="#{clienteBean.cliente}">
<f:selectItem itemLabel="--Selecione um cliente--" />
<f:selectItems value="#{clienteBean.selectClientes}" />
</p:selectOneMenu>
<p:outputLabel value="Informe o valor da venda:" for="valor_venda" />
<p:inputText id="valor_venda"
value="#{bonusBean.bonus.valor_venda}" />
<h:commandButton value="Próximo" action="#{bonusBean.gravar}" />
</p:panelGrid>
</p:panel>
</h:form>
</h:body>
</ui:define>
My DAO:
public class DAOCliente {
public EntityManager getEntityManager() {
EntityManagerFactory factory = Persistence.createEntityManagerFactory("cliente");
EntityManager entityManager = factory.createEntityManager();
return entityManager;
}
public void adiciona (Cliente cliente){
EntityManager entityManager = getEntityManager();
entityManager.getTransaction().begin();
entityManager.persist(cliente);
entityManager.getTransaction().commit();
entityManager.close();
}
public void excluir(Cliente cliente)throws Exception{
EntityManager entityManager = getEntityManager();
try {
entityManager.getTransaction().begin();
cliente = entityManager.merge(cliente);
entityManager.remove(cliente);
entityManager.getTransaction().commit();
} finally {
entityManager.close();
}
}
public Cliente consultar (Long id){
Cliente cliente = new Cliente();
EntityManager entityManager = getEntityManager();
try {
entityManager.getTransaction().begin();
cliente = entityManager.find(Cliente.class, id);
entityManager.getTransaction().commit();
}
catch (Exception e) {
entityManager.getTransaction().rollback();
}
finally {
entityManager.close();
}
return cliente;
}
#SuppressWarnings("unchecked")
public List<Cliente> listarTodosClientes() throws Exception{
EntityManager entityManager = getEntityManager();
List<Cliente> lista = null;
try {
Query query = entityManager.createQuery("SELECT c FROM Cliente c");
lista = query.getResultList();
for (Cliente cliente : lista) {
System.out.println("Nome: " + cliente.getNome());
System.out.println("Fone Residencia: " + cliente.getFone_residencia());
System.out.println("Fone Celular: " + cliente.getFone_celular());
System.out.println("Perfil FB: " + cliente.getPerfil_facebook());
System.out.println("------------------------------------");
}
} catch (Exception e) {
e.printStackTrace();
} finally {
entityManager.close();
}
return lista;
}
}
My converter:
#FacesConverter(forClass = ClienteBean.class)
public class ConverterCliente implements Converter {
#Override
public Object getAsObject(FacesContext ctx, UIComponent component, String value) {
if(value!=null && value.trim().length()>0){
Long id = Long.valueOf(value);
DAOCliente dao = new DAOCliente();
return dao.consultar(id);
}
return null;
}
#Override
public String getAsString(FacesContext facesContext, UIComponent component, Object value) {
if(value!=null){
Cliente cliente = (Cliente) value;
return cliente.getId().toString();
}
return null;
}
}
My Managed Bean:
#ManagedBean
public class ClienteBean {
private Cliente cliente;
List<Cliente> clientes;
List<SelectItem> selectClientes;
DAOCliente dao = new DAOCliente();
public List<SelectItem> getSelectClientes() throws Exception {
if(selectClientes==null){
selectClientes = new ArrayList<SelectItem>();
clientes = dao.listarTodosClientes();
if(clientes!=null && !clientes.isEmpty()){
SelectItem item;
for(Cliente lista : clientes){
item = new SelectItem(lista, lista.getNome());
selectClientes.add(item);
}
}
}
return selectClientes;
}
public List<Cliente> getClientes() throws Exception{
if(clientes == null){
clientes = dao.listarTodosClientes();
}
return clientes;
}
public Cliente getCliente() {
return cliente;
}
public void gravar() {
dao.adiciona(cliente);
this.cliente = new Cliente();
}
public void excluir(Cliente cliente) throws Exception{
dao.excluir(cliente);
}
public void setClientes(List<Cliente> clientes) {
this.clientes = clientes;
}
}
My Cliente class:
public class Cliente {
#Id #GeneratedValue
private Long id;
private String nome;
private String fone_residencia;
private String fone_celular;
private String perfil_facebook;
#OneToMany(mappedBy = "cliente", fetch = FetchType.EAGER, targetEntity = Bonus.class, cascade = CascadeType.ALL)
private List<Bonus> bonus;
public List<Bonus> getBonus() {
return bonus;
}
public void setBonus(List<Bonus> bonus) {
this.bonus = bonus;
}
public String getPerfil_facebook() {
return perfil_facebook;
}
public void setPerfil_facebook(String perfil_facebook) {
this.perfil_facebook = perfil_facebook;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getNome() {
return nome;
}
public void setNome(String nome) {
this.nome = nome;
}
public String getFone_residencia() {
return fone_residencia;
}
public void setFone_residencia(String fone_residencia) {
this.fone_residencia = fone_residencia;
}
public String getFone_celular() {
return fone_celular;
}
public void setFone_celular(String fone_celular) {
this.fone_celular = fone_celular;
}
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((bonus == null) ? 0 : bonus.hashCode());
result = prime * result
+ ((fone_celular == null) ? 0 : fone_celular.hashCode());
result = prime * result
+ ((fone_residencia == null) ? 0 : fone_residencia.hashCode());
result = prime * result + ((id == null) ? 0 : id.hashCode());
result = prime * result + ((nome == null) ? 0 : nome.hashCode());
result = prime * result
+ ((perfil_facebook == null) ? 0 : perfil_facebook.hashCode());
return result;
}
#Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Cliente other = (Cliente) obj;
if (bonus == null) {
if (other.bonus != null)
return false;
} else if (!bonus.equals(other.bonus))
return false;
if (fone_celular == null) {
if (other.fone_celular != null)
return false;
} else if (!fone_celular.equals(other.fone_celular))
return false;
if (fone_residencia == null) {
if (other.fone_residencia != null)
return false;
} else if (!fone_residencia.equals(other.fone_residencia))
return false;
if (id == null) {
if (other.id != null)
return false;
} else if (!id.equals(other.id))
return false;
if (nome == null) {
if (other.nome != null)
return false;
} else if (!nome.equals(other.nome))
return false;
if (perfil_facebook == null) {
if (other.perfil_facebook != null)
return false;
} else if (!perfil_facebook.equals(other.perfil_facebook))
return false;
return true;
}
#Override
public String toString() {
return "Cliente [id=" + id + ", nome=" + nome + ", fone_residencia="
+ fone_residencia + ", fone_celular=" + fone_celular
+ ", perfil_facebook=" + perfil_facebook + ", bonus=" + bonus
+ "]";
}
}
You should mention the used converter class in the concerned tag to enable conversion :
<p:selectOneMenu value="#{clienteBean.cliente}" converter="converterCliente">
...
</p:selectOneMenu>
I got a problem using selectOneMenu, it can clearly convert the Suppliers to SupplierBean (my boss use to call it that way-he was the one who set it up), and display it correctly on the page, but the moment i save it, it returns a null value.
My code in XHTML:
<p:selectOneMenu value="#{itemSupplierController.supplierBean}"
converter="supplierConverter">
<f:selectItem itemLabel="Select..." itemValue="" />
<f:selectItems value="#{supplierController.suppliersBean}"
var="s" itemValue="#{s}" itemLabel="#{s.supplierName}" />
</p:selectOneMenu>
Code in SupplierBean:
public class SupplierBean {
private int id;
private String supplierName;
public SupplierBean(){
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getSupplierName() {
return supplierName;
}
public void setSupplierName(String supplierName) {
this.supplierName = supplierName;
}
}
Code for converter:
#FacesConverter(value = "supplierConverter")
public class SupplierConverter implements Converter {
private static final Logger logger = Logger.getLogger("SupplierConverter");
#Override
public Object getAsObject(FacesContext arg0, UIComponent arg1, String id) {
logger.info(id);
SupplierManager manager = EjbInitializer.getSupplierManager();
if (StringUtils.isNullOrEmpty(id)
|| !org.apache.commons.lang.math.NumberUtils.isNumber(id)) {
return null;
} else {
SupplierBean sb = null;
try {
sb = convertToPojo((Supplier) manager.find(Integer.valueOf(id)));
} catch (SoftTechPersistenceException e) {
e.printStackTrace();
}
return sb;
}
}
#Override
public String getAsString(FacesContext arg0, UIComponent arg1, Object s) {
String val = null;
logger.info("object: " + s);
if (s != null && (s instanceof SupplierBean)) {
SupplierBean supplier = (SupplierBean) s;
val = Integer.toString(supplier.getId());
}
logger.info(String.format("value %s", val));
return val;
}
public static SupplierBean convertToPojo(Supplier s) {
SupplierBean supplier = new SupplierBean();
supplier.setId(s.getId());
String name = "";
if (s.getFullName().isEmpty()) {
name = s.getFullName();
} else {
name = s.getCompany();
}
supplier.setSupplierName(name);
return supplier;
}
}
Overview of the methods in my backingBean that i use to save the supplier(I used to call it controller):
public void supplierSave() {
logger.info("supplier save or update commenced.");
if (SupplierAction.Create.equals(supplierCurrentAction)) {
logger.info("adding supplier to the table...");
addSupplierToTable();
} else if (SupplierAction.Update.equals(supplierCurrentAction)) {
logger.info("supplier updating...");
updateSupplier();
}
}
public void addSupplierToTable() {
try {
logger.info(String.format("supplier id: %s", getSupplierBean().getId()));
setSupplier((Supplier)supplierManager.find(getSupplierBean().getId()));
getItemSupplier().setSupplier(getSupplier());
getItemSuppliers().add(getItemSupplier());
resetSupplier();
} catch (Exception e) {
e.printStackTrace();
}
logger.info("supplier successfully added to the table.");
}
my jsf page
<h:form>
<h:dataTable id="btable" value="#{ballController.items}" var="item">
<h:column>
<h:outputText value="#{item.id}"/>
</h:column>
<h:column>
<h:outputText value="#{item.bname}"/>
</h:column>
</h:dataTable>
<h:commandButton action="#{ballCOntroller.items}" value="test">
<f:ajax execute="#form" render="btable" />
</h:commandButton>
</h:form>
in my controller, this method is called by ballController.items
public DataModel getItems() {
if (items == null) {
items = getPagination().createPageDataModel();
}
return items;
}
but upon clicking the button itl give me an error saying:
serverError: classjavax.faces.el.MethodNotFoundException
/app/ball/index.xhtml #40,101 action="#{ballController.items}": Method
not found: ballController#a7150b6.items()
my goal is to reload the dataTable on clicking the command button without refreshing the entire page.
*Edited
my whole bean code
#ManagedBean(name = "ballController")
#ViewScoped
public class ballController implements Serializable {
private ball current;
private DataModel items = null;
#EJB
private ballFacade ejbFacade;
private PaginationHelper pagination;
private int selectedItemIndex;
public ballController() {
}
public ball getSelected() {
if (current == null) {
current = new ball();
selectedItemIndex = -1;
}
return current;
}
private ballFacade getFacade() {
return ejbFacade;
}
public PaginationHelper getPagination() {
if (pagination == null) {
pagination = new PaginationHelper(10) {
#Override
public int getItemsCount() {
return getFacade().count();
}
#Override
public DataModel createPageDataModel() {
return new ListDataModel(getFacade().findRange(new int[]{getPageFirstItem(), getPageFirstItem() + getPageSize()}));
}
};
}
return pagination;
}
public String prepareList() {
recreateModel();
return "List";
}
public String prepareView() {
current = (ball) getItems().getRowData();
selectedItemIndex = pagination.getPageFirstItem() + getItems().getRowIndex();
return "View";
}
public String prepareCreate() {
current = new ball();
selectedItemIndex = -1;
return "index";
}
public String create() {
try {
getFacade().create(current);
JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/Bundle").getString("ballCreated"));
return prepareCreate();
// return null;
} catch (Exception e) {
JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured"));
return null;
}
}
public String prepareEdit() {
current = (ball) getItems().getRowData();
selectedItemIndex = pagination.getPageFirstItem() + getItems().getRowIndex();
return "Edit";
}
public String update() {
try {
getFacade().edit(current);
JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/Bundle").getString("ballUpdated"));
return "View";
} catch (Exception e) {
JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured"));
return null;
}
}
public String destroy() {
current = (ball) getItems().getRowData();
selectedItemIndex = pagination.getPageFirstItem() + getItems().getRowIndex();
performDestroy();
recreatePagination();
recreateModel();
return "List";
}
public String destroyAndView() {
performDestroy();
recreateModel();
updateCurrentItem();
if (selectedItemIndex >= 0) {
return "View";
} else {
// all items were removed - go back to list
recreateModel();
return "List";
}
}
private void performDestroy() {
try {
getFacade().remove(current);
JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/Bundle").getString("ballDeleted"));
} catch (Exception e) {
JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured"));
}
}
private void updateCurrentItem() {
int count = getFacade().count();
if (selectedItemIndex >= count) {
// selected index cannot be bigger than number of items:
selectedItemIndex = count - 1;
// go to previous page if last page disappeared:
if (pagination.getPageFirstItem() >= count) {
pagination.previousPage();
}
}
if (selectedItemIndex >= 0) {
current = getFacade().findRange(new int[]{selectedItemIndex, selectedItemIndex + 1}).get(0);
}
}
public DataModel getItems() {
if (items == null) {
items = getPagination().createPageDataModel();
}
return items;
}
private void recreateModel() {
items = null;
}
private void recreatePagination() {
pagination = null;
}
public String next() {
getPagination().nextPage();
recreateModel();
return "List";
}
public String previous() {
getPagination().previousPage();
recreateModel();
return "List";
}
public SelectItem[] getItemsAvailableSelectMany() {
return JsfUtil.getSelectItems(ejbFacade.findAll(), false);
}
public SelectItem[] getItemsAvailableSelectOne() {
return JsfUtil.getSelectItems(ejbFacade.findAll(), true);
}
#FacesConverter(forClass = ball.class)
public static class ballControllerConverter implements Converter {
public Object getAsObject(FacesContext facesContext, UIComponent component, String value) {
if (value == null || value.length() == 0) {
return null;
}
ballController controller = (ballController) facesContext.getApplication().getELResolver().
getValue(facesContext.getELContext(), null, "ballController");
return controller.ejbFacade.find(getKey(value));
}
java.lang.Integer getKey(String value) {
java.lang.Integer key;
key = Integer.valueOf(value);
return key;
}
String getStringKey(java.lang.Integer value) {
StringBuffer sb = new StringBuffer();
sb.append(value);
return sb.toString();
}
public String getAsString(FacesContext facesContext, UIComponent component, Object object) {
if (object == null) {
return null;
}
if (object instanceof ball) {
ball o = (ball) object;
return getStringKey(o.getId());
} else {
throw new IllegalArgumentException("object " + object + " is of type " + object.getClass().getName() + "; expected type: " + ball.class.getName());
}
}
}
}
To reload the table , you just need to use <f:ajax render="btable" />
<h:commandButton value="test">
<f:ajax render="btable" />
</h:commandButton>
But to to do some action , like adding some data to table you need to point the button to a a proper method
<h:commandButton value="test" action="#{ballController.addItem}"">
<f:ajax render="btable" />
</h:commandButton>
public void addItem() {
if (items == null) {
items = getPagination().createPageDataModel();
}
items.getWrappedData().add(/*something like new MyObject("one","two")*/);
}
serverError: classjavax.faces.el.MethodNotFoundException /app/ball/index.xhtml #40,101 action="#{ballController.items}": Method not found: ballController#a7150b6.items()
Is occurring because you are trying to access getItems in an incorrect way.
Update your bean code as:
public DataModel items() {
if (items == null) {
items = getPagination().createPageDataModel();
}
return items;
}
or else change your facelet action EL expression as action="#{ballCOntroller.getItems}".
EDIT
You can update your List as:
public class DataTableBean implements Serializable {
List<String> dataModelList = new ArrayList<DataModel>();
public List<DataModel> getDataModelList() {
return dataTableList;
}
public void setDataModelList(List<String> dataModelList) {
this.dataTableList = dataTableList;
}
public void addItems(){
List<DataModel> tempList = getPagination().createPageDataModel(); // Returns a list of type `List<DataModel>`.
dataModelList.addAll(tempList);
}
}
I am developing a JSF application with JPA using Netbeans. I crate Entity classes and then generate JSF pages from Entity classes through Netbeans. It creates an AbstractFacade, facade extending the abstract facade for each entity, controller bean for each entity and a JSF page. Then I alter and use these generated codes to create my logic.
There is intermittently a ClassCastException when I use two controller beans within a single JSF page. But when I restart the GLassFish server, the exception disappers for some time and appear again and I can not find out what initiated the change.
For example, consider a situation where there is an Entity called Atm.It has a property MedicineGroup, which is also another entity. When an object from Atm entity is going to be saved through a JSF page, I get all the MedicineGroups calling the MedicineGroupController and assigning it to a selected GenericName property of Atm object. This logic works well until that ClassCastException occur.
(The same above method is used in most JSF pages. Atm entity has a property of Vtm. Ampp has peoperties like Atm atm, MeasurmentUnit strengthUnit, Double strength, Double rol, etc.)
I can also get the same thing done by changing the logic so that there will be only one controller for each JSF page, but it is very easy if multiple controller beans can be referred within the same JSF page.
What is wrong here?
I have listed some important code below.
The relevant part of JSF page.
<h:selectOneListbox id="txtGroup" value="#{vtmController.current.medicineGroup}" size="5" >
<f:selectItems value="#{medicineGroupController.items}" var="gp" itemValue="#{gp}" itemLabel="#{gp.name}"/>
</h:selectOneListbox>
Example of an Entity class
#Entity
#Inheritance
public class Vtm extends PharmaceuticalItem implements Serializable {
#ManyToOne
MedicineGroup medicineGroup;
public MedicineGroup getMedicineGroup() {
return medicineGroup;
}
public void setMedicineGroup(MedicineGroup medicineGroup) {
this.medicineGroup = medicineGroup;
}
}
The controller class example which include an auto-generated converter.
#ManagedBean
#SessionScoped
public final class VtmController {
#EJB
private VtmFacade ejbFacade;
SessionController sessionController = new SessionController();
List<Vtm> lstItems;
private Vtm current;
private DataModel<Vtm> items = null;
private int selectedItemIndex;
boolean selectControlDisable = false;
boolean modifyControlDisable = true;
String selectText = "";
public VtmController() {
}
public List<Vtm> getLstItems() {
return getFacade().findBySQL("Select d From Vtm d");
}
public void setLstItems(List<Vtm> lstItems) {
this.lstItems = lstItems;
}
public int getSelectedItemIndex() {
return selectedItemIndex;
}
public void setSelectedItemIndex(int selectedItemIndex) {
this.selectedItemIndex = selectedItemIndex;
}
public Vtm getCurrent() {
if (current == null) {
current = new Vtm();
}
return current;
}
public void setCurrent(Vtm current) {
this.current = current;
}
private VtmFacade getFacade() {
return ejbFacade;
}
public DataModel<Vtm> getItems() {
items = new ListDataModel(getFacade().findAll("name", true));
return items;
}
public static int intValue(long value) {
int valueInt = (int) value;
if (valueInt != value) {
throw new IllegalArgumentException(
"The long value " + value + " is not within range of the int type");
}
return valueInt;
}
public DataModel searchItems() {
recreateModel();
if (items == null) {
if (selectText.equals("")) {
items = new ListDataModel(getFacade().findAll("name", true));
} else {
items = new ListDataModel(getFacade().findAll("name", "%" + selectText + "%",
true));
if (items.getRowCount() > 0) {
items.setRowIndex(0);
current = (Vtm) items.getRowData();
Long temLong = current.getId();
selectedItemIndex = intValue(temLong);
} else {
current = null;
selectedItemIndex = -1;
}
}
}
return items;
}
public Vtm searchItem(String itemName, boolean createNewIfNotPresent) {
Vtm searchedItem = null;
items = new ListDataModel(getFacade().findAll("name", itemName, true));
if (items.getRowCount() > 0) {
items.setRowIndex(0);
searchedItem = (Vtm) items.getRowData();
} else if (createNewIfNotPresent) {
searchedItem = new Vtm();
searchedItem.setName(itemName);
searchedItem.setCreatedAt(Calendar.getInstance().getTime());
searchedItem.setCreater(sessionController.loggedUser);
getFacade().create(searchedItem);
}
return searchedItem;
}
private void recreateModel() {
items = null;
}
public void prepareSelect() {
this.prepareModifyControlDisable();
}
public void prepareEdit() {
if (current != null) {
selectedItemIndex = intValue(current.getId());
this.prepareSelectControlDisable();
} else {
JsfUtil.addErrorMessage(new MessageProvider().getValue("nothingToEdit"));
}
}
public void prepareAdd() {
selectedItemIndex = -1;
current = new Vtm();
this.prepareSelectControlDisable();
}
public void saveSelected() {
if (selectedItemIndex > 0) {
getFacade().edit(current);
JsfUtil.addSuccessMessage(new MessageProvider().getValue("savedOldSuccessfully"));
} else {
current.setCreatedAt(Calendar.getInstance().getTime());
current.setCreater(sessionController.loggedUser);
getFacade().create(current);
JsfUtil.addSuccessMessage(new MessageProvider().getValue("savedNewSuccessfully"));
}
this.prepareSelect();
recreateModel();
getItems();
selectText = "";
selectedItemIndex = intValue(current.getId());
}
public void addDirectly() {
JsfUtil.addSuccessMessage("1");
try {
current.setCreatedAt(Calendar.getInstance().getTime());
current.setCreater(sessionController.loggedUser);
getFacade().create(current);
JsfUtil.addSuccessMessage(new MessageProvider().getValue("savedNewSuccessfully"));
current = new Vtm();
} catch (Exception e) {
JsfUtil.addErrorMessage(e, "Error");
}
}
public void cancelSelect() {
this.prepareSelect();
}
public void delete() {
if (current != null) {
current.setRetired(true);
current.setRetiredAt(Calendar.getInstance().getTime());
current.setRetirer(sessionController.loggedUser);
getFacade().edit(current);
JsfUtil.addSuccessMessage(new MessageProvider().getValue("deleteSuccessful"));
} else {
JsfUtil.addErrorMessage(new MessageProvider().getValue("nothingToDelete"));
}
recreateModel();
getItems();
selectText = "";
selectedItemIndex = -1;
current = null;
this.prepareSelect();
}
public boolean isModifyControlDisable() {
return modifyControlDisable;
}
public void setModifyControlDisable(boolean modifyControlDisable) {
this.modifyControlDisable = modifyControlDisable;
}
public boolean isSelectControlDisable() {
return selectControlDisable;
}
public void setSelectControlDisable(boolean selectControlDisable) {
this.selectControlDisable = selectControlDisable;
}
public String getSelectText() {
return selectText;
}
public void setSelectText(String selectText) {
this.selectText = selectText;
searchItems();
}
public void prepareSelectControlDisable() {
selectControlDisable = true;
modifyControlDisable = false;
}
public void prepareModifyControlDisable() {
selectControlDisable = false;
modifyControlDisable = true;
}
#FacesConverter(forClass = Vtm.class)
public static class VtmControllerConverter implements Converter {
public Object getAsObject(FacesContext facesContext, UIComponent component, String value) {
if (value == null || value.length() == 0) {
return null;
}
VtmController controller = (VtmController) facesContext.getApplication().getELResolver().
getValue(facesContext.getELContext(), null, "vtmController");
return controller.ejbFacade.find(getKey(value));
}
java.lang.Long getKey(String value) {
java.lang.Long key;
key = Long.valueOf(value);
return key;
}
String getStringKey(java.lang.Long value) {
StringBuffer sb = new StringBuffer();
sb.append(value);
return sb.toString();
}
public String getAsString(FacesContext facesContext, UIComponent component, Object object) {
if (object == null) {
return null;
}
if (object instanceof Vtm) {
Vtm o = (Vtm) object;
return getStringKey(o.getId());
} else {
throw new IllegalArgumentException("object " + object + " is of type "
+ object.getClass().getName() + "; expected type: " + VtmController.class.getName());
}
}
}
}
An Example for a Facade
#Stateless
public class VtmFacade extends AbstractFacade<Vtm> {
#PersistenceContext(unitName = "HOPU")
private EntityManager em;
#Override
protected EntityManager getEntityManager() {
return em;
}
public VtmFacade() {
super(Vtm.class);
}
}
The generated abstract facade and the changes I made.
public abstract class AbstractFacade<T> {
protected 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(boolean withoutRetired) {
return findAll(null, null, withoutRetired);
}
public List<T> findAll() {
javax.persistence.criteria.CriteriaBuilder cb = getEntityManager().getCriteriaBuilder();
javax.persistence.criteria.CriteriaQuery<T> cq = cb.createQuery(entityClass);
javax.persistence.criteria.Root<T> rt = cq.from(entityClass);
return getEntityManager().createQuery(cq).getResultList();
}
public List<T> findAll(String fieldName) {
return findAll(fieldName, "", false);
}
public List<T> findAll(String fieldName, boolean withoutRetired) {
return findAll(fieldName, "", withoutRetired);
}
public List<T> findAll(String fieldName, String fieldValue) {
return findAll(fieldName, fieldValue, false);
}
public List<T> findBySQL(String temSQL) {
TypedQuery<T> qry = getEntityManager().createQuery(temSQL, entityClass);
return qry.getResultList();
}
public List<T> findBySQL(String temSQL, Map<String, Date> parameters) {
TypedQuery<T> qry = getEntityManager().createQuery(temSQL, entityClass);
Set s=parameters.entrySet();
Iterator it=s.iterator();
while (it.hasNext()){
Map.Entry m=(Map.Entry)it.next();
Date pVal = (Date) m.getValue();
String pPara=(String) m.getKey();
qry.setParameter(pPara, pVal, TemporalType.DATE);
System.out.println("Parameter " + pPara + "\tVal" + pVal);
}
return qry.getResultList();
}
private void test(Class myClass, Object ob) {
}
public List<T> findAll(String fieldName, String fieldValue, boolean withoutRetired) {
javax.persistence.criteria.CriteriaBuilder cb = getEntityManager().getCriteriaBuilder();
javax.persistence.criteria.CriteriaQuery<T> cq = cb.createQuery(entityClass);
javax.persistence.criteria.Root<T> rt = cq.from(entityClass);
ParameterExpression<String> p = cb.parameter(String.class);
Predicate predicateField = cb.like(rt.<String>get(fieldName), fieldValue);
Predicate predicateRetired = cb.equal(rt.<Boolean>get("retired"), false);
Predicate predicateFieldRetired = cb.and(predicateField, predicateRetired);
if (withoutRetired && !fieldValue.equals("")) {
cq.where(predicateFieldRetired);
} else if (withoutRetired) {
cq.where(predicateRetired);
} else if (!fieldValue.equals("")) {
cq.where(predicateField);
}
if (!fieldName.equals("")) {
cq.orderBy(cb.asc(rt.get(fieldName)));
}
return getEntityManager().createQuery(cq).getResultList();
}
public List<T> findExact(String fieldName, String fieldValue, boolean withoutRetired) {
javax.persistence.criteria.CriteriaBuilder cb = getEntityManager().getCriteriaBuilder();
javax.persistence.criteria.CriteriaQuery<T> cq = cb.createQuery(entityClass);
javax.persistence.criteria.Root<T> rt = cq.from(entityClass);
ParameterExpression<String> p = cb.parameter(String.class);
Predicate predicateField = cb.equal(cb.upper(rt.<String>get(fieldName)), fieldValue.toLowerCase());
Predicate predicateRetired = cb.equal(rt.<Boolean>get("retired"), false);
Predicate predicateFieldRetired = cb.and(predicateField, predicateRetired);
if (withoutRetired && !fieldValue.equals("")) {
cq.where(predicateFieldRetired);
} else if (withoutRetired) {
cq.where(predicateRetired);
} else if (!fieldValue.equals("")) {
cq.where(predicateField);
}
if (!fieldName.equals("")) {
cq.orderBy(cb.asc(rt.get(fieldName)));
}
return getEntityManager().createQuery(cq).getResultList();
}
public T findByField(String fieldName, String fieldValue, boolean withoutRetired) {
List<T> lstAll = findExact(fieldName, fieldValue, true);
if (lstAll.isEmpty()) {
return null;
} else {
return lstAll.get(0);
}
}
public T findFirstBySQL(String temSQL) {
TypedQuery<T> qry = getEntityManager().createQuery(temSQL, entityClass);
try {
return qry.getResultList().get(0);
} catch (Exception e) {
System.out.println(e.getMessage());
return null;
}
}
public <U> List<T> testMethod(U[] a, Collection<U> all) {
List<T> myList = new ArrayList<T>();
return myList;
}
public <U> List<T> findAll(String fieldName, int searchID, boolean withoutRetired) {
javax.persistence.criteria.CriteriaBuilder cb = getEntityManager().getCriteriaBuilder();
javax.persistence.criteria.CriteriaQuery<T> cq = cb.createQuery(entityClass);
javax.persistence.criteria.Root<T> rt = cq.from(entityClass);
if (withoutRetired) {
cq.where(cb.and(cb.equal(rt.get("retired"), false)),
(cb.equal(rt.get(fieldName).get("id"), searchID)));
} else {
cq.where(cb.equal(rt.get("retired"), false));
}
return getEntityManager().createQuery(cq).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();
}
public Double findAggregateDbl(String strJQL){
Query q= getEntityManager().createQuery(strJQL);
try{
return (Double) q.getSingleResult();
}catch (Exception e){
System.out.println(e.getMessage());
return 0.0;
}
}
}
This is the code which is referred by the exception.
AtmController controller = (AtmController) facesContext.getApplication().getELResolver().
getValue(facesContext.getELContext(), null, "atmController");
In different instances, this same corresponding place, but a different controller. When error occur once, despite the JSF page access afterwords, the same Controller is giving the error, but after server restart, the controller differs depending on the page where error started to occur.
This is the full stack trace. (The name of the controller classes changes depending on the JSF page I use to access.)
INFO: java.lang.ClassCastException: gov.sp.health.bean.VtmController cannot be cast to gov.sp.health.bean.AtmController
java.lang.ClassCastException: gov.sp.health.bean.VtmController cannot be cast to gov.sp.health.bean.AtmController
at gov.sp.health.bean.AtmController$VtmControllerConverter.getAsObject(AtmController.java:252)
at com.sun.faces.renderkit.html_basic.HtmlBasicInputRenderer.getConvertedValue(HtmlBasicInputRenderer.java:171)
at com.sun.faces.renderkit.html_basic.MenuRenderer.convertSelectOneValue(MenuRenderer.java:202)
at com.sun.faces.renderkit.html_basic.MenuRenderer.getConvertedValue(MenuRenderer.java:319)
at javax.faces.component.UIInput.getConvertedValue(UIInput.java:1030)
at javax.faces.component.UIInput.validate(UIInput.java:960)
at javax.faces.component.UIInput.executeValidate(UIInput.java:1233)
at javax.faces.component.UIInput.processValidators(UIInput.java:698)
at com.sun.faces.context.PartialViewContextImpl$PhaseAwareVisitCallback.visit(PartialViewContextImpl.java:508)
at com.sun.faces.component.visit.PartialVisitContext.invokeVisitCallback(PartialVisitContext.java:183)
at javax.faces.component.UIComponent.visitTree(UIComponent.java:1590)
at javax.faces.component.UIComponent.visitTree(UIComponent.java:1601)
at javax.faces.component.UIComponent.visitTree(UIComponent.java:1601)
at javax.faces.component.UIComponent.visitTree(UIComponent.java:1601)
at javax.faces.component.UIComponent.visitTree(UIComponent.java:1601)
at javax.faces.component.UIComponent.visitTree(UIComponent.java:1601)
at javax.faces.component.UIComponent.visitTree(UIComponent.java:1601)
at javax.faces.component.UIForm.visitTree(UIForm.java:344)
at javax.faces.component.UIComponent.visitTree(UIComponent.java:1601)
at javax.faces.component.UIComponent.visitTree(UIComponent.java:1601)
at javax.faces.component.UIComponent.visitTree(UIComponent.java:1601)
at javax.faces.component.UIComponent.visitTree(UIComponent.java:1601)
at javax.faces.component.UIComponent.visitTree(UIComponent.java:1601)
at javax.faces.component.UIComponent.visitTree(UIComponent.java:1601)
at javax.faces.component.UIComponent.visitTree(UIComponent.java:1601)
at com.sun.faces.context.PartialViewContextImpl.processComponents(PartialViewContextImpl.java:376)
at com.sun.faces.context.PartialViewContextImpl.processPartial(PartialViewContextImpl.java:252)
at javax.faces.context.PartialViewContextWrapper.processPartial(PartialViewContextWrapper.java:183)
at javax.faces.component.UIViewRoot.processValidators(UIViewRoot.java:1170)
at com.sun.faces.lifecycle.ProcessValidationsPhase.execute(ProcessValidationsPhase.java:76)
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:1542)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:343)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:217)
at org.primefaces.webapp.filter.FileUploadFilter.doFilter(FileUploadFilter.java:79)
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 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:722)
Converter inside AtmController
#FacesConverter(forClass = Atm.class)
public static class AtmControllerConverter implements Converter {
public Object getAsObject(FacesContext facesContext, UIComponent component, String value) {
if (value == null || value.length() == 0) {
return null;
}
AtmController controller = (AtmController) facesContext.getApplication().getELResolver().
getValue(facesContext.getELContext(), null, "atmController");
return controller.ejbFacade.find(getKey(value));
}
java.lang.Long getKey(String value) {
java.lang.Long key;
key = Long.valueOf(value);
return key;
}
String getStringKey(java.lang.Long value) {
StringBuffer sb = new StringBuffer();
sb.append(value);
return sb.toString();
}
public String getAsString(FacesContext facesContext, UIComponent component, Object object) {
if (object == null) {
return null;
}
if (object instanceof Atm) {
Atm o = (Atm) object;
return getStringKey(o.getId());
} else {
throw new IllegalArgumentException("object " + object + " is of type "
+ object.getClass().getName() + "; expected type: " + AtmController.class.getName());
}
}
}
Converter inside the VtmController
#FacesConverter(forClass = Vtm.class)
public static class VtmControllerConverter implements Converter {
public Object getAsObject(FacesContext facesContext, UIComponent component, String value) {
if (value == null || value.length() == 0) {
return null;
}
VtmController controller = (VtmController) facesContext.getApplication().getELResolver().
getValue(facesContext.getELContext(), null, "vtmController");
return controller.ejbFacade.find(getKey(value));
}
java.lang.Long getKey(String value) {
java.lang.Long key;
key = Long.valueOf(value);
return key;
}
String getStringKey(java.lang.Long value) {
StringBuffer sb = new StringBuffer();
sb.append(value);
return sb.toString();
}
public String getAsString(FacesContext facesContext, UIComponent component, Object object) {
if (object == null) {
return null;
}
if (object instanceof Vtm) {
Vtm o = (Vtm) object;
return getStringKey(o.getId());
} else {
throw new IllegalArgumentException("object " + object + " is of type "
+ object.getClass().getName() + "; expected type: " + VtmController.class.getName());
}
}
}
Converter inside the MedicineGroupController
#FacesConverter(forClass = MedicineGroup.class)
public static class MedicineGroupControllerConverter implements Converter {
public Object getAsObject(FacesContext facesContext, UIComponent component, String value) {
if (value == null || value.length() == 0) {
return null;
}
MedicineGroupController controller = (MedicineGroupController) facesContext.getApplication().getELResolver().
getValue(facesContext.getELContext(), null, "medicineGroupController");
return controller.ejbFacade.find(getKey(value));
}
java.lang.Long getKey(String value) {
java.lang.Long key;
key = Long.valueOf(value);
return key;
}
String getStringKey(java.lang.Long value) {
StringBuffer sb = new StringBuffer();
sb.append(value);
return sb.toString();
}
public String getAsString(FacesContext facesContext, UIComponent component, Object object) {
if (object == null) {
return null;
}
if (object instanceof MedicineGroup) {
MedicineGroup o = (MedicineGroup) object;
return getStringKey(o.getId());
} else {
throw new IllegalArgumentException("object " + object + " is of type "
+ object.getClass().getName() + "; expected type: " + MedicineGroupController.class.getName());
}
}
}
I used converters for each selectOneListbox. The error did not occur afterwords. Below is a similar example I used. (Not exactly the very same as above code)
Initial Converter
#FacesConverter(forClass = Investigation.class)
public static class InvestigationControllerConverter implements Converter {
public InvestigationControllerConverter() {
}
#Override
public Object getAsObject(FacesContext facesContext, UIComponent component, String value) {
if (value == null || value.length() == 0) {
return null;
}
InvestigationController controller = (InvestigationController) facesContext.getApplication().getELResolver().
getValue(facesContext.getELContext(), null, "investigationController");
return controller.ejbFacade.find(getKey(value));
}
java.lang.Long getKey(String value) {
java.lang.Long key;
key = Long.valueOf(value);
return key;
}
String getStringKey(java.lang.Long value) {
StringBuilder sb = new StringBuilder();
sb.append(value);
return sb.toString();
}
#Override
public String getAsString(FacesContext facesContext, UIComponent component, Object object) {
if (object == null) {
return null;
}
if (object instanceof Investigation) {
Investigation o = (Investigation) object;
return getStringKey(o.getId());
} else {
throw new IllegalArgumentException("object " + object + " is of type "
+ object.getClass().getName() + "; expected type: " + InvestigationController.class.getName());
}
}
}
Later I changed it like this.
#FacesConverter("ixcon")
public static class InvestigationConverter implements Converter {
public InvestigationConverter() {
}
#Override
public Object getAsObject(FacesContext facesContext, UIComponent component, String value) {
if (value == null || value.length() == 0) {
return null;
}
InvestigationController controller = (InvestigationController) facesContext.getApplication().getELResolver().
getValue(facesContext.getELContext(), null, "investigationController");
return controller.getEjbFacade().find(getKey(value));
}
java.lang.Long getKey(String value) {
java.lang.Long key;
key = Long.valueOf(value);
return key;
}
String getStringKey(java.lang.Long value) {
StringBuilder sb = new StringBuilder();
sb.append(value);
return sb.toString();
}
#Override
public String getAsString(FacesContext facesContext, UIComponent component, Object object) {
if (object == null) {
return null;
}
if (object instanceof Investigation) {
Investigation o = (Investigation) object;
return getStringKey(o.getId());
} else {
throw new IllegalArgumentException("object " + object + " is of type "
+ object.getClass().getName() + "; expected type: " + InvestigationController.class.getName());
}
}
}
I used that converter in JSF pages like this.
<p:autoComplete converter="ixcon" widgetVar="aIx" id="acIx" forceSelection="true" value="#{investigationItemValueFlagController.investigation}" completeMethod="#{investigationController.completeItem}" var="ix" itemLabel="#{ix.name}" itemValue="#{ix}" size="30" style="width: 400px;">
<p:ajax process="acIx iif" update="iif tbl" event="itemSelect"/>
</p:autoComplete>