Example usage for java.sql Timestamp getTime

List of usage examples for java.sql Timestamp getTime

Introduction

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

Prototype

public long getTime() 

Source Link

Document

Returns the number of milliseconds since January 1, 1970, 00:00:00 GMT represented by this Timestamp object.

Usage

From source file:io.stallion.dataAccess.db.DB.java

/**
 * Intialize the database based on the passed in configuration object.
 * @param config/*from   w w w . j a  v  a2  s. c  om*/
 */
public void initialize(DbConfig config) {
    try {
        dbImplementation = (DbImplementation) StallionClassLoader.loadClass(config.getImplementationClass())
                .newInstance();
    } catch (InstantiationException e) {
        throw new RuntimeException(e);
    } catch (IllegalAccessException e) {
        throw new RuntimeException(e);
    }

    // Test out the connection. We do this directly, because if we test via the ComboPooledDataSource
    // exceptions will make the driver hang while retrying, and will also bury the underlying cause

    try {
        Driver driver = (Driver) StallionClassLoader.loadClass(config.getDriverClass()).newInstance();
        Properties props = new Properties();
        props.setProperty("user", config.getUsername());
        props.setProperty("password", config.getPassword());
        try (Connection conn = driver.connect(config.getUrl(), props)) {
            Statement st = conn.createStatement();
            ResultSet results = st.executeQuery("SELECT 1 AS oneCol");
            results.next();
            Long i = results.getLong("oneCol");
            assert i == 1L;
        }
    } catch (SQLException e) {
        throw new RuntimeException(e);
    } catch (InstantiationException e) {
        throw new RuntimeException(e);
    } catch (IllegalAccessException e) {
        throw new RuntimeException(e);
    }

    ComboPooledDataSource cpds = new ComboPooledDataSource();
    /*
    try {
    try (Connection conn = cpds.getConnection()) {
        Statement st = conn.createStatement();
        ResultSet results = st.executeQuery("SELECT 1");
        Long i = results.getLong(0);
        assert i == 1L;
    }
    } catch (SQLException e) {
    throw new RuntimeException(e);
    }
            
    */
    try {
        cpds.setDriverClass(config.getDriverClass()); //loads the jdbc driver
    } catch (PropertyVetoException e) {
        throw new RuntimeException(e);
    }

    String url = config.getUrl();
    if (!url.contains("?")) {
        url += "?";
    }
    // Assume the database server is in UTC
    if (!url.contains("&useLegacyDatetimeCode=")) {
        url += "&useLegacyDatetimeCode=false";
    }
    if (!url.contains("&serverTimezone=")) {
        url += "&serverTimezone=UTC";
    }
    //&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC

    cpds.setJdbcUrl(url);
    cpds.setUser(config.getUsername());
    cpds.setPassword(config.getPassword());

    if (url.contains("utf8mb4_unicode_ci")) {
        cpds.setConnectionCustomizerClassName("io.stallion.dataAccess.db.mysql.Utf8InitCustomizer");
    }

    cpds.setAcquireRetryAttempts(10);
    cpds.setAcquireRetryDelay(200);
    //cpds.setCheckoutTimeout(1);
    // the settings below are optional -- c3p0 can work with defaults
    cpds.setMinPoolSize(5);
    cpds.setAcquireIncrement(5);
    cpds.setMaxPoolSize(20);
    cpds.setIdleConnectionTestPeriod(5000);
    cpds.setTestConnectionOnCheckin(true);

    this.dataSource = cpds;

    // Make sure the database server time is UTC and in sync with the local server time
    // or else stop execution to prevent nasty and insiduious errors.
    //Timestamp date = this.queryScalar(dbImplementation.getCurrentTimeStampQuery());
    Timestamp date = this.queryScalar(dbImplementation.getCurrentTimeStampQuery());
    ZonedDateTime now = utcNow();
    ZonedDateTime dbTime = ZonedDateTime.ofInstant(Instant.ofEpochMilli(date.getTime()), ZoneId.of("UTC"));

    //LocalDateTime now = utcNow().toLocalDateTime();
    ZonedDateTime max = now.plusMinutes(2);
    ZonedDateTime min = now.minusMinutes(2);

    //LocalDateTime dbTime = date.toLocalDateTime();
    if (dbTime.isAfter(max) || dbTime.isBefore(min)) {
        throw new ConfigException(
                "The database CURRENT_TIMESTAMP() is mismatched with the server time. Db time is " + dbTime
                        + ". Server time is " + now
                        + ". Make sure the database server is in UTC and that all your servers clocks are matched. ");
    }

    // Todo: why not lazy load converters???
    registerConverter(new JsonMapConverter());
    registerConverter(new JsonSetConverter());
    registerConverter(new JsonObjectConverter());
    registerConverter(new JsonListConverter());

    this.tickets = dbImplementation.initTicketsService(this);

}

