adeb73f88d1059e58d3d610ca3b5d4ccee5d2eae
[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 javax.script.Compilable;
24 import javax.script.CompiledScript;
25 import javax.script.ScriptEngine;
26 import javax.script.ScriptEngineManager;
27 import javax.script.ScriptException;
28
29 import org.onap.policy.apex.context.ContextException;
30 import org.onap.policy.apex.core.engine.event.EnEvent;
31 import org.onap.policy.apex.core.engine.executor.TaskSelectExecutor;
32 import org.onap.policy.apex.core.engine.executor.exception.StateMachineException;
33 import org.onap.policy.apex.model.basicmodel.concepts.AxArtifactKey;
34 import org.slf4j.ext.XLogger;
35 import org.slf4j.ext.XLoggerFactory;
36
37 /**
38  * The Class JavascriptTaskSelectExecutor is the task selection executor for task selection logic written in Javascript
39  * It is unlikely that this is thread safe.
40  *
41  * @author Liam Fallon (liam.fallon@ericsson.com)
42  */
43 public class JavascriptTaskSelectExecutor extends TaskSelectExecutor {
44     // Logger for this class
45     private static final XLogger LOGGER = XLoggerFactory.getXLogger(JavascriptTaskSelectExecutor.class);
46
47     // Recurring string constants
48     private static final String TSL_FAILED_PREFIX =
49                     "execute: task selection logic failed to set a return value for state  \"";
50
51     // Javascript engine
52     private ScriptEngine engine = new ScriptEngineManager().getEngineByName("JavaScript");
53     private CompiledScript compiled = null;
54
55     /**
56      * Prepares the task for processing.
57      *
58      * @throws StateMachineException thrown when a state machine execution error occurs
59      */
60     @Override
61     public void prepare() throws StateMachineException {
62         // Call generic prepare logic
63         super.prepare();
64         try {
65             compiled = ((Compilable) engine).compile(getSubject().getTaskSelectionLogic().getLogic());
66         } catch (final ScriptException e) {
67             LOGGER.error("execute: task selection logic failed to compile for state  \"" + getSubject().getKey().getId()
68                             + "\"");
69             throw new StateMachineException("task selection logic failed to compile for state  \""
70                             + getSubject().getKey().getId() + "\"", e);
71         }
72
73     }
74
75     /**
76      * Executes the executor for the task in a sequential manner.
77      *
78      * @param executionId the execution ID for the current APEX policy execution
79      * @param incomingEvent the incoming event
80      * @return The outgoing event
81      * @throws StateMachineException on an execution error
82      * @throws ContextException on context errors
83      */
84     @Override
85     public AxArtifactKey execute(final long executionId, final EnEvent incomingEvent)
86                     throws StateMachineException, ContextException {
87         // Do execution pre work
88         executePre(executionId, incomingEvent);
89
90         // Set up the Javascript engine
91         engine.put("executor", getExecutionContext());
92
93         // Check and execute the Javascript logic
94         boolean returnValue = false;
95         try {
96             if (compiled == null) {
97                 engine.eval(getSubject().getTaskSelectionLogic().getLogic());
98             } else {
99                 compiled.eval(engine.getContext());
100             }
101         } catch (final ScriptException e) {
102             LOGGER.error("execute: task selection logic failed to run for state  \"" + getSubject().getKey().getId()
103                             + "\"");
104             throw new StateMachineException(
105                             "task selection logic failed to run for state  \"" + getSubject().getKey().getId() + "\"",
106                             e);
107         }
108
109         try {
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             returnValue = (Boolean) ret;
116         } catch (NullPointerException | ClassCastException e) {
117             LOGGER.error("execute: task selection logic failed to set a correct return value for state  \""
118                             + getSubject().getKey().getId() + "\"", e);
119             throw new StateMachineException(TSL_FAILED_PREFIX + getSubject().getKey().getId() + "\"", e);
120         }
121
122         // Do the execution post work
123         executePost(returnValue);
124
125         // Send back the return event
126         if (returnValue) {
127             return getOutgoing();
128         } else {
129             return null;
130         }
131     }
132
133     /**
134      * Cleans up the task after processing.
135      *
136      * @throws StateMachineException thrown when a state machine execution error occurs
137      */
138     @Override
139     public void cleanUp() throws StateMachineException {
140         LOGGER.debug("cleanUp:" + getSubject().getKey().getId() + ","
141                         + getSubject().getTaskSelectionLogic().getLogicFlavour() + ","
142                         + getSubject().getTaskSelectionLogic().getLogic());
143         engine = null;
144     }
145 }