14e4ba384243f12a439add3698643b90fbdeea46
[policy/apex-pdp.git] /
1 /*-
2  * ============LICENSE_START=======================================================
3  *  Copyright (C) 2016-2018 Ericsson. All rights reserved.
4  * ================================================================================
5  * Licensed under the Apache License, Version 2.0 (the "License");
6  * you may not use this file except in compliance with the License.
7  * You may obtain a copy of the License at
8  *
9  *      http://www.apache.org/licenses/LICENSE-2.0
10  *
11  * Unless required by applicable law or agreed to in writing, software
12  * distributed under the License is distributed on an "AS IS" BASIS,
13  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14  * See the License for the specific language governing permissions and
15  * limitations under the License.
16  *
17  * SPDX-License-Identifier: Apache-2.0
18  * ============LICENSE_END=========================================================
19  */
20
21 package org.onap.policy.apex.plugins.executor.javascript;
22
23 import java.util.Map;
24
25 import javax.script.Compilable;
26 import javax.script.CompiledScript;
27 import javax.script.ScriptEngine;
28 import javax.script.ScriptEngineManager;
29 import javax.script.ScriptException;
30
31 import org.onap.policy.apex.context.ContextException;
32 import org.onap.policy.apex.core.engine.executor.TaskExecutor;
33 import org.onap.policy.apex.core.engine.executor.exception.StateMachineException;
34 import org.slf4j.ext.XLogger;
35 import org.slf4j.ext.XLoggerFactory;
36
37 /**
38  * The Class JavascriptTaskExecutor is the task executor for task logic written in Javascript It is unlikely that this
39  * is thread safe.
40  *
41  * @author Liam Fallon (liam.fallon@ericsson.com)
42  */
43 public class JavascriptTaskExecutor extends TaskExecutor {
44     // Logger for this class
45     private static final XLogger LOGGER = XLoggerFactory.getXLogger(JavascriptTaskExecutor.class);
46
47     // Javascript engine
48     private ScriptEngine engine = new ScriptEngineManager().getEngineByName("JavaScript");
49     private CompiledScript compiled = null;
50
51     /**
52      * Prepares the task for processing.
53      *
54      * @throws StateMachineException thrown when a state machine execution error occurs
55      */
56     @Override
57     public void prepare() throws StateMachineException {
58         // Call generic prepare logic
59         super.prepare();
60         try {
61             compiled = ((Compilable) engine).compile(getSubject().getTaskLogic().getLogic());
62         } catch (final ScriptException e) {
63             LOGGER.error("execute: task logic failed to compile for task  \"" + getSubject().getKey().getId() + "\"");
64             throw new StateMachineException(
65                     "task logic failed to compile for task  \"" + getSubject().getKey().getId() + "\"", e);
66         }
67     }
68
69     /**
70      * Executes the executor for the task in a sequential manner.
71      *
72      * @param executionId the execution ID for the current APEX policy execution
73      * @param incomingFields the incoming fields
74      * @return The outgoing fields
75      * @throws StateMachineException on an execution error
76      * @throws ContextException on context errors
77      */
78     @Override
79     public Map<String, Object> execute(final long executionId, final Map<String, Object> incomingFields)
80             throws StateMachineException, ContextException {
81         // Do execution pre work
82         executePre(executionId, incomingFields);
83
84         // Set up the Javascript engine
85         engine.put("executor", getExecutionContext());
86
87         // Check and execute the Javascript logic
88         boolean returnValue = false;
89         try {
90             if (compiled == null) {
91                 engine.eval(getSubject().getTaskLogic().getLogic());
92             } else {
93                 compiled.eval(engine.getContext());
94             }
95         } catch (final ScriptException e) {
96             LOGGER.error("execute: task logic failed to run for task  \"" + getSubject().getKey().getId() + "\"");
97             throw new StateMachineException(
98                     "task logic failed to run for task  \"" + getSubject().getKey().getId() + "\"", e);
99         }
100
101         try {
102             final Object ret = engine.get("returnValue");
103             if (ret == null) {
104                 LOGGER.error("execute: task logic failed to set a return value for task  \""
105                         + getSubject().getKey().getId() + "\"");
106                 throw new StateMachineException("execute: task logic failed to set a return value for task  \""
107                         + getSubject().getKey().getId() + "\"");
108             }
109             returnValue = (Boolean) ret;
110         } catch (NullPointerException | ClassCastException e) {
111             LOGGER.error("execute: task selection logic failed to set a correct return value for state  \""
112                     + getSubject().getKey().getId() + "\"", e);
113             throw new StateMachineException("execute: task selection logic failed to set a return value for state  \""
114                     + getSubject().getKey().getId() + "\"", e);
115         }
116
117         // Do the execution post work
118         executePost(returnValue);
119
120         // Send back the return event
121         if (returnValue) {
122             return getOutgoing();
123         } else {
124             return null;
125         }
126     }
127
128     /**
129      * Cleans up the task after processing.
130      *
131      * @throws StateMachineException thrown when a state machine execution error occurs
132      */
133     @Override
134     public void cleanUp() throws StateMachineException {
135         LOGGER.debug("cleanUp:" + getSubject().getKey().getId() + "," + getSubject().getTaskLogic().getLogicFlavour()
136                 + "," + getSubject().getTaskLogic().getLogic());
137         engine = null;
138     }
139 }