001/*
002 * (C) Copyright 2010 Nuxeo SAS (http://nuxeo.com/) and contributors.
003 *
004 * All rights reserved. This program and the accompanying materials
005 * are made available under the terms of the GNU Lesser General Public License
006 * (LGPL) version 2.1 which accompanies this distribution, and is available at
007 * http://www.gnu.org/licenses/lgpl.html
008 *
009 * This library is distributed in the hope that it will be useful,
010 * but WITHOUT ANY WARRANTY; without even the implied warranty of
011 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
012 * Lesser General Public License for more details.
013 * Contributors:
014 * Nuxeo - initial API and implementation
015 */
016package org.nuxeo.ecm.platform.rendition.service;
017
018import static org.nuxeo.ecm.platform.rendition.Constants.RENDITION_NAME_PROPERTY;
019import static org.nuxeo.ecm.platform.rendition.Constants.RENDITION_SOURCE_ID_PROPERTY;
020
021import java.util.List;
022
023import org.nuxeo.ecm.core.api.DocumentModel;
024import org.nuxeo.ecm.core.api.UnrestrictedSessionRunner;
025
026/**
027 * Retrives stored Rendition associated to a DocumentModel.
028 * <p>
029 * Can run Unrestricted or not.
030 *
031 * @author <a href="mailto:tdelprat@nuxeo.com">Tiry</a>
032 */
033public class RenditionFinder extends UnrestrictedSessionRunner {
034
035    protected final DocumentModel source;
036
037    protected DocumentModel storedRendition;
038
039    protected final String definitionName;
040
041    protected RenditionFinder(DocumentModel source, String definitionName) {
042        super(source.getCoreSession());
043        this.source = source;
044        this.definitionName = definitionName;
045    }
046
047    @Override
048    public void run() {
049
050        String query = "select * from Document where ecm:isProxy = 0 AND  ecm:isCheckedInVersion = 1 AND ";
051        query = query + RENDITION_NAME_PROPERTY + "='" + definitionName + "' AND ";
052        String versionUUUID = source.getId();
053        if (!source.isVersion() && !source.isCheckedOut()) {
054            DocumentModel lastVersion = session.getLastDocumentVersion(source.getRef());
055            if (lastVersion != null) {
056                versionUUUID = lastVersion.getId();
057            } else {
058                // no version at all
059                return;
060            }
061        }
062        query = query + RENDITION_SOURCE_ID_PROPERTY + "='" + versionUUUID + "' ";
063
064        query = query + " order by dc:modified desc ";
065
066        List<DocumentModel> docs = session.query(query);
067        if (docs.size() > 0) {
068            storedRendition = docs.get(0);
069            storedRendition.detach(true);
070        }
071    }
072
073    public DocumentModel getStoredRendition() {
074        return storedRendition;
075    }
076
077}