From source file:com.funambol.foundation.items.dao.DataBaseFileDataObjectMetadataDAO.java

/**
 * Updates metadata fields when FileDataObject body changes, like crc, size,
 * localname etc and the properties associated to it.
 *
 * @param fdow the wrapper with the new body file
 * @throws DAOException if an error occurs
 *///w ww .  ja va2  s.  c  o m
public void updateItemWhenBodyChanges(FileDataObjectWrapper fdow) throws DAOException {

    Connection con = null;
    PreparedStatement ps = null;

    try {

        Long fdoId = Long.valueOf(fdow.getId());

        FileDataObject fdo = fdow.getFileDataObject();

        Timestamp currentTime = new Timestamp(System.currentTimeMillis());

        StringBuilder updateQuery = new StringBuilder();

        updateQuery.append(SQL_UPDATE_FNBL_FILE_DATA_OBJECT_BEGIN);

        updateQuery.append(SQL_FIELD_LAST_UPDATE).append(SQL_EQUALS_QUESTIONMARK_COMMA);

        String localName = fdow.getLocalName();
        if (localName != null) {
            updateQuery.append(SQL_FIELD_LOCAL_NAME).append(SQL_EQUALS_QUESTIONMARK_COMMA);
        }

        updateQuery.append(SQL_FIELD_UPLOAD_STATUS).append(SQL_EQUALS_QUESTIONMARK_COMMA);

        Long crc = Long.valueOf(fdow.getFileDataObject().getCrc());
        updateQuery.append(SQL_FIELD_CRC).append(SQL_EQUALS_QUESTIONMARK_COMMA);

        Long size = fdo.getSize();
        if (size != null) {
            updateQuery.append(SQL_FIELD_SIZE).append(SQL_EQUALS_QUESTIONMARK_COMMA);
        }

        Long sizeOnStorage = fdow.getSizeOnStorage();
        if (sizeOnStorage != null) {
            updateQuery.append(SQL_FIELD_SIZE_ON_STORAGE).append(SQL_EQUALS_QUESTIONMARK_COMMA);
        }

        // set always created and modified dates
        updateQuery.append(SQL_FIELD_CREATED).append(SQL_EQUALS_QUESTIONMARK_COMMA);
        updateQuery.append(SQL_FIELD_MODIFIED).append(SQL_EQUALS_QUESTIONMARK_COMMA);

        if (updateQuery.charAt(updateQuery.length() - 2) == ',') {
            updateQuery.deleteCharAt(updateQuery.length() - 2);
        }

        updateQuery.append(SQL_UPDATE_FNBL_FILE_DATA_OBJECT_END);

        // Looks up the data source when the first connection is created
        con = getUserDataSource().getRoutedConnection(userId);

        ps = con.prepareStatement(updateQuery.toString());

        int k = 1;

        Timestamp lastUpdate = (fdow.getLastUpdate() == null) ? currentTime : fdow.getLastUpdate();
        ps.setLong(k++, lastUpdate.getTime());

        if (localName != null) {
            ps.setString(k++, StringUtils.left(localName, SQL_LOCAL_NAME_DIM));
        }

        ps.setString(k++, "" + fdo.getUploadStatus());
        ps.setLong(k++, crc);

        if (size != null) {
            ps.setLong(k++, size);
        }

        if (sizeOnStorage != null) {
            ps.setLong(k++, sizeOnStorage);
        }

        MediaUtils.setFDODates(fdo, fdo.getCreated(), fdo.getModified());

        Timestamp created = timestamp(fdo.getCreated());
        if (created != null) {
            ps.setTimestamp(k++, created);
        } else {
            ps.setTimestamp(k++, currentTime);
        }

        Timestamp modified = timestamp(fdo.getModified());
        if (modified != null) {
            ps.setTimestamp(k++, modified);
        } else {
            ps.setTimestamp(k++, currentTime);
        }

        ps.setLong(k++, fdoId);
        ps.setString(k++, userId);
        ps.setString(k++, sourceURI);

        ps.executeUpdate();

        DBTools.close(con, ps, null);

        // delete and add the properties associated to the new FDO
        removeAllProperties(fdow.getId());
        addProperties(fdow);

    } catch (Exception e) {
        throw new DAOException("Error updating file data object and its properties.", e);
    } finally {
        DBTools.close(con, ps, null);
    }
}

