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:org.plasma.sdo.access.provider.jdbc.JDBCDataConverter.java

public Object fromJDBCDataType(ResultSet rs, int columnIndex, int sourceType, PlasmaProperty targetProperty)
        throws SQLException {

    Object result = null;/*from ww  w . jav a 2s  .  co  m*/

    if (targetProperty.getType().isDataType()) {
        DataType targetDataType = DataType.valueOf(targetProperty.getType().getName());

        switch (targetDataType) {
        case String:
        case URI:
        case Month:
        case MonthDay:
        case Day:
        case Time:
        case Year:
        case YearMonth:
        case YearMonthDay:
        case Duration:
            result = rs.getString(columnIndex);
            break;
        case Date:
            java.sql.Timestamp ts = rs.getTimestamp(columnIndex);
            if (ts != null)
                result = new java.util.Date(ts.getTime());
            break;
        case DateTime:
            ts = rs.getTimestamp(columnIndex);
            if (ts != null)
                result = new java.util.Date(ts.getTime());
            break;
        case Decimal:
            result = rs.getBigDecimal(columnIndex);
            break;
        case Bytes:
            result = rs.getBytes(columnIndex);
            break;
        case Byte:
            result = rs.getByte(columnIndex);
            break;
        case Boolean:
            result = rs.getBoolean(columnIndex);
            break;
        case Character:
            result = rs.getInt(columnIndex);
            break;
        case Double:
            result = rs.getDouble(columnIndex);
            break;
        case Float:
            result = rs.getFloat(columnIndex);
            break;
        case Int:
            result = rs.getInt(columnIndex);
            break;
        case Integer:
            result = new BigInteger(rs.getString(columnIndex));
            break;
        case Long:
            result = rs.getLong(columnIndex);
            break;
        case Short:
            result = rs.getShort(columnIndex);
            break;
        case Strings:
            String value = rs.getString(columnIndex);
            String[] values = value.split("\\s");
            List<String> list = new ArrayList<String>(values.length);
            for (int i = 0; i < values.length; i++)
                list.add(values[i]); // what no Java 5 sugar for this ??
            result = list;
            break;
        case Object:
        default:
            result = rs.getObject(columnIndex);
            break;
        }
    } else {
        // FIXME: or get the opposite containing type
        // of the property and get its pri-key(s)
        result = rs.getObject(columnIndex);
    }

    return result;
}

From source file:org.apache.sqoop.mapreduce.hcat.SqoopHCatExportHelper.java

private Object convertStringTypes(Object val, String javaColType) {
    String valStr = val.toString();
    if (javaColType.equals(BIG_DECIMAL_TYPE)) {
        return new BigDecimal(valStr);
    } else if (javaColType.equals(DATE_TYPE) || javaColType.equals(TIME_TYPE)
            || javaColType.equals(TIMESTAMP_TYPE)) {
        // Oracle expects timestamps for Date also by default based on version
        // Just allow all date types to be assignment compatible
        if (valStr.length() == 10 && valStr.matches("^\\d{4}-\\d{2}-\\d{2}$")) {
            // Date in yyyy-mm-dd format
            Date d = Date.valueOf(valStr);
            if (javaColType.equals(DATE_TYPE)) {
                return d;
            } else if (javaColType.equals(TIME_TYPE)) {
                return new Time(d.getTime());
            } else if (javaColType.equals(TIMESTAMP_TYPE)) {
                return new Timestamp(d.getTime());
            }//w w  w.  ja  va2 s .c o m
        } else if (valStr.length() == 8 && valStr.matches("^\\d{2}:\\d{2}:\\d{2}$")) {
            // time in hh:mm:ss
            Time t = Time.valueOf(valStr);
            if (javaColType.equals(DATE_TYPE)) {
                return new Date(t.getTime());
            } else if (javaColType.equals(TIME_TYPE)) {
                return t;
            } else if (javaColType.equals(TIMESTAMP_TYPE)) {
                return new Timestamp(t.getTime());
            }
        } else if (valStr.length() >= 19 && valStr.length() <= 26
                && valStr.matches("^\\d{4}-\\d{2}-\\d{2} \\d{2}:\\d{2}:\\d{2}(.\\d+)?$")) {
            // timestamp in yyyy-mm-dd hh:mm:ss
            Timestamp ts = Timestamp.valueOf(valStr);
            if (javaColType.equals(DATE_TYPE)) {
                return new Date(ts.getTime());
            } else if (javaColType.equals(TIME_TYPE)) {
                return new Time(ts.getTime());
            } else if (javaColType.equals(TIMESTAMP_TYPE)) {
                return ts;
            }
        } else {
            return null;
        }
    } else if (javaColType.equals(STRING_TYPE)) {
        return valStr;
    } else if (javaColType.equals(BOOLEAN_TYPE)) {
        return Boolean.valueOf(valStr);
    } else if (javaColType.equals(BYTE_TYPE)) {
        return Byte.parseByte(valStr);
    } else if (javaColType.equals(SHORT_TYPE)) {
        return Short.parseShort(valStr);
    } else if (javaColType.equals(INTEGER_TYPE)) {
        return Integer.parseInt(valStr);
    } else if (javaColType.equals(LONG_TYPE)) {
        return Long.parseLong(valStr);
    } else if (javaColType.equals(FLOAT_TYPE)) {
        return Float.parseFloat(valStr);
    } else if (javaColType.equals(DOUBLE_TYPE)) {
        return Double.parseDouble(valStr);
    }
    return null;
}

