Getting javax.faces.FacesException: java.lang.NullPointerException - jsf-2

I am developing a Web App with following :
Glassfish v3.1.2
Eclipse Juno SR2
JPA EclipseLink2.0
JSF 2.0
I have different set of pages for the normal user and for admin users. While trying to setup a page filter during login i am getting this error in my login bean : javax.faces.FacesException: #{loginBean.login}: java.lang.NullPointerException
My whole login code works without this part
if (uGDB.validateGroup(username, adminGroup)) {
return "home.jsf?faces-redirect=true&includeViewParams=true";
}
return "normalHome.jsf?faces-redirect=true&includeViewParams=true"
;
What I am trying to do here is to get the Group Id of the user who is logging in and check if it is admin or not. And accordingly I want to direct the user to the corresponding page. This is because i have different set of pages for admin users and normal users. I don't want to use the Glassfish Realms because the end user doesn't require it.
Can someone please help me identify where I am going wrong in this. (Please excuse me for stupid mistakes I am just starting with such an development). Thanks a lot in advance!
Below is the code for my loginBean
package beans;
import java.io.Serializable;
import javax.ejb.EJB;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
import javax.faces.context.FacesContext;
import ejb.UserDaoBean;
import ejb.UserGroupDaoBean;
import model.User;
#ManagedBean(name = "loginBean")
#RequestScoped
public class LoginBean implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
#EJB
private UserDaoBean uDB;
private UserGroupDaoBean uGDB;
private User userId;
private int adminGroup = 1;
private String username;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String login() {
FacesContext context = FacesContext.getCurrentInstance();
if (uDB.validateUser(username)) {
userId = uDB.findUser(username);
context.getExternalContext().getSessionMap().put("userId", userId);
if (uGDB.validateGroup(username, adminGroup)) {
return "home.jsf?faces-redirect=true&includeViewParams=true";
}
return "normalHome.jsf?faces-redirect=true&includeViewParams=true";
} else {
FacesMessage message = new FacesMessage();
message.setSeverity(FacesMessage.SEVERITY_ERROR);
message.setSummary("Username doesn't exists! OR User is trying to login from someone else's account");
context.addMessage("", message);
return null;
}
}
public String logout() {
FacesContext.getCurrentInstance().getExternalContext()
.invalidateSession();
return "logout.jsf?faces-redirect=true";
}
}
Here is the complete error stack from Glassfish log
WARNING: #{loginBean.login}: java.lang.NullPointerException
javax.faces.FacesException: #{loginBean.login}: java.lang.NullPointerException
at com.sun.faces.application.ActionListenerImpl.processAction(ActionListenerImpl.java:118)
at javax.faces.component.UICommand.broadcast(UICommand.java:315)
at javax.faces.component.UIViewRoot.broadcastEvents(UIViewRoot.java:794)
at javax.faces.component.UIViewRoot.processApplication(UIViewRoot.java:1259)
at com.sun.faces.lifecycle.InvokeApplicationPhase.execute(InvokeApplicationPhase.java:81)
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:1550)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:281)
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:860)
at com.sun.grizzly.http.ProcessorTask.doProcess(ProcessorTask.java:757)
at com.sun.grizzly.http.ProcessorTask.process(ProcessorTask.java:1056)
at com.sun.grizzly.http.DefaultProtocolFilter.execute(DefaultProtocolFilter.java:229)
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)
Caused by: javax.faces.el.EvaluationException: java.lang.NullPointerException
at javax.faces.component.MethodBindingMethodExpressionAdapter.invoke(MethodBindingMethodExpressionAdapter.java:102)
at com.sun.faces.application.ActionListenerImpl.processAction(ActionListenerImpl.java:102)
... 31 more
Caused by: java.lang.NullPointerException
at beans.LoginBean.login(LoginBean.java:49)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:601)
at com.sun.el.parser.AstValue.invoke(AstValue.java:254)
at com.sun.el.MethodExpressionImpl.invoke(MethodExpressionImpl.java:302)
at com.sun.faces.facelets.el.TagMethodExpression.invoke(TagMethodExpression.java:105)
at javax.faces.component.MethodBindingMethodExpressionAdapter.invoke(MethodBindingMethodExpressionAdapter.java:88)
... 32 more
Here is my controller class
package ejb;
import java.util.List;
import javax.ejb.LocalBean;
import javax.ejb.Stateful;
import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.Query;
import javax.persistence.PersistenceContext;
import model.Group;
import model.User;
import model.UserGroup;
#Stateful
#LocalBean
public class UserGroupDaoBean {
#PersistenceContext(unitName = "myPU")
private EntityManager entityManager;
public UserGroupDaoBean() {
}
public UserGroup createNewUserGroup(int groupId, String username) {
UserGroup newUserGrp = new UserGroup();
User myUsr;
myUsr = entityManager.find(User.class, username);
newUserGrp.setUser(myUsr);
Group myGrp;
myGrp = entityManager.find(Group.class, groupId);
newUserGrp.setGroup(myGrp);
saveNewUsrGrp(newUserGrp);
return newUserGrp;
}
private void saveNewUsrGrp(UserGroup usrGrp) {
entityManager.persist(usrGrp);
entityManager.flush();
}
public boolean checkUsertoGroup(String username, int groupId) {
Group chkGrp;
chkGrp = entityManager.find(Group.class, groupId);
User chkUsr;
chkUsr = entityManager.find(User.class, username);
if (chkGrp != null) {
if (chkUsr != null) {
try {
entityManager.createNamedQuery("findGroupsbyUser")
.setParameter("username", chkUsr)
.setParameter("groupId", chkGrp).getSingleResult();
System.out.println("UserGroup already exists");
return false;
} catch (NoResultException e) {
return true;
}
}
System.out.println("User doesn't exist");
return false;
}
System.out.println("Group doesn't exist");
return false;
}
public void deleteUserGroup(UserGroup userGroup) {
userGroup = entityManager.merge(userGroup);
entityManager.remove(userGroup);
}
public UserGroup update(UserGroup myUserGroup) {
return entityManager.merge(myUserGroup);
}
#SuppressWarnings("unchecked")
public List<UserGroup> getAllUserGroups() {
try {
Query query = entityManager.createNamedQuery("findAllUserGroup");
List<UserGroup> result = (List<UserGroup>) query.getResultList();
return result;
} catch (NoResultException e) {
System.out.println("No Result found");
return null;
}
}
public boolean validateGroup(String username, int groupId) {
try {
UserGroup myGroupId = (UserGroup) entityManager
.createNamedQuery("findGroup")
.setParameter("username", username)
.setParameter("groupId", groupId).getSingleResult();
if (myGroupId != null) {
System.out.println("This user is admin!!!");
return true;
}
} catch (NoResultException e) {
return false;
}
System.out.println("This user is not admin");
return false;
}
}
Below is my entity UserGroup
package model;
import java.io.Serializable;
import javax.persistence.*;
/**
* The persistent class for the UserGroup database table.
*
*/
#NamedQueries({
#NamedQuery(name = "findGroupsbyUser", query = "Select ug.group from UserGroup ug where ug.user=:username AND ug.group=:groupId"),
#NamedQuery(name = "findAllUserGroup", query="Select ug from UserGroup ug"),
#NamedQuery(name = "findAdminGroupId", query = "Select ug from UserGroup ug where ug.user=:username AND ug.group=:groupId"),
})
#Entity
#Table(name="usergroup")
public class UserGroup implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name="RowId" )
private int rowId;
//bi-directional many-to-one association to Group
#ManyToOne
#JoinColumn(name="groupId")
private Group group;
//bi-directional many-to-one association to User
#ManyToOne
#JoinColumn(name="username")
private User user;
public UserGroup() {
}
public int getRowId() {
return this.rowId;
}
public void setRowId(int rowId) {
this.rowId = rowId;
}
public Group getGroup() {
return this.group;
}
public void setGroup(Group group) {
this.group = group;
}
public User getUser() {
return this.user;
}
public void setUser(User user) {
this.user = user;
}
}

