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.plos.repo.RepoServiceSpringTest.java

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

    Calendar cal = Calendar.getInstance();
    cal.setTimeInMillis(0);//from w  ww . ja  va 2  s  . co m
    cal.set(2014, 10, 30, 1, 1, 1);
    Timestamp creationDateTime1 = new Timestamp(cal.getTime().getTime());

    // create object with creation date time
    InputRepoObject inputRepoObject = createInputRepoObject();
    inputRepoObject.setCreationDateTime(creationDateTime1.toString());
    inputRepoObject.setTimestamp(creationDateTime1.toString());
    inputRepoObject.setTag("FINAL");
    repoService.createObject(RepoService.CreateMethod.NEW, inputRepoObject);

    cal.set(2014, 10, 20, 1, 1, 1);
    Timestamp creationDateTime2 = new Timestamp(cal.getTime().getTime());
    // create object with creation date time before object 1 creation date time
    inputRepoObject.setCreationDateTime(creationDateTime2.toString());
    inputRepoObject.setTimestamp(creationDateTime2.toString());
    repoService.createObject(RepoService.CreateMethod.VERSION, inputRepoObject);

    // get the latest object
    RepoObject repoObject = repoService.getObject(bucket1.getBucketName(), KEY,
            new ElementFilter(null, "FINAL", null));

    // object must match the one with the oldest creation time
    Assert.assertEquals(new Integer(0), repoObject.getVersionNumber());
    Assert.assertEquals(creationDateTime1, repoObject.getCreationDate());
}

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

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

    Calendar cal = Calendar.getInstance();
    cal.setTimeInMillis(0);//from   ww w .  ja  va 2s  . c  om
    cal.set(2014, 10, 30, 1, 1, 1);
    Timestamp creationDateTime1 = new Timestamp(cal.getTime().getTime());

    // create object with creation date time
    InputRepoObject inputRepoObject = createInputRepoObject();
    inputRepoObject.setCreationDateTime(creationDateTime1.toString());
    inputRepoObject.setTimestamp(creationDateTime1.toString());
    inputRepoObject.setTag("DRAFT");
    repoService.createObject(RepoService.CreateMethod.NEW, inputRepoObject);

    cal.set(2014, 10, 20, 1, 1, 1);
    Timestamp creationDateTime2 = new Timestamp(cal.getTime().getTime());
    inputRepoObject.setCreationDateTime(creationDateTime2.toString());
    inputRepoObject.setUploadedInputStream(IOUtils.toInputStream("data2"));
    inputRepoObject.setTimestamp(creationDateTime2.toString());
    // create object with creation date time before object 1 creation date time
    RepoObject repoObject = repoService.createObject(RepoService.CreateMethod.VERSION, inputRepoObject);

    // get the latest object
    RepoObject resultRepoObject = repoService.getObject(bucket1.getBucketName(), KEY,
            new ElementFilter(null, null, repoObject.getUuid().toString()));

    // object must match the one with the oldest creation time
    Assert.assertEquals(new Integer(1), resultRepoObject.getVersionNumber());
    Assert.assertEquals(creationDateTime2, resultRepoObject.getCreationDate());
    Assert.assertEquals(repoObject.getUuid(), resultRepoObject.getUuid());
}

From source file:uk.org.funcube.fcdw.server.extract.csv.RealTimeCsvExtractor.java

