How to enable or disable user in Spring Boot Security - java

I am using spring security for my spring boot app ,this is my user entity
#Document(collection = "users")
public class User {
#Id
private String id;
private String username;
private String isactive;
private String type;
private String date;
private String registrarid;
private String registrartype;
public String getRegistrarid() {
return registrarid;
}
public void setRegistrarid(String registrarid) {
this.registrarid = registrarid;
}
public String getRegistrartype() {
return registrartype;
}
public void setRegistrartype(String registrartype) {
this.registrartype = registrartype;
}
public String getIsactive() {
return isactive;
}
public void setIsactive(String isactive) {
this.isactive = isactive;
}
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
long temp;
temp = Double.doubleToLongBits(balance);
result = prime * result + (int) (temp ^ (temp >>> 32));
result = prime * result + ((date == null) ? 0 : date.hashCode());
result = prime * result + (enabled ? 1231 : 1237);
result = prime * result + ((id == null) ? 0 : id.hashCode());
result = prime * result + ((isactive == null) ? 0 : isactive.hashCode());
result = prime * result + ((password == null) ? 0 : password.hashCode());
result = prime * result + ((registrarid == null) ? 0 : registrarid.hashCode());
result = prime * result + ((registrartype == null) ? 0 : registrartype.hashCode());
result = prime * result + ((roles == null) ? 0 : roles.hashCode());
result = prime * result + ((type == null) ? 0 : type.hashCode());
result = prime * result + ((username == null) ? 0 : username.hashCode());
return result;
}
#Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
User other = (User) obj;
if (Double.doubleToLongBits(balance) != Double.doubleToLongBits(other.balance))
return false;
if (date == null) {
if (other.date != null)
return false;
} else if (!date.equals(other.date))
return false;
if (enabled != other.enabled)
return false;
if (id == null) {
if (other.id != null)
return false;
} else if (!id.equals(other.id))
return false;
if (isactive == null) {
if (other.isactive != null)
return false;
} else if (!isactive.equals(other.isactive))
return false;
if (password == null) {
if (other.password != null)
return false;
} else if (!password.equals(other.password))
return false;
if (registrarid == null) {
if (other.registrarid != null)
return false;
} else if (!registrarid.equals(other.registrarid))
return false;
if (registrartype == null) {
if (other.registrartype != null)
return false;
} else if (!registrartype.equals(other.registrartype))
return false;
if (roles == null) {
if (other.roles != null)
return false;
} else if (!roles.equals(other.roles))
return false;
if (type == null) {
if (other.type != null)
return false;
} else if (!type.equals(other.type))
return false;
if (username == null) {
if (other.username != null)
return false;
} else if (!username.equals(other.username))
return false;
return true;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
private double balance;
public double getBalance() {
return balance;
}
public void setBalance(double balance) {
this.balance = balance;
}
private boolean enabled=true;
#DBRef
private Set<Role> roles;
private String password;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public boolean isEnabled() {
return enabled;
}
public void setEnabled(boolean enabled) {
this.enabled = enabled;
}
public Set<Role> getRoles() {
return roles;
}
public void setRoles(Set<Role> roles) {
this.roles = roles;
}
#Override
public String toString() {
return "User [id=" + id + ", username=" + username + ", isactive=" + isactive + ", type=" + type + ", date="
+ date + ", registrarid=" + registrarid + ", registrartype=" + registrartype + ", balance=" + balance
+ ", enabled=" + enabled + ", roles=" + roles + ", password=" + password + "]";
}
}
This is my CustomUser Details Service
#Service
public class CustomUserDetailsService implements UserDetailsService{
#Autowired
private UserServiceImpl userservice;
#Autowired
private RoleServiceImpl roleservice;
#Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
// TODO Auto-generated method stub
User user=userservice.getUserByusername(username);
if(user != null) {
List<GrantedAuthority> authorities = getUserAuthority(user.getRoles());
return buildUserForAuthentication(user, authorities);
}
else {
throw new UsernameNotFoundException("username not found");
}
}
private List<GrantedAuthority> getUserAuthority(Set<Role> userRoles) {
Set<GrantedAuthority> roles = new HashSet<>();
userRoles.forEach((role) -> {
roles.add(new SimpleGrantedAuthority(role.getRole()));
});
List<GrantedAuthority> grantedAuthorities = new ArrayList<>(roles);
return grantedAuthorities;
}
private UserDetails buildUserForAuthentication(User user, List<GrantedAuthority> authorities) {
return new org.springframework.security.core.userdetails.User(user.getUsername(), user.getPassword(), authorities);
}
}
Currently Custom UserDetails ServiceChecks if username exists or not and then if not found throws exception ,I want to check if the user is enabled or not as well in that ,so that I can set isenabled false as well to deactivate the users.

