List of usage examples for java.text DateFormat parse
public Date parse(String source) throws ParseException
From source file:com.zhengxuetao.gupiao.service.impl.DayServiceImpl.java
@Override public boolean saveDayDataFromFile(File file) { if (file != null && file.exists() && file.isFile()) { DayData dayData = new DayData(); String fileName = file.getName(); //SH#600004.txt dayData.setFinanceId(Long.parseLong(fileName.substring(3, 9))); String encoding = "GBK"; InputStreamReader reader = null; DateFormat format = new SimpleDateFormat("yyyy-mm-dd hh:mm:ss"); DateFormat parseFormat = new SimpleDateFormat("yyyy-mm-dd"); try {//from www . java2 s . c o m reader = new InputStreamReader(new FileInputStream(file), encoding); BufferedReader bufferedReader = new BufferedReader(reader); String readLine; while ((readLine = bufferedReader.readLine()) != null) { //?????????? String[] arr = readLine.split(","); dayData.setTime(Timestamp.valueOf(format.format(parseFormat.parse(arr[0])))); dayData.setStartPrice(Float.valueOf(arr[1])); dayData.setHighPrice(Float.valueOf(arr[2])); dayData.setLowPrice(Float.valueOf(arr[3])); dayData.setEndPrice(Float.valueOf(arr[4])); dayData.setVolume(Long.valueOf(arr[5])); dayData.setAmount(Double.valueOf(arr[6])); userDAO.saveDayData(dayData); } } catch (IOException | ParseException ex) { logger.error(ex.getMessage()); } finally { try { reader.close(); } catch (IOException ex) { logger.error(ex.getMessage()); } } } else { logger.error("?!"); } return true; }
From source file:net.jperf.log4j.AppenderTest.java
public void testCsvRenderer() throws Exception { DOMConfigurator.configure(getClass().getResource("log4jWCsv.xml")); Logger logger = Logger.getLogger("net.jperf.CsvAppenderTest"); for (int i = 0; i < 20; i++) { StopWatch stopWatch = new Log4JStopWatch(logger); Thread.sleep(i * 10);//from www .j ava2 s . co m stopWatch.stop("csvTest"); } //close the appender logger.getAppender("coalescingStatistics").close(); //verify the statisticsLog.csv file DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); for (Object line : FileUtils.readLines(new File("./target/statisticsLog.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:com.krawler.spring.companyDetails.companyDetailsDAOImpl.java
@Override public KwlReturnObject updateCompany(HashMap hm) throws ServiceException { String companyid = ""; DateFormat dateformat = null; List ll = null;//from w w w . j ava 2s . c o m int dl = 0; try { Company company = null; if (hm.containsKey("companyid") && hm.get("companyid") != null) { companyid = hm.get("companyid").toString(); if (hm.containsKey("addCompany") && (Boolean) hm.get("addCompany")) { company = new Company(); company.setCompanyID(companyid); if (hm.containsKey("companyId") && hm.get("companyId") != null) { Long companyId = (Long) hm.get("companyId"); company.setCompanyId(companyId); } } else { company = (Company) get(Company.class, companyid); } } if (hm.containsKey("dateformat") && hm.get("dateformat") != null) { dateformat = (DateFormat) hm.get("dateformat"); } if (hm.containsKey("creater") && hm.get("creater") != null) { company.setCreator((User) get(User.class, (String) hm.get("creater"))); } if (hm.containsKey("companyname") && hm.get("companyname") != null) { company.setCompanyName((String) hm.get("companyname")); } if (hm.containsKey("address") && hm.get("address") != null) { company.setAddress((String) hm.get("address")); } if (hm.containsKey("city") && hm.get("city") != null) { company.setCity((String) hm.get("city")); } if (hm.containsKey("state") && hm.get("state") != null) { company.setState((String) hm.get("state")); } if (hm.containsKey("zip") && hm.get("zip") != null) { company.setZipCode((String) hm.get("zip")); } if (hm.containsKey("phone") && hm.get("phone") != null) { company.setPhoneNumber((String) hm.get("phone")); } if (hm.containsKey("fax") && hm.get("fax") != null) { company.setFaxNumber((String) hm.get("fax")); } if (hm.containsKey("website") && hm.get("website") != null) { company.setWebsite((String) hm.get("website")); } if (hm.containsKey("mail") && hm.get("mail") != null) { company.setEmailID((String) hm.get("mail")); } if (hm.containsKey("domainname") && hm.get("domainname") != null) { company.setSubDomain((String) hm.get("domainname")); } if (hm.containsKey("country") && hm.get("country") != null) { company.setCountry((Country) get(Country.class, hm.get("country").toString())); } if (hm.containsKey("currency") && hm.get("currency") != null) { company.setCurrency((KWLCurrency) get(KWLCurrency.class, (String) hm.get("currency"))); } if (hm.containsKey("timezone") && hm.get("timezone") != null) { KWLTimeZone timeZone = (KWLTimeZone) get(KWLTimeZone.class, (String) hm.get("timezone")); company.setTimeZone(timeZone); } if (hm.containsKey("deleteflag") && hm.get("deleteflag") != null) { company.setDeleted((Integer) hm.get("deleteflag")); } if (hm.containsKey("createdon") && hm.get("createdon") != null) { company.setCreatedOn(new Date()); } if (hm.containsKey("activated") && hm.get("activated") != null) { company.setActivated(Boolean.TRUE.getBoolean(hm.get("activated").toString())); } company.setModifiedOn(new Date()); if (hm.containsKey("holidays") && hm.get("holidays") != null) { JSONArray jArr = new JSONArray((String) hm.get("holidays")); Set<CompanyHoliday> holidays = company.getHolidays(); holidays.clear(); DateFormat formatter = dateformat; for (int i = 0; i < jArr.length(); i++) { CompanyHoliday day = new CompanyHoliday(); JSONObject obj = jArr.getJSONObject(i); day.setDescription(obj.getString("description")); day.setHolidayDate(formatter.parse(obj.getString("day"))); day.setCompany(company); holidays.add(day); } } if (hm.containsKey("logo") && hm.get("logo") != null && !StringUtil.isNullOrEmpty(hm.get("logo").toString())) { String imageName = ((FileItem) (hm.get("logo"))).getName(); if (imageName != null && imageName.length() > 0) { String fileName = companyid + FileUploadHandler.getCompanyImageExt(); company.setCompanyLogo(Constants.ImgBasePath + fileName); new FileUploadHandler().uploadImage((FileItem) hm.get("logo"), fileName, storageHandlerImpl.GetProfileImgStorePath(), 130, 25, true, false); } } save(company); ll = new ArrayList(); ll.add(company); dl = ll.size(); } catch (Exception e) { throw ServiceException.FAILURE("companyDetailsDAOImpl.updateCompany", e); } return new KwlReturnObject(true, KWLErrorMsgs.S01, "", ll, dl); }
From source file:com.msds.km.controller.BespeakController.java
@RequestMapping("/toBespeak") public ModelAndView toBespeak(BespeakEntity entity, HttpServletRequest request) throws Exception { String sn = codeGenerator.getCode(CodeType.BESPEAK_ID_PREFIX, "", CodeTypeEnum.bespeak_code.getId()); entity.setBespeakSn(sn);// ww w.j a v a 2 s . c o m //?? DateFormat format1 = new SimpleDateFormat("yyyy-MM-dd"); entity.setStartDate(format1.parse(format1.format(new Date()))); request.setAttribute("bespeak", entity); return forword("/km/bespeak/bespeak_edit", null); }
From source file:ch.icclab.cyclops.support.database.influxdb.client.InfluxDBClient.java
private void savePoint(String message, InfluxDB influxDB) { try {/*ww w. j a v a2 s .c o m*/ System.out.println(" [x] Received '" + message + "'"); JSONObject msg = new JSONObject(message); DateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss"); Date date = format.parse(msg.get("dateModified").toString()); long timeMillisec = date.getTime(); Point event2add = Point.measurement("events").time(timeMillisec, TimeUnit.MILLISECONDS) .field("id", msg.get("id")).field("status", msg.get("status")) .field("billingmodel", msg.get("billingModel").toString()) .field("producttype", msg.get("productType").toString()) .field("productid", msg.get("productId").toString()) .field("instanceid", msg.get("instanceId").toString()).field("setupcost", msg.get("setupCost")) .field("periodcost", msg.get("periodCost")).field("period", msg.get("period")) .field("providerid", msg.get("providerId").toString()) .field("clientid", msg.get("clientId").toString()).field("startdate", msg.get("startDate")) .field("lastbilldate", msg.get("lastBillDate")) .field("agreementid", msg.get("agreementId").toString()) .field("relatives", msg.get("relatives")).field("renew", msg.get("renew")) .field("dateCreated", msg.get("dateCreated")).field("priceUnit", msg.get("priceUnit")).build(); BatchPoints batchPoints = giveMeEmptyContainer(); batchPoints.point(event2add); saveContainerToDB(batchPoints); //influxDB.write(load.configuration.get("dbName"), "default", event2add); } catch (Exception ex) { System.err.println("Caught exception in client thread: " + ex.getMessage()); } }
From source file:net.qvex.dommel.data.DommelDataService.java
public boolean getData(String username, String password) throws ClientProtocolException, IOException { // adapted from phptelemeter unlimited = false;/* ww w . j a va 2s .c om*/ /* login */ Map<String, String> urlParameters = new HashMap<String, String>(); urlParameters.put("op", "login"); urlParameters.put("new_language", "english"); urlParameters.put("submit", "login"); urlParameters.put("username", username); urlParameters.put("password", password); String res; // try{ res = this.httpPost(URL_LOGIN, urlParameters); // // }catch(Exception e) // { // // TODO: check for errors in res. possibly just catch nullpointer // // exception.. // throw new Exception(e); // } /* go to the packages page, and get the serv_id and client_id */ res = this.httpGet(URL_PACKAGES); // TODO: check for errors in res String[] lines = res.split("\n"); String log = null; int pos = 0; /* figure out the stats exact url */ for (int i = 0; i < lines.length; i++) { pos = lines[i].indexOf(URL_STATS_INIT); if (pos >= 0) { log = lines[i].substring(pos); break; } } String url_stats = log.substring(0, log.indexOf("'")); /* and get the data */ String data = this.httpGet(url_stats); /* logout */ res = this.httpGet(URL_LOGOUT); lines = data.split("/n"); String data2 = null; pos = 0; /* find the entry position */ for (int i = 0; i < lines.length; i++) { pos = lines[i].indexOf("total traffic downloaded in broadband"); if (pos >= 0) { data2 = lines[i].substring(pos); break; } } lines = data2.split("<br>"); /* set some default positions */ int pos_remaining = -1; int pos_traffic = -1; int pos_reset_date = -1; int pos_total = -1; @SuppressWarnings("unused") int strpos_total = -1; /* position finding & data cleanup */ for (int i = 0; i < lines.length; i++) { lines[i] = stripTags(lines[i]); //System.out.println(lines[i]); if (lines[i].contains("total traffic downloaded")) { pos_traffic = i; } else if (lines[i].contains("next counter reset")) { pos_reset_date = i; } else if (lines[i].contains("remaining")) { pos_remaining = i; if (lines[i].contains("unlimited")) { unlimited = true; } } else if (lines[i].contains("maximum datatransfer")) { pos_total = i; /* data cleanup */ int test_ind = lines[i].indexOf("maximum datatransfer:"); if (test_ind >= 0 && test_ind + 1 < lines[i].length()) { lines[i] = lines[i].substring(test_ind + 21); } } /* data cleanup */ int test_ind = lines[i].indexOf(":"); if (test_ind >= 0 && test_ind + 1 < lines[i].length()) { lines[i] = lines[i].substring(test_ind + 2); } } /* stats */ /* total used */ volume_used = Float.parseFloat(lines[pos_traffic].substring(0, lines[pos_traffic].length() - 3)) * 1024; volume_remaining = 0; /* remaining, if exists? */ if (pos_remaining >= 0) { if (!unlimited) { volume_remaining = Float .parseFloat(lines[pos_remaining].substring(0, lines[pos_remaining].length() - 3)) * 1024; if (pos_total >= 0) { volume_total = Float.parseFloat(lines[pos_total].substring(0, 4)) * 1024; } } else { // Unlimited account volume_remaining = Float.POSITIVE_INFINITY; } } /* reset date */ String reset_date_str = lines[pos_reset_date].substring(0, 10); DateFormat df = new SimpleDateFormat("dd/MM/yyyy"); try { reset_date.setTime(df.parse(reset_date_str)); } catch (ParseException e) { e.printStackTrace(); // TODO: handle error return false; } days_left = calculateDaysLeft(reset_date); Date now = new Date(); Editor edit = prefs.edit(); edit.putFloat("volume_used", volume_used); edit.putFloat("volume_remaining", volume_remaining); edit.putFloat("volume_total", volume_total); edit.putLong("reset_date", reset_date.getTimeInMillis()); edit.putInt("days_left", days_left); edit.putBoolean("unlimited", unlimited); edit.putLong("last_update", now.getTime()); edit.putBoolean("last_update_success", true); return edit.commit(); }
From source file:com.registryKit.client.engagementDAO.java
/** * The 'updateEngagementFields' will update the fields from the engagement form * /*w ww .ja v a2s. co m*/ * @param engagementId The id of the engagement being updated * @param tableName The table to be updated * @param tableCol The column to update * @param tableValue The new value to save into the column */ public void updateEngagementFields(boolean newEnagement, Integer engagementId, Integer clientId, String tableName, String tableCol, String fieldValue, String currFieldValue, Integer fieldId, Integer fieldType, Integer systemUserId) throws Exception { String sqlQuery; /* Check to see if the table is a patient table */ if (tableName.contains("patient")) { /* Check to see if the field is a date field */ if (fieldType == 6) { DateFormat format = new SimpleDateFormat("MM/dd/yyyy", Locale.ENGLISH); Date date = format.parse(fieldValue); Timestamp timestamp = new Timestamp(date.getTime()); sqlQuery = "update " + tableName + " set " + tableCol + " = '" + timestamp + "' where programpatientId = " + clientId; } else { sqlQuery = "update " + tableName + " set " + tableCol + " = '" + fieldValue + "' where programpatientId = " + clientId; } Query query = sessionFactory.getCurrentSession().createSQLQuery(sqlQuery); query.executeUpdate(); } else { /* See if an entry exists in the table */ Query findEngagement = sessionFactory.getCurrentSession() .createSQLQuery("select id from " + tableName + " where engagementId = " + engagementId); if (findEngagement.list().size() > 0) { if (fieldValue != null) { if (fieldType == 6) { DateFormat format = new SimpleDateFormat("MM/dd/yyyy", Locale.ENGLISH); Date date = format.parse(fieldValue); Timestamp timestamp = new Timestamp(date.getTime()); sqlQuery = "update " + tableName + " set " + tableCol + " = '" + timestamp + "' where engagementId = " + engagementId; } else { /* If fieldValue contain multilple items then clear out the values first */ if (fieldValue.contains(",") && "storage_engagementMedicalServices".equals(tableName)) { String deleteQuery = "delete from " + tableName + " where engagementId = " + engagementId + " and engagementFieldId = " + fieldId; Query query = sessionFactory.getCurrentSession().createSQLQuery(deleteQuery); query.executeUpdate(); List<String> fieldValues = Arrays.asList(fieldValue.split(",")); sqlQuery = "insert into " + tableName + " (engagementId, engagementFieldId, codeId, " + tableCol + ") values "; for (Iterator it = fieldValues.iterator(); it.hasNext();) { String itValue = it.next().toString(); if (itValue.contains("~")) { Integer codeId = 0; String textValue = ""; List<String> values = Arrays.asList(itValue.split("~")); codeId = Integer.parseInt(values.get(0)); textValue = values.get(1); sqlQuery += "(" + engagementId + "," + fieldId + "," + codeId + ", '" + textValue + "')"; } else { sqlQuery += "(" + engagementId + "," + fieldId + ",0, '" + itValue + "')"; } if (it.hasNext()) { sqlQuery += ","; } } } else { sqlQuery = "update " + tableName + " set " + tableCol + " = '" + fieldValue + "' where engagementId = " + engagementId; } } Query query = sessionFactory.getCurrentSession().createSQLQuery(sqlQuery); query.executeUpdate(); /* Insert the modified entry */ if (!newEnagement && !currFieldValue.equals(fieldValue)) { modifiedEngagementFields modifiedField = new modifiedEngagementFields(); modifiedField.setFieldId(fieldId); modifiedField.setEngagementId(engagementId); modifiedField.setSystemUserId(systemUserId); String oldFieldValue = ""; if (currFieldValue.contains(",")) { List<String> currfieldValues = Arrays.asList(currFieldValue.split(",")); for (Iterator it = currfieldValues.iterator(); it.hasNext();) { String itValue = it.next().toString(); if (itValue.contains("~")) { List<String> values = Arrays.asList(itValue.split("~")); oldFieldValue += values.get(1); } else { oldFieldValue += itValue; } if (it.hasNext()) { oldFieldValue += ","; } } } else { oldFieldValue = currFieldValue; } modifiedField.setOldFieldValue(oldFieldValue); String newFieldValue = ""; if (fieldValue.contains(",")) { List<String> newfieldValues = Arrays.asList(fieldValue.split(",")); for (Iterator it = newfieldValues.iterator(); it.hasNext();) { String itValue = it.next().toString(); if (itValue.contains("~")) { List<String> values = Arrays.asList(itValue.split("~")); newFieldValue += values.get(1); } else { newFieldValue += itValue; } if (it.hasNext()) { newFieldValue += ","; } } } else { newFieldValue = fieldValue; } modifiedField.setNewFieldValue(newFieldValue); sessionFactory.getCurrentSession().save(modifiedField); } } } else { if (fieldType == 6) { DateFormat format = new SimpleDateFormat("MM/dd/yyyy", Locale.ENGLISH); Date date = format.parse(fieldValue); Timestamp timestamp = new Timestamp(date.getTime()); sqlQuery = "insert into " + tableName + " (engagementId, " + tableCol + ") values (" + engagementId + ",'" + timestamp + "')"; Query insertQuery = sessionFactory.getCurrentSession().createSQLQuery(sqlQuery); insertQuery.executeUpdate(); } else { sqlQuery = "insert into " + tableName + " (engagementId, " + tableCol + ") values (" + engagementId + ",'" + fieldValue + "')"; Query insertQuery = sessionFactory.getCurrentSession().createSQLQuery(sqlQuery); insertQuery.executeUpdate(); } } } }
From source file:com.liferay.portal.upgrade.util.Table.java
public void setColumn(PreparedStatement ps, int index, Integer type, String value) throws Exception { int t = type.intValue(); int paramIndex = index + 1; if (t == Types.BIGINT) { ps.setLong(paramIndex, GetterUtil.getLong(value)); } else if (t == Types.BOOLEAN) { ps.setBoolean(paramIndex, GetterUtil.getBoolean(value)); } else if ((t == Types.CLOB) || (t == Types.VARCHAR)) { value = StringUtil.replace(value, SAFE_CHARS[1], SAFE_CHARS[0]); ps.setString(paramIndex, value); } else if (t == Types.DOUBLE) { ps.setDouble(paramIndex, GetterUtil.getDouble(value)); } else if (t == Types.FLOAT) { ps.setFloat(paramIndex, GetterUtil.getFloat(value)); } else if (t == Types.INTEGER) { ps.setInt(paramIndex, GetterUtil.getInteger(value)); } else if (t == Types.SMALLINT) { ps.setShort(paramIndex, GetterUtil.getShort(value)); } else if (t == Types.TIMESTAMP) { if (StringPool.NULL.equals(value)) { ps.setTimestamp(paramIndex, null); } else {// www. j a v a 2 s .c o m DateFormat df = DateUtil.getISOFormat(); ps.setTimestamp(paramIndex, new Timestamp(df.parse(value).getTime())); } } else { throw new UpgradeException("Upgrade code using unsupported class type " + type); } }
From source file:com.charts.OneMonthChart.java
protected OHLCDataItem[] getData(YStockQuote currentStock) throws ParseException { ArrayList<OHLCDataItem> dataItems = new ArrayList<OHLCDataItem>(); DateFormat df; if (currentStock instanceof Index) df = new SimpleDateFormat("y-MM-dd"); else/* w w w.j a va 2s .c o m*/ df = new SimpleDateFormat("d-MM-yy"); String oneMonthDate = df.format(DayRange.one_month); ArrayList<String> historicalData = currentStock.get_historical_data(); int length = historicalData.size(); for (int i = 1; i < length; i++) { String[] data = historicalData.get(i).split(","); Date date = df.parse(data[0]); double open = Double.parseDouble(data[1]); double high = Double.parseDouble(data[2]); double low = Double.parseDouble(data[3]); double close = Double.parseDouble(data[4]); this.close.addOrUpdate(new Day(date), close); double volume; try { volume = Double.parseDouble(data[5]); } catch (NumberFormatException nfe) { volume = 0; } if (data[0].equals(oneMonthDate)) { break; } OHLCDataItem item = new OHLCDataItem(date, open, high, low, close, volume); dataItems.add(item); } Collections.reverse(dataItems); OHLCDataItem[] OHLCData = dataItems.toArray(new OHLCDataItem[dataItems.size()]); return OHLCData; }
From source file:com.msds.km.controller.BespeakController.java
/** * ?// w w w .j a v a 2s .co m * * @param entity * @param request * @return * @throws Exception */ @RequestMapping(value = "/getBespeak") @ResponseBody public ModelAndView getBespeak(BespeakEntity entity, HttpServletRequest requestd) { BespeakEntity bespeak = new BespeakEntity(); ; try { bespeak = bespeakService.findByBespeakId(entity); bespeak.setIsEdit(entity.getIsEdit()); DateFormat format1 = new SimpleDateFormat("yyyy-MM-dd"); bespeak.setStartDate(format1.parse(format1.format(new Date()))); requestd.setAttribute("bespeak", bespeak); } catch (Exception e) { logger.info("?id{}", entity.getId()); } return forword("/km/bespeak/bespeak_edit", null); }