Example usage for java.sql Timestamp toString

List of usage examples for java.sql Timestamp toString

Introduction

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

Prototype

@SuppressWarnings("deprecation")
public String toString() 

Source Link

Document

Formats a timestamp in JDBC timestamp escape format.

Usage

From source file:org.wso2.carbon.identity.application.authentication.framework.store.SessionDataStore.java

private void deleteSTOREOperationsTask(Timestamp timestamp) {
    Connection connection = null;
    PreparedStatement statement = null;
    try {/*from w ww . j  av  a  2s .  com*/
        connection = IdentityDatabaseUtil.getDBConnection();
    } catch (IdentityRuntimeException e) {
        log.error(e.getMessage(), e);
        return;
    }
    try {
        statement = connection.prepareStatement(sqlDeleteSTORETask);
        statement.setLong(1, timestamp.getTime());
        statement.execute();
        if (!connection.getAutoCommit()) {
            connection.commit();
        }
        return;
    } catch (SQLException e) {
        log.error("Error while removing STORE operation data from the database for the timestamp "
                + timestamp.toString(), e);
    } finally {
        IdentityDatabaseUtil.closeAllConnections(connection, null, statement);

    }

}

From source file:org.wso2.carbon.identity.application.authentication.framework.store.SessionDataStore.java

private void deleteDELETEOperationsTask(Timestamp timestamp) {
    Connection connection = null;
    PreparedStatement statement = null;
    try {/*from w  w  w.  j  ava  2 s.co  m*/
        connection = IdentityDatabaseUtil.getDBConnection();
    } catch (IdentityRuntimeException e) {
        log.error(e.getMessage(), e);
        return;
    }
    try {
        statement = connection.prepareStatement(sqlDeleteDELETETask);
        statement.setLong(1, timestamp.getTime());
        statement.execute();
        if (!connection.getAutoCommit()) {
            connection.commit();
        }
        return;
    } catch (SQLException e) {
        log.error("Error while removing DELETE operation data from the database for the timestamp "
                + timestamp.toString(), e);
    } finally {
        IdentityDatabaseUtil.closeAllConnections(connection, null, statement);

    }
}

From source file:org.plos.repo.RepoServiceSpringTest.java

@Test
public void updateObjectMetadata() throws Exception {
    repoService.createBucket(bucket1.getBucketName(), CREATION_DATE_TIME_STRING);

    try {/*w  w w.  j  a va  2s .  c om*/
        InputRepoObject inputRepoObject = createInputRepoObject();
        repoService.createObject(RepoService.CreateMethod.NEW, inputRepoObject);

        Timestamp creationDateObj2 = new Timestamp(new Date().getTime());
        inputRepoObject.setContentType("new content type");
        inputRepoObject.setDownloadName("new download name");
        inputRepoObject.setUploadedInputStream(IOUtils.toInputStream(""));
        inputRepoObject.setTimestamp(creationDateObj2.toString());
        inputRepoObject.setCreationDateTime(creationDateObj2.toString());
        repoService.createObject(RepoService.CreateMethod.VERSION, inputRepoObject);
    } catch (RepoException e) {
        Assert.fail(e.getMessage());
    }

    // check internal state
    sqlService.getReadOnlyConnection();

    RepoObject objFromDb = sqlService.getObject(bucket1.getBucketName(), KEY);
    Assert.assertTrue(objFromDb.getKey().equals(KEY));
    List<Audit> auditList = sqlService.listAudit(bucket1.getBucketName(), KEY, objFromDb.getUuid().toString(),
            null, null);
    Assert.assertTrue(auditList.size() > 0);
    Assert.assertTrue(auditList.get(0).getOperation().equals(Operation.UPDATE_OBJECT));
    sqlService.releaseConnection();

    Assert.assertTrue(objectStore.objectExists(objFromDb));

    // check external state

    Assert.assertTrue(repoService.getObjectVersions(objFromDb.getBucketName(), objFromDb.getKey()).size() == 2);
    Assert.assertTrue(
            repoService.listObjects(bucket1.getBucketName(), null, null, false, false, null).size() == 2);

    Assert.assertTrue(IOUtils
            .toString(repoService.getObjectInputStream(
                    repoService.getObject(bucket1.getBucketName(), KEY, new ElementFilter(0, null, null))))
            .equals("data1"));

    Assert.assertTrue(IOUtils
            .toString(repoService.getObjectInputStream(
                    repoService.getObject(bucket1.getBucketName(), KEY, new ElementFilter(1, null, null))))
            .equals(""));

    Assert.assertTrue(repoService.getObjectContentType(objFromDb).equals("new content type"));
    Assert.assertTrue(repoService.getObjectExportFileName(objFromDb).equals("new+download+name"));
}

