There have been many posts that covers this topic but however I adjust them to my code I could not find a suitable answer.
try (BufferedReader br = new BufferedReader(new FileReader(path));)
{
String line = "";
Person tempPerson = null;
String dateFormat = "dd-MM-yyyy";
SimpleDateFormat sdf = new SimpleDateFormat(dateFormat);
Date tempBirthdayDate = null;
while ((line = br.readLine()) != null)
{
String[] splitFormat = line.split("/");
for (String s : splitFormat)
{
String[] datamember = s.split(", ");
//Some more stuff...
tempBirthdayDate = sdf.parse(datamember[3]);
sdf.format(tempBirthdayDate);
sdf.applyPattern(dateFormat);
//Some more stuff...
}
tempPerson = new Person(...,...,...,tempBirthdayDate,...,...);
}
}
Person.java copy constructor:
public Person(..., ..., ..., Date birthdayDate, ..., ...)
{
this.xxx = ...;
this.xxx = ...;
this.xxx = ...;
this.birthdayDate = birthdayDate;
this.xxx = adresse;
this.xxx = ...;
}
Those "..." are just place holders to shorten the code. In the source file (.txt) the date is in the same format I defined up there. But as soon as I call the toString()-Method on the birthdayDate I get following result for e.g. 05/26/1993:
Wed May 26 00:00:00 CEST 1993. Thank you for helping!
the toString method of a Date object is not affected by SimpleDateFormat you initialized.
You need to create a custom class extending Date and override the toString method
public class CustomDate extends Date {
......
#Override
public String toString(){
return new SimpleDateFormat("dd-MM-yyyy").format(this);
}
}
In Person constructor
public Person(..., ..., ..., CustomDate birthdayDate, ..., ...)
{
this.xxx = ...;
this.xxx = ...;
this.xxx = ...;
this.birthdayDate = birthdayDate;
this.xxx = adresse;
this.xxx = ...;
}
you can now call toString on birthdayDate and get the format you want
Related
I am trying to check if 'toDate' lies within the range , for that i tried 2 approaches but both haven't worked for me
approach 1:
if (MyEntity.getFromDate() != null
&& MyEntity.getToDate() != null)) {
predicate.getExpressions()
.add(criteriaBuilder.between((root.<Date>get("toDate")), MyEntity.getFromDate(),MyEntity.getToDate()));
approach 2
if(MyEntity.getFromDate() != null
&& MyEntity.getToDate() != null) {
DateFormat dateFormat = new SimpleDateFormat(Constants.DBDATEFORMAT);
String fromDateInString = dateFormat.format(MyEntity.getFromDate());
String toDateInString = dateFormat.format(MyEntity.getToDate());
String[] fromDateSplitation = fromDateInString.split(" ");
String[] toDateSplitation = toDateInString.split(" ");
StringBuilder startLimit = new StringBuilder();
StringBuilder endLimit = new StringBuilder();
startLimit.append(fromDateSplitation[0]).append(" ").append("00:00:00");
endLimit.append(toDateSplitation[0]).append(" ").append("23:59:59");
Date fromDate;
try {
fromDate = dateFormat.parse(startLimit.toString());
Date toDate = dateFormat.parse(endLimit.toString());
MyEntity.setFromDate(fromDate);
MyEntity.setToDate(toDate);
predicate.getExpressions().add(criteriaBuilder.between(root.get("toDate"),
MyEntity.getFromDate(), MyEntity.getToDate()));
} catch (ParseException e) {
e.printStackTrace();
}
Can anyone tell me how to properly use Between and Equal for date with criteria builder ?
I've always used your first approach, but not specifying the generic on the Path. Could you maybe try:
.add(criteriaBuilder.between(root.get("toDate"),
MyEntity.getFromDate(),MyEntity.getToDate()));
and most importantly, are you certain that the toDate field of your Entity is Annotated with #Temporal(TemporalType.TIMESTAMP)
I made two RestController apis. On response of second api I wanted first api's response (which is a json response), so I tried to use HttpServletResponse.redirect. I also set required content type to it. But on second api response I got Unsupported Media Type Content type 'null' not supported.
first API
#GetMapping(value="checkStatus/{msisdn}",consumes=MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<CoreResponseHandler> fetchOcsByDate2(#PathVariable(value="msisdn",required=true)String msisdn){
long l_time_start = System.currentTimeMillis();
List<Object[]> list = repository.getSingleCallDetail(msisdn);
if(list==null || list.size()==0) {
System.out.println("NO RECORD FOUND");
}
JSONObject objMain = new JSONObject();
for(Object[] objArr: list) {
JSONObject obj = new JSONObject();
String msisdn_ = objArr[0]==null?null:objArr[0].toString();
String songId = objArr[1]==null?null:objArr[1].toString();
String songName = objArr[2]==null?null:objArr[2].toString();
String status = objArr[3]==null?null:objArr[3].toString();
String lang = objArr[4]==null?null:objArr[4].toString();
String startDate = objArr[5]==null?null:objArr[5].toString();
objMain.put("status", status);
objMain.put("language", lang);
obj.put("id", songId);
obj.put("msisdn", msisdn);
obj.put("songName", songName);
objMain.put("subscription", obj);
}
long l_time_end = System.currentTimeMillis();
long l_diff = l_time_end-l_time_start;
if(list!=null && list.size()>0) {
return new ResponseEntity<CoreResponseHandler>(new SuccessResponseBeanRefined(HttpStatus.OK, ResponseStatusEnum.SUCCESSFUL, ApplicationResponse.SUCCESSFUL, objMain,l_diff+" ms"),HttpStatus.OK);
}
if(list==null || list.size()==0) {
return new ResponseEntity<CoreResponseHandler>(new SuccessResponseBeanRefined(HttpStatus.NOT_FOUND, ResponseStatusEnum.FAILED, ApplicationResponse.Failed, "not found",l_diff+" ms"),HttpStatus.NOT_FOUND);
}
return new ResponseEntity<CoreResponseHandler>(new SuccessResponseBeanRefined(HttpStatus.BAD_REQUEST, ResponseStatusEnum.FAILED, ApplicationResponse.Failed," > Bad request",l_diff+" ms"),HttpStatus.BAD_REQUEST);
}
no problem in output. ran smooth
second API
#GetMapping(value="verifyOtp/{msisdn}/{otp}",consumes=MediaType.APPLICATION_JSON_VALUE)
public void verifyOtp(#PathVariable(value="msisdn",required=true)String msisdn,
#PathVariable(value="otp",required=true)String otp,HttpServletResponse response) throws Exception{
long l_time_start = System.currentTimeMillis();
long l_time_end = System.currentTimeMillis();
long l_diff = l_time_end-l_time_start;
List<Object[]> list = repository.verifyOtp(msisdn,otp);
SimpleDateFormat sdf = new SimpleDateFormat("YYYY-MM-dd HH:mm:ss");
if(list!=null && list.size()>0) {
for(Object[] obj:list) {
String strDate = obj[3]==null?null:obj[3].toString();
Date dtDb = sdf.parse(strDate);
Date dtNow = new Date();
String strDtNow = sdf.format(dtNow);
dtNow = sdf.parse(strDtNow);
long ldtDb = dtDb.getTime();
long ldtNow = dtNow.getTime();
if(ldtDb>ldtNow) {
System.out.println("success within time");
int ii = repository.updateIsActive(msisdn);
response.setContentType("application/json");
response.sendRedirect("http://localhost:9393/crbt/api/subscriber/ivr/checkStatus/"+msisdn);
}
else {
System.out.println("failure time over!");
}
}
}
else {
}
}
second Api Response in postman
What I expected was first API's response. But its giving me some 415 content type error
How can I get first API's success json response from second api's response.. I even tried org.springframework.http.HttpHeaders but couldn't get desired output. What changes I had to do in order to get first Api's response in my second api response.
I have a strange feeling answering your questions, because I dislike the solution I'll provided. But it might help, so I'll give a try.
Basically, your Controller are just Spring beans, which means you can do is having a dependency, and second controller will call first controller. This will also change your method verifyOtp to make it change the return type.
Something like that:
...
#Autowired
private FirstController firstController;
...
#GetMapping(value="verifyOtp/{msisdn}/{otp}",consumes=MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<CoreResponseHandler> verifyOtp(#PathVariable(value="msisdn",required=true)String msisdn,
#PathVariable(value="otp",required=true)String otp,HttpServletResponse response) throws Exception{
long l_time_start = System.currentTimeMillis();
long l_time_end = System.currentTimeMillis();
long l_diff = l_time_end-l_time_start;
List<Object[]> list = repository.verifyOtp(msisdn,otp);
SimpleDateFormat sdf = new SimpleDateFormat("YYYY-MM-dd HH:mm:ss");
if(list!=null && list.size()>0) {
for(Object[] obj:list) {
String strDate = obj[3]==null?null:obj[3].toString();
Date dtDb = sdf.parse(strDate);
Date dtNow = new Date();
String strDtNow = sdf.format(dtNow);
dtNow = sdf.parse(strDtNow);
long ldtDb = dtDb.getTime();
long ldtNow = dtNow.getTime();
if(ldtDb>ldtNow) {
System.out.println("success within time");
int ii = repository.updateIsActive(msisdn);
return firstController.fetchOcsByDate2(msidn);
}
else {
System.out.println("failure time over!");
return null;
}
}
}
else {
return null;
}
}
I think you are trying to achieve something uncommon, and to avoid having this dependency between controller, consider:
Change your use case. Make the second controller returning a HttpStatus.OK, and make the client do the next call to the first controller
Create a service in charge of loading the msidn, which will avoid duplicate code, and keep you in a more standard position to make our evolutions.
The issue occurred due to GetMapping .
#GetMapping(value="checkStatus/{msisdn}",consumes=MediaType.APPLICATION_JSON_VALUE)
replace with below in first Api:
#GetMapping(value="checkStatus/{msisdn}")
Assume that I have a data input like this:
018492114,51863406,X0,1,20160218
018529816,51864472,X0,1,20150603
018543434,51864629,X0,1,20150702
018543464,51864990,N5+,1,2015063
018530309,51865142,X0,1,20150603
I want only to convert the 5 column's element to Date format because it was imported as a string. And I want to do a sorting operation by DA_PRM_CTR_ORDER variable (the end column).
Note that I am using arraylist object defined as Personne and I am using Comparable interface to use Comparable method for sorting:
this is my class personne which includes the needed object:
public class Personne implements Comparable {
private String IDC_PSE_PCL;
private String IDC_CD_NOT;
private String CD_NOTE;
private String IDT_ETT_PSE;
private String DA_PRM_CTR_ORDER;
public Personne(String IDC_PSE_PCL, String IDC_CD_NOT,
String DA_PRM_CTR_ORDER, String IDT_ETT_PSE, String CD_NOTE) {
this.IDC_PSE_PCL = IDC_PSE_PCL;
this.IDC_CD_NOT = IDC_CD_NOT;
this.IDT_ETT_PSE = IDT_ETT_PSE;
this.CD_NOTE = CD_NOTE;
this.DA_PRM_CTR_ORDER = DA_PRM_CTR_ORDER;
}
public String getIDC_CD_NOT() {
return this.IDC_CD_NOT;
}
public String getIDC_PSE_PCL() {
return this.IDC_PSE_PCL;
}
public String getDA_PRM_CTR_ORDER() {
return this.DA_PRM_CTR_ORDER;
}
public String getIDT_ETT_PSE() {
return this.IDT_ETT_PSE;
}
public String getCD_NOTE() {
return this.CD_NOTE;
}
#Override
public int compareTo(Object o) {
Personne other = (Personne) o;
DateFormat df = new SimpleDateFormat("yyyyMMdd");
Date converted = (Date) df.parse(other.getDA_PRM_CTR_ORDER());
int res = this.DA_PRM_CTR_ORDER.compareTo(converted);
// Si Egalite des dates
if (res == 0) {
res = IDT_ETT_PSE.compareTo(other.getIDT_ETT_PSE());
}
return res;
}
My problem is in the line:
int res = this.DA_PRM_CTR_ORDER.compareTo(converted);
when I want to sort by DA_PRM_CTR_ORDER values but it show me this problem:
The method compareTo(String) in the type String is not applicable for
the arguments (Date)
How can I resolve this issue please?
A quick fix could be to parse this.DA_PRM_CTR_ORDER to Date too. So the line you highlighted would look like:
int res = df.parse(this.DA_PRM_CTR_ORDER).compareTo(converted);
you should use Date.compareTo(Date) instead of String.compareTo(Date).
suggestion:
Long currentDate = Long.parseLong(this.DA_PRM_CTR_ORDER);
return currentDate.compareTo(Long.parseLong(other.getDA_PRM_CTR_ORDER()));
It would be better if you compare the timestamp of two dates to compare.
Date self = (Date) df.parse(this.getDA_PRM_CTR_ORDER());
String ConvertedTs = String.valueOf(converted.getTime());
String selfTs = String.valueOf(self.getTime());
int res = selfTs.compareTo(ConvertedTs);
How to parse two different objects from the same json file knowing that parsing one of them block parsing the other, which means that i have to parse only one of them, this is my code:
try {
time = json1.getJSONObject(TAG_TIME);
String Time2 = time.toString();
deals = json1.getJSONObject(TAG_DEALS);
final String plusinfo = deals.getString(TAG_PLUS_INFO);
String title = deals.getString(TAG_TITLE);
Integer retail = deals.getInt(TAG_RETAIL);
String nretail = Integer.toString(retail);
Integer deal = deals.getInt(TAG_DEAL);
String ndeal = Integer.toString(deal);
String duration = deals.getString(TAG_DURATION);
String image = deals.getString(TAG_IMAGE_URL);
String participant = deals.getString(TAG_PARTICIPANT);
final String details = deals.getString(TAG_DETAILS);
final String name = deals.getString(TAG_ADVERTISER_NAME);
final String adress = deals.getString(TAG_ADVERTISER_ADDRESS);
final String phone = deals.getString(TAG_ADVERTISSER_PHONE);
/*String Time1 = deals.getString(TAG_DATE);
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date1 = new GregorianCalendar(0,0,0).getTime();
Date date2 = new GregorianCalendar(0,0,0).getTime();
try {
date1 = sdf.parse(Time1);
date2 = sdf.parse(Time2);
} catch (ParseException e) {
e.printStackTrace();
}
final String precision = deals.getString(TAG_PRECISION);
JSONArray c = deals.getJSONArray(TAG_PRECISION);
ArrayList<String> arrays = new ArrayList<String>();
for(int i = 0; i < c.length(); i++){
precision = c.getString(i);
arrays.add(precision);
}
HashMap<String, String> map = new HashMap<String, String>();
map.put(TAG_TITLE, title);
map.put(TAG_RETAIL, nretail);
map.put(TAG_DEAL, ndeal);
map.put(TAG_DURATION, duration);
map.put(TAG_IMAGE_URL, image);
map.put(TAG_PARTICIPANT, participant);
map.put(TAG_SERVER_TIME, Time2);
otherdeals.add(map);
What do you mean it gets blocked? I dont see what the issue is with what you have posted. If you wish to parse two different JSON responses, either kick off two background threads (AsyncTask) or just parse them one after the other
I am writing a credit card program. I want the program to use the current date every time the method is used to make a purchase and put the date into the array
private GregorianCalendar transDate;
public CreditCard(double amount,String storeName, GregorianCalendar transDate) {
this.amount=amount;
this.storeName=storeName;
transDate=new GregorianCalendar();
}
public void purchase(double amount, String storeName, GregorianCalendar date)throws Exception
{
if (numPurchases<purchases.length)
if (amount >0 )
if(amount+balance<=creditLimit)
if( GregorianCalendar.getInstance().getTimeInMillis()<=expDate.getTimeInMillis())
{
balance+=amount;
transDate=getTransDate();
purchases[numPurchases] = new CreditCard(amount, storeName,transDate);
numPurchases++;
}
else
{
throw new Exception("card expired");
}
else{
throw new Exception("insufficient credit");
}
else{
throw new Exception("invalid amount");
}
else{
throw new Exception("exceeded number of allowed purchases");
}
}
I would like to display the information in String info
info+="Purchases:\n";
for(int index=0;index<numPurchases;index++){
info+="["+(index+1)+"] ";
info+=transDate.get(Calendar.YEAR)+"\t";
info+= purchases[index].getStoreName()+"\t";
info+=(formatter.format(purchases[index].getPurchase()))+"\n" ;
}
how do I need to set up the code to use the current date and add it to the array and display it in the string
Why don't you use a List implementation instead of an array? You can override the toString method to print it the way you want.
final SimpleDateFormat formatter = new SimpleDateFormat("dd MM yyyy");
List<Calendar> dates = new ArrayList<Calendar>() {
private static final long serialVersionUID = -5079502477457556887L;
#Override
public String toString() {
Iterator<Calendar> i = iterator();
if (!i.hasNext())
return "[]";
StringBuilder sb = new StringBuilder();
sb.append('[');
for (;;) {
Calendar c = i.next();
sb.append(formatter.format(c.getTime()));
if (! i.hasNext())
return sb.append(']').toString();
sb.append(", ");
}
}
};
dates.add(Calendar.getInstance());
dates.add(Calendar.getInstance());
System.out.println(dates);
What does your getTransDate() function do? Ideally it should return the transDate variable of CreditCard object. To calculate transDate for a purchase, you are better off renaming the method to calculateTransDate() or something like that.
Once you have getTransDate() method returning the transDate, your info string can be :
info+="Purchases:\n";
for(int index=0;index<numPurchases;index++){
info+="["+(index+1)+"] ";
info+=purchases[index].getTransDate().get(Calendar.YEAR)+"\t";
info+= purchases[index].getStoreName()+"\t";
info+=(formatter.format(purchases[index].getPurchase()))+"\n"
}