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.CalendarFormatter;
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 CalendarPropertyEditor 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 Calendar) {
40 super.setValueInternal(value);
41 } else if (value instanceof Date) {
42 Calendar c = Calendar.getInstance();
43 c.setTime((Date) value);
44 super.setValueInternal(c);
45 } else if (value instanceof Number) {
46 Calendar c = Calendar.getInstance();
47 c.setTime(new Date(((Number) value).longValue()));
48 super.setValueInternal(c);
49 } else {
50 throw illegalValue(value, Calendar.class);
51 }
52 }
53
54 protected void handleAsString(String str) {
55 if (isBlank(str)) {
56 super.setValueInternal(null);
57 return;
58 }
59
60 Calendar c = Calendar.getInstance();
61 try {
62 c.setTime(new Date(Long.parseLong(str)));
63 super.setValueInternal(c);
64 return;
65 } catch (NumberFormatException nfe) {
66 // ignore, let's try parsing the date in a locale specific format
67 }
68
69 try {
70 c.setTime(new SimpleDateFormat().parse(str));
71 super.setValueInternal(c);
72 } catch (ParseException e) {
73 throw illegalValue(str, Calendar.class, e);
74 }
75 }
76
77 @Override
78 protected Formatter<Calendar> resolveFormatter() {
79 return isBlank(getFormat()) ? null : new CalendarFormatter(getFormat());
80 }
81 }
|