From source file:it.cnr.icar.eric.server.query.QueryManagerImpl.java

/**
 * Replaces special environment variables within specified query string.
 *//*from   w  ww  .  ja  v a  2 s. co  m*/
private String replaceSpecialVariables(UserType user, String query) {
    String newQuery = query;

    // Replace $currentUser
    if (user != null) {
        newQuery = newQuery.replaceAll("\\$currentUser", "'" + user.getId() + "'");
    }

    // Replace $currentTime
    Timestamp currentTime = new Timestamp(Calendar.getInstance().getTimeInMillis());

    // ??The timestamp is being truncated to work around a bug in PostgreSQL
    // 7.2.2 JDBC driver
    String currentTimeStr = currentTime.toString().substring(0, 19);
    newQuery = newQuery.replaceAll("\\$currentTime", currentTimeStr);

    return newQuery;
}

From source file:org.apache.ddlutils.platform.oracle.Oracle8ModelReader.java

/**
  * {@inheritDoc}//www .ja  v a2  s  .  co  m
  */
protected Column readColumn(DatabaseMetaDataWrapper metaData, Map values) throws SQLException {
    Column column = super.readColumn(metaData, values);

    if (column.getDefaultValue() != null) {
        // Oracle pads the default value with spaces
        column.setDefaultValue(column.getDefaultValue().trim());
    }
    if (column.getTypeCode() == Types.DECIMAL) {
        // We're back-mapping the NUMBER columns returned by Oracle
        // Note that the JDBC driver returns DECIMAL for these NUMBER columns
        switch (column.getSizeAsInt()) {
        case 1:
            if (column.getScale() == 0) {
                column.setTypeCode(Types.BIT);
            }
            break;
        case 3:
            if (column.getScale() == 0) {
                column.setTypeCode(Types.TINYINT);
            }
            break;
        case 5:
            if (column.getScale() == 0) {
                column.setTypeCode(Types.SMALLINT);
            }
            break;
        case 18:
            column.setTypeCode(Types.REAL);
            break;
        case 22:
            if (column.getScale() == 0) {
                column.setTypeCode(Types.INTEGER);
            }
            break;
        case 38:
            if (column.getScale() == 0) {
                column.setTypeCode(Types.BIGINT);
            } else {
                column.setTypeCode(Types.DOUBLE);
            }
            break;
        }
    } else if (column.getTypeCode() == Types.FLOAT) {
        // Same for REAL, FLOAT, DOUBLE PRECISION, which all back-map to FLOAT but with
        // different sizes (63 for REAL, 126 for FLOAT/DOUBLE PRECISION)
        switch (column.getSizeAsInt()) {
        case 63:
            column.setTypeCode(Types.REAL);
            break;
        case 126:
            column.setTypeCode(Types.DOUBLE);
            break;
        }
    } else if ((column.getTypeCode() == Types.DATE) || (column.getTypeCode() == Types.TIMESTAMP)) {
        // Oracle has only one DATE/TIME type, so we can't know which it is and thus map
        // it back to TIMESTAMP
        column.setTypeCode(Types.TIMESTAMP);

        // we also reverse the ISO-format adaptation, and adjust the default value to timestamp
        if (column.getDefaultValue() != null) {
            Matcher matcher = _oracleIsoTimestampPattern.matcher(column.getDefaultValue());
            Timestamp timestamp = null;

            if (matcher.matches()) {
                String timestampVal = matcher.group(1);

                timestamp = Timestamp.valueOf(timestampVal);
            } else {
                matcher = _oracleIsoDatePattern.matcher(column.getDefaultValue());
                if (matcher.matches()) {
                    String dateVal = matcher.group(1);

                    timestamp = new Timestamp(Date.valueOf(dateVal).getTime());
                } else {
                    matcher = _oracleIsoTimePattern.matcher(column.getDefaultValue());
                    if (matcher.matches()) {
                        String timeVal = matcher.group(1);

                        timestamp = new Timestamp(Time.valueOf(timeVal).getTime());
                    }
                }
            }
            if (timestamp != null) {
                column.setDefaultValue(timestamp.toString());
            }
        }
    } else if (TypeMap.isTextType(column.getTypeCode())) {
        column.setDefaultValue(unescape(column.getDefaultValue(), "'", "''"));
    }
    return column;
}

From source file:org.apache.hive.jdbc.HivePreparedStatement.java

public void setTimestamp(int parameterIndex, Timestamp x) throws SQLException {
    this.parameters.put(parameterIndex, x.toString());
}

From source file:org.geowebcache.storage.jdbc.metastore.JDBCMBWrapper.java

