Example usage for java.sql Timestamp equals

List of usage examples for java.sql Timestamp equals

Introduction

In this page you can find the example usage for java.sql Timestamp equals.

Prototype

public boolean equals(java.lang.Object ts) 

Source Link

Document

Tests to see if this Timestamp object is equal to the given object.

Usage

From source file:Main.java

public static void main(String[] args) {
    java.sql.Timestamp ts1 = java.sql.Timestamp.valueOf("2012-04-06 09:01:10");
    java.sql.Timestamp ts2 = java.sql.Timestamp.valueOf("2013-04-06 09:01:10");

    System.out.println(ts1.equals(ts2));

}

From source file:de.fraunhofer.iosb.ilt.sta.persistence.postgres.PropertyHelper.java

private static TimeValue valueFromTimes(Timestamp timeStart, Timestamp timeEnd) {
    if (timeEnd == null || timeEnd.equals(timeStart)) {
        return instantFromTime(timeStart);
    }/*from  w w  w.  ja v  a2 s .c  o  m*/
    return intervalFromTimes(timeStart, timeEnd);
}

From source file:com.concursive.connect.web.modules.profile.utils.ProjectUtils.java

public static boolean datesDiffer(Timestamp a, Timestamp b) {
    if (a == null && b == null) {
        return false;
    }//from w  w w .j a v  a2  s. c  om
    if (a != null && b == null) {
        return true;
    }
    if (a == null) {
        return true;
    }
    return !a.equals(b);
}

From source file:net.bioclipse.structuredb.persistence.dao.GenericDaoTest.java

/**
 * tests updating an instance of the domain type handled by the tested dao
 *//*from   w  ww . j a v a 2  s.c o  m*/
public void testUpdate() {
    DomainType loadedObject1 = dao.getById(object1.getId());
    Timestamp before = loadedObject1.getEdited();
    dao.update(loadedObject1);
    loadedObject1 = dao.getById(object1.getId());
    assertFalse("timestamp should have changed", before.equals(loadedObject1.getEdited()));
}

From source file:no.trank.openpipe.jdbc.store.StateDocumentProducerTest.java

public void testUpdateModifiedDocuments_RollbackOnFail() throws Exception {
    createValidTable();/*from  w  w  w  .j a  va  2 s . c  o  m*/
    final Timestamp ts = new Timestamp(System.currentTimeMillis());
    Thread.sleep(15); // So test will not fail on Windows
    jdbcTemplate.update(
            "INSERT INTO " + TABLE_NAME + " (" + COL_ID_NAME + ", " + COL_UPD_NAME + ") VALUES (?, ?)", DOC_ID,
            ts);

    // Setting up mock
    final Document doc = new Document();
    doc.setFieldValue(FIELD_ID, DOC_ID);
    final DocumentProducer mockProd = setUpMockProducer(Arrays.asList(doc).iterator(), true);

    final StateDocumentProducer producer = setupProducer(mockProd);
    producer.init();
    final Iterator<Document> it = producer.iterator();
    assertTrue(it.hasNext());
    assertEquals(DocumentOperation.MODIFY_VALUE, it.next().getOperation());
    assertFalse(it.hasNext());
    producer.fail();
    verify(mockProd);
    final String id = jdbcTemplate.queryForObject(getSelectId(), new StringRowMapper(), (Object[]) null);
    assertEquals(DOC_ID, id);
    final Timestamp upd = jdbcTemplate.queryForObject(getSelectUpd(), new TimestampRowMapper(),
            (Object[]) null);
    assertTrue(upd.equals(ts));
}

From source file:dk.nsi.sdm4.dosering.parser.DoseringParserIntegrationTest.java

@Test
public void testImportUpdatesModifiedDate() throws Exception {
    runImporter();// w  w  w  .  j  a  v a  2  s  . c  o  m
    Timestamp modified1 = jdbcTemplate.queryForObject("SELECT ModifiedDate FROM DosageDrug LIMIT 1",
            Timestamp.class);
    Thread.sleep(1000);
    jdbcTemplate.update("UPDATE DosageVersion SET releaseNumber=124");
    drugsFile = getFile("multiple/Drugs.json");
    runImporter();

    Timestamp modified2 = jdbcTemplate.queryForObject(
            "SELECT ModifiedDate FROM DosageDrug ORDER BY ModifiedDate DESC LIMIT 1", Timestamp.class);
    assertFalse(modified1.equals(modified2));
}

From source file:name.wramner.jmstools.analyzer.DataProvider.java

/**
 * Get list with flight time metrics per minute.
 *
 * @return list with flight time metrics.
 *//*from  w w w. j  ava2s. co  m*/
