01: /*
02: * Copyright (c) 1998 - 2005 Versant Corporation
03: * All rights reserved. This program and the accompanying materials
04: * are made available under the terms of the Eclipse Public License v1.0
05: * which accompanies this distribution, and is available at
06: * http://www.eclipse.org/legal/epl-v10.html
07: *
08: * Contributors:
09: * Versant Corporation - initial API and implementation
10: */
11: package com.versant.core.jdbc.sql.conv;
12:
13: import com.versant.core.jdbc.JdbcConverter;
14: import com.versant.core.jdbc.JdbcTypeRegistry;
15: import com.versant.core.jdbc.metadata.JdbcColumn;
16:
17: import javax.jdo.JDOFatalDataStoreException; //todo: appears only in throws clause
18: import java.sql.*;
19: import java.util.Date;
20:
21: /**
22: * This converts java.util.Date's to and from a column using setTimestamp
23: * and createTimestamp.
24: */
25: public class DateTimestampConverter extends JdbcConverterBase {
26:
27: private static final boolean useNanos;
28:
29: static {
30:
31: String v = System.getProperty("java.version");
32: useNanos = v.startsWith("1.3");
33:
34: }
35:
36: public static class Factory extends NoArgJdbcConverterFactory {
37:
38: private DateTimestampConverter converter;
39:
40: /**
41: * Create a converter for col using props as parameters. Return null if
42: * no converter is required.
43: */
44: public JdbcConverter createJdbcConverter(JdbcColumn col,
45: Object args, JdbcTypeRegistry jdbcTypeRegistry) {
46: if (converter == null)
47: converter = new DateTimestampConverter();
48: return converter;
49: }
50:
51: }
52:
53: /**
54: * Get the value of col from rs at position index.
55: *
56: * @throws SQLException on SQL errors
57: * @throws JDOFatalDataStoreException if the ResultSet value is invalid
58: */
59: public Object get(ResultSet rs, int index, JdbcColumn col)
60: throws SQLException, JDOFatalDataStoreException {
61: Timestamp t = rs.getTimestamp(index);
62: if (t == null)
63: return null;
64: if (useNanos) {
65: return new Date(t.getTime() + (t.getNanos() / 1000000));
66: } else {
67: return new Date(t.getTime());
68: }
69: }
70:
71: /**
72: * Set parameter index on ps to value (for col).
73: *
74: * @throws SQLException on SQL errors
75: * @throws JDOFatalDataStoreException if value is invalid
76: */
77: public void set(PreparedStatement ps, int index, JdbcColumn col,
78: Object value) throws SQLException,
79: JDOFatalDataStoreException {
80: if (value == null) {
81: ps.setNull(index, col.jdbcType);
82: } else {
83: Date d = (Date) value;
84: if (col.jdbcType == Types.DATE) {
85: ps.setDate(index, new java.sql.Date(d.getTime()));
86: } else {
87: ps.setTimestamp(index, new Timestamp(d.getTime()));
88: }
89: }
90: }
91:
92: /**
93: * Get the type of our expected value objects (e.g. java.util.Locale
94: * for a converter for Locale's).
95: */
96: public Class getValueType() {
97: return Date.class;
98: }
99: }
|