DatePropertyEditor.java
01 /*
02  * Copyright 2008-2016 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     protected void setValueInternal(Object value) {
34         if (null == value) {
35             super.setValueInternal(null);
36         else if (value instanceof CharSequence) {
37             handleAsString(String.valueOf(value));
38         else if (value instanceof Date) {
39             super.setValueInternal(value);
40         else if (value instanceof Calendar) {
41             super.setValueInternal(((Calendarvalue).getTime());
42         else if (value instanceof Number) {
43             super.setValueInternal(new Date(((Numbervalue).longValue()));
44         else {
45             throw illegalValue(value, Date.class);
46         }
47     }
48 
49     protected void handleAsString(String str) {
50         if (isBlank(str)) {
51             super.setValueInternal(null);
52             return;
53         }
54 
55         try {
56             super.setValueInternal(new Date(Long.parseLong(str)));
57             return;
58         catch (NumberFormatException nfe) {
59             // ignore, let's try parsing the date in a locale specific format
60         }
61 
62         try {
63             super.setValueInternal(new SimpleDateFormat().parse(str));
64         catch (ParseException e) {
65             throw illegalValue(str, Date.class, e);
66         }
67     }
68 
69     protected Formatter<Date> resolveFormatter() {
70         return isBlank(getFormat()) null new DateFormatter(getFormat());
71     }
72 }