public List<FlightTimeMetrics> getFlightTimeMetrics() {
    if (_flightTimeMetrics != null) {
        return _flightTimeMetrics;
    }
    List<FlightTimeMetrics> list = new ArrayList<>();
    try (Statement stat = _conn.createStatement();
            ResultSet rs = stat.executeQuery("select trunc(produced_time, 'mi'), flight_time_millis"
                    + " from message_flight_time order by 1")) {
        if (rs.next()) {
            Timestamp lastTime = rs.getTimestamp(1);
            MutableIntList flightTimes = IntLists.mutable.empty();
            do {
                Timestamp time = rs.getTimestamp(1);
                int flightTimeMillis = rs.getInt(2);
                if (!time.equals(lastTime)) {
                    list.add(computeFlightTimeMetrics(lastTime, flightTimes));
                    flightTimes.clear();
                    lastTime = time;
                }
                flightTimes.add(flightTimeMillis);
            } while (rs.next());
            if (!flightTimes.isEmpty()) {
                list.add(computeFlightTimeMetrics(lastTime, flightTimes));
            }
        }
        return (_flightTimeMetrics = list);
    } catch (SQLException e) {
        throw new UncheckedSqlException(e);
    }
}

From source file:dk.dbc.rawrepo.oai.OAIIdentifierCollection.java

/**
 * Fetch identifiers from database//w w  w .  jav a2 s  .c om
 *
 * json argument is object with: null null null null null     {@literal
 * f: fromTimestamp*
 * u: untilTimestamp*
 * m: metadataPrefix
 * o: fromOffset (how many records with fromTimestamp has been seen)*
 * s: set*
 * }
 *
 * @param json  as described
 * @param limit how many records to fetch
 * @return json as described or null if no more records
 */
@SuppressFBWarnings("SQL_PREPARED_STATEMENT_GENERATED_FROM_NONCONSTANT_STRING")
public ObjectNode fetch(ObjectNode json, int limit) {
    log.debug("limit = " + limit);
    StringBuilder sb = new StringBuilder();
    String set = json.path("s").asText(null);
    String from = json.path("f").asText(null);
    String until = json.path("u").asText(null);
    String metadataPrefix = json.path("m").asText("");
    int offset = json.path("o").asInt(0);
    sb.append("SELECT pid, changed, deleted FROM oairecords JOIN oairecordsets USING (pid) WHERE");
    if (set != null) {
        sb.append(" setSpec = ?");
    } else if (allowedSets.isEmpty()) {
        return null;
    } else {
        sb.append(" setSpec IN ('");
        sb.append(allowedSets.stream().sorted().collect(Collectors.joining("', '")));
        sb.append("')");
    }
    sb.append(" AND ? in (SELECT prefix FROM oaiformats)");

    if (from != null) {
        sb.append(" AND");
        if (from.contains(".")) {
            sb.append(
                    " DATE_TRUNC('milliseconds', changed) >= DATE_TRUNC('milliseconds', ?::timestamp AT TIME ZONE 'UTC')");
        } else if (from.contains("T")) {
            sb.append(
                    " DATE_TRUNC('second', changed) >= DATE_TRUNC('second', ?::timestamp AT TIME ZONE 'UTC')");
        } else {
            sb.append(" DATE_TRUNC('day', changed) >= DATE_TRUNC('day', ?::timestamp AT TIME ZONE 'UTC')");
        }
    }
    if (until != null) {
        sb.append(" AND");
        if (until.contains(".")) {
            sb.append(
                    " DATE_TRUNC('milliseconds', changed) <= DATE_TRUNC('milliseconds', ?::timestamp AT TIME ZONE 'UTC')");
        } else if (until.contains("T")) {
            sb.append(
                    " DATE_TRUNC('second', changed) <= DATE_TRUNC('second', ?::timestamp AT TIME ZONE 'UTC')");
        } else {
            sb.append(" DATE_TRUNC('day', changed) <= DATE_TRUNC('day', ?::timestamp AT TIME ZONE 'UTC')");
        }
    }
    sb.append(" GROUP BY pid");
    if (set != null) {
        sb.append(", gone");
    }
    sb.append(" ORDER BY changed, pid OFFSET ? LIMIT ?");
    String query = sb.toString();
    log.debug("query = " + query);

    sb = new StringBuilder();
    sb.append("SELECT setSpec FROM oairecordsets WHERE pid = ? AND setSpec IN ('")
            .append(allowedSets.stream().sorted().collect(Collectors.joining("', '")))
            .append("') AND NOT gone ORDER BY setSpec");
    String setQuery = sb.toString();

    Timestamp last = null;
    int row = 0;
    try (PreparedStatement stmt = connection.prepareStatement(query);
            PreparedStatement sets = connection.prepareStatement(setQuery)) {
        int i = 1;
        if (set != null) {
            stmt.setString(i++, set);
        }
        stmt.setString(i++, metadataPrefix);
        if (from != null) {
            stmt.setString(i++, from);
        }
        if (until != null) {
            stmt.setString(i++, until);
        }
        stmt.setInt(i++, offset);
        stmt.setInt(i++, limit + 1);
        try (ResultSet resultSet = stmt.executeQuery()) {
            while (resultSet.next()) {
                row++;
                String pid = resultSet.getString(1);
                Timestamp changed = resultSet.getTimestamp(2);
                Boolean deleted = resultSet.getBoolean(3);
                if (row <= limit) {
                    OAIIdentifier oaiRecord = new OAIIdentifier(pid, changed, deleted);
                    sets.setString(1, pid);
                    try (ResultSet setsResult = sets.executeQuery()) {
                        while (setsResult.next()) {
                            oaiRecord.add(setsResult.getString(1));
                        }
                    }
                    if (oaiRecord.isEmpty() && !oaiRecord.isDeleted()) {
                        oaiRecord = new OAIIdentifier(pid, changed, true);
                    }
                    add(oaiRecord);
                    if (changed.equals(last)) {
                        offset++;
                    } else {
                        last = changed;
                        offset = 1;
                    }
                } else {
                    ObjectNode obj = OBJECT_MAPPER.createObjectNode();
                    String continueFrom = changed.toInstant().atZone(ZoneId.systemDefault())
                            .format(DateTimeFormatter.ISO_INSTANT);
                    obj.put("f", continueFrom);
                    if (changed.equals(last)) {
                        obj.put("o", offset);
                    }
                    if (until != null) {
                        obj.put("u", until);
                    }
                    if (set != null) {
                        obj.put("s", set);
                    }
                    if (metadataPrefix != null) {
                        obj.put("m", metadataPrefix);
                    }
                    log.debug("continueFrom = " + obj);
                    return obj;
                }
            }
        }
    } catch (SQLException ex) {
        log.error("Exception: " + ex.getMessage());
        log.debug("Exception:", ex);
        throw new ServerErrorException(Response.Status.INTERNAL_SERVER_ERROR, "Internal Error");
    }
    return null;
}

