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 boolean isIdempotent() {
101        // The same rendering can be executed multiple times because the result is transient.
102        return false;
103    }
104
105    @Override
106    public void work() {
107        if (log.isDebugEnabled()) {
108            log.debug(String.format("Starting %s work with id %s for transient store key %s and document %s.",
109                    getClass().getSimpleName(), id, key, docRef));
110        }
111        openUserSession();
112        DocumentModel doc = session.getDocument(docRef);
113
114        RenditionService rs = Framework.getService(RenditionService.class);
115        RenditionDefinition def = ((RenditionServiceImpl) rs).getRenditionDefinition(renditionName);
116
117        log.debug("Starting rendition computation.");
118        List<Blob> blobs = doComputeRendition(session, doc, def);
119        updateAndCompleteStoreEntry(getSourceDocumentModificationDate(doc), blobs);
120    }
121
122    @Override
123    public void cleanUp(boolean ok, Exception e) {
124        if (ok) {
125            super.cleanUp(ok, e);
126            return;
127        }
128
129        // Fetch document and compute its modification date before cleaning up which closes the session
130        DocumentModel doc = session.getDocument(docRef);
131        String sourceDocumentModificationDate = getSourceDocumentModificationDate(doc);
132
133        super.cleanUp(ok, e);
134
135        List<Blob> blobs = new ArrayList<Blob>();
136        StringBlob emptyBlob = new StringBlob("");
137        emptyBlob.setFilename("error");
138        emptyBlob.setMimeType("text/plain;" + LazyRendition.ERROR_MARKER);
139        blobs.add(emptyBlob);
140        updateAndCompleteStoreEntry(sourceDocumentModificationDate, blobs);
141    }
142
143    void updateAndCompleteStoreEntry(String sourceDocumentModificationDate, List<Blob> blobs) {
144        if (log.isDebugEnabled()) {
145            log.debug(
146                    String.format("Updating and completing transient store entry with key %s (workId=%s, document=%s).",
147                            key, id, docRef));
148        }
149        TransientStoreService tss = Framework.getService(TransientStoreService.class);
150        TransientStore ts = tss.getStore(getTransientStoreName());
151
152        if (sourceDocumentModificationDate != null) {
153            ts.putParameter(key, AbstractLazyCachableRenditionProvider.SOURCE_DOCUMENT_MODIFICATION_DATE_KEY,
154                    sourceDocumentModificationDate);
155        }
156        ts.putBlobs(key, blobs);
157        ts.setCompleted(key, true);
158    }
159
160    protected String getSourceDocumentModificationDate(DocumentModel doc) {
161        RenditionService rs = Framework.getService(RenditionService.class);
162        RenditionDefinition definition = ((RenditionServiceImpl) rs).getRenditionDefinition(renditionName);
163        RenditionProvider provider = definition.getProvider();
164        if (provider instanceof AbstractLazyCachableRenditionProvider) {
165            return ((AbstractLazyCachableRenditionProvider) provider).getSourceDocumentModificationDate(doc,
166                    definition);
167        }
168        return null;
169    }
170
171    /**
172     * Does the actual Rendition Computation : this code will be called from inside an Asynchronous Work
173     *
174     * @param session
175     * @param doc
176     * @param def
177     * @return
178     */
179    protected abstract List<Blob> doComputeRendition(CoreSession session, DocumentModel doc, RenditionDefinition def);
180
181}