0b99c435686f57a0c4d220368f8bafb17147b4a8
[policy/apex-pdp.git] / core / core-engine / src / main / java / org / onap / policy / apex / core / engine / executor / context / TaskExecutionContext.java
1 /*-
2  * ============LICENSE_START=======================================================
3  *  Copyright (C) 2016-2018 Ericsson. All rights reserved.
4  *  Modifications Copyright (C) 2020 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.core.engine.executor.context;
23
24 import java.util.ArrayList;
25 import java.util.Collections;
26 import java.util.HashMap;
27 import java.util.List;
28 import java.util.Map;
29 import java.util.Properties;
30 import java.util.TreeMap;
31
32 import lombok.Getter;
33 import lombok.Setter;
34
35 import org.onap.policy.apex.context.ContextAlbum;
36 import org.onap.policy.apex.context.ContextRuntimeException;
37 import org.onap.policy.apex.core.engine.context.ApexInternalContext;
38 import org.onap.policy.apex.core.engine.executor.Executor;
39 import org.onap.policy.apex.core.engine.executor.TaskExecutor;
40 import org.onap.policy.apex.model.basicmodel.concepts.AxArtifactKey;
41 import org.onap.policy.apex.model.basicmodel.concepts.AxConcept;
42 import org.onap.policy.apex.model.policymodel.concepts.AxTask;
43 import org.onap.policy.apex.model.policymodel.concepts.AxTaskParameter;
44 import org.slf4j.ext.XLogger;
45 import org.slf4j.ext.XLoggerFactory;
46
47 /**
48  * Container class for the execution context for Task logic executions in a task being executed in an Apex engine. The
49  * task must have easy access to the task definition, the incoming and outgoing field contexts, as well as the policy,
50  * global, and external context.
51  *
52  * @author Sven van der Meer (sven.van.der.meer@ericsson.com)
53  */
54 @Getter
55 public class TaskExecutionContext {
56     // Logger for task execution
57     private static final XLogger EXECUTION_LOGGER =
58             XLoggerFactory.getXLogger("org.onap.policy.apex.executionlogging.TaskExecutionLogging");
59
60     // CHECKSTYLE:OFF: checkstyle:VisibilityModifier Logic has access to these field
61
62     /** A constant <code>boolean true</code> value available for reuse e.g., for the return value */
63     public final Boolean isTrue = true;
64
65     /**
66      * A constant <code>boolean false</code> value available for reuse e.g., for the return value
67      */
68     public final Boolean isFalse = false;
69
70     /** A facade to the full task definition for the task logic being executed. */
71     public final AxTaskFacade subject;
72
73     /** the execution ID for the current APEX policy execution instance. */
74     public final Long executionId;
75
76     /**
77      * The incoming fields from the trigger event for the task. The task logic can access these fields when executing
78      * its logic.
79      */
80     public final Map<String, Object> inFields;
81
82     /**
83      * The outgoing fields from the task. The task logic can access and set these fields with its logic. A task outputs
84      * its result using these fields.
85      */
86     public final Map<String, Object> outFields;
87
88     /**
89      * Logger for task execution, task logic can use this field to access and log to Apex logging.
90      */
91     public final XLogger logger = EXECUTION_LOGGER;
92
93     // CHECKSTYLE:ON: checkstyle:VisibilityModifier
94
95     // All available context albums
96     private final Map<String, ContextAlbum> context;
97
98     // The artifact stack of users of this context
99     private final List<AxConcept> usedArtifactStack;
100
101     // A message specified in the logic
102     @Getter
103     @Setter
104     private String message;
105
106     // Execution properties for a policy execution
107     @Getter
108     private Properties executionProperties;
109
110     // Parameters associated to a task
111     @Getter
112     private Map<String, String> parameters = new HashMap<>();
113
114     /**
115      * Instantiates a new task execution context.
116      *
117      * @param taskExecutor the task executor that requires context
118      * @param executionId the execution ID for the current APEX policy execution instance
119      * @param executionProperties the execution properties for task execution
120      * @param axTask the task definition that is the subject of execution
121      * @param inFields the in fields
122      * @param outFields the out fields
123      * @param internalContext the execution context of the Apex engine in which the task is being executed
124      */
125     public TaskExecutionContext(final TaskExecutor taskExecutor, final long executionId,
126             final Properties executionProperties, final AxTask axTask, final Map<String, Object> inFields,
127             final Map<String, Object> outFields, final ApexInternalContext internalContext) {
128         // The subject is the task definition
129         subject = new AxTaskFacade(axTask);
130
131         // Populate parameters to be accessed in the task logic from the task parameters.
132         populateParameters(axTask.getTaskParameters());
133
134         // Execution ID is the current policy execution instance
135         this.executionId = executionId;
136         this.executionProperties = executionProperties;
137
138         // The input and output fields
139         this.inFields = Collections.unmodifiableMap(inFields);
140         this.outFields = outFields;
141
142         // Set up the context albums for this task
143         context = new TreeMap<>();
144         for (final AxArtifactKey mapKey : subject.task.getContextAlbumReferences()) {
145             context.put(mapKey.getName(), internalContext.getContextAlbums().get(mapKey));
146         }
147
148         // Get the artifact stack of the users of the policy
149         usedArtifactStack = new ArrayList<>();
150         for (Executor<?, ?, ?, ?> parent = taskExecutor.getParent(); parent != null; parent = parent.getParent()) {
151             // Add each parent to the top of the stack
152             usedArtifactStack.add(0, parent.getKey());
153         }
154
155         // Change the stack to an array
156         final AxConcept[] usedArtifactStackArray = usedArtifactStack.toArray(new AxConcept[usedArtifactStack.size()]);
157
158         // Set the user of the context
159         for (final ContextAlbum contextAlbum : context.values()) {
160             contextAlbum.setUserArtifactStack(usedArtifactStackArray);
161         }
162     }
163
164     /**
165      * Populate parameters to be accessed in the task logic.
166      *
167      * @param taskParameters The task parameters
168      */
169     private void populateParameters(Map<String, AxTaskParameter> taskParameters) {
170         taskParameters.entrySet().forEach(taskParamEntry -> parameters.put(taskParamEntry.getKey(),
171                 taskParamEntry.getValue().getTaskParameterValue()));
172     }
173
174     /**
175      * Return a context album if it exists in the context definition of this task.
176      *
177      * @param contextAlbumName The context album name
178      * @return The context album
179      * @throws ContextRuntimeException if the context album does not exist on the task for this executor
180      */
181     public ContextAlbum getContextAlbum(final String contextAlbumName) {
182         // Find the context album
183         final ContextAlbum foundContextAlbum = context.get(contextAlbumName);
184
185         // Check if the context album exists
186         if (foundContextAlbum != null) {
187             return foundContextAlbum;
188         } else {
189             throw new ContextRuntimeException("cannot find definition of context album \"" + contextAlbumName
190                     + "\" on task \"" + subject.getId() + "\"");
191         }
192     }
193 }