I am currently developing an application in Java with FusionAuth, I am using the Java Client of that tool, and I want to create a user, so I use the createUser() method, which needs the UID and a UserRequest object, this one, need an User object which constructor is the next one:
UserRequest class
public class UserRequest {
public boolean sendSetPasswordEmail;
public boolean skipVerification;
public User user;
#JacksonConstructor
public UserRequest() {
}
public UserRequest(User user) {
this.sendSetPasswordEmail = false;
this.skipVerification = true;
this.user = user;
}
public UserRequest(boolean sendSetPasswordEmail, boolean skipVerification, User user) {
this.sendSetPasswordEmail = sendSetPasswordEmail;
this.skipVerification = skipVerification;
this.user = user;
}
}
User class
public class User extends SecureIdentity implements Buildable<User>, _InternalJSONColumn, Tenantable {
#InternalJSONColumn
#JsonMerge(OptBoolean.FALSE)
public final List<Locale> preferredLanguages = new ArrayList();
#JsonMerge(OptBoolean.FALSE)
private final List<GroupMember> memberships = new ArrayList();
#JsonMerge(OptBoolean.FALSE)
private final List<UserRegistration> registrations = new ArrayList();
public boolean active;
public LocalDate birthDate;
public UUID cleanSpeakId;
#JsonMerge(OptBoolean.FALSE)
public Map<String, Object> data = new LinkedHashMap();
public String email;
public ZonedDateTime expiry;
public String firstName;
public String fullName;
public URI imageUrl;
public ZonedDateTime insertInstant;
public ZonedDateTime lastLoginInstant;
public String lastName;
public String middleName;
public String mobilePhone;
public String parentEmail;
public UUID tenantId;
public ZoneId timezone;
public TwoFactorDelivery twoFactorDelivery;
public boolean twoFactorEnabled;
public String twoFactorSecret;
public String username;
public ContentStatus usernameStatus;
public User() {
}
public User(User user) {
this.active = user.active;
this.birthDate = user.birthDate;
this.cleanSpeakId = user.cleanSpeakId;
this.email = user.email;
this.encryptionScheme = user.encryptionScheme;
this.expiry = user.expiry;
this.factor = user.factor;
this.firstName = user.firstName;
this.fullName = user.fullName;
this.id = user.id;
this.imageUrl = user.imageUrl;
this.insertInstant = user.insertInstant;
this.lastLoginInstant = user.lastLoginInstant;
this.lastName = user.lastName;
this.memberships.addAll((Collection)user.memberships.stream().map(GroupMember::new).collect(Collectors.toList()));
this.middleName = user.middleName;
this.mobilePhone = user.mobilePhone;
this.parentEmail = user.parentEmail;
this.password = user.password;
this.passwordChangeRequired = user.passwordChangeRequired;
this.passwordLastUpdateInstant = user.passwordLastUpdateInstant;
this.preferredLanguages.addAll(user.preferredLanguages);
this.registrations.addAll((Collection)user.registrations.stream().map(UserRegistration::new).collect(Collectors.toList()));
this.salt = user.salt;
this.tenantId = user.tenantId;
this.timezone = user.timezone;
this.twoFactorDelivery = user.twoFactorDelivery;
this.twoFactorEnabled = user.twoFactorEnabled;
this.twoFactorSecret = user.twoFactorSecret;
this.username = user.username;
this.usernameStatus = user.usernameStatus;
this.verified = user.verified;
if (user.data != null) {
this.data.putAll(user.data);
}
}
public void addMemberships(GroupMember member) {
this.memberships.removeIf((m) -> {
return m.groupId.equals(member.groupId);
});
this.memberships.add(member);
}
public boolean equals(Object o) {
if (this == o) {
return true;
} else if (!(o instanceof User)) {
return false;
} else {
User user = (User)o;
this.sort();
user.sort();
return super.equals(o) && Objects.equals(this.active, user.active) && Objects.equals(this.birthDate, user.birthDate) && Objects.equals(this.cleanSpeakId, user.cleanSpeakId) && Objects.equals(this.data, user.data) && Objects.equals(this.email, user.email) && Objects.equals(this.expiry, user.expiry) && Objects.equals(this.firstName, user.firstName) && Objects.equals(this.fullName, user.fullName) && Objects.equals(this.imageUrl, user.imageUrl) && Objects.equals(this.insertInstant, user.insertInstant) && Objects.equals(this.lastLoginInstant, user.lastLoginInstant) && Objects.equals(this.lastName, user.lastName) && Objects.equals(this.memberships, user.memberships) && Objects.equals(this.middleName, user.middleName) && Objects.equals(this.mobilePhone, user.mobilePhone) && Objects.equals(this.registrations, user.registrations) && Objects.equals(this.parentEmail, user.parentEmail) && Objects.equals(this.tenantId, user.tenantId) && Objects.equals(this.timezone, user.timezone) && Objects.equals(this.twoFactorDelivery, user.twoFactorDelivery) && Objects.equals(this.twoFactorEnabled, user.twoFactorEnabled) && Objects.equals(this.twoFactorSecret, user.twoFactorSecret) && Objects.equals(this.username, user.username) && Objects.equals(this.usernameStatus, user.usernameStatus);
}
}
#JsonIgnore
public int getAge() {
return this.birthDate == null ? -1 : (int)this.birthDate.until(LocalDate.now(), ChronoUnit.YEARS);
}
#JsonIgnore
public String getLogin() {
return this.email == null ? this.username : this.email;
}
public List<GroupMember> getMemberships() {
return this.memberships;
}
#JsonIgnore
public String getName() {
if (this.fullName != null) {
return this.fullName;
} else {
return this.firstName != null ? this.firstName + (this.lastName != null ? " " + this.lastName : "") : null;
}
}
public UserRegistration getRegistrationForApplication(UUID id) {
return (UserRegistration)this.getRegistrations().stream().filter((reg) -> {
return reg.applicationId.equals(id);
}).findFirst().orElse((Object)null);
}
public List<UserRegistration> getRegistrations() {
return this.registrations;
}
public Set<String> getRoleNamesForApplication(UUID id) {
UserRegistration registration = this.getRegistrationForApplication(id);
return registration != null ? registration.roles : null;
}
public UUID getTenantId() {
return this.tenantId;
}
public boolean hasUserData() {
if (!this.data.isEmpty()) {
return true;
} else {
Iterator var1 = this.registrations.iterator();
UserRegistration userRegistration;
do {
if (!var1.hasNext()) {
return false;
}
userRegistration = (UserRegistration)var1.next();
} while(!userRegistration.hasRegistrationData());
return true;
}
}
public int hashCode() {
return Objects.hash(new Object[]{super.hashCode(), this.active, this.birthDate, this.cleanSpeakId, this.data, this.email, this.expiry, this.firstName, this.fullName, this.imageUrl, this.insertInstant, this.lastLoginInstant, this.lastName, this.memberships, this.middleName, this.mobilePhone, this.registrations, this.parentEmail, this.tenantId, this.timezone, this.twoFactorDelivery, this.twoFactorEnabled, this.twoFactorSecret, this.username, this.usernameStatus});
}
public String lookupEmail() {
if (this.email != null) {
return this.email;
} else {
return this.data.containsKey("email") ? this.data.get("email").toString() : null;
}
}
public Locale lookupPreferredLanguage(UUID applicationId) {
Iterator var2 = this.registrations.iterator();
UserRegistration registration;
do {
if (!var2.hasNext()) {
if (this.preferredLanguages.size() > 0) {
return (Locale)this.preferredLanguages.get(0);
}
return null;
}
registration = (UserRegistration)var2.next();
} while(!registration.applicationId.equals(applicationId) || registration.preferredLanguages.size() <= 0);
return (Locale)registration.preferredLanguages.get(0);
}
public void normalize() {
Normalizer.removeEmpty(this.data);
this.email = Normalizer.toLowerCase(Normalizer.trim(this.email));
this.encryptionScheme = Normalizer.trim(this.encryptionScheme);
this.firstName = Normalizer.trim(this.firstName);
this.fullName = Normalizer.trim(this.fullName);
this.lastName = Normalizer.trim(this.lastName);
this.middleName = Normalizer.trim(this.middleName);
this.mobilePhone = Normalizer.trim(this.mobilePhone);
this.parentEmail = Normalizer.toLowerCase(Normalizer.trim(this.parentEmail));
this.preferredLanguages.removeIf(Objects::isNull);
this.username = Normalizer.trim(this.username);
if (this.username != null && this.username.length() == 0) {
this.username = null;
}
this.getRegistrations().forEach(UserRegistration::normalize);
}
public void removeMembershipById(UUID groupId) {
this.memberships.removeIf((m) -> {
return m.groupId.equals(groupId);
});
}
public User secure() {
this.encryptionScheme = null;
this.factor = null;
this.password = null;
this.salt = null;
this.twoFactorSecret = null;
return this;
}
public User sort() {
this.registrations.sort(Comparator.comparing((ur) -> {
return ur.applicationId;
}));
return this;
}
public String toString() {
return ToString.toString(this);
}
}
So, my question is, how do I create an User Object?
That constructor is the only one that the class have besides the empty constructor. Also the class does not have any setters.
I looked at the source code for the library you're working with. The fields are all public, so you can create an empty constructor and then set them by doing user.name = xxxx.
Related
I'm trying to write some code that determines if a customer has certain feature. I have this method for that:
#Transactional(readOnly = true)
public boolean customerHasFeature(String customerId, String feature) {
Customer customer = customerDAO.findByCid(customerId);
if(customer != null) {
return customer.hasFeatureNamed(feature);
}
return false;
}
The customerDAO method is here
#Transactional(readOnly = true)
public Customer findByCid(String cid) {
List<Customer> customers = findByCriteriaImpl(Restrictions.eq("cid", cid));
if(customers.size() > 0)
return customers.get(0);
return null;
}
In customerHasFeature after I retrieve the customer it doesn't load the features and I get the error
org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role: com.socialware.model.Customer.features, no session or session was closed
When debugging findbyCid, I can see the features loaded after the criteria retrieves the customer, but when returned customer gets to customerHasFeature, it has an error.
I tried adding
Hibernate.initialize(customer.getFeatures());
after I call the customerDAO in customerHasFeature method but then I get
org.hibernate.HibernateException: collection is not associated with any session
I'm using hibernate 3,I appreciate any help or guides.
EDIT
Here's the findByCriteriaImpl method.
List<T> findByCriteriaImpl(Criterion... criterion) {
Criteria crit = createCriteria(getPersistentClass());
if (criterion != null) {
for (Criterion c : criterion) {
crit.add(c);
}
}
long startTime = System.currentTimeMillis();
List<T> toReturn = crit.list();
reportQueryTimeForMonitoring(System.currentTimeMillis() - startTime, "findByCriteriaImpl", "for criteria " + crit);
return toReturn;
}
And the Customer class
public class Customer implements Serializable{
private static final long serialVersionUID = -1L;
#Field(index=Index.UN_TOKENIZED)
private long customerId;
private String cid;
//#Field
private String name;
private Set<Feature> features;
private boolean deleted = false;
private String randomKey;
public Customer() {
}
#Override
public String toString() {
return new StringBuilder()
.append("Customer{")
.append(customerId).append(", ")
.append(cid).append(", ")
.append(name).append(", ")
.append(deleted)
.append("}").toString();
}
#Override
public boolean equals(Object obj) {
if(this == obj)
return true;
if(obj == null)
return false;
if(getClass() != obj.getClass())
return false;
Customer other = (Customer) obj;
if(cid == null) {
if(other.cid != null)
return false;
}
else if(!cid.equals(other.cid))
return false;
if(customerId != other.customerId)
return false;
if(name == null) {
if(other.name != null)
return false;
}
else if(!name.equals(other.name))
return false;
return true;
}
public long getCustomerId() {
return customerId;
}
public void setCustomerId(long customerId) {
this.customerId = customerId;
}
public void addFeature(Feature feature) {
if(null == getFeatures()) {
features = new HashSet<Feature>();
}
features.add(feature);
}
public Set<Feature> getFeatures() {
return features;
}
public void setFeatures(Set<Feature> features) {
this.features = features;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getCid() {
return cid;
}
public void setCid(String cid) {
this.cid = cid;
}
public boolean isDeleted() {
return deleted;
}
public void setDeleted(boolean deleted) {
this.deleted = deleted;
}
public String getRandomKey() {
return randomKey;
}
public void setRandomKey(String randomKey) {
this.randomKey = randomKey;
}
public boolean hasFeatureNamed(String name) {
Set<Feature> features = getFeatures();
if (features == null) {
return false;
}
for (Feature feature : features) {
if (feature != null && feature.getName().equals(name)) {
return true;
}
}
return false;
}
public void removeFeature(String name) {
Set<Feature> features = getFeatures();
if (features == null) {
return;
}
for (Iterator<Feature> i = features.iterator(); i.hasNext();) {
Feature feature = i.next();
if (feature.getName().equals(name)) {
i.remove();
}
}
}
}
Looking at your Customer class, I cannot see how did you map the features set, but note that, however you did, the default fetching type is LAZY, meaning that your collection will not be initialized during the read.
Please try the following:
List<T> findByCriteriaImpl(List<String> fetches, Criterion... criterion) {
Criteria crit = createCriteria(getPersistentClass());
if (criterion != null) {
for (Criterion c : criterion) {
crit.add(c);
}
for (String s : fetches) {
crit.setFetchMode(s, FetchMode.JOIN);
}
}
long startTime = System.currentTimeMillis();
List<T> toReturn = crit.list();
reportQueryTimeForMonitoring(System.currentTimeMillis() - startTime, "findByCriteriaImpl", "for criteria " + crit);
return toReturn;
}
And call the findByCriteriaImpl like:
List<Customer> customers = findByCriteriaImpl(Collections.asList("features"), Restrictions.eq("cid", cid));
This way you can tell your method which collections you want to fetch together with your entity.
I am using Android MVP architecture and trying to resolve issue with my test.
When user click confirmation button on registration form, it should test that user was successfully created and pass the created object to View.
Here is my test(not working version):
#Test
public void clickOnConfirmButtonWithValidInput_RegisterSuccessfulCalled(){
when(view.getEmail()).thenReturn(USER_TEST_EMAIL);
when(view.getUsername()).thenReturn(USER_TEST_USERNAME);
when(view.getPassword()).thenReturn(USER_TEST_PASSWORD);
when(view.getConfirmPassword()).thenReturn(USER_TEST_PASSWORD);
UserRegisterFormDTO userRegisterFormDTO = new UserRegisterFormDTO(USER_TEST_EMAIL, USER_TEST_USERNAME, USER_TEST_PASSWORD);
registerPresenter.confirmRegistrationButtonClicked();
UserDTO userDTO = new UserDTO(USER_TEST_ID, userRegisterFormDTO.getUsername(), userRegisterFormDTO.getEmail());
verify(model).createUser(eq(userRegisterFormDTO), createNewUserCallbackArgumentCaptor.capture());
createNewUserCallbackArgumentCaptor.getValue().onUserCreated(userDTO);
verify(view).registerSuccessful(userDTO);
}
And this is the test, which is successfull.
#Test
public void clickOnConfirmButtonWithValidInput_RegisterSuccessfulCalled(){
when(view.getEmail()).thenReturn(USER_TEST_EMAIL);
when(view.getUsername()).thenReturn(USER_TEST_USERNAME);
when(view.getPassword()).thenReturn(USER_TEST_PASSWORD);
when(view.getConfirmPassword()).thenReturn(USER_TEST_PASSWORD);
UserRegisterFormDTO userRegisterFormDTO = new UserRegisterFormDTO(USER_TEST_EMAIL, USER_TEST_USERNAME, USER_TEST_PASSWORD);
registerPresenter.confirmRegistrationButtonClicked();
UserDTO userDTO = new UserDTO(USER_TEST_ID, userRegisterFormDTO.getUsername(), userRegisterFormDTO.getEmail());
verify(model).createUser(eq(USER_TEST_USERNAME), eq(USER_TEST_EMAIL), eq(USER_TEST_PASSWORD), createNewUserCallbackArgumentCaptor.capture());
createNewUserCallbackArgumentCaptor.getValue().onUserCreated(userDTO);
verify(view).registerSuccessful(userDTO);
}
The Exception is like this:
https://gist.github.com/oksett/4571d09557514e6fe7ada2cc21b28d46
So I am only extract values from my UserRegisterFormDTO object and pass its values to the method as a parameter.
In my presenter i was using Model method like this:
#Override
public void confirmRegistrationButtonClicked() {
if (view != null) {
if (view.getUsername().trim().equals("") || view.getEmail().trim().equals("") || view.getPassword().trim().equals("") || view.getConfirmPassword().trim().equals("") || view.getPassword().length() < 6) {
view.showInputError();
} else {
view.setRegisterProcessAlpha();
view.showProgressBar();
UserRegisterFormDTO userRegisterFormDTO = new UserRegisterFormDTO(view.getUsername(), view.getEmail(), view.getPassword());
model.createUser(userRegisterFormDTO, new RegisterMVP.Model.CreateNewUserCallback() {
#Override
public void onUserCreated(UserDTO userDto) {
if (userDto != null) {
view.setRegisterNormalAlpha();
view.hideProgressBar();
view.registerSuccessful(userDto);
} else {
view.setRegisterNormalAlpha();
view.hideProgressBar();
view.showErrorMessage("Unfortunately user was not created, please try again");
}
}
});
}
}
}
So the test works normally for the extracting values from UserRegisterFormDTO to method as parameters. What is wrong?
UPDATE:
Here is my UserRegisterFormDTO class:
public class UserRegisterFormDTO {
private String username;
private String email;
private String password;
public UserRegisterFormDTO(String username, String email, String password) {
this.username = username;
this.email = email;
this.password = password;
}
public String getUsername() {
return username;
}
public String getEmail() {
return email;
}
public String getPassword() {
return password;
}
#Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
UserRegisterFormDTO that = (UserRegisterFormDTO) o;
if (!username.equals(that.username)) return false;
if (!email.equals(that.email)) return false;
return password.equals(that.password);
}
}
I implemented the equals() method, but it still not working.
So this is the answer:
I needed to implement not only equal method, but also hashCode to my UserRegistrationFormDTO.
Here what it looks like now:
public class UserRegisterFormDTO {
private String username;
private String email;
private String password;
public UserRegisterFormDTO(String username, String email, String password) {
this.username = username;
this.email = email;
this.password = password;
}
public String getUsername() {
return username;
}
public String getEmail() {
return email;
}
public String getPassword() {
return password;
}
#Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
UserRegisterFormDTO that = (UserRegisterFormDTO) o;
if (username != null ? !username.equals(that.username) : that.username != null)
return false;
if (email != null ? !email.equals(that.email) : that.email != null) return false;
return password != null ? password.equals(that.password) : that.password == null;
}
#Override
public int hashCode() {
int result = username != null ? username.hashCode() : 0;
result = 31 * result + (email != null ? email.hashCode() : 0);
result = 31 * result + (password != null ? password.hashCode() : 0);
return result;
}
}
The test pass now.
I need your help to understand why in my method the object allocation returns Stack Overflow error.
Here is the method:
public String toJson(){
JSONObject json;
json = new JSONObject(this); //error happens here...
return json.toString();
}
Here all code from this class:
package com.neocloud.model;
import java.io.Serializable;
import com.amazonaws.util.json.JSONObject;
import com.neocloud.amazon.AwsSns;
import com.neocloud.model.dao.DeviceDAO;
import com.neocloud.model.dao.GroupDAO;
import com.neocloud.model.dao.SubscriptionDAO;
public class Subscription implements Serializable{
private static final long serialVersionUID = -3901714994276495605L;
private long id;
private Device dispositivo;
private Group grupo;
private String subscription;
public Subscription(){
clear();
}
public void clear(){
id = 0;
subscription = "";
grupo = new Group();
dispositivo = new Device();
}
public String toJson(){
JSONObject json;
json = new JSONObject(this); //error happens here...
return json.toString();
}
public String registerDB(boolean registrarSNS){
GroupDAO gDAO = new GroupDAO();
DeviceDAO dDAO = new DeviceDAO();
gDAO.selectById(this.grupo);
dDAO.selectById(this.dispositivo);
if (registrarSNS)
registerSNS(this.dispositivo.getEndPointArn(), this.grupo.getTopicArn());
SubscriptionDAO sDAO = new SubscriptionDAO();
return sDAO.insert(this);
}
public String registerSNS(String endpointArn, String topicArn){
String resposta;
AwsSns sns = AwsSns.getInstance();
resposta = ""+sns.addSubscriptionToTopic(endpointArn, topicArn);
setSubscription(resposta);
return resposta;
}
public String delete(){
AwsSns sns = AwsSns.getInstance();
SubscriptionDAO sDAO = new SubscriptionDAO();
sDAO.selectById(this);
sns.deleteSubscriptionFromTopic(this.subscription);
return sDAO.delete(this);
}
public long getId() {
return id;
}
public void setId(long id) {
if (this.id != id)
this.id = id;
}
public String getSubscription() {
return subscription;
}
public void setSubscription(String subscription) {
if (subscription != null){
if (!this.subscription.equals(subscription))
this.subscription = subscription;
}else
this.subscription = new String();
}
public Device getDispositivo() {
return dispositivo;
}
public void setDispositivo(Device dispositivo) {
if (dispositivo != null){
if (dispositivo.getId() != this.dispositivo.getId())
this.dispositivo = dispositivo;
}else
this.dispositivo = new Device();
}
public Group getGrupo() {
return grupo;
}
public void setGrupo(Group grupo) {
if (grupo != null){
if (grupo.getId() != this.grupo.getId())
this.grupo = grupo;
}else
this.grupo = new Group();
}
}
Here is the Device class:
package com.neocloud.model;
import java.io.Serializable;
import java.util.ArrayList;
import com.amazonaws.util.json.JSONException;
import com.amazonaws.util.json.JSONObject;
import com.neocloud.amazon.AwsSns;
import com.neocloud.model.dao.DeviceDAO;
import com.neocloud.model.enums.EEnvironment;
import com.neocloud.model.enums.EProduct;
import com.neocloud.model.enums.ESystem;
public class Device implements Serializable{
private static final long serialVersionUID = 8515474788917476721L;
private long id;
private String development;
private String SSL = "tls://gateway.push.apple.com:2195";
private String feedback = "tls://feedback.push.apple.com:2196";
private String sandboxSSL = "tls://gateway.sandbox.push.apple.com:2195";
private String sandboxFeedback = "tls://feedback.sandbox.push.apple.com:2196";
private String message;
private String endPointArn;
private String deviceToken;
private EProduct appID;
private String appVersion;
private String deviceUID;
private String deviceName;
private String deviceModel;
private String deviceVersion;
private boolean pushBadge;
private boolean pushAlert;
private boolean pushSound;
private ESystem system;
private EEnvironment environment;
private ArrayList<Subscription> subscriptions;
private String deviceUser;
public Device(){
clear();
}
public String deleteToken(){
/*
*
* terminar aqui ainda...
*
DeviceDAO dDAO = new DeviceDAO();
AwsSns sns = AwsSns.getInstance();
sns.deleteDeviceEndpoint(getEndPointArn());
ArrayList<String> subscriptions = dDAO.getSubscriptionsFromEndpointArn(this);
for (int i=0; i<subscriptions.size();i++){
sns.deleteSubscriptionFromTopic(subscriptions.get(i));
}
return dDAO.delete(this);
*/ return "";
}
public String updateToken(){
if ((system == ESystem.IOS) && (deviceToken.length() != 64))
return "deviceTokenlen64";
AwsSns sns = AwsSns.getInstance();
String jsonResposta = ""+sns.updateDeviceEndpoint(getEndPointArn(), deviceToken);
DeviceDAO dDAO = new DeviceDAO();
dDAO.update(this);
return jsonResposta;
}
public String registerDevice(){
if (appVersion.length() == 0)
return "applen0";
if (deviceUID.length() > 40)
return "deviceUID40";
if ((system == ESystem.IOS) && (deviceToken.length() != 64))
return "deviceTokenlen64";
if (deviceName.length() == 0)
return "deviceNamelen0";
if (deviceModel.length() == 0)
return "deviceModellen0";
if (deviceVersion.length() == 0)
return "deviceVersionlen0";
AwsSns sns = AwsSns.getInstance();
String jsonResposta = null;
switch (getAppID()) {
case MODULE: {
if (system == ESystem.IOS)
jsonResposta = ""+sns.createDeviceEndpoint(deviceToken, Constants.ENDPOINTMODULEIOS);
else if (system == ESystem.ANDROID)
jsonResposta = ""+sns.createDeviceEndpoint(deviceToken, Constants.ENDPOINTMODULEANDROID);
break;
}
case HOSTPRO: {
if (system == ESystem.IOS)
jsonResposta = ""+sns.createDeviceEndpoint(deviceToken, Constants.ENDPOINTHOSTPROIOS);
else if (system == ESystem.ANDROID)
jsonResposta = ""+sns.createDeviceEndpoint(deviceToken, Constants.ENDPOINTHOSTPROANDROID);
break;
}
case CONNEXOON: {
if (system == ESystem.IOS)
jsonResposta = ""+sns.createDeviceEndpoint(deviceToken, Constants.ENDPOINTCONNEXOONIOS);
else if (system == ESystem.ANDROID)
jsonResposta = ""+sns.createDeviceEndpoint(deviceToken, Constants.ENDPOINTCONNEXOONANDROID);
break;
}
case TAHOMA: {
break;
}
case MINIBOX: {
break;
}
case NONE: {
}
default: {
}
}
if (jsonResposta != null){
JSONObject json;
try {
jsonResposta = jsonResposta.replace("}", "\"}").replace("arn", "\"arn");
jsonResposta = jsonResposta.replace("{EndPointArn:", "{\"EndPointArn\":");
json = new JSONObject(jsonResposta);
setEndPointArn(json.getString("EndpointArn"));
} catch (JSONException e) {
e.printStackTrace();
}
}
Subscription subscription;
switch (getAppID()){
case MODULE: {
subscription = new Subscription();
subscription.getGrupo().setId(19);
subscription.registerSNS(getEndPointArn(), Constants.ENDPOINTTOPICMODULEGERAL);
subscriptions.add(subscription);
if (system == ESystem.IOS){
subscription = new Subscription();
subscription.getGrupo().setId(25);
subscription.registerSNS(getEndPointArn(), Constants.ENDPOINTTOPICMODULEIOS);
subscriptions.add(subscription);
}
else if (system == ESystem.ANDROID){
subscription = new Subscription();
subscription.getGrupo().setId(22);
subscription.registerSNS(getEndPointArn(), Constants.ENDPOINTTOPICMODULEANDROID);
subscriptions.add(subscription);
}
break;
}
case HOSTPRO: {
subscription = new Subscription();
subscription.getGrupo().setId(10);
subscription.registerSNS(getEndPointArn(), Constants.ENDPOINTTOPICHOSTPROGERAL);
subscriptions.add(subscription);
if (system == ESystem.IOS){
subscription = new Subscription();
subscription.getGrupo().setId(16);
subscription.registerSNS(getEndPointArn(), Constants.ENDPOINTTOPICHOSTPROIOS);
subscriptions.add(subscription);
}
else if (system == ESystem.ANDROID){
subscription = new Subscription();
subscription.getGrupo().setId(13);
subscription.registerSNS(getEndPointArn(), Constants.ENDPOINTTOPICHOSTPROANDROID);
subscriptions.add(subscription);
}
break;
}
case CONNEXOON: {
subscription = new Subscription();
subscription.getGrupo().setId(1);
subscription.registerSNS(getEndPointArn(), Constants.ENDPOINTTOPICCONNEXOONGERAL);
subscriptions.add(subscription);
if (system == ESystem.IOS){
subscription = new Subscription();
subscription.getGrupo().setId(7);
subscription.registerSNS(getEndPointArn(), Constants.ENDPOINTTOPICCONNEXOONIOS);
subscriptions.add(subscription);
}
else if (system == ESystem.ANDROID){
subscription = new Subscription();
subscription.getGrupo().setId(4);
subscription.registerSNS(getEndPointArn(), Constants.ENDPOINTTOPICCONNEXOONANDROID);
subscriptions.add(subscription);
}
break;
}
case TAHOMA: {
break;
}
case MINIBOX: {
break;
}
case NONE: {
}
default: {
}
}
DeviceDAO dDAO = new DeviceDAO();
return dDAO.insert(this);
}
public void clear(){
development = "";
message = "";
endPointArn = "";
deviceToken = "";
appID = EProduct.NONE;
appVersion = "";
deviceUID = "";
deviceName = "";
deviceModel = "";
deviceVersion = "";
pushBadge = false;
pushAlert = false;
pushSound = false;
system = ESystem.NONE;
environment = EEnvironment.HOMOLOGATION;
subscriptions = new ArrayList<Subscription>();
deviceUser = "";
}
public String toJson(){
JSONObject json;
json = new JSONObject(this);
return json.toString();
}
public String getDevelopment() {
return development;
}
public void setDevelopment(String development) {
if (development != null){
if (!development.equals(this.development))
this.development = development;
}
this.development = new String();
}
public String getSSL() {
return SSL;
}
public void setSSL(String sSL) {
if (sSL != null){
if (!sSL.equals(this.SSL))
this.SSL = sSL;
}
else
this.SSL = new String();
}
public String getFeedback() {
return feedback;
}
public void setFeedback(String feedback) {
if (feedback != null){
if (!feedback.equals(this.feedback))
this.feedback = feedback;
}
this.feedback = new String();
}
public String getSandboxSSL() {
return sandboxSSL;
}
public void setSandboxSSL(String sandboxSSL) {
if (sandboxSSL != null){
if (!sandboxSSL.equals(this.sandboxSSL))
this.sandboxSSL = sandboxSSL;
}else
this.sandboxSSL = new String();
}
public String getSandboxFeedback() {
return sandboxFeedback;
}
public void setSandboxFeedback(String sandboxFeedback) {
if (sandboxFeedback != null){
if (!sandboxFeedback.equals(this.sandboxFeedback))
this.sandboxFeedback = sandboxFeedback;
}else
this.sandboxFeedback = new String();
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
if (message != null){
if (!message.equals(this.message))
this.message = message;
}else
this.message = new String();
}
public String getEndPointArn() {
return endPointArn;
}
public void setEndPointArn(String createPlatformEndpointResult) {
if (createPlatformEndpointResult != null){
if (!createPlatformEndpointResult.equals(this.endPointArn))
this.endPointArn = createPlatformEndpointResult;
}else
this.endPointArn = new String();
}
public String getDeviceToken() {
return deviceToken;
}
public void setDeviceToken(String deviceToken) {
if (deviceToken != null){
if (!deviceToken.equals(this.deviceToken))
this.deviceToken = deviceToken;
}else
this.deviceToken = new String();
}
public EProduct getAppID() {
return appID ;
}
public void setAppID(EProduct appID){
if (appID != this.appID)
this.appID = appID;
}
public String getAppVersion() {
return appVersion;
}
public void setAppVersion(String appVersion) {
if (appVersion != null){
if (!appVersion.equals(this.appVersion))
this.appVersion = appVersion;
}else
this.appVersion = new String();
}
public String getDeviceUID() {
return deviceUID;
}
public void setDeviceUID(String deviceUID) {
if (deviceUID != null){
if (!deviceUID.equals(this.deviceUID))
this.deviceUID = deviceUID;
}else
this.deviceUID = new String();
}
public String getDeviceName() {
return deviceName;
}
public void setDeviceName(String deviceName) {
if (deviceName != null){
if (!deviceName.equals(this.deviceName))
this.deviceName = deviceName;
}else
this.deviceName = new String();
}
public String getDeviceModel() {
return deviceModel;
}
public void setDeviceModel(String deviceModel) {
if (deviceModel != null){
if (!deviceModel.equals(this.deviceModel))
this.deviceModel = deviceModel;
}else
this.deviceModel = new String();
}
public String getDeviceVersion() {
return deviceVersion;
}
public void setDeviceVersion(String deviceVersion) {
if (deviceVersion != null){
if (!deviceVersion.equals(this.deviceVersion))
this.deviceVersion = deviceVersion;
}else
this.deviceVersion = new String();
}
public boolean isPushBadge() {
return pushBadge;
}
public void setPushBadge(boolean pushBadge) {
if (pushBadge != this.pushBadge)
this.pushBadge = pushBadge;
}
public boolean isPushAlert() {
return pushAlert;
}
public void setPushAlert(boolean pushAlert) {
if (pushAlert != this.pushAlert)
this.pushAlert = pushAlert;
}
public boolean isPushSound() {
return pushSound;
}
public void setPushSound(boolean pushSound) {
if (this.pushSound != pushSound)
this.pushSound = pushSound;
}
public ESystem getSystem() {
return system;
}
public void setTipoSmartphone(ESystem system) {
if (system != this.system)
this.system = system;
}
public EEnvironment getEnvironment() {
return environment;
}
public void setEnvironment(EEnvironment environment) {
if (environment != this.environment)
this.environment = environment;
}
public long getId() {
return id;
}
public void setId(long id) {
if (this.id != id)
this.id = id;
}
public void setSystem(ESystem system) {
if (system != this.system)
this.system = system;
}
public ArrayList<Subscription> getSubscriptions() {
return subscriptions;
}
public void setSubscriptions(ArrayList<Subscription> subscriptions) {
if (subscriptions != null)
this.subscriptions = subscriptions;
else
this.subscriptions = new ArrayList<Subscription>();
}
public String getDeviceUser() {
return deviceUser;
}
public void setDeviceUser(String deviceUser) {
if (deviceUser != null){
if (!deviceUser.equals(this.deviceUser))
this.deviceUser = deviceUser;
}else
this.deviceUser = new String();
}
}
Here is the Group class:
package com.neocloud.model;
import java.io.Serializable;
import java.util.ArrayList;
import com.amazonaws.util.json.JSONException;
import com.amazonaws.util.json.JSONObject;
import com.neocloud.amazon.AwsSns;
import com.neocloud.model.dao.GroupDAO;
public class Group implements Serializable{
private static final long serialVersionUID = -5032857327241801763L;
private long id;
private String nome;
private String topicArn;
public Group(){
this.clear();
}
public void clear(){
this.id = 0;
this.nome = new String();
this.topicArn = new String();
}
public String registerGrupo(){
AwsSns snsClient = AwsSns.getInstance();
String topic = ""+snsClient.createTopic(this.nome);
JSONObject json;
String jsonResposta = topic;
try {
jsonResposta = jsonResposta.replace("}", "\"}").replace("arn", "\"arn");
jsonResposta = jsonResposta.replace("{TopicArn:", "{\"TopicArn\":");
json = new JSONObject(jsonResposta);
setTopicArn(json.getString("TopicArn"));
} catch (JSONException e) {
e.printStackTrace();
}
GroupDAO grupoDAO = new GroupDAO();
return grupoDAO.insert(this);
}
public String deleteGrupo(){
AwsSns snsClient = AwsSns.getInstance();
GroupDAO grupoDAO = new GroupDAO();
ArrayList<Group> grupos = grupoDAO.select(this);
if (grupos.size() > 0){
for (int i = 0; i<grupos.size(); i++){
this.topicArn = grupos.get(i).getTopicArn();
this.nome = grupos.get(i).getNome();
this.id = grupos.get(i).getId();
snsClient.deleteTopic(this.topicArn);
}
return grupoDAO.delete(this);
}
return "-1";
}
public String toJson(){
JSONObject json;
json = new JSONObject(this);
return json.toString();
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getNome() {
return nome;
}
public void setNome(String nome) {
this.nome = nome;
}
public String getTopicArn() {
return topicArn;
}
public void setTopicArn(String topicArn) {
this.topicArn = topicArn;
}
}
Here is the Tomcat log:
Exception in thread "http-bio-8080-exec-5"
java.lang.StackOverflowError at
java.lang.reflect.Executable.(Unknown Source) at
java.lang.reflect.Method.(Unknown Source) at
java.lang.reflect.Method.copy(Unknown Source) at
java.lang.reflect.ReflectAccess.copyMethod(Unknown Source) at
sun.reflect.ReflectionFactory.copyMethod(Unknown Source) at
java.lang.Class.copyMethods(Unknown Source) at
java.lang.Class.getMethods(Unknown Source) at
com.amazonaws.util.json.JSONObject.populateMap(JSONObject.java:930)
at com.amazonaws.util.json.JSONObject.(JSONObject.java:285) at
com.amazonaws.util.json.JSONObject.wrap(JSONObject.java:1540) at
com.amazonaws.util.json.JSONObject.populateMap(JSONObject.java:960)
Thanks for all help!
Maybe a circular reference in your object.
json = new JSONObject(this);
You're trying to JSONify this
id = 0;
subscription = "";
grupo = new Group();
dispositivo = new Device();
And i think that somehow, it cant JSONify Group and Device. Could you show us the code for those classes ?
UPDATE : In your Subscription.clear() method, you affect a new Group() & a new Device(). When creating a new Device(), the method Device.clear() get called and create a new ArrayList<Subscription>(), that'll call the method Subscription.clear(), that'll affect a new Group() & a new Device() and so on. You're infinitely looping, that's why you get the StackOverflow error. It's weird that you're subscription is made of a Group that is made of an ArrayList of subscription who are also mades of Groups etc.
Maybe you have a circular reference...
Object a = X;
Object c = Y;
a.prop = Y;
c.prop2 = X;
then, your JSON(a) is
{
prop : {
prop2 : {
prop : Y (Y have prop2 again)
/*infinite..*/
}
}
}
I run my test code but show from console
==========Start==========
Exception in thread "main" java.lang.NullPointerException
at practice.BeanUtilsCopyPropertiesTest.main(BeanUtilsCopyPropertiesTest.java:16)
If I use
Ch409FId fromBean = new Ch409FId();
fromBean.setxxx
it's work!!
but I don't know why I can't use
Ch409F fromBean = new Ch409F();
fromBean.getId().setxxxx
thanks a lot...
my code like this:
Main
this is my main code
package practice;
import java.lang.reflect.InvocationTargetException;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.lang.builder.ToStringBuilder;
import bean.Ch409DifF;
import bean.Ch409F;
public class BeanUtilsCopyPropertiesTest {
public static void main(String[] args) {
System.out.println("==========Start==========");
Ch409F fromBean = new Ch409F();
fromBean.getId().setCardClass("fromBean:CardClass");
fromBean.getId().setCardNo("fromBean:CardNo");
fromBean.getId().setRegId("fromBean:RegId");
fromBean.getId().setSeqNo("fromBean:SeqNo");
fromBean.getId().setStoreNo("fromBean:StoreNo");
fromBean.getId().setTaskId("fromBean:TaskId");
fromBean.getId().setTransDate("fromBean:TransDate");
fromBean.getId().setTransTime("fromBean:TransTime");
fromBean.getId().setTransType("fromBean:TransType");
Ch409DifF toBean = new Ch409DifF();
toBean.getId().setCardClass("toBean:CardClass");
toBean.getId().setCardNo("toBean:CardNo");
toBean.getId().setRegId("toBean:RegId");
toBean.getId().setSeqNo("toBean:SeqNo");
toBean.getId().setStoreNo("toBean:StoreNo");
toBean.getId().setTaskId("toBean:TaskId");
toBean.getId().setTransDate("toBean:TransDate");
toBean.getId().setTransTime("toBean:TransTime");
toBean.getId().setTransType("toBean:Transtype");
System.out.println(ToStringBuilder.reflectionToString(fromBean.getId()));
System.out.println(ToStringBuilder.reflectionToString(toBean.getId()));
try {
System.out.println("Copying properties from fromBean to toBean without setActDate");
BeanUtils.copyProperties(toBean, fromBean);
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
System.out.println(ToStringBuilder.reflectionToString(fromBean.getId()));
System.out.println(ToStringBuilder.reflectionToString(toBean.getId()));
fromBean.getId().setActDate(toBean.getActDate());
try {
System.out.println("Copying properties from fromBean to toBean with setActDate");
BeanUtils.copyProperties(toBean, fromBean);
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
System.out.println(ToStringBuilder.reflectionToString(fromBean.getId()));
System.out.println(ToStringBuilder.reflectionToString(toBean.getId()));
System.out.println("==========END==========");
}
}
Ch409DifF:
this is bean
package bean;
import java.util.Date;
public class Ch409DifF implements java.io.Serializable {
private Ch409DifFId id;
private String actDate;
private String clerkNo;
private String amt;
private String invAmt;
private String incAmt;
private String pfsAmt;
private String fee;
private String pfsFee;
private String beforeAmt;
private String afterAmt;
private String cardType;
private String cardSeqNo;
private String rwNo;
private String samId;
private String other;
private String updFlag;
private String updId;
private String autoloadAmt;
private String procFlag;
public Ch409DifF() {
}
public Ch409DifF(Ch409DifFId id, String actDate, String updFlag) {
this.id = id;
this.actDate = actDate;
this.updFlag = updFlag;
}
public Ch409DifF(Ch409DifFId id, String actDate, String clerkNo, String amt,
String invAmt, String incAmt, String pfsAmt, String fee,
String pfsFee, String beforeAmt, String afterAmt,
String cardType, String cardSeqNo, String rwNo, String samId,
String other, String updFlag, String updId, String autoloadAmt,String procFlag) {
this.id = id;
this.actDate = actDate;
this.clerkNo = clerkNo;
this.amt = amt;
this.invAmt = invAmt;
this.incAmt = incAmt;
this.pfsAmt = pfsAmt;
this.fee = fee;
this.pfsFee = pfsFee;
this.beforeAmt = beforeAmt;
this.afterAmt = afterAmt;
this.cardType = cardType;
this.cardSeqNo = cardSeqNo;
this.rwNo = rwNo;
this.samId = samId;
this.other = other;
this.updFlag = updFlag;
this.updId = updId;
this.autoloadAmt = autoloadAmt;
this.procFlag = procFlag;
}
public Ch409DifFId getId() {
return this.id;
}
public void setId(Ch409DifFId id) {
this.id = id;
}
public String getActDate() {
return this.actDate;
}
public void setActDate(String actDate) {
this.actDate = actDate;
}
public String getClerkNo() {
return this.clerkNo;
}
public void setClerkNo(String clerkNo) {
this.clerkNo = clerkNo;
}
public String getAmt() {
return this.amt;
}
public void setAmt(String amt) {
this.amt = amt;
}
public String getInvAmt() {
return this.invAmt;
}
public void setInvAmt(String invAmt) {
this.invAmt = invAmt;
}
public String getIncAmt() {
return this.incAmt;
}
public void setIncAmt(String incAmt) {
this.incAmt = incAmt;
}
public String getPfsAmt() {
return this.pfsAmt;
}
public void setPfsAmt(String pfsAmt) {
this.pfsAmt = pfsAmt;
}
public String getFee() {
return this.fee;
}
public void setFee(String fee) {
this.fee = fee;
}
public String getPfsFee() {
return this.pfsFee;
}
public void setPfsFee(String pfsFee) {
this.pfsFee = pfsFee;
}
public String getBeforeAmt() {
return this.beforeAmt;
}
public void setBeforeAmt(String beforeAmt) {
this.beforeAmt = beforeAmt;
}
public String getAfterAmt() {
return this.afterAmt;
}
public void setAfterAmt(String afterAmt) {
this.afterAmt = afterAmt;
}
public String getCardType() {
return this.cardType;
}
public void setCardType(String cardType) {
this.cardType = cardType;
}
public String getCardSeqNo() {
return this.cardSeqNo;
}
public void setCardSeqNo(String cardSeqNo) {
this.cardSeqNo = cardSeqNo;
}
public String getRwNo() {
return this.rwNo;
}
public void setRwNo(String rwNo) {
this.rwNo = rwNo;
}
public String getSamId() {
return this.samId;
}
public void setSamId(String samId) {
this.samId = samId;
}
public String getOther() {
return this.other;
}
public void setOther(String other) {
this.other = other;
}
public String getUpdFlag() {
return this.updFlag;
}
public void setUpdFlag(String updFlag) {
this.updFlag = updFlag;
}
public String getUpdId() {
return this.updId;
}
public void setUpdId(String updId) {
this.updId = updId;
}
public String getAutoloadAmt() {
return this.autoloadAmt;
}
public void setAutoloadAmt(String autoloadAmt) {
this.autoloadAmt = autoloadAmt;
}
public String getProcFlag() {
return this.procFlag;
}
public void setProcFlag(String procFlag) {
this.procFlag = procFlag;
}
}
ch490DifFId:
this is bean
package bean;
import java.util.Date;
public class Ch409DifFId implements java.io.Serializable {
private String storeNo;
private String taskId;
private String regId;
private String transType;
private String seqNo;
private String cardNo;
private String transDate;
private String transTime;
private String cardClass;
public Ch409DifFId() {
}
public Ch409DifFId(String storeNo, String taskId, String regId,
String transType, String seqNo, String cardNo, String transDate,
String transTime, String cardClass) {
this.storeNo = storeNo;
this.taskId = taskId;
this.regId = regId;
this.transType = transType;
this.seqNo = seqNo;
this.cardNo = cardNo;
this.transDate = transDate;
this.transTime = transTime;
this.cardClass = cardClass;
}
public String getStoreNo() {
return this.storeNo;
}
public void setStoreNo(String storeNo) {
this.storeNo = storeNo;
}
public String getTaskId() {
return this.taskId;
}
public void setTaskId(String taskId) {
this.taskId = taskId;
}
public String getRegId() {
return this.regId;
}
public void setRegId(String regId) {
this.regId = regId;
}
public String getTransType() {
return this.transType;
}
public void setTransType(String transType) {
this.transType = transType;
}
public String getSeqNo() {
return this.seqNo;
}
public void setSeqNo(String seqNo) {
this.seqNo = seqNo;
}
public String getCardNo() {
return this.cardNo;
}
public void setCardNo(String cardNo) {
this.cardNo = cardNo;
}
public String getTransDate() {
return this.transDate;
}
public void setTransDate(String transDate) {
this.transDate = transDate;
}
public String getTransTime() {
return this.transTime;
}
public void setTransTime(String transTime) {
this.transTime = transTime;
}
public String getCardClass() {
return this.cardClass;
}
public void setCardClass(String cardClass) {
this.cardClass = cardClass;
}
public boolean equals(Object other) {
if ((this == other))
return true;
if ((other == null))
return false;
if (!(other instanceof Ch409DifFId))
return false;
Ch409DifFId castOther = (Ch409DifFId) other;
return ((this.getStoreNo() == castOther.getStoreNo()) || (this
.getStoreNo() != null && castOther.getStoreNo() != null && this
.getStoreNo().equals(castOther.getStoreNo())))
&& ((this.getTaskId() == castOther.getTaskId()) || (this
.getTaskId() != null && castOther.getTaskId() != null && this
.getTaskId().equals(castOther.getTaskId())))
&& ((this.getRegId() == castOther.getRegId()) || (this
.getRegId() != null && castOther.getRegId() != null && this
.getRegId().equals(castOther.getRegId())))
&& ((this.getTransType() == castOther.getTransType()) || (this
.getTransType() != null
&& castOther.getTransType() != null && this
.getTransType().equals(castOther.getTransType())))
&& ((this.getSeqNo() == castOther.getSeqNo()) || (this
.getSeqNo() != null && castOther.getSeqNo() != null && this
.getSeqNo().equals(castOther.getSeqNo())))
&& ((this.getCardNo() == castOther.getCardNo()) || (this
.getCardNo() != null && castOther.getCardNo() != null && this
.getCardNo().equals(castOther.getCardNo())))
&& ((this.getTransDate() == castOther.getTransDate()) || (this
.getTransDate() != null
&& castOther.getTransDate() != null && this
.getTransDate().equals(castOther.getTransDate())))
&& ((this.getTransTime() == castOther.getTransTime()) || (this
.getTransTime() != null
&& castOther.getTransTime() != null && this
.getTransTime().equals(castOther.getTransTime())))
&& (this.getCardClass() == castOther.getCardClass());
}
public int hashCode() {
int result = 17;
result = 37 * result
+ (getStoreNo() == null ? 0 : this.getStoreNo().hashCode());
result = 37 * result
+ (getTaskId() == null ? 0 : this.getTaskId().hashCode());
result = 37 * result
+ (getRegId() == null ? 0 : this.getRegId().hashCode());
result = 37 * result
+ (getTransType() == null ? 0 : this.getTransType().hashCode());
result = 37 * result
+ (getSeqNo() == null ? 0 : this.getSeqNo().hashCode());
result = 37 * result
+ (getCardNo() == null ? 0 : this.getCardNo().hashCode());
result = 37 * result
+ (getTransDate() == null ? 0 : this.getTransDate().hashCode());
result = 37 * result
+ (getTransTime() == null ? 0 : this.getTransTime().hashCode());
result = 37 * result + (getCardClass() == null ? 0 : this.getCardClass().hashCode());
return result;
}
}
Ch409F:
this is bean
package bean;
import java.util.Date;
public class Ch409F implements java.io.Serializable {
private Ch409FId id;
private String clerkNo;
private String amt;
private String invAmt;
private String incAmt;
private String pfsAmt;
private String fee;
private String pfsFee;
private String beforeAmt;
private String afterAmt;
private String cardType;
private String cardSeqNo;
private String rwNo;
private String samId;
private String autoloadAmt;
private String other;
private String sendDate;
private String updFlag;
private String updId;
private String updDate;
public Ch409F() {
}
public Ch409F(Ch409FId id, String updFlag) {
this.id = id;
this.updFlag = updFlag;
}
public Ch409F(Ch409FId id, String clerkNo, String amt, String invAmt,
String incAmt, String pfsAmt, String fee, String pfsFee,
String beforeAmt, String afterAmt, String cardType,
String cardSeqNo, String rwNo, String samId, String autoloadAmt,
String other, String sendDate, String updFlag, String updId,
String updDate) {
this.id = id;
this.clerkNo = clerkNo;
this.amt = amt;
this.invAmt = invAmt;
this.incAmt = incAmt;
this.pfsAmt = pfsAmt;
this.fee = fee;
this.pfsFee = pfsFee;
this.beforeAmt = beforeAmt;
this.afterAmt = afterAmt;
this.cardType = cardType;
this.cardSeqNo = cardSeqNo;
this.rwNo = rwNo;
this.samId = samId;
this.autoloadAmt = autoloadAmt;
this.other = other;
this.sendDate = sendDate;
this.updFlag = updFlag;
this.updId = updId;
this.updDate = updDate;
}
public Ch409FId getId() {
return this.id;
}
public void setId(Ch409FId id) {
this.id = id;
}
public String getClerkNo() {
return this.clerkNo;
}
public void setClerkNo(String clerkNo) {
this.clerkNo = clerkNo;
}
public String getAmt() {
return this.amt;
}
public void setAmt(String amt) {
this.amt = amt;
}
public String getInvAmt() {
return this.invAmt;
}
public void setInvAmt(String invAmt) {
this.invAmt = invAmt;
}
public String getIncAmt() {
return this.incAmt;
}
public void setIncAmt(String incAmt) {
this.incAmt = incAmt;
}
public String getPfsAmt() {
return this.pfsAmt;
}
public void setPfsAmt(String pfsAmt) {
this.pfsAmt = pfsAmt;
}
public String getFee() {
return this.fee;
}
public void setFee(String fee) {
this.fee = fee;
}
public String getPfsFee() {
return this.pfsFee;
}
public void setPfsFee(String pfsFee) {
this.pfsFee = pfsFee;
}
public String getBeforeAmt() {
return this.beforeAmt;
}
public void setBeforeAmt(String beforeAmt) {
this.beforeAmt = beforeAmt;
}
public String getAfterAmt() {
return this.afterAmt;
}
public void setAfterAmt(String afterAmt) {
this.afterAmt = afterAmt;
}
public String getCardType() {
return this.cardType;
}
public void setCardType(String cardType) {
this.cardType = cardType;
}
public String getCardSeqNo() {
return this.cardSeqNo;
}
public void setCardSeqNo(String cardSeqNo) {
this.cardSeqNo = cardSeqNo;
}
public String getRwNo() {
return this.rwNo;
}
public void setRwNo(String rwNo) {
this.rwNo = rwNo;
}
public String getSamId() {
return this.samId;
}
public void setSamId(String samId) {
this.samId = samId;
}
public String getAutoloadAmt() {
return this.autoloadAmt;
}
public void setAutoloadAmt(String autoloadAmt) {
this.autoloadAmt = autoloadAmt;
}
public String getOther() {
return this.other;
}
public void setOther(String other) {
this.other = other;
}
public String getSendDate() {
return this.sendDate;
}
public void setSendDate(String sendDate) {
this.sendDate = sendDate;
}
public String getUpdFlag() {
return this.updFlag;
}
public void setUpdFlag(String updFlag) {
this.updFlag = updFlag;
}
public String getUpdId() {
return this.updId;
}
public void setUpdId(String updId) {
this.updId = updId;
}
public String getUpdDate() {
return this.updDate;
}
public void setUpdDate(String updDate) {
this.updDate = updDate;
}
}
Ch409FId:
this is bean
package bean;
import java.util.Date;
public class Ch409FId implements java.io.Serializable {
private String storeNo;
private String actDate;
private String taskId;
private String regId;
private String transType;
private String seqNo;
private String cardNo;
private String transDate;
private String transTime;
private String cardClass;
public Ch409FId() {
}
public Ch409FId(String storeNo, String actDate, String taskId, String regId,
String transType, String seqNo, String cardNo, String transDate,
String transTime, String cardClass) {
this.storeNo = storeNo;
this.actDate = actDate;
this.taskId = taskId;
this.regId = regId;
this.transType = transType;
this.seqNo = seqNo;
this.cardNo = cardNo;
this.transDate = transDate;
this.transTime = transTime;
this.cardClass = cardClass;
}
public String getStoreNo() {
return this.storeNo;
}
public void setStoreNo(String storeNo) {
this.storeNo = storeNo;
}
public String getActDate() {
return this.actDate;
}
public void setActDate(String actDate) {
this.actDate = actDate;
}
public String getTaskId() {
return this.taskId;
}
public void setTaskId(String taskId) {
this.taskId = taskId;
}
public String getRegId() {
return this.regId;
}
public void setRegId(String regId) {
this.regId = regId;
}
public String getTransType() {
return this.transType;
}
public void setTransType(String transType) {
this.transType = transType;
}
public String getSeqNo() {
return this.seqNo;
}
public void setSeqNo(String seqNo) {
this.seqNo = seqNo;
}
public String getCardNo() {
return this.cardNo;
}
public void setCardNo(String cardNo) {
this.cardNo = cardNo;
}
public String getTransDate() {
return this.transDate;
}
public void setTransDate(String transDate) {
this.transDate = transDate;
}
public String getTransTime() {
return this.transTime;
}
public void setTransTime(String transTime) {
this.transTime = transTime;
}
public String getCardClass() {
return this.cardClass;
}
public void setCardClass(String cardClass) {
this.cardClass = cardClass;
}
public boolean equals(Object other) {
if ((this == other))
return true;
if ((other == null))
return false;
if (!(other instanceof Ch409FId))
return false;
Ch409FId castOther = (Ch409FId) other;
return ((this.getStoreNo() == castOther.getStoreNo()) || (this
.getStoreNo() != null && castOther.getStoreNo() != null && this
.getStoreNo().equals(castOther.getStoreNo())))
&& ((this.getActDate() == castOther.getActDate()) || (this
.getActDate() != null && castOther.getActDate() != null && this
.getActDate().equals(castOther.getActDate())))
&& ((this.getTaskId() == castOther.getTaskId()) || (this
.getTaskId() != null && castOther.getTaskId() != null && this
.getTaskId().equals(castOther.getTaskId())))
&& ((this.getRegId() == castOther.getRegId()) || (this
.getRegId() != null && castOther.getRegId() != null && this
.getRegId().equals(castOther.getRegId())))
&& ((this.getTransType() == castOther.getTransType()) || (this
.getTransType() != null
&& castOther.getTransType() != null && this
.getTransType().equals(castOther.getTransType())))
&& ((this.getSeqNo() == castOther.getSeqNo()) || (this
.getSeqNo() != null && castOther.getSeqNo() != null && this
.getSeqNo().equals(castOther.getSeqNo())))
&& ((this.getCardNo() == castOther.getCardNo()) || (this
.getCardNo() != null && castOther.getCardNo() != null && this
.getCardNo().equals(castOther.getCardNo())))
&& ((this.getTransDate() == castOther.getTransDate()) || (this
.getTransDate() != null
&& castOther.getTransDate() != null && this
.getTransDate().equals(castOther.getTransDate())))
&& ((this.getTransTime() == castOther.getTransTime()) || (this
.getTransTime() != null
&& castOther.getTransTime() != null && this
.getTransTime().equals(castOther.getTransTime())))
&& (this.getCardClass() == castOther.getCardClass());
}
public int hashCode() {
int result = 17;
result = 37 * result
+ (getStoreNo() == null ? 0 : this.getStoreNo().hashCode());
result = 37 * result
+ (getActDate() == null ? 0 : this.getActDate().hashCode());
result = 37 * result
+ (getTaskId() == null ? 0 : this.getTaskId().hashCode());
result = 37 * result
+ (getRegId() == null ? 0 : this.getRegId().hashCode());
result = 37 * result
+ (getTransType() == null ? 0 : this.getTransType().hashCode());
result = 37 * result
+ (getSeqNo() == null ? 0 : this.getSeqNo().hashCode());
result = 37 * result
+ (getCardNo() == null ? 0 : this.getCardNo().hashCode());
result = 37 * result
+ (getTransDate() == null ? 0 : this.getTransDate().hashCode());
result = 37 * result
+ (getTransTime() == null ? 0 : this.getTransTime().hashCode());
result = 37 * result + (getCardClass() == null ? 0 : this.getCardClass().hashCode());
return result;
}
}
you are not creating object of Ch409DifF for the identifier id. So when you call getID(), it returns null,default value of Object .So either use constructor with 3 parameters,
public Ch409DifF(Ch409DifFId id, String actDate, String updFlag) {
OR
public Ch409DifF(Ch409DifFId id, String actDate, String clerkNo, String amt,
String invAmt, String incAmt, String pfsAmt, String fee,
String pfsFee, String beforeAmt, String afterAmt,
String cardType, String cardSeqNo, String rwNo, String samId,
String other, String updFlag, String updId, String autoloadAmt,String procFlag) {
I replace some codes:
Ch409F fromBean = new Ch409F();
//add
Ch409FId c409fid = new Ch409FId();
fromBean.setId(c409fid);
Ch409DifF toBean = new Ch409DifF();
//add
Ch409DifFId c409diffid = new Ch409DifFId();
toBean.setId(c409diffid);
and replace
System.out.println(ToStringBuilder.reflectionToString(fromBean);
System.out.println(ToStringBuilder.reflectionToString(toBean);
to
System.out.println(ToStringBuilder.reflectionToString(fromBean.getId()));
System.out.println(ToStringBuilder.reflectionToString(toBean.getId()));
and it's working!!!
I have a Canteen class and a Course class (and a BaseEntity). The Canteen class has a set of courses. A course is unique if the composition of name, dateOfServing and the canteen id is unique. I tried to write a test case which should throw an exception if a non-unique course is added to a canteen. But the test doesn't throw any exception at all. Which leads me to believe that I'm doing me Canteen and Course class wrong. The test in question is addDuplicatedCourseToCanteenTest. Anyone got a clue about what I'm doing wrong?
I'm new to TDD as well so any critique in that area is very welcome as well.
BaseEntity.java
#MappedSuperclass
public class BaseEntity {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
long id;
private Date createdAt;
private Date updatedAt;
// TODO: http://stackoverflow.com/a/11174297/672009
// Using the above we wouldn't have to created a CommentRepository
// Is that a good idea?
/**
* http://www.devsniper.com/base-entity-class-in-jpa/
*/
/**
* Sets createdAt before insert
*/
#PrePersist
public void setCreationDate() {
this.setCreatedAt(new Date());
}
/**
* Sets updatedAt before update
*/
#PreUpdate
public void setChangeDate() {
this.setUpdatedAt(new Date());
}
public Date getCreatedAt() {
return createdAt;
}
protected void setCreatedAt(Date createdAt) {
this.createdAt = createdAt;
}
public Date getUpdatedAt() {
return updatedAt;
}
protected void setUpdatedAt(Date updatedAt) {
this.updatedAt = updatedAt;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + (int) (id ^ (id >>> 32));
return result;
}
#Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
BaseEntity other = (BaseEntity) obj;
if (id != other.id)
return false;
return true;
}
}
Canteen.java
#Entity
public class Canteen extends BaseEntity {
private String name;
// TODO: https://schuchert.wikispaces.com/JPA+Tutorial+1+-+Embedded+Entity
// http://docs.oracle.com/javaee/6/api/javax/xml/registry/infomodel/PostalAddress.html
//private Address address;
//private PostalAddress postalAddress;
/**
* In honor of KISS I simply use a simple string address as a holder for the restaurants address.
* The idea is that the string will contain an address which will be valid according to google maps.
* Same goes for openingHours, phoneNumber and homepage... KISS wise.
*/
private String address;
private String openingHours; // A string which will be presented within a pre tag
// Eg. <pre>Mandag - Torsdag 10-22
// Fredag - Lørdag 10-24
// Søndag 11-20</pre>
private String contact;
#OneToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL)
private Set<Course> courses = new HashSet<>();
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getOpeningHours() {
return openingHours;
}
public void setOpeningHours(String openingHours) {
this.openingHours = openingHours;
}
public String getContact() {
return contact;
}
public void setContact(String contact) {
this.contact = contact;
}
public Set<Course> getCourses() {
return courses;
}
public void setCourses(Set<Course> courses) {
this.courses = courses;
}
public boolean addCourse(Course course)
{
return getCourses().add(course);
}
#Override
public int hashCode() {
final int prime = 31;
int result = super.hashCode();
result = prime * result + ((address == null) ? 0 : address.hashCode());
result = prime * result + ((name == null) ? 0 : name.hashCode());
return result;
}
#Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (!super.equals(obj))
return false;
if (getClass() != obj.getClass())
return false;
Canteen other = (Canteen) obj;
if (address == null) {
if (other.address != null)
return false;
} else if (!address.equals(other.address))
return false;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
return true;
}
}
Course.java
#Entity
public class Course extends BaseEntity {
private String name;
private Date dateOfServing;
#ManyToOne
private Canteen canteen;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Date getDateOfServing() {
return dateOfServing;
}
public void setDateOfServing(Date dateOfServing) {
this.dateOfServing = dateOfServing;
}
public Canteen getCanteen() {
return canteen;
}
public void setCanteen(Canteen canteen) {
this.canteen = canteen;
}
#Override
public int hashCode() {
final int prime = 31;
int result = super.hashCode();
result = prime * result + ((canteen == null) ? 0 : canteen.hashCode());
result = prime * result
+ ((dateOfServing == null) ? 0 : dateOfServing.hashCode());
result = prime * result + ((name == null) ? 0 : name.hashCode());
return result;
}
#Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (!super.equals(obj))
return false;
if (getClass() != obj.getClass())
return false;
Course other = (Course) obj;
if (canteen == null) {
if (other.canteen != null)
return false;
} else if (!canteen.equals(other.canteen))
return false;
if (dateOfServing == null) {
if (other.dateOfServing != null)
return false;
} else if (!dateOfServing.equals(other.dateOfServing))
return false;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
return true;
}
}
CanteenHasCoursesTest.java
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration(classes = PersistenceConfig.class)
public class CanteenHasCoursesTest {
#Autowired
private CanteenRepository canteenRepository;
private String canteenName;
private String courseName;
private Canteen canteen;
private Course course;
#Before
public void setUp() {
// Generate unique random name
canteenName = UUID.randomUUID().toString();
// Generate unique random name
courseName = UUID.randomUUID().toString();
// Create new canteen
canteen = new Canteen();
canteen.setName(canteenName);
// Create new course
course = new Course();
course.setName(courseName);
}
#Test
public void addCourseToCanteenTest() {
// Add course
canteen.addCourse(course);
// Save canteen
canteenRepository.save(canteen);
// Find it again
Canteen c = canteenRepository.findOne(canteen.getId());
// Confirm attributes are as expected
assertNotNull(c);
Set<Course> courses = c.getCourses();
Iterator<Course> it = courses.iterator();
assertTrue(it.hasNext());
Course course = it.next();
assertEquals(courseName, course.getName());
}
// TODO: expect some data violation exception
// #Test(expected = IndexOutOfBoundsException.class)
#Test
public void addDuplicatedCourseToCanteenTest() {
// Add course
canteen.addCourse(course);
// Add it again
canteen.addCourse(course);
// Save canteen
canteenRepository.save(canteen);
}
#After
public void tearDown() {
canteenRepository = null;
canteenName = null;
courseName = null;
canteen = null;
course = null;
}
}