List of usage examples for java.sql Timestamp valueOf
@SuppressWarnings("deprecation") public static Timestamp valueOf(LocalDateTime dateTime)
From source file:com.alibaba.wasp.jdbc.TestJdbcResultSet.java
public void testDatetimeWithCalendar() throws SQLException { trace("test DATETIME with Calendar"); ResultSet rs;//ww w. j a va 2s . c om stat = conn.createStatement(); stat.execute("CREATE TABLE test(ID INT PRIMARY KEY, D DATE, T TIME, TS TIMESTAMP)"); PreparedStatement prep = conn.prepareStatement("INSERT INTO test VALUES(?, ?, ?, ?)"); Calendar regular = Calendar.getInstance(); Calendar other = null; // search a locale that has a _different_ raw offset long testTime = java.sql.Date.valueOf("2001-02-03").getTime(); for (String s : TimeZone.getAvailableIDs()) { TimeZone zone = TimeZone.getTimeZone(s); long rawOffsetDiff = regular.getTimeZone().getRawOffset() - zone.getRawOffset(); // must not be the same timezone (not 0 h and not 24 h difference // as for Pacific/Auckland and Etc/GMT+12) if (rawOffsetDiff != 0 && rawOffsetDiff != 1000 * 60 * 60 * 24) { if (regular.getTimeZone().getOffset(testTime) != zone.getOffset(testTime)) { other = Calendar.getInstance(zone); break; } } } trace("regular offset = " + regular.getTimeZone().getRawOffset() + " other = " + other.getTimeZone().getRawOffset()); prep.setInt(1, 0); prep.setDate(2, null, regular); prep.setTime(3, null, regular); prep.setTimestamp(4, null, regular); prep.execute(); prep.setInt(1, 1); prep.setDate(2, null, other); prep.setTime(3, null, other); prep.setTimestamp(4, null, other); prep.execute(); prep.setInt(1, 2); prep.setDate(2, java.sql.Date.valueOf("2001-02-03"), regular); prep.setTime(3, java.sql.Time.valueOf("04:05:06"), regular); prep.setTimestamp(4, Timestamp.valueOf("2007-08-09 10:11:12.131415"), regular); prep.execute(); prep.setInt(1, 3); prep.setDate(2, java.sql.Date.valueOf("2101-02-03"), other); prep.setTime(3, java.sql.Time.valueOf("14:05:06"), other); prep.setTimestamp(4, Timestamp.valueOf("2107-08-09 10:11:12.131415"), other); prep.execute(); prep.setInt(1, 4); prep.setDate(2, java.sql.Date.valueOf("2101-02-03")); prep.setTime(3, java.sql.Time.valueOf("14:05:06")); prep.setTimestamp(4, Timestamp.valueOf("2107-08-09 10:11:12.131415")); prep.execute(); rs = stat.executeQuery("SELECT * FROM test ORDER BY ID"); assertResultSetMeta(rs, 4, new String[] { "ID", "D", "T", "TS" }, new int[] { Types.INTEGER, Types.DATE, Types.TIME, Types.TIMESTAMP }, new int[] { 10, 8, 6, 23 }, new int[] { 0, 0, 0, 10 }); rs.next(); assertEquals(0, rs.getInt(1)); assertTrue(rs.getDate(2, regular) == null && rs.wasNull()); assertTrue(rs.getTime(3, regular) == null && rs.wasNull()); assertTrue(rs.getTimestamp(3, regular) == null && rs.wasNull()); rs.next(); assertEquals(1, rs.getInt(1)); assertTrue(rs.getDate(2, other) == null && rs.wasNull()); assertTrue(rs.getTime(3, other) == null && rs.wasNull()); assertTrue(rs.getTimestamp(3, other) == null && rs.wasNull()); rs.next(); assertEquals(2, rs.getInt(1)); assertEquals("2001-02-03", rs.getDate(2, regular).toString()); assertEquals("04:05:06", rs.getTime(3, regular).toString()); assertFalse(rs.getTime(3, other).toString().equals("04:05:06")); assertEquals("2007-08-09 10:11:12.131415", rs.getTimestamp(4, regular).toString()); assertFalse(rs.getTimestamp(4, other).toString().equals("2007-08-09 10:11:12.131415")); rs.next(); assertEquals(3, rs.getInt("ID")); assertFalse(rs.getTimestamp("TS", regular).toString().equals("2107-08-09 10:11:12.131415")); assertEquals("2107-08-09 10:11:12.131415", rs.getTimestamp("TS", other).toString()); assertFalse(rs.getTime("T", regular).toString().equals("14:05:06")); assertEquals("14:05:06", rs.getTime("T", other).toString()); // checkFalse(rs.getDate(2, regular).toString(), "2101-02-03"); // check(rs.getDate("D", other).toString(), "2101-02-03"); rs.next(); assertEquals(4, rs.getInt("ID")); assertEquals("2107-08-09 10:11:12.131415", rs.getTimestamp("TS").toString()); assertEquals("14:05:06", rs.getTime("T").toString()); assertEquals("2101-02-03", rs.getDate("D").toString()); assertFalse(rs.next()); stat.execute("DROP TABLE test"); }
From source file:org.apache.calcite.runtime.SqlFunctions.java
public static long toLong(String s) { if (s.startsWith("199") && s.contains(":")) { return Timestamp.valueOf(s).getTime(); }/*from w w w .ja va 2 s . c o m*/ return Long.parseLong(s.trim()); }
From source file:org.apache.ofbiz.base.util.UtilHttp.java
/** * Given the prefix of a composite parameter, recomposes a single Object from * the composite according to compositeType. For example, consider the following * form widget field,//from w w w . j a v a 2 s . c om * * <pre> * {@code * <field name="meetingDate"> * <date-time type="timestamp" input-method="time-dropdown"> * </field> * } * </pre> * * The result in HTML is three input boxes to input the date, hour and minutes separately. * The parameter names are named meetingDate_c_date, meetingDate_c_hour, meetingDate_c_minutes. * Additionally, there will be a field named meetingDate_c_compositeType with a value of "Timestamp". * where _c_ is the COMPOSITE_DELIMITER. These parameters will then be recomposed into a Timestamp * object from the composite fields. * * @param request * @param prefix * @return Composite object from data or null if not supported or a parsing error occurred. */ public static Object makeParamValueFromComposite(HttpServletRequest request, String prefix, Locale locale) { String compositeType = request.getParameter(makeCompositeParam(prefix, "compositeType")); if (UtilValidate.isEmpty(compositeType)) return null; // collect the composite fields into a map Map<String, String> data = new HashMap<String, String>(); for (Enumeration<String> names = UtilGenerics.cast(request.getParameterNames()); names.hasMoreElements();) { String name = names.nextElement(); if (!name.startsWith(prefix + COMPOSITE_DELIMITER)) continue; // extract the suffix of the composite name String suffix = name.substring(name.indexOf(COMPOSITE_DELIMITER) + COMPOSITE_DELIMITER_LENGTH); // and the value of this parameter String value = request.getParameter(name); // key = suffix, value = parameter data data.put(suffix, value); } if (Debug.verboseOn()) { Debug.logVerbose("Creating composite type with parameter data: " + data.toString(), module); } // handle recomposition of data into the compositeType if ("Timestamp".equals(compositeType)) { String date = data.get("date"); String hour = data.get("hour"); String minutes = data.get("minutes"); String ampm = data.get("ampm"); if (date == null || date.length() < 10) return null; if (UtilValidate.isEmpty(hour)) return null; if (UtilValidate.isEmpty(minutes)) return null; boolean isTwelveHour = UtilValidate.isNotEmpty(ampm); // create the timestamp from the data try { int h = Integer.parseInt(hour); Timestamp timestamp = Timestamp.valueOf(date.substring(0, 10) + " 00:00:00.000"); Calendar cal = Calendar.getInstance(locale); cal.setTime(timestamp); if (isTwelveHour) { boolean isAM = ("AM".equals(ampm) ? true : false); if (isAM && h == 12) h = 0; if (!isAM && h < 12) h += 12; } cal.set(Calendar.HOUR_OF_DAY, h); cal.set(Calendar.MINUTE, Integer.parseInt(minutes)); return new Timestamp(cal.getTimeInMillis()); } catch (IllegalArgumentException e) { Debug.logWarning("User input for composite timestamp was invalid: " + e.getMessage(), module); return null; } } // we don't support any other compositeTypes (yet) return null; }
From source file:org.wso2.carbon.apimgt.core.dao.impl.ApiDAOImpl.java
@Override public void addComment(Comment comment, String apiId) throws APIMgtDAOException { final String addCommentQuery = "INSERT INTO AM_API_COMMENTS (UUID, COMMENT_TEXT, USER_IDENTIFIER, API_ID, " + "CREATED_BY, CREATED_TIME, UPDATED_BY, LAST_UPDATED_TIME" + ") VALUES (?,?,?,?,?,?,?,?)"; try (Connection connection = DAOUtil.getConnection(); PreparedStatement statement = connection.prepareStatement(addCommentQuery)) { try {//ww w. j a v a 2s .c o m connection.setAutoCommit(false); statement.setString(1, comment.getUuid()); statement.setString(2, comment.getCommentText()); statement.setString(3, comment.getCommentedUser()); statement.setString(4, apiId); statement.setString(5, comment.getCreatedUser()); statement.setTimestamp(6, Timestamp.valueOf(LocalDateTime.now())); statement.setString(7, comment.getUpdatedUser()); statement.setTimestamp(8, Timestamp.valueOf(LocalDateTime.now())); statement.execute(); connection.commit(); } catch (SQLException e) { connection.rollback(); String errorMessage = "Error while adding comment for api id: " + apiId; log.error(errorMessage, e); throw new APIMgtDAOException(e); } finally { connection.setAutoCommit(DAOUtil.isAutoCommit()); } } catch (SQLException e) { log.error("Error while creating database connection/prepared-statement", e); throw new APIMgtDAOException(e); } }
From source file:com.portfolioeffect.quant.client.portfolio.Portfolio.java
public MethodResult setFromTime(String fromTime) { updatePriceData();/*ww w . ja v a2 s . c o m*/ portfolioData.setFromTime(""); if (fromTime.contains("t")) { int daysBack; if (fromTime.trim().equals("t")) { portfolioData.setFromTime(fromTime); return new MethodResult(); } else { String[] a = fromTime.trim().split("-"); try { portfolioData.setFromTime(fromTime); return new MethodResult(); } catch (Exception e) { return new MethodResult(String.format(MessageStrings.WRONG_TIME_FORMAT_FROM, fromTime)); } } } else if (!fromTime.contains(":")) { String s = fromTime.trim() + " 09:30:01"; try { Timestamp t = Timestamp.valueOf(s); portfolioData.setFromTime(fromTime); return new MethodResult(); } catch (Exception e) { return new MethodResult(String.format(MessageStrings.WRONG_TIME_FORMAT_FROM, fromTime)); } } try { Timestamp t = Timestamp.valueOf(fromTime); } catch (Exception e) { return new MethodResult(String.format(MessageStrings.WRONG_TIME_FORMAT_FROM, fromTime)); } portfolioData.setFromTime(fromTime); return new MethodResult(); }
From source file:org.wso2.carbon.apimgt.core.dao.impl.ApiDAOImpl.java
@Override public void updateComment(Comment comment, String commentId, String apiId) throws APIMgtDAOException { final String updateCommentQuery = "UPDATE AM_API_COMMENTS SET COMMENT_TEXT = ? " + ", UPDATED_BY = ? , LAST_UPDATED_TIME = ?" + " WHERE UUID = ? AND API_ID = ?"; try (Connection connection = DAOUtil.getConnection(); PreparedStatement statement = connection.prepareStatement(updateCommentQuery)) { try {/*www .j a v a2s .c o m*/ connection.setAutoCommit(false); statement.setString(1, comment.getCommentText()); statement.setString(2, comment.getUpdatedUser()); statement.setTimestamp(3, Timestamp.valueOf(LocalDateTime.now())); statement.setString(4, commentId); statement.setString(5, apiId); statement.execute(); connection.commit(); } catch (SQLException e) { connection.rollback(); String errorMessage = "Error while updating comment for api id: " + apiId + " and comment id: " + commentId; log.error(errorMessage, e); throw new APIMgtDAOException(e); } finally { connection.setAutoCommit(DAOUtil.isAutoCommit()); } } catch (SQLException e) { log.error("Error while creating database connection/prepared-statement", e); throw new APIMgtDAOException(e); } }
From source file:com.krawler.formbuilder.servlet.ReportBuilderDaoImpl.java
public String createNewReport(HttpServletRequest request) throws ServiceException { String result = "{\"success\":true}"; try {//from w w w . j a v a2 s . com String query = "select max(mb_reportlist.reportkey) as count from com.krawler.esp.hibernate.impl.mb_reportlist as mb_reportlist "; List list = executeQuery(query); Iterator ite = list.iterator(); String mkey = ""; if (ite.hasNext()) { Object cnt = (Object) ite.next(); if (cnt == null) { mkey = "1"; } else { mkey = Integer.toString(Integer.parseInt(cnt.toString()) + 1); } } mkey = toLZ(Integer.parseInt(mkey), 3); String reportname = request.getParameter("name");//.replace(" ","").toLowerCase(); // String tableName = "report_"+mkey+"_"+reportname; com.krawler.esp.hibernate.impl.mb_reportlist report = new com.krawler.esp.hibernate.impl.mb_reportlist(); java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat(ModuleBuilderController.USER_DATEPREF); java.sql.Timestamp timestamp1 = Timestamp.valueOf(sdf.format(new java.util.Date())); report.setReportname(reportname); report.setReportkey(Integer.parseInt(mkey)); report.setCreateddate(timestamp1); report.setModifieddate(timestamp1); report.setType(1); report.setCreatedby(sessionHandlerDao.getUserid()); report.setTableflag(Integer.parseInt(request.getParameter("tableflag"))); save(report); // result = "{\"success\":true, \"reportid\":\""+report.getReportid()+"\",\"reportkey\":\""+report.getReportkey()+"\",\"title\":\""+reportname+"\"}"; // String actionType = "Add Report"; // String details = request.getParameter("name") + " Report Added"; // long actionId = AuditTrialHandler.getActionId(session, actionType); //Changes done by sm and anup JSONObject jobj = new JSONObject(); JSONObject jtemp2 = new JSONObject(); jtemp2.put("reportname", report.getReportname()); jtemp2.put("reportid", report.getReportid()); jtemp2.put("tablename", report.getTablename()); jtemp2.put("reportkey", report.getReportkey()); jtemp2.put("createddate", report.getCreateddate()); jtemp2.put("title", reportname); jtemp2.put("id", "report_" + report.getReportid()); jtemp2.put("tableflag", report.getTableflag()); jobj.append("data", jtemp2.toString()); jobj.put("success", "true"); result = jobj.toString(); // AuditTrialHandler.insertAuditLog(session, actionId, details, request); } catch (Exception e) { logger.warn(e.getMessage(), e); result = "{\"success\":false}"; throw ServiceException.FAILURE("reportbuilder.createNewReport", e); } return result; }
From source file:com.portfolioeffect.quant.client.portfolio.Portfolio.java
public MethodResult setToTime(String toTime) { updatePriceData();/* w w w . j ava2 s . c o m*/ portfolioData.setToTime(""); if (toTime.contains("t")) { if (toTime.trim().equals("t")) { portfolioData.setToTime(toTime); return new MethodResult(); } else { String[] a = toTime.trim().split("-"); try { int daysBack = Integer.parseInt(a[1].split("d")[0]); portfolioData.setToTime(toTime); return new MethodResult(); } catch (Exception e) { return new MethodResult(String.format(MessageStrings.WRONG_TIME_FORMAT_TO, toTime)); } } } else if (!toTime.contains(":")) { String s = toTime.trim() + " 09:30:01"; try { Timestamp t = Timestamp.valueOf(s); portfolioData.setToTime(toTime); return new MethodResult(); } catch (Exception e) { return new MethodResult(String.format(MessageStrings.WRONG_TIME_FORMAT_TO, toTime)); } } try { Timestamp t = Timestamp.valueOf(toTime); } catch (Exception e) { return new MethodResult(String.format(MessageStrings.WRONG_TIME_FORMAT_TO, toTime)); } portfolioData.setToTime(toTime); return new MethodResult(); }
From source file:org.wso2.carbon.apimgt.core.dao.impl.ApiDAOImpl.java
@Override public void addRating(String apiId, Rating rating) throws APIMgtDAOException { final String addRatingQuery = "INSERT INTO AM_API_RATINGS (UUID, API_ID, RATING, USER_IDENTIFIER, " + "CREATED_BY, CREATED_TIME, UPDATED_BY, LAST_UPDATED_TIME" + ") VALUES (?,?,?,?,?,?,?,?)"; try (Connection connection = DAOUtil.getConnection(); PreparedStatement statement = connection.prepareStatement(addRatingQuery)) { try {// w ww .ja va 2 s . co m connection.setAutoCommit(false); statement.setString(1, rating.getUuid()); statement.setString(2, apiId); statement.setInt(3, rating.getRating()); statement.setString(4, rating.getUsername()); statement.setString(5, rating.getCreatedUser()); statement.setTimestamp(6, Timestamp.valueOf(LocalDateTime.now())); statement.setString(7, rating.getLastUpdatedUser()); statement.setTimestamp(8, Timestamp.valueOf(LocalDateTime.now())); statement.execute(); connection.commit(); } catch (SQLException e) { connection.rollback(); String errorMessage = "Error while adding rating for api id: " + apiId; log.error(errorMessage, e); throw new APIMgtDAOException(e); } finally { connection.setAutoCommit(DAOUtil.isAutoCommit()); } } catch (SQLException e) { log.error("Error while creating database connection/prepared-statement", e); throw new APIMgtDAOException(e); } }