List of usage examples for java.sql Timestamp getTime
public long getTime()
From source file:com.tesora.dve.sql.CurrentTimestampDefaultValueTest.java
@Test public void testTimezoneVariableChange() throws Throwable { // set timezone to UTC+1 conn.execute("set time_zone='+01:00'"); // insert a row into the test table and get the timestamp value back conn.execute("create table `tz` (`id` int, `ts` timestamp default current_timestamp, primary key (`id`)) "); conn.execute("insert into `tz` (`id`) values (1)"); ResourceResponse resp = conn.fetch("select ts from tz where id=1"); List<ResultRow> rows = resp.getResults(); assertEquals("Expected one row only", 1, rows.size()); Timestamp utcValue = (Timestamp) (rows.get(0).getResultColumn(1).getColumnValue()); // change the timezone and do the select again conn.execute("set time_zone='+02:00'"); resp = conn.fetch("select ts from tz where id=1"); rows = resp.getResults();/* w ww . jav a2 s .c o m*/ assertEquals("Expected one row only", 1, rows.size()); Timestamp newTZValue = (Timestamp) (rows.get(0).getResultColumn(1).getColumnValue()); // there should be a 1 hour difference now between the selected timestamp values // because of the time_zone change long timeDiff = TimeUnit.MILLISECONDS.toHours(newTZValue.getTime() - utcValue.getTime()); assertTrue("Changing time_zone variable should alter returned timestamp value.", timeDiff == 1); }
From source file:edu.ku.brc.specify.toycode.RegAdder.java
/** * @param mv/*w w w.ja va 2 s. com*/ */ private void insertTrack(final HashMap<String, String> mv) { if (mv.size() > 0) { /* +------------------+-------------+------+-----+---------+----------------+ | Field | Type | Null | Key | Default | Extra | +------------------+-------------+------+-----+---------+----------------+ | TrackID | int(11) | NO | PRI | NULL | auto_increment | | TimestampCreated | datetime | NO | | NULL | | | Id | varchar(64) | YES | | NULL | | | CountAmt | int(11) | YES | | NULL | | +------------------+-------------+------+-----+---------+----------------+ 4 rows in set (0.00 sec) mysql> describe trackitem; +-------------+-------------+------+-----+---------+----------------+ | Field | Type | Null | Key | Default | Extra | +-------------+-------------+------+-----+---------+----------------+ | TrackItemID | int(11) | NO | PRI | NULL | auto_increment | | Name | varchar(64) | NO | | NULL | | | CountAmt | int(11) | YES | | NULL | | | Value | varchar(64) | YES | | NULL | | | TrackID | int(11) | NO | MUL | NULL | | +-------------+-------------+------+-----+---------+----------------+ */ try { String id = mv.get("id"); String ip = mv.get("IP"); if (StringUtils.isNotEmpty(id) && (ip == null || !ip.startsWith("129.237.201"))) { cnt++; if (cnt % 100 == 0) { System.out.println(cnt); } int recCnt = BasicSQLUtils .getCountAsInt(String.format("SELECT COUNT(*) FROM track WHERE Id = '%s'", id)); if (recCnt == 0) // Insert { Timestamp timeStamp = getTimestamp(mv.get("date")); if (timeStamp.getTime() < startDate) return; trkStmt1.setTimestamp(1, timeStamp); trkStmt1.setString(2, id); trkStmt1.setInt(3, 1); //pStmt.toString(); if (trkStmt1.executeUpdate() == 1) { recCnt++; if (recCnt % 100 == 0) { System.out.println(recCnt); } Integer trkId = BasicSQLUtils.getInsertedId(trkStmt1); doTrackInserts(trkId, mv, trkStmt2); } else { throw new RuntimeException("Error insert track for ID: " + id); } } else // Update { recCnt = BasicSQLUtils .getCountAsInt(String.format("SELECT CountAmt FROM track WHERE Id = '%s'", id)) + 1; Integer trackId = BasicSQLUtils .getCount(String.format("SELECT TrackID FROM track WHERE Id = '%s'", id)); if (trackId != null) { trkStmt4.setInt(1, recCnt); trkStmt4.setInt(2, trackId); if (trkStmt4.executeUpdate() == 1) { for (String key : mv.keySet()) { String sql = String.format( "SELECT TrackItemID FROM trackitem WHERE TrackID = %d AND Name ='%s'", trackId, key); Integer trackItemId = BasicSQLUtils.getCount(sql); if (trackItemId == null) // Insert { doTrackInserts(trackId, mv, trkStmt2); } else // Update { doTrackUpdate(trackItemId, mv.get(key), trkStmt3); } } } else { log.error(trkStmt4.toString()); log.error("Error updating " + id); } } } } } catch (SQLException ex) { for (String k : mv.keySet()) { System.out.println("[" + k + "][" + mv.get(k) + "]"); } System.err.println("------------------------ Line No: " + lineNo); ex.printStackTrace(); } } }
From source file:edu.ku.brc.specify.toycode.RegAdder.java
/** * @param mv// w w w. j a va 2s. c om */ private void insertReg(final HashMap<String, String> mv) { if (mv.size() > 0) { /* +------------------+-------------+------+-----+---------+----------------+ | Field | Type | Null | Key | Default | Extra | +------------------+-------------+------+-----+---------+----------------+ | RegisterID | int(11) | NO | PRI | NULL | auto_increment | | TimestampCreated | datetime | NO | | NULL | | | RegNumber | varchar(32) | YES | UNI | NULL | | | RegType | varchar(32) | YES | | NULL | | +------------------+-------------+------+-----+---------+----------------+ 4 rows in set (0.00 sec) mysql> describe registeritem; +----------------+-------------+------+-----+---------+----------------+ | Field | Type | Null | Key | Default | Extra | +----------------+-------------+------+-----+---------+----------------+ | RegisterItemID | int(11) | NO | PRI | NULL | auto_increment | | Name | varchar(32) | NO | | NULL | | | CountAmt | int(11) | YES | | NULL | | | Value | varchar(64) | YES | | NULL | | | RegisterID | int(11) | NO | MUL | NULL | | +----------------+-------------+------+-----+---------+----------------+ */ try { String type = mv.get("reg_type"); String num = mv.get("reg_number"); String ip = mv.get("ip"); boolean isNotLocalIP = ip == null || (!ip.startsWith("129.237.201") && !ip.startsWith("24.124")); if (StringUtils.isNotEmpty(type) && StringUtils.isNotEmpty(num) && isNotLocalIP) { int numRegNum = BasicSQLUtils.getCountAsInt( String.format("SELECT COUNT(*) FROM register WHERE RegNumber = '%s'", num)); if (numRegNum > 0) { return; } Timestamp timeStamp = getTimestamp(mv.get("date")); if (timeStamp.getTime() < startDate) return; regStmt1.setTimestamp(1, timeStamp); regStmt1.setString(2, num); regStmt1.setString(3, type); regStmt1.setString(4, ip); //pStmt.toString(); if (regStmt1.executeUpdate() == 1) { cnt++; if (cnt % 100 == 0) { System.out.println(cnt); } Integer regId = BasicSQLUtils.getInsertedId(regStmt1); for (String key : mv.keySet()) { String value = mv.get(key); regStmt2.setString(1, key); if (!StringUtils.contains(value, ".") && StringUtils.isNumeric(value) && value.length() < 10) { regStmt2.setInt(2, value.isEmpty() ? 0 : Integer.parseInt(value)); regStmt2.setNull(3, java.sql.Types.VARCHAR); } else if (value.length() < STR_SIZE + 1) { regStmt2.setNull(2, java.sql.Types.INTEGER); regStmt2.setString(3, value); } else { String v = value.substring(0, STR_SIZE); System.err.println("Error - On line " + lineNo + " Value[" + value + "] too big trunccating to[" + v + "]"); regStmt2.setNull(2, java.sql.Types.INTEGER); regStmt2.setString(3, v); } regStmt2.setInt(4, regId); //System.out.println(pStmt2.toString()); int rv = regStmt2.executeUpdate(); if (rv != 1) { for (String k : mv.keySet()) { System.out.println("[" + k + "][" + mv.get(k) + "]"); } System.err.println("------------------------ Line No: " + lineNo); throw new RuntimeException("Error insert registeritem for Reg Id: " + regId); } } } else { throw new RuntimeException("Error insert register for Reg Type: " + type + " Num: " + num); } } else if (isNotLocalIP) { System.err.println("------------------------ Line No: " + lineNo); System.err.println("Error for Reg Type: [" + type + "] or Num: [" + num + "] is null."); } } catch (SQLException ex) { for (String k : mv.keySet()) { System.out.println("[" + k + "][" + mv.get(k) + "]"); } System.err.println("------------------------ Line No: " + lineNo); ex.printStackTrace(); } } }
From source file:it.cnr.icar.eric.server.persistence.rdb.SubscriptionDAO.java
@SuppressWarnings("unchecked") protected void loadObject(Object obj, ResultSet rs) throws RegistryException { try {/* www . j a v a 2s.co m*/ if (!(obj instanceof SubscriptionType)) { throw new RegistryException(ServerResourceBundle.getInstance() .getString("message.SubscriptionTypeExpected", new Object[] { obj })); } SubscriptionType ebSubscriptionType = (SubscriptionType) obj; super.loadObject(obj, rs); String selector = rs.getString("selector"); ebSubscriptionType.setSelector(selector); // Need to work around a bug in PostgreSQL and loading of // ClassificationScheme data from NIST tests try { Timestamp endTimestamp = rs.getTimestamp("endTime"); if (endTimestamp != null) { // Calendar calendar = Calendar.getInstance(); // calendar.setTimeInMillis(endTime.getTime()); GregorianCalendar calendar = new GregorianCalendar(); calendar.setTimeInMillis(endTimestamp.getTime()); XMLGregorianCalendar endTime = DatatypeFactory.newInstance().newXMLGregorianCalendar(calendar); ebSubscriptionType.setEndTime(endTime); } } catch (StringIndexOutOfBoundsException e) { String id = rs.getString("id"); log.error(ServerResourceBundle.getInstance().getString("message.SubscriptionDAOId", new Object[] { id }), e); } String notificationIntervalString = rs.getString("notificationInterval"); if (notificationIntervalString != null) { Duration notificationInterval = DatatypeFactory.newInstance() .newDuration(notificationIntervalString); ebSubscriptionType.setNotificationInterval(notificationInterval); } // Need to work around a bug in PostgreSQL and loading of // ClassificationScheme data from NIST tests try { Timestamp startTimestamp = rs.getTimestamp("startTime"); if (startTimestamp != null) { // Calendar calendar = Calendar.getInstance(); // calendar.setTimeInMillis(startTime.getTime()); GregorianCalendar calendar = new GregorianCalendar(); calendar.setTimeInMillis(startTimestamp.getTime()); XMLGregorianCalendar startTime = DatatypeFactory.newInstance() .newXMLGregorianCalendar(new GregorianCalendar()); ebSubscriptionType.setStartTime(startTime); } } catch (StringIndexOutOfBoundsException e) { String id = rs.getString("id"); log.error(ServerResourceBundle.getInstance().getString("message.SubscriptionDAOId", new Object[] { id }), e); } NotifyActionDAO notifyActionDAO = new NotifyActionDAO(context); notifyActionDAO.setParent(ebSubscriptionType); @SuppressWarnings("rawtypes") List notifyActions = notifyActionDAO.getByParent(); if (notifyActions != null) { bu.getActionTypeListFromElements(ebSubscriptionType.getAction()).addAll(notifyActions); } } catch (SQLException e) { log.error(ServerResourceBundle.getInstance().getString("message.CaughtException1"), e); throw new RegistryException(e); } catch (DatatypeConfigurationException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
From source file:nl.sidn.pcap.parquet.DNSParquetPacketWriter.java
private void writeProctime(Packet reqTransport, Packet respTransport, GenericRecordBuilder builder) { if (reqTransport != null && respTransport != null) { Timestamp reqTs = new Timestamp((reqTransport.getTs() * 1000000)); Timestamp respTs = new Timestamp((respTransport.getTs() * 1000000)); //from second to microseconds long millis1 = respTs.getTime() - reqTs.getTime(); long millis2 = (respTransport.getTsmicros() - reqTransport.getTsmicros()); builder.set("proc_time", millis1 + millis2); }//from ww w . jav a2s .c o m }
From source file:org.kuali.rice.kew.impl.document.WorkflowDocumentServiceImpl.java
@Override public List<DateTime> getSearchableAttributeDateTimeValuesByKey(String documentId, String key) { if (StringUtils.isEmpty(documentId)) { throw new RiceIllegalArgumentException("documentId was blank or null"); }/*from w ww.j ava 2 s . com*/ if (StringUtils.isEmpty(key)) { throw new RiceIllegalArgumentException("key was blank or null"); } List<Timestamp> results = KEWServiceLocator.getRouteHeaderService() .getSearchableAttributeDateTimeValuesByKey(documentId, key); if (results == null) { return null; } List<DateTime> dateTimes = new ArrayList<DateTime>(); for (Timestamp time : results) { dateTimes.add(new DateTime(time.getTime())); } return dateTimes; }
From source file:org.projectforge.business.task.TaskDao.java
/** * Gets the total duration of all time sheets of the given task (excluding the child tasks). * /*from www.j a v a 2 s .c o m*/ * @param node * @return */ @Transactional(readOnly = true, propagation = Propagation.SUPPORTS) public long readTotalDuration(final Integer taskId) { log.debug("Calculating duration for all tasks"); final String intervalInSeconds = DatabaseSupport.getInstance().getIntervalInSeconds("startTime", "stopTime"); if (intervalInSeconds != null) { @SuppressWarnings("unchecked") final List<Object> list = (List<Object>) getHibernateTemplate() .find("select " + DatabaseSupport.getInstance().getIntervalInSeconds("startTime", "stopTime") + " from TimesheetDO where task.id = ? and deleted=false", taskId); if (list.size() == 0) { return new Long(0); } Validate.isTrue(list.size() == 1); if (list.get(0) == null) { // Has happened one time, why (PROJECTFORGE-543)? return new Long(0); } else if (list.get(0) instanceof Integer) { return new Long((Integer) list.get(0)); } else { return (Long) list.get(0); } } @SuppressWarnings("unchecked") final List<Object[]> result = (List<Object[]>) getHibernateTemplate() .find("select startTime, stopTime from TimesheetDO where task.id = ? and deleted=false", taskId); if (CollectionUtils.isEmpty(result) == true) { return new Long(0); } long totalDuration = 0; for (final Object[] oa : result) { final Timestamp startTime = (Timestamp) oa[0]; final Timestamp stopTime = (Timestamp) oa[1]; final long duration = stopTime.getTime() - startTime.getTime(); totalDuration += duration; } return totalDuration / 1000; }
From source file:controller.ISLogin.java
protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("application/json"); try (PrintWriter out = response.getWriter()) { String email = request.getParameter("email"); String password = request.getParameter("password"); JSONObject object = new JSONObject(); if (email != null && password != null) { String sql = "SELECT * FROM user WHERE email = ? AND password = SHA1(?)"; try (PreparedStatement statement = conn.prepareStatement(sql)) { statement.setString(1, email); statement.setString(2, password); ResultSet result = statement.executeQuery(); if (result.next()) { int u_id = result.getInt("u_id"); String uuid = UUID.randomUUID().toString().replaceAll("-", ""); Calendar time = Calendar.getInstance(); time.setTime(new Date()); time.add(Calendar.HOUR, 2); conn.setAutoCommit(false); String delete = "DELETE from token WHERE u_id = ?"; String insert = "INSERT INTO token (access_token, u_id, expiry_date)" + "VALUES (?, ?, ?)"; try (PreparedStatement deleteStatement = conn.prepareStatement(delete); PreparedStatement insertStatement = conn.prepareStatement(insert);) { deleteStatement.setInt(1, u_id); Timestamp timestamp = new Timestamp(time.getTimeInMillis()); insertStatement.setString(1, uuid); insertStatement.setInt(2, u_id); insertStatement.setTimestamp(3, timestamp); deleteStatement.execute(); insertStatement.execute(); object.put("token", uuid); object.put("expiry_date", timestamp.getTime()); conn.commit();//from ww w.j a va 2s .co m } finally { conn.setAutoCommit(true); } } else { object.put("error", "Invalid email or password"); } } catch (SQLException e) { e.printStackTrace(); } } else { object.put("error", "Empty email or password"); } out.println(object.toString()); } }
From source file:com.rogchen.common.xml.UtilDateTime.java
/** * Timestamp Calendar//from w ww.j ava2s .co m * * @param stamp * @return */ public static Calendar toCalendar(Timestamp stamp) { Calendar cal = Calendar.getInstance(); if (stamp != null) { cal.setTimeInMillis(stamp.getTime()); } return cal; }
From source file:com.mothsoft.alexis.web.ChartServlet.java
private boolean addSeries(final XYSeriesCollection seriesCollection, final String dataSetName, final List<DataSetPoint> points, final Timestamp startDate, final Integer numberOfSamples, final StandardXYItemRenderer renderer) { // create the series final XYSeries series = new XYSeries(dataSetName); Double total = 0.0d;//w w w . j av a 2s. c o m final Map<Date, Double> rawPoints = new LinkedHashMap<Date, Double>(); final Calendar calendar = new GregorianCalendar(); calendar.setTime(new Date(startDate.getTime())); for (int i = 0; i < numberOfSamples; i++) { rawPoints.put(calendar.getTime(), 0.0d); calendar.add(Calendar.HOUR_OF_DAY, 1); } for (final DataSetPoint ith : points) { final Date date = new Date(ith.getX().getTime()); rawPoints.put(date, ith.getY()); total += ith.getY(); } for (final Map.Entry<Date, Double> entry : rawPoints.entrySet()) { final long x = entry.getKey().getTime(); final Double y = entry.getValue(); logger.debug("Adding point to series: (" + entry.getKey() + ", " + y + ")"); series.add(new XYDataItem(x, (Number) y)); } seriesCollection.addSeries(series); return total > 0; }