Init not being called PrimeFaces - jsf

I have an init function in my ManagedBean that is view scoped. But I can't seem to get it to run when the page loads.
Its a private field in this Class
.............
package mike.food;
import java.io.IOException;
import java.io.Serializable;
import java.util.ArrayList;
import javax.annotation.PostConstruct;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import org.codehaus.jackson.JsonParseException;
import org.codehaus.jackson.annotate.JsonIgnoreProperties;
import org.codehaus.jackson.map.JsonMappingException;
#JsonIgnoreProperties(ignoreUnknown = true)
#ManagedBean(name = "nutrition")
#ViewScoped
public class NutritionixResponse implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1016196967087965738L;
private String total_hits;
private String max_score;
private ArrayList<Hits> hits;
private ArrayList<Hits> droppedhits;
public NutritionixResponse() throws JsonParseException, JsonMappingException, IOException {
}
#PostConstruct
public void init() {
this.droppedhits = new ArrayList<Hits>();
}
public String getTotal_hits() {
return total_hits;
}
public void setTotal_hits(String total_hits) {
this.total_hits = total_hits;
}
public String getMax_score() {
return max_score;
}
public void setMax_score(String max_score) {
this.max_score = max_score;
}
public ArrayList<Hits> getHits() {
return hits;
}
public void setHits(ArrayList<Hits> hits) {
this.hits = hits;
}
public ArrayList<Hits> getDroppedhits() {
return droppedhits;
}
public void setDroppedhits(ArrayList<Hits> droppedhits) {
this.droppedhits = droppedhits;
}
}
The main class
#JsonIgnoreProperties(ignoreUnknown = true)
#Manaents Serializable {
gedBean(name = "FoodClient")
#ViewScoped
public class FoodClient implem
/**
* Need to test something
*/
private static final long serialVersionUID = 3874520453001209544L;
private NutritionixResponse nurition;
And the page
<p:outputPanel id="dropArea">
<p:dataTable id="droppedfoodtable" var="food"
value="#{FoodClient.nurition.droppedhits}"

Related

setPropertyActionListener not working after a action