Just Check for is enabled in loadByUsername method ,Further you can activate and deactivate accordingly.I hope it helps
#Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
// TODO Auto-generated method stub
User user=userservice.getUserByusername(username);
if(user != null && user.isEnabled()) {//here you can check that
List<GrantedAuthority> authorities = getUserAuthority(user.getRoles());
return buildUserForAuthentication(user, authorities);
}
else {
throw new UsernameNotFoundException("username not found");
}
}

A better approach would be to implement your User entity with org.springframework.security.core.userdetails.UserDetails
and override various methods like
#Override
public boolean isAccountNonExpired() {
return true;
}
#Override
public boolean isAccountNonLocked() {
return true;
}
#Override
public boolean isCredentialsNonExpired() {
return true;
}
#Override
public boolean isEnabled() {
if(this.isactive == null) return false;
if(!this.isactive.equals("ACTIVE")) return false;
return true;
}
Override other methods also as required. Spring Security will automatically give org.springframework.security.authentication.DisabledException: User is disabled exception based on isEnabled() result.

If you want to persist the enabled or locked status in the database then you would want to pass the getters for the locked and enabled fields from the User model instance to the UserDetailsImpl constructor.
Firstly,
The authenticate function of the authenticationManager returns these exceptions:
DisabledException, if an account is disabled
LockedException, if an account is locked
BadCredentialsException, if incorrect credentials are presented
You would want to do something along the lines of this:
try {
Authentication authentication = authenticationManager.authenticate(
new UsernamePasswordAuthenticationToken(authreq.getUsername(), authreq.getPassword()));
} catch (BadCredentialsException ex) {
// do something
} catch (LockedException ex) {
// do something
} catch (DisabledException ex) {
// do something
}
And then in the UserDetailsImpl:
public UserDetailsImpl(Integer id, String username, String email, String password,
Collection<? extends GrantedAuthority> authorities, boolean isEnabled) {
this.id = id;
this.username = username;
this.email = email;
this.password = password;
this.authorities = authorities;
this.isEnabled = isEnabled;
}
public static UserDetailsImpl build(User user) {
List<GrantedAuthority> authorities = user.getRoles().stream()
.map(role -> new SimpleGrantedAuthority(role.getName().name())).collect(Collectors.toList());
return new UserDetailsImpl(user.getId(), user.getUsername(), user.getEmail(), user.getPassword(), authorities,
user.isIsenabled());
}
By the way, in order for this to work you must remove the if statement from the previous answer by #Shubh, instead just have this: return buildUserForAuthentication(user, authorities);
I think this is pretty much what you are looking for.

Related

Need help traversing an ArrayList of HashMap

