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