Read the stack trace: the NPE is thrown at line 49 of LoginBean.java.
With high probability, uGBD is null, because the EJB annotation is missing. You need to use the #EJB annotation in front of each of the EJBs you are injecting:
#EJB
private UserDaoBean uDB;
#EJB
private UserGroupDaoBean uGDB;
...

Related

Spring Security not populating database with hashed password

I'm trying to populate the database with a hashed password and then log in to my application, by matching the data I'm submitting through my log in form, just like how a typical hashed password is suppose to work. I'm using spring security and spring boot, and so far I know that the log in form is working because I get the error Encoded password does not look like BCrypt. And I know that when I'm submitting the user to the database it's not working because I just see a plain string in the password column in the database. I'm really not sure where I'm going wrong here.
Here's my User object
package com.example.objects;
import java.util.HashSet;
import java.util.Set;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.persistence.Version;
import com.example.security.PasswordCrypto;
import com.example.security.RoleEnum;
#Entity
#Table(name = "users")
public class User {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
#Version
private Long version;
#Column(name = "username")
private String username;
#Column(name = "password")
private String password;
#Column(name = "email")
private String email;
#Column(name = "termsOfService")
private Boolean termsOfService;
#OneToMany(mappedBy = "user")
private Set<UserRole> roles;
#OneToMany(mappedBy = "user", fetch = FetchType.LAZY)
private Set<QuestionAnswerSet> questionAnswerSet;
public static User createUser(String username, String email, String password) {
User user = new User();
user.username = username;
user.email = email;
user.password = PasswordCrypto.getInstance().encrypt(password);
if(user.roles == null) {
user.roles = new HashSet<UserRole>();
}
//create a new user with basic user privileges
user.roles.add(
new UserRole(
RoleEnum.USER.toString(),
user
));
return user;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Long getVersion() {
return version;
}
public void setVersion(Long version) {
this.version = version;
}
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 Boolean getTermsOfService() {
return termsOfService;
}
public void setTermsOfService(Boolean termsOfService) {
this.termsOfService = termsOfService;
}
public Set<QuestionAnswerSet> getQuestionAnswerSet() {
return questionAnswerSet;
}
public void setQuestionAnswerSet(Set<QuestionAnswerSet> questionAnswerSet) {
this.questionAnswerSet = questionAnswerSet;
}
public Set<UserRole> getRoles() {
return roles;
}
public void setRoles(Set<UserRole> roles) {
this.roles = roles;
}
}
Here's my Security Config
package com.example.security;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.csrf.CsrfTokenRepository;
import org.springframework.security.web.csrf.HttpSessionCsrfTokenRepository;
#Configuration
#EnableWebSecurity
#EnableGlobalMethodSecurity(prePostEnabled = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
private static PasswordEncoder encoder;
#Autowired
private UserDetailsService customUserDetailsService;
#Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf()
.csrfTokenRepository(csrfTokenRepository());
http
.authorizeRequests()
.antMatchers("/","/home","/register", "/result").permitAll()
.anyRequest().authenticated();
http
.formLogin()
.loginPage("/login")
.permitAll()
.and()
.logout()
.permitAll();
}
#Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(customUserDetailsService)
.passwordEncoder(passwordEncoder());
}
#Bean
public PasswordEncoder passwordEncoder() {
if(encoder == null) {
encoder = new BCryptPasswordEncoder();
}
return encoder;
}
private CsrfTokenRepository csrfTokenRepository()
{
HttpSessionCsrfTokenRepository repository = new HttpSessionCsrfTokenRepository();
repository.setSessionAttributeName("_csrf");
return repository;
}
}
My user detail service
package com.example.service;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import javax.transaction.Transactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import com.example.dao.UserDao;
import com.example.objects.UserRole;
#Service
#Qualifier("customUserDetailsService")
public class CustomUserDetailsService implements UserDetailsService {
#Autowired
private UserDao userDao;
#Transactional
#Override
public UserDetails loadUserByUsername(final String username)
throws UsernameNotFoundException {
com.example.objects.User user = userDao.findByUsername(username);
List<GrantedAuthority> authorities = buildUserAuthority(user.getRoles());
return buildUserForAuthentication(user, authorities);
}
private User buildUserForAuthentication(com.example.objects.User user,
List<GrantedAuthority> authorities) {
return new User(user.getUsername(), user.getPassword(), authorities);
}
private List<GrantedAuthority> buildUserAuthority(Set<UserRole> userRoles) {
Set<GrantedAuthority> setAuths = new HashSet<GrantedAuthority>();
// Build user's authorities
for (UserRole userRole : userRoles) {
setAuths.add(new SimpleGrantedAuthority(userRole.getRoleName()));
}
return new ArrayList<GrantedAuthority>(setAuths);
}
}
And PasswordCrypto
package com.example.security;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
public class PasswordCrypto {
#Autowired
private PasswordEncoder passwordEncoder;
private static PasswordCrypto instance;
public static PasswordCrypto getInstance() {
if(instance == null) {
instance = new PasswordCrypto();
}
return instance;
}
public String encrypt(String str) {
return passwordEncoder.encode(str);
}
}
If anyone knows what I'm doing wrong and could help me out, that would be awesome, also let me know if I need to show anymore code. Thanks in advance.
Use encoder to user repository like this :
public class UserRepositoryService implements UserService {
private PasswordEncoder passwordEncoder;
private UserRepository repository;
#Autowired
public UserRepositoryService(PasswordEncoder passwordEncoder,
UserRepository repository) {
this.passwordEncoder = passwordEncoder;
this.repository = repository;
}
private boolean emailExist(String email) {
User user = repository.findByEmail(email);
if (user != null) {
return true;
}
return false;
}
private String encodePassword(RegistrationForm dto) {
String encodedPassword = null;
if (dto.isNormalRegistration()) {
encodedPassword = passwordEncoder.encode(dto.getPassword());
}
return encodedPassword;
}
#Transactional
#Override
public User registerNewUserAccount(RegistrationForm userAccountData)
throws DuplicateEmailException {
if (emailExist(userAccountData.getEmail())) {
LOGGER.debug("Email: {} exists. Throwing exception.",
userAccountData.getEmail());
throw new DuplicateEmailException("The email address: "
+ userAccountData.getEmail() + " is already in use.");
}
String encodedPassword = encodePassword(userAccountData);
User.Builder user = User.getBuilder().email(userAccountData.getEmail())
.firstName(userAccountData.getFirstName())
.lastName(userAccountData.getLastName())
.password(encodedPassword)
.background(userAccountData.getBackground())
.purpose(userAccountData.getPurpose());
if (userAccountData.isSocialSignIn()) {
user.signInProvider(userAccountData.getSignInProvider());
}
User registered = user.build();
return repository.save(registered);
}
}
For morre info, check out this repo
https://bitbucket.org/sulab/biobranch/src/992791aa706d0016de8634ebb6347a81fe952c24/src/main/java/org/scripps/branch/entity/User.java?at=default&fileviewer=file-view-default
My problem was that I needed to add user.setPassword(new BCryptPasswordEncoder().encode(user.getPassword())); in my UserController Post method right before I saved the user

