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 * Nuxeo - initial API and implementation
018 */
019
020package org.nuxeo.ecm.platform.rendition.lazy;
021
022import java.security.MessageDigest;
023import java.security.NoSuchAlgorithmException;
024import java.util.ArrayList;
025import java.util.Calendar;
026import java.util.List;
027
028import org.apache.commons.logging.Log;
029import org.apache.commons.logging.LogFactory;
030import org.nuxeo.ecm.core.api.Blob;
031import org.nuxeo.ecm.core.api.DocumentModel;
032import org.nuxeo.ecm.core.api.NuxeoException;
033import org.nuxeo.ecm.core.api.impl.blob.StringBlob;
034import org.nuxeo.ecm.core.transientstore.api.TransientStore;
035import org.nuxeo.ecm.core.transientstore.api.TransientStoreService;
036import org.nuxeo.ecm.core.work.api.Work;
037import org.nuxeo.ecm.core.work.api.Work.State;
038import org.nuxeo.ecm.core.work.api.WorkManager;
039import org.nuxeo.ecm.platform.rendition.Rendition;
040import org.nuxeo.ecm.platform.rendition.extension.AutomationRenderer;
041import org.nuxeo.ecm.platform.rendition.extension.RenditionProvider;
042import org.nuxeo.ecm.platform.rendition.impl.LazyRendition;
043import org.nuxeo.ecm.platform.rendition.service.RenditionDefinition;
044import org.nuxeo.runtime.api.Framework;
045
046/**
047 * Default implementation of an asynchronous {@link RenditionProvider}
048 *
049 * @author <a href="mailto:tdelprat@nuxeo.com">Tiry</a>
050 * @since 7.2
051 */
052public abstract class AbstractLazyCachableRenditionProvider implements RenditionProvider {
053
054    public static final String WORKERID_KEY = "workerid";
055
056    public static final String CACHE_NAME = "LazyRenditionCache";
057
058    protected static Log log = LogFactory.getLog(AbstractLazyCachableRenditionProvider.class);
059
060    @Override
061    public List<Blob> render(DocumentModel doc, RenditionDefinition def) {
062
063        // build the key
064        String key = buildRenditionKey(doc, def);
065
066        // see if rendition is already in process
067
068        TransientStoreService tss = Framework.getService(TransientStoreService.class);
069
070        TransientStore ts = tss.getStore(CACHE_NAME);
071
072        if (ts == null) {
073            throw new NuxeoException("Unable to find Transient Store  " + CACHE_NAME);
074        }
075
076        if (!ts.exists(key)) {
077            Work work = getRenditionWork(key, doc, def);
078            WorkManager wm = Framework.getService(WorkManager.class);
079            ts.putParameter(key, WORKERID_KEY, work.getId());
080            wm.schedule(work);
081        } else {
082            if (ts.isCompleted(key)) {
083                List<Blob> blobs = ts.getBlobs(key);
084                ts.release(key);
085                return blobs;
086            } else {
087                WorkManager wm = Framework.getService(WorkManager.class);
088                String workId = (String) ts.getParameter(key, WORKERID_KEY);
089                Work work = wm.find(workId, State.COMPLETED);
090                if (work == null) {
091                    work = wm.find(workId, State.FAILED);
092                }
093                if (work != null) {
094                    State state = work.getWorkInstanceState();
095                    if (state == State.FAILED) {
096                        // return an empty Blob
097                        List<Blob> blobs = new ArrayList<Blob>();
098                        StringBlob emptyBlob = new StringBlob("");
099                        emptyBlob.setFilename("error");
100                        emptyBlob.setMimeType("text/plain;" + LazyRendition.ERROR_MARKER);
101                        blobs.add(emptyBlob);
102                        ts.release(key);
103                        return blobs;
104                    }
105                }
106            }
107        }
108        // return an empty Blob
109        List<Blob> blobs = new ArrayList<Blob>();
110        StringBlob emptyBlob = new StringBlob("");
111        emptyBlob.setFilename("inprogress");
112        emptyBlob.setMimeType("text/plain;" + LazyRendition.EMPTY_MARKER);
113        blobs.add(emptyBlob);
114        return blobs;
115    }
116
117    @Override
118    public String getVariant(DocumentModel doc, RenditionDefinition definition) {
119        return AutomationRenderer.getVariant(doc, definition);
120    }
121
122    protected String buildRenditionKey(DocumentModel doc, RenditionDefinition def) {
123
124        StringBuffer sb = new StringBuffer(doc.getId());
125        sb.append("::");
126        String modificationDatePropertyName = def.getSourceDocumentModificationDatePropertyName();
127        Calendar modif = (Calendar) doc.getPropertyValue(modificationDatePropertyName);
128        if (modif != null) {
129            sb.append(modif.getTimeInMillis());
130            sb.append("::");
131        }
132        String variant = getVariant(doc, def);
133        if (variant != null) {
134            sb.append(variant);
135            sb.append("::");
136        }
137        sb.append(def.getName());
138
139        return getDigest(sb.toString());
140    }
141
142    protected String getDigest(String key) {
143        MessageDigest digest;
144        try {
145            digest = MessageDigest.getInstance("MD5");
146        } catch (NoSuchAlgorithmException e) {
147            return key;
148        }
149        byte[] buf = digest.digest(key.getBytes());
150        return toHexString(buf);
151    }
152
153    private static final char[] HEX_DIGITS = "0123456789abcdef".toCharArray();
154
155    protected String toHexString(byte[] data) {
156        StringBuilder buf = new StringBuilder(2 * data.length);
157        for (byte b : data) {
158            buf.append(HEX_DIGITS[(0xF0 & b) >> 4]);
159            buf.append(HEX_DIGITS[0x0F & b]);
160        }
161        return buf.toString();
162    }
163
164    /**
165     * Return the {@link Work} that will compute the {@link Rendition}. {@link AbstractRenditionBuilderWork} can be used
166     * as a base class
167     *
168     * @param key the key used to rendition
169     * @param doc the target {@link DocumentModel}
170     * @param def the {@link RenditionDefinition}
171     * @return
172     */
173    protected abstract Work getRenditionWork(final String key, final DocumentModel doc, final RenditionDefinition def);
174
175}