001/*
002 * (C) Copyright 2012 Nuxeo SA (http://nuxeo.com/) and contributors.
003 *
004 * All rights reserved. This program and the accompanying materials are made
005 * available under the terms of the GNU Lesser General Public License (LGPL)
006 * 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, but WITHOUT
010 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
011 * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
012 * details.
013 *
014 * Contributors: Sun Seng David TAN <stan@nuxeo.com>
015 */
016package org.nuxeo.ecm.automation.core.operations;
017
018import org.mvel2.CompileException;
019import org.nuxeo.ecm.automation.OperationContext;
020import org.nuxeo.ecm.automation.core.Constants;
021import org.nuxeo.ecm.automation.core.annotations.Context;
022import org.nuxeo.ecm.automation.core.annotations.Operation;
023import org.nuxeo.ecm.automation.core.annotations.OperationMethod;
024import org.nuxeo.ecm.automation.core.annotations.Param;
025import org.nuxeo.ecm.automation.core.scripting.Expression;
026import org.nuxeo.ecm.automation.core.scripting.Scripting;
027import org.nuxeo.ecm.core.api.Blob;
028
029/**
030 * Run a script and return the result blob object of the script the output of the operation.
031 *
032 * @since 5.6
033 */
034@Operation(id = RestoreBlobInputFromScript.ID, category = Constants.CAT_EXECUTION, label = "Restore input blob from a script", description = "Run a script and return the result blob object of the script the output of the operation")
035public class RestoreBlobInputFromScript {
036
037    public static final String ID = "Context.RestoreBlobInputFromScript";
038
039    @Context
040    protected OperationContext ctx;
041
042    @Param(name = "script", widget = Constants.W_MULTILINE_TEXT)
043    protected String script;
044
045    private volatile Expression expr;
046
047    @OperationMethod
048    public Blob run() throws CompileException, RuntimeException {
049        if (expr == null) {
050            String text = script.replaceAll("&lt;", "<");
051            text = text.replaceAll("&gt;", ">");
052            text = text.replaceAll("&amp;", "&");
053            expr = Scripting.newExpression(text);
054        }
055        return (Blob) expr.eval(ctx);
056    }
057
058}