001/*
002 * (C) Copyright 2015-2016 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:
017 *     Thierry Delprat <tdelprat@nuxeo.com>
018 */
019package org.nuxeo.automation.scripting.internals;
020
021import java.io.ByteArrayInputStream;
022import java.nio.charset.Charset;
023import java.util.Map;
024
025import javax.script.ScriptException;
026
027import org.nuxeo.automation.scripting.api.AutomationScriptingService;
028import org.nuxeo.automation.scripting.api.AutomationScriptingService.Session;
029import org.nuxeo.ecm.automation.OperationContext;
030import org.nuxeo.ecm.automation.OperationException;
031import org.nuxeo.runtime.api.Framework;
032
033/**
034 * @since 7.2
035 */
036public class ScriptingOperationImpl {
037
038    protected final String script;
039
040    protected final OperationContext ctx;
041
042    protected final Map<String, Object> args;
043
044    protected ScriptingOperationImpl(String script, OperationContext ctx, Map<String, Object> args) {
045        this.script = script;
046        this.ctx = ctx;
047        this.args = args;
048    }
049
050    public interface Runnable {
051        Object run(Object input, Map<String, Object> parameters);
052    }
053
054    public Object run() throws Exception {
055        return run(ctx.getInput());
056    }
057
058    /**
059     * {@code run} method accepting an input as first argument.
060     *
061     * @since 9.3
062     */
063    public Object run(Object input) throws Exception {
064        try (Session session = Framework.getService(AutomationScriptingService.class).get(ctx)) {
065            return session.handleof(new ByteArrayInputStream(script.getBytes(Charset.forName("UTF-8"))), Runnable.class)
066                          .run(input, args);
067        } catch (ScriptException e) {
068            throw new OperationException(e);
069        }
070    }
071}