001/*
002 * Copyright (c) 2006-2011 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 *     bstefanescu
011 */
012package org.nuxeo.ecm.automation.core.operations.stack;
013
014import org.nuxeo.ecm.automation.OperationContext;
015import org.nuxeo.ecm.automation.OperationException;
016import org.nuxeo.ecm.automation.core.Constants;
017import org.nuxeo.ecm.automation.core.annotations.Context;
018import org.nuxeo.ecm.automation.core.annotations.Operation;
019import org.nuxeo.ecm.automation.core.annotations.OperationMethod;
020import org.nuxeo.ecm.core.api.DocumentModel;
021import org.nuxeo.ecm.core.api.DocumentRef;
022
023/**
024 * Pop a document from the context stack and restore the input from the poped document. If on the top of the stack there
025 * is no document an exception is thrown This operation contains dynamic logic so it should be handled in a special way
026 * by the UI tools to validate the chain (a Pop operation can succeed only if the last push operation has the same type
027 * as the pop)
028 *
029 * @author <a href="mailto:bs@nuxeo.com">Bogdan Stefanescu</a>
030 */
031@Operation(id = PopDocument.ID, category = Constants.CAT_EXECUTION_STACK, label = "Pop Document", description = "Restore the last saved input document in the context input stack. This operation must be used only if a PUSH operation was previously made. Return the last <i>pushed</i> document.", aliases = { "Document.Pop" })
032public class PopDocument {
033
034    public static final String ID = "Context.PopDocument";
035
036    @Context
037    protected OperationContext ctx;
038
039    @OperationMethod
040    public DocumentModel run() throws OperationException {
041        Object obj = ctx.pop(Constants.O_DOCUMENT);
042        if (obj instanceof DocumentModel) {
043            return (DocumentModel) obj;
044        } else if (obj instanceof DocumentRef) {
045            return ctx.getCoreSession().getDocument((DocumentRef) obj);
046        }
047        throw new OperationException(
048                "Illegal state error for pop document operation. The context stack doesn't contains a document on its top");
049    }
050
051}