Issue with accessing FacesContext in Servlet Filter

I am trying to access FacesContext in Servlet Filter,
And sometimes (not everytime) i encounter internal server errors.
AuthenticationFilter.java
import java.io.IOException;
import javax.faces.context.FacesContext;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.codec.binary.Base64;
public class AuthenticationFilter implements Filter {
#Override
public void destroy() {
}
#Override
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
request.setCharacterEncoding("UTF-8");
UserDetailsBean userBean = null;
HttpServletRequest req = (HttpServletRequest)request;
HttpServletResponse res = (HttpServletResponse)response;
FacesContext context = FacesUtil.getFacesContext(req, res);
String param = req.getParameter("PARAMETER_VALUES");
if((param!=null && param.isEmpty()) || !isAuthenticated(req)) {
if(param != null && !param.isEmpty()) {
userBean = new UserDetailsBean();
setCookies(param, userBean, req, res);
FacesUtil.setManagedBeanInView(context, "userDetailsBean", userBean);
request.setAttribute("userDetailsBean", userBean);
chain.doFilter(request, response);
}
else {
String homePage = "http://homePage";
res.sendRedirect(homePage);
}
}
else {
try {
if(!context.isPostback()){
userBean = getUserBeanFromCookies(req.getCookies());
request.setAttribute("userDetailsBean", userBean);
}
} catch(Exception e) {
userBean = getUserBeanFromCookies(req.getCookies());
request.setAttribute("userDetailsBean", userBean);
}
chain.doFilter(request, response);
}
}
private UserDetailsBean getUserBeanFromCookies(Cookie[] cookies) {
UserDetailsBean userBean = new UserDetailsBean();
for(Cookie c: cookies) {
String cName = c.getName();
if("userId".equals(cName)) {
userBean.setUserNbr(c.getValue());
}
else if("userEmail".equals(cName)) {
userBean.setEmail(c.getValue());
}
else if("firstName".equals(cName)) {
userBean.setFirstName(c.getValue());
}
else if("lastName".equals(cName)) {
userBean.setLastName(c.getValue());
}
}
return userBean;
}
private boolean setCookies(String param, UserDetailsBean userBean, HttpServletRequest request, HttpServletResponse response) {
boolean validUser = false;
if(param != null) {
String strParams = new String(Base64.decodeBase64(param.getBytes()));
String[] pairs = strParams.split("&");
for(String pp: pairs) {
String[] s = pp.split("=");
if("p_userid".equals(s[0])) {
userBean.setUserNbr(s[1]);
validUser = true;
}
else if("p_email".equals(s[0])){
userBean.setEmail(s[1]);
}
else if("p_first_name".equals(s[0])) {
userBean.setFirstName(s[1]);
}
else if("p_last_name".equals(s[0])) {
userBean.setLastName(s[1]);
}
}
}
if(validUser) {
String cookiePath = "/";
Cookie cookie = new Cookie("userId", userBean.getUserNbr());
cookie.setMaxAge(-1); // Expire time. -1 = by end of current session, 0 = immediately expire it, otherwise just the lifetime in seconds.
cookie.setPath(cookiePath);
response.addCookie(cookie);
cookie = new Cookie("userEmail", userBean.getEmail());
cookie.setMaxAge(-1);
cookie.setPath(cookiePath);
response.addCookie(cookie);
cookie = new Cookie("firstName",userBean.getFirstName());
cookie.setMaxAge(-1);
cookie.setPath(cookiePath);
response.addCookie(cookie);
cookie = new Cookie("lastName", userBean.getLastName());
cookie.setMaxAge(-1);
cookie.setPath(cookiePath);
response.addCookie(cookie);
}
return validUser;
}
public boolean isAuthenticated(HttpServletRequest request) {
Cookie[] cookies = request.getCookies();
if(cookies == null) {
return false;
}
for(Cookie c: cookies) {
String cName = c.getName();
if("userId".equals(cName)) {
if(c.getValue() == null || c.getValue().isEmpty()) {
return false;
}
else {
return true;
}
}
}
return false;
}
#Override
public void init(FilterConfig arg0) throws ServletException {
}
}
UserDetailsBean.java
import java.io.Serializable;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
#ViewScoped
#ManagedBean(name="userDetailsBean")
public class UserDetailsBean implements Serializable {
private String userNbr;
private String email;
private String firstName;
private String lastName;
public String getUserNbr() {
return userNbr;
}
public void setUserNbr(String userNbr) {
this.userNbr = userNbr;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
}
FacesUtil.java
import javax.faces.FactoryFinder;
import javax.faces.component.UIViewRoot;
import javax.faces.context.FacesContext;
import javax.faces.context.FacesContextFactory;
import javax.faces.lifecycle.Lifecycle;
import javax.faces.lifecycle.LifecycleFactory;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class FacesUtil {
public static FacesContext getFacesContext(HttpServletRequest request, HttpServletResponse response) {
FacesContext facesContext = FacesContext.getCurrentInstance();
if (facesContext == null) {
LifecycleFactory lifecycleFactory = (LifecycleFactory) FactoryFinder.getFactory(FactoryFinder.LIFECYCLE_FACTORY);
Lifecycle lifecycle = lifecycleFactory.getLifecycle(LifecycleFactory.DEFAULT_LIFECYCLE);
FacesContextFactory contextFactory = (FacesContextFactory) FactoryFinder.getFactory(FactoryFinder.FACES_CONTEXT_FACTORY);
facesContext = contextFactory.getFacesContext(request.getSession().getServletContext(), request, response, lifecycle);
UIViewRoot view = facesContext.getApplication().getViewHandler().createView(facesContext, "");
facesContext.setViewRoot(view);
FacesContextWrapper.setCurrentInstance(facesContext);
}
return facesContext;
}
// Wrap the protected FacesContext.setCurrentInstance() in a inner class.
private static abstract class FacesContextWrapper extends FacesContext {
protected static void setCurrentInstance(FacesContext facesContext) {
FacesContext.setCurrentInstance(facesContext);
}
}
}
Here the authentication is actually handling by other application,
Once the user login it will send a request parameter (PARAMETER_VALUES) with some information.
We are using JSF 2.1.9 & Tomcat 6.0.35.
i am getting an error at this line from Filter
FacesContext context = FacesUtil.getFacesContext(req, res);
Error stack trace:
Exception=java.lang.NullPointerException
at org.apache.catalina.connector.Request.parseParameters(Request.java:2599)
at org.apache.catalina.connector.Request.getParameter(Request.java:1106)
at org.apache.catalina.connector.RequestFacade.getParameter(RequestFacade.java:355)
at javax.servlet.ServletRequestWrapper.getParameter(ServletRequestWrapper.java:158)
at com.sun.faces.context.RequestParameterMap.containsKey(RequestParameterMap.java:99)
at java.util.Collections$UnmodifiableMap.containsKey(Collections.java:1280)
at com.sun.faces.renderkit.ResponseStateManagerImpl.isPostback(ResponseStateManagerImpl.java:84)
at com.sun.faces.context.FacesContextImpl.isPostback(FacesContextImpl.java:207)
at com.sandbox.external.site.test.filter.AuthenticationFilter.doFilter(AuthenticationFilter.java:36)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:233)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:127)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
at org.apache.catalina.ha.tcp.ReplicationValve.invoke(ReplicationValve.java:347)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:293)
at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:859)
at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:602)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:396)
at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:886)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:908)
at java.lang.Thread.run(Thread.java:662)
When i see the source code of Tomcat 6.0.35 at the line stated in error,
if (!getMethod().equalsIgnoreCase("POST"))
return;
cannot find much information here.
You cannot access the FacesContext in a filter because the FacesContext is initialized by the FacesServlet, and your filter is processed before the request arrives to the servlet.
If it works sometimes, it is probably because of a side effect (JSF creates one FacesContext for every request, every request is bound to a Thread and Threads are reused by the servlet container).
I'm also wondering why are you trying to reinvent the wheel by implementing you own security filters. There is already existing solution which are available (like Spring Security or standard JEE security) and well tested.
See this question for more information from BalusC:
How do I retrieve the FacesContext within a Filter

