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!!!
Related
I have a problem. I have the following class:
public class Cross implements Comparable<Cross> {
private Long openTime;
private String market;
private String coin;
private String period;
private String metric1;
private String metric2;
private Double close;
private String trend;
public Long getOpenTime() {
return this.openTime;
}
public void setOpenTime(long openTime) {
this.openTime = openTime;
}
public String getMarket() {
return this.market;
}
public void setMarket(String market) {
this.market = market;
}
public String getCoin() {
return this.coin;
}
public void setCoin(String coin) {
this.coin = coin;
}
public String getPeriod() {
return this.period;
}
public void setPeriod(String period) {
this.period = period;
}
public String getMetric1() {
return this.metric1;
}
public void setMetric1(String metric1) {
this.metric1 = metric1;
}
public String getMetric2() {
return this.metric2;
}
public void setMetric2(String metric2) {
this.metric2 = metric2;
}
public Double getClose() {
return this.close;
}
public void setClose(double close) {
this.close = close;
}
public String getTrend() {
return this.trend;
}
#Override
public boolean equals(Object object) {
if (object != null && object instanceof Cross) {
Cross cross = (Cross) object;
return (
openTime.equals(cross.getOpenTime()) &&
market.equals(cross.getMarket()) &&
coin.equals(cross.getCoin()) &&
period.equals(cross.getPeriod()) &&
metric1.equals(cross.getMetric1()) &&
metric2.equals(cross.getMetric2())
);
}
return false;
}
#Override
public int compareTo(Cross o) {
return this.getOpenTime().compareTo(o.getOpenTime());
}
}
Now I have a list containing 500 objects of these elements. Here are the first 4 shown:
{ openTime='1504332000000', market='USDT', coin='ETH', period='2h', metric1='EMA12', metric2='EMA26', close='363.7', trend='Down'}
{ openTime='1504663200000', market='USDT', coin='ETH', period='2h', metric1='EMA12', metric2='EMA26', close='325.73', trend='Up'}
{ openTime='1504879200000', market='USDT', coin='ETH', period='2h', metric1='EMA12', metric2='EMA26', close='294.05', trend='Down'}
{ openTime='1505181600000', market='USDT', coin='ETH', period='2h', metric1='EMA12', metric2='EMA26', close='304.41', trend='Up'}
In a variable I have stored the epoch of a specific datetime and with that I want to find the first valid cross, so I tried this:
private Cross getValidCross(List<Cross> crossList, LocalDateTime runDateTimeGMT0) {
long searchEpoch = runDateTimeGMT0.toEpochSecond(ZoneOffset.UTC) * 1000;
return crossList.stream().filter(cross -> cross.getOpenTime() < searchEpoch).max(Cross::compareTo).orElse(null);
}
But this code returns the value null When my searchEpoch is for example: 1514764800000. In the list I do see multiple objects that have a lower openTime than the searchEpoch. The result I want is the cross with the highest openTime, but it still has to be smaller than the searchEpoch.
Here is the error I get:
runDateTimeGMT0: 2018-01-01T00:00
Exception in thread "main" java.lang.reflect.InvocationTargetException
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:64)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:564)
at com.hatop.drivers.SimulatorDriver.run(SimulatorDriver.java:297)
at com.hatop.drivers.HatopDriver.main(HatopDriver.java:120)
Caused by: java.lang.NullPointerException: Cannot invoke "com.hatop.models.Cross.getTrend()" because the return value of "com.hatop.drivers.HatopDriver.getValidCross(List<Cross>, LocalDateTime)"
is null
at com.hatop.strategies.modules.module_java001.run(module_java001.java:186)
... 6 more
Why is my return value null?
This is caused due to the value the argument runDateTimeGMT0 is given and this:
long searchEpoch = runDateTimeGMT0.toEpochSecond(ZoneOffset.UTC) * 1000;
Since this is working:
public class Demo {
private static Cross getValidCross(List<Cross> crossList, LocalDateTime runDateTimeGMT0) {
long searchEpoch = 1514764800000L;
return crossList.stream()
.filter(cross -> cross.getOpenTime() < searchEpoch)
.max(Cross::compareTo)
.orElse(null);
}
#SneakyThrows
public static void main(String[] args) {
List<Cross> crosses = Arrays.asList(
new Cross(1504332000000L, "USDT", "ETH", "2h", "EMA12", "EMA26", 363.7, "Down"),
new Cross(1504663200000L, "USDT", "ETH", "2h", "EMA12", "EMA26", 325.73, "Up"),
new Cross(1504879200000L, "USDT", "ETH", "2h", "EMA12", "EMA26", 294.05, "Down"),
new Cross(1505181600000L, "USDT", "ETH", "2h", "EMA12", "EMA26", 304.41, "Up")
);
Cross validCross = getValidCross(crosses, null);
System.out.println(validCross);
}
}
Output:
Cross(openTime=1505181600000, market=USDT, coin=ETH, period=2h, metric1=EMA12, metric2=EMA26, close=304.41, trend=Up)
By the way, equals() is implemented without hashcode() - a recipe for problems.
I tested you code by passing the value in a proper Cross constructor, as it appears in your list and it works fine. In particular, openingTime is passed as primitive type long.
The issue is NOT in the filter, as you can definitely use any operator with Long type.
In my opinion, there is something wrong in the file format of your Cross object. Highly likely is because of the openingTime field's value, which is probably converted in the wrong value.
Here is the test I wrote:
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.util.List;
public class TestCross {
public static void main(String[] args) {
List<Cross> crossList = List.of(new Cross(1504332000000L,"USDT", "ETH", "2h","EMA12", "EMA26",363.7,"Down" ),
new Cross(1505181600000L,"USDT", "ETH", "2h","EMA12", "EMA26",304.41,"Up" ),
new Cross(1504663200000L,"USDT", "ETH", "2h","EMA12", "EMA26",325.73,"Up" ),
new Cross(1504879200000L,"USDT", "ETH", "2h","EMA12", "EMA26",294.05,"Down" ));
Cross cross = new TestCross().getValidCross(crossList, LocalDateTime.now());
System.out.println(cross);
}
private Cross getValidCross(List<Cross> crossList, LocalDateTime runDateTimeGMT0) {
long searchEpoch = runDateTimeGMT0.toEpochSecond(ZoneOffset.UTC) * 1000;
return crossList.stream().filter(cross -> cross.getOpenTime() < searchEpoch).max(Cross::compareTo).orElse(null);
}
}
Cross class
public class Cross implements Comparable<Cross> {
public Cross(Long openTime, String market, String coin, String period, String metric1, String metric2, Double close,
String trend) {
super();
this.openTime = openTime;
this.market = market;
this.coin = coin;
this.period = period;
this.metric1 = metric1;
this.metric2 = metric2;
this.close = close;
this.trend = trend;
}
private Long openTime;
private String market;
private String coin;
private String period;
private String metric1;
private String metric2;
private Double close;
private String trend;
public Long getOpenTime() {
return this.openTime;
}
public void setOpenTime(long openTime) {
this.openTime = openTime;
}
public String getMarket() {
return this.market;
}
public void setMarket(String market) {
this.market = market;
}
public String getCoin() {
return this.coin;
}
public void setCoin(String coin) {
this.coin = coin;
}
public String getPeriod() {
return this.period;
}
public void setPeriod(String period) {
this.period = period;
}
public String getMetric1() {
return this.metric1;
}
public void setMetric1(String metric1) {
this.metric1 = metric1;
}
public String getMetric2() {
return this.metric2;
}
public void setMetric2(String metric2) {
this.metric2 = metric2;
}
public Double getClose() {
return this.close;
}
public void setClose(double close) {
this.close = close;
}
public String getTrend() {
return this.trend;
}
#Override
public boolean equals(Object object) {
if (object != null && object instanceof Cross) {
Cross cross = (Cross) object;
return (
openTime.equals(cross.getOpenTime()) &&
market.equals(cross.getMarket()) &&
coin.equals(cross.getCoin()) &&
period.equals(cross.getPeriod()) &&
metric1.equals(cross.getMetric1()) &&
metric2.equals(cross.getMetric2())
);
}
return false;
}
#Override
public String toString() {
return "Cross [openTime=" + openTime + ", market=" + market + ", coin=" + coin + ", period=" + period
+ ", metric1=" + metric1 + ", metric2=" + metric2 + ", close=" + close + ", trend=" + trend + "]";
}
#Override
public int compareTo(Cross o) {
return this.getOpenTime().compareTo(o.getOpenTime());
}
}
And here is the output:
Cross [openTime=1505181600000, market=USDT, coin=ETH, period=2h, metric1=EMA12, metric2=EMA26, close=304.41, trend=Up]
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.
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 try to send a json Object to a Rest Service. The problem is that I recieve the object with empty attributes
The rest Service:
#RequestMapping(value = "/retrieve_combo_values",
consumes="application/json",
method = RequestMethod.POST)
public List<ComboValueDTO> retrieveValuesForCombo(#RequestBody ElementDTO element)
throws Exception {
return service.retrieveValuesForCombo(element);
}
ElementDTO:
public class ElementDTO implements Serializable {
private String name = "";
private String labelId = "";
private ParameterType parameterType;
private boolean mandatory = false;
private boolean visible = true;
private String defaultValue = "";
private UIElementTypeDTO elementType;
private String regExErrMsg = "";
private String requiredErrMsg = "";
public ElementDTO() { }
public ElementDTO(String name, String labelId,
ParameterType parameterType,
boolean mandatory,
boolean visible,
String defaultValue,
UIElementTypeDTO elementType,
String regExErrMsg,
String requiredErrMsg)
{
this.name = name;
this.labelId = labelId;
this.parameterType = parameterType;
this.mandatory = mandatory;
this.visible = visible;
this.defaultValue = defaultValue;
this.elementType = elementType;
this.regExErrMsg = regExErrMsg;
this.requiredErrMsg = requiredErrMsg;
}
public ElementDTO(UIQueryParameter el) {
this(el.getName(), "", el.getParameterType(),
el.isMandatory(), el.isVisible(), el.getDefaultValue(),
getElementTypeFromParameterType(el.getParameterType()),
"", "");
ResourceBundle props =
ResourceBundle.getBundle(IConstants.BUNDLE_KEY,
BdociConfig.getLocale());
this.labelId = Utils.getUTF8ResourceBundleString(props,
el.getLabelId());
this.regExErrMsg = Utils.getUTF8ResourceBundleString(
props, IConstants.RegExp_Error_Prefix + parameterType.getErrID());
if (this.mandatory) {
this.requiredErrMsg =
Utils.getUTF8ResourceBundleString(
props, IConstants.Required_Error_Key);
}
}
private static UIElementTypeDTO
getElementTypeFromParameterType(ParameterType parameterType)
{
String pType = parameterType.getClass().getSimpleName();
return UIElementTypeDTO.get(pType);
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getLabelId() {
return labelId;
}
public void setLabelId(String labelId) {
this.labelId = labelId;
}
public ParameterType getParameterType() {
return parameterType;
}
public void setParameterType(ParameterType parameterType) {
this.parameterType = parameterType;
}
public boolean isMandatory() {
return mandatory;
}
public void setMandatory(boolean mandatory) {
this.mandatory = mandatory;
}
public boolean isVisible() {
return visible;
}
public void setVisible(boolean visible) {
this.visible = visible;
}
public String getDefaultValue() {
return defaultValue;
}
public void setDefaultValue(String defaultValue) {
this.defaultValue = defaultValue;
}
public UIElementTypeDTO getElementType() {
return elementType;
}
public void setElementType(UIElementTypeDTO elementType) {
this.elementType = elementType;
}
public String getRegExErrMsg() {
return regExErrMsg;
}
public void setRegExErrMsg(String regExErrMsg) {
this.regExErrMsg = regExErrMsg;
}
public String getRequiredErrMsg() {
return requiredErrMsg;
}
public void setRequiredErrMsg(String requiredErrMsg) {
this.requiredErrMsg = requiredErrMsg;
}
public List<ComboValueDTO>
retrieveValues(IBdocDesktopController service)
throws BdocWebAccessException,
TransformerException,
ParserConfigurationException
{
return elementType.retrieveValues(parameterType, service);
}
#Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
ElementDTO that = (ElementDTO) o;
if (mandatory != that.mandatory) return false;
if (visible != that.visible) return false;
if (defaultValue != null ?
!defaultValue.equals(that.defaultValue) :
that.defaultValue != null)
return false;
if (elementType != that.elementType) return false;
if (labelId != null ? !labelId.equals(that.labelId) :
that.labelId != null) return false;
if (name != null ? !name.equals(that.name) : that.name != null)
return false;
if (parameterType != null ?
!parameterType.equals(that.parameterType) :
that.parameterType != null)
return false;
if (regExErrMsg != null ? !regExErrMsg.equals(that.regExErrMsg) :
that.regExErrMsg != null)
return false;
if (requiredErrMsg != null ?
!requiredErrMsg.equals(that.requiredErrMsg) :
that.requiredErrMsg != null)
return false;
return true;
}
#Override
public int hashCode() {
int result = name != null ? name.hashCode() : 0;
result = 31 * result + (labelId != null ? labelId.hashCode() : 0);
result = 31 * result + (parameterType != null ?
parameterType.hashCode() : 0);
result = 31 * result + (mandatory ? 1 : 0);
result = 31 * result + (visible ? 1 : 0);
result = 31 * result + (defaultValue != null ?
defaultValue.hashCode() : 0);
result = 31 * result + (elementType != null ?
elementType.hashCode() : 0);
result = 31 * result + (regExErrMsg != null ?
regExErrMsg.hashCode() : 0);
result = 31 * result + (requiredErrMsg != null ?
requiredErrMsg.hashCode() : 0);
return result;
}
}
In the client side: I want to create an Extjs Store using this Service
store.on('beforeload', function (store) {
store.proxy.extraParams = {
element: me //me is the json Object
}
});
Request body:
{"query":"","element":{"name":"domaine","labelId":"Domaines ","parameterType":{"regEx":"^.*$","errID":"121","selectedValue":""},"mandatory":false,"visible":true,"defaultValue":"","elementType":"BDOC_DOMAIN_LIST","regExErrMsg":"Valeur invalide.","requiredErrMsg":""}}
When debugging in the service, I found the element object but its attributes are empty.
Can you help me please?
You need to make your handler method parameter POJO fit your JSON
{
"query": "",
"element": {
"name": "domaine",
"labelId": "Domaines ",
"parameterType": {
"regEx": "^.*$",
"errID": "121",
"selectedValue": ""
},
"mandatory": false,
"visible": true,
"defaultValue": "",
"elementType": "BDOC_DOMAIN_LIST",
"regExErrMsg": "Valeur invalide.",
"requiredErrMsg": ""
}
}
That is
class Wrapper {
private String query;
private ElementDTO element;
// getters and setters
}
which will change
public List<ComboValueDTO> retrieveValuesForCombo(#RequestBody ElementDTO element)
to
public List<ComboValueDTO> retrieveValuesForCombo(#RequestBody Wrapper element)
i want add Method Expression support on to my custom component.
i've seen that i must write a tagHandler.
i've seen this post :
How to add Method Expression to a custom JSF component
I don't understand what are the parameters "void.class" and "moveEvent" of the methodRule method.
This is my customComponent code :
public class Link extends UIOutput{
private StringBuilder style = new StringBuilder();
private String id = "";
private Boolean active = false;
private String alt = "";
private String href = "";
private String hreflang = "";
private String rel = "";
private String target = "";
private String download = "";
private String media = "";
private String type = "";
public Boolean isActive() {
return active;
}
public void setActive(Boolean active) {
this.active = active;
}
public String getAlt() {
return alt;
}
public void setAlt(String alt) {
this.alt = alt;
}
public String getHref() {
return href;
}
public void setHref(String href) {
this.href = href;
}
public String getHreflang() {
return hreflang;
}
public void setHreflang(String hreflang) {
this.hreflang = hreflang;
}
public String getRel() {
return rel;
}
public void setRel(String rel) {
this.rel = rel;
}
public String getTarget() {
return target;
}
public void setTarget(String target) {
this.target = target;
}
public String getDownload() {
return download;
}
public void setDownload(String download) {
this.download = download;
}
public String getMedia() {
return media;
}
public void setMedia(String media) {
this.media = media;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
#Override
public void encodeBegin(FacesContext context)throws IOException {
ResponseWriter writer = context.getResponseWriter();
String clientId = getClientId(context);
if("".equals(id) || id == null){
id = clientId;
}
Object styleClass = (getAttributes().get("styleClass") != null) ? (Boolean)getAttributes().get("styleClass") : "";
writer.startElement("li", this);
if(active){
style.append(" active ");
}
if(!"".equals(styleClass)){
style.append(styleClass);
}
writer.writeAttribute("id", id, null);
writer.writeAttribute("class", style.toString().trim(), null);
writer.startElement("a", this);
writer.writeAttribute("href", href, null);
if(!"".equals(alt)) { writer.writeAttribute("alt", alt, null); }
if(!"".equals(hreflang)) { writer.writeAttribute("hreflang", hreflang, null); }
System.out.println("rel = " + rel);
if(!"".equals(rel)) { writer.writeAttribute("rel", rel, null); }
if(!"".equals(target)) { writer.writeAttribute("target", target, null); }
if(!"".equals(download)) { writer.writeAttribute("download", download, null); }
if(!"".equals(media)) { writer.writeAttribute("media", media, null); }
if(!"".equals(type)) { writer.writeAttribute("type", type, null); }
for (UIComponent child : getChildren()) {
child.encodeAll(context);
}
}
#Override
public Object saveState(FacesContext context) {
Object values[] = new Object[10];
values[0] = super.saveState(context);
values[1] = id;
values[2] = style;
values[3] = active;
values[4] = alt;
values[5] = href;
values[6] = hreflang;
values[7] = rel;
values[8] = target;
values[9] = download;
values[10] = media;
values[110] = type;
return ((Object) (values));
}
#Override
public void restoreState(FacesContext context, Object state) {
Object values[] = (Object[])state;
super.restoreState(context, values[0]);
id = (String)values[1];
style.insert(0, values[2]);
active = (Boolean)values[3];
alt = (String)values[4];
href = (String)values[5];
hreflang = (String)values[6];
rel = (String)values[7];
target = (String)values[8];
download = (String)values[9];
media = (String)values[10];
type = (String)values[11];
}
}