001/*
002 * Copyright (c) 2011 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 *     Florent Guillaume
011 */
012
013package org.nuxeo.ecm.platform.rendering.fm.adapters;
014
015import org.nuxeo.ecm.core.api.DocumentModel;
016import org.nuxeo.ecm.core.api.PropertyException;
017
018import freemarker.template.TemplateHashModel;
019import freemarker.template.TemplateModel;
020import freemarker.template.TemplateModelException;
021
022/**
023 * A template for a document's schema, that can still take advantage of the document's prefetched values.
024 */
025public class SchemaTemplate extends PropertyWrapper implements TemplateHashModel {
026
027    private final DocumentModel doc;
028
029    private final String schemaName;
030
031    public static class DocumentSchema {
032        public final DocumentModel doc;
033
034        public final String schemaName;
035
036        public DocumentSchema(DocumentModel doc, String schemaName) {
037            this.doc = doc;
038            this.schemaName = schemaName;
039        }
040    }
041
042    public SchemaTemplate(DocumentObjectWrapper wrapper, DocumentSchema schema) {
043        super(wrapper);
044        this.doc = schema.doc;
045        this.schemaName = schema.schemaName;
046    }
047
048    @Override
049    public TemplateModel get(String name) throws TemplateModelException {
050        try {
051            if (doc.isPrefetched(schemaName, name)) {
052                // simple value already available, don't load DocumentPart
053                return wrapper.wrap(doc.getProperty(schemaName, name));
054            } else {
055                // use normal Property lookup in Part
056                return wrap(doc.getPart(schemaName).get(name));
057            }
058        } catch (PropertyException e) {
059            throw new TemplateModelException(e);
060        }
061    }
062
063    @Override
064    public boolean isEmpty() throws TemplateModelException {
065        return false;
066    }
067
068}