I have a grid with a list of objects and I am trying to create a basic CRUD. Updates and deletes are going quite fine and without any problems, however, when I try to perform a edit on the selected object the setPropertyActionListener that I've set isn't performing as expected. I've searched on several threads but no success.
Here goes my code:
On my crud-aplicacoes.html I gotta a grid and this is the code of my button where I set my setPropertyActionListener and also my action which goes to action ="editar-aplicacao" that is another page. I'm getting my property aplicacaoSelecionada always null.
<p:commandButton icon="ui-icon-pencil"
title="#{msg['label.button.editar']}" action="editar-aplicacao"
actionListener="#{aplicacoesMB.editarAplicacao}">
<f:setPropertyActionListener
target="#{aplicacoesMB.aplicacaoSelecionada}" value="#{app}" />
</p:commandButton>
My managed bean:
import java.util.ArrayList;
import java.util.List;
import javax.annotation.PostConstruct;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
import javax.faces.bean.SessionScoped;
import javax.faces.event.ActionEvent;
import javax.inject.Inject;
import org.primefaces.model.DualListModel;
import br.com.cnen.enums.SituacaoAplicacaoeEnum;
import br.com.cnen.vo.AplicacaoVO;
import br.com.cnen.vo.PerfilVO;
import br.com.cnen.web.facade.AplicacoesFacade;
#RequestScoped
#ManagedBean(name = "aplicacoesMB")
public class AplicacoesMB extends BeanAbstract {
private static final long serialVersionUID = 1L;
private List<AplicacaoVO> listaAplicacoes;
private AplicacaoVO aplicacaoSelecionada;
private PerfilVO perfilSelecionado;
private boolean edicaoExibicao;
#Inject
private AplicacoesFacade facadeAplicacao;
private List<PerfilVO> source;
private List<PerfilVO> target;
private DualListModel<PerfilVO> dualListPerfil;
#PostConstruct
public void carregarAplicacoes() {
listaAplicacoes = facadeAplicacao.listarTodos();
this.edicaoExibicao = false;
dualListPerfil = new DualListModel<PerfilVO>();
}
public List<PerfilVO> perfis() {
return facadeAplicacao.carregarComboPerfis();
}
public List<SituacaoAplicacaoeEnum> comboStatus() {
List<SituacaoAplicacaoeEnum> lista = new ArrayList<SituacaoAplicacaoeEnum>();
for (SituacaoAplicacaoeEnum current : SituacaoAplicacaoeEnum.values()) {
lista.add(current);
}
return lista;
}
public String editarAplicacao() {
this.edicaoExibicao = false;
pickList();
return "editar-aplicacao";
}
public String visualizarAplicacao() {
this.edicaoExibicao = true;
return "editar-aplicacao";
}
public void excluirAplicacao() {
facadeAplicacao.remover(this.aplicacaoSelecionada);
this.carregarAplicacoes();
this.addMensagem("A exclusão foi realizada com sucesso.", FacesMessage.SEVERITY_INFO);
}
public void bloquearAplicacao() {
this.aplicacaoSelecionada.setSituacao(SituacaoAplicacaoeEnum.BLOQUEADO);
facadeAplicacao.bloquear(this.aplicacaoSelecionada);
this.addMensagem("O bloqueio foi realizado com sucesso!", FacesMessage.SEVERITY_INFO);
}
public void desbloquearAplicacao() {
this.aplicacaoSelecionada
.setSituacao(SituacaoAplicacaoeEnum.DESBLOQUEADO);
facadeAplicacao.desbloquear(this.aplicacaoSelecionada);
this.addMensagem("O desbloqueio com sucesso!", FacesMessage.SEVERITY_INFO);
}
public void alterarAplicacao(){
facadeAplicacao.alterar(aplicacaoSelecionada);
this.addMensagem("O atualização foi realizada com sucesso!", FacesMessage.SEVERITY_INFO);
}
public void addPerfil(){
}
public void pickList(){
source = facadeAplicacao.carregarComboPerfis();
target = new ArrayList<PerfilVO>();
if(aplicacaoSelecionada!=null)
target = aplicacaoSelecionada.getListaPerfis();
dualListPerfil = new DualListModel<PerfilVO>(source, target);
}
/**
*
* Getts and setters
*
*/
public List<AplicacaoVO> getListaAplicacoes() {
return listaAplicacoes;
}
public AplicacaoVO getAplicacaoSelecionada() {
return aplicacaoSelecionada;
}
public void setAplicacaoSelecionada(AplicacaoVO aplicacaoSelecionada) {
this.aplicacaoSelecionada = aplicacaoSelecionada;
System.out.println("-> "+ aplicacaoSelecionada.getAplicaoId());
}
public PerfilVO getPerfilSelecionado() {
return perfilSelecionado;
}
public void setPerfilSelecionado(PerfilVO perfilSelecionado) {
this.perfilSelecionado = perfilSelecionado;
}
public boolean isEdicaoExibicao() {
return edicaoExibicao;
}
public List<PerfilVO> getSource() {
return source;
}
public void setSource(List<PerfilVO> source) {
this.source = source;
}
public List<PerfilVO> getTarget() {
return target;
}
public void setTarget(List<PerfilVO> target) {
this.target = target;
}
public DualListModel<PerfilVO> getDualListPerfil() {
return dualListPerfil;
}
public void setDualListPerfil(DualListModel<PerfilVO> dualListPerfil) {
this.dualListPerfil = dualListPerfil;
}
}
On my editarAplicacao() I can't access the property because it is always going null. Any thoughts on this issue?
Your concrete problem is caused by (ab)using actionListener instead of action to perform a business action. All actionListeners are invoked in the very same order as they have been attached on the component and then finally the action is invoked.
In other words, the <f:setPropertyActionListener> is in your particular case invoked after #{aplicacoesMB.editarAplicacao}, which totally explains the symptom you're seeing of the property not being set.
Fix actionListener to be action.
action="#{aplicacoesMB.editarAplicacao}"
Additionally, you can also get rid of <f:propertyActionListener> altogether and pass the property as action method argument.
action="#{aplicacoesMB.editarAplicacao(app)}"
with
public String editarAplicacao(AplicacaoVO aplicacaoSelecionada) {
// ...
}
See also:
Differences between action and actionListener
How can I pass selected row to commandLink inside dataTable?
You can replace
<f:setPropertyActionListener
target="#{aplicacoesMB.aplicacaoSelecionada}" value="#{app}" />
with
<f:attribute name="aplicacao" value="#{app}"></f:attribute>
and in your actionListenerMethod getting the attribute :
this.aplicacaoSelecionada = ((AplicacaoVO) event.getComponent().getAttributes().get("aplicacao"));