protected boolean getTile(TileObject stObj) throws SQLException {
    String query;/* ww w .  j  av  a2s.c o m*/
    if (stObj.getParametersId() == -1L) {
        query = "SELECT TILE_ID,BLOB_SIZE,CREATED,LOCK,NOW() FROM TILES WHERE "
                + " LAYER_ID = ? AND X = ? AND Y = ? AND Z = ? AND GRIDSET_ID = ? "
                + " AND FORMAT_ID = ? AND PARAMETERS_ID IS NULL LIMIT 1 ";
    } else {
        query = "SELECT TILE_ID,BLOB_SIZE,CREATED,LOCK,NOW() FROM TILES WHERE "
                + " LAYER_ID = ? AND X = ? AND Y = ? AND Z = ? AND GRIDSET_ID = ? "
                + " AND FORMAT_ID = ? AND PARAMETERS_ID = ? LIMIT 1 ";
    }
    long[] xyz = stObj.getXYZ();

    final Connection conn = getConnection();
    PreparedStatement prep = null;
    try {
        prep = conn.prepareStatement(query);
        prep.setLong(1, stObj.getLayerId());
        prep.setLong(2, xyz[0]);
        prep.setLong(3, xyz[1]);
        prep.setLong(4, xyz[2]);
        prep.setLong(5, stObj.getGridSetIdId());
        prep.setLong(6, stObj.getFormatId());

        if (stObj.getParametersId() != -1L) {
            prep.setLong(7, stObj.getParametersId());
        }

        ResultSet rs = prep.executeQuery();
        try {
            if (rs.first()) {
                Timestamp lock = rs.getTimestamp(4);

                // This tile is locked
                if (lock != null) {
                    Timestamp now = rs.getTimestamp(5);
                    long diff = now.getTime() - lock.getTime();
                    // System.out.println(now.getTime() + " " + System.currentTimeMillis());
                    if (diff > lockTimeout) {
                        log.warn("Database lock exceeded (" + diff + "ms , " + lock.toString() + ") for "
                                + stObj.toString() + ", clearing tile.");
                        deleteTile(conn, stObj);
                        stObj.setStatus(StorageObject.Status.EXPIRED_LOCK);
                    } else {
                        stObj.setStatus(StorageObject.Status.LOCK);
                    }

                    // This puts the request back in the queue
                    return false;
                }

                stObj.setId(rs.getLong(1));
                stObj.setBlobSize(rs.getInt(2));
                stObj.setCreated(rs.getLong(3));
                stObj.setStatus(StorageObject.Status.HIT);
                return true;
            } else {
                stObj.setStatus(StorageObject.Status.MISS);
                return false;
            }
        } finally {
            close(rs);
        }
    } finally {
        close(prep);
        close(conn);
    }
}

From source file:org.wso2.bpmn.mysql.DBConnector.java

