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