Java-Spring-JUnit5-Mockito Test Setup - java

I am trying to set up a testing environment using an expectedPojo, but I continue getting the error that the constructor is undefined. From the error, I see it is listing the LocalTimeDate in the expectedPojo as String which may be the cause, but I am unfamiliar with testing with a LocalDateTime entry.
public class UserPojo {
private int id;
private String name;
private String email;
private String phoneNumber;
private String username;
private String password;
private boolean darkModePreference;
private LocalDateTime registerDate;
private int roleId;
public UserPojo() {
}
public UserPojo(int id, String name, String email, String phoneNumber, String username, String password,
boolean darkModePreference, LocalDateTime registerDate, int roleId) {
super();
this.id = id;
this.name = name;
this.email = email;
this.phoneNumber = phoneNumber;
this.username = username;
this.password = password;
this.darkModePreference = darkModePreference;
this.registerDate = registerDate;
this.roleId = roleId;
}
#ExtendWith(MockitoExtension.class)
public class LoginAndRegisterTest {
#Mock
UserDao userDao;
#InjectMocks
UserServiceImpl userService;
private UserPojo expectedPojo;
private UserEntity dummyEntity;
#BeforeEach
public void setup() {
LocalDateTime now;
expectedPojo = new UserPojo(1, "Goldendeep", "golden#coolkids.com", "333-343-3434", "golden", "kaur11", false, "2022-06-25T22:37:24.894", 2);
dummyEntity = new UserEntity(1, "Goldendeep", "golden#coolkids.com", "333-343-3434", "golden", "kaur11", false, "2022-06-25T22:37:24.894", 2);
}

While creating the object of UserPojo class you are passing the second-to-last argument as String instead an argument of LocalDateTime type is expected, which is causing the issue. Either provide the argument of LocalDateTime type or modify the constructor definition to accept String argument.

Related

"inStream parameter is null" Server Error(REST API)

I want to convert an old application to a new one in which i make HTTP calls (GET/POST/DELETE). I have a model package where i have my POJO classes and i made a DTO package where i have Dto classes. When i make a simple GET method to take a String message as a response i dont have any problem but when i use dependency injection and i want to use GET or POST methods to see some details about my app i get in postman this message: inStream parameter is null
OwnerResource.java
#Path("ownerResource")
public class OwnerResource {
#GET
public Response ping() { // When i use only this method i dont have any problem and i can see the message
return Response
.ok("pang")
.build();
}
// When i use the below code i have problem in HTTP calls
#Inject
private OwnerService ownerService;
#GET
#Path("owner/{ownerId}")
#Produces("application/json")
public RestApiResult<PropertyOwnerDto> getOwner(#PathParam("ownerId") int ownerId) {
return ownerService.getOwner(ownerId);
}
#POST
#Path("owner")
#Produces("application/json")
#Consumes("application/json")
public void createNewOwner(PropertyOwnerDto owner) {
ownerService.createPropertyOwner(owner);
}
}
PropertyOwner.java
#Data
#NoArgsConstructor
#Entity(name = "propertyowner")
#Table
public class PropertyOwner extends PersistentClass {
// id is in PersistenceClass
private int vat;
private String name;
private String surname;
private String address;
private String phoneNumber;
private String email;
private String username;
private String password;
#OneToMany(mappedBy = "owner", orphanRemoval = true)
private List<Property> properties;
public PropertyOwner(int vat, String name, String surname, String address, String phoneNumber, String email, String username, String password) {
this.vat = vat;
this.name = name;
this.surname = surname;
this.address = address;
this.phoneNumber = phoneNumber;
this.email = email;
this.username = username;
this.password = password;
}
}
PropertyOwnerDto.java
#Data#Getter#Setter
public class PropertyOwnerDto {
private int vat;
private String name;
private String surname;
private String address;
private String phoneNumber;
private String email;
private String username;
private String password;
public PropertyOwnerDto() {
}
public PropertyOwnerDto(PropertyOwner propertyOwner) {
this.vat = propertyOwner.getVat();
this.name = propertyOwner.getName();
this.surname = propertyOwner.getSurname();
this.address = propertyOwner.getAddress();
this.phoneNumber = propertyOwner.getPhoneNumber();
this.email = propertyOwner.getEmail();
this.username = propertyOwner.getUsername();
this.password = propertyOwner.getPassword();
}
public PropertyOwner asOwner() {
PropertyOwner propertyOwner = new PropertyOwner();
propertyOwner.setVat(vat);
propertyOwner.setName(name);
propertyOwner.setSurname(surname);
propertyOwner.setAddress(address);
propertyOwner.setPhoneNumber(phoneNumber);
propertyOwner.setEmail(email);
propertyOwner.setUsername(username);
propertyOwner.setPassword(password);
return propertyOwner;
}
OwnerService.java
public interface OwnerService {
void createPropertyOwner(PropertyOwnerDto ownerDto);
RestApiResult<PropertyOwnerDto> getOwner(int ownerId);
}
OwnerServiceImpl.java
public class OwnerServiceImpl implements OwnerService {
private final Properties sqlCommands = new Properties();
{
final ClassLoader loader = getClass().getClassLoader();
try ( InputStream config = loader.getResourceAsStream("sql.properties")) {
sqlCommands.load(config);
} catch (IOException e) {
throw new IOError(e);
}
}
private static final Logger logger = LogManager.getLogger(OwnerServiceImpl.class);
#Inject
private PropertyOwnerRepository propertyOwnerRepository;
#Inject
private PropertyRepository propertyRepository;
#Inject
private RepairRepository repairRepository;
// SOME OTHER CODE HERE //
#Override
public RestApiResult<PropertyOwnerDto> getOwner(int ownerId) {
PropertyOwnerDto ownerDto = new PropertyOwnerDto(propertyOwnerRepository.findById(ownerId));
return new RestApiResult<PropertyOwnerDto>(ownerDto, 0, "successful");
}
#Override
public void registerNewPropertyDto(PropertyDto propertyDto) {
propertyRepository.create(propertyDto.asProperty());
}
}
beans.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/beans_2_0.xsd"
bean-discovery-mode="all">
</beans>
I use WILDFLY as application server.

Error upon testing OneToMany relationship to Postman with Spring Boot

#Entity
#Table(name = "users")
public class User implements Serializable {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(nullable = false, unique = true)
private Long id;
private String firstName;
private String lastName;
private String email;
private String password;
#OneToOne(fetch = FetchType.LAZY,
cascade = CascadeType.ALL,
mappedBy = "user")
private UserProfile userProfile;
// Hibernate requires a no-arg constructor
public User() {
}
public User(String firstName, String lastName, String email, String password) {
this.firstName = firstName;
this.lastName = lastName;
this.email = email;
this.password = password;
}
// Getters and Setters (Omitted for brevity)
}
UserProfile
#Entity
#Table(name = "user_profiles")
public class UserProfile implements Serializable {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String phoneNumber;
private String gender;
private String address1;
private String address2;
private String street;
private String city;
private String state;
private String country;
private String zipCode;
#OneToOne(fetch = FetchType.LAZY, optional = false)
#JoinColumn(name = "user_id", nullable = false)
private User user;
public UserProfile() {
}
public UserProfile(String phoneNumber, String gender,
String address1, String address2, String street, String city,
String state, String country, String zipCode) {
this.phoneNumber = phoneNumber;
this.gender = gender;
this.address1 = address1;
this.address2 = address2;
this.street = street;
this.city = city;
this.state = state;
this.country = country;
this.zipCode = zipCode;
}
// Getters and Setters (Omitted for brevity)
}
My Service
#Component
public class UserService {
#Autowired
UserRepo userRepo;
public ResponseEntity<User> createUser(String firstName, String lastName, String email, String password){
User user=new User(firstName,lastName,email,password);
return new ResponseEntity<>(user,HttpStatus.OK);
}
public ResponseEntity<List<User>> savedataBase(User user){
userRepo.save(user);
return new ResponseEntity<>( userRepo.findAll(), HttpStatus.OK);
}
}
#Component
public class UserPServer {
#Autowired
UserProfileRepo userProfileRepo;
public ResponseEntity<List<UserProfile>> save(UserProfile userProfile){
userProfileRepo.save(userProfile);
return new ResponseEntity<>( userProfileRepo.findAll(), HttpStatus.OK);
}
}
My Controller
#RestController
#RequestMapping("/user")
public class UserController {
#Autowired
UserService userService;
#GetMapping("/create/{firsName}/{lastName}/{email}/{password}")
public ResponseEntity<User> create(#PathVariable("firsName") String firstName,
#PathVariable("lastName") String lastName,
#PathVariable("email") String email,
#PathVariable("password") String password){
return userService.createUser(firstName,lastName,email,password);
}
#PostMapping("/usersave")
public ResponseEntity<List<User>> saveDateBase(#RequestBody User users){
return userService.savedataBase(users);
}
}
#RestController
#RequestMapping("/userprofile")
public class UserPConroller {
#Autowired
UserPServer userPServer;
#PostMapping("/userpsave")
public ResponseEntity<List<UserProfile>> savep(UserProfile userProfile){
return userPServer.save(userProfile);
}
}
UserProfile classes like above
I get error like this:
*Column 'user_id' cannot be null
2019-12-26 11:27:35.618 ERROR 6540 --- [nio-8883-exec-2] o.a.c.c.C.[.[.[/].[dispatcherServlet] : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is org.springframework.dao.DataIntegrityViolationException: could not execute statement; SQL [n/a]; constraint [null]; nested exception is org.hibernate.exception.ConstraintViolationException: could not execute statement] with root cause
edit your application.properties file like this
spring.jpa.hibernate.ddl-auto = update
Once you decided who is the "parent" in this relationship you should save the child first with its repository.
Lets assume it is the User.
You would do something like this in your controller
UserProfile newUser = user.getUserProfile();
userProfileRepository.save(newUser);
userRepository.save(user);
This guarantee garantee that the relation is successful.

ArrayList from user model returns null

So in the app I'm creating I have a user class defined as the following
public class User implements Serializable{
private int id;
private String username;
private String firstName;
private String lastName;
private String email;
private String password;
private String picture;
private ArrayList<String> tags;
private double rating;
private Category favorite;
private boolean star;
private Location homeLocation;
public User(int id, String username, String firstName,String lastName,String picture, ArrayList<String> tags,double rating, Category favorite, boolean star,Location homeLocation,String email,String password) {
this.id = id;
this.username = username;
this.firstName = firstName;
this.lastName = lastName;
this.picture = picture;
this.tags = tags;
this.rating = rating;
this.favorite = favorite;
this.star = star;
this.homeLocation = homeLocation;
this.email = email;
this.password = password;
}
public int getId() {
return id;
}
public String getUsername() {
return username;
}
public String getFirstName() {
return firstName;
}
public String getLastName(){ return lastName;}
public String getPicture(){ return picture;}
public ArrayList<String> getTags() {
return tags;
}
public double getRating(){ return rating;}
public Category getFavorite(){ return favorite;}
public Boolean getStar(){ return star;}
public Location getHomeLocation(){return homeLocation;}
public String getEmail(){return email;}
public String getPassword(){return password;}
public void setId(int id){
this.id = id;
}
Now, when I create a User object I pass an ArrayList<String> tags which, when logged, shows just as intended.
List<String> listTags = Arrays.asList(DummyTags.tagsNewUser);
ArrayList<String> tags = new ArrayList<>();
tags.addAll(listTags);
Log.d("Tags",tags.toString());
user = new User(0,userName,firstName,lastName,picturePlaceHolder,tags,4,category,true,loc,email,password);
However, when I use this user object in, say a profile page, and retrieve the users tags through the getter in the class it always returns null.
user = (User) getArguments().getSerializable("User");
tags = user.getTags();
Doing this always has tags be null, no matter what ArrayList I pass when creating the user object.
I also get a warning in android studio saying that invoking user.getTags() may produce a npe. Every other part of the user model works just fine. I have tried to solve this for a while now and have not been able to find anything relating to my problem so any help would be appreciated!
Try:
Bundle bundle=new Bundle();
bundle.putStringArrayList("tags",tags);
bundle.putSerializable("User",user);
and then retrieve as:
tags = getArguments().getStringArrayList("tags");
The reason that your solution does not work is that ArrayList is not implementing Serializable interface

JPA Eclipselink error inserting into table

So first a bit of back story. The issue I am having is when I create a user. Previously I had tried to create a user and assign them a role separately before discovering that by inserting into the SEC_USER_ROLE table the program was also inserting into the APP_USER table and I was getting an error about inserting duplicate values into the parent table. However, now by creating the user and role together I am getting the following error:
Primary key should be primitive (or list of primitives for composite
pk) , an instance of java.lang.Long with the primary keys filled in or
an instance of WebIntSecRole.......
Code as follows, not sure where I'm goin g wrong or the best solution at this point.
Admin.java:
//New User Creation
WebIntUser newUser = new WebIntUser();
newUser.setLoginId(newLoginName);
newUser.setCreatedBy(loggedUser);
newUser.setCreatedOn(today);
newUser.setDbAuth(true);
newUser.setDeleted(false);
newUser.setDisabled(false);
newUser.setEmail(newEmail);
newUser.setEncrypted(true);
newUser.setEncryptPassword(true);
newUser.setFirstName(newFirstName);
newUser.setLastName(newLastName);
newUser.setUpdatedBy(loggedUser);
newUser.setUpdatedOn(today);
newUser.setVersion(1);
newUser.setLdapId(1);
//userService.createUser(newUser);
//Set role for new user
WebIntSecRoleUser newUserRole = new WebIntSecRoleUser();
newUserRole.setUser(newUser);
newUserRole.setDeleted(false);
newUserRole.setRole(userService.selectRoleById(1));
//newUserRole.setCreatedBy(loggedUser);
//newUserRole.setCreatedOn(today);
//newUserRole.setUpdatedBy(loggedUser);
//newUserRole.setUpdatedOn(today);
newUserRole.setVersionNumber(0);
userService.createRole(newUserRole);
WebIntUser.java
#Entity
#Table(name = "APP_USER")
#EntityListeners(value = { AuditChangeListener.class })
public class WebIntUser implements Serializable {
public WebIntUser() {
};
public WebIntUser(String login, String pass) {
this.loginId = login;
this.password = pass;
}
private Integer userId;
private String loginId;
private String password;
private String firstName;
private String lastName;
private String email;
private boolean disabled;
private boolean deleted;
private boolean dbAuth;
private boolean isEncrypted;
private boolean encryptPassword;
private Date lastLogin;
private Date prevLogin;
private Integer version;
private Date lastPasswordChange;
private Date createdOn;
private Date updatedOn;
private String createdBy;
private String updatedBy;
private Integer ldapId;
public static interface propertyName {
String userId = "userId";
String loginId = "loginId";
String password = "password";
String firstName = "firstName";
String lastName = "lastName";
String email = "email";
String disabled = "disabled";
String deleted = "deleted";
String dbAuth = "dbAuth";
String isEncrypted = "isEncrypted";
String encryptPassword = "encryptPassword";
String lastLogin = "lastLogin";
String prevLogin = "prevLogin";
String version = "version";
String lastPasswordChange = "lastPasswordChange";
String createdOn = "createdOn";
String updatedOn = "updatedOn";
String createdBy = "createdBy";
String updatedBy = "updatedBy";
String ldapId = "ldapId";
}
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "USER_ID", nullable = false)
public Integer getUserId() {
return userId;
}
public void setUserId(Integer userId) {
this.userId = userId;
}
.....getters/setters
}
WebIntSecRoleUser.java:
#Entity
#Table(name = "SEC_ROLE_USER")
#EntityListeners(value = {AuditInfoChangeListener.class})
public class WebIntSecRoleUser implements AuditableDomainObject {
private Long id;
private WebIntSecRole role;
private WebIntUser user;
private boolean deleted;
private AuditInfo auditInfo;
private long versionNumber;
private Date createdOn;
private Date updatedOn;
private String createdBy;
private String updatedBy;
public interface propertyName extends Auditable.propertyName {
String id="id";
String role="role";
String user="user";
String deleted = "deleted";
String createdOn = "createdOn";
String updatedOn = "updatedOn";
String createdBy = "createdBy";
String updatedBy = "updatedBy";
}
public static interface permissionKey{
String UPDATE="SecRoleUser.U";
}
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
#Column(name = "ROLE_USER_ID",nullable = false, unique = true)
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
#JoinColumn(name="ROLE_ID", nullable=false)
public WebIntSecRole getRole() {
return role;
}
public void setRole(WebIntSecRole role) {
this.role = role;
}
#ManyToOne(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
#JoinColumn(name="USER_ID", nullable = false)
public WebIntUser getUser() {
return user;
}
public void setUser(WebIntUser user) {
this.user = user;
}
Getters/setters
}
Note: There is some commented out code that I'm either trying not to use anymore, or in the case of Created By and Created On etc I was getting errors for multiple inserts.
In my opinion you have missed the #ManyToOne mapping on the WebIntSecRole. You only specified the #JoinColumn.
#ManyToOne(/* desired options */)
#JoinColumn(name="ROLE_ID", nullable=false)
public WebIntSecRole getRole() {
return role;

Custom IDM authentication and Authorizer

I have custom implementation of the Picketlink IDM JPA authentication model. I got it by coping an example from there https://github.com/jboss-developer/jboss-picketlink-quickstarts/tree/master/picketlink-idm-custom-identity-model to package org.picketlink.idm.jpa.model.custom.simple. Then I have implemented this example https://github.com/pedroigor/picketlink-quickstarts/tree/master/picketlink-deltaspike-authorization .
I changed User class and UserTypeEntity in picketlink-idm-custom-identity-model example like this:
#IdentityStereotype(USER)
public class User extends AbstractIdentityType implements Account {
public static final QueryParameter USER_NAME = QUERY_ATTRIBUTE.byName("userName");
#StereotypeProperty(IDENTITY_USER_NAME)
#AttributeProperty
#Unique
private String userName;
#AttributeProperty
private String firstName;
#AttributeProperty
private String lastName;
#AttributeProperty
private String email;
#AttributeProperty
private String middleName;
#AttributeProperty
private String telephone;
#AttributeProperty
private String address;
#AttributeProperty
private int postIndex;
#AttributeProperty
private Date registerDate;
#AttributeProperty
private Date lastVisitDate;
#AttributeProperty
private boolean isOrganizer;
#AttributeProperty
private boolean isAdmin;
#Embedded
private Organizer organizer;
#Embedded
private Customer customer;
// getters and setters
}
class UserTypeEntity
#IdentityManaged(User.class)
#Entity
public class UserTypeEntity extends AbstractIdentityTypeEntity {
#AttributeValue
private String userName;
#OwnerReference
#ManyToOne(fetch = FetchType.LAZY)
private RealmTypeEntity realm;
#AttributeProperty
private String firstName;
#AttributeProperty
private String lastName;
#AttributeProperty
private String email;
#AttributeProperty
#Column(length = 255)
private String middleName;
#AttributeProperty
#Size(max = 12)
#Column(length = 12)
private String telephone;
#AttributeProperty
#Column(length = 5000)
#Size(max = 5000)
private String address;
#AttributeProperty
private int postIndex;
#AttributeProperty
private Date registerDate;
#AttributeProperty
private Date lastVisitDate;
#AttributeProperty
private boolean isOrganizer;
#AttributeProperty
private boolean isAdmin;
#Embedded
private Organizer organizer;
#Embedded
private Customer customer;
// getters and setters
}
Then I implemented Login controller:
#Named
#Stateless
public class LoginController {
#Inject
private Identity identity;
#Inject
private FacesContext facesContext;
public void login() {
AuthenticationResult result = identity.login();
if (AuthenticationResult.FAILED.equals(result)) {
facesContext.addMessage(
null,
new FacesMessage("Invalid user name or password"));
}
}
}
And Registration Controller:
#Named
#RequestScoped
public class RegistrationController {
private IdentityManager identityManager;
#Inject
private PartitionManager partitionManager;
#Inject
private FacesContext facesContext;
#Inject
private User user;
private String password;
private String passwordVerify;
private boolean isOrganizer;
public RegistrationController() {
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
public String getPasswordVerify() {
return passwordVerify;
}
public void setPasswordVerify(String passwordVerify) {
this.passwordVerify = passwordVerify;
}
public boolean getIsOrganizer() {
return isOrganizer;
}
public void setIsOrganizer(boolean isOrganizer) {
this.isOrganizer = isOrganizer;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
#Transactional
public String register() throws Exception {
if (password.isEmpty()) {
String message = LocaleBean.loadErrorMessage(facesContext, LocaleBean.EX_RESOURCE_BUNDLE_NAME, "password.empty");
facesContext.addMessage("signup:registrationPassword", new FacesMessage(message));
return "returnToSignup";
}
if (!password.equals(passwordVerify)) {
String message = LocaleBean.loadErrorMessage(facesContext, LocaleBean.EX_RESOURCE_BUNDLE_NAME, "password.NotEqual");
facesContext.addMessage("signup:registrationPassword", new FacesMessage(message));
return "returnToSignup";
}
identityManager = partitionManager.createIdentityManager(partitionManager.getPartition(Realm.class,
Resources.REALM_ACME_NAME));
if (isOrganizer) {
user.setOrganizer(true);
user.setOrganizer(new Organizer());
try {
identityManager.add(user);
} catch (IdentityManagementException e) {
String message = LocaleBean.loadErrorMessage(facesContext, LocaleBean.EX_RESOURCE_BUNDLE_NAME, "login.Registered");
facesContext.addMessage(null, new FacesMessage(message));
return "returnToSignup";
}
Password password = new Password(this.password);
identityManager.updateCredential(user, password);
RelationshipManager relationshipManager = partitionManager.createRelationshipManager();
IdentityQuery<Group> query = identityManager.createIdentityQuery(Group.class);
// query all childs of sales unit
query.setParameter(Group.NAME, Resources.ORGANIZERS_GROUP_NAME);
List<Group> groups = query.getResultList();
Group organizersGroup = groups.get(0);
relationshipManager.add(new GroupMembership(user, organizersGroup));
} else {
}
return "signin";
}
}
After that I implemented Authorizer:
#ApplicationScoped
public class SPAuthorizer {
#Secures
#Admins
public boolean doAdminsCheck(Identity identity, IdentityManager identityManager, RelationshipManager relationshipManager) throws Exception {
return hasGroup(identity, identityManager, relationshipManager, Resources.ADMINS_GROUP_NAME);
}
#Secures
#Organizers
public boolean doOrganizersCheck(Identity identity, IdentityManager identityManager, RelationshipManager relationshipManager) throws Exception {
return hasGroup(identity, identityManager, relationshipManager, Resources.ORGANIZERS_GROUP_NAME);
}
#Secures
#Customers
public boolean doCustomersCheck(Identity identity, IdentityManager identityManager, RelationshipManager relationshipManager) throws Exception {
return hasGroup(identity, identityManager, relationshipManager, Resources.CUSTOMERS_GROUP_NAME);
}
private boolean hasGroup(Identity identity, IdentityManager identityManager, RelationshipManager relationshipManager,
String groupName) {
IdentityQuery<Group> queryGroup = identityManager.createIdentityQuery(Group.class);
// query all childs of sales unit
queryGroup.setParameter(Group.NAME, groupName);
List<Group> groups = queryGroup.getResultList();
if (groups.size() == 1) {
Group group = groups.get(0);
Account user = identity.getAccount();
if (user == null) {
return false;
}
RelationshipQuery<GroupMembership> query = relationshipManager.createRelationshipQuery(GroupMembership.class);
query.setParameter(GroupMembership.GROUP, group);
query.setParameter(GroupMembership.MEMBER, user);
// user is assigned with two groups
List<GroupMembership> resultList = query.getResultList();
return resultList.size() > 0;
}
return false;
}
}
So I implemented authorization checker to check belonging user to a some group in JSF:
#Named
#Stateless
public class AuthorizationChecker {
#Inject
private Identity identity;
#Inject
private PartitionManager partitionManager;
public boolean hasGroup(String groupName) {
IdentityManager identityManager = partitionManager.createIdentityManager(partitionManager.getPartition(Realm.class,
Resources.REALM_ACME_NAME));
IdentityQuery<Group> queryGroup = identityManager.createIdentityQuery(Group.class);
// query all childs of sales unit
queryGroup.setParameter(Group.NAME, groupName);
List<Group> groups = queryGroup.getResultList();
if (groups.size() == 1) {
Group group = groups.get(0);
Account user = identity.getAccount();
RelationshipManager relationshipManager = partitionManager.createRelationshipManager();
RelationshipQuery<GroupMembership> query = relationshipManager.createRelationshipQuery(GroupMembership.class);
query.setParameter(GroupMembership.GROUP, group);
query.setParameter(GroupMembership.MEMBER, user);
// user is assigned with two groups
List<GroupMembership> resultList = query.getResultList();
return resultList.size() > 0;
}
return false;
}
}
But an instance of Identity in hasGroup of the SPAuthorizer doesn't corresponds to an instance that I have in AuthorizationChecker. I checked it in debugger. And when I do identity.getAccount(); it returns null although user was authenticated. Any idea what to do?
The problem was in missed annotation #Stateless in Controller.
There is workable example https://github.com/lynx-r/picketlink-deltaspike-authorization-and-idm-custom-identity-model.

Categories

Resources