time download can't convert to GMT timing - java

my concept for download file is as below:
if the adapter restart at 7.00am,
first time download will be starting from 00:00:00 until 7am..
after 5 minute will download again, so is the download timing will be 6.58am to 7.05am.
Timezome will be different, like Asia/Singapore,Asia/Hong_Kong etc..
but this timezone need convert to GMT for some purpose.
the below is my coding
private String TIME_ZONE_ID = "America/New_York";
private final String TIME_ZONE_ID_TRKD_DEFAULT = "Etc/GMT";
public void run() {
// TODO Auto-generated method stub
if (sessionFactory.fileServer == null)
throw new NullPointerException("sessionfactory.fileServer is null");
// hsding#debug
out.println("d> 2.1");
while (true && isStarted) {
try {
if (!isConnected) {
out.println("d> 2.2");
openTransport(); // Connect
}// end if
} catch (Exception e) {
e.printStackTrace();
out.println(expMsg + " run():" + e.getMessage());
}
try {
boolean isValid = getTokenValidity();
if (isConnected) {
// boolean isValid = getTokenValidity();
out.println("Is Token Valid = [" + isValid + "]");
if (isValid) {
try {
for (int i = 0; i < garrNewsFilterCriteria.length; i++) {
giCurrSubscribeSeqNo = i;
// add in keep track of last download time. hsding#debug#2016041x
if (garrLastNewsSubscribeStartTime[i] == null) {
out.println("garrLastNewsSubscribeStartTime= " + garrLastNewsSubscribeStartTime[i]);
garrLastNewsSubscribeStartTime[i] = getStartDateTime(true);
} else {
out.println("garrLastNewsSubscribeStartTime2= " + garrLastNewsSubscribeStartTime[i]);
garrLastNewsSubscribeStartTime[i] = getStartDateTime();
}
} catch (Exception e) {
e.printStackTrace();
}
try {
Thread.sleep(SLEEP_TIME);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} else {
out.println("Token not valid!!!");
isConnected = false;
}
} else
isConnected = false;
} catch (Exception e) {
e.printStackTrace();
// TODO Auto-generated catch block
out.println(expMsg + " run():" + e.getMessage());
}
}
}
private XMLGregorianCalendar getStartDateTime() {
return getStartDateTime(false);
}
private XMLGregorianCalendar getStartDateTime(boolean startFromZeroHour) {
XMLGregorianCalendar xmlCal = null;
try {
xmlCal = DatatypeFactory.newInstance().newXMLGregorianCalendar();
} catch (DatatypeConfigurationException e) {
e.printStackTrace();
}
// hsding#debug#20160419. enhance on the retrieve time FROM and TO.
// Calendar c = new GregorianCalendar(TimeZone.getTimeZone("Canada/Eastern"));
Calendar now = Calendar.getInstance(TimeZone.getTimeZone("Asia/Singapore"));
out.println("D> now 0=" + now);
if (startFromZeroHour) {
// ??????
now.set(Calendar.HOUR_OF_DAY, 0);
now.set(Calendar.MINUTE, 0);
now.set(Calendar.SECOND, 0);
} else {
now.set(Calendar.SECOND, 0); // pre offset the second to zero for easy the polling job in future.
int fallback_prev_N_second = (int) (SLEEP_TIME * 2) / 1000 * -1;
now.add(Calendar.SECOND, fallback_prev_N_second);
}
out.println("D> now 1=" + now);
now.setTimeZone(TimeZone.getTimeZone(TIME_ZONE_ID_TRKD_DEFAULT));
// hsding#debug#2016041x
out.println("D> now 2=" + now);
xmlCal.setDay(now.get(Calendar.DAY_OF_MONTH));
xmlCal.setMonth(now.get(Calendar.MONTH) + 1);
xmlCal.setYear(now.get(Calendar.YEAR));
xmlCal.setTime(now.get(Calendar.HOUR_OF_DAY), now.get(Calendar.MINUTE), now.get(Calendar.SECOND));
out.println("D> xmlCal=" + xmlCal);
}
private XMLGregorianCalendar getEndDateTime() {
XMLGregorianCalendar xmlCal = null;
int iDay = 0;
int iMonth = 0;
try {
xmlCal = DatatypeFactory.newInstance().newXMLGregorianCalendar();
} catch (DatatypeConfigurationException e) {
e.printStackTrace();
}
now.get(Calendar.MINUTE), now.get(Calendar.SECOND));
// out.println("News Retrieve [End Time] =" + xmlCal.toGregorianCalendar().getTime());
// hsding#debug#20160419. enhance on the retrieve time FROM and TO.
// Calendar c = new GregorianCalendar(TimeZone.getTimeZone("Canada/Eastern"));
Calendar now = Calendar.getInstance(TimeZone.getTimeZone("Asia/Singapore"));
out.println("D> End time =" + now);
now.setTimeZone(TimeZone.getTimeZone(TIME_ZONE_ID_TRKD_DEFAULT));
out.println("D> End time2 =" + now);
xmlCal.setDay(now.get(Calendar.DAY_OF_MONTH));
// xmlCal.setDay(12);
// We do a +1 below because XMLGregorianCalendar goes from 1 to 12
// while Calendar.MONTH goes from 0 to 11 !!!
xmlCal.setMonth(now.get(Calendar.MONTH) + 1);
// xmlCal.setMonth(1);
xmlCal.setYear(now.get(Calendar.YEAR));
xmlCal.setTime(now.get(Calendar.HOUR), now.get(Calendar.MINUTE), 59);
out.println("D> End time xmlcal =" + xmlCal);
return xmlCal;
}
private void getNewsHeaderFromReuters(String sParam01, String sParam02, XMLGregorianCalendar xmlParam03) throws Exception {
try{
RetrieveHeadlineMLRequest1 headlineRequest = new RetrieveHeadlineMLRequest1();
NewsRequest newsRequest = new NewsRequest();
Filter filter = new Filter();
MetaDataConstraint constraint = new MetaDataConstraint();
newsRequest.setStartTime(xmlParam03);
newsRequest.setEndTime(getEndDateTime());
out.println("News Retrieve [START Time]=" + newsRequest.getStartTime());
out.println("News Retrieve [END Time]=" + newsRequest.getEndTime());
headlineRequest.setHeadlineMLRequest(newsRequest);
RetrieveHeadlineMLResponse1 headlineResponse;
int i = 0;
try {
String sNewsID = "";
boolean isProcess = true;
headlineResponse = newsPort.retrieveHeadlineML1(headlineRequest);
out.println("SOAP request : " + messageDumper.nextMessage());
out.println("SOAP response : " + messageDumper.nextMessage());
} catch (Exception e) {
e.printStackTrace();
out.println(expMsg + " getNewsHeaderFromReuters()" + e.getMessage());
isConnected = false;
throw new Exception(e.getMessage());
}
}
i use example for present my problem:
When the adapter restart on 2017-02-18 7am on Singapore timing, After convert to GMT Start time is 2017-02-18 00:00:00, but end time is 2017-02-17 11:50:34.
this is wrong de..
When the adapter restart after 2017-02-18 8 am on Singapore timing, After convert to GMT Start time is 2017-02-18 00:00:00, but end time is 2017-02-18 00:05:34( up to the timing convert to GMT). but it is correct..
if i no convert to GMT, all timing is correct , but i don't wan this answer cause it will affected some data, so it need convert to GMT first.
Please kindly advice what wrong for my coding...
Thanks
Regards
Sharon

Related

Thread automatically stop (freeze) in Eclipse

I am running a thread in eclipse to get data from mysql server. Thread works fine. The problem is after bit of time thread stop running(withing 6 to 8 hours). Thread get freeze. After that I have to manually close and re-run the program. Eclipse runs in a windows server 2012 r2 machine. No error or exception is shown.
Main class.
public class Main {
private final static int fONE_DAY = 1;
private final static int fZERO_MINUTES = 0;
public static void main(String[] argv) {
Timer timer1 = new Timer();
Timer timer4 = new Timer();
try {
timer1.scheduleAtFixedRate(new CearteSDQuatation(),500 , 1000*60*4);// 4min
System.out.println("timer 1 : createSDQuotation");
} catch (Exception e) {
e.printStackTrace();
}
try {
timer4.schedule(new GarbageCol(), 5000, 1000 * 60 * 60);// 60mins
System.out.println("timer 2 : garbageCollector");
} catch (Exception e) {
e.printStackTrace();
}
}
private static Date getTomorrowRunningTime(int Ftime){
Calendar tomorrow = new GregorianCalendar();
tomorrow.add(Calendar.DATE, fONE_DAY);
Calendar result = new GregorianCalendar(
tomorrow.get(Calendar.YEAR),
tomorrow.get(Calendar.MONTH),
tomorrow.get(Calendar.DATE),
Ftime,
fZERO_MINUTES
);
return result.getTime();
}
}
CearteSDQuatation class.
public class CearteSDQuatation extends TimerTask {
DateFormat formatter = new SimpleDateFormat("dd.MM.yyyy");;
DateFormat dateFormat = new SimpleDateFormat("dd.MM.yyyy");
Date date = new Date();
DBPool_SF pooler;
DataSource dataSource;
DataSource dataSource1;
DBTableQueryExcecutre qex = null;
DBTableQueryExcecutre qex3 = null;
DBTableQueryExcecutre qex1 = null;
DBTableQueryExcecutre qex2 = null;
ArrayList<String> dates = null;
HashSet<String> dateSet = null;
Iterator<String> itr = null;
StringBuilder inClause;
int rcount = 0;
StringBuilder sbDel = null;
int delStatus = 0;
ArrayList<String> elements = new ArrayList<String>();// for update query
int queryStatus = 0;
String delete_query1 = " ";
String strDate = "";
String strMatnr = "";
String strkunnr = "";
// Object for table data
private Object[][] itemData;
RFCHandler handler;
public CearteSDQuatation(){
handler = new RFCHandler();
}
#Override
public void run() {
// TODO Auto-generated method stub
try{
CallItem_ListCreate();
CallRFC_CreateSDQuata();
System.out.println("Thread Run");
}
catch (Exception e){
e.printStackTrace();
}
}
private void CallItem_ListCreate() {
// TODO Auto-generated method stub
DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
Date date = new Date();
System.out.println(dateFormat.format(date));
System.out.println("Create Quotation : Started sub excecutions List create...");
String sbQuery3 = "SELECT d.plant, h.dis_channel, h.order_no, h.Rep_no," +
"h.dealer_no,h.order_date,h.last_date, d.items_no," +
"d.quantity " +
"FROM tbl_item_list as d, " +
"tbl_items_header_t as h " +
"where d.order_no = h.order_no " +
"and h.status <> 'X'" ;
try {
pooler = DBPool_SF.getInstance();
dataSource1 = pooler.getDataSource();
System.out.println("pooler");
} catch (Exception e1)
{
e1.printStackTrace();
}
try {
Connection con3 = dataSource1.getConnection();
con3.setAutoCommit(false);
Statement st = con3.createStatement();
ResultSet rs = st.executeQuery(sbQuery3);
int lineitem = 0;
try {
rs.last();
rcount = rs.getRow();
rs.beforeFirst();
}
catch(Exception ex) {
ex.printStackTrace();
}
System.out.println("while loop");
itemData = new Object[9][rcount];
while(rs.next())
{
itemData[0][lineitem] = rs.getString("plant");
lineitem = lineitem + 1;
}
} catch (SQLException e)
{
e.printStackTrace();
}
}
public void CallRFC_CreateSDQuata()
{
System.out.println("Create Quotation : Started sub excecutions");
JCO.Table IT_LIST = null;
JCO.Table IT_LIST1 = null;
JCO.Table IT_REF = null;
JCO.Table IT_Msg = null;
try {
if(rcount > 0)
{
handler.createRFCFunction("ZSL");
IT_LIST = handler.getTablePara("IT_LIST");
IT_LIST1 = handler.getTablePara("IT_LIST1");
for(int x = 0; x < rcount; x++ )
{
IT_LIST.appendRow();
IT_LIST1.appendRow();
IT_LIST.setValue( itemData[0][x].toString().trim(), "SAL_ORG");
}
handler.excFunction();
IT_REF = handler.getTablePara("IT_REF");
IT_Msg = handler.getTablePara("IT_MSG");
handler.releaseClient();
int int_row = IT_REF.getNumRows();
if (int_row > 0) {
this.tableOparator(IT_REF , IT_Msg);
}
}
} catch (Exception ex) {
handler.releaseClient();
ex.printStackTrace();
}
finally {
// Release the client to the pool
//handler.releaseClient();
rcount = 0;
}
}
public String leadingZeros(String s, int length) {
if (s.length() >= length) return s;
else return String.format("%0" + (length-s.length()) + "d%s", 0, s);
}
public void tableOparator(JCO.Table table , JCO.Table table1 ) throws Exception {
pooler = DBPool_SF.getInstance();
dataSource = pooler.getDataSource();
Connection con = dataSource.getConnection();
con.setAutoCommit(false);
qex = new DBTableQueryExcecutre(con);
StringBuilder sbQuery = new StringBuilder(
"INSERT INTO tbl_RefQut (QuatationNo,RefOrderNumber) VALUES");
System.out.println("COL -->"+table.getNumRows()
+ " records to insert for tbl_RefQut");
// --- create query ---------------------------------
for (int i = 0; i < table.getNumRows(); i++) {
// table.setRow(i);
sbQuery.append("(?,?),");
}
sbQuery.deleteCharAt(sbQuery.length() - 1);
sbQuery.append(";");
qex.setUpdateQuery(sbQuery.toString());// *****************
elements.clear();
for (int i = 0; i < table.getNumRows(); i++) {
table.setRow(i);
elements.add(table.getString("SDOCUMENT").trim());
elements.add(table.getString("ONUMBER").trim());
}
qex.updateInsertQuery(elements);
con.commit();
StringBuilder sbQuery1 = new StringBuilder(
"INSERT INTO tbl_item_order_msg (order_no,msg) VALUES");
System.out.println("COL -->"+table1.getNumRows()
+ " records to insert for tbl_item_order_msg");
// --- create query ---------------------------------
for (int i = 0; i < table1.getNumRows(); i++) {
// table.setRow(i);
sbQuery1.append("(?,?),");
}
sbQuery1.deleteCharAt(sbQuery1.length() - 1);
sbQuery1.append(";");
qex.setUpdateQuery(sbQuery1.toString());// *****************
elements.clear();
for (int i = 0; i < table1.getNumRows(); i++) {
table1.setRow(i);
elements.add(table1.getString("ORDER_NUMBER").trim());
elements.add(table1.getString("MESSAGE").trim());
}
qex.updateInsertQuery(elements);
con.commit();
for (int i = 0; i < table.getNumRows(); i++) {
table.setRow(i);
String sbQuery2 = "update tbl_items_header_t set status = 'X' where order_no = '" + table.getString("ORDER_NUMBER").trim() + "';";
int rcount = qex.runQuery(sbQuery2);
System.out.println("tbl_items_header_t Rows -->"+rcount + "Status Updated");
con.commit();
}
qex.closeConnections();
System.out.println("COL --> Cycle Finished....");
}
}
a possible reason to this situation is, you are hitting mysql's max open connections error, because you are not closing connections in method CallItem_ListCreate. it seems mysql default max connection count is 151. you are openning 15 connections per hour and after 10 hour you will hit that mentiooned error.
p.s. : you should try running your code in debug mode (or using tools like visualvm, jstack) and view thread dumps as #saurav commented.

Parse JSON and retrieve Last Element

I have the following JSON below I want to retrieve the value of the that last dateTime at the end 2011-05-01
{
"activities-log-steps":[
{"dateTime":"2011-04-27","value":5490},
{"dateTime":"2011-04-28","value":2344},
{"dateTime":"2011-04-29","value":2779},
{"dateTime":"2011-04-30","value":9196},
{"dateTime":"2011-05-01","value":15828},
{"dateTime":"2011-05-02","value":1945},
{"dateTime":"2011-05-03","value":366}
]
}
I have included the code for the current method I am using to try and retrieve that value.
protected void onPostExecute(JSONObject jsonObject) {
Calendar cal = Calendar.getInstance();
cal.add(Calendar.DATE, 1);
SimpleDateFormat format1 = new SimpleDateFormat("yyyy-MM-dd");
String currentDate = format1.format(cal.getTime());
if (jsonObject != null) {
try {
name = jsonObject.getString("dateTime" + ":" + "" + currentDate + "," + "value");
Toast.makeText(getActivity(), name, Toast.LENGTH_LONG).show();
Log.d("Token Access", name);
// _access.setText("Access Token:" + heartrate);
new refresh().execute();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} else {
Toast.makeText(getActivity(), "Network Error", Toast.LENGTH_SHORT).show();
}
}
}
This is not returning a value
JSONArray ar = jsonObject.getJSONArray("activities-log-steps");
JSONObject lastObj = ar.getJSONObject(ar.size()-1);
String dateTime = lastObj.getString("dateTime");
String value = lastObj.getString("value");
You need to locate the last Object from the array activities-log-steps and then extract your JSON vars.

Converting Youtube Data API V3 video duration to hh:mm:ss format in java?

I am using Youtube data api v3 to get video information like title, views count and duration.The duration value is new to me as it's an ISO8601 date which I need to convert to a readable format like hh:mm:ss. Duration can have the following different values:
PT1S --> 00:01
PT1M --> 01:00
PT1H --> 01:00:00
PT1M1S --> 01:01
PT1H1S --> 01:00:01
PT1H1M1S --> 01:01:01
I could use Joda Time library to parse the value and calculate the duration in seconds but the library is of 500kb in size which will increase the size of my application that I don't want.
look at this code :
private static HashMap<String, String> regexMap = new HashMap<>();
private static String regex2two = "(?<=[^\\d])(\\d)(?=[^\\d])";
private static String two = "0$1";
public static void main(String[] args) {
regexMap.put("PT(\\d\\d)S", "00:$1");
regexMap.put("PT(\\d\\d)M", "$1:00");
regexMap.put("PT(\\d\\d)H", "$1:00:00");
regexMap.put("PT(\\d\\d)M(\\d\\d)S", "$1:$2");
regexMap.put("PT(\\d\\d)H(\\d\\d)S", "$1:00:$2");
regexMap.put("PT(\\d\\d)H(\\d\\d)M", "$1:$2:00");
regexMap.put("PT(\\d\\d)H(\\d\\d)M(\\d\\d)S", "$1:$2:$3");
String[] dates = { "PT1S", "PT1M", "PT1H", "PT1M1S", "PT1H1S", "PT1H1M", "PT1H1M1S", "PT10H1M13S", "PT10H1S", "PT1M11S" };
for (String date : dates) {
String d = date.replaceAll(regex2two, two);
String regex = getRegex(d);
if (regex == null) {
System.out.println(d + ": invalid");
continue;
}
String newDate = d.replaceAll(regex, regexMap.get(regex));
System.out.println(date + " : " +newDate);
}
}
private static String getRegex(String date) {
for (String r : regexMap.keySet())
if (Pattern.matches(r, date))
return r;
return null;
}
The regex2two has been used to add a leading zero0 to 1-digit numbers. you can try this demo.
In the regexMap I'v stored all 7 cases and appropriate regex-replace.
I did by myself
Let's try
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.
public class YouTubeDurationUtils {
/**
*
* #param duration
* #return "01:02:30"
*/
public static String convertYouTubeDuration(String duration) {
String youtubeDuration = duration; //"PT1H2M30S"; // "PT1M13S";
Calendar c = new GregorianCalendar();
try {
DateFormat df = new SimpleDateFormat("'PT'mm'M'ss'S'");
Date d = df.parse(youtubeDuration);
c.setTime(d);
} catch (ParseException e) {
try {
DateFormat df = new SimpleDateFormat("'PT'hh'H'mm'M'ss'S'");
Date d = df.parse(youtubeDuration);
c.setTime(d);
} catch (ParseException e1) {
try {
DateFormat df = new SimpleDateFormat("'PT'ss'S'");
Date d = df.parse(youtubeDuration);
c.setTime(d);
} catch (ParseException e2) {
}
}
}
c.setTimeZone(TimeZone.getDefault());
String time = "";
if ( c.get(Calendar.HOUR) > 0 ) {
if ( String.valueOf(c.get(Calendar.HOUR)).length() == 1 ) {
time += "0" + c.get(Calendar.HOUR);
}
else {
time += c.get(Calendar.HOUR);
}
time += ":";
}
// test minute
if ( String.valueOf(c.get(Calendar.MINUTE)).length() == 1 ) {
time += "0" + c.get(Calendar.MINUTE);
}
else {
time += c.get(Calendar.MINUTE);
}
time += ":";
// test second
if ( String.valueOf(c.get(Calendar.SECOND)).length() == 1 ) {
time += "0" + c.get(Calendar.SECOND);
}
else {
time += c.get(Calendar.SECOND);
}
return time ;
}
}
Had to deal with this problem as well. I had to convert the length to milliseconds, but once you get the secs/mins/hours variables populated you can convert to any format you want:
// Test Value
$vidLength = 'PT1H23M45S';
$secs = '';
$mins = '';
$hours = '';
$inspecting = '';
for($i=(strlen($vidLength)-1); $i>0; $i--){
if(is_numeric($vidLength[$i])){
if($inspecting == 'S'){
$secs = $vidLength[$i].$secs;
}
else if($inspecting == 'M'){
$mins = $vidLength[$i].$mins;
}
else if($inspecting == 'H'){
$hours = $vidLength[$i].$hours;
}
}
else {
$inspecting = $vidLength[$i];
}
}
$lengthInMS = 1000*(($hours*60*60) + ($mins*60) + $secs);
I needed a array of all these converted duration. So I wrote the below as a workaround and also java.time.duration was not working for me, don't know why.
String[] D_uration = new String[10];
while(iteratorSearchResults.hasNext()){String Apiduration1=Apiduration.replace("PT","");
if(Apiduration.indexOf("H")>=0){
String Apiduration2=Apiduration1.replace("H",":");
if(Apiduration.indexOf("M")>=0){
String Apiduration3=Apiduration2.replace("M",":");
if(Apiduration.indexOf("S")>=0){
D_uration[i]=Apiduration3.replace("S","");
}
else{
String Apiduration4=Apiduration2.replace("M",":00");
D_uration[i]=Apiduration4;
}
}
else{
String Apiduration4=Apiduration2.replace(":",":00:");
if(Apiduration.indexOf("S")>=0){
D_uration[i]=Apiduration4.replace("S","");
}
else{
String Apiduration3=Apiduration4.replace(":00:",":00:00");
D_uration[i]=Apiduration3;
}
}
}
else{
if(Apiduration.indexOf("M")>=0){
String Apiduration2=Apiduration1.replace("M",":");
if(Apiduration.indexOf("S")>=0){
D_uration[i]=Apiduration2.replace("S","");
}
else{
String Apiduration4=Apiduration2.replace(":",":00");
D_uration[i]=Apiduration4;
}
}
else{
D_uration[i]=Apiduration1.replace("S","");
}
}
"Apiduration" is returned by the Youtube data Api in ISO8601 format.
Made some edits now i think it should work fine.

Simple Date Format Parse Not Working

I am having issuing with the 2 Date try/catch block in the method below.
I am getting a null pointer exception when I hit this method:
private List<HashMap<String,Object>> getOrderHistoryData(final HttpServletRequest request)
{
List<HashMap<String,Object>> productInfo = new ArrayList<HashMap<String,Object>>();
JsCustomerSession sess = (JsCustomerSession) getRequestHelper().getCustomerSession(request);
JsCustomer customer = (JsCustomer) sess.getShopper().getCustomer();
ExtStore store = (ExtStore) sess.getShopper().getCurrentShoppingCart().getStore();
RemoteOrderHistoryService orderHistoryService = remoteServiceLocator.getOrderHistoryService(store);
DateFormat formatter = new SimpleDateFormat("MM-dd-yyyy", Locale.ENGLISH);
Calendar cal = Calendar.getInstance();
String defaultEnd = formatter.format(cal.getTime());
log.debug("Your default end string is: " + defaultEnd);
cal.add(Calendar.DATE, -30);
String defaultStart = formatter.format(cal.getTime());
log.debug("Your defaultStart string is: " + defaultStart);
String startStr = ServletRequestUtils.getStringParameter(request, "start", defaultStart);
String endStr = ServletRequestUtils.getStringParameter(request, "end", defaultEnd);
log.debug("Your start string is: " + startStr);
Date end;
try {
end = formatter.parse(endStr);
} catch (ParseException e) {
e.printStackTrace();
end = new Date();
}
String searchString = ServletRequestUtils.getStringParameter(request, "searchString", "").trim();
String show = ServletRequestUtils.getStringParameter(request, "show", "");
String searchType = ServletRequestUtils.getStringParameter(request, "search-filter", "");
if(startStr.equals(defaultStart))
{
if(searchString != "")
{
Calendar newStart = Calendar.getInstance();
newStart.add(Calendar.YEAR, -25);
startStr = formatter.format(newStart.getTime());
}
else
{
startStr = defaultStart;
}
}
if (show == "")
{
show = "all";
}
if(store.getPosType().equals(ExtStoreImpl.POS_TYPE_INFOR) || store.getPosType().equals(ExtStoreImpl.POS_TYPE_DATABASE))
{
searchString += "show: " + show + "type: " + searchType;
}
Date start;
try {
start = formatter.parse( startStr );
} catch (ParseException e) {
e.printStackTrace();
start = new Date();
}
log.debug("SEARCHING FROM " + start + " TO " + end);
log.debug("SEARCHING FOR " + searchString);
log.debug("SEARCHING TYPE " + searchType);
List<OrderHistoryBean> ohs = orderHistoryService.getOrderHistory(customer, start, end, searchString);
HashMap<String,Object> excelRowData = new HashMap<String,Object>();
if (store.getPosType().equals(ExtStoreImpl.POS_TYPE_ECLIPSE))
{
for(OrderHistoryBean orderHistory : ohs)
{
String shipToFirstName = orderHistory.getShipTo().getFirstName().toString();
String shipToLastName = orderHistory.getShipTo().getLastName().toString();
String shipToFirstAndLastName = shipToFirstName + "" + shipToLastName;
excelRowData.put("Order#", orderHistory.getReferenceNumber());
excelRowData.put("PO#", orderHistory.getPoNumber());
excelRowData.put("Ordered", orderHistory.getPostedDate());
excelRowData.put("Shipped", orderHistory.getShippedDate());
excelRowData.put("Status", orderHistory.getStatus());
excelRowData.put("Ship To", shipToFirstAndLastName);
excelRowData.put("Amount", orderHistory.getAmount());
productInfo.add(excelRowData);
}
}
else if (store.getPosType().equals(ExtStoreImpl.POS_TYPE_DATABASE))
{
for(OrderHistoryBean orderHistory : ohs)
{
excelRowData.put("Reference#", orderHistory.getOrderNumber());
excelRowData.put("Posted Date", orderHistory.getPostedDate());
excelRowData.put("PO/Job#", orderHistory.getPoNumber());
excelRowData.put("Amount", orderHistory.getAmount());
productInfo.add(excelRowData);
}
}
else if (store.getPosType().equals(ExtStoreImpl.POS_TYPE_INFOR))
{
for(OrderHistoryBean orderHistory : ohs)
{
excelRowData.put("Order Number", orderHistory.getOrderNumber());
excelRowData.put("PO Number", orderHistory.getPoNumber());
excelRowData.put("Order Date", orderHistory.getPostedDate());
excelRowData.put("Status", orderHistory.getStatus());
excelRowData.put("Order Total", orderHistory.getAmount());
productInfo.add(excelRowData);
}
}
else if (store.getPosType().equals(ExtStoreImpl.POS_TYPE_NRT))
{
for(OrderHistoryBean orderHistory : ohs)
{
excelRowData.put("Order Number", orderHistory.getOrderNumber());
excelRowData.put("Store", store);
excelRowData.put("Order Date", orderHistory.getPostedDate());
excelRowData.put("Order Total", orderHistory.getAmount());
productInfo.add(excelRowData);
}
}
return productInfo;
}
Also, basically the same code works just fine in my Groovy class:
private ModelAndView performHistorySearch(final HttpServletRequest request){
JsCustomerSession sess = (JsCustomerSession) getRequestHelper().getCustomerSession(request);
JsCustomer customer = sess.getShopper().getCustomer();
ExtStore store = (ExtStore) sess.getShopper().getCurrentShoppingCart().getStore();
RemoteOrderHistoryService orderHistoryService = remoteServiceLocator.getOrderHistoryService(store);
Map<String, Object> model = new HashMap<String, Object>();
DateFormat formatter = new SimpleDateFormat("MM-dd-yyyy");
Calendar cal = Calendar.getInstance();
String defaultEnd = formatter.format(cal.getTime());
cal.add(Calendar.DATE, -30);
String defaultStart = formatter.format(cal.getTime());
String startStr = ServletRequestUtils.getStringParameter(request, "start");
Date end = formatter.parse( ServletRequestUtils.getStringParameter(request, "end", defaultEnd) );
String searchString = ServletRequestUtils.getStringParameter(request, "searchString", "").trim();
String show = ServletRequestUtils.getStringParameter(request, "show", "");
String searchType = ServletRequestUtils.getStringParameter(request, "search-filter", "");
if(startStr == null) {
if(searchString != "") {
Calendar newStart = Calendar.getInstance();
newStart.add(Calendar.YEAR, -25);
startStr = formatter.format(newStart.getTime());
} else {
startStr = defaultStart;
}
}
if (show == ""){
show = 'all';
}
if(store.getPosType().equals(ExtStoreImpl.POS_TYPE_INFOR) || store.getPosType().equals(ExtStoreImpl.POS_TYPE_DATABASE)){
searchString += 'show: ' + show + "type: " + searchType;
}
Date start = formatter.parse( startStr );
log.debug("SEARCHING FROM " + start + ' TO ' + end);
log.debug("SEARCHING FOR " + searchString);
log.debug("SEARCHING TYPE " + searchType);
List<OrderHistoryBean> ohs = orderHistoryService.getOrderHistory(customer, start, end, searchString);
if (store.getPosType().equals(ExtStoreImpl.POS_TYPE_INFOR) || store.getPosType().equals(ExtStoreImpl.POS_TYPE_DATABASE)){
model.put("orders", ohs);
} else {
List<OrderHistoryBean> returnOhs = new ArrayList<OrderHistoryBean>();
ohs.each({oh ->
if(oh.getType() != 'Payment') {
if(show == 'all') {
returnOhs.add(oh);
log.debug('adding ' + oh.getOrderNumber());
} else if (show == 'invoice' && oh.getType() == 'Invoice') {
returnOhs.add(oh);
log.debug('adding ' + oh.getOrderNumber());
} else if (show == 'open' && oh.getType() != 'Invoice') {
returnOhs.add(oh);
log.debug('adding ' + oh.getOrderNumber());
}
}
})
log.debug(returnOhs.size());
model.put("orders", returnOhs);
}
return new ModelAndView(this.getSuccessView(), model);
}
I'm stuck, any help would be appreciated.
Try this:
Date end;
try {
end = formatter.parse(endStr);
} catch (ParseException e) {
e.printStackTrace();
throw e;
}
or
Date end;
try {
end = formatter.parse(endStr);
} catch (ParseException e) {
e.printStackTrace();
end = new Date(); // default to now
}

How do I validate a timestamp?

my application takes in a string like this "2002-10-15 10:55:01.000000". I need to validate that the string is a valid for a db2 timestamp.
How can I do this?
EDIT: This mostly works
public static boolean isTimeStampValid(String inputString) {
SimpleDateFormat format = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSSSSS");
try {
format.parse(inputString);
return true;
} catch (ParseException e) {
return false;
}
}
The problem is that if I pass it a bad format for milliseconds like "2011-05-02 10:10:01.0av" this will pass validation. I am assuming that since the first millisecond character is valid then it just truncates the rest of the string.
I'm not exactly sure about the format but you you can play around it and can try something like this
public static bool isTimeStampValid(String inputString)
{
SimpleDateFormat format = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSSSSS");
try{
format.parse(inputString);
return true;
}
catch(ParseException e)
{
return false;
}
}
EDIT: if you want to validate for numbers after successful parsing, you could do
format.parse(inputString);
Pattern p = Pattern.compile("^\\d{4}[-]?\\d{1,2}[-]?\\d{1,2} \\d{1,2}:\\d{1,2}:\\d{1,2}[.]?\\d{1,6}$");
return p.matcher(inputString).matches();
instead of
format.parse(inputString);
return true;
http://download.oracle.com/javase/6/docs/api/java/text/SimpleDateFormat.html
I believe the format would be "yyyy-MM-dd HH:mm:ss.SSSSSS"
Call parse(String) and catch ParseException indicating it is invalid.
/**
* This method validates the given time stamp in String format
* #param timestamp
* #return
*/
public static boolean isTimeStampValid(String timestamp) {
//(Considering that formal will be yyyy-MM-dd HH:mm:ss.SSSSSS )
//Tokenize string and separate date and time
boolean time = false;
try {
//Tokenize string and separate date and time
StringTokenizer st = new StringTokenizer(timestamp, " ");
if (st.countTokens() != 2) {
return false;
}
String[] dateAndTime = new String[2];
int i = 0;
while (st.hasMoreTokens()) {
dateAndTime[i] = st.nextToken();
i++;
}
String timeToken = dateAndTime[1];
StringTokenizer timeTokens = new StringTokenizer(timeToken, ":");
if (timeTokens.countTokens() != 3) {
return false;
}
String[] timeAt = new String[4];
int j = 0;
while (timeTokens.hasMoreTokens()) {
timeAt[j] = timeTokens.nextToken();
j++;
}
try {
int HH = Integer.valueOf(timeAt[0].toString());
int mm = Integer.valueOf(timeAt[1].toString());
float ss = Float.valueOf(timeAt[2].toString());
if (HH < 60 && HH >= 0 && mm < 60 && mm >= 0 && ss < 60 && ss >= 0) {
time = true;
} else {
}
} catch (Exception e) {
e.printStackTrace();
}
//Got Date
String dateToken = dateAndTime[0];//st.nextToken();
//Tokenize separated date and separate year-month-day
StringTokenizer dateTokens = new StringTokenizer(dateToken, "-");
if (dateTokens.countTokens() != 3) {
return false;
}
String[] tokenAt = new String[3];
//This will give token string array with year month and day value.
int k = 0;
while (dateTokens.hasMoreTokens()) {
tokenAt[k] = dateTokens.nextToken();
k++;
}
//Now try to create new date with got value of date
int dayInt = Integer.parseInt(tokenAt[2]);
int monthInt = Integer.parseInt(tokenAt[1]);
int yearInt = Integer.parseInt(tokenAt[0]);
Calendar cal = new GregorianCalendar();
cal.setLenient(false);
cal.set(yearInt, monthInt - 1, dayInt);
cal.getTime();//If not able to create date it will throw error
} catch (Exception e) {
e.printStackTrace();
return false;
}
//Here we ll check for correct format is provided else it ll return false
try {
Pattern p = Pattern.compile("^\\d{4}[-]?\\d{1,2}[-]?\\d{1,2} \\d{1,2}:\\d{1,2}:\\d{1,2}[.]?\\d{1,6}$");
if (p.matcher(timestamp).matches()) {
} else {
return false;
}
} catch (Exception e) {
e.printStackTrace();
return false;
}
//Cross checking with simple date format to get correct time stamp only
SimpleDateFormat format = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSSSSS");
try {
format.parse(timestamp);
//return true;
if (time) {
return true;
} else {
return false;
}
} catch (ParseException e) {
e.printStackTrace();
return false;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
If you're already connected to the database, you can execute a query that attempts to cast the input string as a timestamp, and check for a failure message (in this case, SQLSTATE 22007).
VALUES CAST( ? AS TIMESTAMP )
The above query will fully validate the input string while consuming hardly any resources on the database server. If the string is invalid for any reason, your database client will encounter an exception.

Categories