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 */
018package org.nuxeo.ecm.platform.rendition.service;
019
020import org.nuxeo.ecm.core.api.Blob;
021import org.nuxeo.ecm.core.api.DocumentModel;
022import org.nuxeo.ecm.platform.rendition.impl.StoredRendition;
023
024/**
025 * The default @{link StoredRenditionManager} to Manage {@link StoredRendition}s on behalf of the
026 * {@link RenditionService}.
027 *
028 * @since 8.1
029 */
030public class DefaultStoredRenditionManager implements StoredRenditionManager {
031
032    @Override
033    public StoredRendition createStoredRendition(DocumentModel liveDocument, DocumentModel versionDocument,
034            Blob renditionBlob, RenditionDefinition renditionDefinition) {
035        RenditionCreator rc = new RenditionCreator(liveDocument, versionDocument, renditionBlob, renditionDefinition);
036        rc.runUnrestricted();
037        DocumentModel storedDoc = rc.getDetachedRendition();
038        String sessionId = liveDocument.getCoreSession().getSessionId();
039        return toStoredRendition(storedDoc, renditionDefinition, sessionId);
040    }
041
042    @Override
043    public StoredRendition findStoredRendition(DocumentModel sourceDocument, RenditionDefinition renditionDefinition) {
044        RenditionFinder finder = new RenditionFinder(sourceDocument, renditionDefinition);
045        finder.runUnrestricted();
046        DocumentModel storedDoc = finder.getStoredRendition();
047        String sessionId = sourceDocument.getCoreSession().getSessionId();
048        return toStoredRendition(storedDoc, renditionDefinition, sessionId);
049    }
050
051    /**
052     * Wraps the re-attached stored document in a {@link StoredRendition}.
053     *
054     * @param storedDoc the stored document
055     * @param def the rendition definition
056     * @param sessionId the session id
057     * @return the stored rendition
058     */
059    protected StoredRendition toStoredRendition(DocumentModel storedDoc, RenditionDefinition def, String sessionId) {
060        if (storedDoc == null) {
061            return null;
062        }
063        // re-attach the detached doc
064        storedDoc.attach(sessionId);
065        return new StoredRendition(storedDoc, def);
066    }
067
068}