private void writeRecord(CsvWriter csvOutput, Timestamp satelliteTime, String c1, String c2, String c3,
        String c4, String c5, String c6, String c7, String c8, String c9, String c10, String c11, String c12,
        String c13, String c14, String c15, String c16, String c17, String c18, String c19, String c20,
        String c21, String c22, String c23, String c24, String c25, String c26, String c27, String c28)
        throws IOException {
    for (int i = 0; i < 31; i++) {

        switch (i) {
        case 0:/*from   ww w  . j  ava2 s.co m*/
            csvOutput.write(satelliteTime.toString());
            break;
        case 1:
            csvOutput.write(c1);
            break;
        case 2:
            csvOutput.write(c2);
            break;
        case 3:
            csvOutput.write(c3);
            break;
        case 4:
            csvOutput.write(c4);
            break;
        case 5:
            csvOutput.write(c5);
            break;
        case 6:
            csvOutput.write(c6);
            break;
        case 7:
            csvOutput.write(c7);
            break;
        case 8:
            csvOutput.write(c8);
            break;
        case 9:
            csvOutput.write(c9);
            break;
        case 10:
            csvOutput.write(c10);
            break;
        case 11:
            csvOutput.write(c11);
            break;
        case 12:
            csvOutput.write(c12);
            break;
        case 13:
            csvOutput.write(c13);
            break;
        case 14:
            csvOutput.write(c14);
            break;
        case 15:
            csvOutput.write(c15);
            break;
        case 16:
            csvOutput.write(c16);
            break;
        case 17:
            csvOutput.write(c17);
            break;
        case 18:
            csvOutput.write(c18);
            break;
        case 19:
            csvOutput.write(c19);
            break;
        case 20:
            csvOutput.write(c20);
            break;
        case 21:
            csvOutput.write(c21);
            break;
        case 22:
            csvOutput.write(c22);
            break;
        case 23:
            csvOutput.write(c23);
            break;
        case 24:
            csvOutput.write(c24);
            break;
        case 25:
            csvOutput.write(c25);
            break;
        case 26:
            csvOutput.write(c26);
            break;
        case 27:
            csvOutput.write(c27);
            break;
        case 28:
            csvOutput.write(c28);
            break;
        }

    }

    csvOutput.endRecord();
}

From source file:org.accada.epcis.repository.query.QueryOperationsBackendSQL.java

/**
 * {@inheritDoc}//from   w  ww  .j  a va  2s  . c o  m
 */
