View Javadoc

1   /*
2    * Copyright 2004-2008 the Seasar Foundation and the Others.
3    *
4    * Licensed under the Apache License, Version 2.0 (the "License");
5    * you may not use this file except in compliance with the License.
6    * You may obtain a copy of the License at
7    *
8    *     http://www.apache.org/licenses/LICENSE-2.0
9    *
10   * Unless required by applicable law or agreed to in writing, software
11   * distributed under the License is distributed on an "AS IS" BASIS,
12   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
13   * either express or implied. See the License for the specific language
14   * governing permissions and limitations under the License.
15   */
16  package org.seasar.cubby.converter.impl;
17  
18  import java.text.DateFormat;
19  import java.text.ParseException;
20  
21  import org.seasar.cubby.converter.ConversionHelper;
22  
23  /**
24   * {@link java.sql.Time}への変換を行うコンバータです。
25   * <p>
26   * 変換元のオブジェクトの文字列表現をフォーマットに従って{@link java.sql.Time}に変換した結果を変換先とします。
27   * </p>
28   * 
29   * @author baba
30   * @since 1.1.0
31   */
32  public class SqlTimeConverter extends AbstractConverter {
33  
34  	/**
35  	 * {@inheritDoc}
36  	 */
37  	public Class<?> getObjectType() {
38  		return java.sql.Time.class;
39  	}
40  
41  	/**
42  	 * {@inheritDoc}
43  	 */
44  	public Object convertToObject(final Object value,
45  			final Class<?> objectType, ConversionHelper helper) {
46  		if (value == null) {
47  			return null;
48  		}
49  		final DateFormat dateFormat = helper.getFormatPattern().getTimeFormat();
50  		return toTime((String) value, dateFormat);
51  	}
52  
53  	/**
54  	 * 文字列を{@link java.sql.Time}に変換して返します。
55  	 * 
56  	 * @param date
57  	 *            変換元のオブジェクトの文字列表現
58  	 * @param dateFormat
59  	 *            フォーマット
60  	 * @return 変換した結果の{@link java.sql.Time}
61  	 */
62  	protected java.sql.Time toTime(final String date,
63  			final DateFormat dateFormat) {
64  		if (date == null || date.length() == 0) {
65  			return null;
66  		}
67  		try {
68  			return new java.sql.Time(dateFormat.parse(date).getTime());
69  		} catch (final ParseException e) {
70  			return null;
71  		}
72  	}
73  
74  	/**
75  	 * {@inheritDoc}
76  	 */
77  	public String convertToString(final Object value, ConversionHelper helper) {
78  		if (value == null) {
79  			return null;
80  		}
81  		final DateFormat formatter = helper.getFormatPattern().getTimeFormat();
82  		return formatter.format((java.sql.Time) value);
83  	}
84  
85  }