Tomcat JAASRealm - return only one Principal - java

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?

Related

Serialization in the hazelcast jet

I'm getting the following error when I tried to processing the data from hazelcast jet.
Caused by: java.lang.IllegalArgumentException: Invalid lambda deserialization
at com.example.LearnJet.joins.LeftJoins.$deserializeLambda$(LeftJoins.java:1)
... 59 more
Here is the code:-
AddToCart1 instance
public class AddToCart1 implements Serializable {
private int number;
private String cart;
public AddToCart1() {
super();
// TODO Auto-generated constructor stub
}
public int getNumber() {
return number;
}
public AddToCart1(int number, String cart) {
super();
this.number = number;
this.cart = cart;
}
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((cart == null) ? 0 : cart.hashCode());
result = prime * result + number;
return result;
}
#Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
AddToCart1 other = (AddToCart1) obj;
if (cart == null) {
if (other.cart != null)
return false;
} else if (!cart.equals(other.cart))
return false;
if (number != other.number)
return false;
return true;
}
public void setNumber(int number) {
this.number = number;
}
public String getCart() {
return cart;
}
public void setCart(String cart) {
this.cart = cart;
}
}
PageVisit1 instance
public class PageVisit1 implements Serializable {
/**
*
*/
private int number;
private String pageName;
public PageVisit1() {
}
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + number;
result = prime * result + ((pageName == null) ? 0 : pageName.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;
PageVisit1 other = (PageVisit1) obj;
if (number != other.number)
return false;
if (pageName == null) {
if (other.pageName != null)
return false;
} else if (!pageName.equals(other.pageName))
return false;
return true;
}
public PageVisit1(int number, String pageName) {
super();
this.number = number;
this.pageName = pageName;
}
/**
* #return the number
*/
public int getNumber() {
return number;
}
/**
* #param number the number to set
*/
public void setNumber(int number) {
this.number = number;
}
/**
* #return the pageName
*/
public String getPageName() {
return pageName;
}
/**
* #param pageName the pageName to set
*/
public void setPageName(String pageName) {
this.pageName = pageName;
}
}
Here is the main class
public class LeftJoins {
public static void main(String[] args) throws InvocationTargetException {
JetInstance jet = Jet.bootstrappedInstance();
IList<AddToCart1> addToCartList = jet.getList("cart");
IList<PageVisit1> paymentList = jet.getList("page");
// AddToCartData
AddToCart1 ad1 = new AddToCart1();
ad1.setNumber(1);
ad1.setCart("lulu bazar");
AddToCart1 ad2 = new AddToCart1();
ad2.setNumber(2);
ad2.setCart("krishna bazar");
AddToCart1 ad3 = new AddToCart1();
ad3.setNumber(3);
ad3.setCart("ram bazar");
addToCartList.add(ad1);
addToCartList.add(ad2);
addToCartList.add(ad3);
// Page Data
PageVisit1 pg1 = new PageVisit1();
pg1.setNumber(1);
pg1.setPageName("k login");
PageVisit1 pg2 = new PageVisit1();
pg2.setNumber(2);
pg2.setPageName("plogin");
paymentList.add(pg1);
paymentList.add(pg2);
// creating a piple-line here
Pipeline p = Pipeline.create();
BatchStageWithKey<AddToCart1, Object> cart = p.readFrom(Sources.<AddToCart1>list("cart"))
.groupingKey(cart1 -> cart1.getNumber());
BatchStageWithKey<PageVisit1, Object> page = p.readFrom(Sources.<PageVisit1>list("page"))
.groupingKey(page1 -> page1.getNumber());
BatchStage<Tuple2<List<PageVisit1>, List<AddToCart1>>> joinedLists1 = page.aggregate2(toList(), cart, toList())
.map(Entry::getValue);
BatchStage<Tuple2<List<PageVisit1>, List<AddToCart1>>> m = joinedLists1.filter(pair -> !pair.f0().isEmpty());
m.writeTo(Sinks.logger());
jet.newJob(p).join();
// joinedLists.filter(pair -> !pair.isEmpty());
}
The code is obviously incomplete, because there's no page variable so that page.aggregate2(...) shouldn't compile.
For this reason, I'm unable to point you to the exact line where the issue occurs. However, the error message tells you're using a "standard" lambda from the JDK that isn't Serializable, whereas you should use the ones from Jet, which are.
Please check this package.
EDIT:
I've created a dedicated GitHub project with the above code.
Everything works as expected. The 2 tuples are displayed correctly in the log:
09:33:59.974 [ INFO] [c.h.j.i.c.WriteLoggerP] [05d8-7d0a-e3c0-0001/loggerSink#0] ([ch.frankel.so.PageVisit1#c544b8f8], [ch.frankel.so.AddToCart1#41c722ed])
09:33:59.974 [ INFO] [c.h.j.i.c.WriteLoggerP] [05d8-7d0a-e3c0-0001/loggerSink#0] ([ch.frankel.so.PageVisit1#58fbcb54], [ch.frankel.so.AddToCart1#c666a2c4])

How to enable or disable user in Spring Boot Security

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.

How to group values in list based on id in java?

Hello folks this may be dumb question but as a beginner am struggling with this how to group values based on id in list, Now let me clarify you briefly am having set of objects like this :
ID:1,UserID:330
ID:2,UserID:303
ID:3,UserID:090
ID:1,UserID:302
ID:2,UserID:306
How my list should look like is(Json Format):
[{"ID":1,"UserID":[330,302]},{"ID":2,"UserID":[303,306]},{"ID":3,"UserID":[090]}]
Now let me post what i have tried so far:
final List<Integer>list=new ArrayList<>();
final List<SpareReturnModel>lisobj=new ArrayList<>();
int duplicate=0;
for(int i=0;i<tView.getSelected().size();i++){
Object o= tView.getSelected().get(i).getValue();
SpareReturnModel asset=(SpareReturnModel) o;
int flag=asset.getFlag();
if(flag==2) {
int warehouseid = asset.getWareHouseID();
asset.setWareHouseID(warehouseid);
int partid = asset.getSerialNoID();
list.add(partid);
}
else {
Log.d("s","no value for header");
}
if(duplicate!=asset.getWareHouseID()){
asset.setParlist(list);
asset.setWareHouseID(asset.getWareHouseID());
lisobj.add(asset);
list.clear();
}
duplicate=asset.getWareHouseID();
}
Gson gson=new Gson();
//this will convert list to json
String value=gson.toJson(listobj);
SpareReturn Model Class:
public class SpareReturnModel {
private Integer SerialNoID;
private String SerialNumber;
private List<Integer>parlist;
public List<Integer> getParlist() {
return parlist;
}
public void setParlist(List<Integer> parlist) {
this.parlist = parlist;
}
public Integer getFlag() {
return flag;
}
public void setFlag(Integer flag) {
this.flag = flag;
}
private Integer flag;
public Integer getWareHouseID() {
return WareHouseID;
}
public void setWareHouseID(Integer wareHouseID) {
WareHouseID = wareHouseID;
}
private Integer WareHouseID;
public Integer getSerialNoID() {
return SerialNoID;
}
public void setSerialNoID(Integer serialNoID) {
SerialNoID = serialNoID;
}
public String getSerialNumber() {
return SerialNumber;
}
public void setSerialNumber(String serialNumber) {
SerialNumber = serialNumber;
}
}
Can someone let me know how to achieve this am struggling with this.
I simplify your class to make solution clearer:
public class SpareReturnModel implements Comparable<SpareReturnModel> {
private Integer id;
private String userId;
public SpareReturnModel(Integer id, String userId) {
this.id = id;
this.userId = userId;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
#Override
public int compareTo(SpareReturnModel other) {
return this.getId().compareTo(other.getId());
}
#Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
SpareReturnModel model = (SpareReturnModel) o;
if (id != null ? !id.equals(model.id) : model.id != null) return false;
return userId != null ? userId.equals(model.userId) : model.userId == null;
}
#Override
public int hashCode() {
int result = id != null ? id.hashCode() : 0;
result = 31 * result + (userId != null ? userId.hashCode() : 0);
return result;
}
}
and add JsonSpareReturnModel
public class JsonSpareRuturnModel implements Comparable<JsonSpareRuturnModel> {
private final List<SpareReturnModel> modelList;
private final Integer id;
public JsonSpareRuturnModel(List<SpareReturnModel> modelList) {
this.modelList = modelList;
this.id = modelList.get(0).getId();
}
private final String toJson() {
return String.format("{\"ID\":%s,\"UserID\":%s}", id, formatUserIdList());
}
private String formatUserIdList() {
StringBuilder builder = new StringBuilder("[");
Iterator<SpareReturnModel> modelIterator = modelList.iterator();
while (modelIterator.hasNext()) {
builder.append(modelIterator.next().getUserId());
if (modelIterator.hasNext()) {
builder.append(",");
}
}
builder.append("]");
return builder.toString();
}
#Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
JsonSpareRuturnModel that = (JsonSpareRuturnModel) o;
return id != null ? id.equals(that.id) : that.id == null;
}
#Override
public int hashCode() {
return id != null ? id.hashCode() : 0;
}
#Override
public int compareTo(JsonSpareRuturnModel other) {
return this.id.compareTo(other.id);
}
#Override
public String toString() {
return toJson();
}
if you need to group by user id you need to sort your models according to id's
and place them to json format model:
public class Main {
public static void main(String[] args) {
List<SpareReturnModel> models = new ArrayList<>(Arrays.asList(
new SpareReturnModel(1, "330"),
new SpareReturnModel(2, "303"),
new SpareReturnModel(3, "090"),
new SpareReturnModel(1, "302"),
new SpareReturnModel(2, "306")
));
Map<Integer, List<SpareReturnModel>> groupById = new HashMap<>();
for (SpareReturnModel model : models) {
List<SpareReturnModel> listById = groupById.get(model.getId());
if (listById == null) {
groupById.put(model.getId(), new ArrayList<>(Arrays.asList(model)));
} else {
listById.add(model);
}
}
List<JsonSpareRuturnModel> jsonList = new ArrayList<>();
for (Map.Entry<Integer, List<SpareReturnModel>> pair : groupById.entrySet()) {
jsonList.add(new JsonSpareRuturnModel(pair.getValue()));
}
System.out.println(jsonList);
final String expected = "[{\"ID\":1,\"UserID\":[330,302]}, {\"ID\":2,\"UserID\":[303,306]}, {\"ID\":3,\"UserID\":[090]}]";
System.out.println(jsonList.toString().equals(expected));
}
}

Getting null value for xml formatted string after Deserialization

I am a beginner in android.I am calling a webservice from my android project which returns a json string as response which contain a xml formatted string as one entry.
String jsoncontent=restTemplate.getForObject(constr+"getAssetdata/{Id}", String.class, curAcct.getiD());
final GsonBuilder gsonBuilder = new GsonBuilder();
gsonBuilder.registerTypeAdapter(Assets.class, new AssetDeserialiser());
final Gson gson = gsonBuilder.create();
Assets assetAcc = gson.fromJson(jsoncontent, Assets.class);
Toast.makeText(getApplicationContext(), assetAcc.getKeyValueData(), 68000).show();
Below is the json string that i got as webservice response
jsoncontent={"id":39,"name":"ICICI Bank","purchaseValue":6000.0,"purchaseDate":1402403751000,"keyValueData":"<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?><root><Description><Name>Tax and other payments</Name><Value>433</Value></Description><Description><Name>Add more details...</Name><Value></Value></Description></root>"}
But i am getting a null value for assetAcc.getKeyValueData() after deserialization,there is no isue with other fields in assets.How to solve this issue? Please help me.
AssetDeserialiser.java:
public class AssetDeserialiser implements JsonDeserializer<Assets> {
#Override
public Assets deserialize(JsonElement arg0, Type arg1, JsonDeserializationContext arg2) throws JsonParseException {
JsonObject jobject =arg0.getAsJsonObject();
final Assets asset = new Assets();
try{
asset.setId(jobject.get("id").getAsInt());
asset.setName(jobject.get("name").getAsString());
asset.setPurchaseValue(jobject.get("purchaseValue").getAsFloat());
asset.setPurchaseDate(new Timestamp(jobject.get("purchaseDate").getAsLong()));
asset.setKeyValueData(jobject.get("keyValueData").isJsonNull() ? "" : jobject.get("keyValueData").getAsString());
}catch(Exception es){
System.out.println("es "+es);
}
return asset;
}
}
Assets.java:
public class Assets implements Serializable{
private Integer id;
private String name;
private Float purchaseValue;
private Timestamp purchaseDate;
private String keyValueData;
public Assets() {
super();
// TODO Auto-generated constructor stub
}
public Assets(Integer id, String name, Float purchaseValue, Timestamp purchaseDate, String keyValueData) {
super();
this.id = id;
this.name = name;
this.purchaseValue = purchaseValue;
this.purchaseDate = purchaseDate;
this.keyValueData = keyValueData;
}
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 Float getPurchaseValue() {
return purchaseValue;
}
public void setPurchaseValue(Float purchaseValue) {
this.purchaseValue = purchaseValue;
}
public Timestamp getPurchaseDate() {
return purchaseDate;
}
public void setPurchaseDate(Timestamp purchaseDate) {
this.purchaseDate = purchaseDate;
}
public String getKeyValueData() {
return keyValueData;
}
public void setKeyValueData(String keyValueData) {
this.keyValueData = keyValueData;
}
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((id == null) ? 0 : id.hashCode());
result = prime * result
+ ((keyValueData == null) ? 0 : keyValueData.hashCode());
result = prime * result + ((name == null) ? 0 : name.hashCode());
result = prime * result
+ ((purchaseDate == null) ? 0 : purchaseDate.hashCode());
result = prime * result
+ ((purchaseValue == null) ? 0 : purchaseValue.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;
Assets other = (Assets) obj;
if (id == null) {
if (other.id != null)
return false;
} else if (!id.equals(other.id))
return false;
if (keyValueData == null) {
if (other.keyValueData != null)
return false;
} else if (!keyValueData.equals(other.keyValueData))
return false;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
if (purchaseDate == null) {
if (other.purchaseDate != null)
return false;
} else if (!purchaseDate.equals(other.purchaseDate))
return false;
if (purchaseValue == null) {
if (other.purchaseValue != null)
return false;
} else if (!purchaseValue.equals(other.purchaseValue))
return false;
return true;
}
#Override
public String toString() {
return name;
}
}
You can set this keyValueData after deserialisation from your json string that contain the xml string as below
String jsoncontent=restTemplate.getForObject(constr+"getAssetdata/{Id}", String.class, curAcct.getiD());
final GsonBuilder gsonBuilder = new GsonBuilder();
gsonBuilder.registerTypeAdapter(Assets.class, new AssetDeserialiser());
final Gson gson = gsonBuilder.create();
Assets assetAcc = gson.fromJson(jsoncontent, Assets.class);
JSONObject jsonObj=new JSONObject(jsoncontent);
assetAcc.setKeyValueData(jsonObj.getString("keyValueData"));
1.Use Parcelable -its much faster.
2.Timestamp change to long. (Then can parce this value like this):
private String parceDate(data long){
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd hh:mm");
try {
retrun df.format(your long from Assets.class);
}catch (Exception e){
return "";
}
}
UPDATE:
Y can change your getter and setter for use Timestamp object from Assets class like this:
public void setPurchaseDate(long purchaseDate){
this.purchaseDate=purchaseDate
}
public Timestamp getPurchaseDate(){
return new Timestamp(purchaseDate); //from java.sql.Timestamp;
}
You can use jackson for deserialization.
public class AssetDeserialiser extends JsonDeserializer<Asset> {
#Override
public Asset deserialize(JsonParser arg0, DeserializationContext arg1)
throws IOException, JsonProcessingException {
ObjectMapper mapper = new ObjectMapper();
JsonNode node = mapper.readTree(arg0);
final Asset asset = new Asset();
try{
asset.setId(mapper.readValue(node.get("id"),Integer.class));
asset.setName(mapper.readValue(node.get("name"),String.class));
asset.setPurchaseDate(mapper.readValue(node.get("purchaseDate"),Timestamp.class));
asset.setPurchaseValue(mapper.readValue(node.get("purchaseValue"),Float.class));
asset.setKeyValueData(mapper.readValue(node.get("keyValueData"), String.class));
}catch(Exception es){
System.out.println("es "+es);
}
return asset;
}
}
This may help you.
Also you will have to add "#JsonDeserialize(using=AssetDeserialiser.class)" at the beginning of your asset class. It is done like this:
#JsonDeserialize(using=AssetDeserialiser.class)
public class Asset implements Serializable{

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