SpringData Neo4J REST: RuntimeException when using #Indexed(unique=true)

I'm using SpringData and Neo4j via REST and I am seeing an exception when I add #Indexed(unique=true). This does not throw an exception in embedded, and it does not throw an exception in REST if I remove the unique=true. It Happens even it the database is empty (no nodes and no indexes).
Any ideas?
package com.mycompany;
import org.springframework.data.neo4j.annotation.GraphId;
import org.springframework.data.neo4j.annotation.Indexed;
import org.springframework.data.neo4j.annotation.NodeEntity;
#NodeEntity
public class Person {
#GraphId
private Long id;
#Indexed(unique=true) private String name; // <<<-- does not error if I remove unique-true)
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
#Override
public int hashCode() {
int hash = 7;
hash = 23 * hash + (this.name != null ? this.name.hashCode() : 0);
return hash;
}
#Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final Person other = (Person) obj;
if ((this.name == null) ? (other.name != null) : !this.name.equals(other.name)) {
return false;
}
return true;
}
}
Here's the exception trace:
java.lang.RuntimeException: Error adding element 10 className com.mycompany.Person to index __types__
at org.neo4j.rest.graphdb.ExecutingRestAPI.addToIndex(ExecutingRestAPI.java:397)
at org.neo4j.rest.graphdb.RestAPIFacade.addToIndex(RestAPIFacade.java:166)
at org.neo4j.rest.graphdb.index.RestIndex.add(RestIndex.java:60)
at org.springframework.data.neo4j.support.typerepresentation.AbstractIndexingTypeRepresentationStrategy.add(AbstractIndexingTypeRepresentationStrategy.java:123)
at org.springframework.data.neo4j.support.typerepresentation.AbstractIndexingTypeRepresentationStrategy.addToTypesIndex(AbstractIndexingTypeRepresentationStrategy.java:115)
at org.springframework.data.neo4j.support.typerepresentation.AbstractIndexingTypeRepresentationStrategy.writeTypeTo(AbstractIndexingTypeRepresentationStrategy.java:63)
at org.springframework.data.neo4j.support.mapping.TRSTypeAliasAccessor.writeTypeTo(TRSTypeAliasAccessor.java:46)
at org.springframework.data.neo4j.support.mapping.TRSTypeAliasAccessor.writeTypeTo(TRSTypeAliasAccessor.java:26)
at org.springframework.data.convert.DefaultTypeMapper.writeType(DefaultTypeMapper.java:199)
at org.springframework.data.convert.DefaultTypeMapper.writeType(DefaultTypeMapper.java:186)
at org.springframework.data.neo4j.support.mapping.Neo4jEntityConverterImpl.write(Neo4jEntityConverterImpl.java:165)
at org.springframework.data.neo4j.support.mapping.Neo4jEntityPersister$CachedConverter.write(Neo4jEntityPersister.java:179)
at org.springframework.data.neo4j.support.mapping.Neo4jEntityPersister.persist(Neo4jEntityPersister.java:243)
at org.springframework.data.neo4j.support.mapping.Neo4jEntityPersister.persist(Neo4jEntityPersister.java:231)
at org.springframework.data.neo4j.support.Neo4jTemplate.save(Neo4jTemplate.java:294)
at org.springframework.data.neo4j.support.Neo4jTemplate.save(Neo4jTemplate.java:288)
at com.mycompany.NeoTest.testSomething(NeoTest.java:28)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:44)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:15)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:41)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:20)
at org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:74)
at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:83)
at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:72)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:231)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:88)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:193)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:52)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:191)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:42)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:184)
at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:71)
at org.junit.runners.ParentRunner.run(ParentRunner.java:236)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:174)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:50)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:467)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:683)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:390)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:197)
And just for completeness, here's the test code:
package com.mycompany;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.neo4j.support.Neo4jTemplate;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.transaction.annotation.Transactional;
import com.mycompany.Person;
import static org.junit.Assert.*;
#ContextConfiguration(locations = "classpath:testContext.xml")
#RunWith(SpringJUnit4ClassRunner.class)
public class NeoTest {
#Autowired
Neo4jTemplate template;
#Test
//#Transactional
public void testSomething() {
Person add = new Person();
add.setName("Jorgan Jorgansen");
add = template.save(add);
Person other = template.findOne(add.getId(), Person.class);
assertNotNull("Retrieved entity is non-null", other);
assertEquals("Retrieved entity equals saved entity", add, other);
}
}
Seems a known bug, see this link.
Anyway the exception is about the __types__ index that has nothing to do with the index you define in your class, it's used by SDN to retrieve objects by class name.