public void storeSupscriptions(final QueryOperationsSession session, QueryParams queryParams, String dest,
        String subscrId, SubscriptionControls controls, String trigger,
        QuerySubscriptionScheduled newSubscription, String queryName, Schedule schedule)
        throws SQLException, ImplementationExceptionResponse {
    String insert = "INSERT INTO subscription (subscriptionid, "
            + "params, dest, sched, trigg, initialrecordingtime, "
            + "exportifempty, queryname, lastexecuted) VALUES "
            + "((?), (?), (?), (?), (?), (?), (?), (?), (?))";
    PreparedStatement stmt = session.getConnection().prepareStatement(insert);
    LOG.debug("QUERY: " + insert);
    try {
        stmt.setString(1, subscrId);
        LOG.debug("       query param 1: " + subscrId);

        ByteArrayOutputStream outStream = new ByteArrayOutputStream();
        ObjectOutput out = new ObjectOutputStream(outStream);
        out.writeObject(queryParams);
        ByteArrayInputStream inStream = new ByteArrayInputStream(outStream.toByteArray());
        stmt.setBinaryStream(2, inStream, inStream.available());
        LOG.debug("       query param 2: [" + inStream.available() + " bytes]");

        stmt.setString(3, dest.toString());
        LOG.debug("       query param 3: " + dest);

        outStream = new ByteArrayOutputStream();
        out = new ObjectOutputStream(outStream);
        out.writeObject(schedule);
        inStream = new ByteArrayInputStream(outStream.toByteArray());
        stmt.setBinaryStream(4, inStream, inStream.available());
        LOG.debug("       query param 4: [" + inStream.available() + " bytes]");

        stmt.setString(5, trigger);
        LOG.debug("       query param 5: " + trigger);

        Calendar cal = newSubscription.getInitialRecordTime();
        Timestamp ts = new Timestamp(cal.getTimeInMillis());
        String time = ts.toString();
        stmt.setString(6, time);
        LOG.debug("       query param 6: " + time);

        stmt.setBoolean(7, controls.isReportIfEmpty());
        LOG.debug("       query param 7: " + controls.isReportIfEmpty());

        stmt.setString(8, queryName);
        LOG.debug("       query param 8: " + queryName);

        stmt.setString(9, time);
        LOG.debug("       query param 9: " + time);

        stmt.executeUpdate();
    } catch (IOException e) {
        String msg = "Unable to store the subscription to the database: " + e.getMessage();
        LOG.error(msg);
        ImplementationException iex = new ImplementationException();
        iex.setReason(msg);
        iex.setSeverity(ImplementationExceptionSeverity.ERROR);
        throw new ImplementationExceptionResponse(msg, iex, e);
    }
}

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

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

    Calendar cal = Calendar.getInstance();
    cal.setTimeInMillis(0);//from   www . jav a 2 s. c o m
    cal.set(2014, 10, 30, 1, 1, 1);
    Timestamp creationDateTime1 = new Timestamp(cal.getTime().getTime());

    String key = KEY;
    // create object with creation date time
    InputRepoObject inputRepoObject = createInputRepoObject();
    inputRepoObject.setCreationDateTime(creationDateTime1.toString());
    inputRepoObject.setTimestamp(creationDateTime1.toString());
    inputRepoObject.setTag("DRAFT");
    repoService.createObject(RepoService.CreateMethod.NEW, inputRepoObject);

    cal.set(2014, 10, 20, 1, 1, 1);
    Timestamp creationDateTime2 = new Timestamp(cal.getTime().getTime());
    // create object with creation date time before object 1 creation date time
    inputRepoObject.setCreationDateTime(creationDateTime2.toString());
    inputRepoObject.setTimestamp(creationDateTime2.toString());
    inputRepoObject.setTag("FINAL");
    repoService.createObject(RepoService.CreateMethod.VERSION, inputRepoObject);

    // get the latest object
    RepoObject repoObject = repoService.getObject(bucket1.getBucketName(), key,
            new ElementFilter(null, "DRAFT", null));

    // object must match the one with the oldest creation time
    Assert.assertEquals(new Integer(0), repoObject.getVersionNumber());
    Assert.assertEquals(creationDateTime1, repoObject.getCreationDate());
}

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

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

    try {//from w w  w.  ja v a 2 s  .com
        InputRepoObject inputRepoObject = createInputRepoObject();
        repoService.createObject(RepoService.CreateMethod.NEW, inputRepoObject);

        Timestamp creationDateTimeObj2 = new Timestamp(new Date().getTime());
        inputRepoObject.setContentType("new content type");
        inputRepoObject.setDownloadName("new download name");
        inputRepoObject.setTimestamp(creationDateTimeObj2.toString());
        inputRepoObject.setUploadedInputStream(IOUtils.toInputStream("data2"));
        inputRepoObject.setCreationDateTime(creationDateTimeObj2.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(),
            Operation.UPDATE_OBJECT, null);
    Assert.assertTrue(auditList.size() == 1);
    Assert.assertTrue(auditList.get(0).getOperation().equals(Operation.UPDATE_OBJECT));

    sqlService.releaseConnection();

    Assert.assertTrue(objectStore.objectExists(objFromDb));
    Assert.assertTrue(IOUtils.toString(objectStore.getInputStream(objFromDb)).equals("data2"));

    // 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("data2"));

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

From source file:org.freebxml.omar.server.query.QueryManagerImpl.java

/**
 * Replaces special environment variables within specified query string.
 */// w  ww .j av a2  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.fosstrak.epcis.repository.query.QueryOperationsBackendSQL.java

/**
 * {@inheritDoc}//from  w w  w  .  java  2s .  com
 */
public void storeSupscriptions(final QueryOperationsSession session, QueryParams queryParams, String dest,
        String subscrId, SubscriptionControls controls, String trigger,
        QuerySubscriptionScheduled newSubscription, String queryName, Schedule schedule)
        throws SQLException, ImplementationExceptionResponse {
    String insert = "INSERT INTO subscription (subscriptionid, "
            + "params, dest, sched, trigg, initialrecordingtime, "
            + "exportifempty, queryname, lastexecuted) VALUES "
            + "((?), (?), (?), (?), (?), (?), (?), (?), (?))";
    PreparedStatement stmt = session.getConnection().prepareStatement(insert);
    LOG.debug("QUERY: " + insert);
    try {
        stmt.setString(1, subscrId);
        LOG.debug("       query param 1: " + subscrId);

        ByteArrayOutputStream outStream = new ByteArrayOutputStream();
        ObjectOutput out = new ObjectOutputStream(outStream);
        out.writeObject(queryParams);
        ByteArrayInputStream inStream = new ByteArrayInputStream(outStream.toByteArray());
        stmt.setBinaryStream(2, inStream, inStream.available());
        LOG.debug("       query param 2: [" + inStream.available() + " bytes]");

        stmt.setString(3, dest.toString());
        LOG.debug("       query param 3: " + dest);

        outStream = new ByteArrayOutputStream();
        out = new ObjectOutputStream(outStream);
        out.writeObject(schedule);
        inStream = new ByteArrayInputStream(outStream.toByteArray());
        stmt.setBinaryStream(4, inStream, inStream.available());
        LOG.debug("       query param 4: [" + inStream.available() + " bytes]");

        stmt.setString(5, trigger);
        LOG.debug("       query param 5: " + trigger);

        Calendar cal = newSubscription.getInitialRecordTime();
        Timestamp ts = new Timestamp(cal.getTimeInMillis());
        String time = ts.toString();
        stmt.setString(6, time);
        LOG.debug("       query param 6: " + time);

        stmt.setBoolean(7, controls.isReportIfEmpty());
        LOG.debug("       query param 7: " + controls.isReportIfEmpty());

        stmt.setString(8, queryName);
        LOG.debug("       query param 8: " + queryName);

        stmt.setString(9, time);
        LOG.debug("       query param 9: " + time);

        stmt.executeUpdate();
        session.commit();
    } catch (IOException e) {
        String msg = "Unable to store the subscription to the database: " + e.getMessage();
        LOG.error(msg);
        ImplementationException iex = new ImplementationException();
        iex.setReason(msg);
        iex.setSeverity(ImplementationExceptionSeverity.ERROR);
        throw new ImplementationExceptionResponse(msg, iex, e);
    }
}

From source file:com.streamsets.pipeline.lib.jdbc.JdbcUtil.java

public Field resultToField(ResultSetMetaData md, ResultSet rs, int columnIndex, int maxClobSize,
        int maxBlobSize, DataType userSpecifiedType, UnknownTypeAction unknownTypeAction,
        boolean timestampToString) throws SQLException, IOException, StageException {
    Field field;/*w w w.j  ava 2 s  .co  m*/
    if (userSpecifiedType != DataType.USE_COLUMN_TYPE) {
        // If user specifies the data type, overwrite the column type returned by database.
        field = Field.create(Field.Type.valueOf(userSpecifiedType.getLabel()), rs.getObject(columnIndex));
    } else {
        // All types as of JDBC 2.0 are here:
        // https://docs.oracle.com/javase/8/docs/api/constant-values.html#java.sql.Types.ARRAY
        // Good source of recommended mappings is here:
        // http://www.cs.mun.ca/java-api-1.5/guide/jdbc/getstart/mapping.html
        switch (md.getColumnType(columnIndex)) {
        case Types.BIGINT:
            field = Field.create(Field.Type.LONG, rs.getObject(columnIndex));
            break;
        case Types.BINARY:
        case Types.LONGVARBINARY:
        case Types.VARBINARY:
            field = Field.create(Field.Type.BYTE_ARRAY, rs.getBytes(columnIndex));
            break;
        case Types.BIT:
        case Types.BOOLEAN:
            field = Field.create(Field.Type.BOOLEAN, rs.getObject(columnIndex));
            break;
        case Types.CHAR:
        case Types.LONGNVARCHAR:
        case Types.LONGVARCHAR:
        case Types.NCHAR:
        case Types.NVARCHAR:
        case Types.VARCHAR:
            field = Field.create(Field.Type.STRING, rs.getObject(columnIndex));
            break;
        case Types.CLOB:
        case Types.NCLOB:
            field = Field.create(Field.Type.STRING, getClobString(rs.getClob(columnIndex), maxClobSize));
            break;
        case Types.BLOB:
            field = Field.create(Field.Type.BYTE_ARRAY, getBlobBytes(rs.getBlob(columnIndex), maxBlobSize));
            break;
        case Types.DATE:
            field = Field.create(Field.Type.DATE, rs.getDate(columnIndex));
            break;
        case Types.DECIMAL:
        case Types.NUMERIC:
            field = Field.create(Field.Type.DECIMAL, rs.getBigDecimal(columnIndex));
            field.setAttribute(HeaderAttributeConstants.ATTR_SCALE,
                    String.valueOf(rs.getMetaData().getScale(columnIndex)));
            field.setAttribute(HeaderAttributeConstants.ATTR_PRECISION,
                    String.valueOf(rs.getMetaData().getPrecision(columnIndex)));
            break;
        case Types.DOUBLE:
            field = Field.create(Field.Type.DOUBLE, rs.getObject(columnIndex));
            break;
        case Types.FLOAT:
        case Types.REAL:
            field = Field.create(Field.Type.FLOAT, rs.getObject(columnIndex));
            break;
        case Types.INTEGER:
            field = Field.create(Field.Type.INTEGER, rs.getObject(columnIndex));
            break;
        case Types.ROWID:
            field = Field.create(Field.Type.STRING, rs.getRowId(columnIndex).toString());
            break;
        case Types.SMALLINT:
        case Types.TINYINT:
            field = Field.create(Field.Type.SHORT, rs.getObject(columnIndex));
            break;
        case Types.TIME:
            field = Field.create(Field.Type.TIME, rs.getObject(columnIndex));
            break;
        case Types.TIMESTAMP:
            final Timestamp timestamp = rs.getTimestamp(columnIndex);
            if (timestampToString) {
                field = Field.create(Field.Type.STRING, timestamp == null ? null : timestamp.toString());
            } else {
                field = Field.create(Field.Type.DATETIME, timestamp);
                if (timestamp != null) {
                    final long actualNanos = timestamp.getNanos() % NANOS_TO_MILLIS_ADJUSTMENT;
                    if (actualNanos > 0) {
                        field.setAttribute(FIELD_ATTRIBUTE_NANOSECONDS, String.valueOf(actualNanos));
                    }
                }
            }
            break;
        // Ugly hack until we can support LocalTime, LocalDate, LocalDateTime, etc.
        case Types.TIME_WITH_TIMEZONE:
            OffsetTime offsetTime = rs.getObject(columnIndex, OffsetTime.class);
            field = Field.create(Field.Type.TIME, Date.from(offsetTime.atDate(LocalDate.MIN).toInstant()));
            break;
        case Types.TIMESTAMP_WITH_TIMEZONE:
            OffsetDateTime offsetDateTime = rs.getObject(columnIndex, OffsetDateTime.class);
            field = Field.create(Field.Type.ZONED_DATETIME, offsetDateTime.toZonedDateTime());
            break;
        //case Types.REF_CURSOR: // JDK8 only
        case Types.SQLXML:
        case Types.STRUCT:
        case Types.ARRAY:
        case Types.DATALINK:
        case Types.DISTINCT:
        case Types.JAVA_OBJECT:
        case Types.NULL:
        case Types.OTHER:
        case Types.REF:
        default:
            if (unknownTypeAction == null) {
                return null;
            }
            switch (unknownTypeAction) {
            case STOP_PIPELINE:
                throw new StageException(JdbcErrors.JDBC_37, md.getColumnType(columnIndex),
                        md.getColumnLabel(columnIndex));
            case CONVERT_TO_STRING:
                Object value = rs.getObject(columnIndex);
                if (value != null) {
                    field = Field.create(Field.Type.STRING, rs.getObject(columnIndex).toString());
                } else {
                    field = Field.create(Field.Type.STRING, null);
                }
                break;
            default:
                throw new IllegalStateException("Unknown action: " + unknownTypeAction);
            }
        }
    }

    return field;
}

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

public void removeExpiredSessionData(Timestamp timestamp) {
    Connection connection = null;
    PreparedStatement statement = null;
    try {//from w w  w . j a v  a2s  .c  om
        connection = IdentityDatabaseUtil.getDBConnection();
    } catch (IdentityRuntimeException e) {
        log.error(e.getMessage(), e);
        return;
    }
    try {
        statement = connection.prepareStatement(sqlDeleteExpiredDataTask);
        statement.setLong(1, timestamp.getTime());
        statement.execute();
        if (!connection.getAutoCommit()) {
            connection.commit();
        }
    } catch (SQLException e) {
        log.error(
                "Error while removing session data from the database for the timestamp " + timestamp.toString(),
                e);
    } finally {
        IdentityDatabaseUtil.closeAllConnections(connection, null, statement);

    }
}