001/*
002 * (C) Copyright 2012 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: Sun Seng David TAN <stan@nuxeo.com>
017 */
018package org.nuxeo.ecm.automation.core.operations;
019
020import org.mvel2.CompileException;
021import org.nuxeo.ecm.automation.OperationContext;
022import org.nuxeo.ecm.automation.core.Constants;
023import org.nuxeo.ecm.automation.core.annotations.Context;
024import org.nuxeo.ecm.automation.core.annotations.Operation;
025import org.nuxeo.ecm.automation.core.annotations.OperationMethod;
026import org.nuxeo.ecm.automation.core.annotations.Param;
027import org.nuxeo.ecm.automation.core.scripting.Expression;
028import org.nuxeo.ecm.automation.core.scripting.Scripting;
029import org.nuxeo.ecm.core.api.DocumentModelList;
030
031/**
032 * Run a script and return the result documents object of the script the output of the operation
033 *
034 * @since 5.6
035 */
036@Operation(id = RestoreDocumentsInputFromScript.ID, category = Constants.CAT_EXECUTION, label = "Restore input documents from a script", description = "Run a script and return the result documents object of the script the output of the operation")
037public class RestoreDocumentsInputFromScript {
038
039    public static final String ID = "Context.RestoreDocumentsInputFromScript";
040
041    @Context
042    protected OperationContext ctx;
043
044    @Param(name = "script", widget = Constants.W_MULTILINE_TEXT)
045    protected String script;
046
047    private volatile Expression expr;
048
049    @OperationMethod
050    public DocumentModelList run() throws CompileException, RuntimeException {
051        if (expr == null) {
052            String text = script.replaceAll("&lt;", "<");
053            text = text.replaceAll("&gt;", ">");
054            text = text.replaceAll("&amp;", "&");
055            expr = Scripting.newExpression(text);
056        }
057        return (DocumentModelList) expr.eval(ctx);
058    }
059
060}