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.voltdb.HsqlBackend.java

VoltTable runSQLWithSubstitutions(final SQLStmt stmt, ParameterSet params, byte[] paramJavaTypes) {
    //HSQLProcedureWrapper does nothing smart. it just implements this interface with runStatement()
    StringBuilder sqlOut = new StringBuilder(stmt.getText().length() * 2);

    assert (paramJavaTypes != null);

    int lastIndex = 0;
    String sql = stmt.getText();//  ww  w.jav a 2  s  .c o m

    // if there's no ? in the statmemt, then zero out any auto-parameterization
    int paramCount = StringUtils.countMatches(sql, "?");
    if (paramCount == 0) {
        params = ParameterSet.emptyParameterSet();
        paramJavaTypes = new byte[0];
    }

    Object[] paramObjs = params.toArray();
    for (int i = 0; i < paramObjs.length; i++) {
        int nextIndex = sql.indexOf('?', lastIndex);
        if (nextIndex == -1)
            throw new RuntimeException("SQL Statement has more arguments than params.");
        sqlOut.append(sql, lastIndex, nextIndex);
        lastIndex = nextIndex + 1;

        VoltType type = VoltType.get(paramJavaTypes[i]);

        if (VoltType.isNullVoltType(paramObjs[i])) {
            sqlOut.append("NULL");
        } else if (paramObjs[i] instanceof TimestampType) {
            if (type != VoltType.TIMESTAMP)
                throw new RuntimeException("Inserting date into mismatched column type in HSQL.");
            TimestampType d = (TimestampType) paramObjs[i];
            // convert VoltDB's microsecond granularity to millis.
            Timestamp t = new Timestamp(d.getTime() / 1000);
            sqlOut.append('\'').append(t.toString()).append('\'');
        } else if (paramObjs[i] instanceof byte[]) {
            if (type == VoltType.STRING) {
                // Convert from byte[] -> String; escape single quotes
                try {
                    sqlOut.append(sqlEscape(new String((byte[]) paramObjs[i], "UTF-8")));
                } catch (UnsupportedEncodingException e) {
                    // should NEVER HAPPEN
                    System.err.println("FATAL: Your JVM doens't support UTF-&");
                    System.exit(-1);
                }
            } else if (type == VoltType.VARBINARY) {
                // Convert from byte[] -> String; using hex
                sqlOut.append(sqlEscape(Encoder.hexEncode((byte[]) paramObjs[i])));
            } else {
                throw new RuntimeException(
                        "Inserting string/varbinary (bytes) into mismatched column type in HSQL.");
            }
        } else if (paramObjs[i] instanceof String) {
            if (type != VoltType.STRING)
                throw new RuntimeException("Inserting string into mismatched column type in HSQL.");
            // Escape single quotes
            sqlOut.append(sqlEscape((String) paramObjs[i]));
        } else {
            if (type == VoltType.TIMESTAMP) {
                long t = Long.parseLong(paramObjs[i].toString());
                TimestampType d = new TimestampType(t);
                // convert VoltDB's microsecond granularity to millis
                Timestamp ts = new Timestamp(d.getTime() * 1000);
                sqlOut.append('\'').append(ts.toString()).append('\'');
            } else
                sqlOut.append(paramObjs[i].toString());
        }
    }
    sqlOut.append(sql, lastIndex, sql.length());

    return runDML(sqlOut.toString());
}

From source file:org.apache.hive.storage.jdbc.spitter.TimestampIntervalSplitter.java

