List of usage examples for java.text DateFormat parse
public Date parse(String source) throws ParseException
From source file:com.esri.geoevent.transport.httpPoll.HttpPollInboundTransport.java
@Override public void beforeConnect(TransportContext context) { DateFormat df = null; tsvalue = ""; if (!(context instanceof HttpTransportContext)) return;//from w w w. j a v a2s . c o m // Parse user defined initial ts try { df = new SimpleDateFormat(tsformat); } catch (Exception e) { df = null; } if (df != null) { if (ts == null) { try { Date userdefined = df.parse(tsinit); if (userdefined == null) { ts = new Date(0); tsvalue = df.format(ts); } else { tsvalue = df.format(userdefined); } } catch (ParseException e) { ts = new Date(0); tsvalue = df.format(ts); } } else { tsvalue = df.format(ts); } ts = new Date(); } HttpRequest request = ((HttpTransportContext) context).getHttpRequest(); if (request instanceof HttpPost) { ArrayList<NameValuePair> postParameters; postParameters = new ArrayList<NameValuePair>(); if (tsvalue.length() > 0) postParameters.add(new BasicNameValuePair(tsparam, tsvalue)); try { Map<String, String> paramMap = parseParameters(params); Iterator<Entry<String, String>> itr = paramMap.entrySet().iterator(); while (itr.hasNext()) { Entry<String, String> pairs = itr.next(); postParameters.add(new BasicNameValuePair((String) pairs.getKey(), (String) pairs.getValue())); itr.remove(); } if (postParameters.size() > 0) { UrlEncodedFormEntity entity = new UrlEncodedFormEntity(postParameters, StandardCharsets.UTF_8); ((HttpPost) request).setEntity(entity); } } catch (Exception error) { LOGGER.error("PARSING_ERROR", error.getMessage()); LOGGER.info(error.getMessage(), error); } } }
From source file:com.mentor.questa.vrm.jenkins.QuestaVrmRegressionResult.java
public Date getRegressionBegin() { DateFormat df = new SimpleDateFormat("yyyy-MM-dd\'T\'HH:mm:ss"); try {/*w ww . j a v a 2 s . c om*/ return df.parse(timestamp); } catch (Exception e) { } return null; }
From source file:eu.serco.dhus.plugin.slstr.SlstrPlugin.java
private Date computeMiddleDate(String start, String stop) { DateFormat inputFormat = new SimpleDateFormat("yyyyMMdd'T'HHmmss"); // 2016-07-16T00:00:00.000Z DateFormat outputFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss"); Date startDate;// www . j ava 2s. c o m Date stopDate; try { startDate = inputFormat.parse(start); stopDate = inputFormat.parse(stop); return new Date((startDate.getTime() + stopDate.getTime()) / 2); } catch (Exception e) { logger.error("Error computing middle date " + e.getMessage()); e.printStackTrace(); return null; } }
From source file:ch.entwine.weblounge.cache.impl.CacheEntry.java
/** * Sets the response headers, which will be used to extract certain common * information such as the etag or the last-modified date. * /*w w w.j a v a 2 s .c om*/ * @param headers * the response headers */ public void setHeaders(CacheableHttpServletResponseHeaders headers) { this.headers = headers; // Overwrite local Last-Modified? if (headers.containsHeader("Last-Modified")) { DateFormat df = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss zzz", Locale.US); String lastModifiedHeader = (String) headers.getHeaders().get("Last-Modified"); try { modificationDate = getTimeWithoutMilliseconds( new Date(Math.max(modificationDate, df.parse(lastModifiedHeader).getTime()))); logger.trace("Changing modification date to '{}' as provided by response headers", lastModifiedHeader); eTag = createETag(modificationDate); logger.trace("Changing eTag to '{}' as provided by response headers", eTag); } catch (ParseException e) { logger.error("Unexpected date format for 'Last-Modified' header: {}", lastModifiedHeader); } } // Overwrite local ETag? if (headers.containsHeader("ETag")) { eTag = (String) headers.getHeaders().get("ETag"); logger.trace("Changing eTag to '{}' as provided by response headers", eTag); } }
From source file:net.jperf.logback.AppenderTest.java
public void testCsvRenderer() throws Exception { LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory(); JoranConfigurator configurator = new JoranConfigurator(); configurator.setContext(lc);// w ww .ja v a2 s. c o m // the context was probably already configured by default configuration // rules lc.reset(); configurator.doConfigure(getClass().getResource("logbackWCsv.xml")); Logger logger = lc.getLogger("net.jperf.CsvAppenderTest"); for (int i = 0; i < 20; i++) { StopWatch stopWatch = new Slf4JStopWatch(logger); Thread.sleep(i * 10); stopWatch.stop("csvTest"); } //close the appender logger.getAppender("coalescingStatistics").stop(); //verify the statisticsLog.csv file DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); for (Object line : FileUtils.readLines(new File("./target/statisticsLogback.csv"))) { String[] values = line.toString().split(","); //first column is the tag assertEquals("\"csvTest\"", values[0]); //next 2 columns are the dates - ensure they can be parsed assertTrue(dateFormat.parse(values[1]).before(dateFormat.parse(values[2]))); //next 3 columns are mean, min and max double mean = Double.parseDouble(values[3]); int min = Integer.parseInt(values[4]); int max = Integer.parseInt(values[5]); assertTrue(mean >= min && mean <= max); //next column is stddev - ust make sure it's parseable Double.parseDouble(values[6]); //next column is count assertTrue(Integer.parseInt(values[7]) < 20); //final column is TPS - just make sure it's parseable Double.parseDouble(values[8]); } //verify the pivotedStatisticsLog.csv file for (Object line : FileUtils.readLines(new File("./target/pivotedStatisticsLog.csv"))) { String[] values = line.toString().split(","); //first 2 columns are the dates - ensure they can be parsed assertTrue(dateFormat.parse(values[0]).before(dateFormat.parse(values[1]))); //next column is mean, ensure it can be parsed Double.parseDouble(values[2]); //last column should be empty, so make sure last char on string is comma assertEquals(',', line.toString().charAt(line.toString().length() - 1)); } }
From source file:org.openmrs.module.patientnarratives.web.controller.FullNarrativeFormController.java
@Override protected Object formBackingObject(HttpServletRequest request) throws Exception { try {//from w ww. ja v a2 s . co m if (StringUtils.hasLength(request.getParameter("comment"))) { PatientNarrativesService patientNarrativesService = Context .getService(PatientNarrativesService.class); NarrativeComments narrativeComments = new NarrativeComments(); narrativeComments.setComment(request.getParameter("comment")); String encounterId = request.getParameter("encounterId"); narrativeComments.setEncounterId(Integer.parseInt(encounterId)); patientNarrativesService.saveNarrativesComment(narrativeComments); request.getSession().setAttribute(WebConstants.OPENMRS_MSG_ATTR, "patientnarratives.comment.added"); } if (StringUtils.hasLength(request.getParameter("newStatus"))) { String newStatus = request.getParameter("newStatus"); int encounterId = Integer.parseInt(request.getParameter("encounterId")); Encounter encounter = Context.getEncounterService().getEncounter(encounterId); Set<Obs> obs = encounter.getObs(); Iterator<Obs> observation = obs.iterator(); Integer statusObsId = null; Obs nowOb = null; while (observation.hasNext()) { nowOb = observation.next(); if (nowOb.getConcept().getConceptId() == 15 && !nowOb.isVoided()) { statusObsId = nowOb.getId(); Obs statusObs = Context.getObsService().getObs(statusObsId); Context.getObsService().voidObs(statusObs, "obs voided"); break; } } Person patient = encounter.getPatient(); Location location = Context.getLocationService().getDefaultLocation(); Obs newObs = new Obs(patient, nowOb.getConcept(), new Date(), location); newObs.setValueText(newStatus); newObs.setEncounter(encounter); Context.getObsService().saveObs(newObs, null); request.getSession().setAttribute(WebConstants.OPENMRS_MSG_ATTR, "patientnarratives.status.updated"); } if (StringUtils.hasLength(request.getParameter("registerEncounterId"))) { Integer encounterId = Integer.parseInt(request.getParameter("registerEncounterId")); PatientService patientService = Context.getPatientService(); Patient patient = new Patient(); EncounterService encounterService = Context.getEncounterService(); Encounter encounter = encounterService.getEncounter(encounterId); String patientName = ""; String patientAge = ""; String patientGender = ""; Set<Obs> obs = encounter.getObs(); Iterator<Obs> observation = obs.iterator(); while (observation.hasNext()) { Obs nowOb = observation.next(); if (nowOb.getConcept().getConceptId() == 12) { patientName = nowOb.getValueText(); } if (nowOb.getConcept().getConceptId() == 8) { patientAge = nowOb.getValueText(); } if (nowOb.getConcept().getConceptId() == 13) { patientGender = nowOb.getValueText(); } } PersonName personName = new PersonName(); int patientCount = patientService.getAllPatients().size(); int newPatientId = patientCount + 5; String nameArr[] = patientName.split(" "); if (nameArr.length == 1) { personName.setGivenName(nameArr[0]); personName.setFamilyName("----"); } else if (nameArr.length == 2) { personName.setGivenName(nameArr[0]); personName.setFamilyName(nameArr[1]); } else if (nameArr.length >= 3) { String nameArr2[] = parseFullName(patientName); personName.setGivenName(nameArr2[0]); personName.setMiddleName(nameArr2[1]); personName.setFamilyName(nameArr2[2]); } Set<PersonName> personNameSet = new TreeSet<PersonName>(); personNameSet.add(personName); patient.setNames(personNameSet); patient.setGender(patientGender); DateFormat df = new SimpleDateFormat("yyyy-MM-dd"); String date = new SimpleDateFormat("yyyy-MM-dd").format(new Date()); patient.setBirthdateFromAge(Integer.parseInt(patientAge), df.parse(date)); PatientIdentifierType patientIdentifierType = Context.getPatientService() .getPatientIdentifierType(2); Location location = Context.getLocationService().getDefaultLocation(); PatientIdentifier patientIdentifier = new PatientIdentifier(String.valueOf(newPatientId), patientIdentifierType, location); patient.addIdentifier(patientIdentifier); patientService.savePatient(patient); int patientId = patientService.getPatients(String.valueOf(newPatientId)).get(0).getPatientId(); encounter.setPatient(patientService.getPatient(patientId)); encounterService.saveEncounter(encounter); request.getSession().setAttribute(WebConstants.OPENMRS_MSG_ATTR, "patientnarratives.newpatient.created.alert"); } } catch (Exception e) { request.getSession().setAttribute(WebConstants.OPENMRS_MSG_ATTR, "Error occurred while Registering the Patient: " + e.getMessage()); log.error(e); } return request.getParameter("encounterId"); }
From source file:eu.serco.dhus.plugin.slstr.SlstrPlugin.java
public List<Request> retrieveRequests(String productType, String startTime, String stopTime) { List<Request> requests = new ArrayList<Request>(); Date startDate;/*from w ww . ja va 2 s .c om*/ Date stopDate; long startDateInMillis; long stopDateInMillis; DateFormat inputFormat = new SimpleDateFormat("yyyyMMdd'T'HHmmss"); // 2016-07-16T00:00:00.000Z DateFormat outputFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss"); try { startDate = inputFormat.parse(startTime); stopDate = inputFormat.parse(stopTime); startDateInMillis = startDate.getTime(); stopDateInMillis = stopDate.getTime(); if (taskTables.get(productType) != null) { for (Task task : taskTables.get(productType).getTasks()) { logger.info("task.getName()" + task.getName()); logger.info("task.getInputs()" + task.getInputs()); Request request; for (Input in : task.getInputs()) { request = new Request(); request.setMandatory(in.getMandatory()); // TODO: Manage Mode when getting requests to perform request.setMode(in.getMode()); List<InputRequest> inputRequests = new ArrayList<InputRequest>(); for (Alternative alternative : in.getAlternatives()) { InputRequest inReq = new InputRequest(); String url = propFiles.get(productType).getProperty(alternative.getRetrievalMode()); url = url.replace("<filename>", alternative.getFileType()); long startValidity; long stopValidity; if (alternative.getT0() > 0) { startValidity = startDateInMillis - (long) Math.ceil(alternative.getT0() * 1000); } else { startValidity = startDateInMillis; } if (alternative.getT1() > 0) { stopValidity = stopDateInMillis + (long) Math.ceil(alternative.getT1() * 1000); } else { stopValidity = stopDateInMillis; } Date startValidityDate = new Date(startValidity); String beginPosition = outputFormat.format(startValidityDate) + ".000Z"; Date stopValidityDate = new Date(stopValidity); String endPosition = outputFormat.format(stopValidityDate) + ".000Z"; url = url.replace("<beginPosition>", beginPosition); url = url.replace("<endPosition>", endPosition); url = externalDHuSUrl + url; inReq.setUrl(url); inReq.setType(alternative.getFileType()); inReq.setRetrievalMode(alternative.getRetrievalMode()); inputRequests.add(inReq); logger.info("----------"); logger.info("Request to perform: " + externalDHuSUrl + url); } logger.info("How many urls???: " + inputRequests.size()); request.setRequests(inputRequests); requests.add(request); } } } } catch (ParseException pe) { pe.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } logger.info("Request size is: ????? **** " + requests.size()); return requests; }
From source file:eu.serco.dhus.plugin.sral.SralPlugin.java
private Date computeMiddleDate(String start, String stop) { DateFormat inputFormat = new SimpleDateFormat("yyyyMMdd'T'HHmmss"); //2016-07-16T00:00:00.000Z DateFormat outputFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss"); Date startDate;/*from w ww . ja va 2 s.c om*/ Date stopDate; try { startDate = inputFormat.parse(start); stopDate = inputFormat.parse(stop); return new Date((startDate.getTime() + stopDate.getTime()) / 2); } catch (Exception e) { logger.error("Error computing middle date " + e.getMessage()); e.printStackTrace(); return null; } }
From source file:com.microsoft.azure.storage.core.Utility.java
/** * Given a String representing a date in a form of the ISO8601 pattern, generates a Date representing it * with up to millisecond precision. //from www. j av a2 s .co m * * @param dateString * the <code>String</code> to be interpreted as a <code>Date</code> * * @return the corresponding <code>Date</code> object */ public static Date parseDate(String dateString) { String pattern = MAX_PRECISION_PATTERN; switch (dateString.length()) { case 28: // "yyyy-MM-dd'T'HH:mm:ss.SSSSSSS'Z'"-> [2012-01-04T23:21:59.1234567Z] length = 28 case 27: // "yyyy-MM-dd'T'HH:mm:ss.SSSSSS'Z'"-> [2012-01-04T23:21:59.123456Z] length = 27 case 26: // "yyyy-MM-dd'T'HH:mm:ss.SSSSS'Z'"-> [2012-01-04T23:21:59.12345Z] length = 26 case 25: // "yyyy-MM-dd'T'HH:mm:ss.SSSS'Z'"-> [2012-01-04T23:21:59.1234Z] length = 25 case 24: // "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"-> [2012-01-04T23:21:59.123Z] length = 24 dateString = dateString.substring(0, MAX_PRECISION_DATESTRING_LENGTH); break; case 23: // "yyyy-MM-dd'T'HH:mm:ss.SS'Z'"-> [2012-01-04T23:21:59.12Z] length = 23 // SS is assumed to be milliseconds, so a trailing 0 is necessary dateString = dateString.replace("Z", "0"); break; case 22: // "yyyy-MM-dd'T'HH:mm:ss.S'Z'"-> [2012-01-04T23:21:59.1Z] length = 22 // S is assumed to be milliseconds, so trailing 0's are necessary dateString = dateString.replace("Z", "00"); break; case 20: // "yyyy-MM-dd'T'HH:mm:ss'Z'"-> [2012-01-04T23:21:59Z] length = 20 pattern = Utility.ISO8601_PATTERN; break; case 17: // "yyyy-MM-dd'T'HH:mm'Z'"-> [2012-01-04T23:21Z] length = 17 pattern = Utility.ISO8601_PATTERN_NO_SECONDS; break; default: throw new IllegalArgumentException(String.format(SR.INVALID_DATE_STRING, dateString)); } final DateFormat format = new SimpleDateFormat(pattern, Utility.LOCALE_US); format.setTimeZone(UTC_ZONE); try { return format.parse(dateString); } catch (final ParseException e) { throw new IllegalArgumentException(String.format(SR.INVALID_DATE_STRING, dateString), e); } }
From source file:com.bringcommunications.etherpay.HistoryActivity.java
private int set_transactions(String rsp) { //typical response id: //{//from w w w .j av a 2s. c o m // "status": 1, // "data": [ // { // "hash": "0x1b3dca103e0605b45f81eede754401df4082b87c4faf3f1205755b36f1b34ddf", // "sender": "0x8b8a571730b631f58e7965d78582eae1b0417ab6", // "recipient": "0x85d9147b0ec6d60390c8897244d039fb55b087c6", // "accountNonce": "76", // "price": 25000000000, // "gasLimit": 35000, // "amount": 2000000108199936, // "block_id": 2721132, // "time": "2016-11-30T09:58:07.000Z", // "newContract": 0, // "isContractTx": null, // "blockHash": "0x5c1118c94176902cab1783f8d4f8d17544c7a16c8ef377f674fa89693eb3ab0c", // "parentHash": "0x1b3dca103e0605b45f81eede754401df4082b87c4faf3f1205755b36f1b34ddf", // "txIndex": null, // "gasUsed": 21000, // "type": "tx" // }, // ..... // } int idx = 0; int status = 0; int no_transactions = 0; if (rsp.contains("status")) { int field_idx = rsp.indexOf("status") + "status".length(); int beg_idx = rsp.indexOf(':', field_idx) + 1; int end_idx = rsp.indexOf(',', beg_idx); status = Integer.valueOf(rsp.substring(beg_idx, end_idx).trim()); idx = end_idx + 1; } if (status != 1) { Util.show_err(getBaseContext(), "error retrieving transactions!", 3); Util.show_err(getBaseContext(), rsp.substring(0, 30), 10); return (0); } rsp = rsp.substring(idx); idx = 0; for (int i = 0; i < 100; ++i) { if (rsp.contains("{")) { idx = rsp.indexOf('{') + 1; rsp = rsp.substring(idx); } else { break; } ++no_transactions; String txid = ""; String from = ""; String to = ""; long nonce = 0; float size = 0; Calendar date = Calendar.getInstance(); if (rsp.contains("hash")) { int field_idx = rsp.indexOf("hash") + "hash".length(); int beg_idx = rsp.indexOf(':', field_idx) + 1; int end_idx = rsp.indexOf(',', beg_idx); txid = rsp.substring(beg_idx, end_idx).replaceAll("\"", "").trim(); } if (rsp.contains("sender")) { int field_idx = rsp.indexOf("sender") + "sender".length(); int beg_idx = rsp.indexOf(':', field_idx) + 1; int end_idx = rsp.indexOf(',', beg_idx); from = rsp.substring(beg_idx, end_idx).replace("\"", "").trim(); if (!show_sent && from.equals(acct_addr)) continue; } if (rsp.contains("recipient")) { int field_idx = rsp.indexOf("recipient") + "recipient".length(); int beg_idx = rsp.indexOf(':', field_idx) + 1; int end_idx = rsp.indexOf(',', beg_idx); to = rsp.substring(beg_idx, end_idx).replace("\"", "").trim(); if (!show_received && to.equals(acct_addr)) continue; } if (rsp.contains("accountNonce")) { int field_idx = rsp.indexOf("accountNonce") + "accountNonce".length(); int beg_idx = rsp.indexOf(':', field_idx) + 1; int end_idx = rsp.indexOf(',', beg_idx); nonce = Long.valueOf(rsp.substring(beg_idx, end_idx).replace("\"", "").trim()); } if (rsp.contains("amount")) { int field_idx = rsp.indexOf("amount") + "amount".length(); int beg_idx = rsp.indexOf(':', field_idx) + 1; int end_idx = rsp.indexOf(',', beg_idx); long wei_amount = Long.valueOf(rsp.substring(beg_idx, end_idx).trim()); size = wei_amount / WEI_PER_ETH; } if (rsp.contains("time")) { int field_idx = rsp.indexOf("time") + "time".length(); int beg_idx = rsp.indexOf(':', field_idx) + 1; int end_idx = rsp.indexOf(',', beg_idx); String date_str = rsp.substring(beg_idx, end_idx).replace("\"", "").trim(); //System.out.println("raw date: " + created_at); //could the date string have more or less than 3 digits after the decimal? (eg 5: 2015-11-10T01:20:14.16525Z). to avoid //complication, (and parse exceotions) we always force 3. int decimal_idx = date_str.indexOf("."); String conforming_date_str = date_str; if (decimal_idx < 0) System.out.println("hey! no decimal in date string: " + conforming_date_str); if (decimal_idx >= 0) { //decimal_idx is idx of decimal point. add 1 to get len, and we need 3 more digits (followed by 'Z') if (date_str.length() >= decimal_idx + 5) //substring includes end_idx -1 conforming_date_str = date_str.substring(0, decimal_idx + 4) + "Z"; else conforming_date_str = date_str.substring(0, decimal_idx) + ".000Z"; } //in java 7, an 'X' in the dateformat indicates that the date string might contain an ISO8601 suffix, eg. Z for UTC. //unfortunately that doesn't work for android. a 'Z' in the dateformat indicates that the timezone conforms to the RFC822 //time zone standard, e.g. -0800. so we'll just convert to that. DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ"); conforming_date_str = conforming_date_str.replaceAll("Z$", "+0000"); try { date.setTime(df.parse(conforming_date_str)); } catch (ParseException e) { System.out.println(e.toString()); } } Transaction_Info transaction_info = new Transaction_Info(txid, to, from, nonce, size, date); transaction_list.add(transaction_info); if (rsp.contains("}")) { idx = rsp.indexOf('}') + 1; rsp = rsp.substring(idx); } else { break; } } return (no_transactions); }