001/*
002 * (C) Copyright 2014 Nuxeo SA (http://nuxeo.com/) and others.
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License");
005 * you may not use this file except in compliance with the License.
006 * You may obtain a copy of the License at
007 *
008 *     http://www.apache.org/licenses/LICENSE-2.0
009 *
010 * Unless required by applicable law or agreed to in writing, software
011 * distributed under the License is distributed on an "AS IS" BASIS,
012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 * See the License for the specific language governing permissions and
014 * limitations under the License.
015 *
016 * Contributors:
017 *     Nicolas Chapurlat <nchapurlat@nuxeo.com>
018 */
019
020package org.nuxeo.ecm.core.schema.types.constraints;
021
022import java.util.HashMap;
023
024import org.nuxeo.ecm.core.schema.types.PrimitiveType;
025import org.nuxeo.ecm.core.schema.types.Type;
026
027/**
028 * This constraint ensures some object's is supported by some {@link Type}.
029 *
030 * @since 7.1
031 */
032public class TypeConstraint extends AbstractConstraint {
033
034    private static final long serialVersionUID = 1L;
035
036    protected final PrimitiveType type;
037
038    public TypeConstraint(PrimitiveType type) {
039        this.type = type;
040    }
041
042    @Override
043    public boolean validate(Object object) {
044        if (object == null) {
045            return true;
046        }
047        return type.validate(object);
048    }
049
050    /**
051     * Here, value is : <br>
052     * name = {@link PrimitiveType#getName} <br>
053     * parameters =
054     */
055    @Override
056    public Description getDescription() {
057        return new Description(type.getName(), new HashMap<>());
058    }
059
060    /**
061     * @return The type used by this constraint to validate.
062     * @since 7.1
063     */
064    public Type getType() {
065        return type;
066    }
067
068    @Override
069    public int hashCode() {
070        final int prime = 31;
071        int result = 1;
072        result = prime * result + ((type == null) ? 0 : type.hashCode());
073        return result;
074    }
075
076    @Override
077    public boolean equals(Object obj) {
078        if (this == obj) {
079            return true;
080        }
081        if (obj == null) {
082            return false;
083        }
084        if (getClass() != obj.getClass()) {
085            return false;
086        }
087        TypeConstraint other = (TypeConstraint) obj;
088        if (type == null) {
089            if (other.type != null) {
090                return false;
091            }
092        } else if (!type.equals(other.type)) {
093            return false;
094        }
095        return true;
096    }
097
098}