Javafx combobox bound value cannot be set exception

I'm using trying to use a javafx combobox with a cell factory to render the list, I was using the setText on the override updateItem() of my CellList, but I found out when I change a value on the underlying model, that doesnẗ afects the deployed list on the combo box. So I try to make it binding both properties and It's works but when a try to clear the selection I have a Exception. This is the code:
import javafx.application.Application;
import javafx.beans.property.SimpleStringProperty;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.layout.*;
import javafx.stage.Stage;
import javafx.util.Callback;
public class BasicComboBoxSample extends Application {
public static void main(String[] args) { launch(args); }
#Override public void start(Stage stage) {
final Employee john = new Employee("John");
final Employee jill = new Employee("Jill");
final Employee jack = new Employee("Jack");
final ComboBox<Employee> cboEmployees = new ComboBox();
cboEmployees.getItems().addAll(john, jill, jack);
cboEmployees.setValue(jill);
Button b = new Button("ChangeName");
b.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent actionEvent) {
john.setName("Maria");
}
});
Button c = new Button("Clear");
c.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent actionEvent) {
cboEmployees.getSelectionModel().clearSelection();
}
});
Button d = new Button("Select First");
d.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent actionEvent) {
cboEmployees.getSelectionModel().select(john);
}
});
Callback<ListView<Employee>, ListCell<Employee>> cellFactory = new Callback<ListView<Employee>, ListCell<Employee>>() {
#Override
public ListCell<Employee> call(ListView<Employee> listView) {
return new EmployeeListCell(); //To change body of implemented methods use File | Settings | File Templates.
}
};
cboEmployees.setButtonCell(new EmployeeListCell());
cboEmployees.setCellFactory(cellFactory);
final StackPane layout = new StackPane();
VBox v = new VBox();
v.getChildren().add(cboEmployees);
v.getChildren().add(b);
v.getChildren().add(c);
v.getChildren().add(d);
layout.getChildren().add(v);
layout.setStyle("-fx-background-color: cornsilk; -fx-padding: 15;");
stage.setScene(new Scene(layout));
stage.show();
}
class Employee {
public Employee(String name) { this.setName(name); }
private SimpleStringProperty name = new SimpleStringProperty("");
String getName() {
return name.get();
}
SimpleStringProperty nameProperty() {
return name;
}
void setName(String name) {
this.name.set(name);
}
}
public class EmployeeListCell extends ListCell<Employee> {
#Override
protected void updateItem(Employee emp, boolean b) {
super.updateItem(emp, b);
if(emp != null){
textProperty().bind(emp.nameProperty());
}
}
}
}
And the Exception was:
Exception in thread "JavaFX Application Thread" java.lang.RuntimeException: A bound value cannot be set.
at javafx.beans.property.StringPropertyBase.set(StringPropertyBase.java:157)
at javafx.beans.property.StringPropertyBase.set(StringPropertyBase.java:67)
at javafx.beans.property.StringProperty.setValue(StringProperty.java:84)
at javafx.scene.control.Labeled.setText(Labeled.java:135)
at com.sun.javafx.scene.control.skin.ComboBoxListViewSkin.updateDisplayText(ComboBoxListViewSkin.java:420)
at com.sun.javafx.scene.control.skin.ComboBoxListViewSkin.updateDisplayNode(ComboBoxListViewSkin.java:399)
at com.sun.javafx.scene.control.skin.ComboBoxListViewSkin.getDisplayNode(ComboBoxListViewSkin.java:229)
at com.sun.javafx.scene.control.skin.ComboBoxBaseSkin.updateDisplayArea(ComboBoxBaseSkin.java:125)
at com.sun.javafx.scene.control.skin.ComboBoxBaseSkin.handleControlPropertyChanged(ComboBoxBaseSkin.java:120)
at com.sun.javafx.scene.control.skin.ComboBoxListViewSkin.handleControlPropertyChanged(ComboBoxListViewSkin.java:198)
at com.sun.javafx.scene.control.skin.SkinBase$3.changed(SkinBase.java:282)
at javafx.beans.value.WeakChangeListener.changed(WeakChangeListener.java:107)
at com.sun.javafx.binding.ExpressionHelper$Generic.fireValueChangedEvent(ExpressionHelper.java:367)
at com.sun.javafx.binding.ExpressionHelper.fireValueChangedEvent(ExpressionHelper.java:100)
at javafx.beans.property.ObjectPropertyBase.fireValueChangedEvent(ObjectPropertyBase.java:123)
at javafx.beans.property.ObjectPropertyBase.markInvalid(ObjectPropertyBase.java:130)
at javafx.beans.property.ObjectPropertyBase.set(ObjectPropertyBase.java:163)
at javafx.scene.control.ComboBoxBase.setValue(ComboBoxBase.java:148)
at javafx.scene.control.ComboBox.updateValue(ComboBox.java:416)
at javafx.scene.control.ComboBox.access$300(ComboBox.java:166)
at javafx.scene.control.ComboBox$6.changed(ComboBox.java:401)
at com.sun.javafx.binding.ExpressionHelper$Generic.fireValueChangedEvent(ExpressionHelper.java:367)
at com.sun.javafx.binding.ExpressionHelper.fireValueChangedEvent(ExpressionHelper.java:100)
at javafx.beans.property.ReadOnlyObjectWrapper$ReadOnlyPropertyImpl.fireValueChangedEvent(ReadOnlyObjectWrapper.java:195)
at javafx.beans.property.ReadOnlyObjectWrapper.fireValueChangedEvent(ReadOnlyObjectWrapper.java:161)
at javafx.beans.property.ObjectPropertyBase.markInvalid(ObjectPropertyBase.java:130)
at javafx.beans.property.ObjectPropertyBase.set(ObjectPropertyBase.java:163)
at javafx.scene.control.SelectionModel.setSelectedItem(SelectionModel.java:101)
at javafx.scene.control.ComboBox$ComboBoxSelectionModel$1.invalidated(ComboBox.java:448)
at com.sun.javafx.binding.ExpressionHelper$SingleInvalidation.fireValueChangedEvent(ExpressionHelper.java:155)
at com.sun.javafx.binding.ExpressionHelper.fireValueChangedEvent(ExpressionHelper.java:100)
at javafx.beans.property.ReadOnlyIntegerWrapper$ReadOnlyPropertyImpl.fireValueChangedEvent(ReadOnlyIntegerWrapper.java:195)
at javafx.beans.property.ReadOnlyIntegerWrapper.fireValueChangedEvent(ReadOnlyIntegerWrapper.java:161)
at javafx.beans.property.IntegerPropertyBase.markInvalid(IntegerPropertyBase.java:130)
at javafx.beans.property.IntegerPropertyBase.set(IntegerPropertyBase.java:163)
at javafx.scene.control.SelectionModel.setSelectedIndex(SelectionModel.java:67)
at javafx.scene.control.SingleSelectionModel.updateSelectedIndex(SingleSelectionModel.java:208)
at javafx.scene.control.SingleSelectionModel.clearSelection(SingleSelectionModel.java:67)
at de.thomasbolz.javafx.BasicComboBoxSample$2.handle(BasicComboBoxSample.java:45)
at de.thomasbolz.javafx.BasicComboBoxSample$2.handle(BasicComboBoxSample.java:42)
at com.sun.javafx.event.CompositeEventHandler.dispatchBubblingEvent(CompositeEventHandler.java:69)
at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:217)
at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:170)
at com.sun.javafx.event.CompositeEventDispatcher.dispatchBubblingEvent(CompositeEventDispatcher.java:38)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:37)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:92)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:35)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:92)
at com.sun.javafx.event.EventUtil.fireEventImpl(EventUtil.java:53)
at com.sun.javafx.event.EventUtil.fireEvent(EventUtil.java:28)
at javafx.event.Event.fireEvent(Event.java:171)
at javafx.scene.Node.fireEvent(Node.java:6863)
at javafx.scene.control.Button.fire(Button.java:179)
at com.sun.javafx.scene.control.behavior.ButtonBehavior.mouseReleased(ButtonBehavior.java:193)
at com.sun.javafx.scene.control.skin.SkinBase$4.handle(SkinBase.java:336)
at com.sun.javafx.scene.control.skin.SkinBase$4.handle(SkinBase.java:329)
at com.sun.javafx.event.CompositeEventHandler.dispatchBubblingEvent(CompositeEventHandler.java:64)
at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:217)
at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:170)
at com.sun.javafx.event.CompositeEventDispatcher.dispatchBubblingEvent(CompositeEventDispatcher.java:38)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:37)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:92)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:35)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:92)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:35)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:92)
at com.sun.javafx.event.EventUtil.fireEventImpl(EventUtil.java:53)
at com.sun.javafx.event.EventUtil.fireEvent(EventUtil.java:33)
at javafx.event.Event.fireEvent(Event.java:171)
at javafx.scene.Scene$MouseHandler.process(Scene.java:3328)
at javafx.scene.Scene$MouseHandler.process(Scene.java:3168)
at javafx.scene.Scene$MouseHandler.access$1900(Scene.java:3123)
at javafx.scene.Scene.impl_processMouseEvent(Scene.java:1563)
at javafx.scene.Scene$ScenePeerListener.mouseEvent(Scene.java:2265)
at com.sun.javafx.tk.quantum.GlassViewEventHandler$MouseEventNotification.run(GlassViewEventHandler.java:250)
at com.sun.javafx.tk.quantum.GlassViewEventHandler$MouseEventNotification.run(GlassViewEventHandler.java:173)
at java.security.AccessController.doPrivileged(Native Method)
at com.sun.javafx.tk.quantum.GlassViewEventHandler.handleMouseEvent(GlassViewEventHandler.java:292)
at com.sun.glass.ui.View.handleMouseEvent(View.java:528)
at com.sun.glass.ui.View.notifyMouse(View.java:922)
at com.sun.glass.ui.gtk.GtkApplication._runLoop(Native Method)
at com.sun.glass.ui.gtk.GtkApplication$3$1.run(GtkApplication.java:82)
at java.lang.Thread.run(Thread.java:722)
You need to unbind the textProperty in case the emp is null
Add the condition in EmployeeListCell class
else {
textProperty().unbind();
}