public void calculateValues() throws SQLException, IOException, ParseException {

    ResultSet resultSet = null;//from  ww w  .  java  2s . c  om

    try {
        ConfigLoader configLoader = ConfigLoader.getInstance();
        resultSet = statement
                .executeQuery("select START_TIME_, END_TIME_, DURATION_ FROM ACT_HI_PROCINST WHERE "
                        + "PROC_DEF_ID_ " + "= '" + configLoader.getProcessDefID()
                        + "' AND END_TIME_ IS NOT NULL ORDER BY START_TIME_ ASC");

        StringBuffer stringBuffer = new StringBuffer();
        stringBuffer.append("INSTANCE_COUNT__ \t\t");
        stringBuffer.append("START_TIME_ \t\t");
        stringBuffer.append("END_TIME_ \t\t\t");
        stringBuffer.append("DURATION_ \t");
        int rowCount = 0;
        Long totalDuration = 0l;
        while (resultSet.next()) {

            Timestamp rowStartTime = resultSet.getTimestamp(1);
            Timestamp rowStopTime = resultSet.getTimestamp(2);
            Long duration = resultSet.getLong(3);

            if (initialStartTime == null) {

                initialStartTime = rowStartTime;

                Calendar cal = Calendar.getInstance();
                cal.setTimeInMillis(rowStartTime.getTime());
                cal.add(Calendar.SECOND, configLoader.getInitialTruncatingTime());

                leastCalculationTime = new Timestamp(cal.getTime().getTime());

            }

            if (rowStartTime.before(leastCalculationTime) == true) {
                continue;
            }

            if (startTime == null) {
                startTime = rowStartTime;
            }

            if (stopTime == null) {
                stopTime = rowStopTime;
            }

            if (rowStopTime.after(stopTime)) {
                stopTime = rowStopTime;
            }

            totalDuration += duration;
            ++rowCount;

            String resultString = rowCount + "\t\t\t" + rowStartTime.toString() + "\t\t" + rowStopTime + "\t\t"
                    + duration;

            stringBuffer.append("\n");
            stringBuffer.append(resultString);

        }

        if (rowCount == 0) {
            System.out.println("Error : Row count not found : ");
        }

        double averageDuration = (double) totalDuration / rowCount;

        double tps = ((double) rowCount) / calculateTimeDifferenceInSeconds();
        String resultValue = "\tstartTime: " + startTime + "\n" + "\tendTime: " + stopTime + "\n" + "\tTotal "
                + "duration: " + totalDuration + "\n" + "\tAverage duration: " + averageDuration + "\n"
                + "\tInstance count: " + rowCount + "\n" + "\tTPS: " + tps;

        stringBuffer.append("\n\n\n\n");
        stringBuffer.append(resultValue);
        FileUtils.writeStringToFile(new File(configLoader.getFilePath()), stringBuffer.toString());

        System.out.println("===================Completed Calculation========================");
        System.out.println(resultValue);
    } finally {

        if (resultSet != null) {
            try {
                resultSet.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

        if (connection != null) {
            try {
                connection.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

        if (statement != null) {
            try {
                statement.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

}

From source file:org.jumpmind.db.platform.oracle.OracleDdlReader.java

@Override
protected Column readColumn(DatabaseMetaDataWrapper metaData, Map<String, Object> values) throws SQLException {
    Column column = super.readColumn(metaData, values);
    if (column.getMappedTypeCode() == Types.DECIMAL) {
        // We're back-mapping the NUMBER columns returned by Oracle
        // Note that the JDBC driver returns DECIMAL for these NUMBER
        // columns
        if (column.getScale() <= -127 || column.getScale() >= 127) {
            if (column.getSizeAsInt() == 0) {
                /*//  w  w  w . j  ava2 s.  co m
                 * Latest oracle jdbc drivers for 11g return (0,-127) for
                 * types defined as integer resulting in bad mappings.
                 * NUMBER without scale or precision looks the same as
                 * INTEGER in the jdbc driver. We must check the Oracle
                 * meta data to see if type is an INTEGER.
                 */
                if (isColumnInteger((String) values.get("TABLE_NAME"), (String) values.get("COLUMN_NAME"))) {
                    column.setMappedTypeCode(Types.BIGINT);
                }
            } else if (column.getSizeAsInt() <= 63) {
                column.setMappedTypeCode(Types.REAL);
            } else {
                column.setMappedTypeCode(Types.DOUBLE);
            }
        }
    } else if (column.getMappedTypeCode() == Types.FLOAT) {
        // Same for REAL, FLOAT, DOUBLE PRECISION, which all back-map to
        // FLOAT but with
        // different sizes (63 for REAL, 126 for FLOAT/DOUBLE PRECISION)
        switch (column.getSizeAsInt()) {
        case 63:
            column.setMappedTypeCode(Types.REAL);
            break;
        case 126:
            column.setMappedTypeCode(Types.DOUBLE);
            break;
        }
    } else if ((column.getMappedTypeCode() == Types.DATE) || (column.getMappedTypeCode() == Types.TIMESTAMP)) {
        // we also reverse the ISO-format adaptation, and adjust the default
        // value to timestamp
        if (column.getDefaultValue() != null) {
            Timestamp timestamp = null;

            Matcher matcher = oracleIsoTimestampPattern.matcher(column.getDefaultValue());

            if (matcher.matches()) {
                String timestampVal = matcher.group(1);
                timestamp = Timestamp.valueOf(timestampVal);
            } else {
                matcher = oracleIsoDatePattern.matcher(column.getDefaultValue());
                if (matcher.matches()) {
                    String dateVal = matcher.group(1);
                    timestamp = new Timestamp(Date.valueOf(dateVal).getTime());
                } else {
                    matcher = oracleIsoTimePattern.matcher(column.getDefaultValue());
                    if (matcher.matches()) {
                        String timeVal = matcher.group(1);

                        timestamp = new Timestamp(Time.valueOf(timeVal).getTime());
                    }
                }
            }
            if (timestamp != null) {
                column.setDefaultValue(timestamp.toString());
            }
        }
    } else if (TypeMap.isTextType(column.getMappedTypeCode())) {
        String defaultValue = column.getDefaultValue();
        if (isNotBlank(defaultValue) && defaultValue.startsWith("('") && defaultValue.endsWith("')")) {
            defaultValue = defaultValue.substring(2, defaultValue.length() - 2);
        }
        column.setDefaultValue(unescape(defaultValue, "'", "''"));
    }
    return column;
}

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

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