From source file:org.apache.ofbiz.entity.transaction.TransactionUtil.java

public static Timestamp getTransactionUniqueNowStamp() {
    Timestamp lastNowStamp = transactionLastNowStamp.get();
    Timestamp nowTimestamp = UtilDateTime.nowTimestamp();

    // check for an overlap with the lastNowStamp, or if the lastNowStamp is in the future because of incrementing to make each stamp unique
    if (lastNowStamp != null && (lastNowStamp.equals(nowTimestamp) || lastNowStamp.after(nowTimestamp))) {
        nowTimestamp = new Timestamp(lastNowStamp.getTime() + 1);
    }/*w w w .jav a2s  .c o  m*/

    transactionLastNowStamp.set(nowTimestamp);
    return nowTimestamp;
}

From source file:data.DefaultExchanger.java

protected void putTimestamp(JsonGenerator generator, String fieldName, ResultSet rs, short index)
        throws SQLException, IOException {
    generator.writeFieldName(fieldName);
    Timestamp timestamp = rs.getTimestamp(index);
    if (timestamp == null) {
        generator.writeNull();//from ww  w  .j a  va 2  s.c o  m
    } else {
        generator.writeNumber(timestamp.getTime());
    }
}

From source file:org.apache.sqoop.mapreduce.hcat.SqoopHCatExportHelper.java

private Object convertToSqoop(Object val, HCatFieldSchema.Type fieldType, String javaColType,
        String hCatTypeString) throws IOException {

    if (val == null) {
        return null;
    }//www.  j  a  v  a2 s  . c om

    switch (fieldType) {
    case INT:
    case TINYINT:
    case SMALLINT:
    case FLOAT:
    case DOUBLE:
        val = convertNumberTypes(val, javaColType);
        if (val != null) {
            return val;
        }
        break;
    case BOOLEAN:
        val = convertBooleanTypes(val, javaColType);
        if (val != null) {
            return val;
        }
        break;
    case BIGINT:
        if (javaColType.equals(DATE_TYPE)) {
            return new Date((Long) val);
        } else if (javaColType.equals(TIME_TYPE)) {
            return new Time((Long) val);
        } else if (javaColType.equals(TIMESTAMP_TYPE)) {
            return new Timestamp((Long) val);
        } else {
            val = convertNumberTypes(val, javaColType);
            if (val != null) {
                return val;
            }
        }
        break;
    case DATE:
        Date date = (Date) val;
        if (javaColType.equals(DATE_TYPE)) {
            return date;
        } else if (javaColType.equals(TIME_TYPE)) {
            return new Time(date.getTime());
        } else if (javaColType.equals(TIMESTAMP_TYPE)) {
            return new Timestamp(date.getTime());
        }
        break;
    case TIMESTAMP:
        Timestamp ts = (Timestamp) val;
        if (javaColType.equals(DATE_TYPE)) {
            return new Date(ts.getTime());
        } else if (javaColType.equals(TIME_TYPE)) {
            return new Time(ts.getTime());
        } else if (javaColType.equals(TIMESTAMP_TYPE)) {
            return ts;
        }
        break;
    case STRING:
    case VARCHAR:
    case CHAR:
        val = convertStringTypes(val, javaColType);
        if (val != null) {
            return val;
        }
        break;
    case BINARY:
        val = convertBinaryTypes(val, javaColType);
        if (val != null) {
            return val;
        }
        break;
    case DECIMAL:
        val = convertDecimalTypes(val, javaColType);
        if (val != null) {
            return val;
        }
        break;
    case ARRAY:
    case MAP:
    case STRUCT:
    default:
        throw new IOException("Cannot convert HCatalog type " + fieldType);
    }
    LOG.error("Cannot convert HCatalog object of " + " type " + hCatTypeString + " to java object type "
            + javaColType);
    return null;
}

