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