aboutsummaryrefslogtreecommitdiffstats
path: root/core/core-engine/src/main/java/org/onap/policy/apex/core/engine/executor/context/TaskExecutionContext.java
blob: 9d5087e83dbdd35ebd361a4d24b0227e4bc9484a (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
/*-
 * ============LICENSE_START=======================================================
 *  Copyright (C) 2016-2018 Ericsson. All rights reserved.
 *  Modifications Copyright (C) 2020 Nordix Foundation.
 * ================================================================================
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 * SPDX-License-Identifier: Apache-2.0
 * ============LICENSE_END=========================================================
 */

package org.onap.policy.apex.core.engine.executor.context;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.TreeMap;
import lombok.Getter;
import lombok.Setter;
import org.onap.policy.apex.context.ContextAlbum;
import org.onap.policy.apex.context.ContextRuntimeException;
import org.onap.policy.apex.core.engine.context.ApexInternalContext;
import org.onap.policy.apex.core.engine.executor.Executor;
import org.onap.policy.apex.core.engine.executor.TaskExecutor;
import org.onap.policy.apex.model.basicmodel.concepts.AxArtifactKey;
import org.onap.policy.apex.model.basicmodel.concepts.AxConcept;
import org.onap.policy.apex.model.policymodel.concepts.AxTask;
import org.onap.policy.apex.model.policymodel.concepts.AxTaskParameter;
import org.slf4j.ext.XLogger;
import org.slf4j.ext.XLoggerFactory;

/**
 * Container class for the execution context for Task logic executions in a task being executed in an Apex engine. The
 * task must have easy access to the task definition, the incoming and outgoing field contexts, as well as the policy,
 * global, and external context.
 *
 * @author Sven van der Meer (sven.van.der.meer@ericsson.com)
 */
@Getter
public class TaskExecutionContext {
    // Logger for task execution
    private static final XLogger EXECUTION_LOGGER =
            XLoggerFactory.getXLogger("org.onap.policy.apex.executionlogging.TaskExecutionLogging");

    // CHECKSTYLE:OFF: checkstyle:VisibilityModifier Logic has access to these field

    /** A constant <code>boolean true</code> value available for reuse e.g., for the return value */
    public final Boolean isTrue = true;

    /**
     * A constant <code>boolean false</code> value available for reuse e.g., for the return value
     */
    public final Boolean isFalse = false;

    /** A facade to the full task definition for the task logic being executed. */
    public final AxTaskFacade subject;

    /** the execution ID for the current APEX policy execution instance. */
    public final Long executionId;

    /**
     * The incoming fields from the trigger event for the task. The task logic can access these fields when executing
     * its logic.
     */
    public final Map<String, Object> inFields;

    /**
     * The outgoing fields from the task. The task logic can access and set these fields with its logic. A task outputs
     * its result using these fields.
     */
    public final Map<String, Object> outFields;

    /**
     * Logger for task execution, task logic can use this field to access and log to Apex logging.
     */
    public final XLogger logger = EXECUTION_LOGGER;

    // CHECKSTYLE:ON: checkstyle:VisibilityModifier

    // All available context albums
    private final Map<String, ContextAlbum> context;

    // The artifact stack of users of this context
    private final List<AxConcept> usedArtifactStack;

    // A message specified in the logic
    @Getter
    @Setter
    private String message;

    // Execution properties for a policy execution
    @Getter
    private Properties executionProperties;

    // Parameters associated to a task
    @Getter
    private Map<String, String> parameters = new HashMap<>();

    /**
     * Instantiates a new task execution context.
     *
     * @param taskExecutor the task executor that requires context
     * @param executionId the execution ID for the current APEX policy execution instance
     * @param executionProperties the execution properties for task execution
     * @param axTask the task definition that is the subject of execution
     * @param inFields the in fields
     * @param outFields the out fields
     * @param internalContext the execution context of the Apex engine in which the task is being executed
     */
    public TaskExecutionContext(final TaskExecutor taskExecutor, final long executionId,
            final Properties executionProperties, final AxTask axTask, final Map<String, Object> inFields,
            final Map<String, Object> outFields, final ApexInternalContext internalContext) {
        // The subject is the task definition
        subject = new AxTaskFacade(axTask);

        // Populate parameters to be accessed in the task logic from the task parameters.
        populateParameters(axTask.getTaskParameters());

        // Execution ID is the current policy execution instance
        this.executionId = executionId;
        this.executionProperties = executionProperties;

        // The input and output fields
        this.inFields = Collections.unmodifiableMap(inFields);
        this.outFields = outFields;

        // Set up the context albums for this task
        context = new TreeMap<>();
        for (final AxArtifactKey mapKey : subject.task.getContextAlbumReferences()) {
            context.put(mapKey.getName(), internalContext.getContextAlbums().get(mapKey));
        }

        // Get the artifact stack of the users of the policy
        usedArtifactStack = new ArrayList<>();
        for (Executor<?, ?, ?, ?> parent = taskExecutor.getParent(); parent != null; parent = parent.getParent()) {
            // Add each parent to the top of the stack
            usedArtifactStack.add(0, parent.getKey());
        }

        // Change the stack to an array
        final AxConcept[] usedArtifactStackArray = usedArtifactStack.toArray(new AxConcept[usedArtifactStack.size()]);

        // Set the user of the context
        for (final ContextAlbum contextAlbum : context.values()) {
            contextAlbum.setUserArtifactStack(usedArtifactStackArray);
        }
    }

    /**
     * Populate parameters to be accessed in the task logic.
     *
     * @param taskParameters The task parameters
     */
    private void populateParameters(Map<String, AxTaskParameter> taskParameters) {
        taskParameters.entrySet().forEach(taskParamEntry -> parameters.put(taskParamEntry.getKey(),
                taskParamEntry.getValue().getTaskParameterValue()));
    }

    /**
     * Return a context album if it exists in the context definition of this task.
     *
     * @param contextAlbumName The context album name
     * @return The context album
     * @throws ContextRuntimeException if the context album does not exist on the task for this executor
     */
    public ContextAlbum getContextAlbum(final String contextAlbumName) {
        // Find the context album
        final ContextAlbum foundContextAlbum = context.get(contextAlbumName);

        // Check if the context album exists
        if (foundContextAlbum != null) {
            return foundContextAlbum;
        } else {
            throw new ContextRuntimeException("cannot find definition of context album \"" + contextAlbumName
                    + "\" on task \"" + subject.getId() + "\"");
        }
    }
}