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.api.model.resolver;
019
020import java.io.Serializable;
021import java.util.List;
022
023import org.nuxeo.ecm.core.api.DocumentModel;
024import org.nuxeo.ecm.core.schema.SchemaManager;
025import org.nuxeo.ecm.core.schema.types.Field;
026import org.nuxeo.ecm.core.schema.types.resolver.ObjectResolver;
027import org.nuxeo.runtime.api.Framework;
028
029/**
030 * @since 7.1
031 */
032public class DocumentPropertyObjectResolverImpl implements PropertyObjectResolver {
033
034    protected DocumentModel doc;
035
036    protected String xpath;
037
038    protected ObjectResolver resolver;
039
040    public static DocumentPropertyObjectResolverImpl create(DocumentModel doc, String xpath) {
041        Field field = Framework.getService(SchemaManager.class).getField(xpath);
042        if (field != null) {
043            ObjectResolver resolver = field.getType().getObjectResolver();
044            if (resolver != null) {
045                return new DocumentPropertyObjectResolverImpl(doc, xpath, resolver);
046            }
047        }
048        return null;
049    }
050
051    public DocumentPropertyObjectResolverImpl(DocumentModel doc, String xpath, ObjectResolver resolver) {
052        this.doc = doc;
053        this.xpath = xpath;
054        this.resolver = resolver;
055    }
056
057    @Override
058    public List<Class<?>> getManagedClasses() {
059        return resolver.getManagedClasses();
060    }
061
062    @Override
063    public boolean validate() {
064        return resolver.validate(doc.getPropertyValue(xpath));
065    }
066
067    @Override
068    public Object fetch() {
069        return resolver.fetch(doc.getPropertyValue(xpath));
070    }
071
072    @Override
073    public <T> T fetch(Class<T> type) {
074        return resolver.fetch(type, doc.getPropertyValue(xpath));
075    }
076
077    @Override
078    public void setObject(Object object) {
079        Serializable reference = resolver.getReference(object);
080        doc.setPropertyValue(xpath, reference);
081    }
082
083    @Override
084    public ObjectResolver getObjectResolver() {
085        return resolver;
086    }
087
088}