01: /*
02: * Licensed to the Apache Software Foundation (ASF) under one
03: * or more contributor license agreements. See the NOTICE file
04: * distributed with this work for additional information
05: * regarding copyright ownership. The ASF licenses this file
06: * to you under the Apache License, Version 2.0 (the
07: * "License"); you may not use this file except in compliance
08: * with the License. You may obtain a copy of the License at
09: *
10: * http://www.apache.org/licenses/LICENSE-2.0
11: *
12: * Unless required by applicable law or agreed to in writing,
13: * software distributed under the License is distributed on an
14: * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15: * KIND, either express or implied. See the License for the
16: * specific language governing permissions and limitations
17: * under the License.
18: *
19: */
20: package org.apache.mina.integration.beans;
21:
22: import java.beans.PropertyEditor;
23: import java.text.DateFormat;
24: import java.text.ParseException;
25: import java.text.SimpleDateFormat;
26: import java.util.Date;
27: import java.util.Locale;
28: import java.util.regex.Pattern;
29:
30: /**
31: * A {@link PropertyEditor} which converts a {@link String} into
32: * a {@link Date} and vice versa.
33: *
34: * @author The Apache MINA Project (dev@mina.apache.org)
35: * @version $Revision: 601229 $, $Date: 2007-12-05 00:13:18 -0700 (Wed, 05 Dec 2007) $
36: */
37: public class DateEditor extends AbstractPropertyEditor {
38: private static final Pattern MILLIS = Pattern
39: .compile("[0-9][0-9]*");
40:
41: private final DateFormat[] formats = new DateFormat[] {
42: new SimpleDateFormat("EEE MMM dd HH:mm:ss zzz yyyy",
43: Locale.ENGLISH),
44: new SimpleDateFormat("yyyy-MM-dd HH:mm:ss Z",
45: Locale.ENGLISH),
46: new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.ENGLISH),
47: new SimpleDateFormat("yyyy-MM-dd", Locale.ENGLISH),
48: new SimpleDateFormat("yyyy-MM", Locale.ENGLISH),
49: new SimpleDateFormat("yyyy", Locale.ENGLISH), };
50:
51: public DateEditor() {
52: for (DateFormat f : formats) {
53: f.setLenient(true);
54: }
55: }
56:
57: @Override
58: protected String toText(Object value) {
59: if (value instanceof Number) {
60: long time = ((Number) value).longValue();
61: if (time <= 0) {
62: return null;
63: }
64: value = new Date(time);
65: }
66: return formats[0].format((Date) value);
67: }
68:
69: @Override
70: protected Object toValue(String text)
71: throws IllegalArgumentException {
72: if (MILLIS.matcher(text).matches()) {
73: long time = Long.parseLong(text);
74: if (time <= 0) {
75: return null;
76: }
77: return new Date(time);
78: }
79:
80: for (DateFormat f : formats) {
81: try {
82: return f.parse(text);
83: } catch (ParseException e) {
84: }
85: }
86:
87: throw new IllegalArgumentException("Wrong date: " + text);
88: }
89: }
|