From source file:se.crisp.codekvast.warehouse.file_import.ImportDAOImpl.java

@Override
public boolean saveInvocation(Invocation invocation, ImportContext context) {
    long applicationId = context.getApplicationId(invocation.getLocalApplicationId());
    long methodId = context.getMethodId(invocation.getLocalMethodId());
    long jvmId = context.getJvmId(invocation.getLocalJvmId());
    Timestamp invokedAt = new Timestamp(invocation.getInvokedAtMillis());

    Timestamp oldInvokedAt = queryForTimestamp(
            "SELECT invokedAtMillis FROM invocations WHERE applicationId = ? AND methodId = ? AND jvmId = ? ",
            applicationId, methodId, jvmId);

    boolean databaseTouched = false;
    if (oldInvokedAt == null) {
        jdbcTemplate.update(/*from  w w  w .ja va 2s .c  o m*/
                "INSERT INTO invocations(applicationId, methodId, jvmId, invokedAtMillis, invocationCount, status) "
                        + "VALUES(?, ?, ?, ?, ?, ?) ",
                applicationId, methodId, jvmId, invokedAt.getTime(), invocation.getInvocationCount(),
                invocation.getStatus().name());
        log.trace("Inserted invocation {}:{}:{} {}", applicationId, methodId, jvmId, invokedAt);
        databaseTouched = true;
    } else if (invokedAt.after(oldInvokedAt)) {
        jdbcTemplate.update(
                "UPDATE invocations SET invokedAtMillis = ?, invocationCount = invocationCount + ?, status = ? "
                        + "WHERE applicationId = ? AND methodId = ? AND jvmId = ? ",
                invokedAt.getTime(), invocation.getInvocationCount(), invocation.getStatus().name(),
                applicationId, methodId, jvmId);
        log.trace("Updated invocation {}:{}:{} {}", applicationId, methodId, jvmId, invokedAt);
        databaseTouched = true;
    } else if (oldInvokedAt.equals(invokedAt)) {
        log.trace("Ignoring invocation, same row exists in database");
    } else {
        log.trace("Ignoring invocation, a newer row exists in database");
    }
    return databaseTouched;
}

From source file:com.alibaba.wasp.jdbc.TestJdbcResultSet.java