I need to loop through an ArrayList and look for a particular "keys" HashMap and return the corresponding "params" HashMap as shown in the screenshot.
This is what I have so far but it's not working
private void getParam() {
List<Map<String, Object>> matrix = transactionInfoMatrix.getMatrixTransactionInfo();
MatrixTransactionInfoKeys key = new MatrixTransactionInfoKeys("OP/OP", "2777", "CT", "NBCTRANSFER", "AMT");
for (Map<String, Object> entry : matrix) {
if (entry.containsValue(key)) {
System.out.println("Found it");
}
}
}
Here is the MatrixTransactionInfoKeys class, but I have removed the getters and setters for the purposes of this post.
public class MatrixTransactionInfoKeys {
private String accountType;
private String applicationSourceCode;
private String operationType;
private String service;
private String transactionType;
public MatrixTransactionInfoKeys(String accountType, String applicationSourceCode, String operationType, String service, String transactionType) {
this.accountType = accountType;
this.applicationSourceCode = applicationSourceCode;
this.operationType = operationType;
this.service = service;
this.transactionType = transactionType;
}
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((accountType == null) ? 0 : accountType.hashCode());
result = prime * result + ((applicationSourceCode == null) ? 0 : applicationSourceCode.hashCode());
result = prime * result + ((operationType == null) ? 0 : operationType.hashCode());
result = prime * result + ((service == null) ? 0 : service.hashCode());
result = prime * result + ((transactionType == null) ? 0 : transactionType.hashCode());
return result;
}
#Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
MatrixTransactionInfoKeys other = (MatrixTransactionInfoKeys) obj;
if (accountType == null) {
if (other.accountType != null) {
return false;
}
} else if (!accountType.equals(other.accountType)) {
return false;
}
if (applicationSourceCode == null) {
if (other.applicationSourceCode != null) {
return false;
}
} else if (!applicationSourceCode.equals(other.applicationSourceCode)) {
return false;
}
if (operationType == null) {
if (other.operationType != null) {
return false;
}
} else if (!operationType.equals(other.operationType)) {
return false;
}
if (service == null) {
if (other.service != null) {
return false;
}
} else if (!service.equals(other.service)) {
return false;
}
if (transactionType == null) {
return other.transactionType == null;
} else
return transactionType.equals(other.transactionType);
}
#Override
public String toString() {
return "MatrixTransactionInfoKeys [service=" + service + ", applicationSourceCode=" + applicationSourceCode
+ ", transactionType=" + transactionType + ", operationType=" + operationType + ", accountType=" + accountType + "]";
}
}
Remaking this answer, since I originally misinterpreted the question.
Based on the code supplied, assuming the MatrixTransactionInfoKeys in the map actually match and are created similarly, I get "Found it" in the output of this:
public class MatrixCheck {
public TransactionInfoMatrix transactionInfoMatrix;
private void getParam() {
List<Map<String, Object>> matrix = transactionInfoMatrix.getMatrixTransactionInfo();
MatrixTransactionInfoKeys key = new MatrixTransactionInfoKeys("OP/OP", "2777", "CT", "NBCTRANSFER", "AMT");
for (Map<String, Object> entry : matrix) {
if (entry.containsValue(key)) {
System.out.println("Found it");
}
}
}
public static void main( String[] args ) {
MatrixCheck matrixCheck = new MatrixCheck();
matrixCheck.transactionInfoMatrix = new TransactionInfoMatrix();
matrixCheck.transactionInfoMatrix.transactionInfo = new ArrayList<>();
matrixCheck.transactionInfoMatrix.transactionInfo.add( new HashMap<>() );
// Add the object to the map exactly as how it is
// constructed in the "getParam" portion
matrixCheck.transactionInfoMatrix.transactionInfo.get(0).put( "MyTest", new MatrixTransactionInfoKeys("OP/OP", "2777", "CT", "NBCTRANSFER", "AMT") );
matrixCheck.getParam();
}
static class TransactionInfoMatrix {
List<Map<String,Object>> transactionInfo;
public List<Map<String,Object>> getMatrixTransactionInfo() {
return transactionInfo;
}
}
static class MatrixTransactionInfoKeys {
private String accountType;
private String applicationSourceCode;
private String operationType;
private String service;
private String transactionType;
public MatrixTransactionInfoKeys(String accountType, String applicationSourceCode, String operationType, String service, String transactionType) {
this.accountType = accountType;
this.applicationSourceCode = applicationSourceCode;
this.operationType = operationType;
this.service = service;
this.transactionType = transactionType;
}
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((accountType == null) ? 0 : accountType.hashCode());
result = prime * result + ((applicationSourceCode == null) ? 0 : applicationSourceCode.hashCode());
result = prime * result + ((operationType == null) ? 0 : operationType.hashCode());
result = prime * result + ((service == null) ? 0 : service.hashCode());
result = prime * result + ((transactionType == null) ? 0 : transactionType.hashCode());
return result;
}
#Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
MatrixTransactionInfoKeys other = (MatrixTransactionInfoKeys) obj;
if (accountType == null) {
if (other.accountType != null) {
return false;
}
} else if (!accountType.equals(other.accountType)) {
return false;
}
if (applicationSourceCode == null) {
if (other.applicationSourceCode != null) {
return false;
}
} else if (!applicationSourceCode.equals(other.applicationSourceCode)) {
return false;
}
if (operationType == null) {
if (other.operationType != null) {
return false;
}
} else if (!operationType.equals(other.operationType)) {
return false;
}
if (service == null) {
if (other.service != null) {
return false;
}
} else if (!service.equals(other.service)) {
return false;
}
if (transactionType == null) {
return other.transactionType == null;
} else
return transactionType.equals(other.transactionType);
}
#Override
public String toString() {
return "MatrixTransactionInfoKeys [service=" + service + ", applicationSourceCode=" + applicationSourceCode
+ ", transactionType=" + transactionType + ", operationType=" + operationType + ", accountType=" + accountType + "]";
}
}
}