From source file:org.nuxeo.ecm.core.storage.sql.db.dialect.DialectPostgreSQL.java

@Override
@SuppressWarnings("boxing")
public Serializable getFromResultSet(ResultSet rs, int index, Column column) throws SQLException {
    switch (column.getJdbcType()) {
    case Types.VARCHAR:
    case Types.CLOB:
        String string = rs.getString(index);
        if (column.getType() == ColumnType.BLOBID && string != null) {
            return column.getModel().getBinary(string);
        } else {//  w w w.  j  a  va2s .co m
            return string;
        }
    case Types.BIT:
        return rs.getBoolean(index);
    case Types.SMALLINT:
    case Types.INTEGER:
    case Types.BIGINT:
        return rs.getLong(index);
    case Types.DOUBLE:
        return rs.getDouble(index);
    case Types.TIMESTAMP:
        Timestamp ts = rs.getTimestamp(index);
        if (ts == null) {
            return null;
        } else {
            Serializable cal = new GregorianCalendar(); // XXX timezone
            ((Calendar) cal).setTimeInMillis(ts.getTime());
            return cal;
        }
    case Types.ARRAY:
        return (Serializable) rs.getArray(index).getArray();
    }
    throw new SQLException("Unhandled JDBC type: " + column.getJdbcType());
}

From source file:PVGraph.java

public java.util.List<DayData> getDayData(int year, int month, int day) {
    Statement stmt = null;//from   w  ww .j a v a  2  s . c om
    String query = "select * from DayData where year(DateTime) = " + year + " and month(DateTime) = " + month
            + " and dayofmonth(DateTime) = " + day + " order by DateTime";
    Map<String, DayData> result = new HashMap<String, DayData>();
    try {
        getDatabaseConnection();
        stmt = conn.createStatement();
        ResultSet rs = stmt.executeQuery(query);
        long lastTime = 0;
        int lastPower = 0;
        while (rs.next()) {
            String serial = rs.getString("serial");
            DayData dd = result.get(serial);
            if (dd == null) {
                dd = new DayData();
                dd.serial = serial;
                dd.inverter = rs.getString("inverter");
                dd.startTotalPower = rs.getDouble("ETotalToday");
                result.put(serial, dd);
            }
            Timestamp currentTime = rs.getTimestamp("DateTime");
            int currentPower = rs.getInt("CurrentPower");
            if (lastTime != 0) {
                long fiveMinutesAfterLastTime = lastTime + 300 * 1000;
                long fiveMinutesBeforeCurrentTime = currentTime.getTime() - 300 * 1000;
                if (currentTime.getTime() > fiveMinutesAfterLastTime) {
                    for (long t = fiveMinutesAfterLastTime; t <= fiveMinutesBeforeCurrentTime; t += 300
                            * 1000) {
                        //System.err.println("Adding zero power at " + new Timestamp(t));
                        dd.times.add(new Timestamp(t));
                        dd.powers.add(0);
                    }
                }
            }
            dd.times.add(currentTime);
            dd.powers.add(currentPower);
            dd.endTotalPower = rs.getDouble("ETotalToday");
            lastTime = currentTime.getTime();
            lastPower = currentPower;
        }
    } catch (SQLException e) {
        System.err.println("Query failed: " + e.getMessage());
    } finally {
        try {
            stmt.close();
        } catch (SQLException e) {
            // relax
        }
    }
    return new java.util.ArrayList<DayData>(result.values());
}

