001/*
002 * (C) Copyright 2014 Nuxeo SA (http://nuxeo.com/) and contributors.
003 *
004 * All rights reserved. This program and the accompanying materials
005 * are made available under the terms of the GNU Lesser General Public License
006 * (LGPL) version 2.1 which accompanies this distribution, and is available at
007 * http://www.gnu.org/licenses/lgpl-2.1.html
008 *
009 * This library is distributed in the hope that it will be useful,
010 * but WITHOUT ANY WARRANTY; without even the implied warranty of
011 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
012 * Lesser General Public License for more details.
013 *
014 * Contributors:
015 *     Nicolas Chapurlat <nchapurlat@nuxeo.com>
016 */
017
018package org.nuxeo.ecm.core.schema.types.constraints;
019
020import java.io.Serializable;
021import java.util.HashMap;
022
023import org.nuxeo.ecm.core.schema.types.PrimitiveType;
024import org.nuxeo.ecm.core.schema.types.Type;
025
026/**
027 * This constraint ensures some object's is supported by some {@link Type}.
028 *
029 * @since 7.1
030 */
031public class TypeConstraint extends AbstractConstraint {
032
033    private static final long serialVersionUID = 1L;
034
035    protected final PrimitiveType type;
036
037    public TypeConstraint(PrimitiveType type) {
038        this.type = type;
039    }
040
041    @Override
042    public boolean validate(Object object) {
043        if (object == null) {
044            return true;
045        }
046        return type.validate(object);
047    }
048
049    /**
050     * <p>
051     * Here, value is : <br>
052     * name = {@value #NAME} <br>
053     * parameters =
054     * <ul>
055     * <li>{@value #PNAME_TYPE} : org.nuxeo.ecm.core.schema.types.primitives.IntegerType</li>
056     * </ul>
057     * </p>
058     */
059    @Override
060    public Description getDescription() {
061        return new Description(type.getName(), new HashMap<String, Serializable>());
062    }
063
064    /**
065     * @return The type used by this constraint to validate.
066     * @since 7.1
067     */
068    public Type getType() {
069        return type;
070    }
071
072    @Override
073    public int hashCode() {
074        final int prime = 31;
075        int result = 1;
076        result = prime * result + ((type == null) ? 0 : type.hashCode());
077        return result;
078    }
079
080    @Override
081    public boolean equals(Object obj) {
082        if (this == obj) {
083            return true;
084        }
085        if (obj == null) {
086            return false;
087        }
088        if (getClass() != obj.getClass()) {
089            return false;
090        }
091        TypeConstraint other = (TypeConstraint) obj;
092        if (type == null) {
093            if (other.type != null) {
094                return false;
095            }
096        } else if (!type.equals(other.type)) {
097            return false;
098        }
099        return true;
100    }
101
102}