getting all keys belonging to one object in a hashmap

Below is my user Class. I also have a Card class which is the parent class of a Single currency card class and a multi card currency class.
I am fairly new to coding and have trouble understanding some concepts. What I need to do is return the cards that the user owns if the username and password match. This is in the getCards method. After this, i need to add the card to the Hashmap list if the username and password match. Any tips or other sites that would really help as I struggle a lot with the HashMap concept.
public class User {
String username;
String password;
User user;
HashMap<String,Card> userHash = new HashMap <String, Card>(); //key is the cardID
public User(String username, String password)
{
this.username = username;
this.password = password;
}
public String toString()
{
return "User ---------" + "\n" + "Username: " + username + "\n" + "Password: " + password;
}
public String getUsername()
{
return username;
}
public String getPassword()
{
return password;
}
public boolean userValidate(String username, String password)
{
if (username.contains(user.getUsername()) && password.contains(user.getPassword()))
{
System.out.println("User accepted");
return true;
}else
System.out.println("Access denied");
return false;
}
public HashMap<String, Card> getCards(String username, String password)
{
for(String value : userHash.keySet())
if (user.userValidate(username, password) == true)
{
//return user's cards
return true;
}else
return null;
return null;
}
public boolean addCard(Card card, String username, String password)
{
if(user.userValidate(username, password) == true)
{
user.getCards(username, password);
}
return false;
}
The card which belongs to the user
Here is my design concept.
In this case, the user class can have many cards and each card has an id.
The validation check must be saved every time when creation user.
The userValidate method can be checked the arguments with its own values then save it to isvalid variable(boolean).
public boolean userValidate(String username, String password)
{
if (username.contains(getUsername()) && password.contains(getPassword()))
{
System.out.println("User accepted");
return isvalid = true;
}else
System.out.println("Access denied");
return isvalid = false;
}
The getCards method is simple because it checks that the isvalid is true or not.
public HashMap<String, Card> getCards() {
if (isvalid) {
// return user's cards
return userHash;
} else
return null;
}
The addCard method, I can just save the card with card id, if user validation is success or nothing...
public boolean addCard(Card card, String username, String password)
{
if(userValidate(username, password))
{
userHash.put(card.getCardId(), card);
return true;
}
return false;
}
So, come together with all these codes.
import java.util.HashMap;
class Card
{
private String cardId;
public String getCardId() {
return cardId;
}
public void setCardId(String cardId) {
this.cardId = cardId;
}
}
public class User {
private String username;
private String password;
private boolean isvalid;
HashMap<String, Card> userHash = new HashMap<String, Card>(); // key is the
// cardID
public User(String username, String password) {
this.username = username;
this.password = password;
}
public boolean userValidate(String username, String password)
{
if (username.contains(getUsername()) && password.contains(getPassword()))
{
System.out.println("User accepted");
return isvalid = true;
}else
System.out.println("Access denied");
return isvalid = false;
}
public String toString() {
return "User ---------" + "\n" + "Username: " + username + "\n" + "Password: " + password;
}
public String getUsername() {
return username;
}
public String getPassword() {
return password;
}
public HashMap<String, Card> getCards() {
if (isvalid) {
// return user's cards
return userHash;
} else
return null;
}
public boolean addCard(Card card, String username, String password)
{
if(userValidate(username, password))
{
userHash.put(card.getCardId(), card);
return true;
}
return false;
}
}
You can iterate over the map and add all cards to a list:
List<Card> list = new ArrayList();
for (Map.Entry<String, Card> entry : userHash.entrySet()) {
if(entry.getKey().equals(username)) { list.add(entry.getValue(); }
}
Is that what you were looking for?
Or if you already understood streams:
userHash.entrySet().stream().filter(entry -> username.equals(entry.getValue())
.map(Entry::getKey)
.collect(toList());

Type inference not working in Eclipse Luna

I have newly started off with Java 8 and I'm trying out some examples on Collectors. I'm following the book, Java 8 in action. I have got a doubt regarding type inference :
I have used basic model classes Student, Name to create examples. PFB the details:
package com.learning.fundamentals;
import java.util.ArrayList;
import java.util.List;
public class Student {
public enum Gender {
MALE, FEMALE;
}
private String id;
private Name name;
private Gender gender;
public Student(String id, Name name, Gender gender) {
this.id = id;
this.name = name;
this.gender = gender;
}
public String getId() {
return id;
}
public Name getName() {
return name;
}
public Gender getGender() {
return gender;
}
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((gender == null) ? 0 : gender.hashCode());
result = prime * result + ((id == null) ? 0 : id.hashCode());
result = prime * result + ((name == null) ? 0 : name.hashCode());
return result;
}
#Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Student other = (Student) obj;
if (gender != other.gender)
return false;
if (id == null) {
if (other.id != null)
return false;
} else if (!id.equals(other.id))
return false;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
return true;
}
#Override
public String toString() {
return "Student [id=" + id + ", name=" + name + ", gender=" + gender
+ "]";
}
}
package com.learning.fundamentals;
public class Name {
private String firstName;
private String middleName;
private String lastName;
public Name(String firstName, String middleName, String lastName) {
this.firstName = firstName;
this.middleName = middleName;
this.lastName = lastName;
}
public String getFirstName() {
return firstName;
}
public String getMiddleName() {
return middleName;
}
public String getLastName() {
return lastName;
}
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result
+ ((firstName == null) ? 0 : firstName.hashCode());
result = prime * result
+ ((lastName == null) ? 0 : lastName.hashCode());
result = prime * result
+ ((middleName == null) ? 0 : middleName.hashCode());
return result;
}
#Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Name other = (Name) obj;
if (firstName == null) {
if (other.firstName != null)
return false;
} else if (!firstName.equals(other.firstName))
return false;
if (lastName == null) {
if (other.lastName != null)
return false;
} else if (!lastName.equals(other.lastName))
return false;
if (middleName == null) {
if (other.middleName != null)
return false;
} else if (!middleName.equals(other.middleName))
return false;
return true;
}
#Override
public String toString() {
return "Name [firstName=" + firstName + ", middleName=" + middleName
+ ", lastName=" + lastName + "]";
}
}
Now I have a list of Students like this
List<Student> studentList = getStudents(); //some method to create the list
Now, let's try out an grouping example. This is a multilevel grouping, first I'm grouping it using Gender and then some criteria on first name (not important). Here is the code :
Map<Student.Gender, Map<String, List<Student>>> studentsByGenderName =
studentList.stream()
.collect(Collectors.groupingBy(Student::getGender,
Collectors.groupingBy(std -> std.getName().getFirstName().substring(0, 4))));
This gives me an error at the second collector, stating "The method getName() is undefined for the type Object". Now, I was able to resolve the issue by providing the type of 'std' like this:
Map<Student.Gender, Map<String, List<Student>>> studentsByGenderName =
studentList.stream()
.collect(Collectors.groupingBy(Student::getGender,
Collectors.groupingBy((Student std) -> std.getName().getFirstName().substring(0, 4))));
My question is why can't java infer the type of the argument in lambda expression used in the second collector while it's able to do that for the first collector?