JSF Interceptor doesn't fire

Why my interceptor doesn't work?
MyLog.java
#Inherited
#InterceptorBinding
#Retention(RUNTIME)
#Target({METHOD, TYPE})
public #interface MyLog {
}
MyLogger.java
#Interceptor
#MyLog
#Priority(Interceptor.Priority.APPLICATION)
public class MyLogger {
#AroundInvoke
public Object log(InvocationContext context) throws Exception{
System.out.println("begin " + context.getMethod().getName());
Object obj = context.proceed();
System.out.println("end " + context.getMethod().getName());
return obj;
}
}
PerguntaController.java
import interceptor.MyLog;
import java.io.Serializable;
import java.util.List;
import javax.ejb.EJB;
import javax.ejb.EJBException;
import javax.inject.Named;
import javax.enterprise.context.SessionScoped;
#Named("PerguntaController")
#SessionScoped
public class PerguntaController implements Serializable {
#EJB
private PerguntaFacade ejbFacade;
#MyLog
public List<> getAll() {
return ejbFacade.getAll();
}
#MyLog
public void update(Pergunta pergunta) {
ejbFacade.update(pergunta);
}
}
PerguntaFacade.java
import interceptor.MyLog;
import java.util.List;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
#Stateless
public class PerguntaFacade {
#PersistenceContext(unitName = "WebApplicationPU")
private EntityManager em;
#MyLog
public List<Pergunta> getAll() {
return em.createQuery("SELECT p FROM Pergunta p", Pergunta.class).getResultList();
}
#MyLog
public void update(Pergunta pergunta) {
//do something
}
}
When use getAll and update (from PerguntaController) in jsf page doesn't fire the interceptor neither getAll and update on PerguntaFacade. What im doing wrong?
Solved.
On beans.xml with bean-discovery-mode="annotated" doesn't work.
Then change to bean-discovery-mode="all" and works fine.

Primefaces Picklist is always empty when using Postconstruct

My code below doesn't work, I'm using primefaces picklist and postconstruct annotation to init method with try catch block.
However my picklistbean is empty, I tried all the ways to make it work but none of them worked.
Can anyone provide me working example for picklist, or in my code am I missing something ?
I'm stuck to this problem for so long, I'll be glad if someone helps me.
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import javax.annotation.PostConstruct;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import javax.faces.context.FacesContext;
import org.primefaces.event.TransferEvent;
import org.primefaces.model.DualListModel;
import org.springframework.beans.factory.annotation.Autowired;
#ManagedBean(name = "pickListBeanTani")
#ViewScoped
public class PickListBeanTani implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
private DualListModel<TrvrTani> tanis;
#ManagedProperty(value = "#{TrvrTaniDAO}")
private TrvrTaniDAO tanidao;
public TrvrTaniDAO getTanidao() {
return tanidao;
}
public void setTanidao(TrvrTaniDAO tanidao) {
this.tanidao = tanidao;
}
private List<TrvrTani> sourcetani;
private List<TrvrTani> targettani;
#PostConstruct
public void init(){
try {
sourcetani = new ArrayList<TrvrTani>();
targettani = new ArrayList<TrvrTani>();
tanidao = new TrvrTaniDAO();
List<TrvrTani> taniList = tanidao.findAll();
System.out.println("tanılist" +taniList);
for (TrvrTani tani : taniList) {
sourcetani.add(new TrvrTani(tani.getTaniid(), tani.getTaniadi(), tani
.getTanikodu()));
}
tanis = new DualListModel<TrvrTani>(sourcetani, targettani);
} catch (Exception e) {
throw e;
}
}
public List<TrvrTani> getSourcetani() {
return sourcetani;
}
public void setSourcetani(List<TrvrTani> sourcetani) {
this.sourcetani = sourcetani;
}
public List<TrvrTani> getTargettani() {
return targettani;
}
public void setTargettani(List<TrvrTani> targettani) {
this.targettani = targettani;
}
public DualListModel<TrvrTani> getTanis() {
return tanis;
}
public void setTanis(DualListModel<TrvrTani> tanis) {
this.tanis = tanis;
}
public void onTransferTani(TransferEvent event) {
StringBuilder builder = new StringBuilder();
for (Object item : event.getItems()) {
builder.append(((TrvrTani) item).getTaniadi()).append("<br />");
int tanisize = tanis.getTarget().size();
System.out.println(" ************target************* : "
+ tanis.getTarget().size());
for (int h = 0; h < tanisize; h++) {
/* elemanin adi, id si ve kodu */
String taniadi = tanis.getTarget().get(h).getTaniadi();
System.out.println(" ************taniadi1************* : "
+ taniadi);
Long taniidp = tanis.getTarget().get(h).getTaniid();
System.out.println(" ************taniid2************* : "
+ taniidp);
String tanikodu = tanis.getTarget().get(h).getTanikodu();
System.out.println(" ************tanikodu3************* : "
+ tanikodu);
}
}
FacesMessage msgtani = new FacesMessage();
msgtani.setSeverity(FacesMessage.SEVERITY_INFO);
msgtani.setSummary("Tanı Eklendi");
msgtani.setDetail(builder.toString());
FacesContext.getCurrentInstance().addMessage(null, msgtani);
}
}
In PostContruct,your dao class doesn't inject in your bean.Try preRenderView when you want to initialize somethings in your bean.
Also dont use tanidao = new TrvrTaniDAO(); in your bean.TaniDao should be injected by spring with Autowired.
PreRenderView Example
EDIT
Also if you should inject TrvrTaniDAO with jsf managed property.
#ManagedProperty(value = "#{TrvrTaniDAO}")
private TrvrTaniDAO tanidao;

