001/*
002 * (C) Copyright 2012 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 *     Thierry Delprat
018 */
019package org.nuxeo.template.context;
020
021import java.util.HashMap;
022import java.util.Map;
023
024import org.apache.commons.logging.Log;
025import org.apache.commons.logging.LogFactory;
026import org.nuxeo.ecm.core.api.CoreSession;
027import org.nuxeo.ecm.core.api.DocumentModel;
028import org.nuxeo.runtime.api.Framework;
029import org.nuxeo.template.api.TemplateProcessorService;
030import org.nuxeo.template.api.adapters.TemplateBasedDocument;
031import org.nuxeo.template.api.context.DocumentWrapper;
032
033public abstract class AbstractContextBuilder {
034
035    protected static final Log log = LogFactory.getLog(AbstractContextBuilder.class);
036
037    public static final String[] RESERVED_VAR_NAMES = { "doc", "document", "blobHolder", "username", "principal",
038            "templateName" };
039
040    public Map<String, Object> build(DocumentModel doc, DocumentWrapper nuxeoWrapper, String templateName) {
041
042        Map<String, Object> ctx = new HashMap<>();
043
044        CoreSession session = doc.getCoreSession();
045
046        // doc infos
047        ctx.put("doc", nuxeoWrapper.wrap(doc));
048        ctx.put("document", nuxeoWrapper.wrap(doc));
049
050        // blob wrapper
051        ctx.put("blobHolder", new BlobHolderWrapper(doc));
052
053        // user info
054        ctx.put("username", session.getPrincipal().getName());
055        ctx.put("principal", session.getPrincipal());
056
057        ctx.put("templateName", templateName);
058
059        // fetch extensions
060        TemplateProcessorService tps = Framework.getService(TemplateProcessorService.class);
061        tps.addContextExtensions(doc, nuxeoWrapper, ctx);
062
063        return ctx;
064    }
065
066    public Map<String, Object> build(TemplateBasedDocument templateBasedDocument, String templateName) {
067
068        DocumentModel doc = templateBasedDocument.getAdaptedDoc();
069
070        Map<String, Object> context = build(doc, templateName);
071
072        return context;
073    }
074
075    protected abstract DocumentWrapper getWrapper();
076
077    public Map<String, Object> build(DocumentModel doc, String templateName) {
078
079        return build(doc, getWrapper(), templateName);
080    }
081}