From source file:org.cloudgraph.cassandra.service.GraphDispatcher.java

/**
 * Compares the application-level concurrency state of the given datastore entity against the 
 * query snapshot date. If the snapshot date is current, the concurrency data for the entity is 
 * refreshed. Otherwise a shapshot concurrency exception is thrown. 
 * @param type - the type definition// www.  j a va2  s. co  m
 * @param entity - the map representing datastore entity
 * @param lastUpdatedDateProperty - the last updated date property definition metadata 
 * @param lastUpdatedByNameProperty - the last updated by name property definition metadata
 * @param snapshotDate - the query snapshot date
 */
private void checkConcurrencyFields(Type type, Map<String, PropertyPair> entity,
        Property lastUpdatedDateProperty, Property lastUpdatedByNameProperty, Timestamp snapshotDate)
        throws IllegalAccessException, IllegalArgumentException, InvocationTargetException {
    PropertyPair lastUpdatedDatePair = entity.get(lastUpdatedDateProperty.getName());
    PropertyPair lastUpdatedByPair = entity.get(lastUpdatedByNameProperty.getName());

    String entityName = type.getName();

    if (lastUpdatedDatePair != null) {
        Date lastUpdatedDate = (Date) lastUpdatedDatePair.getValue();
        if (log.isDebugEnabled())
            log.debug("comparing " + lastUpdatedDate + "greater than snapshot: " + snapshotDate);
        if (lastUpdatedDate.getTime() > snapshotDate.getTime()) {
            if (lastUpdatedByPair != null) {
                String lastUpdatedBy = (String) lastUpdatedByPair.getValue();
                throw new InvalidSnapshotException(entityName, username, snapshotDate, lastUpdatedBy,
                        lastUpdatedDate);
            } else
                throw new InvalidSnapshotException(entityName, username, snapshotDate, "unknown",
                        lastUpdatedDate);
        }
    }
}

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