From source file:com.tesora.dve.sql.CurrentTimestampDefaultValueTest.java

@Ignore
@Test/*  w w w.ja  v  a  2s .co m*/
public void testAlterAddCurrentTimestampStringAsDefault() throws Throwable {
    // make sure user can alter a table and timestamp column default
    conn.execute("create table b (id int, ts timestamp default '2012-05-05 01:00:00.0')");

    SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.ENGLISH);
    long preTestTime = formatter.parse("2012-05-05 01:00:00").getTime();

    // make sure value inserted is the expected value
    conn.execute("insert into b (id) values (1))");
    ResourceResponse resp = conn.fetch("select ts from b where id=1");
    List<ResultRow> rows = resp.getResults();
    assertEquals("Expected one row only", 1, rows.size());

    Timestamp insertedValue = (Timestamp) (rows.get(0).getResultColumn(1).getColumnValue());
    assertTrue("Inserted time must be = starting time", preTestTime == insertedValue.getTime());

    // this fails in native MySQL!
    try {
        String query = "alter table b alter ts set default current_timestamp";
        conn.execute(query);
        fail("Expected alter statement to fail: " + query);
    } catch (PEException e) {
        // expected
    }

    conn.execute("alter table b alter ts drop default");
    conn.execute("insert into b (id) values (2))");
    resp = conn.fetch("select ts from b where id=2");
    rows = resp.getResults();
    assertEquals("Expected one row only", 1, rows.size());

    // TODO mysql fails because the ts column has a not null attribute due to the 
    // default value on create
    // we should fail too but we insert the current timestamp...
    assertTrue("Inserted value must be null", rows.get(0).getResultColumn(1).getColumnValue() == null);
}

From source file:jp.co.opentone.bsol.framework.test.util.AssertMapComparer.java

/**
 * Date??.//from  w w  w.  ja  va 2 s  .  c o  m
 * obj?Date???????????.
 * @param obj ?
 * @param format ?
 * @return ???
 */
private Date convertDate(Object obj, String format) {
    Date result = null;
    try {
        if (null != obj) {
            if (obj instanceof Date) {
                result = (Date) obj;
            } else if (obj instanceof oracle.sql.Datum) {
                if (obj instanceof oracle.sql.TIMESTAMP) {
                    java.sql.Timestamp t = (java.sql.Timestamp) ((oracle.sql.TIMESTAMP) obj).toJdbc();
                    result = new Date(t.getTime());
                } else if (obj instanceof oracle.sql.DATE) {
                    java.sql.Date d = (java.sql.Date) ((oracle.sql.DATE) obj).toJdbc();
                    result = new Date(d.getTime());
                } else {
                    throw new IllegalArgumentException(
                            "not implemented. type[" + obj.getClass().toString() + "]");
                }
            } else {
                result = DateUtils.parseDate(obj.toString(), new String[] { format });
            }
        }
    } catch (ParseException pe) {
        pe.printStackTrace();
    } catch (SQLException e) {
        e.printStackTrace();
    }
    return result;
}

From source file:org.apache.syncope.core.util.ContentExporter.java

private String getValues(final ResultSet rs, final String columnName, final Integer columnType)
        throws SQLException {

    String res = null;/*from   w ww  . j a va 2s  . c o  m*/

    try {
        switch (columnType) {
        case Types.BINARY:
        case Types.VARBINARY:
        case Types.LONGVARBINARY:
            final InputStream is = rs.getBinaryStream(columnName);
            if (is != null) {
                res = new String(Hex.encode(IOUtils.toByteArray(is)));
            }
            break;

        case Types.BLOB:
            final Blob blob = rs.getBlob(columnName);
            if (blob != null) {
                res = new String(Hex.encode(IOUtils.toByteArray(blob.getBinaryStream())));
            }
            break;

        case Types.BIT:
        case Types.BOOLEAN:
            if (rs.getBoolean(columnName)) {
                res = "1";
            } else {
                res = "0";
            }
            break;

        case Types.DATE:
        case Types.TIME:
        case Types.TIMESTAMP:
            final Timestamp timestamp = rs.getTimestamp(columnName);
            if (timestamp != null) {
                res = DataFormat.format(new Date(timestamp.getTime()));
            }
            break;

        default:
            res = rs.getString(columnName);
        }
    } catch (IOException e) {
        LOG.error("Error retrieving hexadecimal string", e);
    }

    return res;
}