Custom OgnlValueStack in Struts 2

I want to implement a custom ValueStack in my application by extending the OgnlValueStack class of Struts 2.3.x.
Please let me know how to accomplish this. What classes do I need to extend and implement in my application and how to inject different dependencies using the #Inject annotation?
Update
I have made the changes as suggested earlier. My ValueStackFactory implementation is:
package jp.co.spectrum.insight.core.mvc.factory;
import java.util.Map;
import java.util.Set;
import jp.co.spectrum.insight.core.datamodel.InsightValueStackImpl;
import ognl.MethodAccessor;
import ognl.OgnlRuntime;
import ognl.PropertyAccessor;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.TextProvider;
import com.opensymphony.xwork2.conversion.NullHandler;
import com.opensymphony.xwork2.conversion.impl.XWorkConverter;
import com.opensymphony.xwork2.inject.Container;
import com.opensymphony.xwork2.inject.Inject;
import com.opensymphony.xwork2.ognl.OgnlNullHandlerWrapper;
import com.opensymphony.xwork2.ognl.accessor.CompoundRootAccessor;
import com.opensymphony.xwork2.util.CompoundRoot;
import com.opensymphony.xwork2.util.ValueStack;
import com.opensymphony.xwork2.util.ValueStackFactory;
public class InsightValueStackFactory implements ValueStackFactory {
#Inject
private XWorkConverter xworkConverter;
private CompoundRootAccessor compoundRootAccessor;
#Inject("system")
private TextProvider textProvider;
#Inject
private Container container;
private boolean allowStaticMethodAccess;
/*
private static ValueStackFactory instance;
public static ValueStackFactory getInstance() {
if (instance == null) {
instance = new InsightValueStackFactory();
}
return instance;
}
*/
private static ValueStackFactory factory = new InsightValueStackFactory();
public static void setFactory(ValueStackFactory factoryParam) {
factory = factoryParam;
}
public static ValueStackFactory getFactory() {
return factory;
}
public void setXWorkConverter(XWorkConverter conv) {
this.xworkConverter = conv;
}
public void setTextProvider(TextProvider textProvider) {
this.textProvider = textProvider;
}
#Inject(value="allowStaticMethodAccess", required=true)
public void setAllowStaticMethodAccess(String allowStaticMethodAccess) {
this.allowStaticMethodAccess = "true".equalsIgnoreCase(allowStaticMethodAccess);
}
public ValueStack createValueStack() {
ValueStack stack = new InsightValueStackImpl(xworkConverter, compoundRootAccessor, textProvider, allowStaticMethodAccess);
container.inject(stack);
stack.getContext().put(ActionContext.CONTAINER, container);
return stack;
}
public ValueStack createValueStack(ValueStack stack) {
ValueStack result = new InsightValueStackImpl(stack, xworkConverter, compoundRootAccessor, allowStaticMethodAccess);
container.inject(result);
stack.getContext().put(ActionContext.CONTAINER, container);
return result;
}
public void setContainer(Container container) throws ClassNotFoundException {
Set<String> names = container.getInstanceNames(PropertyAccessor.class);
for (String name : names) {
Class cls = Class.forName(name);
if (cls != null) {
if (Map.class.isAssignableFrom(cls)) {
PropertyAccessor acc = container.getInstance(PropertyAccessor.class, name);
}
OgnlRuntime.setPropertyAccessor(cls, container.getInstance(PropertyAccessor.class, name));
if (compoundRootAccessor == null && CompoundRoot.class.isAssignableFrom(cls)) {
compoundRootAccessor = (CompoundRootAccessor) container.getInstance(PropertyAccessor.class, name);
}
}
}
names = container.getInstanceNames(MethodAccessor.class);
for (String name : names) {
Class cls = Class.forName(name);
if (cls != null) {
OgnlRuntime.setMethodAccessor(cls, container.getInstance(MethodAccessor.class, name));
}
}
names = container.getInstanceNames(NullHandler.class);
for (String name : names) {
Class cls = Class.forName(name);
if (cls != null) {
OgnlRuntime.setNullHandler(cls, new OgnlNullHandlerWrapper(container.getInstance(NullHandler.class, name)));
}
}
if (compoundRootAccessor == null) {
throw new IllegalStateException("Couldn't find the compound root accessor");
}
this.container = container;
}
}
The InsightValueStackImpl class is my customized ValueStack and it extends the OgnlValueStack.
After the changes as suggested earlier, when I start the application, I get the following error:
java.lang.IllegalArgumentException: Wrapped type converter cannot be null
at com.opensymphony.xwork2.ognl.OgnlTypeConverterWrapper.<init>(OgnlTypeConverterWrapper.java:32)
at com.opensymphony.xwork2.ognl.OgnlValueStack.setRoot(OgnlValueStack.java:88)
at com.opensymphony.xwork2.ognl.OgnlValueStack.<init>(OgnlValueStack.java:71)
at jp.co.spectrum.insight.core.datamodel.InsightValueStackImpl.<init>(InsightValueStackImpl.java:86)
at jp.co.spectrum.insight.core.mvc.factory.InsightValueStackFactory.createValueStack(InsightValueStackFactory.java:85)
at jp.co.spectrum.insight.core.mvc.dispatcher.InsightFilterDispatcher.<init>(InsightFilterDispatcher.java:118)
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:39)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:27)
at java.lang.reflect.Constructor.newInstance(Constructor.java:513)
at java.lang.Class.newInstance0(Class.java:355)
at java.lang.Class.newInstance(Class.java:308)
at org.apache.catalina.core.ApplicationFilterConfig.getFilter(ApplicationFilterConfig.java:275)
at org.apache.catalina.core.ApplicationFilterConfig.setFilterDef(ApplicationFilterConfig.java:422)
at org.apache.catalina.core.ApplicationFilterConfig.<init>(ApplicationFilterConfig.java:115)
at org.apache.catalina.core.StandardContext.filterStart(StandardContext.java:4072)
at org.apache.catalina.core.StandardContext.start(StandardContext.java:4726)
at org.apache.catalina.core.ContainerBase.start(ContainerBase.java:1057)
at org.apache.catalina.core.StandardHost.start(StandardHost.java:840)
at org.apache.catalina.core.ContainerBase.start(ContainerBase.java:1057)
at org.apache.catalina.core.StandardEngine.start(StandardEngine.java:463)
at org.apache.catalina.core.StandardService.start(StandardService.java:525)
at org.apache.catalina.core.StandardServer.start(StandardServer.java:754)
at org.apache.catalina.startup.Catalina.start(Catalina.java:595)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at org.apache.catalina.startup.Bootstrap.start(Bootstrap.java:289)
at org.apache.catalina.startup.Bootstrap.main(Bootstrap.java:414)
This is because of null XWorkConverter instance.
Please let me know why it is not getting injected.
Thanks in advance
Thanks
I have made the changes as suggested earlier.
My ValueStackFactory implementation is:
package jp.co.spectrum.insight.core.mvc.factory;
import java.util.Map;
import java.util.Set;
import jp.co.spectrum.insight.core.datamodel.InsightValueStackImpl;
import ognl.MethodAccessor;
import ognl.OgnlRuntime;
import ognl.PropertyAccessor;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.TextProvider;
import com.opensymphony.xwork2.conversion.NullHandler;
import com.opensymphony.xwork2.conversion.impl.XWorkConverter;
import com.opensymphony.xwork2.inject.Container;
import com.opensymphony.xwork2.inject.Inject;
import com.opensymphony.xwork2.ognl.OgnlNullHandlerWrapper;
import com.opensymphony.xwork2.ognl.accessor.CompoundRootAccessor;
import com.opensymphony.xwork2.util.CompoundRoot;
import com.opensymphony.xwork2.util.ValueStack;
import com.opensymphony.xwork2.util.ValueStackFactory;
public class InsightValueStackFactory implements ValueStackFactory {
#Inject
private XWorkConverter xworkConverter ;
private CompoundRootAccessor compoundRootAccessor ;
#Inject("system")
private TextProvider textProvider ;
#Inject
private Container container;
private boolean allowStaticMethodAccess;
/*private static ValueStackFactory instance;
public static ValueStackFactory getInstance(){
if(instance==null){
instance = new InsightValueStackFactory();
}
return instance;
}*/
private static ValueStackFactory factory = new InsightValueStackFactory();
public static void setFactory(ValueStackFactory factoryParam) {
factory = factoryParam;
}
public static ValueStackFactory getFactory() {
return factory;
}
public void setXWorkConverter(XWorkConverter conv) {
this.xworkConverter = conv;
}
public void setTextProvider(TextProvider textProvider) {
this.textProvider = textProvider;
}
#Inject(value="allowStaticMethodAccess", required=true)
public void setAllowStaticMethodAccess(String allowStaticMethodAccess) {
this.allowStaticMethodAccess = "true".equalsIgnoreCase(allowStaticMethodAccess);
}
public ValueStack createValueStack() {
ValueStack stack = new InsightValueStackImpl(xworkConverter, compoundRootAccessor, textProvider, allowStaticMethodAccess);
container.inject(stack);
stack.getContext().put(ActionContext.CONTAINER, container);
return stack;
}
public ValueStack createValueStack(ValueStack stack) {
ValueStack result = new InsightValueStackImpl(stack, xworkConverter, compoundRootAccessor, allowStaticMethodAccess);
container.inject(result);
stack.getContext().put(ActionContext.CONTAINER, container);
return result;
}
public void setContainer(Container container) throws ClassNotFoundException {
Set<String> names = container.getInstanceNames(PropertyAccessor.class);
for (String name : names) {
Class cls = Class.forName(name);
if (cls != null) {
if (Map.class.isAssignableFrom(cls)) {
PropertyAccessor acc = container.getInstance(PropertyAccessor.class, name);
}
OgnlRuntime.setPropertyAccessor(cls, container.getInstance(PropertyAccessor.class, name));
if (compoundRootAccessor == null && CompoundRoot.class.isAssignableFrom(cls)) {
compoundRootAccessor = (CompoundRootAccessor) container.getInstance(PropertyAccessor.class, name);
}
}
}
names = container.getInstanceNames(MethodAccessor.class);
for (String name : names) {
Class cls = Class.forName(name);
if (cls != null) {
OgnlRuntime.setMethodAccessor(cls, container.getInstance(MethodAccessor.class, name));
}
}
names = container.getInstanceNames(NullHandler.class);
for (String name : names) {
Class cls = Class.forName(name);
if (cls != null) {
OgnlRuntime.setNullHandler(cls, new OgnlNullHandlerWrapper(container.getInstance(NullHandler.class, name)));
}
}
if (compoundRootAccessor == null) {
throw new IllegalStateException("Couldn't find the compound root accessor");
}
this.container = container;
}
}
The InsightValueStackImpl class is my customized ValueStack and it extends the OgnlValueStack.
After the changes as suggested earlier, when I start the application, I get the following error:
java.lang.IllegalArgumentException: Wrapped type converter cannot be null
at com.opensymphony.xwork2.ognl.OgnlTypeConverterWrapper.(OgnlTypeConverterWrapper.java:32)
at com.opensymphony.xwork2.ognl.OgnlValueStack.setRoot(OgnlValueStack.java:88)
at com.opensymphony.xwork2.ognl.OgnlValueStack.(OgnlValueStack.java:71)
at jp.co.spectrum.insight.core.datamodel.InsightValueStackImpl.(InsightValueStackImpl.java:86)
at jp.co.spectrum.insight.core.mvc.factory.InsightValueStackFactory.createValueStack(InsightValueStackFactory.java:85)
at jp.co.spectrum.insight.core.mvc.dispatcher.InsightFilterDispatcher.(InsightFilterDispatcher.java:118)
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:39)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:27)
at java.lang.reflect.Constructor.newInstance(Constructor.java:513)
at java.lang.Class.newInstance0(Class.java:355)
at java.lang.Class.newInstance(Class.java:308)
at org.apache.catalina.core.ApplicationFilterConfig.getFilter(ApplicationFilterConfig.java:275)
at org.apache.catalina.core.ApplicationFilterConfig.setFilterDef(ApplicationFilterConfig.java:422)
at org.apache.catalina.core.ApplicationFilterConfig.(ApplicationFilterConfig.java:115)
at org.apache.catalina.core.StandardContext.filterStart(StandardContext.java:4072)
at org.apache.catalina.core.StandardContext.start(StandardContext.java:4726)
at org.apache.catalina.core.ContainerBase.start(ContainerBase.java:1057)
at org.apache.catalina.core.StandardHost.start(StandardHost.java:840)
at org.apache.catalina.core.ContainerBase.start(ContainerBase.java:1057)
at org.apache.catalina.core.StandardEngine.start(StandardEngine.java:463)
at org.apache.catalina.core.StandardService.start(StandardService.java:525)
at org.apache.catalina.core.StandardServer.start(StandardServer.java:754)
at org.apache.catalina.startup.Catalina.start(Catalina.java:595)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at org.apache.catalina.startup.Bootstrap.start(Bootstrap.java:289)
at org.apache.catalina.startup.Bootstrap.main(Bootstrap.java:414)
This is because of null XWorkConverter instance.
Please let me know why it is not getting injected.
Thanks in advance
You need to implement a ValueStackFactory and register it in your struts.xml, as follows:
<bean type="com.opensymphony.xwork2.util.ValueStackFactory"
name="yourOgnlValueStackFactory"
class="com.example.YourOgnlValueStackFactory" />
Then, set your implementation as the factory to use, using:
<constant name="struts.valueStackFactory" value="yourOgnlValueStackFactory"/>
Update
I'm not sure if you are able to mix field and method injection like you are doing. Try moving the #Inject annotations back to the setter methods and see if that resolves the issue.

Resources