View Javadoc
1   /*
2    * Licensed to the Apache Software Foundation (ASF) under one or more
3    * contributor license agreements.  See the NOTICE file distributed with
4    * this work for additional information regarding copyright ownership.
5    * The ASF licenses this file to You under the Apache License, Version 2.0
6    * (the "License"); you may not use this file except in compliance with
7    * the License.  You may obtain a copy of the License at
8    *
9    *      http://www.apache.org/licenses/LICENSE-2.0
10   *
11   * Unless required by applicable law or agreed to in writing, software
12   * distributed under the License is distributed on an "AS IS" BASIS,
13   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14   * See the License for the specific language governing permissions and
15   * limitations under the License.
16   */
17  package org.apache.commons.dbutils.handlers.properties;
18  
19  import java.sql.Timestamp;
20  import java.util.Date;
21  
22  import org.apache.commons.dbutils.PropertyHandler;
23  
24  /**
25   * {@link PropertyHandler} for date fields. Will convert {@link java.sql.Date}, {@link java.sql.Time}, and {@link java.sql.Timestamp} from SQL types to java
26   * types.
27   */
28  public class DatePropertyHandler implements PropertyHandler {
29  
30      private static final String JAVA_SQL_TIMESTAMP = "java.sql.Timestamp";
31      private static final String JAVA_SQL_TIME = "java.sql.Time";
32      private static final String JAVA_SQL_DATE = "java.sql.Date";
33  
34      @Override
35      public Object apply(final Class<?> parameter, Object value) {
36          final String targetType = parameter.getName();
37          final Date dateValue = (Date) value;
38          final long time = dateValue.getTime();
39  
40          if (JAVA_SQL_DATE.equals(targetType)) {
41              value = new java.sql.Date(time);
42          } else if (JAVA_SQL_TIME.equals(targetType)) {
43              value = new java.sql.Time(time);
44          } else if (JAVA_SQL_TIMESTAMP.equals(targetType)) {
45              value = new Timestamp(time);
46          }
47  
48          return value;
49      }
50  
51      @Override
52      public boolean match(final Class<?> parameter, final Object value) {
53          if (value instanceof Date) {
54              final String targetType = parameter.getName();
55              if (JAVA_SQL_DATE.equals(targetType)) {
56                  return true;
57              }
58              if (JAVA_SQL_TIME.equals(targetType)) {
59                  return true;
60              }
61              if (JAVA_SQL_TIMESTAMP.equals(targetType) && !Timestamp.class.isInstance(value)) {
62                  return true;
63              }
64          }
65  
66          return false;
67      }
68  }