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