@Override
public List<MutablePair<String, String>> getIntervals(String lowerBound, String upperBound, int numPartitions,
        TypeInfo typeInfo) {//from   ww  w.  ja  v a 2  s . c  o  m
    List<MutablePair<String, String>> intervals = new ArrayList<>();
    Timestamp timestampLower = Timestamp.valueOf(lowerBound);
    Timestamp timestampUpper = Timestamp.valueOf(upperBound);
    // Note nano is not fully represented as the precision limit
    double timestampInterval = (timestampUpper.getTime() - timestampLower.getTime()) / (double) numPartitions;
    Timestamp splitTimestampLower, splitTimestampUpper;
    for (int i = 0; i < numPartitions; i++) {
        splitTimestampLower = new Timestamp(Math.round(timestampLower.getTime() + timestampInterval * i));
        splitTimestampUpper = new Timestamp(Math.round(timestampLower.getTime() + timestampInterval * (i + 1)));
        if (splitTimestampLower.compareTo(splitTimestampUpper) < 0) {
            intervals.add(new MutablePair<String, String>(splitTimestampLower.toString(),
                    splitTimestampUpper.toString()));
        }
    }
    return intervals;
}

From source file:org.gdms.driver.csv.CSVDriver.java

@Override
public String getStatementString(Timestamp ts) {
    return ts.toString();
}

From source file:it.cnr.icar.eric.server.persistence.rdb.AuditableEventDAO.java

/**
 * Returns the SQL fragment string needed by insert or update statements 
 * within insert or update method of sub-classes. This is done to avoid code
 * duplication.//from  ww w  .  j  av a  2  s.c o  m
 */
protected String getSQLStatementFragment(Object ro) throws RegistryException {

    AuditableEventType auditableEvent = (AuditableEventType) ro;

    String stmtFragment = null;

    try {

        String requestId = auditableEvent.getRequestId();
        String eventType = auditableEvent.getEventType();

        if (auditableEvent.getTimestamp() == null) {
            XMLGregorianCalendar timeNow;
            timeNow = DatatypeFactory.newInstance().newXMLGregorianCalendar(new GregorianCalendar());

            auditableEvent.setTimestamp(timeNow);
        }

        Timestamp timestamp = new Timestamp(
                auditableEvent.getTimestamp().toGregorianCalendar().getTimeInMillis());

        // ??The timestamp is being truncated to work around a bug in
        // PostgreSQL 7.2.2 JDBC driver
        String timestampStr = timestamp.toString().substring(0, 19);

        String aeUser = auditableEvent.getUser();
        if (aeUser == null) {
            UserType user = context.getUser();
            if (user != null) {
                aeUser = user.getId();
            }
        }

        if (action == DAO_ACTION_INSERT) {
            stmtFragment = "INSERT INTO AuditableEvent " + super.getSQLStatementFragment(ro) + ", '" + requestId
                    + "', '" + eventType + "', '" + timestampStr + "', '" + aeUser + "' ) ";
        } else if (action == DAO_ACTION_UPDATE) {
            stmtFragment = "UPDATE AuditableEvent SET " + super.getSQLStatementFragment(ro) + ", requestId='"
                    + requestId + "', eventType='" + eventType + "', timestamp_='" + timestampStr + "', user_='"
                    + aeUser + "' WHERE id = '" + ((RegistryObjectType) ro).getId() + "' ";
        } else if (action == DAO_ACTION_DELETE) {
            stmtFragment = super.getSQLStatementFragment(ro);
        }
    } catch (DatatypeConfigurationException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    return stmtFragment;
}

From source file:uk.ac.kcl.partitioners.RealtimePKRangePartitioner.java

private ScheduledPartitionParams getParams(Timestamp startTimeStamp) {
    JdbcTemplate jdbcTemplate = new JdbcTemplate(sourceDataSource);
    String sql = "\n SELECT " + " MAX(" + column + ") AS max_id , \n" + " MIN(" + column + ") AS min_id , \n"
            + " MAX(" + timeStamp + ") AS max_time_stamp , \n" + " MIN(" + timeStamp + ") AS min_time_stamp  \n"
            + " FROM " + table;
    if (configuredFirstRunTimestamp != null && firstRun) {
        sql = sql + " WHERE " + timeStamp + " >= CAST ('" + startTimeStamp.toString() + "' as "
                + env.getProperty("dbmsToJavaSqlTimestampType") + " ) ";
    } else if (startTimeStamp == null) {
        Timestamp newStartTimeStamp = getLastTimestampFromLastSuccessfulJob();
        logger.info("Commencing from after " + newStartTimeStamp.toString());
        sql = sql + "\n WHERE CAST (" + timeStamp + " as " + env.getProperty("dbmsToJavaSqlTimestampType")
                + " ) > CAST ('" + newStartTimeStamp.toString() + "' as "
                + env.getProperty("dbmsToJavaSqlTimestampType") + " ) ";
    } else if (firstRun) {
        //no new SQL required - process all data for first run
        logger.debug("first run");
    } else {//from w w w . j av a 2s  . co m
        throw new RuntimeException("unable to determine partition requirement");
    }
    logger.info("This job SQL: " + sql);
    return (ScheduledPartitionParams) jdbcTemplate.queryForObject(sql, new PartitionParamsRowMapper());
}

From source file:com.softech.tbb.bean.Bean.java

/**
 * Set the contributed of the article.//from  w  w  w  . ja v a2 s . c om
 * <p>
 * 
 * @param contributed
 *            The new contributed
 */
public String getContributedDisplay() {
    Timestamp contributed = getContributed();

    if (contributed == null) {
        return null;
    } else {
        return contributed.toString();
    }
}

From source file:uk.org.funcube.fcdw.server.extract.csv.WodCsvExtractor.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) throws IOException {
    for (int i = 0; i < 15; i++) {

        switch (i) {
        case 0:/*from  ww  w  .  j  a  va2s  .c om*/
            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;
        }

    }

    csvOutput.endRecord();
}

