001/* 002 * (C) Copyright 2006-2011 Nuxeo SA (http://nuxeo.com/) and others. 003 * 004 * Licensed under the Apache License, Version 2.0 (the "License"); 005 * you may not use this file except in compliance with the License. 006 * You may obtain a copy of the License at 007 * 008 * http://www.apache.org/licenses/LICENSE-2.0 009 * 010 * Unless required by applicable law or agreed to in writing, software 011 * distributed under the License is distributed on an "AS IS" BASIS, 012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 013 * See the License for the specific language governing permissions and 014 * limitations under the License. 015 * 016 * Contributors: 017 * bstefanescu 018 * 019 * $Id$ 020 */ 021 022package org.nuxeo.ecm.core.api.model.impl.primitives; 023 024import java.io.Serializable; 025import java.util.Calendar; 026import java.util.Date; 027 028import org.nuxeo.ecm.core.api.model.Property; 029import org.nuxeo.ecm.core.api.model.PropertyConversionException; 030import org.nuxeo.ecm.core.api.model.impl.ScalarProperty; 031import org.nuxeo.ecm.core.schema.types.Field; 032 033/** 034 * @author <a href="mailto:bs@nuxeo.com">Bogdan Stefanescu</a> 035 */ 036public class DateProperty extends ScalarProperty { 037 038 private static final long serialVersionUID = -7344978155078073495L; 039 040 public DateProperty(Property parent, Field field, int flags) { 041 super(parent, field, flags); 042 } 043 044 @Override 045 public boolean isNormalized(Object value) { 046 return value == null || value instanceof Calendar; 047 } 048 049 @Override 050 public Serializable normalize(Object value) throws PropertyConversionException { 051 if (isNormalized(value)) { 052 return (Serializable) value; 053 } 054 if (value.getClass() == Date.class) { 055 Calendar cal = Calendar.getInstance(); 056 cal.setTime((Date) value); 057 return cal; 058 } 059 if (value instanceof String) { 060 String string = (String) value; 061 if (string.length() == 0) { 062 return null; 063 } 064 return (Calendar) field.getType().decode(value.toString()); 065 } 066 throw new PropertyConversionException(value.getClass(), Calendar.class); 067 } 068 069 @SuppressWarnings("unchecked") 070 @Override 071 public <T> T convertTo(Serializable value, Class<T> toType) throws PropertyConversionException { 072 if (value == null || toType == Calendar.class) { 073 return (T) value; 074 } 075 if (toType == Date.class) { 076 return (T) ((Calendar) value).getTime(); 077 } 078 throw new PropertyConversionException(value.getClass(), toType); 079 } 080 081 @Override 082 public Object newInstance() { 083 return Calendar.getInstance(); 084 } 085 086}