How to handle blank dates sent as parameters to Servlet - java

I'm writing a webapp where there are dates to be sent to a Servlet and I want to send some blank dates and based on these dates I want to build a query. But here My problem is when I pass the parameters i.e. the dates it's working fine, And when I send blank parameters it is throwing me the below error.
Start date got is and end date is //Here I'm checking the output
Unparseable date: "" servlet Errotr
When I give in the dates it shows in console as
Start date got is (TheStartDateValue) and end date is (TheEndDateValue)
and there is no exception (since the dates are parsed). And below is my code.
public class Controller extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
try {
/* Date Start */
String startDateStr = request.getParameter("startDate");
String endDateStr = request.getParameter("endDate");
System.out.println("Start date got is " + startDateStr + " and end date is " + endDateStr);
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
SimpleDateFormat print = new SimpleDateFormat("yyyy-MM-dd");
Date startParsedDate = null, endParsedDate = null;
String startDate = null, endDate = null;
if (!startDateStr.equals(null) || !startDateStr.equals("")) {
startParsedDate = sdf.parse(startDateStr);
startDate = print.format(startParsedDate);
}
if (!endDateStr.equals(null) || !endDateStr.equals("")) {
endParsedDate = sdf.parse(endDateStr);
endDate = print.format(endParsedDate);
}
System.out.println(startDate + " value and " + endDate);
/* Date End */
DataDao dataDao = new DataDao();
ArrayList<UserBean> list = dataDao.getFrameWork(startDate, endDate);
String searchList = new Gson().toJson(list);
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
response.getWriter().write(searchList);
System.out.println("servlet Done");
} catch (Exception e) {
System.err.println(e.getMessage() + " servlet Errotr");
}
}
I'm trying to handle the startDateStr and startDateStrto chweck if the input values are null or having some value using the below block in my above code.
if (!startDateStr.equals(null) || !startDateStr.equals("")) {
startParsedDate = sdf.parse(startDateStr);
startDate = print.format(startParsedDate);
}
if (!endDateStr.equals(null) || !endDateStr.equals("")) {
endParsedDate = sdf.parse(endDateStr);
endDate = print.format(endParsedDate);
}
Please let me know where am I going wrong and how can I fix this.
Thanks

Problem is in condition !startDateStr.equals(null) || !startDateStr.equals(""), you should change it to startDateStr != null && !startDateStr.equals("") and the same problem is in second condition.

Related

unable to redirect response in rest controller

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}")

Command manager procedure in MicroStrategy not converting to date

I am running below command manager procedure in Microstrategy but it does not convert the string into date, tried lot of options. Can someone please assist?
*********** PROCEDURE***************************************
String sQuery = "LIST ALL SUBSCRIPTIONS FOR SCHEDULE \"" + sScheduleName + "\" FOR PROJECT \"" + projectName + "\";";
ResultSet oSubs=executeCapture(sQuery);
oSubs.moveFirst();
while(!oSubs.isEof()){
String sSubsName = oSubs.getFieldValueString(DisplayPropertyEnum.GUID);
ResultSet RecList = executeCapture("LIST ALL PROPERTIES FOR SUBSCRIPTION GUID " +sSubsName+ " FOR PROJECT \"projectname\";");
RecList.moveFirst();
while(!RecList.isEof()){
ResultSet oResultSetSubProps = (ResultSet)RecList.getResultCell(SUBSCRIPTION_RESULT_SET).getValue();
oResultSetSubProps.moveFirst();
while(!oResultSetSubProps.isEof())
{
String d1 = oResultSetSubProps.getFieldValueString(DisplayPropertyEnum.EXPIRATIONDATE);
// the below few lines in red return nothing, its unable to convert to Date as it is unable to recognize the Expiration date in the String format.
java.text.SimpleDateFormat formatter = new java.text.SimpleDateFormat("M/dd/yyyy");
String dateInString = d1;
Date date = formatter.parse(dateInString);
printOut(formatter.format(date));
oResultSetSubProps.moveNext();
}
RecList.moveNext();
}
oSubs.moveNext();
}
This worked for me. The string was neither empty, nor null and no even blank but it would still not parse it so i had to use the length of the string.
java.text.DateFormat formatter = new java.text.SimpleDateFormat("M/d/yyyy",Locale.US);
String dateInString = d1;
if(d1.trim().length()>0)
{
Date date = formatter.parse(dateInString);
if(todaydate.compareTo(date)>0)
{
printOut(name+";"+formatter.format(date));
}
}
if(d1.contains("/"))
{
Date EDate=new Date(d1);
Date today= new Date();
if(d1.compareTo(today)<0)
{
printOut("Expired");
}
}
else
{
printOut("Active");
}
//blank or null values can be handled in Else condition instead.. Hope it helps..

