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.CoreSession;
021import org.nuxeo.ecm.core.api.DocumentModelList;
022import org.nuxeo.ecm.core.api.DocumentRef;
023import org.nuxeo.ecm.core.api.DocumentRefList;
024import org.nuxeo.ecm.core.api.impl.DocumentModelListImpl;
025
026/**
027 * Pop a document from the context stack and restore the input from the popped document. If on the top of the stack
028 * there is no document an exception is thrown This operation contains dynamic logic so it should be handled in a
029 * special way by the UI tools to validate the chain (a Pop operation can succeed only if the last push operation has
030 * the same type as the pop)
031 *
032 * @author <a href="mailto:bs@nuxeo.com">Bogdan Stefanescu</a>
033 */
034@Operation(id = PopDocumentList.ID, category = Constants.CAT_EXECUTION_STACK, label = "Pop Document List", description = "Restore the last saved input document list in the context input stack", aliases = { "Document.PopList" })
035public class PopDocumentList {
036
037    public static final String ID = "Context.PopDocumentList";
038
039    @Context
040    protected OperationContext ctx;
041
042    @OperationMethod
043    public DocumentModelList run() throws OperationException {
044        Object obj = ctx.pop(Constants.O_DOCUMENTS);
045        if (obj instanceof DocumentModelList) {
046            return (DocumentModelList) obj;
047        } else if (obj instanceof DocumentRefList) {
048            CoreSession session = ctx.getCoreSession();
049            DocumentRefList refs = (DocumentRefList) obj;
050            DocumentModelListImpl list = new DocumentModelListImpl((int) refs.totalSize());
051            for (DocumentRef ref : refs) {
052                list.add(session.getDocument(ref));
053            }
054            // FIXME: variable list is never used!
055        }
056        throw new OperationException(
057                "Illegal state error for pop document operation. The context stack doesn't contains a document list on its top");
058    }
059
060}