DatePropertyEditor.java
01 /*
02  * SPDX-License-Identifier: Apache-2.0
03  *
04  * Copyright 2008-2017 the original author or authors.
05  *
06  * Licensed under the Apache License, Version 2.0 (the "License");
07  * you may not use this file except in compliance with the License.
08  * 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, software
13  * distributed under the License is distributed on an "AS IS" BASIS,
14  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15  * See the License for the specific language governing permissions and
16  * limitations under the License.
17  */
18 package griffon.core.editors;
19 
20 import griffon.core.formatters.DateFormatter;
21 import griffon.core.formatters.Formatter;
22 
23 import java.text.ParseException;
24 import java.text.SimpleDateFormat;
25 import java.util.Calendar;
26 import java.util.Date;
27 
28 import static griffon.util.GriffonNameUtils.isBlank;
29 
30 /**
31  @author Andres Almiray
32  @since 2.0.0
33  */
34 public class DatePropertyEditor extends AbstractPropertyEditor {
35     @Override
36     protected void setValueInternal(Object value) {
37         if (null == value) {
38             super.setValueInternal(null);
39         else if (value instanceof CharSequence) {
40             handleAsString(String.valueOf(value));
41         else if (value instanceof Date) {
42             super.setValueInternal(value);
43         else if (value instanceof Calendar) {
44             super.setValueInternal(((Calendarvalue).getTime());
45         else if (value instanceof Number) {
46             super.setValueInternal(new Date(((Numbervalue).longValue()));
47         else {
48             throw illegalValue(value, Date.class);
49         }
50     }
51 
52     protected void handleAsString(String str) {
53         if (isBlank(str)) {
54             super.setValueInternal(null);
55             return;
56         }
57 
58         try {
59             super.setValueInternal(new Date(Long.parseLong(str)));
60             return;
61         catch (NumberFormatException nfe) {
62             // ignore, let's try parsing the date in a locale specific format
63         }
64 
65         try {
66             super.setValueInternal(new SimpleDateFormat().parse(str));
67         catch (ParseException e) {
68             throw illegalValue(str, Date.class, e);
69         }
70     }
71 
72     @Override
73     protected Formatter<Date> resolveFormatter() {
74         return isBlank(getFormat()) null new DateFormatter(getFormat());
75     }
76 }