Storing a http session attribute in database - jsf

How can I pass an injected http session attribute (see below), along with other values (informe by the user) and save them using JPA?
The session attribute is correctly displayed and injected, but I need to pass it using the selected to be stored in the database (actually, it passess null).
The JSF:
<p:outputLabel value="UserID (the sessionAttribute):" for="userID" />
<p:inputText id="userID" value="#{userBean.myUser.xChave}" title="userID" />
<p:outputLabel value="Type the Reason:" for="reason" />
<p:inputText id="reason" value="#{viagensController.selected.reason}" />
<!-- updated (just the call to the action method: -->
<p:commandButton actionListener="#{viagensController.saveNew}" value="#{viagensBundle.Save}" update="display,:ViagensListForm:datalist,:growl" oncomplete="handleSubmit(xhr,status,args,ViagensCreateDialog);" />
The bean:
import java.io.Serializable;
import javax.annotation.PostConstruct;
import javax.enterprise.context.SessionScoped;
import javax.faces.context.FacesContext;
import javax.inject.Named;
#Named(value = "userBean")
#SessionScoped
public class UserBean implements Serializable {
private bean_login myUser;
public bean_login getMyUser() {
return myUser;
}
public void setMyUser(bean_login myUser) {
this.myUser = myUser;
}
#PostConstruct
public void init() {
String uid = FacesContext.getCurrentInstance().getExternalContext().getSessionMap().get("xChave").toString();
myUser = new bean_login();
myUser.setxChave(uid);
System.out.print("from init:" + myUser.toString());
}
}
The AbstractFacade:
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) {{ /*impl. ommited*/ }
public List<T> findAll() {{ /*impl. ommited*/ }
public List<T> findRange(int[] range) { /*impl. ommited*/ }
public int count() { /*impl. ommited*/ }
}
The AbstractController (for the selected in JSF above and other methods):
public abstract class AbstractController<T> {
#Inject
private AbstractFacade<T> ejbFacade;
private Class<T> itemClass;
private T selected;
private Collection<T> items;
private enum PersistAction {
CREATE,
DELETE,
UPDATE
}
public AbstractController() {
}
public AbstractController(Class<T> itemClass) {
this.itemClass = itemClass;
}
public T getSelected() {
return selected;
}
// Pass in the currently selected item
public void setSelected(T selected) {
this.selected = selected;
}
protected void setEmbeddableKeys() {
}
protected void initializeEmbeddableKey() {
}
public Collection<T> getItems() {
if (items == null) {
items = this.ejbFacade.findAll();
}
return items;
}
// Pass in collection of items
public void setItems(Collection<T> items) {
this.items = items;
}
// Apply changes to an existing item to the data layer.
public void save(ActionEvent event) {
String msg = ResourceBundle.getBundle("/viagensBundle").getString(itemClass.getSimpleName() + "Updated");
persist(PersistAction.UPDATE, msg);
}
// Store a new item in the data layer.
public void saveNew(ActionEvent event) {
String msg = ResourceBundle.getBundle("/viagensBundle").getString(itemClass.getSimpleName() + "Created");
persist(PersistAction.CREATE, msg);
if (!isValidationFailed()) {
items = null; // Invalidate list of items to trigger re-query.
}
}
public void delete(ActionEvent event) {/*implementations ommited*/ }
private void persist(PersistAction persistAction, String successMessage) {
if (selected != null) {
this.setEmbeddableKeys();
try {
if (persistAction != PersistAction.DELETE) {
this.ejbFacade.edit(selected);
} else {
this.ejbFacade.remove(selected);
}
JsfUtil.addSuccessMessage(successMessage);
} catch (EJBException ex) {
String msg = "";
Throwable cause = JsfUtil.getRootCause(ex.getCause());
if (cause != null) {
if (cause instanceof ConstraintViolationException) {
ConstraintViolationException excp = (ConstraintViolationException) cause;
for (ConstraintViolation s : excp.getConstraintViolations()) {
JsfUtil.addErrorMessage(s.getMessage());
}
} else {
msg = cause.getLocalizedMessage();
if (msg.length() > 0) {
JsfUtil.addErrorMessage(msg);
} else {
JsfUtil.addErrorMessage(ex, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured"));
}
}
}
} catch (Exception ex) {
Logger.getLogger(this.getClass().getName()).log(Level.SEVERE, null, ex);
JsfUtil.addErrorMessage(ex, ResourceBundle.getBundle("/viagensBundle").getString("PersistenceErrorOccured"));
}
}
}
// Creates a new instance of an underlying entity and assigns it to Selected property.
public T prepareCreate(ActionEvent event) {
T newItem;
try {
newItem = itemClass.newInstance();
this.selected = newItem;
initializeEmbeddableKey();
return newItem;
} catch (InstantiationException ex) {
Logger.getLogger(this.getClass().getName()).log(Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
Logger.getLogger(this.getClass().getName()).log(Level.SEVERE, null, ex);
}
return null;
}
// Inform the user interface whether any validation error exist on a page.
public boolean isValidationFailed() {
return JsfUtil.isValidationFailed();
}
// Retrieve all messages as a String to be displayed on the page.
public String getComponentMessages(String clientComponent, String defaultMessage) {
return JsfUtil.getComponentMessages(clientComponent, defaultMessage);
}
}
Thanks in advance.
updated:
The ViagensController:
#Named(value = "viagensController")
#ViewScoped
public class ViagensController extends AbstractController<Viagens> implements Serializable {
//generics:passing JPA Entity class, where the 'reason' in JSF is defined
public ViagensController() {
super(Viagens.class);
}
}

Need to override the save method passing the injected http session value :
#ManagedBean(name = "riscosController")
#ViewScoped
public class RiscosController extends AbstractController<Riscos> {
#EJB
private RiscosFacade ejbFacade;
#Inject
#SessionChave
private String iSessionChave;
private String sessionChave;
private UorPosController matriculaController;
private UorPosController informanteController;
public String getSessionChave(String chave) {
if (sessionChave.isEmpty()) {
sessionChave = iSessionChave;
}
return sessionChave;
}
public void setSessionChave(String sessionChave) {
this.sessionChave = sessionChave;
}
#PostConstruct
#Override
public void init() {
super.setFacade(ejbFacade);
FacesContext context = FacesContext.getCurrentInstance();
matriculaController = context.getApplication().evaluateExpressionGet(context, "#{uorPosController}", UorPosController.class);
informanteController = context.getApplication().evaluateExpressionGet(context, "#{uorPosController}", UorPosController.class);
sessionChave = "";
}
#Override
public void saveNew(ActionEvent event) {
this.getSelected().setObs(this.getSessionChave(sessionChave));
super.saveNew(event);
}
}

Related

SimpleJSFNavigationHandler cannot be cast to javax.faces.application.ConfigurableNavigationHandler

I'm migrating a JSF 1.2 project to JSF 2 and PrimeFaces 6 with Ultima layout.
When using Ultima layout, I get the below exception:
SimpleJSFNavigationHandler cannot be cast to javax.faces.application.ConfigurableNavigationHandler.
How to fix it?
Below is the SimpleJSFNavigationHandler.
import java.io.IOException;
import javax.faces.FacesException;
import javax.faces.application.NavigationHandler;
import javax.faces.application.ViewHandler;
import javax.faces.component.UIViewRoot;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import org.springframework.web.jsf.DecoratingNavigationHandler;
public class SimpleJSFNavigationHandler extends DecoratingNavigationHandler {
public static final String DEFAULT_REDIRECT_PREFIX = "redirect:";
public static final String DEFAULT_FORWARD_PREFIX = "/";
private String redirectPrefix = DEFAULT_REDIRECT_PREFIX;
private String forwardPrefix = DEFAULT_FORWARD_PREFIX;
public SimpleJSFNavigationHandler() {
}
public SimpleJSFNavigationHandler(NavigationHandler originalNavigationHandler) {
super(originalNavigationHandler);
}
#Override
public void handleNavigation(FacesContext facesContext, String fromAction, String outcome, NavigationHandler originalNavigationHandler) {
if (outcome != null && outcome.startsWith(redirectPrefix)) {
ExternalContext externalContext = facesContext.getExternalContext();
ViewHandler viewHandler = facesContext.getApplication().getViewHandler();
String url = outcome.substring(redirectPrefix.length());
String urlParams="";
if(url.indexOf("?")>0)
urlParams = url.substring(url.indexOf("?"));
String redirectPath = viewHandler.getActionURL(facesContext, url);
try {
//System.out.println("MMMMMMMMMMMMMMMM:::::::::::::::::" + urlParams);
externalContext.redirect(externalContext.encodeActionURL(redirectPath+urlParams));
} catch (IOException e) {
throw new FacesException(e.getMessage(), e);
}
facesContext.responseComplete();
} else if (outcome != null && outcome.startsWith(forwardPrefix)) {
ViewHandler viewHandler = facesContext.getApplication().getViewHandler();
//create new view
String newViewId = outcome.substring(forwardPrefix.length());
if (newViewId.length()>0 && newViewId.charAt(0)!='/') {
newViewId = "/" + newViewId;
}
UIViewRoot viewRoot = viewHandler.createView(facesContext, newViewId);
viewRoot.setViewId(newViewId);
facesContext.setViewRoot(viewRoot);
facesContext.renderResponse();
} else {
callNextHandlerInChain(facesContext, fromAction, outcome, originalNavigationHandler);
}
}
}
You don't need Spring's DecoratingNavigationHandler. You can just use JSF's own ConfigurableNavigationHandlerWrapper.
public class SimpleJSFNavigationHandler extends ConfigurableNavigationHandlerWrapper {
private ConfigurableNavigationHandler wrapped;
public SimpleJSFNavigationHandler(ConfigurableNavigationHandler wrapped) {
this.wrapped = wrapped;
}
#Override
public void handleNavigation(FacesContext facesContext, String fromAction, String outcome) {
if (...) {
// Your original code here.
} else if (...) {
// Your original code here.
} else {
// Update only the last else part as below.
getWrapped().handleNavigation(facesContext, fromAction, outcome);
}
}
#Override
public ConfigurableNavigationHandler getWrapped() {
return wrapped;
}
}
In the upcoming JSF 2.3 this can even be further simplified as per spec issue 1429 which should further reduce boilerplate code in FacesWrapper implementations.
public class SimpleJSFNavigationHandler extends ConfigurableNavigationHandlerWrapper {
public SimpleJSFNavigationHandler(ConfigurableNavigationHandler wrapped) {
super(wrapped);
}
#Override
public void handleNavigation(FacesContext facesContext, String fromAction, String outcome) {
if (...) {
// Your original code here.
} else if (...) {
// Your original code here.
} else {
// Update only the last else part as below.
getWrapped().handleNavigation(facesContext, fromAction, outcome);
}
}
}

#ManagedProperty - access properties Injected from one view scoped bean into another view scoped bean

I have injected one view scoped bean into another view scoped bean , and I can access some properties of the first bean but others appear as null in #PostContruct. How can I see their real value?
Thanks in advance
Update:
I can only see the value of properties updated in #PostContruct of the first bean and not others
Bean 1(SelectOfferMpans)
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package sofyc.backingbean.offer;
import es.iberdrola.configuration.LogginManager;
import java.io.Serializable;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.annotation.PostConstruct;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import javax.faces.model.SelectItem;
import org.apache.log4j.Logger;
import sofyc.bean.BeanInstanceLocator;
import sofyc.bean.IOffersBean;
import sofyc.corejsf.SofycNavigation;
import sofyc.corejsf.SofycParamNames;
import sofyc.utils.JSFHelper;
import sofyc.valueobject.CustomerFindVO;
import sofyc.valueobject.MpanVO;
import sofyc.valueobject.OfferSitesVO;
#ManagedBean
#ViewScoped
public class SelectOfferMpans implements Serializable{
/**
* Logger.
*/
private static Logger log = LogginManager.getLogger(SelectOfferMpans.class.getName());
static {
adq_ren_types = new String[2];
}
private final String ID_OFFER_SELECT_MPANS_FORM = "selectMpans";
private String menuOrigin;
/**
* Parametro de busqueda del formulario.
*/
private String registrationNumber;
private List<CustomerFindVO> customerfoundList;
private CustomerFindVO customerfound;
private String companyRegNo;
private String customerId;
private CustomerFindVO selectedCustomer;
private List<OfferSitesVO> offerSites;
private List<OfferSitesVO> filteredSites;
private OfferSitesVO selectedSite;
private OfferSitesVO[] selectedSites;
private List<MpanVO> siteMpans;
private SelectItem[] hh_nhh_List;
private SelectItem[] adq_ren_List;
private final static String[] adq_ren_types;
private Map<String,String> hh_nhh_types;
public Map<String, String> getHh_nhh_types() {
return hh_nhh_types;
}
public void setHh_nhh_types(Map<String, String> hh_nhh_types) {
this.hh_nhh_types = hh_nhh_types;
}
public SelectItem[] getHh_nhh_List() {
return hh_nhh_List;
}
public void setHh_nhh_List(SelectItem[] hh_nhh_List) {
this.hh_nhh_List = hh_nhh_List;
}
public SelectItem[] getAdq_ren_List() {
return adq_ren_List;
}
public void setAdq_ren_List(SelectItem[] adq_ren_List) {
this.adq_ren_List = adq_ren_List;
}
public List<OfferSitesVO> getOfferSites() {
return offerSites;
}
public void setOfferSites(List<OfferSitesVO> offerSites) {
this.offerSites = offerSites;
}
public List<OfferSitesVO> getFilteredSites() {
return filteredSites;
}
public void setFilteredSites(List<OfferSitesVO> filteredSites) {
this.filteredSites = filteredSites;
}
public OfferSitesVO getSelectedSite() {
return selectedSite;
}
public void setSelectedSite(OfferSitesVO selectedSite) {
this.selectedSite = selectedSite;
}
public OfferSitesVO[] getSelectedSites() {
return selectedSites;
}
public void setSelectedSites(OfferSitesVO[] selectedSites) {
this.selectedSites = selectedSites;
}
public List<MpanVO> getSiteMpans() {
return siteMpans;
}
public void setSiteMpans(List<MpanVO> siteMpans) {
this.siteMpans = siteMpans;
}
public CustomerFindVO getSelectedCustomer() {
return selectedCustomer;
}
public void setSelectedCustomer(CustomerFindVO selectedCustomer) {
this.selectedCustomer = selectedCustomer;
}
public String getCustomerId() {
return customerId;
}
public void setCustomerId(String customerId) {
this.customerId = customerId;
}
public String getCompanyRegNo() {
return companyRegNo;
}
public void setCompanyRegNo(String companyRegNo) {
this.companyRegNo = companyRegNo;
}
public List<CustomerFindVO> getCustomerfoundList() {
return customerfoundList;
}
public void setCustomerfoundList(List<CustomerFindVO> customerfoundList) {
this.customerfoundList = customerfoundList;
}
public String getRegistrationNumber() {
return registrationNumber;
}
public void setRegistrationNumber(String registrationNumber) {
this.registrationNumber = registrationNumber;
}
public CustomerFindVO getCustomerfound() {
return customerfound;
}
public void setCustomerfound(CustomerFindVO customerfound) {
this.customerfound = customerfound;
}
public String getMenuOrigin() {
return menuOrigin;
}
public void setMenuOrigin(String menuOrigin) {
this.menuOrigin = menuOrigin;
}
/**
* Creates a new instance of SelectOfferMpans
*/
public SelectOfferMpans() {
}
#PostConstruct
public void init() {
try{
if(log.isDebugEnabled()) {
log.debug("INIT");
}
if (getMenuOrigin() == null) {
setMenuOrigin(JSFHelper.getParameterFromView("OPTION"));
if (getMenuOrigin() == null) {
setMenuOrigin((String) JSFHelper.getParameterFromRequest("OPTION"));
}
if (log.isDebugEnabled()) {
log.debug("CREATE OFFER --> guardado en VIEW VAR menuOrigin el "
+ "valor recuperado en la Request del parametro OPTION:: "
+ getMenuOrigin());
}
}
adq_ren_types[0] = "Adquisitions";
adq_ren_types[1] = "Renews";
this.setHh_nhh_types(cargaHHNHH());
//hh_nhh_List = createFilterOptions(hh_nhh_types);
hh_nhh_List = createFilterOptions1(hh_nhh_types,true);
adq_ren_List = createFilterOptions(adq_ren_types);
}catch(Exception e)
{
log.error("SearchCustomer:Init", e);
JSFHelper.addErrorMessage("messagesError", e.getMessage());
}
}
public void findCustomer() throws Exception {
CustomerFindVO customer=null;
try{
if (log.isDebugEnabled()) {
log.debug("Searching Customer....");
}
IOffersBean offersBean = BeanInstanceLocator.getOffersBean();
customerfound = offersBean.searchCustomer(companyRegNo);
if (customerfound!=null){
this.setOfferSites(offersBean.getCustomerSites(customerfound.getCustomerId()));
}
else{
this.setOfferSites(null);
JSFHelper.addErrorMessage(ID_OFFER_SELECT_MPANS_FORM, "Error searching customer");
}
if (log.isDebugEnabled()) {
log.debug("Customer Data Found");
}
} catch (Throwable t) {
log.error("findCustomer:", t);
JSFHelper.addErrorMessage(ID_OFFER_SELECT_MPANS_FORM, "Error searching customer");
}
}
public String goToOffers(){
try{
JSFHelper.addParamToRequest(SofycParamNames.CUSTOMER_ID, customerfound.getCustomerId());
JSFHelper.addParamToRequest(SofycParamNames.OPTION, this.getMenuOrigin());
return SofycNavigation.VIEW_CREATE_OFFERS_PAGE;
} catch (Throwable t) {
log.error("goToOffers:", t);
JSFHelper.addErrorMessage(ID_OFFER_SELECT_MPANS_FORM, "Error navigating to offers page");
return null;
}
}
private SelectItem[] createFilterOptions(String[] data) {
SelectItem[] options = new SelectItem[data.length + 1];
options[0] = new SelectItem("", "Select");
for(int i = 0; i < data.length; i++) {
options[i + 1] = new SelectItem(data[i], data[i]);
}
return options;
}
private SelectItem[] createFilterOptions1(Map<String,String> data, boolean select) {
//SelectItem[] options = new SelectItem[data.size() + 1];
SelectItem[] options;
int i = 0;
if (select==true) {
options = new SelectItem[data.size() + 1];
options[i] = new SelectItem("", "Select");
i++;
}
else{
options = new SelectItem[data.size()];
}
for (Map.Entry e: data.entrySet()) {
options[i] = new SelectItem(e.getKey().toString(), e.getValue().toString());
//options[i + 1] = new SelectItem(e.getValue().toString(),e.getKey().toString());
i++;
}
return options;
}
private Map<String,String> cargaHHNHH() {
Map<String,String> hh_nhh_types= new HashMap<String,String>();
hh_nhh_types.put("HH","HH");
hh_nhh_types.put("NHH","NHH");
return hh_nhh_types;
}
}
Bean 2(CreateOffer) property selectedSites of the first bean appears always as null and It's loaded in findCustomer Method.
package sofyc.backingbean.offer;
import es.iberdrola.configuration.LogginManager;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import javax.annotation.PostConstruct;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.ViewScoped;
import javax.faces.context.FacesContext;
import javax.faces.model.SelectItem;
import org.apache.log4j.Logger;
import org.primefaces.event.SelectEvent;
import org.primefaces.event.ToggleEvent;
import org.primefaces.event.UnselectEvent;
import sofyc.bean.BeanInstanceLocator;
import sofyc.bean.IOffersBean;
import sofyc.utils.JSFHelper;
import sofyc.valueobject.CustomerVO;
import sofyc.valueobject.MddMeasurementClassVO;
import sofyc.valueobject.MpanVO;
import sofyc.valueobject.OfferSitesVO;
import sofyc.valueobject.ProfileClassVO;
import sofyc.valueobject.SiteVO;
import sofyc.valueobject.TradebookVO;
#ManagedBean
#ViewScoped
public class CreateOffer implements Serializable {
private static Logger log = LogginManager.getLogger(CreateOffer.class.getName());
/**
* Creates a new instance of CreateOffer
*/
static {
adq_ren_types = new String[2];
}
#ManagedProperty(value="#{selectOfferMpans.selectedSites}")
//#ManagedProperty(value="#{selectOfferMpans}")
//private SelectOfferMpans selectOfferMpans;
private OfferSitesVO[] selectedSites;
/*public void setSelectOfferMpans(SelectOfferMpans selectOfferMpans) {
this.selectOfferMpans = selectOfferMpans;
}*/
public void setSelectedSites(OfferSitesVO[] selectedSites) {
this.selectedSites = selectedSites;
}
/**
* Valores posibles de donde viene la pagina.
*/
private final String CREATE_OFFERS_OPTION = "CREATE";
private final String OFFERS_OPTION = "OFFERS";
private String menuOrigin;
/**
* Corresponde a la columna CUSTOMER_ID.
*/
private Integer customerId;
private Map<String,String> managers;
private Date offerFromDate;
private Date offerToDate;
private Date expiryDate;
private Integer tradeBookId;
private String creditScore;
private String consultantMargin;
private String spMargin;
private Integer productId;
private Integer profileClassId;
private String measurementClassId;
private Integer curveId;
/**
* Customer selected.
*/
private CustomerVO customer;
private List<OfferSitesVO> offerSites;
private List<OfferSitesVO> filteredSites;
private OfferSitesVO selectedSite;
private OfferSitesVO[] selectedSites1;
public OfferSitesVO[] getSelectedSites1() {
return selectedSites1;
}
public void setSelectedSites1(OfferSitesVO[] selectedSites1) {
this.selectedSites1 = selectedSites1;
}
private List<MpanVO> siteMpans;
//private final static String[] hh_nhh_types;
private Map<String,String> hh_nhh_types;
private final static String[] adq_ren_types;
//private final static String[] cotOfferTypes;
private Map<String,String> cotOfferTypes;
private Map<String,String> offerType;
private Map<String,String> loadCurve;
//private final static String[] offerType;
//private final static String[] loadCurve;
private SelectItem[] hh_nhh_List;
private SelectItem[] adq_ren_List;
private SelectItem[] cotOfferList;
private String cotOfferSelection;
private String comcOfferSelection;
private String copcOfferSelection;
private String offerTypeSelection;
private String loadCurveSelection;
//La oferta es de tipo HH o NHH
private String offerHH_NHH;
private SelectItem[] offerTypeList;
private SelectItem[] loadCurveList;
/**
* Site selected.
*/
private SiteVO site;
private MpanVO mpan;
private List<SiteVO> sites;
private List<MpanVO> mpans;
private List<TradebookVO> tradeBookList;
private Map<String,Integer> ProductList;
private List<ProfileClassVO> profileClassList;
private List<MddMeasurementClassVO> measurementClassList;
private Map<String,Integer> CurveList;
#PostConstruct
public void init() {
if(log.isDebugEnabled()) {
log.debug("********************** CreateOffer::init **********************");
}
if (getMenuOrigin() == null) {
setMenuOrigin(JSFHelper.getParameterFromView("OPTION"));
if (getMenuOrigin() == null) {
setMenuOrigin((String) JSFHelper.getParameterFromRequest("OPTION"));
}
if (log.isDebugEnabled()) {
log.debug("CREATE OFFER --> guardado en VIEW VAR menuOrigin el "
+ "valor recuperado en la Request del parametro OPTION:: "
+ getMenuOrigin());
}
}
adq_ren_types[0] = "Adquisitions";
adq_ren_types[1] = "Renews";
//Valor por defecto de COT
cotOfferSelection="0";
//Valor por defecto de COMC
comcOfferSelection="0";
//Valor por defecto de COPC
copcOfferSelection="0";
//Valor por defecto de OfferType
offerTypeSelection="0";
//Valor por defecto de loadCurve
loadCurveSelection="0";
offerHH_NHH="NHH";
this.setHh_nhh_types(cargaHHNHH());
//hh_nhh_List = createFilterOptions(hh_nhh_types);
hh_nhh_List = createFilterOptions1(hh_nhh_types,true);
adq_ren_List = createFilterOptions(adq_ren_types);
//cotOfferList = createFilterOptions(cotOfferTypes);
this.setCotOfferTypes(cargaCOT());
cotOfferList = createFilterOptions1(cotOfferTypes,false);
this.setOfferType(cargaofferType());
offerTypeList = createFilterOptions1(offerType,false);
this.setLoadCurve(cargaloadCurve());
loadCurveList = createFilterOptions1(loadCurve,false);
populateRequestParamsInViewVars();
initCustomerInfo();
CurveList = new LinkedHashMap<String,Integer>();
ProductList = new LinkedHashMap<String,Integer>();
//hh_nhh_List = new LinkedHashMap<String,Integer>();
profileClassId=2;
measurementClassId="A";
curveId=1;
tradeBookId=3;
profileClassList = new ArrayList<ProfileClassVO>();
measurementClassList = new ArrayList<MddMeasurementClassVO>();
tradeBookList = new ArrayList<TradebookVO>();
loadProfileClass();
loadMeasurementClass();
loadTradeBook();
}
public void onRowSelect(SelectEvent event) {
//FacesMessage msg = new FacesMessage("Car Selected", ((Car) event.getObject()).getModel());
//FacesContext.getCurrentInstance().addMessage(null, msg);
//event.getComponent().
}
public void onRowUnselect(UnselectEvent event) {
//FacesMessage msg = new FacesMessage("Car Unselected", ((Car) event.getObject()).getModel());
//FacesContext.getCurrentInstance().addMessage(null, msg);
}
public String getOfferTypeSelection() {
return offerTypeSelection;
}
public void setOfferTypeSelection(String offerTypeSelection) {
this.offerTypeSelection = offerTypeSelection;
}
public String getLoadCurveSelection() {
return loadCurveSelection;
}
public void setLoadCurveSelection(String loadCurveSelection) {
this.loadCurveSelection = loadCurveSelection;
}
public SelectItem[] getOfferTypeList() {
return offerTypeList;
}
public void setOfferTypeList(SelectItem[] offerTypeList) {
this.offerTypeList = offerTypeList;
}
public SelectItem[] getLoadCurveList() {
return loadCurveList;
}
public void setLoadCurveList(SelectItem[] loadCurveList) {
this.loadCurveList = loadCurveList;
}
public List<ProfileClassVO> getProfileClassList() {
return profileClassList;
}
public void setProfileClassList(List<ProfileClassVO> ProfileClassList) {
this.profileClassList = ProfileClassList;
}
public MpanVO getMpan() {
return mpan;
}
public void setMpan(MpanVO mpan) {
this.mpan = mpan;
}
public List<MpanVO> getMpans() {
return mpans;
}
public void setMpans(List<MpanVO> mpans) {
this.mpans = mpans;
}
public List<SiteVO> getSites() {
return sites;
}
public void setSites(List<SiteVO> sites) {
this.sites = sites;
}
public CustomerVO getCustomer() {
return customer;
}
public void setCustomer(CustomerVO customer) {
this.customer = customer;
}
public SiteVO getSite() {
return site;
}
public void setSite(SiteVO site) {
this.site = site;
}
public String getCreditScore() {
return creditScore;
}
public void setCreditScore(String creditScore) {
this.creditScore = creditScore;
}
public String getConsultantMargin() {
return consultantMargin;
}
public void setConsultantMargin(String consultantMargin) {
this.consultantMargin = consultantMargin;
}
public String getSpMargin() {
return spMargin;
}
public void setSpMargin(String spMargin) {
this.spMargin = spMargin;
}
public List<OfferSitesVO> getOfferSites() {
return offerSites;
}
public void setOfferSites(List<OfferSitesVO> offerSites) {
this.offerSites = offerSites;
}
public List<OfferSitesVO> getFilteredSites() {
return filteredSites;
}
public void setFilteredSites(List<OfferSitesVO> filteredSites) {
this.filteredSites = filteredSites;
}
public SelectItem[] getAdq_ren_List() {
return adq_ren_List;
}
public void setAdq_ren_List(SelectItem[] adq_ren_List) {
this.adq_ren_List = adq_ren_List;
}
public SelectItem[] getHh_nhh_List() {
return hh_nhh_List;
}
public void setHh_nhh_List(SelectItem[] hh_nhh_List) {
this.hh_nhh_List = hh_nhh_List;
}
public Map<String, String> getHh_nhh_types() {
return hh_nhh_types;
}
public void setHh_nhh_types(Map<String, String> hh_nhh_types) {
this.hh_nhh_types = hh_nhh_types;
}
public Map<String, String> getOfferType() {
return offerType;
}
public void setOfferType(Map<String, String> offerType) {
this.offerType = offerType;
}
public Map<String, String> getLoadCurve() {
return loadCurve;
}
public void setLoadCurve(Map<String, String> loadCurve) {
this.loadCurve = loadCurve;
}
public String getOfferHH_NHH() {
return offerHH_NHH;
}
public void setOfferHH_NHH(String OfferHH_NHH) {
this.offerHH_NHH = OfferHH_NHH;
}
public String getMenuOrigin() {
return menuOrigin;
}
public void setMenuOrigin(String menuOrigin) {
this.menuOrigin = menuOrigin;
}
/**
* Metodo que inicializa los valores del cliente.
*/
private void initCustomerInfo() {
this.setSites(new ArrayList<SiteVO>());
this.setMpans(new ArrayList<MpanVO>());
List<OfferSitesVO> offerSitesAux = new ArrayList<OfferSitesVO>();
FacesMessage msg = null;
try{
log.debug("initCustomerInfo: Start");
IOffersBean offerBean = BeanInstanceLocator.getOffersBean();
this.setCustomer(offerBean.getCustomer(customerId));
this.setManagers(offerBean.getManagerList());
if (CREATE_OFFERS_OPTION.equals(menuOrigin)){
if (selectedSites!=null){
for(int i = 0; i < selectedSites.length; i++){
offerSitesAux.add(selectedSites[i]);
}
}
this.setOfferSites(offerSitesAux);
}
else{
this.setOfferSites(offerBean.getCustomerSites(customerId));
}
this.setHh_nhh_List(offerBean.getHHNHHList());
this.setAdq_ren_List(offerBean.getAdquisitionRenewList());
}catch(Exception e){
msg = new FacesMessage("ERROR "+e.getMessage());
FacesContext.getCurrentInstance().addMessage(null, msg);
log.error("ERROR 2:: "+e.getMessage());
}
}
public Integer getProductId() {
return productId;
}
public void setProductId(Integer ProductId) {
this.productId = ProductId;
}
public List<TradebookVO> getTradeBookList() {
return tradeBookList;
}
public void setTradebookList(List<TradebookVO> tradeBookList) {
this.tradeBookList = tradeBookList;
}
public List<MddMeasurementClassVO> getMeasurementClassList() {
return measurementClassList;
}
public void setMeasurementClassList(List<MddMeasurementClassVO> MeasurementClassList) {
this.measurementClassList = MeasurementClassList;
}
public Integer getProfileClassId() {
return profileClassId;
}
public void setProfileClassId(Integer ProfileClassId) {
this.profileClassId = ProfileClassId;
}
public String getMeasurementClassId() {
return measurementClassId;
}
public void setMeasurementClassId(String MeasurementClassId) {
this.measurementClassId = MeasurementClassId;
}
public Integer getCurveId() {
return curveId;
}
public void setCurveId(Integer CurveId) {
this.curveId = CurveId;
}
public Integer getCustomerId() {
return customerId;
}
public void setCustomerId(Integer customerId) {
this.customerId = customerId;
}
public Date getOfferFromDate() {
return offerFromDate;
}
public void setOfferFromDate(Date OfferFromDate) {
this.offerFromDate = OfferFromDate;
}
public Date getOfferToDate() {
return offerToDate;
}
public void setOfferToDate(Date OfferToDate) {
this.offerToDate = OfferToDate;
}
public Integer getTradeBookId() {
return tradeBookId;
}
public void setTradeBookId(Integer tradeBookId) {
this.tradeBookId = tradeBookId;
}
public Map<String, String> getManagers() {
return managers;
}
public void setManagers(Map<String, String> managers) {
this.managers = managers;
}
public OfferSitesVO getSelectedSite() {
return selectedSite;
}
public void setSelectedSite(OfferSitesVO selectedSite) {
this.selectedSite = selectedSite;
}
public OfferSitesVO[] getSelectedSites() {
return selectedSites;
}
public List<MpanVO> getSiteMpans() {
return siteMpans;
}
public void setSiteMpans(List<MpanVO> siteMpans) {
this.siteMpans = siteMpans;
}
public String getCopcOfferSelection() {
return copcOfferSelection;
}
public void setCopcOfferSelection(String copcOfferSelection) {
this.copcOfferSelection = copcOfferSelection;
}
public String getComcOfferSelection() {
return comcOfferSelection;
}
public void setComcOfferSelection(String comcOfferSelection) {
this.comcOfferSelection = comcOfferSelection;
}
public Map<String, String> getCotOfferTypes() {
return cotOfferTypes;
}
public void setCotOfferTypes(Map<String, String> cotOfferTypes) {
this.cotOfferTypes = cotOfferTypes;
}
public String getCotOfferSelection() {
return cotOfferSelection;
}
public void setCotOfferSelection(String cotOfferSelection) {
this.cotOfferSelection = cotOfferSelection;
}
public Date getExpiryDate() {
return expiryDate;
}
public void setExpiryDate(Date expiryDate) {
this.expiryDate = expiryDate;
}
public SelectItem[] getCotOfferList() {
return cotOfferList;
}
public void setCotOfferList(SelectItem[] cotOfferList) {
this.cotOfferList = cotOfferList;
}
private void loadProfileClass() {
FacesMessage msg = null;
try{
log.debug("ProfileClass: Start");
IOffersBean offerBean = BeanInstanceLocator.getOffersBean();
List ProfileClassLista = offerBean.getProfileClassList(offerHH_NHH);
this.setProfileClassList((ArrayList<ProfileClassVO>) ProfileClassLista);
if(ProfileClassLista == null){
msg = new FacesMessage(FacesMessage.SEVERITY_ERROR,"There are not Profile_class elements",null);
FacesContext.getCurrentInstance().addMessage(null, msg);
}
log.debug("ProfileClassLista: end");
}catch(Exception e){
msg = new FacesMessage("ERROR "+e.getMessage());
FacesContext.getCurrentInstance().addMessage(null, msg);
log.error("ERROR 2:: "+e.getMessage());
}
}
private void loadMeasurementClass() {
FacesMessage msg;
try{
log.debug("MeasurementClass: Start");
IOffersBean offerBean = BeanInstanceLocator.getOffersBean();
List MeasureClassList = offerBean.getMeasurementClassList();
this.setMeasurementClassList((ArrayList<MddMeasurementClassVO>) MeasureClassList);
if(measurementClassList == null){
msg = new FacesMessage(FacesMessage.SEVERITY_ERROR,"There are not Measurement_class elements",null);
FacesContext.getCurrentInstance().addMessage(null, msg);
}
log.debug("loadMeasurementClass: end");
}catch(Exception e){
msg = new FacesMessage("ERROR "+e.getMessage());
FacesContext.getCurrentInstance().addMessage(null, msg);
log.error("ERROR 2:: "+e.getMessage());
}
}
}
I have injected one request scoped bean into another view scoped bean
You're not allowed to inject a bean into another bean of a wider scope.
As a rule, the following abominations are not allowed :)
#RequestScoped >> #ViewScoped
#ViewScoped >>#SessionScoped
#SessionScoped >> #ApplicationScoped
EDIT (Based on your update): Injecting a property of a bean, as against injecting the bean itself, will result in a static injection. The static injection means that the value that's injected into the target is what's available as at the time of injection. As a the time the following line was executed:
#ManagedProperty(value="#{selectOfferMpans.selectedSites}")
selectedSites is null. So what you should be doing there instead is injecting the entire bean
#ManagedProperty(value="#{selectOfferMpans}")
This way, you'll have access to the current value of whatever variable you're interested in

primefaces' selectOneMenu with converter not working with my backingBean

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.");
}

Dynamic Textfield In JSF 2.0

hey I am using the following code to create the number of text fields as the user wants
<h:form>
<p>Number Of News <h:inputText value="#{news.noOfFields}" /></p>
<ui:repeat value="#{news.values}" var="item">
<hr/>
News #{item.no}
<h:inputText value="#{item.news}" /><br/>
</ui:repeat>
<hr/>
<h:commandButton styleClass="btn btn-blue" action="#{news.submit}" value="Save" />
</h:form>
The managed bean news has a class News as
#ManagedBean
#SessionScoped
public class News
{
private String noOfFields;
private List<NewsVO> values;
public News()
{
this.values = new ArrayList<NewsVO>();
}
public String submit() {
for(NewsVO newsVO : this.values)
{
System.out.println(newsVO.getNews());
System.out.println(newsVO.getNo());
}
return null;
// save values in database
}
public String getNoOfFields() {
return noOfFields;
}
public List<NewsVO> getValues() {
return values;
}
public void setValues(List<NewsVO> values) {
this.values = values;
}
public void setNoOfFields(String noOfFields) {
this.values = new ArrayList<NewsVO>();
try {
for(int i=0;i<Integer.valueOf(noOfFields);i++)
{
NewsVO newsVO = new NewsVO();
newsVO.setNo(i+1);
this.values.add(newsVO);
}
this.noOfFields = noOfFields;
}
catch(NumberFormatException ex) {
/*values = new String[1];*/
noOfFields = "1";
}
}
}
The NewsVO is just a javaBean class as follows
public class NewsVO
{
public int no;
public String news;
public int getNo() {
return no;
}
public void setNo(int no) {
this.no = no;
}
public String getNews() {
return news;
}
public void setNews(String news) {
this.news = news;
}
}
The problem is the values inside the input Text doesn't get reflected on pressing the save button. It gives me null, even though, I have written something inside all the textfields.
<h:inputText value="#{item.news}" />
Everytime you push the submit button, all setters in the bean are called (including setNoOfFields()). In this setter you are resetting your list, that's why you loose your values. Since you only need to modify your list if there is a size change, here is a simple way doing it :
#ManagedBean
#SessionScoped
public class News
{
private int noOfFields;
private List<NewsVO> values;
public News()
{
this.values = new ArrayList<NewsVO>();
}
public String submit()
{
for(NewsVO newsVO : this.values)
{
System.out.println(newsVO.getNews());
System.out.println(newsVO.getNo());
}
return null;
// save values in database
}
public int getNoOfFields()
{
return noOfFields;
}
public List<NewsVO> getValues()
{
return values;
}
public void setValues(List<NewsVO> values)
{
this.values = values;
}
public void setNoOfFields(int noOfFields)
{
if(noOfFields < this.noOfFields)
{
for(int i = this.noOfFields - 1;i >= noOfFields;i--)
{
getValues().remove(i);
}
}
else if(noOfFields > this.noOfFields)
{
for(int i = this.noOfFields;i < noOfFields;i++)
{
NewsVO newsVO = new NewsVO();
newsVO.setNo(i+1);
getValues().add(newsVO);
}
}
}
}
Note : I've also changed your noOfFields getter/setter for simple int, JSF will do the conversion for you.

selectOneMenu in dataTable, default value not getting set properly

When I place a selectOneMenu within a dataTable, it does not display the correct default value in the selectOneMenu. The datatable is bound to a list of POJO's. The POJO entity Badge references a POJO entity we will call Facility. This Facility should be the selected value of the selectOneMenu in the row (the row being each Badge).
The following is my simple example of a table:
<h:dataTable id="examp" value="#{managedBean.badges}" var="badge">
<h:column rowHeader="rowie">
<h:selectOneMenu value="#{badge.facility}" id="col1">
<f:converter converterId="facilityConverter" />
<f:selectItems value="#{managedBean.facilities}"
/>
</h:selectOneMenu>
</h:column>
</h:dataTable>
The selectItems are a List of SelectItem objects that are created at PostConstruct. These are within my managedbean that is in ViewScope.
public class ListBadges extends BaseBean {
private List<Badge> badges = new ArrayList<Badge>();
private List<SelectItem> facilities = new ArrayList<SelectItem>();
public ListBadges() {
getBadgesFromDatabase(true);
}
#PostConstruct
public void init() {
if (facilities.size() <= 0) {
try {
List<Facility> facilityBeans = FacilityHelper.getFacilities();
for (Facility fac : facilityBeans) {
facilities.add(new SelectItem(fac, fac.getFacilityName()));
}
} catch (tException e) {
log.error("ListBadges.init(): " + e.getMessage());
e.printStackTrace();
}
}
}
public void getBadgesFromDatabase(boolean forceRefresh) {
if (forceRefresh || badges == null || badges.isEmpty())
badges = BadgeHelper.getBadgeList();
}
///
/// Bean Properties
///
public List<Badge> getBadges() {
return badges;
}
public void setBadges(List<Badge> badges) {
this.badges = badges;
}
public List<SelectItem> getFacilities() {
return facilities;
}
public void setFacilities(List<SelectItem> facilities) {
this.facilities = facilities;
}
Stepping through the code I confirm that all of the data is correct. In my converter, I verified that the arguments passed to getAsString is correct, so it should have identified the correct item.
#FacesConverter("facilityConverter")
public class FacilityConverter implements Converter {
#Override
public Object getAsObject(FacesContext context, UIComponent component, String from) {
try {
ELContext elContext = FacesContext.getCurrentInstance().getELContext();
ListBadges neededBean =
(ListBadges) context.getApplication().getELResolver().getValue(elContext, null, "managedBean");
long id = Long.parseLong(from);
for (SelectItem sItem : neededBean.getFacilities()) {
Facility facility = (Facility)sItem.getValue();
if (facility.getFacilityId() == id)
return facility;
}
} catch (Exception e) {
}
return null;
}
#Override
public String getAsString(FacesContext context, UIComponent component, Object value) {
try {
Facility facility = (Facility)value;
return facility.getFacilityId() + "";
} catch (Exception e) {
}
return null;
}
}
Here is the Facility class which has equals and hashCode implemented:
public class Facility implements java.io.Serializable {
private static final long serialVersionUID = 1L;
private long facilityId;
private String facilityName;
private String address1;
private String address2;
private String city;
private String state;
private String postalCode;
private String url;
private String phone;
private String siteManager;
public Facility() {
}
public Facility(String facilityName) {
this.facilityName = facilityName;
}
public Facility(String facilityName,
String address1, String address2, String city, String state,
String postalCode, String url, String phone, String siteManager) {
this.facilityName = facilityName;
this.address1 = address1;
this.address2 = address2;
this.city = city;
this.state = state;
this.postalCode = postalCode;
this.url = url;
this.phone = phone;
this.siteManager = siteManager;
}
public long getFacilityId() {
return this.facilityId;
}
public void setFacilityId(long facilityId) {
this.facilityId = facilityId;
}
public String getFacilityName() {
return this.facilityName;
}
public void setFacilityName(String facilityName) {
this.facilityName = facilityName;
}
public String getAddress1() {
return this.address1;
}
public void setAddress1(String address1) {
this.address1 = address1;
}
public String getAddress2() {
return this.address2;
}
public void setAddress2(String address2) {
this.address2 = address2;
}
public String getCity() {
return this.city;
}
public void setCity(String city) {
this.city = city;
}
public String getState() {
return this.state;
}
public void setState(String state) {
this.state = state;
}
public String getPostalCode() {
return this.postalCode;
}
public void setPostalCode(String postalCode) {
this.postalCode = postalCode;
}
public String getUrl() {
return this.url;
}
public void setUrl(String url) {
this.url = url;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getSiteManager() {
return siteManager;
}
public void setSiteManager(String siteManager) {
this.siteManager = siteManager;
}
#Override
public boolean equals(Object o) {
if (!(o instanceof Facility) || (o == null))
return false;
if (o == this)
return true;
Facility obj = (Facility)o;
return obj.getFacilityId() == this.getFacilityId();
}
#Override
public int hashCode() {
return (new Long(this.getFacilityId()).hashCode()) ^
((this.getAddress1() == null) ? 0 : this.getAddress1().hashCode()) ^
((this.getAddress2() == null) ? 0 : this.getAddress2().hashCode()) ^
((this.getCity() == null) ? 0 : this.getCity().hashCode()) ^
((this.getFacilityName() == null) ? 0 : this.getFacilityName().hashCode()) ^
((this.getPhone() == null) ? 0 : this.getPhone().hashCode()) ^
((this.getPostalCode() == null) ? 0 : this.getPostalCode().hashCode()) ^
((this.getSiteManager() == null) ? 0 : this.getSiteManager().hashCode()) ^
((this.getUrl() == null) ? 0 : this.getUrl().hashCode());
}
}
I would greatly appreciate any feedback.
I found the problem and it is nothing to do with JSF.
Eclipse was loading an older version of the Facility bean class that had a programmatic mistake in its equals method. Even after fully cleaning, republishing, cleaning the working directory, restarting the web server, and restarting Eclipse this old class was still getting loaded. I restarted my computer and finally the correct class was being loaded and this problem went away.
Thanks for looking at this BalusC. Without this blog article you wrote I would be completely lost! http://balusc.blogspot.com/2007/09/objects-in-hselectonemenu.html

Resources