93f6216fc40a37267a13740df31eb0415a7bb5d2
[policy/apex-pdp.git] /
1 /*-
2  * ============LICENSE_START=======================================================
3  * Copyright (C) 2020 Nordix Foundation.
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 org.graalvm.polyglot.Context;
24 import org.graalvm.polyglot.HostAccess;
25 import org.graalvm.polyglot.Value;
26 import org.onap.policy.apex.core.engine.executor.exception.StateMachineException;
27 import org.onap.policy.apex.model.basicmodel.concepts.AxKey;
28
29 /**
30  * The Class JavascriptExecutor is the executor for task logic written in Javascript.
31  *
32  * @author Liam Fallon (liam.fallon@ericsson.com)
33  */
34 public class JavascriptExecutor {
35     // The key of the subject that wants to execute Javascript code
36     final AxKey subjectKey;
37
38     // The Javascript context
39     private final Context jsContext;
40
41     /**
42      * Prepares the executor for processing.
43      *
44      * @param subjectKey the key of the subject that is requesting Javascript execution
45      * @throws StateMachineException thrown when instantiation of the executor fails
46      */
47     public JavascriptExecutor(final AxKey subjectKey) throws StateMachineException {
48         this.subjectKey = subjectKey;
49
50         // @formatter:off
51         jsContext =
52                 Context.newBuilder("js")
53                 .allowHostClassLookup(s -> true)
54                 .allowHostAccess(HostAccess.ALL)
55                 .build();
56         // @formatter:on
57
58         try {
59             jsContext.getBindings("js");
60         } catch (Exception e) {
61             jsContext.close();
62             throw new StateMachineException(
63                     "prepare: javascript engine failed to initialize properly for \"" + subjectKey.getId() + "\"", e);
64         }
65     }
66
67     /**
68      * Executes the the Javascript code.
69      *
70      * @param executionContext the execution context of the subject to be passed to the Javascript context
71      * @param javascriptCode the Javascript code to execute
72      * @return true if the Javascript executed properly
73      * @throws StateMachineException thrown when Javascript execution fails
74      */
75     public boolean execute(final Object executionContext, final String javascriptCode) throws StateMachineException {
76         try {
77             // Set up the Javascript engine context
78             jsContext.getBindings("js").putMember("executor", executionContext);
79             jsContext.eval("js", javascriptCode);
80
81         } catch (final Exception e) {
82             throw new StateMachineException("execute: logic failed to run for \"" + subjectKey.getId() + "\"", e);
83         }
84
85         Value returnValue = jsContext.getBindings("js").getMember("returnValue");
86
87         if (returnValue == null || returnValue.isNull()) {
88             throw new StateMachineException(
89                     "execute: logic failed to set a return value for \"" + subjectKey.getId() + "\"");
90         }
91
92         return returnValue.asBoolean();
93     }
94
95     /**
96      * Cleans up the executor after processing.
97      *
98      * @throws StateMachineException thrown when cleanup of the executor fails
99      */
100     public void cleanUp() throws StateMachineException {
101         try {
102             jsContext.close();
103         } catch (final Exception e) {
104             throw new StateMachineException(
105                     "cleanUp: executor cleanup failed to close for \"" + subjectKey.getId() + "\"", e);
106         }
107     }
108 }