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