Avoiding a particular check for YYYY-MM--dd format in date

I have below method in which different date patterns have been handled
below is the method in which different date formats have been handled now
now for the particulat format YYYY-MM-dd i don't want it to go for the check where we are prefixing 20 before in code please advise how can i skip that part lets say if the date pattern is YYYY-MM-dd then avoid the logic of prefixing 20 in front of year
below is my code
public java.util.Date extractDate(String dateStr, String dateType) {
String[] datePatternsOfUk = { "d-M-yy", "d-M-yyyy", "d/M/yy", "d/M/yyyy", "yyyy-MM-dd","dd-MM-yy", "dd-MMM-yy","dd-MMM-yyyy","dd-MM-yyyy",
"dd/MM/yy","dd/MMM/yy","dd/MMM/yyyy"};
String[] datePatternsOfUs = { "M-d-yy","MM-dd-yy","M/d/yy","MM/dd/yy", "MM/dd/yy", "MMM-dd-yy",
"MMM/dd/yy", "MMM-dd-yyyy", "MM-dd-yyyy", "MMM/dd/yyyy",
"MM/dd/yyyy" };
java.util.Date date = null;
String[] datePatterns = datePatternsOfUk;
if (dateType.equals("US")) {
datePatterns = datePatternsOfUs;
} else if (dateType.equals("UK")) {
datePatterns = datePatternsOfUk;
}
///******code should not go in this check where date pattern is YYYY-MM-dd
int p = dateStr.lastIndexOf("/");
if (p == -1) {
p = dateStr.lastIndexOf("-");
}
String firstSubstring = dateStr.substring(0, p + 1);
String secondSubstring = dateStr.substring(p + 1);
if (p != -1 && secondSubstring.length() <= 2) {
secondSubstring = Integer.toString(2000 + Integer.parseInt(secondSubstring));
dateStr = firstSubstring + secondSubstring;
}
///****************************************//
try {
date = DateUtils.parseDate(dateStr, datePatterns);
} catch (ParseException ex) {
logger.error("##$$$$$### Error in invoice inside extractDate method : ##$$$$$$#### "
+ ErrorUtility.getStackTraceForException(ex));
}
return date;
}
You could avoid trying any inappropriate pattern by checking if the string "looks like" the pattern before parsing with the pattern.
The general way to do this is:
String datePattern = "yyyy-MM-dd"; // for example
String input;
if (input.matches(datePattern.replaceAll("\\w", "\\d"))) {
// the input looks like the pattern
// in this example "dddd-dd-dd" where "d" is any digit
// so go ahead and try the parse
}
You can enhance this logic to add:
if (input.matches("\\d\\d\\D.*")) {
// then it only has a two digit year, so add "20" to the front
}
if (!dateStr.equals("YYYY-MM-dd")) {
// code
}

Function works inside Main method but doesn't work in another class

