ManagedProperty not working - jsf-2

I have problem with JSF 2 property binding and honestly I hit a wall here..
What I want to accomplish is this: a request-scoped bean (loginBean) process login action and stores username in the session-scoped bean (userBean). I want to inject userBean into loginBean via #ManagedProperty, but when loginBean.doLoginAction is called, userBean is set to null.
Here is the code:
UserBean class
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
#ManagedBean
#SessionScoped
public class UserBean {
private String username;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public boolean isLogged() {
if (username != null)
return true;
return false;
}
}
loginBean class:
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.RequestScoped;
#ManagedBean
#RequestScoped
public class LoginBean {
#ManagedProperty(value = "userBean")
private UserBean userBean;
private String name;
private String password;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public UserBean getUserBean() {
return userBean;
}
public void setUserBean(UserBean userBean) {
this.userBean = userBean;
}
public String doLoginAction() {
if (name.equals("kamil") && password.equals("kamil")) {
userBean.setUsername(name);
}
return null;
}
public String doLogoutAction() {
return null;
}
}
Any ideas what I'm doing wrong here?

You need to specify an EL expression #{}, not a plain string:
#ManagedProperty(value = "#{userBean}")
private UserBean userBean;
or, shorter, since the value attirbute is the default already:
#ManagedProperty("#{userBean}")
private UserBean userBean;
See also:
Communication in JSF2 - Injecting managed beans in each other

Related

Not able to populate the User object when using Spring OAuth2 Jdbc token store