From source file:cn.mljia.common.notify.utils.DateUtils.java

/**
 * ???java.sql.TimestampString//from   w ww  .j  a va2 s . c  om
 * 
 * @param dt
 *            java.sql.Timestamp instance
 * @param sFmt
 *            Date ?DATE_FORMAT_DATEONLY/DATE_FORMAT_DATETIME/
 *            DATE_FORMAT_SESSION
 * @return
 * @since 1.0
 * @history
 */
public static String toSqlTimestampString(java.sql.Timestamp dt, String sFmt) {
    String temp = null;
    String out = null;
    if (dt == null || sFmt == null) {
        return null;
    }
    temp = dt.toString();
    if (sFmt.equals(DateUtils.DATE_FORMAT_DATETIME) || // "YYYY/MM/DD
    // HH24:MI:SS"
            sFmt.equals(DateUtils.DATE_FORMAT_DATEONLY)) { // YYYY/MM/DD
        temp = temp.substring(0, sFmt.length());
        out = temp.replace('/', '-');
        // }else if( sFmt.equals (DateUtils.DATE_FORMAT_SESSION ) ){
        // //Session
        // out =
        // temp.substring(0,4)+temp.substring(5,7)+temp.substring(8,10);
        // out += temp.substring(12,14) + temp.substring(15,17);
    }
    return out;
}

From source file:com.funambol.tools.test.PostSyncML.java

private void saveEndTestError(String cause, File file) throws IOException {

    FileOutputStream fos = new FileOutputStream(file);
    Timestamp t = new Timestamp(System.currentTimeMillis());
    String m = "<!-- " + t.toString() + " -->\n";
    fos.write(m.getBytes());//from   ww w. j  a  va2 s  . c o  m
    fos.write(cause.getBytes());
    fos.close();
}

From source file:com.funambol.tools.test.PostSyncML.java

/**
 * Saves the given diff element to the given file
 *
 * @param diffs the diff element//from  w  ww  . ja  v  a  2 s  . c  o m
 * @param file the file to save into
 */
private void saveDiffs(Element diffs, File file) throws IOException {
    XMLOutputter xmlo = new XMLOutputter("  ", true);
    xmlo.setTextNormalize(true);

    FileOutputStream fos = new FileOutputStream(file);
    Timestamp t = new Timestamp(System.currentTimeMillis());
    String m = "<!-- " + t.toString() + " -->\n";
    fos.write(m.getBytes());
    xmlo.output(diffs, fos);
    fos.close();
}