JSF - Getting NullPointerException in constructor when accessing getFacade()

this code produces NullPointerException. I don't know why. When I put the code from constructor to some other void with #PostConstruct - it works. I tried to initiate klientFacade - but it's not working, either. The class KlientFacade is #Stateless.
package view;
import entity.Klient;
import facade.KlientFacade;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import javax.annotation.PostConstruct;
import javax.ejb.EJB;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import static util.Messages.addFlashMessage;
#ManagedBean
#ViewScoped
public class ManageClient implements Serializable {
#EJB
private KlientFacade klientFacade;
private List<Klient> clientList;
public List<Klient> returnClientList(){
return getKlientFacade().findAll();
}
public ManageClient() {
clientList = new ArrayList<>();
clientList = returnClientList();
}
public String removeClient(Klient klient){
addFlashMessage("Klient ["+klient.getLogin()+"] został usunięty.");
getKlientFacade().remove(klient);
return "manage";
}
public List<Klient> getClientList() {
return clientList;
}
public void setClientList(List<Klient> clientList) {
this.clientList = clientList;
}
public KlientFacade getKlientFacade() {
return klientFacade;
}
public void setKlientFacade(KlientFacade klientFacade) {
this.klientFacade = klientFacade;
}
}
Well its because injected objects are not instantiated before the constructor call. Thats why you are not getting NPE with #PostConstruct annotation. If you still need to access injected fields in constructor, try http://openejb.apache.org/constructor-injection.html.

Hibernate + Spring Security

