001/*
002 * Copyright (c) 2006-2013 Nuxeo SA (http://nuxeo.com/) and others.
003 *
004 * All rights reserved. This program and the accompanying materials
005 * are made available under the terms of the Eclipse Public License v1.0
006 * which accompanies this distribution, and is available at
007 * http://www.eclipse.org/legal/epl-v10.html
008 *
009 * Contributors:
010 *     Benjamin JALON <bjalon@nuxeo.com>
011 */
012package org.nuxeo.ecm.automation.core.operations.document;
013
014import org.nuxeo.ecm.automation.core.Constants;
015import org.nuxeo.ecm.automation.core.annotations.Context;
016import org.nuxeo.ecm.automation.core.annotations.Operation;
017import org.nuxeo.ecm.automation.core.annotations.OperationMethod;
018import org.nuxeo.ecm.automation.core.collectors.DocumentModelCollector;
019import org.nuxeo.ecm.core.api.CoreSession;
020import org.nuxeo.ecm.core.api.DocumentModel;
021
022/**
023 * @author <a href="mailto:bjalon@nuxeo.com">Benjamin JALON</a>
024 * @since 5.7
025 */
026@Operation(id = GetLiveDocument.ID, category = Constants.CAT_DOCUMENT, label = "Get Live Document", description = "Get the live document even if this is a Proxy or Version Document.", aliases = { "GetLiveDocument" })
027public class GetLiveDocument {
028
029    public static final String ID = "Proxy.GetSourceDocument";
030
031    private static int MAX_ITERATION = 5;
032
033    @Context
034    protected CoreSession session;
035
036    @OperationMethod(collector = DocumentModelCollector.class)
037    public DocumentModel run(DocumentModel input) {
038        DocumentModel doc = session.getSourceDocument(input.getRef());
039        for (int i = 0; i < MAX_ITERATION && !isLive(doc); i++) {
040            doc = session.getSourceDocument(doc.getRef());
041        }
042
043        return doc;
044    }
045
046    private boolean isLive(DocumentModel doc) {
047        return !doc.isVersion() && !doc.isProxy();
048    }
049
050}