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.
Related
I am fetching data from file using filestream and importing this data into oracle tables. I have column 'FT__FIRST' which is Date data type in oracle table and where i only need date values to be inserted and ignore other values. From file the date is coming in format 'YYYYMMDD'. In future if there is other values coming from file rather than Date datatype for this column and if it tries to insert into oracle table then the java code might throw an error as literal string does not match.
So to avoid this issue i want to modify my java code such that it can take only insert date format value and ignore other values. Currently i am handling only specific string from file which i know and ignoring it as they are not date format..
Java uses classes DateTimeformatter but dont know how to use it in my code..
private String createUpdateTableSql(String line, String tableName, String dateFormat, List<ColumnData> columnData) {
List<String> data = Splitter.on("|").trimResults().splitToList(line);
String ftFirst = "";
String tr = "";
String pds = "";
for (int i = 0; i < columnData.size(); i++) {
if(columnData.get(i) == null || "N.A.".equalsIgnoreCase(data.get(i)) || "N.A".equalsIgnoreCase(data.get(i)) || "UNKNOWN".equalsIgnoreCase(data.get(i))) {
continue;
}
if ("FT_FIRST".equalsIgnoreCase(columnData.get(i).getName().trim())) {
ftFirst = data.get(i);
}
if ("TR".equalsIgnoreCase(columnData.get(i).getName().trim())) {
tr = data.get(i);
}
if ("P_S_SOURCE".equalsIgnoreCase(columnData.get(i).getName().trim())) {
pds = data.get(i);
}
}
return "UPDATE " + tableName + " " +
"SET FT_FIRST=to_date('" + ftFirst + "','YYYYMMDD')" +
" WHERE TR='" + ticker +
"' AND P_S_SOURCE='" + pds + "'";
}
When you read data from file, you could parse the date field to date object like below:
// NEW CODE
private Date getDateValue(String sDate, String format) {
SimpleDateFormat sdf = new SimpleDateFormat(format);
try {
return
sdf.parse(format);
} catch (ParseException ignored) {
// TODO: Log this exception return null;
}
}
As you can see, you are parsing a string to date with an expected format yyyyMMdd (YYYYMMDD on oracle)
If parsing fails (value field does not containts the expected format) you can add the logic as you want on catch clausule or ignore error and let value as null.
Your code will be like this:
private String createUpdateTableSql(String line, String tableName, String dateFormat, List<ColumnData> columnData) {
List<String> data = Splitter.on("|").trimResults().splitToList(line);
String futNoticeFirst = "";
String ticker = "";
String pds = "";
for (int i = 0; i < columnData.size(); i++) {
if (columnData.get(i) == null || "N.A.".equalsIgnoreCase(data.get(i)) || "N.A".equalsIgnoreCase(data.get(i)) || "UNKNOWN".equalsIgnoreCase(data.get(i))) {
continue;
}
if ("FUT_NOTICE_FIRST".equalsIgnoreCase(columnData.get(i).getName().trim())) {
futNoticeFirst = getDateValue(data.get(i), 'yyyyMMdd');
}
if ("TICKER".equalsIgnoreCase(columnData.get(i).getName().trim())) {
ticker = data.get(i);
}
if ("PARSEKYABLE_DES_SOURCE".equalsIgnoreCase(columnData.get(i).getName().trim())) {
pds = data.get(i);
}
}
return "UPDATE " + tableName + " " +
"SET FUT_NOTICE_FIRST= " + futNoticeFirst +
" WHERE TICKER='" + ticker +
"' AND PARSEKYABLE_DES_SOURCE='" + pds + "'";
}
// NEW CODE
private Date getDateValue(String sDate, String format) {
SimpleDateFormat sdf = new SimpleDateFormat(format);
try {
return
sdf.parse(format);
} catch (ParseException ignored) {
// TODO: Log this exception
return null;
}
}
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
How can I make one data use one JSONarray? Currently I am using one JSONARRAY only. Please find code below and suggest.
public class test {
SimpleDateFormat dateFormat = new SimpleDateFormat(
"yyyy-MM-dd HH:mm:ss");
public JSONArray generateData(String idDevice, Date startTime, Date
dateTime, Date endTime) {
JSONArray arrBuff = new JSONArray();
try {
for (long i = startTime.getTime(); i <= endTime.getTime(); i += 1000) {
//for (int l=0;i<l;l++){
arrBuff.add("idDevice:\"" + idDevice + "\"");
arrBuff.add("dateTime:\"" + dateFormat.format(new Date(i)) +
"\"");
arrBuff.add("dateType: HRM");
arrBuff.add("ValueUnit:bpm");
i++;
}
System.out.println("Successfully Copied JSON Object to
File...");
System.out.println("\nJSON Object: " + arrBuff);
return arrBuff;
} catch (Exception e) {
return arrBuff;
}
}
}
In my java project i want to disable a range of dates in the java calendar and could not be successful. I'm using Netbeans as my IDE and JCalendar. Below is my code. Any help would be appreciated.
ArrayList<JSONObject> arrays = new ArrayList<JSONObject>();
for (int i = 0; i < n; i++) {
JSONObject another_json_object = vacation_home_booking_data.getJSONObject(i);
JSONObject[] jsons = new JSONObject[arrays.size()];
arrays.toArray(jsons);
String id = another_json_object.getString("id");
String vh_id = another_json_object.getString("vh_id");
String check_in = another_json_object.getString("check_in");
String check_out = another_json_object.getString("check_out");
String status = another_json_object.getString("status");
//creating two arrays of checking and checkout
//check_in_arr[i] = another_json_object.getString("check_in");
//check_out_arr[i] = another_json_object.getString("check_out");
System.out.println("ID is " + id + "vh id is " + vh_id + "check in is " + check_in + "check out is " + check_out);
DateFormat formatter = new SimpleDateFormat("yyyy-mm-dd");
try {
Date date1 = formatter.parse(check_in);
Date date2 = formatter.parse(check_out);
jCalendar1.setSelectableDateRange(date1, date2);
jCalendar1.setBackground(Color.yellow);
//jCalendar1.setSelectedDate();
} catch (ParseException ex) {
Logger.getLogger(Calender.class.getName()).log(Level.SEVERE, null, ex);
ex.printStackTrace();
}
}
Please see, if the below methods works for you:
private DateChooserCombochooser; // Initialize this somewhere
public void setMaxDate(Calendar aDate) {
chooser.setMaxDate(aDate);
}
public void setMinDate(Calendar aDate) {
chooser.setMinDate(aDate);
}
Alternatively, try using setDefaultPeriods(PeriodSet periods) method in the API.
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
}