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 org.apache.commons.lang.StringUtils; 017import org.nuxeo.ecm.core.schema.types.PrimitiveType; 018import org.nuxeo.ecm.core.schema.types.constraints.Constraint; 019import org.nuxeo.ecm.core.schema.types.constraints.EnumConstraint; 020import org.nuxeo.ecm.core.schema.types.constraints.NotNullConstraint; 021import org.nuxeo.ecm.core.schema.types.constraints.NumericIntervalConstraint; 022import org.nuxeo.ecm.core.schema.types.constraints.PatternConstraint; 023 024/** 025 * The double type. 026 */ 027public final class DoubleType extends PrimitiveType { 028 029 private static final long serialVersionUID = 1L; 030 031 public static final String ID = "double"; 032 033 public static final DoubleType INSTANCE = new DoubleType(); 034 035 private DoubleType() { 036 super(ID); 037 } 038 039 @Override 040 public boolean validate(Object object) { 041 return object instanceof Number; 042 } 043 044 @Override 045 public Object convert(Object value) { 046 if (value instanceof Double) { 047 return value; 048 } else if (value instanceof Number) { 049 return Double.valueOf(((Number) value).longValue()); 050 } else { 051 try { 052 return Double.valueOf((String) value); 053 } catch (NumberFormatException e) { 054 return null; 055 } 056 } 057 } 058 059 @Override 060 public Object decode(String str) { 061 if (StringUtils.isEmpty(str)) { 062 return null; 063 } 064 try { 065 return Double.valueOf(str); 066 } catch (NumberFormatException e) { 067 return Double.valueOf(0.0); 068 } 069 } 070 071 @Override 072 public String encode(Object object) { 073 if (object instanceof Double) { 074 return object.toString(); 075 } else if (object instanceof Number) { 076 return object.toString(); 077 } else { 078 return object != null ? (String) object : ""; 079 } 080 } 081 082 protected Object readResolve() { 083 return INSTANCE; 084 } 085 086 @Override 087 public boolean support(Class<? extends Constraint> constraint) { 088 if (NotNullConstraint.class.equals(constraint)) { 089 return true; 090 } 091 if (EnumConstraint.class.equals(constraint)) { 092 return true; 093 } 094 if (PatternConstraint.class.equals(constraint)) { 095 return true; 096 } 097 if (NumericIntervalConstraint.class.equals(constraint)) { 098 return true; 099 } 100 return false; 101 } 102 103}