Tomcat JAASRealm - return only one Principal

I have created simple web application with JAAS auth, all works fine, but I need get user's roles list in the servlet, I get subject but it is not return any roles list and related principals. It return only first added principal? Why so?How get roles?
here my sources:
AccLoginModule.java
public class AccLoginModule implements LoginModule {
public Subject subject;
private CallbackHandler callbackHandler;
private Map<String, ?> sharedState;
private Map<String, ?> options;
private AccPrincipal principal;
private boolean committed = false;
#Override
public boolean abort() throws LoginException {
System.out.println("abort");
if (!committed)
return false;
if (principal != null) {
logout();
principal = null;
}
return true;
}
#Override
public boolean commit() throws LoginException {
try {
if (subject.getPrincipals().size() == 0) {
subject.getPrincipals().add(new AccPrincipal("principal 1"));
subject.getPrincipals().add(new AccPrincipal("principal 2"));
subject.getPrincipals().add(new AccRole("Acc User"));
subject.getPrincipals().add(new AccRole("Acc User1"));
}
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
#Override
public boolean login() throws LoginException {
// System.out.println("login");
if (callbackHandler == null)
throw new LoginException("No CallbackHandler specified");
Callback callbacks[] = new Callback[2];
callbacks[0] = new NameCallback("Username: ");
callbacks[1] = new PasswordCallback("Password: ", false);
// Interact with the user to retrieve the username and password
String username = null;
String password = null;
try {
callbackHandler.handle(callbacks);
username = ((NameCallback) callbacks[0]).getName();
password = new String(((PasswordCallback) callbacks[1]).getPassword());
return true;
} catch (Exception e) {
throw new LoginException(e.toString());
}
}
#Override
public boolean logout() throws LoginException {
System.out.println("logout");
committed = false;
subject.getPrincipals().remove(principal);
return false;
}
#Override
public void initialize(Subject subject, CallbackHandler callbackHandler, Map<String, ?> sharedState, Map<String, ?> options) {
this.subject = subject;
this.callbackHandler = callbackHandler;
this.sharedState = sharedState;
this.options = options;
}
public Subject getSubject() {
return subject;
}
public void setSubject(Subject subject) {
this.subject = subject;
}
}
AccPrincipal
public class AccPrincipal implements Principal, Serializable {
/**
*
*/
private static final long serialVersionUID = 5002820876845306935L;
private final String loginResponse;
public AccPrincipal(String lr) {
this.loginResponse=lr;
}
#Override
public String getName() {
return loginResponse;
}
public String getLoginResponse() {
return loginResponse;
}
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((loginResponse == null) ? 0 : loginResponse.hashCode());
return result;
}
#Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
AccPrincipal other = (AccPrincipal) obj;
if (loginResponse == null) {
if (other.loginResponse != null)
return false;
} else if (!loginResponse.equals(other.loginResponse))
return false;
return true;
}
}
AccRole
public class AccRole implements Principal, Serializable {
/**
*
*/
private static final long serialVersionUID = 2764250372647034496L;
private String name;
public AccRole(String name){
this.name = name;
}
#Override
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((name == null) ? 0 : name.hashCode());
return result;
}
#Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
AccRole other = (AccRole) obj;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
return true;
}
}
context.xml
<Context>
<Realm className="org.apache.catalina.realm.JAASRealm" appName="acczk"
userClassNames="com.laws.acc.jaas.AccPrincipal"
roleClassNames="com.laws.acc.jaas.AccRole">
</Realm>
</Context>
MyServlet.java
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
final Subject subject = Subject.getSubject(AccessController.getContext());
for (Principal princ : subject.getPrincipals()) {
System.out.println(princ.getName());
}
}
Console:
09.04.2012 17:11:29 org.apache.catalina.startup.Catalina start
INFO: Server startup in 1385 ms
principal 1
How I can get all entity principals (principals+roles)? What I am doing wrong?
Tomcat and Java EE in general doesn't work like that. You can't access the Subject in the way you are doing it.
See this answer for a full explanation: Tomcat-Jaas - How to retrieve subject?

