001/* 002 * Copyright (c) 2006-2012 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 * Bogdan Stefanescu 011 * Florent Guillaume 012 * Nicolas Chapurlat <nchapurlat@nuxeo.com> 013 */ 014package org.nuxeo.ecm.core.schema.types.primitives; 015 016import java.util.Calendar; 017import java.util.Date; 018 019import org.nuxeo.ecm.core.schema.types.PrimitiveType; 020import org.nuxeo.ecm.core.schema.types.constraints.Constraint; 021import org.nuxeo.ecm.core.schema.types.constraints.DateIntervalConstraint; 022import org.nuxeo.ecm.core.schema.types.constraints.NotNullConstraint; 023import org.nuxeo.ecm.core.schema.utils.DateParser; 024 025/** 026 * The date (actually timestamp) type. 027 */ 028public class DateType extends PrimitiveType { 029 030 private static final long serialVersionUID = 1L; 031 032 public static final String ID = "date"; 033 034 public static final DateType INSTANCE = new DateType(); 035 036 public DateType() { 037 super(ID); 038 } 039 040 @Override 041 public boolean validate(Object object) { 042 return object instanceof Date || object instanceof Calendar; 043 } 044 045 @Override 046 public Object convert(Object value) { 047 if (value instanceof Date) { 048 return value; 049 } else if (value instanceof Calendar) { 050 return value; 051 } else { 052 // TODO 053 try { 054 return Integer.valueOf((String) value); 055 } catch (NumberFormatException e) { 056 return null; 057 } 058 } 059 } 060 061 @Override 062 public Object decode(String str) { 063 Date date = DateParser.parseW3CDateTime(str); 064 if (date != null) { 065 Calendar cal = Calendar.getInstance(); 066 cal.setTime(date); 067 return cal; 068 } 069 return null; 070 } 071 072 @Override 073 public String encode(Object object) { 074 if (object instanceof Date) { 075 return DateParser.formatW3CDateTime((Date) object); 076 } else if (object instanceof Calendar) { 077 return DateParser.formatW3CDateTime(((Calendar) object).getTime()); 078 } else { 079 return null; 080 } 081 } 082 083 protected Object readResolve() { 084 return INSTANCE; 085 } 086 087 @Override 088 public boolean support(Class<? extends Constraint> constraint) { 089 if (NotNullConstraint.class.equals(constraint)) { 090 return true; 091 } 092 if (DateIntervalConstraint.class.equals(constraint)) { 093 return true; 094 } 095 return false; 096 } 097 098}