@Test
public void testDatetime() throws SQLException {
    trace("test DATETIME");
    ResultSet rs;/*from  ww  w.j  a v a  2 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());
}

From source file:org.kuali.rice.kim.impl.role.RoleInternalServiceImpl.java

protected void inactivatePrincipalGroupMemberships(String principalId, Timestamp yesterday) {
    if (StringUtils.isBlank(principalId)) {
        return;// w  w w . j ava  2  s. c o  m
    }
    // get all the groups the person is in
    List<String> groupIds = getGroupService().getGroupIdsByPrincipalId(principalId);
    if (groupIds.isEmpty()) {
        return;
    }
    // get all the member records for those groups
    Collection<GroupMember> groupMembers = getGroupService().getMembers(groupIds);
    List<GroupMember> groupPrincipals = new ArrayList<GroupMember>(groupMembers.size());
    for (GroupMember groupMembershipInfo : groupMembers) {
        if (MemberType.PRINCIPAL.equals(groupMembershipInfo.getType())
                && StringUtils.equals(principalId, groupMembershipInfo.getMemberId())
                && groupMembershipInfo.isActive(new DateTime())) {
            groupPrincipals.add(groupMembershipInfo);
            // FIXME: Is there a reason we are not calling the responsible group service?
            //getGroupService().removePrincipalFromGroup(groupMembershipInfo.getMemberId(), groupMembershipInfo.getGroupId());
        }
    }
    // FIXME: Is there a reason we are doing this directly and *not* calling the group service???
    for (GroupMember gm : groupPrincipals) {
        GroupMember.Builder builder = GroupMember.Builder.create(gm);
        builder.setActiveToDate(new DateTime(yesterday.getTime()));
        getDataObjectService().save(GroupMemberBo.from(builder.build()));
    }
}

From source file:com.funambol.foundation.items.dao.DataBaseFileDataObjectMetadataDAO.java

/**
 * Adds file data object metadata of an item to the database.
 * @param fdow//  w w w .  j av a 2 s . c o m
 * @throws com.funambol.foundation.exception.DAOException
 */
public String addItem(FileDataObjectWrapper fdow) throws DAOException {

    Connection con = null;
    PreparedStatement ps = null;

    try {

        // Looks up the data source when the first connection is created
        con = getUserDataSource().getRoutedConnection(userId);

        if (fdow.getId() == null) {
            throw new DAOException("Unable to add item: id should be already defined");
        }

        ps = con.prepareStatement(SQL_INSERT_INTO_FNBL_FILE_DATA_OBJECT);

        int k = 1;

        ps.setLong(k++, Long.parseLong(fdow.getId()));

        ps.setString(k++, userId);

        ps.setString(k++, sourceURI);

        Timestamp currentTime = new Timestamp(System.currentTimeMillis());

        Timestamp lastUpdate = fdow.getLastUpdate();
        if (lastUpdate == null) {
            lastUpdate = currentTime;
        }
        ps.setLong(k++, lastUpdate.getTime());

        ps.setString(k++, String.valueOf(SyncItemState.NEW));

        FileDataObject fdo = fdow.getFileDataObject();

        ps.setString(k++, String.valueOf(fdo.getUploadStatus()));

        String fileName = fdow.getLocalName();
        if (fileName == null || fileName.length() == 0) {
            ps.setNull(k++, Types.VARCHAR);
        } else {
            ps.setString(k++, StringUtils.left(fileName, SQL_LOCAL_NAME_DIM));
        }

        Long crc = Long.valueOf(fdow.getFileDataObject().getCrc());
        ps.setLong(k++, crc);

        ps.setString(k++, StringUtils.left(fdo.getName(), SQL_TRUE_NAME_DIM));

        MediaUtils.setFDODates(fdo, fdo.getCreated(), fdo.getModified());

        Timestamp created = timestamp(fdo.getCreated());
        if (created != null) {
            ps.setTimestamp(k++, created);
        } else {
            ps.setTimestamp(k++, currentTime);
        }

        Timestamp modified = timestamp(fdo.getModified());
        if (modified != null) {
            ps.setTimestamp(k++, modified);
        } else {
            ps.setTimestamp(k++, currentTime);
        }

        ps.setTimestamp(k++, timestamp(fdo.getAccessed()));

        ps.setString(k++, fdo.isHidden() ? ONE : NIL);
        ps.setString(k++, fdo.isSystem() ? ONE : NIL);
        ps.setString(k++, fdo.isArchived() ? ONE : NIL);
        ps.setString(k++, fdo.isDeleted() ? ONE : NIL);
        ps.setString(k++, fdo.isWritable() ? ONE : NIL);
        ps.setString(k++, fdo.isReadable() ? ONE : NIL);
        ps.setString(k++, fdo.isExecutable() ? ONE : NIL);

        if (fdo.getContentType() != null) {
            ps.setString(k++, StringUtils.left(fdo.getContentType(), SQL_CTTYPE_DIM));
        } else {
            ps.setNull(k++, Types.VARCHAR);
        }

        if (fdo.getSize() == null) {
            ps.setNull(k++, Types.BIGINT);
        } else {
            ps.setLong(k++, fdo.getSize());
        }

        if (fdow.getSizeOnStorage() == null) {
            ps.setNull(k++, Types.BIGINT);
        } else {
            ps.setLong(k++, fdow.getSizeOnStorage());
        }

        ps.executeUpdate();
        DBTools.close(null, ps, null);

        // stores file data object properties
        addProperties(fdow);

    } catch (Exception e) {
        throw new DAOException("Error adding file data object.", e);
    } finally {
        DBTools.close(con, ps, null);
    }
    return fdow.getId();
}

From source file:org.cloudgraph.cassandra.service.GraphDispatcher.java

/**
 * Compares the application-level concurrency state of the given datastore entity against the 
 * query snapshot date. If the snapshot date is current, the concurrency data for the entity is 
 * refreshed. Otherwise a shapshot concurrency exception is thrown. 
 * @param type - the type definition/*from   ww  w .java  2s.  com*/
 * @param entity - the map representing datastore entity
 * @param lastUpdatedDateProperty - the last updated date property definition metadata 
 * @param lastUpdatedByNameProperty - the last updated by name property definition metadata
 * @param snapshotDate - the query snapshot date
 */
private void checkAndRefreshConcurrencyFields(Type type, Map<String, PropertyPair> entity,
        Property lastUpdatedDateProperty, Property lastUpdatedByNameProperty, Timestamp snapshotDate)
        throws IllegalAccessException, IllegalArgumentException, InvocationTargetException {
    PropertyPair lastUpdatedDatePair = entity.get(lastUpdatedDateProperty.getName());
    PropertyPair lastUpdatedByPair = entity.get(lastUpdatedByNameProperty.getName());

    String entityName = type.getName();

    if (lastUpdatedDatePair != null) {
        Date lastUpdatedDate = (Date) lastUpdatedDatePair.getValue();
        if (log.isDebugEnabled())
            log.debug("comparing " + lastUpdatedDate + "greater than snapshot: " + snapshotDate);
        if (lastUpdatedDate.getTime() > snapshotDate.getTime()) {
            if (lastUpdatedByPair != null) {
                String lastUpdatedBy = (String) lastUpdatedByPair.getValue();
                throw new InvalidSnapshotException(entityName, username, snapshotDate, lastUpdatedBy,
                        lastUpdatedDate);
            } else
                throw new InvalidSnapshotException(entityName, username, snapshotDate, "unknown",
                        lastUpdatedDate);
        }
        PropertyPair updatedDatePair = new PropertyPair(lastUpdatedDatePair.getProp(),
                this.snapshotMap.getSnapshotDate());
        entity.put(lastUpdatedDatePair.getProp().getName(), updatedDatePair);

        if (lastUpdatedByPair != null) {
            PropertyPair updatedByPair = new PropertyPair(lastUpdatedByPair.getProp(), username);
            entity.put(updatedByPair.getProp().getName(), updatedByPair);
        }
    }
    if (log.isDebugEnabled()) {
        log.debug("reset updated-date " + entity.getClass().getSimpleName() + " (" + entityName + " - "
                + this.snapshotMap.getSnapshotDate() + "("
                + String.valueOf(this.snapshotMap.getSnapshotDate().getTime()) + ")");
    }
}

From source file:com.cisco.dvbu.ps.common.util.CommonUtils.java

/**
 * Convert a timestamp value to big integer.
 * /*w w  w  .  j  a v  a  2 s.  co m*/
 * @param Timestamp timestamp
 * @return
 */
public static BigInteger TimestampToBigint(Timestamp timestamp) {
    BigInteger result = BigInteger.valueOf(new Long(timestamp.getTime()));
    return result;
}