@Test
public void testDatetime() throws SQLException {
    trace("test DATETIME");
    ResultSet rs;//  ww  w . j a v  a2 s  .c o  m
    Object o;

    // rs = stat.executeQuery("call date '99999-12-23'");
    // rs.next();
    // assertEquals("99999-12-23", rs.getString(1));
    // rs = stat.executeQuery("call timestamp '99999-12-23 01:02:03.000'");
    // rs.next();
    // assertEquals("99999-12-23 01:02:03.0", rs.getString(1));
    // rs = stat.executeQuery("call date '-99999-12-23'");
    // rs.next();
    // assertEquals("-99999-12-23", rs.getString(1));
    // rs = stat.executeQuery("call timestamp '-99999-12-23 01:02:03.000'");
    // rs.next();
    // assertEquals("-99999-12-23 01:02:03.0", rs.getString(1));

    stat = conn.createStatement();
    // stat.execute("CREATE TABLE test(ID INT PRIMARY KEY,VALUE DATETIME)");
    stat.execute(
            "INSERT INTO test (column1,column6,column2,column3) VALUES (1,'2011-11-11 0:0:0', 13, 'testDatetime')");
    stat.execute(
            "INSERT INTO test (column1,column6,column2,column3) VALUES (2,'2002-02-02 02:02:02', 13, 'testDatetime')");
    stat.execute(
            "INSERT INTO test (column1,column6,column2,column3) VALUES (3,'1800-01-01 0:0:0', 13, 'testDatetime')");
    stat.execute(
            "INSERT INTO test (column1,column6,column2,column3) VALUES (4,'9999-12-31 23:59:59', 13, 'testDatetime')");
    stat.execute(
            "INSERT INTO test (column1,column6,column2,column3) VALUES (5,'9999-12-31 23:59:59', 13, 'testDatetime')");
    // stat.execute("INSERT INTO test (column1,column6,column2,column3) VALUES(5,NULL)");
    rs = stat.executeQuery("SELECT column1,column6 FROM test where column3='testDatetime' ORDER BY column1");
    // assertResultSetMeta(rs, 2, new String[] { "ID", "VALUE" }, new int[] {
    // Types.INTEGER, Types.TIMESTAMP }, new int[] { 10, 23 }, new int[] { 0,
    // 10 });
    // rs = stat.executeQuery("SELECT * FROM test ORDER BY ID");
    // assertResultSetMeta(rs, 2, new String[] { "ID", "VALUE" }, new int[] {
    // Types.INTEGER, Types.TIMESTAMP }, new int[] { 10, 23 }, new int[] { 0,
    // 10 });
    rs.next();
    java.sql.Date date;
    java.sql.Time time;
    Timestamp ts;
    date = rs.getDate(2);
    assertTrue(!rs.wasNull());
    time = rs.getTime(2);
    assertTrue(!rs.wasNull());
    ts = rs.getTimestamp(2);
    assertTrue(!rs.wasNull());
    trace("Date: " + date.toString() + " Time:" + time.toString() + " Timestamp:" + ts.toString());
    trace("Date ms: " + date.getTime() + " Time ms:" + time.getTime() + " Timestamp ms:" + ts.getTime());
    trace("1970 ms: " + Timestamp.valueOf("1970-01-01 00:00:00.0").getTime());
    assertEquals(Timestamp.valueOf("2011-11-11 00:00:00.0").getTime(), date.getTime());
    assertEquals(Timestamp.valueOf("1970-01-01 00:00:00.0").getTime(), time.getTime());
    assertEquals(Timestamp.valueOf("2011-11-11 00:00:00.0").getTime(), ts.getTime());
    assertTrue(date.equals(java.sql.Date.valueOf("2011-11-11")));
    assertTrue(time.equals(java.sql.Time.valueOf("00:00:00")));
    assertTrue(ts.equals(Timestamp.valueOf("2011-11-11 00:00:00.0")));
    assertFalse(rs.wasNull());
    o = rs.getObject(2);
    trace(o.getClass().getName());
    assertTrue(o instanceof Timestamp);
    assertTrue(((Timestamp) o).equals(Timestamp.valueOf("2011-11-11 00:00:00")));
    assertFalse(rs.wasNull());
    rs.next();
    date = rs.getDate("COLUMN6");
    assertTrue(!rs.wasNull());
    time = rs.getTime("COLUMN6");
    assertTrue(!rs.wasNull());
    ts = rs.getTimestamp("COLUMN6");
    assertTrue(!rs.wasNull());
    trace("Date: " + date.toString() + " Time:" + time.toString() + " Timestamp:" + ts.toString());
    assertEquals("2002-02-02", date.toString());
    assertEquals("02:02:02", time.toString());
    assertEquals("2002-02-02 02:02:02.0", ts.toString());
    rs.next();
    assertEquals("1800-01-01", rs.getDate("column6").toString());
    assertEquals("00:00:00", rs.getTime("column6").toString());
    assertEquals("1800-01-01 00:00:00.0", rs.getTimestamp("column6").toString());
    rs.next();
    assertEquals("9999-12-31", rs.getDate("Column6").toString());
    assertEquals("23:59:59", rs.getTime("Column6").toString());
    assertEquals("9999-12-31 23:59:59.0", rs.getTimestamp("Column6").toString());
    // assertTrue(!rs.next());
}