I am facing this weird issue. I have written following function which fetches tweets of a user between specified dates:
List<Tweet> tweetlist = TweetManager.getTweets("arynewsofficial", fromdate, todate, null);
The function works absolutely fine inside main method and returns collection of tweets. However, when I add this line of code in another function inside some other class, application doesnt return anything. Rather, it hangs. Here is my class in which I have added my function:
public class NewsCollector {
public List<String> collectTweets(String stockdate[], int noofpastimpacts)
throws IOException
{
try
{
int year= Integer.parseInt(stockdate[0]);
int month= Integer.parseInt(stockdate[1]);
int day= Integer.parseInt(stockdate[2]);
List<String> tweetstext = new ArrayList<String>();
LocalDate currentdate = LocalDate.of(year, month, day);
LocalDate datefromdate = currentdate.minusDays(noofpastimpacts+1);
String fromdate= datefromdate.getYear()+ "-" +
datefromdate.getMonthValue() + "-" +
datefromdate.getDayOfMonth();
LocalDate datetodate = datefromdate.plusDays(noofpastimpacts);
String todate = datetodate.getYear() + "-" +
datetodate.getMonthValue() + "-" +
datetodate.getDayOfMonth();
List<Tweet> tweetlist =
TweetManager.getTweets("arynewsofficial", fromdate, todate, null);
List<String[]> data = new ArrayList<String[]>();
data.add(new String[] {"Text", "Date","Sentiment"});
for(Tweet tweety: tweetlist)
{
data.add(new String[] { tweety.getText(),
tweety.getDate().toString(),
"0"});
tweetstext.add(tweety.getText());
}
String csv = "D:/Tweets/"+fromdate+".csv";
CSVWriter writer = new CSVWriter(new FileWriter(csv));
writer.writeAll(data);
writer.close();
System.out.print("Total Tweets Retreived: "+tweetlist.size() );
return tweetstext;
}
catch(Exception e)
{
System.out.println(e.getMessage());
return null;
}
}
}
Is NewsCollector supposed to be used as an object? It doesn't look like that, so you may want to make your method static.

Validating a Date in Java exactly like Oracle does in TO_DATE()

I have to Validate a date in Java to check if it is in correct format and correct value.
If I use SimpleDateformat Class, it will make wrong date valid as well because if a month is given as 14 it will add 1 year to the Year part.
However in Oracle it will indivisually check if Month , Date , Hour , Minute etc is correct.
E.g. in Oracle
TO_DATE(20141511 , 'YYYYMMDD')
will give error that the MONTH i.e. 15 is incorrect
But in Java
Date d = "YYYYMMDD".parse("20141511");
will be valid because it will count it as 2015+3 months.
So, how can I validate a date in Java exactly like Oracle does in its TO_DATE function?
If I understand your question, you could use DateFormat.setLenient(false). Per the JavaDoc,
Specify whether or not date/time parsing is to be lenient ... With strict parsing, inputs must match this object's format.
DateFormat df = new SimpleDateFormat("yyyyMMdd");
df.setLenient(false);
try {
Date d = df.parse("20141511");
} catch (ParseException e) {
e.printStackTrace();
}
Does not allow the invalid date to parse and throws
java.text.ParseException: Unparseable date: "20141511"
None of these solutions account Oracle settings for the date format. A more global solution using oracle.sql.Date and exceptions:
import java.sql.SQLException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import oracle.sql.DATE;
public void validateDate (String dateString, String nlsDateFormat, String nlsDateLanguage) throws ParseException, SQLException {
if (dateString == null) {
throw new ParseException("Date parameter not entered.", 0);
} else {
try {
DATE.fromText(dateString, nlsDateFormat, nlsDateLanguage); //not implemented in every ojdbc driver, works with ojbdbc6.jar
} catch (SQLException e) {
if (!e.getMessage().contains("Unimplemented")) {
throw new SQLException (e);
}
}
}
}
(I discovered some drivers couldn't even handle this.. so validation is bypassed if oracle.sql.DATE is not implemented)/ To get session variables for NLS_FORMAT and NLS_LANGUAGE:
private String getDateNlsFmt() throws SQLException {
String nlsDateFormat;
String sqlStmt =
"SELECT value nlsDateFormat "
+ " FROM nls_session_parameters "
+ " WHERE parameter = 'NLS_DATE_FORMAT' ";
QueryStatement q = new QueryStatement(conn, sqlStmt);
q.open();
if (!q.eof()) {
nlsDateFormat = q.getString("nlsDateFormat");
}
q.close();
return nlsDateFormat;
}
private String getDateNlsLang() throws SQLException {
String nlsDateLanguage;
String sqlStmt =
"SELECT value nlsDateLanguage "
+ " FROM nls_session_parameters "
+ " WHERE parameter = 'NLS_DATE_LANGUAGE' ";
QueryStatement q = new QueryStatement(conn, sqlStmt);
q.open();
if (!q.eof()) {
nlsDateLanguage = q.getString("nlsDateLanguage");
}
q.close();
return nlsDateLanguage;
}

Categories