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