SpringData/Neo4j: cannot persist relationship

I've instances of Person (nodes) who writes (relationships) instances of Status (nodes). This is a bit far-fetched I know, but I wanted to train.
Whenever, I try to persist a Person, here is what I get:
org.springframework.data.neo4j.mapping.InvalidEntityTypeException: Type class org.springframework.data.neo4j.fieldaccess.GraphBackedEntityIterableWrapper is neither a #NodeEntity nor a #RelationshipEntity
at org.springframework.data.neo4j.support.mapping.Neo4jMappingContext.createPersistentEntity(Neo4jMappingContext.java:48)
at org.springframework.data.neo4j.support.mapping.Neo4jMappingContext.createPersistentEntity(Neo4jMappingContext.java:38)
at org.springframework.data.mapping.context.AbstractMappingContext.addPersistentEntity(AbstractMappingContext.java:235)
at org.springframework.data.mapping.context.AbstractMappingContext.getPersistentEntity(AbstractMappingContext.java:165)
at org.springframework.data.mapping.context.AbstractMappingContext.getPersistentEntity(AbstractMappingContext.java:140)
at org.springframework.data.neo4j.support.mapping.EntityStateHandler.getId(EntityStateHandler.java:67)
at org.springframework.data.neo4j.support.mapping.EntityStateHandler.getPersistentState(EntityStateHandler.java:84)
at org.springframework.data.neo4j.support.mapping.Neo4jEntityFetchHandler.fetch(Neo4jEntityFetchHandler.java:58)
at org.springframework.data.neo4j.support.mapping.Neo4jEntityConverterImpl$1.doWithAssociation(Neo4jEntityConverterImpl.java:116)
at org.springframework.data.mapping.model.BasicPersistentEntity.doWithAssociations(BasicPersistentEntity.java:185)
at org.springframework.data.neo4j.support.mapping.Neo4jEntityConverterImpl.cascadeFetch(Neo4jEntityConverterImpl.java:106)
at org.springframework.data.neo4j.support.mapping.Neo4jEntityConverterImpl.loadEntity(Neo4jEntityConverterImpl.java:100)
at org.springframework.data.neo4j.support.mapping.Neo4jEntityConverterImpl.read(Neo4jEntityConverterImpl.java:90)
at org.springframework.data.neo4j.support.mapping.Neo4jEntityPersister$CachedConverter.read(Neo4jEntityPersister.java:168)
at org.springframework.data.neo4j.support.mapping.Neo4jEntityPersister.createEntityFromState(Neo4jEntityPersister.java:186)
at org.springframework.data.neo4j.support.mapping.Neo4jEntityPersister.persist(Neo4jEntityPersister.java:239)
at org.springframework.data.neo4j.support.mapping.Neo4jEntityPersister.persist(Neo4jEntityPersister.java:227)
at org.springframework.data.neo4j.support.Neo4jTemplate.save(Neo4jTemplate.java:295)
at org.springframework.data.neo4j.repository.AbstractGraphRepository.save(AbstractGraphRepository.java:106)
at sun.reflect.GeneratedMethodAccessor19.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:616)
at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.executeMethodOn(RepositoryFactorySupport.java:322)
at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.invoke(RepositoryFactorySupport.java:307)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:110)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:155)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:202)
at $Proxy29.save(Unknown Source)
at sun.reflect.GeneratedMethodAccessor18.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:616)
at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:309)
at org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:183)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:150)
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:110)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:202)
at $Proxy30.save(Unknown Source)
at com.lateralthoughts.devinlove.framework.GraphPopulator.loadABunchOfPeopleIntoTheMatrix(GraphPopulator.java:84)
Here come the entities:
#NodeEntity
public class Person {
public enum ProfoundIdentity {
DEVELOPER, ARCHITECT, SYSADMIN, MANAGER, BOSS;
}
#GraphId
private Long id;
private String firstName;
private String lastName;
private String favoriteColor;
private Mascot mascot;
#RelatedTo(elementClass = Person.class, type = "IS_FRIEND_WITH", direction = BOTH)
private final Set<Person> friends = new LinkedHashSet<Person>();
#RelatedTo(elementClass = Tool.class, type = "WORKS_WITH", direction = OUTGOING)
private final Set<Tool> tools = new LinkedHashSet<Tool>();
/**
* Simplistic European-formatted shoe size
*/
private int shoeSize;
#Fetch
#RelatedToVia(elementClass = StatusRedaction.class, type = "WRITES", direction = OUTGOING)
private final Collection<StatusRedaction> statuses = new LinkedList<StatusRedaction>();
private ProfoundIdentity profoundIdentity;
public Long getId() {
return id;
}
public String getFirstName() {
return firstName;
}
public String getLastName() {
return lastName;
}
public void setFavoriteColor(final String favoriteColor) {
checkNotNull(favoriteColor);
this.favoriteColor = favoriteColor.toUpperCase();
}
public String getFavoriteColor() {
return favoriteColor;
}
public void setMascot(final Mascot mascot) {
this.mascot = mascot;
}
public Mascot getMascot() {
return mascot;
}
public Set<Person> getFriends() {
return unmodifiableSet(friends);
}
public void addFriend(final Person friend) {
checkNotNull(friend);
friends.add(friend);
}
public void addTool(final Tool tool) {
checkNotNull(tool);
tools.add(tool);
}
public Set<Tool> getTools() {
return unmodifiableSet(tools);
}
public void setShoeSize(final int shoeSize) {
checkArgument(shoeSize > 0 && shoeSize < 80);
this.shoeSize = shoeSize;
}
public int getShoeSize() {
return shoeSize;
}
public Iterable<StatusRedaction> getStatuses() {
return statuses;
}
public StatusRedaction addStatus(final Status message, final Date creationDate) {
final StatusRedaction statusRedaction = new StatusRedaction(this, message, creationDate);
statuses.add(statusRedaction);
return statusRedaction;
}
public void setProfoundIdentity(final ProfoundIdentity profoundIdentity) {
checkNotNull(profoundIdentity);
this.profoundIdentity = profoundIdentity;
}
public ProfoundIdentity getProfoundIdentity() {
return profoundIdentity;
}
public void setFirstName(final String firstName) {
this.firstName = firstName;
}
public void setLastName(final String lastName) {
this.lastName = lastName;
}
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((getFirstName() == null) ? 0 : getFirstName().hashCode());
result = prime * result + ((getLastName() == null) ? 0 : getLastName().hashCode());
return result;
}
#Override
public boolean equals(final Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Person other = (Person) obj;
if (getFirstName() == null) {
if (other.getFirstName() != null)
return false;
}
else if (!getFirstName().equals(other.getFirstName()))
return false;
if (getLastName() == null) {
if (other.getLastName() != null)
return false;
}
else if (!getLastName().equals(other.getLastName()))
return false;
return true;
}
}
Here is the status:
#NodeEntity
public class Status {
#GraphId
private Long id;
private String message = "";
public Status() {}
public Status(final String message) {
this.message = message;
}
public void setMessage(final String message) {
this.message = message;
}
public String getMessage() {
return message;
}
public Long getId() {
return id;
}
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((id == null) ? 0 : id.hashCode());
return result;
}
#Override
public boolean equals(final Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Status other = (Status) obj;
if (id == null) {
if (other.id != null)
return false;
}
else if (!id.equals(other.id))
return false;
return true;
}
}
And here is the relationship:
#RelationshipEntity(type = "WRITES")
public class StatusRedaction {
#GraphId
private Long id;
#StartNode
private Person author;
#EndNode
private Status status = new Status("");
private Date creationDate = new Date();
public StatusRedaction() {}
public StatusRedaction(final Person author, final Status status, final Date creationDate) {
this.author = author;
this.status = status;
this.creationDate = creationDate;
}
public Long getId() {
return id;
}
public Person getAuthor() {
return author;
}
public void setAuthor(final Person author) {
this.author = author;
}
public Status getStatus() {
return status;
}
public String getStatusMessage() {
return status.getMessage();
}
public void setStatus(final Status status) {
this.status = status;
}
public Date getCreationDate() {
return creationDate;
}
// shouldnt be here, I know...
public String getFormattedDate() {
PrettyTime prettyTime = new PrettyTime(new Locale("en"));
return prettyTime.format(creationDate);
}
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((id == null) ? 0 : id.hashCode());
return result;
}
#Override
public boolean equals(final Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
StatusRedaction other = (StatusRedaction) obj;
if (id == null) {
if (other.id != null)
return false;
}
else if (!id.equals(other.id))
return false;
return true;
}
}
And finally, the code in charge of persisting users:
public class GraphPopulator implements ApplicationListener<ContextRefreshedEvent> {
#Autowired
private MascotRepository mascotRepository;
#Autowired
private PersonRepository personRepository;
#Autowired
private ToolRepository toolRepository;
#Autowired
private CategoryRepository categoryRepository;
#Override
public void onApplicationEvent(final ContextRefreshedEvent event) {
loadData();
}
public void loadData() {
/* [...] inserting other entities [...] */
loadABunchOfPeopleIntoTheMatrix();
}
/**
* [...]
*/
private void loadABunchOfPeopleIntoTheMatrix() {
personRepository.save(person("John", "Doe", "blue", "Tux", DEVELOPER, 42, "Hello world", "Java Standard Edition"));
personRepository.save(person("Jane", "Doe", "green", "Django Pony", DEVELOPER, 45, "A World Appart (Info)", "Python"));
}
private Person person(final String firstName, final String lastName, final String color, final String mascotName, final Person.ProfoundIdentity profoundIdentity, final int shoeSize, final String firstStatus, final String toolName) {
Person person = new Person();
person.setFavoriteColor(color);
person.setFirstName(firstName);
person.setLastName(lastName);
person.setMascot(findMascot(mascotName));
person.setProfoundIdentity(profoundIdentity);
person.setShoeSize(shoeSize);
person.addStatus(new Status("Hello world"), new Date());
return person;
}
private Tool findTool(final String toolname) {
return toolRepository.findByPropertyValue("name", toolname);
}
private Mascot findMascot(final String mascotName) {
return mascotRepository.findByPropertyValue("name", mascotName);
} }
And the corresponding repository:
import org.springframework.data.neo4j.repository.GraphRepository;
import ***.domain.Person;
public interface PersonRepository extends GraphRepository<Person> {}
I'm not sure what's wrong. The exception message is just too weird and my debug sessions didn't lead me anywhere.
Can anybody tell me what's wrong with my code?

Categories