I updated Roy Clarkson's Spring REST service (https://github.com/royclarkson/spring-rest-service-oauth) with a Jdbc-based token store. The original implementation uses an in-memory token store. I was able to see the user details in the User object. On the other hand, after switching to Jdbc-based token store, all the fields in the User object were empty. It appears somehow Spring security was not able to associate the access token with the user under which I obtained the token when I was using Jdbc-based token store.
The in-memory token store implementation:
#Configuration
#EnableAuthorizationServer
protected static class AuthorizationServerConfiguration extends
AuthorizationServerConfigurerAdapter {
#Autowired
private DataSource dataSource;
private TokenStore tokenStore = new InMemoryTokenStore();
#Autowired
#Qualifier("authenticationManagerBean")
private AuthenticationManager authenticationManager;
#Autowired
private CustomUserDetailsService userDetailsService;
#Autowired
private ClientDetailsService clientDetailsService;
#Bean
public ClientDetailsService clientDetailsService() {
return new JdbcClientDetailsService(dataSource);
}
#Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints)
throws Exception {
// #formatter:off
endpoints
.tokenStore(this.tokenStore)
.authenticationManager(this.authenticationManager)
.userDetailsService(userDetailsService);
// #formatter:on
}
#Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
clients
.withClientDetails(clientDetailsService);
}
#Bean
#Primary
public DefaultTokenServices tokenServices() {
DefaultTokenServices tokenServices = new DefaultTokenServices();
tokenServices.setSupportRefreshToken(true);
tokenServices.setTokenStore(this.tokenStore);
return tokenServices;
}
}
The REST endpoint:
#RequestMapping("/greeting")
public Greeting greeting(#AuthenticationPrincipal User user) {
return new Greeting(counter.incrementAndGet(), String.format(template, user.getName()));
}
user.getName() returns the name of the user under which I obtained the access token.
The jdbc token store implementation:
#Configuration
#EnableAuthorizationServer
protected static class AuthorizationServerConfiguration extends
AuthorizationServerConfigurerAdapter {
#Autowired
private DataSource dataSource;
#Autowired
private TokenStore tokenStore;
#Bean
public TokenStore tokenStore() {
return new JdbcTokenStore(dataSource);
}
#Autowired
#Qualifier("authenticationManagerBean")
private AuthenticationManager authenticationManager;
#Autowired
private CustomUserDetailsService userDetailsService;
#Autowired
private ClientDetailsService clientDetailsService;
#Bean
public ClientDetailsService clientDetailsService() {
return new JdbcClientDetailsService(dataSource);
}
#Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints)
throws Exception {
// #formatter:off
endpoints
.tokenStore(this.tokenStore)
.authenticationManager(this.authenticationManager)
.userDetailsService(userDetailsService);
// #formatter:on
}
#Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
clients
.withClientDetails(clientDetailsService);
}
#Bean
#Primary
public DefaultTokenServices tokenServices() {
DefaultTokenServices tokenServices = new DefaultTokenServices();
tokenServices.setSupportRefreshToken(true);
tokenServices.setTokenStore(this.tokenStore);
return tokenServices;
}
}
The REST endpoint:
#RequestMapping("/greeting")
public Greeting greeting(#AuthenticationPrincipal User user) {
return new Greeting(counter.incrementAndGet(), String.format(template, user.getName()));
}
user.getName() returns null.
CustomUserDetailsService
#Service
public class CustomUserDetailsService implements UserDetailsService {
private final UserRepository userRepository;
#Autowired
public CustomUserDetailsService(UserRepository userRepository) {
this.userRepository = userRepository;
}
#Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
User user = userRepository.findByLogin(username);
if (user == null) {
throw new UsernameNotFoundException(String.format("User %s does not exist!", username));
}
return new UserRepositoryUserDetails(user);
}
private final static class UserRepositoryUserDetails extends User implements UserDetails {
private static final long serialVersionUID = 1L;
private UserRepositoryUserDetails(User user) {
super(user);
}
#Override
public Collection<? extends GrantedAuthority> getAuthorities() {
return getRoles();
}
#Override
public String getUsername() {
return getLogin();
}
#Override
public boolean isAccountNonExpired() {
return true;
}
#Override
public boolean isAccountNonLocked() {
return true;
}
#Override
public boolean isCredentialsNonExpired() {
return true;
}
#Override
public boolean isEnabled() {
return true;
}
}
}
User
#Entity
public class User {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Integer id;
#NotEmpty
private String name;
#NotEmpty
#Column(unique = true, nullable = false)
private String login;
#NotEmpty
private String password;
#NotEmpty
private String privilege;
#JsonIgnore
#ManyToMany(fetch = FetchType.EAGER)
#JoinTable(name = "user_role", joinColumns = { #JoinColumn(name = "user_id") }, inverseJoinColumns = { #JoinColumn(name = "role_id") })
private Set<Role> roles = new HashSet<Role>();
public User() {
}
public User(User user) {
super();
this.id = user.getId();
this.name = user.getName();
this.login = user.getLogin();
this.password = user.getPassword();
this.roles = user.getRoles();
this.privilege = user.getPrivilege();
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getLogin() {
return login;
}
public void setLogin(String login) {
this.login = login;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getPrivilege() {return privilege; }
public void setPrivilege(String privilege) {this.privilege = privilege; }
public Set<Role> getRoles() {
return roles;
}
public void setRoles(Set<Role> roles) {
this.roles = roles;
}
}
The issue is that the "UserRepositoryUserDetails" you are creating is not serializable.
UserRepositoryUserDetails is implementing "UserDetails" which is Serializable but the class it is extending "User" is not Serializable.
You must be getting a warning also from comiler to add a serialId.
Solution
Make your UserRepositoryUserDetails as serializable.
After making User class serializable everything worked as expected.

Swagger springfox hide model property on POST

Would like to know how to hide a model property in Swagger on POST. I have tried both Swagger-springmvc (0.9.3) and Springfox (supports swagger spec 2.0) to no avail.
Problem being I would like to see this in the GET requests through Swagger. But not POST requests, since id is auto-assigned, I would like to hide it just for the POST request.
public class RestModel {
private int id;
#JsonProperty
private String name;
#JsonProperty
public int getId() {
return 0;
}
#JsonIgnore
public void setId(int customerId) {
this.customerId = customerId;
}
public int getName() {
return "abc";
}
public void setName(String name) {
this.name = name;
}
}
So on GET, I should see:
{
"id": 0,
"name" : "abc"
}
And on POST, I should see just:
{
"name"
}
Tried adding: #ApiModelProperty(readonly=true). But that didn't help.
I have solved this with simply extending the Object that I want to hide a property of when using as request parameter.
Example:
I have the object Person.java:
import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonView;
import org.joda.time.DateTime;
import org.joda.time.Years;
import java.util.Date;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import io.swagger.annotations.ApiModelProperty;
/**
* Simple Person pojo
*/
#Entity
public class Person {
#GeneratedValue(strategy = GenerationType.AUTO)
#Id
private Long dbId;
private String name;
private Long id;
#JsonFormat(pattern="yyyy-MM-dd")
private Date birthDate;
private String gender;
public Person() {
}
public Person(long dbId) {
this.dbId = dbId;
}
public Person(Long id, String name, Date birthDate, String gender) {
this.id = id;
this.name = name;
this.birthDate = birthDate;
this.gender = gender;
}
public Long getDbId() {
return dbId;
}
public String getName() {
return name;
}
public Date getBirthDate() {
return birthDate;
}
public String getGender() {
return gender;
}
public Integer getAge() {
return Years.yearsBetween(new DateTime(birthDate), new DateTime()).getYears();
}
public void setDbId(Long dbId) {
this.dbId = dbId;
}
public void setName(String name) {
this.name = name;
}
public void setBirthDate(Date birthDate) {
this.birthDate = birthDate;
}
public void setGender(String gender) {
this.gender = gender;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
}
I have simply created another class: PersonRequest.java:
import com.fasterxml.jackson.annotation.JsonIgnore;
public class PersonRequest extends Person {
#Override
#JsonIgnore
public void setDbId(Long dbId) {
super.setDbId(dbId);
}
}
RequestMapping looks simply like:
#RequestMapping(value = "/KVFirstCare/application", method = RequestMethod.POST)
public ApplicationResult application(#RequestBody List<PersonRequest> persons,
HttpServletResponse response) {
}
Works like charm :)
Unfortunately having different request and response models is not supported currently in springfox. The current thought is that we might support this feature using #JsonView in the future.

How to create joinable entities with Ebean on play framework

How to create enteties in Ebean that reference automaticly with other tabels?
For example in this case:
A user has many photo series.
A photo serie has many photos.
A photo has an extension.
An extension has no references.
Code:
#Entity
public class User extends Model {
#Id
public int id;
#OneToMany
public List<PhotoSerie> photoSeries;
//XXXX
}
#Entity
public class PhotoSerie extends Model {
#Id
public int id;
#OneToMany
public List<Photo> photo;
//XXXX
}
#Entity
public class Photo extends Model {
#Id
public int id;
#OneToOne
PhotoExtension photoExtension;
//XXXX
}
#Entity
public class PhotoExtension extends Model {
#Id
public int id;
public String extension;
//XXXX
}
The following error will be generated:
[error] c.a.e.s.d.BeanDescriptorManager - Error in deployment
javax.persistence.PersistenceException: Error on models.PhotoSerie.photo. #OneTo
Many MUST have Cascade.PERSIST or Cascade.ALL bejavax.persistence.PersistenceExc
eption: Error on models.PhotoSerie.photo. #OneToMany MUST have Cascade.PERSIST o
r Cascade.ALL because this is a unidirectional relationship. That is, there is n
o property of type class models.PhotoSerie on class models.Photocause this is a
unidirectional relationship. That is, there is no property of type class models.
PhotoSerie on class models.Photo
How can I create entities that join in a correct way with other tables?
You need the mappedBy on your OneToMany annotations, and CascadeType.ALL on the owner of the relationship. EBean is a little different that regular ORM, and in the play docs, they mention to use setter/getter instead of field reference. Also you need some finders to do lookups. So using setter/getter approach, with play 2.1.2 (at least what I tested with) this works:
User:
package models.test;
import play.db.ebean.Model;
import javax.persistence.*;
import java.util.ArrayList;
import java.util.List;
#Entity
public class User extends Model {
#Id
public int id;
public String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
#OneToMany(cascade = CascadeType.ALL, mappedBy = "user")
public List<PhotoSeries> photoSeries;
public static Finder<String, User> find = new Finder<String, User>(
String.class, User.class);
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public List<PhotoSeries> getPhotoSeries() {
return photoSeries;
}
public void setPhotoSeries(List<PhotoSeries> photoSeries) {
this.photoSeries = photoSeries;
}
}
PhotoSeries:
package models.test;
import play.db.ebean.Model;
import javax.persistence.*;
import java.util.ArrayList;
import java.util.List;
#Entity
public class PhotoSeries extends Model {
#Id
public int id;
#OneToMany(cascade = CascadeType.ALL, mappedBy = "photoSeries")
public List<Photo> photoList;
#ManyToOne
public User user;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public List<Photo> getPhotoList() {
return photoList;
}
public void setPhotoList(List<Photo> photoList) {
this.photoList = photoList;
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
}
PhotoExtension:
package models.test;
import play.db.ebean.Model;
import javax.persistence.Entity;
import javax.persistence.Id;
#Entity
public class PhotoExtension extends Model {
#Id
public int id;
public String extension;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getExtension() {
return extension;
}
public void setExtension(String extension) {
this.extension = extension;
}
}
Photo:
package models.test;
import play.db.ebean.Model;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.ManyToOne;
import javax.persistence.OneToOne;
#Entity
public class Photo extends Model {
#Id
public int id;
#OneToOne
PhotoExtension photoExtension;
#ManyToOne
PhotoSeries photoSeries;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public PhotoExtension getPhotoExtension() {
return photoExtension;
}
public void setPhotoExtension(PhotoExtension photoExtension) {
this.photoExtension = photoExtension;
}
public PhotoSeries getPhotoSeries() {
return photoSeries;
}
public void setPhotoSeries(PhotoSeries photoSeries) {
this.photoSeries = photoSeries;
}
}
#Test
public void testPhotoSeries() {
User user = new User();
user.setName("Bob");
List<PhotoSeries> photoSeriesList = new ArrayList<PhotoSeries>();
PhotoSeries photoSeries = new PhotoSeries();
photoSeries.setUser(user);
photoSeriesList.add(photoSeries);
user.setPhotoSeries(photoSeriesList);
user.save();
user = User.find.where().eq("name", "Bob").findUnique();
log.info("user has " + user.getPhotoSeries().size() + " photo series");
List<Photo> photoList = new ArrayList<Photo>();
Photo photo = new Photo();
photoList.add(photo);
photoSeries = user.getPhotoSeries().get(0);
photoSeries.setPhotoList(photoList);
user.update();
user = User.find.where().eq("name", "Bob").findUnique();
photoSeries = user.getPhotoSeries().get(0);
photo = photoSeries.getPhotoList().get(0);
log.info("photo " + photo);
}

set method of long variable (setMobile() ) gives error during runtime in action class of struts 2 framework

package com.kumar.student;
import java.util.List;
import com.opensymphony.xwork2.ActionSupport;
public class StudentAction extends ActionSupport {
private static final long serialVersionUID = 1L;
private String name;
private String rollNumber;
private String department;
private String year;
private String dob;
private String email;
private long mobile;
private List<String> gender;
#Override
public String execute() {
return "success";
}
// all setter & getter method for remaining variable
public long getMobile() {
return mobile;
}
public void setMobile(long mobile) {
this.mobile = mobile;
}
public List<String> getGender() {
return gender;
}
public void setGender(List<String> gender) {
this.gender = gender;
}
}
In the above code setMobile(Long mobile) method gives the below exception:
java.lang.NoSuchMethodException: com.kumar.student.StudentAction.setMobile([Ljava.lang.String;)

Managed Property is null defined in Managed Bean

The Managed Property value is null even though the setter method is added in the Managed Bean.
#ManagedBean
#ViewScoped
#XmlRootElement(name = "name")
public class Name{
private String firstName;
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName){
this.firstName= firstName;
}
}
#ManagedBean(eager=true)
#ViewScoped
public class Person{
#ManagedProperty(value = "#{name}")
private Name name;
public String displayName(){
name.getFirstName(); //name is null
}
public void setName(Name name){
this.name= name;
}
}

Resources