001/*
002 * Copyright (c) 2006-2011 Nuxeo SA (http://nuxeo.com/) and others.
003 *
004 * All rights reserved. This program and the accompanying materials
005 * are made available under the terms of the Eclipse Public License v1.0
006 * which accompanies this distribution, and is available at
007 * http://www.eclipse.org/legal/epl-v10.html
008 *
009 * Contributors:
010 *     bstefanescu
011 *
012 * $Id$
013 */
014
015package org.nuxeo.ecm.core.api.model.impl.primitives;
016
017import java.io.Serializable;
018import java.util.Calendar;
019import java.util.Date;
020
021import org.nuxeo.ecm.core.api.model.Property;
022import org.nuxeo.ecm.core.api.model.PropertyConversionException;
023import org.nuxeo.ecm.core.api.model.impl.ScalarProperty;
024import org.nuxeo.ecm.core.schema.types.Field;
025
026/**
027 * @author <a href="mailto:bs@nuxeo.com">Bogdan Stefanescu</a>
028 */
029public class DateProperty extends ScalarProperty {
030
031    private static final long serialVersionUID = -7344978155078073495L;
032
033    public DateProperty(Property parent, Field field, int flags) {
034        super(parent, field, flags);
035    }
036
037    @Override
038    public boolean isNormalized(Object value) {
039        return value == null || value instanceof Calendar;
040    }
041
042    @Override
043    public Serializable normalize(Object value) throws PropertyConversionException {
044        if (isNormalized(value)) {
045            return (Serializable) value;
046        }
047        if (value.getClass() == Date.class) {
048            Calendar cal = Calendar.getInstance();
049            cal.setTime((Date) value);
050            return cal;
051        }
052        if (value instanceof String) {
053            String string = (String) value;
054            if (string.length() == 0) {
055                return null;
056            }
057            return (Calendar) field.getType().decode(value.toString());
058        }
059        throw new PropertyConversionException(value.getClass(), Calendar.class);
060    }
061
062    @SuppressWarnings("unchecked")
063    @Override
064    public <T> T convertTo(Serializable value, Class<T> toType) throws PropertyConversionException {
065        if (value == null || toType == Calendar.class) {
066            return (T) value;
067        }
068        if (toType == Date.class) {
069            return (T) ((Calendar) value).getTime();
070        }
071        throw new PropertyConversionException(value.getClass(), toType);
072    }
073
074    @Override
075    public Object newInstance() {
076        return Calendar.getInstance();
077    }
078
079}