001/*
002 * (C) Copyright 2015 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 *     <a href="mailto:tdelprat@nuxeo.com">Tiry</a>
018 */
019package org.nuxeo.ecm.platform.rendition.lazy;
020
021import java.util.ArrayList;
022import java.util.List;
023
024import org.apache.commons.logging.Log;
025import org.apache.commons.logging.LogFactory;
026import org.nuxeo.ecm.core.api.Blob;
027import org.nuxeo.ecm.core.api.CoreSession;
028import org.nuxeo.ecm.core.api.DocumentModel;
029import org.nuxeo.ecm.core.api.DocumentRef;
030import org.nuxeo.ecm.core.api.impl.blob.StringBlob;
031import org.nuxeo.ecm.core.transientstore.api.TransientStore;
032import org.nuxeo.ecm.core.transientstore.api.TransientStoreService;
033import org.nuxeo.ecm.core.transientstore.work.TransientStoreWork;
034import org.nuxeo.ecm.platform.rendition.extension.RenditionProvider;
035import org.nuxeo.ecm.platform.rendition.impl.LazyRendition;
036import org.nuxeo.ecm.platform.rendition.service.RenditionDefinition;
037import org.nuxeo.ecm.platform.rendition.service.RenditionService;
038import org.nuxeo.ecm.platform.rendition.service.RenditionServiceImpl;
039import org.nuxeo.runtime.api.Framework;
040
041/**
042 * @author <a href="mailto:tdelprat@nuxeo.com">Tiry</a>
043 * @since 7.2
044 */
045public abstract class AbstractRenditionBuilderWork extends TransientStoreWork {
046
047    private static final long serialVersionUID = 1L;
048
049    protected final String key;
050
051    protected final DocumentRef docRef;
052
053    protected final String repositoryName;
054
055    protected final String renditionName;
056
057    protected static Log log = LogFactory.getLog(AbstractRenditionBuilderWork.class);
058
059    public static final String CATEGORY = "renditionBuilder";
060
061    public AbstractRenditionBuilderWork(String key, DocumentModel doc, RenditionDefinition def) {
062        super();
063        this.key = key;
064        docRef = doc.getRef();
065        repositoryName = doc.getRepositoryName();
066        renditionName = def.getName();
067        setOriginatingUsername(doc.getCoreSession().getPrincipal().getName());
068        this.id = buildId(doc, def);
069    }
070
071    protected String buildId(DocumentModel doc, RenditionDefinition def) {
072        StringBuffer sb = new StringBuffer("rendition:");
073        sb.append(doc.getId());
074        String variant = def.getProvider().getVariant(doc, def);
075        if (variant != null) {
076            sb.append("::");
077            sb.append(variant);
078        }
079        sb.append("::");
080        sb.append(def.getName());
081        return sb.toString();
082    }
083
084    @Override
085    public String getTitle() {
086        return "Lazy Rendition for " + renditionName + " on " + docRef.toString() + " on behalf of "
087                + originatingUsername;
088    }
089
090    @Override
091    public String getCategory() {
092        return CATEGORY;
093    }
094
095    protected String getTransientStoreName() {
096        return AbstractLazyCachableRenditionProvider.CACHE_NAME;
097    }
098
099    @Override
100    public void work() {
101        if (log.isDebugEnabled()) {
102            log.debug(String.format("Starting %s work with id %s for transient store key %s and document %s.",
103                    getClass().getSimpleName(), id, key, docRef));
104        }
105        openUserSession();
106        DocumentModel doc = session.getDocument(docRef);
107
108        RenditionService rs = Framework.getService(RenditionService.class);
109        RenditionDefinition def = ((RenditionServiceImpl) rs).getRenditionDefinition(renditionName);
110
111        log.debug("Starting rendition computation.");
112        List<Blob> blobs = doComputeRendition(session, doc, def);
113        updateAndCompleteStoreEntry(getSourceDocumentModificationDate(doc), blobs);
114    }
115
116    @Override
117    public void cleanUp(boolean ok, Exception e) {
118        if (ok) {
119            super.cleanUp(ok, e);
120            return;
121        }
122
123        // Fetch document and compute its modification date before cleaning up which closes the session
124        DocumentModel doc = session.getDocument(docRef);
125        String sourceDocumentModificationDate = getSourceDocumentModificationDate(doc);
126
127        super.cleanUp(ok, e);
128
129        List<Blob> blobs = new ArrayList<Blob>();
130        StringBlob emptyBlob = new StringBlob("");
131        emptyBlob.setFilename("error");
132        emptyBlob.setMimeType("text/plain;" + LazyRendition.ERROR_MARKER);
133        blobs.add(emptyBlob);
134        updateAndCompleteStoreEntry(sourceDocumentModificationDate, blobs);
135    }
136
137    void updateAndCompleteStoreEntry(String sourceDocumentModificationDate, List<Blob> blobs) {
138        if (log.isDebugEnabled()) {
139            log.debug(
140                    String.format("Updating and completing transient store entry with key %s (workId=%s, document=%s).",
141                            key, id, docRef));
142        }
143        TransientStoreService tss = Framework.getService(TransientStoreService.class);
144        TransientStore ts = tss.getStore(getTransientStoreName());
145
146        if (sourceDocumentModificationDate != null) {
147            ts.putParameter(key, AbstractLazyCachableRenditionProvider.SOURCE_DOCUMENT_MODIFICATION_DATE_KEY,
148                    sourceDocumentModificationDate);
149        }
150        ts.putBlobs(key, blobs);
151        ts.setCompleted(key, true);
152    }
153
154    protected String getSourceDocumentModificationDate(DocumentModel doc) {
155        RenditionService rs = Framework.getService(RenditionService.class);
156        RenditionDefinition definition = ((RenditionServiceImpl) rs).getRenditionDefinition(renditionName);
157        RenditionProvider provider = definition.getProvider();
158        if (provider instanceof AbstractLazyCachableRenditionProvider) {
159            return ((AbstractLazyCachableRenditionProvider) provider).getSourceDocumentModificationDate(doc,
160                    definition);
161        }
162        return null;
163    }
164
165    /**
166     * Does the actual Rendition Computation : this code will be called from inside an Asynchronous Work
167     *
168     * @param session
169     * @param doc
170     * @param def
171     * @return
172     */
173    protected abstract List<Blob> doComputeRendition(CoreSession session, DocumentModel doc, RenditionDefinition def);
174
175}