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