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.Collections;
022import java.util.Locale;
023import java.util.Map;
024
025import org.nuxeo.ecm.core.schema.types.resolver.ObjectResolver;
026
027/**
028 * External references are document field with a simple type whose value refers to an external business entity. This
029 * constraints ensure some value is a reference of an existing external entity resolved by the underlying resolver :
030 * {@link #getResolver()} .
031 *
032 * @since 7.1
033 */
034public final class ObjectResolverConstraint extends AbstractConstraint {
035
036    private static final long serialVersionUID = 1L;
037
038    private ObjectResolver resolver;
039
040    public ObjectResolverConstraint(ObjectResolver resolver) {
041        super();
042        this.resolver = resolver;
043    }
044
045    public ObjectResolver getResolver() {
046        return resolver;
047    }
048
049    @Override
050    public boolean validate(Object object) {
051        if (object == null) {
052            return true;
053        }
054        return resolver.validate(object);
055    }
056
057    @Override
058    public Description getDescription() {
059        Map<String, Serializable> parameters = Collections.unmodifiableMap(resolver.getParameters());
060        return new Description(resolver.getName(), parameters);
061    }
062
063    @Override
064    public String getErrorMessage(Object invalidValue, Locale locale) {
065        return resolver.getConstraintErrorMessage(invalidValue, locale);
066    }
067}