I am using spring 3 + spring security 3 + hibernate.
I have some problems with mapping classes. I don't know why, but some classes are mapped they can be used by Hibernate but at the same time some (which are used for Spring Security) are not!
forum-security.xml:
<beans:beans xmlns="http://www.springframework.org/schema/security"
xmlns:beans="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/security
http://www.springframework.org/schema/security/spring-security-3.0.xsd">
<http auto-config='true'>
<intercept-url pattern="/**" access="ROLE_USER" />
</http>
<authentication-manager>
<authentication-provider user-service-ref="userDetailsService"/>
</authentication-manager>
</beans:beans>
UserServiceImpl:
package forum.service;
import java.util.List;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.User;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import forum.domain.ForumUser;
#Service
public class UserServiceImpl implements UserService{
#Autowired private SessionFactory sessionFactory;
#Autowired private Assembler assembler;
public List<ForumUser> listAllUsers(){
return null;
}
public List<ForumUser> listUsersBySellingPont(){
return null;
}
#Transactional
public ForumUser getUserByUsername(String username){
Session session = sessionFactory.getCurrentSession();
List<ForumUser> users = session.createQuery("from ForumUser").list();
ForumUser result = null;
for(ForumUser user : users){
if(user.getUsername().equals(username))
result = user;
}
return result;
}
public void addUser(ForumUser user){
}
public void updateUser(ForumUser user){
}
public void deleteUser(Integer id){
}
}
Assembler:
package forum.service;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import forum.domain.ForumUser;
import forum.domain.UserDetailsImpl;
#Service("assembler")
public class Assembler {
#Transactional(readOnly = true)
UserDetailsImpl buildUserFromUserEntity(ForumUser userEntity) {
Integer id = userEntity.getId();
String username = userEntity.getUsername();
String password = userEntity.getPassword();
String email = userEntity.getEmail();
Date enabled = userEntity.getEnabled();
Date lastEntered = userEntity.getLastEntered();
Date registered = userEntity.getRegistered();
List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
for (GrantedAuthority role : userEntity.getAuthorities()) {
authorities.add(role);
}
UserDetailsImpl user = new UserDetailsImpl();
user.setId(id);
user.setUsername(username);
user.setPassword(password);
user.setEmail(email);
user.setEnabled(enabled);
user.setAuthorities(authorities);
user.setLastEntered(lastEntered);
user.setRegistered(registered);
return user;
}
}
And now classes that are not mapped by hibernate (other classes are mapped):
package forum.domain;
import java.util.Date;
import java.util.List;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.persistence.FetchType;
import javax.persistence.CascadeType;
import org.springframework.security.core.GrantedAuthority;
#Entity
#Table(name="users")
public class ForumUser {
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
#Column(name="id")
private Integer id;
#Column(name="username")
private String username;
#Column(name="password")
private String password;
#Column(name="email")
private String email;
#Column(name="registered")
private Date registered;
#Column(name="lastEntered")
private Date lastEntered;
#Column(name="enabled")
private Date enabled;
#OneToMany(cascade=CascadeType.REFRESH,fetch=FetchType.LAZY,mappedBy="forumUser")
private List<GrantedAuthority> authorities;
public Date getEnabled(){
return enabled;
}
public void setEnabled(Date enabled){
this.enabled = enabled;
}
public Integer getId(){
return id;
}
public void setId(Integer id){
this.id = id;
}
public String getUsername(){
return username;
}
public void setUsername(String username){
this.username = username;
}
public String getPassword(){
return password;
}
public void setPassword(String password){
this.password = password;
}
public String getEmail(){
return email;
}
public void setEmail(String email){
this.email = email;
}
public Date getRegistered(){
return registered;
}
public void setRegistered(Date registered){
this.registered = registered;
}
public Date getLastEntered(){
return lastEntered;
}
public void setLastEntered(Date lastEntered){
this.lastEntered = lastEntered;
}
public List<GrantedAuthority> getAuthorities() {
return authorities;
}
public void setAuthorities(List<GrantedAuthority> authorities){
this.authorities = authorities;
}
}
And the second class:
package forum.domain;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.ManyToOne;
import javax.persistence.CascadeType;
import javax.persistence.JoinColumn;
import javax.persistence.Table;
import org.springframework.security.core.GrantedAuthority;
#Entity
#Table(name="authorities")
public class Authority implements GrantedAuthority{
#ManyToOne(cascade=CascadeType.REFRESH,fetch=FetchType.LAZY)
#JoinColumn(name="userId")
private ForumUser forumUser;
#Column(name="authority")
private String authority;
public String getAuthority() {
return authority;
}
public void setAuthority(String authority) {
this.authority = authority;
}
}
So when I am trying to retrieve an user by username from DB (UserServiceImpl.getUserByUsername() from ForumUser), it throws
org.hibernate.hql.ast.QuerySyntaxException: ForumUser is not mapped [from ForumUser]
And if I change thir HQL to another, for example "from Forum" (it is another class, that is working) it will throw another exception, doesn't really matter what exactly, but the fact is that it mappes another class and can retrieve it.
How can I solve this problem?
Oh, I have found a solution! It all was because of my own inattention. I have forgotten to add new classes to a list of annotated persistent classes in my conf.

Resources