From source file:org.isatools.isatab_v1.DublinTestSet.java

@SuppressWarnings("static-access")
private void persist(String path) throws IOException {
    out.println("\n\n_________ Loading and mapping: " + path + " _______\n\n");

    String baseDir = System.getProperty("basedir");
    String filesPath = baseDir + path;
    ISATABLoader loader = new ISATABLoader(filesPath);

    FormatSetInstance isatabInstance = loader.load();

    out.println("\n\n_____ Loaded, now mapping");
    BIIObjectStore store = new BIIObjectStore();
    ISATABMapper isatabMapper = new ISATABMapper(store, isatabInstance);

    isatabMapper.map();//from  ww  w. ja v a 2s  .c  om
    assertTrue("Oh no! No mapped object! ", store.size() > 0);

    out.println("\n_____________ Persisting");

    // Test the repository too
    String repoPath = baseDir + "/target/bii_test_repo/meta_data";
    File repoDir = new File(repoPath);
    if (!repoDir.exists()) {
        FileUtils.forceMkdir(repoDir);
    }

    if (!transaction.isActive()) {
        transaction.begin();
    }
    ISATABPersister persister = new ISATABPersister(store, DaoFactory.getInstance(entityManager));
    Timestamp ts = persister.persist(filesPath);
    transaction.commit();

    for (Study study : store.valuesOfType(Study.class)) {
        assertTrue("Oh no! Submission didn't go to the repository!",
                new File(repoPath + "/" + DataLocationManager.getObfuscatedStudyFileName(study)).exists());
    }

    out.println("\n\n\n\n_______________ Done, Submission TS: " + ts.getTime() + " (" + ts + " + "
            + ts.getNanos() + "ns)");
}

From source file:org.apache.lucene.store.jdbc.JdbcDirectory.java

/**
 * Delets all the file entries that are marked to be deleted, and they were marked
 * "delta" time ago (base on database time, if possible by dialect).
 *//*  w ww. j  a  v  a  2  s.  c  o  m*/
public void deleteMarkDeleted(long delta) throws IOException {
    long currentTime = System.currentTimeMillis();
    if (dialect.supportsCurrentTimestampSelection()) {
        String timestampSelectString = dialect.getCurrentTimestampSelectString();
        if (dialect.isCurrentTimestampSelectStringCallable()) {
            currentTime = ((Long) jdbcTemplate.executeCallable(timestampSelectString,
                    new JdbcTemplate.CallableStatementCallback() {
                        public void fillCallableStatement(CallableStatement cs) throws Exception {
                            cs.registerOutParameter(1, java.sql.Types.TIMESTAMP);
                        }

                        public Object readCallableData(CallableStatement cs) throws Exception {
                            Timestamp timestamp = cs.getTimestamp(1);
                            return new Long(timestamp.getTime());
                        }
                    })).longValue();
        } else {
            currentTime = ((Long) jdbcTemplate.executeSelect(timestampSelectString,
                    new JdbcTemplate.ExecuteSelectCallback() {
                        public void fillPrepareStatement(PreparedStatement ps) throws Exception {
                            // nothing to do here
                        }

                        public Object execute(ResultSet rs) throws Exception {
                            rs.next();
                            Timestamp timestamp = rs.getTimestamp(1);
                            return new Long(timestamp.getTime());
                        }
                    })).longValue();
        }
    }
    final long deleteBefore = currentTime - delta;
    jdbcTemplate.executeUpdate(table.sqlDeletaMarkDeleteByDelta(),
            new JdbcTemplate.PrepateStatementAwareCallback() {
                public void fillPrepareStatement(PreparedStatement ps) throws Exception {
                    ps.setBoolean(1, true);
                    ps.setTimestamp(2, new Timestamp(deleteBefore));
                }
            });
}