aboutsummaryrefslogtreecommitdiffstats
path: root/core/core-engine
diff options
context:
space:
mode:
Diffstat (limited to 'core/core-engine')
-rw-r--r--core/core-engine/pom.xml54
-rw-r--r--core/core-engine/src/main/java/org/onap/policy/apex/core/engine/EngineParameters.java95
-rw-r--r--core/core-engine/src/main/java/org/onap/policy/apex/core/engine/ExecutorParameters.java123
-rw-r--r--core/core-engine/src/main/java/org/onap/policy/apex/core/engine/context/ApexInternalContext.java232
-rw-r--r--core/core-engine/src/main/java/org/onap/policy/apex/core/engine/context/package-info.java28
-rw-r--r--core/core-engine/src/main/java/org/onap/policy/apex/core/engine/engine/ApexEngine.java144
-rw-r--r--core/core-engine/src/main/java/org/onap/policy/apex/core/engine/engine/EnEventListener.java41
-rw-r--r--core/core-engine/src/main/java/org/onap/policy/apex/core/engine/engine/impl/ApexEngineFactory.java43
-rw-r--r--core/core-engine/src/main/java/org/onap/policy/apex/core/engine/engine/impl/ApexEngineImpl.java451
-rw-r--r--core/core-engine/src/main/java/org/onap/policy/apex/core/engine/engine/impl/StateMachineHandler.java186
-rw-r--r--core/core-engine/src/main/java/org/onap/policy/apex/core/engine/engine/impl/package-info.java27
-rw-r--r--core/core-engine/src/main/java/org/onap/policy/apex/core/engine/engine/package-info.java30
-rw-r--r--core/core-engine/src/main/java/org/onap/policy/apex/core/engine/event/EnEvent.java338
-rw-r--r--core/core-engine/src/main/java/org/onap/policy/apex/core/engine/event/EnException.java51
-rw-r--r--core/core-engine/src/main/java/org/onap/policy/apex/core/engine/event/EnField.java153
-rw-r--r--core/core-engine/src/main/java/org/onap/policy/apex/core/engine/event/package-info.java28
-rw-r--r--core/core-engine/src/main/java/org/onap/policy/apex/core/engine/executor/Executor.java161
-rw-r--r--core/core-engine/src/main/java/org/onap/policy/apex/core/engine/executor/ExecutorFactory.java67
-rw-r--r--core/core-engine/src/main/java/org/onap/policy/apex/core/engine/executor/StateExecutor.java381
-rw-r--r--core/core-engine/src/main/java/org/onap/policy/apex/core/engine/executor/StateFinalizerExecutor.java272
-rw-r--r--core/core-engine/src/main/java/org/onap/policy/apex/core/engine/executor/StateMachineExecutor.java290
-rw-r--r--core/core-engine/src/main/java/org/onap/policy/apex/core/engine/executor/StateOutput.java167
-rw-r--r--core/core-engine/src/main/java/org/onap/policy/apex/core/engine/executor/TaskExecutor.java328
-rw-r--r--core/core-engine/src/main/java/org/onap/policy/apex/core/engine/executor/TaskSelectExecutor.java263
-rw-r--r--core/core-engine/src/main/java/org/onap/policy/apex/core/engine/executor/context/AxStateFacade.java110
-rw-r--r--core/core-engine/src/main/java/org/onap/policy/apex/core/engine/executor/context/AxTaskFacade.java131
-rw-r--r--core/core-engine/src/main/java/org/onap/policy/apex/core/engine/executor/context/StateFinalizerExecutionContext.java194
-rw-r--r--core/core-engine/src/main/java/org/onap/policy/apex/core/engine/executor/context/TaskExecutionContext.java174
-rw-r--r--core/core-engine/src/main/java/org/onap/policy/apex/core/engine/executor/context/TaskSelectionExecutionContext.java180
-rw-r--r--core/core-engine/src/main/java/org/onap/policy/apex/core/engine/executor/context/package-info.java33
-rw-r--r--core/core-engine/src/main/java/org/onap/policy/apex/core/engine/executor/exception/StateMachineException.java51
-rw-r--r--core/core-engine/src/main/java/org/onap/policy/apex/core/engine/executor/exception/StateMachineRuntimeException.java51
-rw-r--r--core/core-engine/src/main/java/org/onap/policy/apex/core/engine/executor/exception/package-info.java27
-rw-r--r--core/core-engine/src/main/java/org/onap/policy/apex/core/engine/executor/impl/ExecutorFactoryImpl.java235
-rw-r--r--core/core-engine/src/main/java/org/onap/policy/apex/core/engine/executor/impl/package-info.java27
-rw-r--r--core/core-engine/src/main/java/org/onap/policy/apex/core/engine/executor/package-info.java27
-rw-r--r--core/core-engine/src/main/java/org/onap/policy/apex/core/engine/monitoring/EventMonitor.java114
-rw-r--r--core/core-engine/src/main/java/org/onap/policy/apex/core/engine/monitoring/package-info.java28
-rw-r--r--core/core-engine/src/main/java/org/onap/policy/apex/core/engine/package-info.java30
39 files changed, 5365 insertions, 0 deletions
diff --git a/core/core-engine/pom.xml b/core/core-engine/pom.xml
new file mode 100644
index 000000000..9b33974ee
--- /dev/null
+++ b/core/core-engine/pom.xml
@@ -0,0 +1,54 @@
+<!--
+ ============LICENSE_START=======================================================
+ Copyright (C) 2018 Ericsson. All rights reserved.
+ ================================================================================
+ 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=========================================================
+-->
+<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
+ <modelVersion>4.0.0</modelVersion>
+ <parent>
+ <groupId>org.onap.policy.apex-pdp.core</groupId>
+ <artifactId>core</artifactId>
+ <version>2.0.0-SNAPSHOT</version>
+ </parent>
+
+ <artifactId>core-engine</artifactId>
+ <name>${project.artifactId}</name>
+ <description>The Apex policy execution engine</description>
+
+ <dependencies>
+ <dependency>
+ <groupId>org.onap.policy.apex-pdp.model</groupId>
+ <artifactId>policy-model</artifactId>
+ <version>${project.version}</version>
+ </dependency>
+ <dependency>
+ <groupId>org.onap.policy.apex-pdp.model</groupId>
+ <artifactId>engine-model</artifactId>
+ <version>${project.version}</version>
+ </dependency>
+ <dependency>
+ <groupId>org.onap.policy.apex-pdp.context</groupId>
+ <artifactId>context-management</artifactId>
+ <version>${project.version}</version>
+ </dependency>
+ <dependency>
+ <groupId>com.google.guava</groupId>
+ <artifactId>guava</artifactId>
+ </dependency>
+ </dependencies>
+</project> \ No newline at end of file
diff --git a/core/core-engine/src/main/java/org/onap/policy/apex/core/engine/EngineParameters.java b/core/core-engine/src/main/java/org/onap/policy/apex/core/engine/EngineParameters.java
new file mode 100644
index 000000000..ff616979d
--- /dev/null
+++ b/core/core-engine/src/main/java/org/onap/policy/apex/core/engine/EngineParameters.java
@@ -0,0 +1,95 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * Copyright (C) 2016-2018 Ericsson. All rights reserved.
+ * ================================================================================
+ * 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;
+
+import java.util.Map;
+import java.util.TreeMap;
+
+import org.onap.policy.apex.context.parameters.ContextParameters;
+import org.onap.policy.apex.model.basicmodel.service.AbstractParameters;
+import org.onap.policy.apex.model.basicmodel.service.ParameterService;
+
+/**
+ * This class holds the parameters for a single Apex engine. This parameter class holds parameters for context schemas
+ * and context albums for the engine and a map of the logic flavour executors defined for the engine and the parameters
+ * for each of those executors.
+ * <p>
+ * The context parameters for the engine are held in a {@link ContextParameters} instance. This instance holds the
+ * parameters for context schema handling that will be used by the engine as well as the context album distribution,
+ * locking, and persistence parameters.
+ * <p>
+ * In Apex, an engine can be configured to use many logic flavours. The executors for each logic flavour are identified
+ * by their name. Each logic flavour executor must have an instance of {@link ExecutorParameters} defined for it, which
+ * specifies the executor plugins to use for that logic flavour executor and specific parameters for those executor
+ * plugins.
+ *
+ * @author Liam Fallon (liam.fallon@ericsson.com)
+ */
+public class EngineParameters extends AbstractParameters {
+ private ContextParameters contextParameters = new ContextParameters();
+
+ // A map of parameters for executors of various logic types
+ private Map<String, ExecutorParameters> executorParameterMap = new TreeMap<String, ExecutorParameters>();
+
+ /**
+ * Constructor to create an engine parameters instance and register the instance with the parameter service.
+ */
+ public EngineParameters() {
+ super(EngineParameters.class.getCanonicalName());
+ ParameterService.registerParameters(EngineParameters.class, this);
+ }
+
+ /**
+ * Gets the parameters for context schema and album handling.
+ *
+ * @return the parameters for context schema and album handling
+ */
+ public ContextParameters getContextParameters() {
+ return contextParameters;
+ }
+
+ /**
+ * Sets the parameters for context schema and album handling.
+ *
+ * @param contextParameters the parameters for context schema and album handling
+ */
+ public void setContextParameters(final ContextParameters contextParameters) {
+ this.contextParameters = contextParameters;
+ }
+
+ /**
+ * Gets the executor parameter map of the engine.
+ *
+ * @return the executor parameter map of the engine
+ */
+ public Map<String, ExecutorParameters> getExecutorParameterMap() {
+ return executorParameterMap;
+ }
+
+ /**
+ * Sets the executor parameter map of the engine.
+ *
+ * @param executorParameterMap the executor parameter map of the engine
+ */
+ public void setExecutorParameterMap(final Map<String, ExecutorParameters> executorParameterMap) {
+ this.executorParameterMap = executorParameterMap;
+ }
+}
diff --git a/core/core-engine/src/main/java/org/onap/policy/apex/core/engine/ExecutorParameters.java b/core/core-engine/src/main/java/org/onap/policy/apex/core/engine/ExecutorParameters.java
new file mode 100644
index 000000000..d3a8ed5ac
--- /dev/null
+++ b/core/core-engine/src/main/java/org/onap/policy/apex/core/engine/ExecutorParameters.java
@@ -0,0 +1,123 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * Copyright (C) 2016-2018 Ericsson. All rights reserved.
+ * ================================================================================
+ * 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;
+
+import org.onap.policy.apex.model.basicmodel.service.AbstractParameters;
+import org.onap.policy.apex.model.basicmodel.service.ParameterService;
+
+/**
+ * This class provides the executors for a logic flavour. Plugin classes for execution of task logic, task selection
+ * logic, and state finalizer logic for the logic flavour must be specified.
+ * <p>
+ * Specializations of this class may provide extra parameters for their specific logic flavour executors.
+ *
+ * @author Liam Fallon (liam.fallon@ericsson.com)
+ */
+public class ExecutorParameters extends AbstractParameters {
+ // Executor Plugin classes for executors
+ private String taskExecutorPluginClass;
+ private String taskSelectionExecutorPluginClass;
+ private String stateFinalizerExecutorPluginClass;
+
+ /**
+ * Constructor to create an executor parameters instance and register the instance with the parameter service.
+ */
+ public ExecutorParameters() {
+ super(ExecutorParameters.class.getCanonicalName());
+ ParameterService.registerParameters(ExecutorParameters.class, this);
+ }
+
+ /**
+ * Constructor to create an executor parameters instance with the name of a sub class of this class and register the
+ * instance with the parameter service.
+ *
+ * @param parameterClassName the class name of a sub class of this class
+ */
+ public ExecutorParameters(final String parameterClassName) {
+ super(parameterClassName);
+ }
+
+ /**
+ * Gets the task executor plugin class for the executor.
+ *
+ * @return the task executor plugin class for the executor
+ */
+ public String getTaskExecutorPluginClass() {
+ return taskExecutorPluginClass;
+ }
+
+ /**
+ * Sets the task executor plugin class for the executor.
+ *
+ * @param taskExecutorPluginClass the task executor plugin class for the executor
+ */
+ public void setTaskExecutorPluginClass(final String taskExecutorPluginClass) {
+ this.taskExecutorPluginClass = taskExecutorPluginClass;
+ }
+
+ /**
+ * Gets the task selection executor plugin class for the executor.
+ *
+ * @return the task selection executor plugin class for the executor
+ */
+ public String getTaskSelectionExecutorPluginClass() {
+ return taskSelectionExecutorPluginClass;
+ }
+
+ /**
+ * Sets the task selection executor plugin class for the executor.
+ *
+ * @param taskSelectionExecutorPluginClass the task selection executor plugin class for the executor
+ */
+ public void setTaskSelectionExecutorPluginClass(final String taskSelectionExecutorPluginClass) {
+ this.taskSelectionExecutorPluginClass = taskSelectionExecutorPluginClass;
+ }
+
+ /**
+ * Gets the state finalizer executor plugin class for the executor.
+ *
+ * @return the state finalizer executor plugin class for the executor
+ */
+ public String getStateFinalizerExecutorPluginClass() {
+ return stateFinalizerExecutorPluginClass;
+ }
+
+ /**
+ * Sets the state finalizer executor plugin class for the executor.
+ *
+ * @param stateFinalizerExecutorPluginClass the state finalizer executor plugin class for the executor
+ */
+ public void setStateFinalizerExecutorPluginClass(final String stateFinalizerExecutorPluginClass) {
+ this.stateFinalizerExecutorPluginClass = stateFinalizerExecutorPluginClass;
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.onap.policy.apex.model.basicmodel.service.AbstractParameters#toString()
+ */
+ @Override
+ public String toString() {
+ return "ExecutorParameters [taskExecutorPluginClass=" + taskExecutorPluginClass
+ + ", taskSelectionExecutorPluginClass=" + taskSelectionExecutorPluginClass
+ + ", StateFinalizerExecutorPluginClass=" + stateFinalizerExecutorPluginClass + "]";
+ }
+}
diff --git a/core/core-engine/src/main/java/org/onap/policy/apex/core/engine/context/ApexInternalContext.java b/core/core-engine/src/main/java/org/onap/policy/apex/core/engine/context/ApexInternalContext.java
new file mode 100644
index 000000000..2186ee31d
--- /dev/null
+++ b/core/core-engine/src/main/java/org/onap/policy/apex/core/engine/context/ApexInternalContext.java
@@ -0,0 +1,232 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * Copyright (C) 2016-2018 Ericsson. All rights reserved.
+ * ================================================================================
+ * 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.context;
+
+import com.google.common.collect.Maps;
+
+import java.util.List;
+import java.util.Map;
+import java.util.Map.Entry;
+import java.util.NavigableMap;
+import java.util.Set;
+import java.util.TreeMap;
+
+import org.onap.policy.apex.context.ContextAlbum;
+import org.onap.policy.apex.context.ContextException;
+import org.onap.policy.apex.context.Distributor;
+import org.onap.policy.apex.context.impl.distribution.DistributorFactory;
+import org.onap.policy.apex.model.basicmodel.concepts.AxArtifactKey;
+import org.onap.policy.apex.model.basicmodel.concepts.AxConceptGetter;
+import org.onap.policy.apex.model.basicmodel.concepts.AxConceptGetterImpl;
+import org.onap.policy.apex.model.basicmodel.service.ModelService;
+import org.onap.policy.apex.model.contextmodel.concepts.AxContextAlbum;
+import org.onap.policy.apex.model.contextmodel.concepts.AxContextAlbums;
+import org.onap.policy.apex.model.contextmodel.handling.ContextComparer;
+import org.onap.policy.apex.model.policymodel.concepts.AxPolicyModel;
+import org.onap.policy.apex.model.utilities.comparison.KeyedMapDifference;
+
+/**
+ * This class manages the internal context for an Apex engine. This class is not thread safe and need not be because
+ * each Context object is owned by one and only one ApexEngine, which runs in a single thread and only runs one policy
+ * at a time. Therefore there is only ever one policy using a Context object at a time. The currentPolicyContextAlbum is
+ * set on the Context object by the StateMachineExecutor each time a policy is triggered.
+ *
+ * @author Liam Fallon
+ */
+public final class ApexInternalContext implements AxConceptGetter<ContextAlbum> {
+ // The key of the currently running Apex model
+ private final AxArtifactKey key;
+
+ // The context albums being used in this engine
+ private final NavigableMap<AxArtifactKey, ContextAlbum> contextAlbums =
+ Maps.synchronizedNavigableMap(new TreeMap<AxArtifactKey, ContextAlbum>());
+
+ // The internal context uses a context distributor to handle distribution of context across multiple instances
+ private Distributor contextDistributor = null;
+
+ // The key of the current policy, used to return the correct policy context album to the user
+ private final AxArtifactKey currentPolicyKey = null;
+
+ /**
+ * Constructor, instantiate the context object from the Apex model.
+ *
+ * @param apexPolicyModel the apex model
+ * @throws ContextException On errors on context setting
+ */
+ public ApexInternalContext(final AxPolicyModel apexPolicyModel) throws ContextException {
+ apexPolicyModel.register();
+
+ // The context distributor used to distribute context across policy engine instances
+ contextDistributor = new DistributorFactory().getDistributor(apexPolicyModel.getKey());
+
+ // Set up the context albums for this engine
+ for (final AxArtifactKey contextAlbumKey : ModelService.getModel(AxContextAlbums.class).getAlbumsMap()
+ .keySet()) {
+ contextAlbums.put(contextAlbumKey, contextDistributor.createContextAlbum(contextAlbumKey));
+ }
+
+ // Record the key of the current model
+ key = apexPolicyModel.getKey();
+ }
+
+ /**
+ * Get the key of the internal context, which is the same as the key of the engine.
+ *
+ * @return the key
+ */
+ public AxArtifactKey getKey() {
+ return key;
+ }
+
+ /**
+ * Get the context albums of the engine.
+ *
+ * @return the context albums
+ */
+ public Map<AxArtifactKey, ContextAlbum> getContextAlbums() {
+ return contextAlbums;
+ }
+
+ /**
+ * Update the current context so that it aligns with this incoming model, transferring context values if they exist
+ * in the new model.
+ *
+ * @param newPolicyModel The new incoming Apex model to use for context
+ * @throws ContextException On errors on context setting
+ */
+ public void update(final AxPolicyModel newPolicyModel) throws ContextException {
+ if (newPolicyModel == null) {
+ throw new ContextException("internal context update failed, supplied model is null");
+ }
+
+ // Get the differences between the existing context and the new context
+ final KeyedMapDifference<AxArtifactKey, AxContextAlbum> contextDifference =
+ new ContextComparer().compare(ModelService.getModel(AxContextAlbums.class), newPolicyModel.getAlbums());
+
+ // Remove maps that are no longer used
+ for (final Entry<AxArtifactKey, AxContextAlbum> removedContextAlbumEntry : contextDifference.getLeftOnly()
+ .entrySet()) {
+ contextDistributor.removeContextAlbum(removedContextAlbumEntry.getValue());
+ contextAlbums.remove(removedContextAlbumEntry.getKey());
+ }
+
+ // We switch over to the new Apex model
+ newPolicyModel.register();
+
+ // Set up the new context albums
+ for (final AxArtifactKey contextAlbumKey : contextDifference.getRightOnly().keySet()) {
+ contextAlbums.put(contextAlbumKey, contextDistributor.createContextAlbum(contextAlbumKey));
+ }
+
+ // Handle the updated maps
+ for (final Entry<AxArtifactKey, List<AxContextAlbum>> contextAlbumEntry : contextDifference.getDifferentValues()
+ .entrySet()) {
+ // Compare the updated maps
+ final AxContextAlbum currentContextAlbum = contextAlbumEntry.getValue().get(0);
+ final AxContextAlbum newContextAlbum = contextAlbumEntry.getValue().get(1);
+
+ // Check that the schemas are the same on the old and new context albums
+ if (currentContextAlbum.getItemSchema().equals(newContextAlbum.getItemSchema())) {
+ // The schema is different, throw an exception because the schema should not change if the key of the
+ // album has not changed
+ throw new ContextException("internal context update failed on context album \""
+ + contextAlbumEntry.getKey().getID() + "\" in model \"" + key.getID() + "\", schema \""
+ + currentContextAlbum.getItemSchema().getID()
+ + "\" on existing context model does not equal schema \""
+ + newContextAlbum.getItemSchema().getID() + "\" on incoming model");
+ }
+ }
+
+ }
+
+ /**
+ * Clear the internal context.
+ *
+ * @throws ContextException on clearing errors
+ */
+ public void clear() throws ContextException {
+ // Clear all context in the distributor
+ contextDistributor.clear();
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see java.lang.Object#toString()
+ */
+ @Override
+ public String toString() {
+ return "ApexInternalContext [contextAlbums=" + contextAlbums + ", contextDistributor=" + contextDistributor
+ + ", currentPolicyKey=" + currentPolicyKey + "]";
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see
+ * org.onap.policy.apex.core.basicmodel.concepts.AxConceptGetter#get(org.onap.policy.apex.core.basicmodel.concepts.
+ * AxArtifactKey)
+ */
+ @Override
+ public ContextAlbum get(final AxArtifactKey conceptKey) {
+ return new AxConceptGetterImpl<>(contextAlbums).get(conceptKey);
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.onap.policy.apex.core.basicmodel.concepts.AxConceptGetter#get(java.lang.String)
+ */
+ @Override
+ public ContextAlbum get(final String conceptKeyName) {
+ return new AxConceptGetterImpl<>(contextAlbums).get(conceptKeyName);
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.onap.policy.apex.core.basicmodel.concepts.AxConceptGetter#get(java.lang.String, java.lang.String)
+ */
+ @Override
+ public ContextAlbum get(final String conceptKeyName, final String conceptKeyVersion) {
+ return new AxConceptGetterImpl<>(contextAlbums).get(conceptKeyName, conceptKeyVersion);
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.onap.policy.apex.core.basicmodel.concepts.AxConceptGetter#getAll(java.lang.String)
+ */
+ @Override
+ public Set<ContextAlbum> getAll(final String conceptKeyName) {
+ return new AxConceptGetterImpl<>(contextAlbums).getAll(conceptKeyName);
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.onap.policy.apex.core.basicmodel.concepts.AxConceptGetter#getAll(java.lang.String, java.lang.String)
+ */
+ @Override
+ public Set<ContextAlbum> getAll(final String conceptKeyName, final String conceptKeyVersion) {
+ return new AxConceptGetterImpl<>(contextAlbums).getAll(conceptKeyName, conceptKeyVersion);
+ }
+}
diff --git a/core/core-engine/src/main/java/org/onap/policy/apex/core/engine/context/package-info.java b/core/core-engine/src/main/java/org/onap/policy/apex/core/engine/context/package-info.java
new file mode 100644
index 000000000..887914ee0
--- /dev/null
+++ b/core/core-engine/src/main/java/org/onap/policy/apex/core/engine/context/package-info.java
@@ -0,0 +1,28 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * Copyright (C) 2016-2018 Ericsson. All rights reserved.
+ * ================================================================================
+ * 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=========================================================
+ */
+
+/**
+ * Manages the context albums that an APEX engine requires during execution. It uses the policy model of the engine to
+ * determine what context albums the engine requires.
+ *
+ * @author Liam Fallon (liam.fallon@ericsson.com)
+ */
+
+package org.onap.policy.apex.core.engine.context;
diff --git a/core/core-engine/src/main/java/org/onap/policy/apex/core/engine/engine/ApexEngine.java b/core/core-engine/src/main/java/org/onap/policy/apex/core/engine/engine/ApexEngine.java
new file mode 100644
index 000000000..9e27e5e86
--- /dev/null
+++ b/core/core-engine/src/main/java/org/onap/policy/apex/core/engine/engine/ApexEngine.java
@@ -0,0 +1,144 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * Copyright (C) 2016-2018 Ericsson. All rights reserved.
+ * ================================================================================
+ * 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.engine;
+
+import java.util.Map;
+
+import org.onap.policy.apex.core.engine.event.EnEvent;
+import org.onap.policy.apex.model.basicmodel.concepts.ApexException;
+import org.onap.policy.apex.model.basicmodel.concepts.AxArtifactKey;
+import org.onap.policy.apex.model.enginemodel.concepts.AxEngineModel;
+import org.onap.policy.apex.model.enginemodel.concepts.AxEngineState;
+import org.onap.policy.apex.model.policymodel.concepts.AxPolicyModel;
+
+/**
+ * The Interface ApexEngine is used to control the execution of a single Apex engine thread. This engine instance
+ * executes the policies in an {@link AxPolicyModel}, which defines the policies that are executed by the engine and the
+ * context in which they execute. Many instances of an Apex engine may run on the same Apex model, in which case they
+ * operate the same policy set in parallel over the same context. When the {@code handleEvent} method is passed to the
+ * Apex engine, the engine executes the policy triggered by that event. A single Apex engine instance does not executed
+ * multiple policies in parallel, it receives a trigger event and executes the policy for that event to completion
+ * before it is available to execute another policy.
+ *
+ * @author Liam Fallon (liam.fallon@ericsson.com)
+ */
+public interface ApexEngine {
+ /**
+ * The amount of milliseconds to wait for the current Apex engine to timeout on engine stop requests. If the timeout
+ * is exceeded, the stop aborts.
+ */
+ int APEX_ENGINE_STOP_EXECUTION_WAIT_TIMEOUT = 3000;
+
+ /** The wait increment (or pause time) when waiting for the Apex engine to stop. */
+ int APEX_ENGINE_STOP_EXECUTION_WAIT_INCREMENT = 100;
+
+ /**
+ * Update the Apex model to be used by the Apex engine. The engine must be in state "STOPPED" when the model is
+ * updated. The engine will replace the current model with the incoming model if the model of the engine was
+ * previously updated and the value of common context is transferred if there is common context in the old and new
+ * models.
+ *
+ * @param apexModel the apex model
+ * @throws ApexException on model update errors
+ */
+ void updateModel(AxPolicyModel apexModel) throws ApexException;
+
+ /**
+ * Starts an Apex engine so that it can receive events.
+ *
+ * @throws ApexException on start errors
+ */
+ void start() throws ApexException;
+
+ /**
+ * Stops an Apex engine in an orderly way. This method must be called prior to model updates.
+ *
+ * @throws ApexException on stop errors
+ */
+ void stop() throws ApexException;
+
+ /**
+ * Clears all models and data from an Apex engine. The engine must be stopped.
+ *
+ * @throws ApexException on clear errors
+ */
+ void clear() throws ApexException;
+
+ /**
+ * This method constructs an event with the correct event context so that it can later be sent to the Apex engine.
+ *
+ * @param eventKey The key of the event in the Apex model
+ * @return the created event
+ */
+ EnEvent createEvent(AxArtifactKey eventKey);
+
+ /**
+ * This method passes an event to the Apex model to invoke a policy. If the event matches a policy, then that policy
+ * is executed.
+ *
+ * @return return true if a policy was invoked without error, otherwise false.
+ * @param incomingEvent the incoming event
+ */
+ boolean handleEvent(EnEvent incomingEvent);
+
+ /**
+ * A method to add a call back listener class that listens for action events from the engine.
+ *
+ * @param listenerName the unique name of the listener
+ * @param listener is an instance of type {@link EnEventListener}
+ */
+ void addEventListener(String listenerName, EnEventListener listener);
+
+ /**
+ * A method to remove a call back listener class.
+ *
+ * @param listenerName the name of the listener to remove
+ */
+ void removeEventListener(String listenerName);
+
+ /**
+ * Get the artifact key of the engine.
+ *
+ * @return the artifact key
+ */
+ AxArtifactKey getKey();
+
+ /**
+ * Get the state of the engine.
+ *
+ * @return the engine state
+ */
+ AxEngineState getState();
+
+ /**
+ * Get the engine status information, this is just the engine state.
+ *
+ * @return the Apex status information
+ */
+ AxEngineModel getEngineStatus();
+
+ /**
+ * Get the engine run time information, the status and context.
+ *
+ * @return the Apex runtime information
+ */
+ Map<AxArtifactKey, Map<String, Object>> getEngineContext();
+}
diff --git a/core/core-engine/src/main/java/org/onap/policy/apex/core/engine/engine/EnEventListener.java b/core/core-engine/src/main/java/org/onap/policy/apex/core/engine/engine/EnEventListener.java
new file mode 100644
index 000000000..32d638aef
--- /dev/null
+++ b/core/core-engine/src/main/java/org/onap/policy/apex/core/engine/engine/EnEventListener.java
@@ -0,0 +1,41 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * Copyright (C) 2016-2018 Ericsson. All rights reserved.
+ * ================================================================================
+ * 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.engine;
+
+import org.onap.policy.apex.core.engine.event.EnEvent;
+import org.onap.policy.apex.model.basicmodel.concepts.ApexException;
+
+/**
+ * This interface is used by users of an Apex engine to receive action events being emitted by the engine.
+ *
+ * @author Liam Fallon
+ *
+ */
+public interface EnEventListener {
+
+ /**
+ * This method is called when an Apex engine emits an event.
+ *
+ * @param enEvent the engine event
+ * @throws ApexException the apex exception
+ */
+ void onEnEvent(EnEvent enEvent) throws ApexException;
+}
diff --git a/core/core-engine/src/main/java/org/onap/policy/apex/core/engine/engine/impl/ApexEngineFactory.java b/core/core-engine/src/main/java/org/onap/policy/apex/core/engine/engine/impl/ApexEngineFactory.java
new file mode 100644
index 000000000..4920486de
--- /dev/null
+++ b/core/core-engine/src/main/java/org/onap/policy/apex/core/engine/engine/impl/ApexEngineFactory.java
@@ -0,0 +1,43 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * Copyright (C) 2016-2018 Ericsson. All rights reserved.
+ * ================================================================================
+ * 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.engine.impl;
+
+import org.onap.policy.apex.core.engine.engine.ApexEngine;
+import org.onap.policy.apex.model.basicmodel.concepts.AxArtifactKey;
+
+/**
+ * A factory class to create APEX engines of a given type. As there is only a single type of Apex engine in existence,
+ * this class is trivial.
+ *
+ * @author Liam Fallon
+ */
+public class ApexEngineFactory {
+
+ /**
+ * Create an Apex engine implementation.
+ *
+ * @param key the key
+ * @return the apex engine
+ */
+ public ApexEngine createApexEngine(final AxArtifactKey key) {
+ return new ApexEngineImpl(key);
+ }
+}
diff --git a/core/core-engine/src/main/java/org/onap/policy/apex/core/engine/engine/impl/ApexEngineImpl.java b/core/core-engine/src/main/java/org/onap/policy/apex/core/engine/engine/impl/ApexEngineImpl.java
new file mode 100644
index 000000000..12ba76afb
--- /dev/null
+++ b/core/core-engine/src/main/java/org/onap/policy/apex/core/engine/engine/impl/ApexEngineImpl.java
@@ -0,0 +1,451 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * Copyright (C) 2016-2018 Ericsson. All rights reserved.
+ * ================================================================================
+ * 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.engine.impl;
+
+import static org.onap.policy.apex.model.utilities.Assertions.argumentNotNull;
+
+import java.util.LinkedHashMap;
+import java.util.Map;
+import java.util.Map.Entry;
+
+import org.onap.policy.apex.context.ContextAlbum;
+import org.onap.policy.apex.context.ContextException;
+import org.onap.policy.apex.core.engine.context.ApexInternalContext;
+import org.onap.policy.apex.core.engine.engine.ApexEngine;
+import org.onap.policy.apex.core.engine.engine.EnEventListener;
+import org.onap.policy.apex.core.engine.event.EnEvent;
+import org.onap.policy.apex.core.engine.executor.exception.StateMachineException;
+import org.onap.policy.apex.model.basicmodel.concepts.ApexException;
+import org.onap.policy.apex.model.basicmodel.concepts.AxArtifactKey;
+import org.onap.policy.apex.model.basicmodel.concepts.AxReferenceKey;
+import org.onap.policy.apex.model.enginemodel.concepts.AxEngineModel;
+import org.onap.policy.apex.model.enginemodel.concepts.AxEngineState;
+import org.onap.policy.apex.model.enginemodel.concepts.AxEngineStats;
+import org.onap.policy.apex.model.policymodel.concepts.AxPolicyModel;
+import org.slf4j.ext.XLogger;
+import org.slf4j.ext.XLoggerFactory;
+
+/**
+ * This class controls the thread of execution of a single engine in an Apex system. An engine is a single thread in a
+ * pool of engines that are running a set of policies. An engine is either inactive, waiting for a policy to be
+ * triggered or executing a policy. The engine runs off a queue of triggers that trigger its state machine. If the queue
+ * is empty, it waits for the next trigger. The Apex engine holds its state machine in a {@link StateMachineHandler}
+ * instance and uses its state machine handler to execute events.
+ *
+ * @author Liam Fallon
+ */
+public class ApexEngineImpl implements ApexEngine {
+ // Logger for this class
+ private static final XLogger LOGGER = XLoggerFactory.getXLogger(ApexEngineImpl.class);
+
+ // The artifact key of this engine
+ private final AxArtifactKey key;
+
+ // The state of this engine
+ private AxEngineState state = AxEngineState.STOPPED;
+
+ // call back listeners
+ private final Map<String, EnEventListener> eventListeners = new LinkedHashMap<String, EnEventListener>();
+
+ // The context of this engine
+ private ApexInternalContext internalContext = null;
+
+ // The state machines
+ private StateMachineHandler stateMachineHandler = null;
+
+ // Statistics on engine execution
+ private final AxEngineStats engineStats;
+
+ /**
+ * Constructor, instantiate the engine with its state machine table.
+ *
+ * @param key the key of the engine
+ */
+ protected ApexEngineImpl(final AxArtifactKey key) {
+ argumentNotNull(key, "AxArtifactKey may not be null");
+
+ LOGGER.entry("ApexEngine()->" + key.getID() + "," + state);
+
+ this.key = key;
+
+ // Set up statistics collection
+ engineStats = new AxEngineStats();
+ engineStats.setKey(new AxReferenceKey(key, "_EngineStats"));
+
+ LOGGER.exit("ApexEngine()<-" + key.getID() + "," + state);
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see
+ * org.onap.policy.apex.core.engine.engine.ApexEngine#updateModel(org.onap.policy.apex.model.policymodel.concepts.
+ * AxPolicyModel)
+ */
+ @Override
+ public void updateModel(final AxPolicyModel apexModel) throws ApexException {
+ if (apexModel != null) {
+ LOGGER.entry("updateModel()->" + key.getID() + ", apexPolicyModel=" + apexModel.getKey().getID());
+ } else {
+ LOGGER.warn("updateModel()<-" + key.getID() + ", Apex model not set");
+ throw new ApexException(
+ "updateModel()<-" + key.getID() + ", Apex model is not defined, it has a null value");
+ }
+
+ // The engine must be stopped in order to do a model update
+ if (!state.equals(AxEngineState.STOPPED)) {
+ throw new ApexException("updateModel()<-" + key.getID()
+ + ", cannot update model, engine should be stopped but is in state " + state);
+ }
+
+ // Create new internal context or update the existing one
+ try {
+ if (internalContext == null) {
+ /// New internal context
+ internalContext = new ApexInternalContext(apexModel);
+ } else {
+ // Exiting internal context which must be updated
+ internalContext.update(apexModel);
+ }
+ } catch (final ContextException e) {
+ LOGGER.warn(
+ "updateModel()<-" + key.getID() + ", error setting the context for engine \"" + key.getID() + "\"",
+ e);
+ throw new ApexException(
+ "updateModel()<-" + key.getID() + ", error setting the context for engine \"" + key.getID() + "\"",
+ e);
+ }
+
+ // Set up the state machines
+ try {
+ // We always set up state machines as new because it's only context that must be transferred; policies are
+ // always set up as new
+ stateMachineHandler = new StateMachineHandler(internalContext);
+ } catch (final StateMachineException e) {
+ LOGGER.warn("updateModel()<-" + key.getID() + ", error setting up the engine state machines \""
+ + key.getID() + "\"", e);
+ throw new ApexException("updateModel()<-" + key.getID() + ", error setting up the engine state machines \""
+ + key.getID() + "\"", e);
+ }
+
+ LOGGER.exit("updateModel()<-" + key.getID());
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.onap.policy.apex.core.engine.engine.ApexEngine#start()
+ */
+ @Override
+ public void start() throws ApexException {
+ LOGGER.entry("start()" + key);
+
+ if (state != AxEngineState.STOPPED) {
+ LOGGER.warn("start()<-" + key.getID() + "," + state + ", cannot start engine, engine not in state STOPPED");
+ throw new ApexException(
+ "start()<-" + key.getID() + "," + state + ", cannot start engine, engine not in state STOPPED");
+ }
+
+ if (stateMachineHandler == null || internalContext == null) {
+ LOGGER.warn("start()<-" + key.getID() + "," + state
+ + ", cannot start engine, engine has not been initialized, its model is not loaded");
+ throw new ApexException("start()<-" + key.getID() + "," + state
+ + ", cannot start engine, engine has not been initialized, its model is not loaded");
+ }
+
+ // Set up the state machines
+ try {
+ // Start the state machines
+ stateMachineHandler.start();
+ engineStats.engineStart();
+ } catch (final StateMachineException e) {
+ LOGGER.warn("updateModel()<-" + key.getID() + ", error starting the engine state machines \"" + key.getID()
+ + "\"", e);
+ throw new ApexException("updateModel()<-" + key.getID() + ", error starting the engine state machines \""
+ + key.getID() + "\"", e);
+ }
+
+ // OK, we are good to go
+ state = AxEngineState.READY;
+
+ LOGGER.exit("start()" + key);
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.onap.policy.apex.core.engine.engine.ApexEngine#stop()
+ */
+ @Override
+ public void stop() throws ApexException {
+ LOGGER.entry("stop()->" + key);
+
+ // Stop the engine if it is in state READY, if it is in state EXECUTING, wait for execution to finish
+ for (int increment = APEX_ENGINE_STOP_EXECUTION_WAIT_TIMEOUT; increment > 0; increment =
+ APEX_ENGINE_STOP_EXECUTION_WAIT_INCREMENT) {
+ synchronized (state) {
+ switch (state) {
+ // Already stopped
+ case STOPPED:
+
+ throw new ApexException("stop()<-" + key.getID() + "," + state
+ + ", cannot stop engine, engine is already stopped");
+ // The normal case, the engine wasn't doing anything or it was executing
+ case READY:
+ case STOPPING:
+
+ state = AxEngineState.STOPPED;
+ stateMachineHandler.stop();
+ engineStats.engineStop();
+ LOGGER.exit("stop()" + key);
+ return;
+ // Engine is executing a policy, wait for it to stop
+ case EXECUTING:
+ state = AxEngineState.STOPPING;
+ break;
+ default:
+ throw new ApexException("stop()<-" + key.getID() + "," + state
+ + ", cannot stop engine, engine is in an undefined state");
+ }
+ }
+ }
+
+ throw new ApexException("stop()<-" + key.getID() + "," + state + ", cannot stop engine, engine stop timed out");
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.onap.policy.apex.core.engine.engine.ApexEngine#clear()
+ */
+ @Override
+ public void clear() throws ApexException {
+ LOGGER.entry("clear()->" + key);
+ if (state != AxEngineState.STOPPED) {
+ throw new ApexException(
+ "clear" + "()<-" + key.getID() + "," + state + ", cannot clear engine, engine is not stopped");
+ }
+
+ // Clear everything
+ stateMachineHandler = null;
+ engineStats.clean();
+ internalContext.clear();
+ internalContext = null;
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.onap.policy.apex.core.engine.engine.ApexEngine#createEvent(org.onap.policy.apex.core.model.concepts.
+ * AxArtifactKey)
+ */
+ @Override
+ public EnEvent createEvent(final AxArtifactKey eventKey) {
+ if (state != AxEngineState.READY && state != AxEngineState.EXECUTING) {
+ LOGGER.warn(
+ "createEvent()<-" + key.getID() + "," + state + ", cannot create event, engine not in state READY");
+ return null;
+ }
+
+ try {
+ // Create an event using the internal context
+ return new EnEvent(eventKey);
+ } catch (final Exception e) {
+ LOGGER.warn("createEvent()<-" + key.getID() + "," + state + ", error on event creation", e);
+ return null;
+ }
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see
+ * org.onap.policy.apex.core.engine.engine.ApexEngine#handleEvent(org.onap.policy.apex.core.engine.event.EnEvent)
+ */
+ @Override
+ public boolean handleEvent(final EnEvent incomingEvent) {
+ boolean ret = false;
+ if (incomingEvent == null) {
+ LOGGER.warn("handleEvent()<-" + key.getID() + "," + state + ", cannot run engine, incoming event is null");
+ return ret;
+ }
+
+ synchronized (state) {
+ if (state != AxEngineState.READY) {
+ LOGGER.warn("handleEvent()<-" + key.getID() + "," + state
+ + ", cannot run engine, engine not in state READY");
+ return ret;
+ }
+
+ state = AxEngineState.EXECUTING;
+ }
+
+ LOGGER.debug("execute(): triggered by event " + incomingEvent.toString());
+
+ // By default we return a null event on errors
+ EnEvent outgoingEvent = null;
+ try {
+ engineStats.executionEnter(incomingEvent.getKey());
+ outgoingEvent = stateMachineHandler.execute(incomingEvent);
+ engineStats.executionExit();
+ ret = true;
+ } catch (final StateMachineException e) {
+ LOGGER.warn("handleEvent()<-" + key.getID() + "," + state + ", engine execution error: ", e);
+
+ // Create an exception return event
+ outgoingEvent = createExceptionEvent(incomingEvent, e);
+ }
+
+ // Publish the outgoing event
+ try {
+ synchronized (eventListeners) {
+ if (eventListeners.isEmpty()) {
+ LOGGER.debug("handleEvent()<-" + key.getID() + "," + state
+ + ", There is no listener registered to recieve outgoing event: " + outgoingEvent);
+ }
+ for (final EnEventListener axEventListener : eventListeners.values()) {
+ axEventListener.onEnEvent(outgoingEvent);
+ }
+ }
+ } catch (final ApexException e) {
+ LOGGER.warn("handleEvent()<-" + key.getID() + "," + state + ", outgoing event publishing error: ", e);
+ ret = false;
+ }
+ synchronized (state) {
+ // Only go to READY if we are still in state EXECUTING, we could be in state STOPPING
+ if (state == AxEngineState.EXECUTING) {
+ state = AxEngineState.READY;
+ }
+ }
+ return ret;
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.onap.policy.apex.core.engine.engine.ApexEngine#addEventListener(java.lang.String,
+ * org.onap.policy.apex.core.engine.engine.EnEventListener)
+ */
+ @Override
+ public void addEventListener(final String listenerName, final EnEventListener listener) {
+ eventListeners.put(listenerName, listener);
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.onap.policy.apex.core.engine.engine.ApexEngine#removeEventListener(java.lang.String)
+ */
+ @Override
+ public void removeEventListener(final String listenerName) {
+ eventListeners.remove(listenerName);
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.onap.policy.apex.core.engine.engine.ApexEngine#getKey()
+ */
+ @Override
+ public AxArtifactKey getKey() {
+ return key;
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.onap.policy.apex.core.engine.engine.ApexEngine#getState()
+ */
+ @Override
+ public final AxEngineState getState() {
+ return state;
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.onap.policy.apex.core.engine.engine.ApexEngine#getEngineStatus()
+ */
+ @Override
+ public AxEngineModel getEngineStatus() {
+ final AxEngineModel engineModel = new AxEngineModel(key);
+ engineModel.setTimestamp(System.currentTimeMillis());
+ engineModel.setState(state);
+ engineModel.setStats(engineStats);
+ return engineModel;
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.onap.policy.apex.core.engine.engine.ApexEngine#getEngineRuntime()
+ */
+ @Override
+ public Map<AxArtifactKey, Map<String, Object>> getEngineContext() {
+ final Map<AxArtifactKey, Map<String, Object>> currentContext =
+ new LinkedHashMap<AxArtifactKey, Map<String, Object>>();
+
+ for (final Entry<AxArtifactKey, ContextAlbum> contextAlbumEntry : internalContext.getContextAlbums()
+ .entrySet()) {
+ currentContext.put(contextAlbumEntry.getKey(), contextAlbumEntry.getValue());
+ }
+
+ return currentContext;
+ }
+
+ /**
+ * Get the internal context for the Apex engine.
+ *
+ * @return The Apex Internal Context
+ */
+ public ApexInternalContext getInternalContext() {
+ return internalContext;
+ }
+
+ /**
+ * Create an exception event from the incoming event including the exception information on the event.
+ *
+ * @param incomingEvent The incoming event that caused the exception
+ * @param eventException The exception that was thrown
+ * @return the exception event
+ */
+ private EnEvent createExceptionEvent(final EnEvent incomingEvent, final Exception eventException) {
+ // The exception event is a clone of the incoming event with the exception suffix added to its name and an extra
+ // field "ExceptionMessage" added
+ final EnEvent exceptionEvent = (EnEvent) incomingEvent.clone();
+
+ // Create the cascaded message string
+ final StringBuilder exceptionMessageStringBuilder = new StringBuilder();
+ exceptionMessageStringBuilder.append(eventException.getMessage());
+
+ Throwable subException = eventException.getCause();
+ while (subException != null) {
+ exceptionMessageStringBuilder.append("\ncaused by: ");
+ exceptionMessageStringBuilder.append(subException.getMessage());
+ subException = subException.getCause();
+ }
+
+ // Set the exception message on the event
+ exceptionEvent.setExceptionMessage(exceptionMessageStringBuilder.toString());
+
+ return exceptionEvent;
+ }
+}
diff --git a/core/core-engine/src/main/java/org/onap/policy/apex/core/engine/engine/impl/StateMachineHandler.java b/core/core-engine/src/main/java/org/onap/policy/apex/core/engine/engine/impl/StateMachineHandler.java
new file mode 100644
index 000000000..856136bab
--- /dev/null
+++ b/core/core-engine/src/main/java/org/onap/policy/apex/core/engine/engine/impl/StateMachineHandler.java
@@ -0,0 +1,186 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * Copyright (C) 2016-2018 Ericsson. All rights reserved.
+ * ================================================================================
+ * 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.engine.impl;
+
+import java.util.HashMap;
+
+import org.onap.policy.apex.core.engine.context.ApexInternalContext;
+import org.onap.policy.apex.core.engine.event.EnEvent;
+import org.onap.policy.apex.core.engine.executor.ExecutorFactory;
+import org.onap.policy.apex.core.engine.executor.StateMachineExecutor;
+import org.onap.policy.apex.core.engine.executor.exception.StateMachineException;
+import org.onap.policy.apex.core.engine.executor.impl.ExecutorFactoryImpl;
+import org.onap.policy.apex.model.basicmodel.concepts.AxArtifactKey;
+import org.onap.policy.apex.model.basicmodel.service.ModelService;
+import org.onap.policy.apex.model.eventmodel.concepts.AxEvent;
+import org.onap.policy.apex.model.eventmodel.concepts.AxEvents;
+import org.onap.policy.apex.model.policymodel.concepts.AxPolicies;
+import org.onap.policy.apex.model.policymodel.concepts.AxPolicy;
+import org.slf4j.ext.XLogger;
+import org.slf4j.ext.XLoggerFactory;
+
+/**
+ * This handler holds and manages state machines for each policy in an Apex engine. When the class is instantiated, an
+ * executor {@link StateMachineExecutor} is created for each policy in the policy model the state machine handler will
+ * execute. The executors for each policy are held in a map indexed by event.
+ * <p>
+ * When an event is received on the policy, the state machine executor to execute that event is looked up on the
+ * executor map and the event is passed to the executor for execution.
+ *
+ * @author Liam Fallon
+ *
+ */
+public class StateMachineHandler {
+ // Logger for this class
+ private static final XLogger LOGGER = XLoggerFactory.getXLogger(StateMachineHandler.class);
+
+ // The key of the Apex model we are executing
+ private final AxArtifactKey key;
+
+ // The state machines in this engine
+ private final HashMap<AxEvent, StateMachineExecutor> stateMachineExecutorMap = new HashMap<>();
+
+ // The executor factory is used to get logic executors for the particular type of executor we need for task
+ // selection logic or task logic
+ private final ExecutorFactory executorFactory;
+
+ /**
+ * This constructor builds the state machines for the policies in the apex model.
+ *
+ * @param internalContext The internal context we are using
+ * @throws StateMachineException On state machine initiation errors
+ */
+ protected StateMachineHandler(final ApexInternalContext internalContext) throws StateMachineException {
+ LOGGER.entry("StateMachineHandler()->" + internalContext.getKey().getID());
+
+ key = internalContext.getKey();
+
+ // Create the executor factory to generate executors as the engine runs policies
+ executorFactory = new ExecutorFactoryImpl();
+
+ // Iterate over the policies in the policy model and create a state machine for each one
+ for (final AxPolicy policy : ModelService.getModel(AxPolicies.class).getPolicyMap().values()) {
+ // Create a state machine for this policy
+ final StateMachineExecutor thisStateMachineExecutor =
+ new StateMachineExecutor(executorFactory, policy.getKey());
+
+ // This executor is the top executor so has no parent
+ thisStateMachineExecutor.setContext(null, policy, internalContext);
+
+ // Get the incoming trigger event
+ final AxEvent triggerEvent = ModelService.getModel(AxEvents.class)
+ .get(policy.getStateMap().get(policy.getFirstState()).getTrigger());
+
+ // Put the state machine executor on the map for this trigger
+ final StateMachineExecutor lastStateMachineExecutor =
+ stateMachineExecutorMap.put(triggerEvent, thisStateMachineExecutor);
+ if (lastStateMachineExecutor != null
+ && lastStateMachineExecutor.getSubject() != thisStateMachineExecutor.getSubject()) {
+ LOGGER.error("No more than one policy in a model can have the same trigger event. In model "
+ + internalContext.getKey().getID() + " Policy ("
+ + lastStateMachineExecutor.getSubject().getKey().getID() + ") and Policy ("
+ + thisStateMachineExecutor.getSubject().getKey().getID() + ") have the same Trigger event ("
+ + triggerEvent.getKey().getID() + ") ");
+ LOGGER.error(" Policy (" + lastStateMachineExecutor.getSubject().getKey() + ") has overwritten Policy ("
+ + thisStateMachineExecutor.getSubject().getKey().getID()
+ + " so this overwritten policy will never be triggered in this engine.");
+ }
+ }
+
+ LOGGER.exit("StateMachineHandler()<-" + internalContext.getKey().getID());
+ }
+
+ /**
+ * This constructor starts the state machines for each policy, carrying out whatever initialization executors need.
+ *
+ * @throws StateMachineException On state machine initiation errors
+ */
+ protected void start() throws StateMachineException {
+ LOGGER.entry("start()->" + key.getID());
+
+ // Iterate over the state machines
+ for (final StateMachineExecutor smExecutor : stateMachineExecutorMap.values()) {
+ try {
+ smExecutor.prepare();
+ } catch (final StateMachineException e) {
+ final String stateMachineID = smExecutor.getContext().getKey().getID();
+ LOGGER.warn("start()<-" + key.getID() + ", start failed, state machine \"" + stateMachineID + "\"", e);
+ throw new StateMachineException(
+ "start()<-" + key.getID() + ", start failed, state machine \"" + stateMachineID + "\"", e);
+ }
+ }
+
+ LOGGER.exit("start()<-" + key.getID());
+ }
+
+ /**
+ * This method is called to execute an event on the state machines in an engine.
+ *
+ * @param event The trigger event for the state machine
+ * @return The result of the state machine execution run
+ * @throws StateMachineException On execution errors in a state machine
+ */
+ protected EnEvent execute(final EnEvent event) throws StateMachineException {
+ LOGGER.entry("execute()->" + event.getName());
+
+ // Try to execute the state machine for the trigger
+ final StateMachineExecutor stateMachineExecutor = stateMachineExecutorMap.get(event.getAxEvent());
+ if (stateMachineExecutor == null) {
+ final String exceptionMessage =
+ "state machine execution not possible, policy not found for trigger event " + event.getName();
+ LOGGER.warn(exceptionMessage);
+
+ event.setExceptionMessage(exceptionMessage);
+ return event;
+ }
+
+ // Run the state machine
+ try {
+ LOGGER.debug("execute(): state machine \"{}\" execution starting . . .", stateMachineExecutor);
+ final EnEvent outputObject = stateMachineExecutor.execute(event.getExecutionID(), event);
+
+ LOGGER.debug("execute()<-: state machine \"{}\" execution completed", stateMachineExecutor);
+ return outputObject;
+ } catch (final Exception e) {
+ LOGGER.warn("execute()<-: state machine \"" + stateMachineExecutor + "\" execution failed", e);
+ throw new StateMachineException("execute()<-: execution failed on state machine " + stateMachineExecutor,
+ e);
+ }
+ }
+
+ /**
+ * Closes down the state machines of an engine.
+ */
+ protected void stop() {
+ LOGGER.entry("stop()->");
+
+ // Iterate through all state machines and clean them
+ for (final StateMachineExecutor smExecutor : stateMachineExecutorMap.values()) {
+ try {
+ smExecutor.cleanUp();
+ } catch (final StateMachineException e) {
+ final String smID = smExecutor.getContext().getKey().getID();
+ LOGGER.warn("stop()<-clean up failed, state machine \"" + smID + "\" cleanup failed", e);
+ }
+ }
+ LOGGER.exit("stop()<-");
+ }
+}
diff --git a/core/core-engine/src/main/java/org/onap/policy/apex/core/engine/engine/impl/package-info.java b/core/core-engine/src/main/java/org/onap/policy/apex/core/engine/engine/impl/package-info.java
new file mode 100644
index 000000000..ce86e2745
--- /dev/null
+++ b/core/core-engine/src/main/java/org/onap/policy/apex/core/engine/engine/impl/package-info.java
@@ -0,0 +1,27 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * Copyright (C) 2016-2018 Ericsson. All rights reserved.
+ * ================================================================================
+ * 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=========================================================
+ */
+
+/**
+ * Provides the implementation of the {@link org.onap.policy.apex.core.engine.engine.ApexEngine} interface.
+ *
+ * @author Liam Fallon (liam.fallon@ericsson.com)
+ */
+
+package org.onap.policy.apex.core.engine.engine.impl;
diff --git a/core/core-engine/src/main/java/org/onap/policy/apex/core/engine/engine/package-info.java b/core/core-engine/src/main/java/org/onap/policy/apex/core/engine/engine/package-info.java
new file mode 100644
index 000000000..5c99f917e
--- /dev/null
+++ b/core/core-engine/src/main/java/org/onap/policy/apex/core/engine/engine/package-info.java
@@ -0,0 +1,30 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * Copyright (C) 2016-2018 Ericsson. All rights reserved.
+ * ================================================================================
+ * 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=========================================================
+ */
+
+/**
+ * Defines the Apex engine Java API. The API is used to set up, control, send events to, and receive events from an APEX
+ * engine. The {@link ApexEngine} interface is used to control the execution of a single APEX engine thread and to send
+ * events to that APEX engine thread. The {@link EnEventListener} interface is used to listen for events being emitted
+ * by an APEX engine thread.
+ *
+ * @author Liam Fallon (liam.fallon@ericsson.com)
+ */
+
+package org.onap.policy.apex.core.engine.engine;
diff --git a/core/core-engine/src/main/java/org/onap/policy/apex/core/engine/event/EnEvent.java b/core/core-engine/src/main/java/org/onap/policy/apex/core/engine/event/EnEvent.java
new file mode 100644
index 000000000..b072a89d0
--- /dev/null
+++ b/core/core-engine/src/main/java/org/onap/policy/apex/core/engine/event/EnEvent.java
@@ -0,0 +1,338 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * Copyright (C) 2016-2018 Ericsson. All rights reserved.
+ * ================================================================================
+ * 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.event;
+
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.Map;
+import java.util.Random;
+import java.util.Set;
+
+import org.onap.policy.apex.core.engine.monitoring.EventMonitor;
+import org.onap.policy.apex.model.basicmodel.concepts.AxArtifactKey;
+import org.onap.policy.apex.model.basicmodel.concepts.AxConcept;
+import org.onap.policy.apex.model.basicmodel.service.ModelService;
+import org.onap.policy.apex.model.eventmodel.concepts.AxEvent;
+import org.onap.policy.apex.model.eventmodel.concepts.AxEvents;
+import org.onap.policy.apex.model.eventmodel.concepts.AxField;
+import org.slf4j.ext.XLogger;
+import org.slf4j.ext.XLoggerFactory;
+
+/**
+ * Instances of the Class EnEvent are events being passed through the Apex system. All events in the system are
+ * instances of this class.
+ *
+ * @author Liam Fallon (liam.fallon@ericsson.com)
+ */
+public class EnEvent extends HashMap<String, Object> {
+ private static final long serialVersionUID = 6311863111866294637L;
+
+ // Logger for this class
+ private static final XLogger LOGGER = XLoggerFactory.getXLogger(EnEvent.class);
+
+ // The definition of this event in the Apex model
+ private final AxEvent axEvent;
+
+ // The event monitor for this event
+ private final EventMonitor eventMonitor = new EventMonitor();
+
+ // The stack of execution of this event, used for monitoring
+ private AxConcept[] userArtifactStack;
+
+ private static Random rand = new Random(System.nanoTime());
+
+ // An identifier for the current event execution. The default value here will always be a random number, and should
+ // be reset
+ private long executionID = rand.nextLong();
+
+ // A string holding a message that indicates why processing of this event threw an exception
+ private String exceptionMessage;
+
+ /**
+ * Instantiates a new EnEvent, an Engine Event.
+ *
+ * @param eventKey the key of the event definition from the Apex model
+ */
+ public EnEvent(final AxArtifactKey eventKey) {
+ this(ModelService.getModel(AxEvents.class).get(eventKey));
+ }
+
+ /**
+ * Instantiates a new EnEvent, an Engine Event.
+ *
+ * @param axEvent the event definition from the Apex model
+ */
+ public EnEvent(final AxEvent axEvent) {
+ super();
+ // Save the event definition from the Apex model
+ this.axEvent = axEvent;
+ }
+
+ /**
+ * Gets the event definition of this event.
+ *
+ * @return the event definition
+ */
+ public AxEvent getAxEvent() {
+ return axEvent;
+ }
+
+ /**
+ * Get the name of the event.
+ *
+ * @return the event name
+ */
+ public String getName() {
+ return axEvent.getKey().getName();
+ }
+
+ /**
+ * Get the key of the event.
+ *
+ * @return the event key
+ */
+ public AxArtifactKey getKey() {
+ return axEvent.getKey();
+ }
+
+ /**
+ * Get the ID of the event.
+ *
+ * @return the event key
+ */
+ public String getID() {
+ return axEvent.getKey().getID();
+ }
+
+ /**
+ * Get the currently set value for the ExecutionID for this event. A ExecutionID in an EnEvent is used identify all
+ * EnEvents (input, internal and output events) used in a single Engine invocation. Therefore, a ExecutionID can be
+ * used to match which output event is the result of a particular input event. The default initialized value for the
+ * ExecutionID is always unique in a single JVM.
+ *
+ * @return the currently set value for the ExecutionID for this event.
+ */
+ public long getExecutionID() {
+ return executionID;
+ }
+
+ /**
+ * Set the value for the ExecutionID for this event. A ExecutionID in an EnEvent is used identify all EnEvents
+ * (input, internal and output events) used in a single Engine invocation. Therefore, a ExecutionID can be used to
+ * match which output event is the result of a particular input event. The default initialised value for the
+ * ExecutionID is always unique in a single JVM.
+ *
+ * @param executionID the new value for the ExecutionID for this event.
+ */
+ public void setExecutionID(final long executionID) {
+ this.executionID = executionID;
+ }
+
+ /**
+ * Gets the exception message explaining why processing of this event to fail.
+ *
+ * @return the exception message
+ */
+ public String getExceptionMessage() {
+ return exceptionMessage;
+ }
+
+ /**
+ * Sets the exception message explaining why processing of this event to fail.
+ *
+ * @param exceptionMessage the exception message
+ */
+ public void setExceptionMessage(final String exceptionMessage) {
+ this.exceptionMessage = exceptionMessage;
+ }
+
+ /**
+ * Store the user artifact stack of the event.
+ *
+ * @param usedArtifactStackArray the event user artifact stack
+ */
+ public void setUserArtifactStack(final AxConcept[] usedArtifactStackArray) {
+ userArtifactStack = usedArtifactStackArray;
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see java.util.Map#get(java.lang.Object)
+ */
+ @Override
+ public Object get(final Object key) {
+ if (key == null) {
+ LOGGER.warn("null values are illegal on method parameter \"key\"");
+ throw new EnException("null values are illegal on method parameter \"key\"");
+ }
+
+ // Check if this key is a parameter on our event
+ final AxField eventParameter = axEvent.getParameterMap().get(key);
+ if (eventParameter == null) {
+ LOGGER.warn("parameter with key " + key + " not defined on this event");
+ throw new EnException("parameter with key " + key + " not defined on this event");
+ }
+
+ // Get the item
+ final Object item = super.get(key);
+
+ // Get the parameter value and monitor it
+ eventMonitor.monitorGet(eventParameter, item, userArtifactStack);
+ return item;
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see java.util.Map#values()
+ */
+ @Override
+ public Collection<Object> values() {
+ // Build the key set and return it
+ final ArrayList<Object> valueList = new ArrayList<>();
+
+ // Override the generic "values()" call as we want to monitor the gets
+ for (final String key : super.keySet()) {
+ valueList.add(this.get(key));
+ }
+
+ return valueList;
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see java.util.Map#entrySet()
+ */
+ @Override
+ public Set<Map.Entry<String, Object>> entrySet() {
+ // Build the entry set and return it
+ final Set<Map.Entry<String, Object>> entrySet = new HashSet<>();
+
+ // Override the generic "entrySet()" call as we want to monitor the gets
+ for (final String key : super.keySet()) {
+ entrySet.add(new SimpleEntry<>(key, this.get(key)));
+ }
+
+ return entrySet;
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see java.util.Map#put(java.lang.Object, java.lang.Object)
+ */
+ @Override
+ public Object put(final String key, final Object incomingValue) {
+ if (key == null) {
+ LOGGER.warn("null keys are illegal on method parameter \"key\"");
+ throw new EnException("null keys are illegal on method parameter \"key\"");
+ }
+
+ // Check if this key is a parameter on our event
+ final AxField eventParameter = axEvent.getParameterMap().get(key);
+ if (eventParameter == null) {
+ LOGGER.warn("parameter with key \"" + key + "\" not defined on event \"" + getName() + "\"");
+ throw new EnException("parameter with key \"" + key + "\" not defined on event \"" + getName() + "\"");
+ }
+
+ // We allow null values
+ if (incomingValue == null) {
+ eventMonitor.monitorSet(eventParameter, incomingValue, userArtifactStack);
+ return super.put(key, incomingValue);
+ }
+
+ // Holder for the object to assign
+ final Object valueToAssign = new EnField(eventParameter, incomingValue).getAssignableValue();
+
+ // Update the value in the parameter map
+ eventMonitor.monitorSet(eventParameter, valueToAssign, userArtifactStack);
+ return super.put(key, valueToAssign);
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see java.util.Map#putAll(java.util.Map)
+ */
+ @Override
+ public void putAll(final Map<? extends String, ? extends Object> incomingMap) {
+ // Override the generic "putAll()" call as we want to monitor the puts
+ for (final java.util.Map.Entry<? extends String, ? extends Object> incomingEntry : incomingMap.entrySet()) {
+ put(incomingEntry.getKey(), incomingEntry.getValue());
+ }
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see java.util.Map#remove(java.lang.Object)
+ */
+ @Override
+ public Object remove(final Object key) {
+ if (key == null) {
+ LOGGER.warn("null keys are illegal on method parameter \"key\"");
+ throw new EnException("null keys are illegal on method parameter \"key\"");
+ }
+
+ // Check if this key is a parameter on our event
+ final AxField eventParameter = axEvent.getParameterMap().get(key);
+ if (eventParameter == null) {
+ LOGGER.warn("parameter with key " + key + " not defined on this event");
+ throw new EnException("parameter with key " + key + " not defined on this event");
+ }
+
+ final Object removedValue = super.remove(key);
+ eventMonitor.monitorRemove(eventParameter, removedValue, userArtifactStack);
+ return removedValue;
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see java.util.Map#clear()
+ */
+ @Override
+ public void clear() {
+ // Override the generic "clear()" call as we want to monitor removals
+ final Set<String> deleteSet = new HashSet<>();
+ deleteSet.addAll(keySet());
+
+ for (final String deleteKey : deleteSet) {
+ this.remove(deleteKey);
+ }
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see java.util.AbstractMap#toString()
+ */
+ @Override
+ public String toString() {
+ return "EnEvent [axEvent=" + axEvent + ", userArtifactStack=" + Arrays.toString(userArtifactStack) + ", map="
+ + super.toString() + "]";
+ }
+}
diff --git a/core/core-engine/src/main/java/org/onap/policy/apex/core/engine/event/EnException.java b/core/core-engine/src/main/java/org/onap/policy/apex/core/engine/event/EnException.java
new file mode 100644
index 000000000..79a65cba4
--- /dev/null
+++ b/core/core-engine/src/main/java/org/onap/policy/apex/core/engine/event/EnException.java
@@ -0,0 +1,51 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * Copyright (C) 2016-2018 Ericsson. All rights reserved.
+ * ================================================================================
+ * 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.event;
+
+import org.onap.policy.apex.model.basicmodel.concepts.ApexRuntimeException;
+
+/**
+ * This class will be called if an error occurs in Apex event handling.
+ *
+ * @author Liam Fallon
+ */
+public class EnException extends ApexRuntimeException {
+ private static final long serialVersionUID = -8507246953751956974L;
+
+ /**
+ * Instantiates a new engine event exception.
+ *
+ * @param message the message
+ */
+ public EnException(final String message) {
+ super(message);
+ }
+
+ /**
+ * Instantiates a new engine event exception.
+ *
+ * @param message the message
+ * @param e the e
+ */
+ public EnException(final String message, final Exception e) {
+ super(message, e);
+ }
+}
diff --git a/core/core-engine/src/main/java/org/onap/policy/apex/core/engine/event/EnField.java b/core/core-engine/src/main/java/org/onap/policy/apex/core/engine/event/EnField.java
new file mode 100644
index 000000000..5f12e8764
--- /dev/null
+++ b/core/core-engine/src/main/java/org/onap/policy/apex/core/engine/event/EnField.java
@@ -0,0 +1,153 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * Copyright (C) 2016-2018 Ericsson. All rights reserved.
+ * ================================================================================
+ * 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.event;
+
+import java.io.Serializable;
+
+import org.onap.policy.apex.context.ContextRuntimeException;
+import org.onap.policy.apex.context.SchemaHelper;
+import org.onap.policy.apex.context.impl.schema.SchemaHelperFactory;
+import org.onap.policy.apex.model.basicmodel.concepts.AxReferenceKey;
+import org.onap.policy.apex.model.eventmodel.concepts.AxField;
+import org.slf4j.ext.XLogger;
+import org.slf4j.ext.XLoggerFactory;
+
+/**
+ * Instances of the Class EnField are event fields being passed through the Apex system.
+ *
+ * @author Liam Fallon (liam.fallon@ericsson.com)
+ */
+public class EnField implements Serializable {
+ private static final long serialVersionUID = -5713525780081840333L;
+
+ // Logger for this class
+ private static final XLogger LOGGER = XLoggerFactory.getXLogger(EnField.class);
+
+ // The definition of this field in the Apex model
+ private final AxField axField;
+
+ // The schema helper for this field
+ private SchemaHelper schemaHelper;
+
+ // The value of this field
+ private final Object value;
+
+ /**
+ * Instantiates a new EnField, an Engine Field.
+ *
+ * @param axField the field definition from the Apex model
+ * @param value the value
+ */
+ public EnField(final AxField axField, final Object value) {
+ // Save the field definition from the Apex model
+ this.axField = axField;
+ this.value = value;
+
+ // Get a schema helper to handle translations of fields to and from the schema
+ try {
+ schemaHelper = new SchemaHelperFactory().createSchemaHelper(axField.getKey(), axField.getSchema());
+ } catch (final ContextRuntimeException e) {
+ final String message = "schema helper cannot be created for parameter with key \"" + axField.getID()
+ + "\" with schema \"" + axField.getSchema() + "\"";
+ LOGGER.warn(message, e);
+ throw new EnException(message, e);
+ }
+ }
+
+ /**
+ * Gets the field definition of this field.
+ *
+ * @return the field definition
+ */
+ public AxField getAxField() {
+ return axField;
+ }
+
+ /**
+ * Gets the schema helper of this field.
+ *
+ * @return the schema helper for this field
+ */
+ public SchemaHelper getSchemaHelper() {
+ return schemaHelper;
+ }
+
+ /**
+ * Get the name of the field.
+ *
+ * @return the field name
+ */
+ public String getName() {
+ return axField.getKey().getLocalName();
+ }
+
+ /**
+ * Get the key of the field.
+ *
+ * @return the field key
+ */
+ public AxReferenceKey getKey() {
+ return axField.getKey();
+ }
+
+ /**
+ * Get the value of the field.
+ *
+ * @return the value
+ */
+ public Object getValue() {
+ return value;
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see java.lang.Object#toString()
+ */
+ @Override
+ public String toString() {
+ return "EnField [axField=" + axField + ", value=" + value + "]";
+ }
+
+ /**
+ * Get an assignable object that will work with the field.
+ *
+ * @return the assignable value
+ */
+ public Object getAssignableValue() {
+ // Use the schema helper to get the translated value of the object
+ return schemaHelper.unmarshal(value);
+ }
+
+ /**
+ * Is the value object assignable to this field.
+ *
+ * @return true if the value is assignable
+ */
+ public boolean isAssignableValue() {
+ try {
+ schemaHelper.unmarshal(value);
+ return true;
+ } catch (final Exception e) {
+ return false;
+ }
+ }
+}
diff --git a/core/core-engine/src/main/java/org/onap/policy/apex/core/engine/event/package-info.java b/core/core-engine/src/main/java/org/onap/policy/apex/core/engine/event/package-info.java
new file mode 100644
index 000000000..e94362a75
--- /dev/null
+++ b/core/core-engine/src/main/java/org/onap/policy/apex/core/engine/event/package-info.java
@@ -0,0 +1,28 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * Copyright (C) 2016-2018 Ericsson. All rights reserved.
+ * ================================================================================
+ * 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=========================================================
+ */
+
+/**
+ * Provides the event handling classes that an APEX engine uses and which uses use to send and receive events to and
+ * from an APEX engine.
+ *
+ * @author Liam Fallon (liam.fallon@ericsson.com)
+ */
+
+package org.onap.policy.apex.core.engine.event;
diff --git a/core/core-engine/src/main/java/org/onap/policy/apex/core/engine/executor/Executor.java b/core/core-engine/src/main/java/org/onap/policy/apex/core/engine/executor/Executor.java
new file mode 100644
index 000000000..d659002b2
--- /dev/null
+++ b/core/core-engine/src/main/java/org/onap/policy/apex/core/engine/executor/Executor.java
@@ -0,0 +1,161 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * Copyright (C) 2016-2018 Ericsson. All rights reserved.
+ * ================================================================================
+ * 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;
+
+import org.onap.policy.apex.context.ContextException;
+import org.onap.policy.apex.core.engine.ExecutorParameters;
+import org.onap.policy.apex.core.engine.executor.exception.StateMachineException;
+import org.onap.policy.apex.model.basicmodel.concepts.AxConcept;
+
+/**
+ * This interface defines what operations must be provided by an executing entity in Apex. It is implemented by classes
+ * that execute logic in a state machine. Each executor has an incoming entity {@code IN} that triggers execution, an
+ * outgoing entity {@code OUT} that is produced by execution, a subject {@code SUBJECT} that is being executed, and a
+ * context {@code CONTEXT} in which execution is being carried out. An executor can be part of a chain of executors and
+ * the {@code setNext} method is used to set the next executor to be executed after this executor has completed.
+ *
+ * @author Sven van der Meer (sven.van.der.meer@ericsson.com)
+ * @author Liam Fallon (liam.fallon@ericsson.com)
+ *
+ * @param <IN> type of the incoming entity
+ * @param <OUT> type of the outgoing entity
+ * @param <SUBJECT> type that is the subject of execution
+ * @param <CONTEXT> context holding the context of execution
+ */
+
+public interface Executor<IN, OUT, SUBJECT, CONTEXT> {
+ /**
+ * Save the subject and context of the executor.
+ *
+ * @param parent the parent executor of this executor or null if this executor is the top executor
+ * @param executorSubject the executor subject, the subject of execution
+ * @param executorContext the executor context, the context in which execution takes place
+ */
+ void setContext(Executor<?, ?, ?, ?> parent, SUBJECT executorSubject, CONTEXT executorContext);
+
+ /**
+ * Prepares the processing.
+ *
+ * @throws StateMachineException thrown when a state machine execution error occurs
+ */
+ void prepare() throws StateMachineException;
+
+ /**
+ * Executes the executor, running through its context in its natural order.
+ *
+ * @param executionID the execution ID of the current APEX execution policy thread
+ * @param incomingEntity the incoming entity that triggers execution
+ * @return The outgoing entity that is the result of execution
+ * @throws StateMachineException on an execution error
+ * @throws ContextException on context errors
+ */
+ OUT execute(long executionID, IN incomingEntity) throws StateMachineException, ContextException;
+
+ /**
+ * Carry out the preparatory work for execution.
+ *
+ * @param executionID the execution ID of the current APEX execution policy thread
+ * @param incomingEntity the incoming entity that triggers execution
+ * @throws StateMachineException on an execution error
+ * @throws ContextException on context errors
+ */
+ void executePre(long executionID, IN incomingEntity) throws StateMachineException, ContextException;
+
+ /**
+ * Carry out the post work for execution, the returning entity should be set by the child execution object.
+ *
+ * @param returnValue the return value indicates whether the execution was successful and, if it failed, how it
+ * failed
+ * @throws StateMachineException on an execution error
+ * @throws ContextException On context errors
+ */
+ void executePost(boolean returnValue) throws StateMachineException, ContextException;
+
+ /**
+ * Cleans up after processing.
+ *
+ * @throws StateMachineException thrown when a state machine execution error occurs
+ */
+ void cleanUp() throws StateMachineException;
+
+ /**
+ * Get the key associated with the executor.
+ *
+ * @return The key associated with the executor
+ */
+ AxConcept getKey();
+
+ /**
+ * Get the parent executor of the executor.
+ *
+ * @return The parent executor of this executor
+ */
+ Executor<?, ?, ?, ?> getParent();
+
+ /**
+ * Get the subject of the executor.
+ *
+ * @return The subject for the executor
+ */
+ SUBJECT getSubject();
+
+ /**
+ * Get the context of the executor.
+ *
+ * @return The context for the executor
+ */
+ CONTEXT getContext();
+
+ /**
+ * Get the incoming object of the executor.
+ *
+ * @return The incoming object for the executor
+ */
+ IN getIncoming();
+
+ /**
+ * Get the outgoing object of the executor.
+ *
+ * @return The outgoing object for the executor
+ */
+ OUT getOutgoing();
+
+ /**
+ * Save the next executor for this executor.
+ *
+ * @param nextExecutor the next executor
+ */
+ void setNext(Executor<IN, OUT, SUBJECT, CONTEXT> nextExecutor);
+
+ /**
+ * Get the next executor to be run after this executor completes its execution.
+ *
+ * @return The next executor
+ */
+ Executor<IN, OUT, SUBJECT, CONTEXT> getNext();
+
+ /**
+ * Set parameters for this executor, overloaded by executors that use parameters.
+ *
+ * @param parameters executor parameters
+ */
+ void setParameters(ExecutorParameters parameters);
+}
diff --git a/core/core-engine/src/main/java/org/onap/policy/apex/core/engine/executor/ExecutorFactory.java b/core/core-engine/src/main/java/org/onap/policy/apex/core/engine/executor/ExecutorFactory.java
new file mode 100644
index 000000000..1bb0b0578
--- /dev/null
+++ b/core/core-engine/src/main/java/org/onap/policy/apex/core/engine/executor/ExecutorFactory.java
@@ -0,0 +1,67 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * Copyright (C) 2016-2018 Ericsson. All rights reserved.
+ * ================================================================================
+ * 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;
+
+import org.onap.policy.apex.core.engine.context.ApexInternalContext;
+import org.onap.policy.apex.model.policymodel.concepts.AxState;
+import org.onap.policy.apex.model.policymodel.concepts.AxStateFinalizerLogic;
+import org.onap.policy.apex.model.policymodel.concepts.AxTask;
+
+/**
+ * This class is used by the state machine to get implementations of task selection and task executors.
+ *
+ * @author Liam Fallon
+ */
+
+public abstract class ExecutorFactory {
+ /**
+ * Get an executor for task selection logic.
+ *
+ * @param stateExecutor the state executor that is requesting the task selection executor
+ * @param state the state containing the task selection logic
+ * @param context the context the context in which the task selection logic will execute
+ * @return The executor that will run the task selection logic
+ */
+ public abstract TaskSelectExecutor getTaskSelectionExecutor(Executor<?, ?, ?, ?> stateExecutor, AxState state,
+ ApexInternalContext context);
+
+ /**
+ * Get an executor for task logic.
+ *
+ * @param stateExecutor the state executor that is requesting the task executor
+ * @param task the task containing the task logic
+ * @param context the context the context in which the task logic will execute
+ * @return The executor that will run the task logic
+ */
+ public abstract TaskExecutor getTaskExecutor(Executor<?, ?, ?, ?> stateExecutor, AxTask task,
+ ApexInternalContext context);
+
+ /**
+ * Get an executor for state finalizer logic.
+ *
+ * @param stateExecutor the state executor that is requesting the state finalizer executor
+ * @param logic the state finalizer logic to execute
+ * @param context the context the context in which the state finalizer logic will execute
+ * @return The executor that will run the state finalizer logic
+ */
+ public abstract StateFinalizerExecutor getStateFinalizerExecutor(Executor<?, ?, ?, ?> stateExecutor,
+ AxStateFinalizerLogic logic, ApexInternalContext context);
+}
diff --git a/core/core-engine/src/main/java/org/onap/policy/apex/core/engine/executor/StateExecutor.java b/core/core-engine/src/main/java/org/onap/policy/apex/core/engine/executor/StateExecutor.java
new file mode 100644
index 000000000..ab5b66969
--- /dev/null
+++ b/core/core-engine/src/main/java/org/onap/policy/apex/core/engine/executor/StateExecutor.java
@@ -0,0 +1,381 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * Copyright (C) 2016-2018 Ericsson. All rights reserved.
+ * ================================================================================
+ * 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;
+
+import java.util.HashMap;
+import java.util.Map;
+import java.util.Map.Entry;
+import java.util.TreeMap;
+
+import org.onap.policy.apex.context.ContextException;
+import org.onap.policy.apex.core.engine.ExecutorParameters;
+import org.onap.policy.apex.core.engine.context.ApexInternalContext;
+import org.onap.policy.apex.core.engine.event.EnEvent;
+import org.onap.policy.apex.core.engine.executor.exception.StateMachineException;
+import org.onap.policy.apex.core.engine.executor.exception.StateMachineRuntimeException;
+import org.onap.policy.apex.model.basicmodel.concepts.AxArtifactKey;
+import org.onap.policy.apex.model.basicmodel.concepts.AxReferenceKey;
+import org.onap.policy.apex.model.basicmodel.service.ModelService;
+import org.onap.policy.apex.model.policymodel.concepts.AxState;
+import org.onap.policy.apex.model.policymodel.concepts.AxStateFinalizerLogic;
+import org.onap.policy.apex.model.policymodel.concepts.AxStateOutput;
+import org.onap.policy.apex.model.policymodel.concepts.AxStateTaskOutputType;
+import org.onap.policy.apex.model.policymodel.concepts.AxStateTaskReference;
+import org.onap.policy.apex.model.policymodel.concepts.AxTask;
+import org.onap.policy.apex.model.policymodel.concepts.AxTasks;
+import org.slf4j.ext.XLogger;
+import org.slf4j.ext.XLoggerFactory;
+
+/**
+ * This class is the executor for a state of a policy.
+ *
+ * @author Sven van der Meer (sven.van.der.meer@ericsson.com)
+ * @author Liam Fallon (liam.fallon@ericsson.com)
+ */
+public class StateExecutor implements Executor<EnEvent, StateOutput, AxState, ApexInternalContext> {
+ // Logger for this class
+ private static final XLogger LOGGER = XLoggerFactory.getXLogger(StateExecutor.class);
+
+ // Hold the state and context definitions for this state
+ private AxState axState = null;
+ private Executor<?, ?, ?, ?> parent = null;
+ private ApexInternalContext context = null;
+
+ // Holds the incoming event and the state output for this state
+ private EnEvent lastIncomingEvent = null;
+ private StateOutput lastStateOutput = null;
+
+ // The task selection logic executor
+ private TaskSelectExecutor taskSelectExecutor = null;
+
+ // The map of task executors for this state
+ private final Map<AxArtifactKey, TaskExecutor> taskExecutorMap = new HashMap<>();
+
+ // The map of state outputs used directly by tasks
+ private final Map<AxArtifactKey, String> directStateOutputMap = new HashMap<>();
+
+ // The map of state finalizer logic executors used by tasks
+ private final Map<AxArtifactKey, StateFinalizerExecutor> task2StateFinalizerMap = new HashMap<>();
+
+ // The next state executor
+ private Executor<EnEvent, StateOutput, AxState, ApexInternalContext> nextExecutor = null;
+
+ // The executor factory
+ private ExecutorFactory executorFactory = null;
+
+ /**
+ * Constructor, save the executor factory.
+ *
+ * @param executorFactory the executor factory to use for getting executors for task selection logic
+ */
+ public StateExecutor(final ExecutorFactory executorFactory) {
+ this.executorFactory = executorFactory;
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see
+ * org.onap.policy.apex.core.engine.executor.Executor#setContext(org.onap.policy.apex.core.engine.executor.Executor,
+ * java.lang.Object, java.lang.Object)
+ */
+ @Override
+ public void setContext(final Executor<?, ?, ?, ?> incomingParent, final AxState incomingAxState,
+ final ApexInternalContext incomingContext) {
+ // Save the state and context definition
+ this.parent = incomingParent;
+ this.axState = incomingAxState;
+ this.context = incomingContext;
+
+ // Set the task selection executor
+ taskSelectExecutor = executorFactory.getTaskSelectionExecutor(this, axState, context);
+
+ // Set a task executor for each task
+ for (final Entry<AxArtifactKey, AxStateTaskReference> stateTaskReferenceEntry : axState.getTaskReferences()
+ .entrySet()) {
+ final AxArtifactKey taskKey = stateTaskReferenceEntry.getKey();
+ final AxStateTaskReference taskReference = stateTaskReferenceEntry.getValue();
+
+ // Get the task
+ final AxTask task = ModelService.getModel(AxTasks.class).get(taskKey);
+
+ // Create a task executor for the task
+ taskExecutorMap.put(taskKey, executorFactory.getTaskExecutor(this, task, context));
+
+ // Check what type of output is specified for the task on this sate
+ if (taskReference.getStateTaskOutputType().equals(AxStateTaskOutputType.DIRECT)) {
+ // Create a task state output reference for this task
+ directStateOutputMap.put(taskKey, taskReference.getOutput().getLocalName());
+ } else if (taskReference.getStateTaskOutputType().equals(AxStateTaskOutputType.LOGIC)) {
+ // Get the state finalizer logic for this task
+ final AxStateFinalizerLogic finalizerLogic =
+ axState.getStateFinalizerLogicMap().get(taskReference.getOutput().getLocalName());
+ if (finalizerLogic == null) {
+ // Finalizer logic for the task does not exist
+ throw new StateMachineRuntimeException("state finalizer logic on task reference \"" + taskReference
+ + "\" on state \"" + axState.getID() + "\" does not exist");
+ }
+
+ // Create a state finalizer executor for the task
+ task2StateFinalizerMap.put(taskKey,
+ executorFactory.getStateFinalizerExecutor(this, finalizerLogic, context));
+ } else {
+ // This should never happen but.....
+ throw new StateMachineRuntimeException("invalid state output type on task reference \"" + taskReference
+ + "\" on state \"" + axState.getID() + "\"");
+ }
+ }
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.onap.policy.apex.core.engine.executor.Executor#prepare()
+ */
+ @Override
+ public void prepare() throws StateMachineException {
+ // There may be no task selection logic
+ if (taskSelectExecutor != null) {
+ // Prepare the task selector
+ taskSelectExecutor.prepare();
+ }
+
+ // Prepare the tasks
+ for (final TaskExecutor taskExecutor : taskExecutorMap.values()) {
+ taskExecutor.prepare();
+ }
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.onap.policy.apex.core.engine.executor.Executor#execute(java.lang.long, java.lang.Object)
+ */
+ @Override
+ public StateOutput execute(final long executionID, final EnEvent incomingEvent)
+ throws StateMachineException, ContextException {
+ this.lastIncomingEvent = incomingEvent;
+
+ // Check that the incoming event matches the trigger for this state
+ if (!incomingEvent.getAxEvent().getKey().equals(axState.getTrigger())) {
+ throw new StateMachineException("incoming event \"" + incomingEvent.getID() + "\" does not match trigger \""
+ + axState.getTrigger().getID() + "\" of state \"" + axState.getID() + "\"");
+ }
+
+ // The key of the task to execute
+ AxArtifactKey taskKey = null;
+
+ try {
+ // There may be no task selection logic, in which case just return the default task
+ if (taskSelectExecutor != null) {
+ // Fire the task selector to find the task to run
+ taskKey = taskSelectExecutor.execute(executionID, incomingEvent);
+ }
+
+ // If there's no task selection logic or the TSL returned no task, just use the default task
+ if (taskKey == null) {
+ taskKey = axState.getDefaultTask();
+ }
+
+ // Execute the task
+ final TreeMap<String, Object> incomingValues = new TreeMap<>();
+ incomingValues.putAll(incomingEvent);
+ final Map<String, Object> taskExecutionResultMap =
+ taskExecutorMap.get(taskKey).execute(executionID, incomingValues);
+ final AxTask task = taskExecutorMap.get(taskKey).getSubject();
+
+ // Check if this task has direct output
+ String stateOutputName = directStateOutputMap.get(taskKey);
+
+ // If a direct state output name was not found, state finalizer logic should be defined for the task
+ if (stateOutputName == null) {
+ // State finalizer logic should exist for the task
+ final StateFinalizerExecutor finalizerLogicExecutor = task2StateFinalizerMap.get(taskKey);
+ if (finalizerLogicExecutor == null) {
+ throw new StateMachineException("state finalizer logic for task \"" + taskKey.getID()
+ + "\" not found for state \"" + axState.getID() + "\"");
+ }
+
+ // Execute the state finalizer logic to select a state output and to adjust the taskExecutionResultMap
+ stateOutputName =
+ finalizerLogicExecutor.execute(incomingEvent.getExecutionID(), taskExecutionResultMap);
+ }
+
+ // Now look up the the actual state output
+ final AxStateOutput stateOutputDefinition = axState.getStateOutputs().get(stateOutputName);
+ if (stateOutputDefinition == null) {
+ throw new StateMachineException("state output definition for state output \"" + stateOutputName
+ + "\" not found for state \"" + axState.getID() + "\"");
+ }
+
+ // Create the state output and transfer all the fields across to its event
+ final StateOutput stateOutput = new StateOutput(stateOutputDefinition);
+ this.lastStateOutput = stateOutput;
+
+ stateOutput.setEventFields(task.getRawOutputFields(), taskExecutionResultMap);
+
+ // Copy across fields from the incoming event that are not set on the outgoing event
+ stateOutput.copyUnsetFields(incomingEvent);
+
+ // Set the ExecutionID for the outgoing event to the value in the incoming event.
+ if (stateOutput != null && stateOutput.getOutputEvent() != null) {
+ stateOutput.getOutputEvent().setExecutionID(incomingEvent.getExecutionID());
+ }
+
+ // That's it, the state execution is complete
+ return stateOutput;
+ } catch (final Exception e) {
+ final String errorMessage = "State execution of state \"" + axState.getID() + "\" on task \""
+ + (taskKey != null ? taskKey.getID() : "null") + "\" failed: " + e.getMessage();
+
+ LOGGER.warn(errorMessage);
+ throw new StateMachineException(errorMessage, e);
+ }
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.onap.policy.apex.core.engine.executor.Executor#executePre(java.lang.long, java.lang.Object)
+ */
+ @Override
+ public final void executePre(final long executionID, final EnEvent incomingEntity) throws StateMachineException {
+ throw new StateMachineException("execution pre work not implemented on class");
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.onap.policy.apex.core.engine.executor.Executor#executePost(boolean)
+ */
+ @Override
+ public final void executePost(final boolean returnValue) throws StateMachineException {
+ throw new StateMachineException("execution post work not implemented on class");
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.onap.policy.apex.core.engine.executor.Executor#cleanUp()
+ */
+ @Override
+ public void cleanUp() throws StateMachineException {
+ // Clean the tasks
+ for (final TaskExecutor taskExecutor : taskExecutorMap.values()) {
+ taskExecutor.cleanUp();
+ }
+
+ if (taskSelectExecutor != null) {
+ // Clean the task selector
+ taskSelectExecutor.cleanUp();
+ }
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.onap.policy.apex.core.engine.executor.Executor#getKey()
+ */
+ @Override
+ public AxReferenceKey getKey() {
+ return axState.getKey();
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.onap.policy.apex.core.engine.executor.Executor#getParent()
+ */
+ @Override
+ public Executor<?, ?, ?, ?> getParent() {
+ return parent;
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.onap.policy.apex.core.engine.executor.Executor#getSubject()
+ */
+ @Override
+ public AxState getSubject() {
+ return axState;
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.onap.policy.apex.core.engine.executor.Executor#getContext()
+ */
+ @Override
+ public final ApexInternalContext getContext() {
+ return context;
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.onap.policy.apex.core.engine.executor.Executor#getIncoming()
+ */
+ @Override
+ public final EnEvent getIncoming() {
+ return lastIncomingEvent;
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.onap.policy.apex.core.engine.executor.Executor#getOutgoing()
+ */
+ @Override
+ public final StateOutput getOutgoing() {
+ return lastStateOutput;
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see
+ * org.onap.policy.apex.core.engine.executor.Executor#setNext(org.onap.policy.apex.core.engine.executor.Executor)
+ */
+ @Override
+ public final void setNext(final Executor<EnEvent, StateOutput, AxState, ApexInternalContext> incomingNextExecutor) {
+ this.nextExecutor = incomingNextExecutor;
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.onap.policy.apex.core.engine.executor.Executor#getNext()
+ */
+ @Override
+ public final Executor<EnEvent, StateOutput, AxState, ApexInternalContext> getNext() {
+ return nextExecutor;
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.onap.policy.apex.core.engine.executor.Executor#setParameters(org.onap.policy.apex.core.engine.
+ * ExecutorParameters)
+ */
+ @Override
+ public void setParameters(final ExecutorParameters parameters) {}
+}
diff --git a/core/core-engine/src/main/java/org/onap/policy/apex/core/engine/executor/StateFinalizerExecutor.java b/core/core-engine/src/main/java/org/onap/policy/apex/core/engine/executor/StateFinalizerExecutor.java
new file mode 100644
index 000000000..17691011f
--- /dev/null
+++ b/core/core-engine/src/main/java/org/onap/policy/apex/core/engine/executor/StateFinalizerExecutor.java
@@ -0,0 +1,272 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * Copyright (C) 2016-2018 Ericsson. All rights reserved.
+ * ================================================================================
+ * 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;
+
+import static org.onap.policy.apex.model.utilities.Assertions.argumentNotNull;
+
+import java.util.Map;
+
+import org.onap.policy.apex.context.ContextException;
+import org.onap.policy.apex.core.engine.ExecutorParameters;
+import org.onap.policy.apex.core.engine.context.ApexInternalContext;
+import org.onap.policy.apex.core.engine.executor.context.StateFinalizerExecutionContext;
+import org.onap.policy.apex.core.engine.executor.exception.StateMachineException;
+import org.onap.policy.apex.model.basicmodel.concepts.AxReferenceKey;
+import org.onap.policy.apex.model.policymodel.concepts.AxState;
+import org.onap.policy.apex.model.policymodel.concepts.AxStateFinalizerLogic;
+import org.slf4j.ext.XLogger;
+import org.slf4j.ext.XLoggerFactory;
+
+/**
+ * This abstract class executes state finalizer logic in a state of an Apex policy and is specialized by classes that
+ * implement execution of state finalizer logic.
+ *
+ * @author Sven van der Meer (sven.van.der.meer@ericsson.com)
+ * @author Liam Fallon (liam.fallon@ericsson.com)
+ */
+public abstract class StateFinalizerExecutor
+ implements Executor<Map<String, Object>, String, AxStateFinalizerLogic, ApexInternalContext> {
+ // Logger for this class
+ private static final XLogger LOGGER = XLoggerFactory.getXLogger(StateFinalizerExecutor.class);
+
+ // Hold the state and context definitions
+ private Executor<?, ?, ?, ?> parent = null;
+ private AxState axState = null;
+ private AxStateFinalizerLogic finalizerLogic = null;
+ private ApexInternalContext internalContext = null;
+
+ // Holds the incoming and outgoing fields
+ private Map<String, Object> incomingFields = null;
+
+ // The next state finalizer executor
+ private Executor<Map<String, Object>, String, AxStateFinalizerLogic, ApexInternalContext> nextExecutor = null;
+
+ // The execution context; contains the facades for events and context to be used by tasks executed by this task
+ // executor
+ private StateFinalizerExecutionContext executionContext = null;
+
+ /**
+ * Gets the execution internalContext.
+ *
+ * @return the execution context
+ */
+ protected StateFinalizerExecutionContext getExecutionContext() {
+ return executionContext;
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see
+ * org.onap.policy.apex.core.engine.executor.Executor#setContext(org.onap.policy.apex.core.engine.executor.Executor,
+ * java.lang.Object, java.lang.Object)
+ */
+ @Override
+ public void setContext(final Executor<?, ?, ?, ?> incomingParent,
+ final AxStateFinalizerLogic incomingFinalizerLogic, final ApexInternalContext incomingInternalContext) {
+ this.parent = incomingParent;
+ axState = (AxState) parent.getSubject();
+ this.finalizerLogic = incomingFinalizerLogic;
+ this.internalContext = incomingInternalContext;
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.onap.policy.apex.core.engine.executor.Executor#prepare()
+ */
+ @Override
+ public void prepare() throws StateMachineException {
+ LOGGER.debug("prepare:" + finalizerLogic.getID() + "," + finalizerLogic.getLogicFlavour() + ","
+ + finalizerLogic.getLogic());
+ argumentNotNull(finalizerLogic.getLogic(), StateMachineException.class, "task logic cannot be null.");
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.onap.policy.apex.core.engine.executor.Executor#execute(java.lang.long, java.lang.Object)
+ */
+ @Override
+ public String execute(final long executionID, final Map<String, Object> newIncomingFields)
+ throws StateMachineException, ContextException {
+ throw new StateMachineException(
+ "execute() not implemented on abstract StateFinalizerExecutionContext class, only on its subclasses");
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.onap.policy.apex.core.engine.executor.Executor#executePre(java.lang.long, java.lang.Object)
+ */
+ @Override
+ public final void executePre(final long executionID, final Map<String, Object> newIncomingFields)
+ throws StateMachineException, ContextException {
+ LOGGER.debug("execute-pre:" + finalizerLogic.getLogicFlavour() + "," + getSubject().getID() + ","
+ + finalizerLogic.getLogic());
+
+ // Record the incoming fields
+ this.incomingFields = newIncomingFields;
+
+ // Get state finalizer context object
+ executionContext = new StateFinalizerExecutionContext(this, executionID, axState, getIncoming(),
+ axState.getStateOutputs().keySet(), getContext());
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.onap.policy.apex.core.engine.executor.Executor#executePost(boolean)
+ */
+ @Override
+ public final void executePost(final boolean returnValue) throws StateMachineException, ContextException {
+ if (!returnValue) {
+ String errorMessage = "execute-post: state finalizer logic execution failure on state \"" + axState.getID()
+ + "\" on finalizer logic " + finalizerLogic.getID();
+ if (executionContext.getMessage() != null) {
+ errorMessage += ", user message: " + executionContext.getMessage();
+ }
+ LOGGER.warn(errorMessage);
+ throw new StateMachineException(errorMessage);
+ }
+
+ // Check a state output has been selected
+ if (getOutgoing() == null) {
+ LOGGER.warn("execute-post: state finalizer logic \"" + finalizerLogic.getID()
+ + "\" did not select an output state");
+ throw new StateMachineException("execute-post: state finalizer logic \"" + finalizerLogic.getID()
+ + "\" did not select an output state");
+ }
+
+ if (!axState.getStateOutputs().keySet().contains(getOutgoing())) {
+ LOGGER.warn(
+ "execute-post: state finalizer logic \"" + finalizerLogic.getID() + "\" selected output state \""
+ + getOutgoing() + "\" that does not exsist on state \"" + axState.getID() + "\"");
+ throw new StateMachineException(
+ "execute-post: state finalizer logic \"" + finalizerLogic.getID() + "\" selected output state \""
+ + getOutgoing() + "\" that does not exsist on state \"" + axState.getID() + "\"");
+ }
+
+ LOGGER.debug("execute-post:" + finalizerLogic.getID() + ", returning state output \"" + getOutgoing()
+ + " and fields " + incomingFields);
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.onap.policy.apex.core.engine.executor.Executor#cleanUp()
+ */
+ @Override
+ public void cleanUp() throws StateMachineException {
+ throw new StateMachineException("cleanUp() not implemented on class");
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.onap.policy.apex.core.engine.executor.Executor#getKey()
+ */
+ @Override
+ public AxReferenceKey getKey() {
+ return finalizerLogic.getKey();
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.onap.policy.apex.core.engine.executor.Executor#getParent()
+ */
+ @Override
+ public Executor<?, ?, ?, ?> getParent() {
+ return parent;
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.onap.policy.apex.core.engine.executor.Executor#getSubject()
+ */
+ @Override
+ public AxStateFinalizerLogic getSubject() {
+ return finalizerLogic;
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.onap.policy.apex.core.engine.executor.Executor#getContext()
+ */
+ @Override
+ public ApexInternalContext getContext() {
+ return internalContext;
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.onap.policy.apex.core.engine.executor.Executor#getIncoming()
+ */
+ @Override
+ public Map<String, Object> getIncoming() {
+ return incomingFields;
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.onap.policy.apex.core.engine.executor.Executor#getOutgoing()
+ */
+ @Override
+ public String getOutgoing() {
+ return executionContext.getSelectedStateOutputName();
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see
+ * org.onap.policy.apex.core.engine.executor.Executor#setNext(org.onap.policy.apex.core.engine.executor.Executor)
+ */
+ @Override
+ public void setNext(
+ final Executor<Map<String, Object>, String, AxStateFinalizerLogic, ApexInternalContext> incomingNextExecutor) {
+ this.nextExecutor = incomingNextExecutor;
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.onap.policy.apex.core.engine.executor.Executor#getNext()
+ */
+ @Override
+ public Executor<Map<String, Object>, String, AxStateFinalizerLogic, ApexInternalContext> getNext() {
+ return nextExecutor;
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.onap.policy.apex.core.engine.executor.Executor#setParameters(org.onap.policy.apex.core.engine.
+ * ExecutorParameters)
+ */
+ @Override
+ public void setParameters(final ExecutorParameters parameters) {}
+}
diff --git a/core/core-engine/src/main/java/org/onap/policy/apex/core/engine/executor/StateMachineExecutor.java b/core/core-engine/src/main/java/org/onap/policy/apex/core/engine/executor/StateMachineExecutor.java
new file mode 100644
index 000000000..05e1b3b4b
--- /dev/null
+++ b/core/core-engine/src/main/java/org/onap/policy/apex/core/engine/executor/StateMachineExecutor.java
@@ -0,0 +1,290 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * Copyright (C) 2016-2018 Ericsson. All rights reserved.
+ * ================================================================================
+ * 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;
+
+import java.util.Map;
+import java.util.TreeMap;
+
+import org.onap.policy.apex.context.ContextException;
+import org.onap.policy.apex.core.engine.ExecutorParameters;
+import org.onap.policy.apex.core.engine.context.ApexInternalContext;
+import org.onap.policy.apex.core.engine.event.EnEvent;
+import org.onap.policy.apex.core.engine.executor.exception.StateMachineException;
+import org.onap.policy.apex.model.basicmodel.concepts.AxArtifactKey;
+import org.onap.policy.apex.model.basicmodel.concepts.AxReferenceKey;
+import org.onap.policy.apex.model.policymodel.concepts.AxPolicy;
+import org.onap.policy.apex.model.policymodel.concepts.AxState;
+import org.onap.policy.apex.model.policymodel.concepts.AxStateOutput;
+
+/**
+ * This class is the executor for a state machine built from a policy.
+ *
+ * @author Sven van der Meer (sven.van.der.meer@ericsson.com)
+ * @author Liam Fallon (liam.fallon@ericsson.com)
+ */
+public class StateMachineExecutor implements Executor<EnEvent, EnEvent, AxPolicy, ApexInternalContext> {
+ // The Apex Policy and context for this state machine
+ private AxPolicy axPolicy = null;
+ private Executor<?, ?, ?, ?> parent = null;
+ private ApexInternalContext internalContext = null;
+
+ // The list of state executors for this state machine
+ private final Map<AxReferenceKey, StateExecutor> stateExecutorMap = new TreeMap<>();
+
+ // The first executor
+ private StateExecutor firstExecutor = null;
+
+ // The next state machine executor
+ private Executor<EnEvent, EnEvent, AxPolicy, ApexInternalContext> nextExecutor = null;
+
+ // The executor factory
+ private ExecutorFactory executorFactory = null;
+
+ /**
+ * Constructor, save the executor factory that will give us executors for task selection logic and task logic.
+ *
+ * @param executorFactory the executor factory
+ * @param owner the artifact key of the owner of this state machine
+ */
+ public StateMachineExecutor(final ExecutorFactory executorFactory, final AxArtifactKey owner) {
+ this.executorFactory = executorFactory;
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see
+ * org.onap.policy.apex.core.engine.executor.Executor#setContext(org.onap.policy.apex.core.engine.executor.Executor,
+ * java.lang.Object, java.lang.Object)
+ */
+ @Override
+ public void setContext(final Executor<?, ?, ?, ?> newParent, final AxPolicy newAxPolicy,
+ final ApexInternalContext newInternalContext) {
+ // Save the policy and context for this state machine
+ this.parent = newParent;
+ this.axPolicy = newAxPolicy;
+ this.internalContext = newInternalContext;
+
+ // Clear the first executor, setContext can be called multiple times
+ firstExecutor = null;
+
+ // Create the state executors for this state machine
+ StateExecutor lastExecutor = null;
+ for (final AxState state : axPolicy.getStateMap().values()) {
+ // Create a state executor for this state and add its context (the state)
+ final StateExecutor stateExecutor = new StateExecutor(executorFactory);
+ stateExecutor.setContext(this, state, internalContext);
+
+ // Update the next executor on the last executor
+ if (lastExecutor != null) {
+ lastExecutor.setNext(stateExecutor);
+ }
+ lastExecutor = stateExecutor;
+
+ // Add the state executor to the executor list
+ stateExecutorMap.put(state.getKey(), stateExecutor);
+
+ // Set the first executor if it is not set
+ if (state.getKey().getLocalName().equals(axPolicy.getFirstState())) {
+ firstExecutor = stateExecutor;
+ }
+ }
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.onap.policy.apex.core.engine.executor.Executor#prepare()
+ */
+ @Override
+ public void prepare() throws StateMachineException {
+ for (final StateExecutor stateExecutor : stateExecutorMap.values()) {
+ stateExecutor.prepare();
+ }
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.onap.policy.apex.core.engine.executor.Executor#executeDirected(java.lang.long, java.lang.Object)
+ */
+ @Override
+ public EnEvent execute(final long executionID, final EnEvent incomingEvent)
+ throws StateMachineException, ContextException {
+ // Check if there are any states on the state machine
+ if (stateExecutorMap.size() == 0) {
+ throw new StateMachineException("no states defined on state machine");
+ }
+
+ // Check if the first state of the machine is defined
+ if (firstExecutor == null) {
+ throw new StateMachineException("first state not defined on state machine");
+ }
+
+ // Get the first state of the state machine and define a state output that starts state execution
+ StateExecutor stateExecutor = firstExecutor;
+ StateOutput stateOutput = new StateOutput(new AxStateOutput(firstExecutor.getSubject().getKey(),
+ incomingEvent.getKey(), firstExecutor.getSubject().getKey()), incomingEvent);
+ while (true) {
+ // Execute the state
+ stateOutput = stateExecutor.execute(executionID, stateOutput.getOutputEvent());
+ if (stateOutput == null) {
+ throw new StateMachineException("state execution failed, invalid state output returned");
+ }
+
+ // Use the next state of the state output to find if all the states have executed
+ if (stateOutput.getNextState().equals(AxReferenceKey.getNullKey())) {
+ break;
+ }
+
+ // Use the next state of the state output to find the next state
+ stateExecutor = stateExecutorMap.get(stateOutput.getNextState());
+ if (stateExecutor == null) {
+ throw new StateMachineException(
+ "state execution failed, next state \"" + stateOutput.getNextState().getID() + "\" not found");
+ }
+ }
+
+ return stateOutput.getOutputEvent();
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.onap.policy.apex.core.engine.executor.Executor#executePre(java.lang.long, java.lang.Object)
+ */
+ @Override
+ public final void executePre(final long executionID, final EnEvent incomingEntity) throws StateMachineException {
+ throw new StateMachineException("execution pre work not implemented on class");
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.onap.policy.apex.core.engine.executor.Executor#executePost(boolean)
+ */
+ @Override
+ public final void executePost(final boolean returnValue) throws StateMachineException {
+ throw new StateMachineException("execution post work not implemented on class");
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.onap.policy.apex.core.engine.executor.Executor#cleanUp()
+ */
+ @Override
+ public void cleanUp() throws StateMachineException {
+ for (final StateExecutor stateExecutor : stateExecutorMap.values()) {
+ stateExecutor.cleanUp();
+ }
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.onap.policy.apex.core.engine.executor.Executor#getKey()
+ */
+ @Override
+ public AxArtifactKey getKey() {
+ return axPolicy.getKey();
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.onap.policy.apex.core.engine.executor.Executor#getParent()
+ */
+ @Override
+ public final Executor<?, ?, ?, ?> getParent() {
+ return parent;
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.onap.policy.apex.core.engine.executor.Executor#getSubject()
+ */
+ @Override
+ public final AxPolicy getSubject() {
+ return axPolicy;
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.onap.policy.apex.core.engine.executor.Executor#getContext()
+ */
+ @Override
+ public final ApexInternalContext getContext() {
+ return internalContext;
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.onap.policy.apex.core.engine.executor.Executor#getIncoming()
+ */
+ @Override
+ public final EnEvent getIncoming() {
+ return null;
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.onap.policy.apex.core.engine.executor.Executor#getOutgoing()
+ */
+ @Override
+ public final EnEvent getOutgoing() {
+ return null;
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see
+ * org.onap.policy.apex.core.engine.executor.Executor#setNext(org.onap.policy.apex.core.engine.executor.Executor)
+ */
+ @Override
+ public final void setNext(final Executor<EnEvent, EnEvent, AxPolicy, ApexInternalContext> newNextExecutor) {
+ this.nextExecutor = newNextExecutor;
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.onap.policy.apex.core.engine.executor.Executor#getNext()
+ */
+ @Override
+ public final Executor<EnEvent, EnEvent, AxPolicy, ApexInternalContext> getNext() {
+ return nextExecutor;
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.onap.policy.apex.core.engine.executor.Executor#setParameters(org.onap.policy.apex.core.engine.
+ * ExecutorParameters)
+ */
+ @Override
+ public void setParameters(final ExecutorParameters parameters) {}
+}
diff --git a/core/core-engine/src/main/java/org/onap/policy/apex/core/engine/executor/StateOutput.java b/core/core-engine/src/main/java/org/onap/policy/apex/core/engine/executor/StateOutput.java
new file mode 100644
index 000000000..2274b7c23
--- /dev/null
+++ b/core/core-engine/src/main/java/org/onap/policy/apex/core/engine/executor/StateOutput.java
@@ -0,0 +1,167 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * Copyright (C) 2016-2018 Ericsson. All rights reserved.
+ * ================================================================================
+ * 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;
+
+import java.util.Map;
+import java.util.Map.Entry;
+
+import org.onap.policy.apex.core.engine.event.EnEvent;
+import org.onap.policy.apex.core.engine.executor.exception.StateMachineException;
+import org.onap.policy.apex.model.basicmodel.concepts.AxReferenceKey;
+import org.onap.policy.apex.model.basicmodel.service.ModelService;
+import org.onap.policy.apex.model.eventmodel.concepts.AxEvent;
+import org.onap.policy.apex.model.eventmodel.concepts.AxEvents;
+import org.onap.policy.apex.model.eventmodel.concepts.AxField;
+import org.onap.policy.apex.model.policymodel.concepts.AxStateOutput;
+import org.onap.policy.apex.model.utilities.Assertions;
+
+/**
+ * This class is the output of a state, and is used by the engine to decide what the next state for execution is.
+ *
+ * @author Liam Fallon (liam.fallon@ericsson.com)
+ */
+public class StateOutput {
+ // The state output has a state and an event
+ private final AxStateOutput stateOutputDefinition;
+ private final AxEvent outputEventDef;
+ private final EnEvent outputEvent;
+
+ /**
+ * Create a new state output from a state output definition.
+ *
+ * @param axStateOutput the state output definition
+ */
+ public StateOutput(final AxStateOutput axStateOutput) {
+ this(axStateOutput, new EnEvent(axStateOutput.getOutgingEvent()));
+ }
+
+ /**
+ * Create a new state output with the given definition and event key.
+ *
+ * @param stateOutputDefinition the state output definition
+ * @param outputEvent the output event
+ */
+ public StateOutput(final AxStateOutput stateOutputDefinition, final EnEvent outputEvent) {
+ Assertions.argumentNotNull(stateOutputDefinition, "stateOutputDefinition may not be null");
+ Assertions.argumentNotNull(outputEvent, "outputEvent may not be null");
+
+ this.stateOutputDefinition = stateOutputDefinition;
+ this.outputEvent = outputEvent;
+ outputEventDef = ModelService.getModel(AxEvents.class).get(stateOutputDefinition.getOutgingEvent());
+ }
+
+ /**
+ * Gets the next state.
+ *
+ * @return the next state
+ */
+ public AxReferenceKey getNextState() {
+ return stateOutputDefinition.getNextState();
+ }
+
+ /**
+ * Gets the state output definition.
+ *
+ * @return the state output definition
+ */
+ public AxStateOutput getStateOutputDefinition() {
+ return stateOutputDefinition;
+ }
+
+ /**
+ * Gets the output event.
+ *
+ * @return the output event
+ */
+ public EnEvent getOutputEvent() {
+ return outputEvent;
+ }
+
+ /**
+ * Transfer the fields from the incoming field map into the event.
+ *
+ * @param incomingFieldDefinitionMap definitions of the incoming fields
+ * @param eventFieldMap the event field map
+ * @throws StateMachineException on errors populating the event fields
+ */
+ public void setEventFields(final Map<String, AxField> incomingFieldDefinitionMap,
+ final Map<String, Object> eventFieldMap) throws StateMachineException {
+ Assertions.argumentNotNull(incomingFieldDefinitionMap, "incomingFieldDefinitionMap may not be null");
+ Assertions.argumentNotNull(eventFieldMap, "eventFieldMap may not be null");
+
+ if (!incomingFieldDefinitionMap.keySet().equals(eventFieldMap.keySet())) {
+ throw new StateMachineException(
+ "field definitions and values do not match for event " + outputEventDef.getID() + '\n'
+ + incomingFieldDefinitionMap.keySet() + '\n' + eventFieldMap.keySet());
+ }
+ for (final Entry<String, Object> incomingFieldEntry : eventFieldMap.entrySet()) {
+ final String fieldName = incomingFieldEntry.getKey();
+ final AxField fieldDef = incomingFieldDefinitionMap.get(fieldName);
+ try {
+
+ // Check if this field is a field in the event
+ if (!outputEventDef.getFields().contains(fieldDef)) {
+ throw new StateMachineException(
+ "field \"" + fieldName + "\" does not exist on event \"" + outputEventDef.getID() + "\"");
+ }
+ } catch (final Exception e) {
+ e.printStackTrace();
+ }
+
+ // Set the value in the output event
+ outputEvent.put(fieldName, incomingFieldEntry.getValue());
+ }
+ }
+
+ /**
+ * This method copies any fields that exist on the input event that also exist on the output event if they are not
+ * set on the output event.
+ *
+ * @param incomingEvent The incoming event to copy from
+ */
+ public void copyUnsetFields(final EnEvent incomingEvent) {
+ Assertions.argumentNotNull(incomingEvent, "incomingEvent may not be null");
+
+ for (final Entry<String, Object> incomingField : incomingEvent.entrySet()) {
+ final String fieldName = incomingField.getKey();
+
+ // Check if the field exists on the outgoing event
+ if (!outputEventDef.getParameterMap().containsKey(fieldName)) {
+ continue;
+ }
+
+ // Check if the field is set on the outgoing event
+ if (outputEvent.containsKey(fieldName)) {
+ continue;
+ }
+
+ // Now, check the fields have the same type
+ if (!incomingEvent.getAxEvent().getParameterMap().get(fieldName)
+ .equals(outputEvent.getAxEvent().getParameterMap().get(fieldName))) {
+ continue;
+ }
+
+ // All checks done, we can copy the value
+ outputEvent.put(fieldName, incomingField.getValue());
+ }
+
+ }
+}
diff --git a/core/core-engine/src/main/java/org/onap/policy/apex/core/engine/executor/TaskExecutor.java b/core/core-engine/src/main/java/org/onap/policy/apex/core/engine/executor/TaskExecutor.java
new file mode 100644
index 000000000..4a105b03f
--- /dev/null
+++ b/core/core-engine/src/main/java/org/onap/policy/apex/core/engine/executor/TaskExecutor.java
@@ -0,0 +1,328 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * Copyright (C) 2016-2018 Ericsson. All rights reserved.
+ * ================================================================================
+ * 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;
+
+import static org.onap.policy.apex.model.utilities.Assertions.argumentNotNull;
+
+import java.util.Iterator;
+import java.util.Map;
+import java.util.Set;
+import java.util.TreeMap;
+import java.util.TreeSet;
+
+import org.onap.policy.apex.context.ContextException;
+import org.onap.policy.apex.core.engine.ExecutorParameters;
+import org.onap.policy.apex.core.engine.context.ApexInternalContext;
+import org.onap.policy.apex.core.engine.executor.context.TaskExecutionContext;
+import org.onap.policy.apex.core.engine.executor.exception.StateMachineException;
+import org.onap.policy.apex.model.basicmodel.concepts.AxArtifactKey;
+import org.onap.policy.apex.model.eventmodel.concepts.AxInputField;
+import org.onap.policy.apex.model.eventmodel.concepts.AxOutputField;
+import org.onap.policy.apex.model.policymodel.concepts.AxTask;
+import org.slf4j.ext.XLogger;
+import org.slf4j.ext.XLoggerFactory;
+
+/**
+ * This abstract class executes a task in a state of an Apex policy and is specialized by classes that implement
+ * execution of task logic.
+ *
+ * @author Sven van der Meer (sven.van.der.meer@ericsson.com)
+ * @author Liam Fallon (liam.fallon@ericsson.com)
+ */
+public abstract class TaskExecutor
+ implements Executor<Map<String, Object>, Map<String, Object>, AxTask, ApexInternalContext> {
+ // Logger for this class
+ private static final XLogger LOGGER = XLoggerFactory.getXLogger(TaskExecutor.class);
+
+ // Hold the task and context definitions for this task
+ private Executor<?, ?, ?, ?> parent = null;
+ private AxTask axTask = null;
+ private ApexInternalContext internalContext = null;
+
+ // Holds the incoming and outgoing fields
+ private Map<String, Object> incomingFields = null;
+ private Map<String, Object> outgoingFields = null;
+
+ // The next task executor
+ private Executor<Map<String, Object>, Map<String, Object>, AxTask, ApexInternalContext> nextExecutor = null;
+
+ // The task execution context; contains the facades for events and context to be used by tasks executed by this task
+ // executor
+ private TaskExecutionContext executionContext = null;
+
+ /**
+ * Gets the execution internalContext.
+ *
+ * @return the execution context
+ */
+ protected TaskExecutionContext getExecutionContext() {
+ return executionContext;
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see
+ * org.onap.policy.apex.core.engine.executor.Executor#setContext(org.onap.policy.apex.core.engine.executor.Executor,
+ * java.lang.Object, java.lang.Object)
+ */
+ @Override
+ public void setContext(final Executor<?, ?, ?, ?> newParent, final AxTask newAxTask,
+ final ApexInternalContext newInternalContext) {
+ this.parent = newParent;
+ this.axTask = newAxTask;
+ this.internalContext = newInternalContext;
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.onap.policy.apex.core.engine.executor.Executor#prepare()
+ */
+ @Override
+ public void prepare() throws StateMachineException {
+ LOGGER.debug("prepare:" + axTask.getKey().getID() + "," + axTask.getTaskLogic().getLogicFlavour() + ","
+ + axTask.getTaskLogic().getLogic());
+ argumentNotNull(axTask.getTaskLogic().getLogic(), StateMachineException.class, "task logic cannot be null.");
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.onap.policy.apex.core.engine.executor.Executor#execute(java.lang.long, java.lang.Object)
+ */
+ @Override
+ public Map<String, Object> execute(final long executionID, final Map<String, Object> newIncomingFields)
+ throws StateMachineException, ContextException {
+ throw new StateMachineException(
+ "execute() not implemented on abstract TaskExecutor class, only on its subclasses");
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.onap.policy.apex.core.engine.executor.Executor#executePre(java.lang.long, java.lang.Object)
+ */
+ @Override
+ public final void executePre(final long executionID, final Map<String, Object> newIncomingFields)
+ throws StateMachineException, ContextException {
+ LOGGER.debug("execute-pre:" + getSubject().getTaskLogic().getLogicFlavour() + ","
+ + getSubject().getKey().getID() + "," + getSubject().getTaskLogic().getLogic());
+
+ // Check that the incoming event has all the input fields for this state
+ final Set<String> missingTaskInputFields = new TreeSet<>(axTask.getInputFields().keySet());
+ missingTaskInputFields.removeAll(newIncomingFields.keySet());
+
+ // Remove fields from the set that are optional
+ for (final Iterator<String> missingFieldIterator = missingTaskInputFields.iterator(); missingFieldIterator
+ .hasNext();) {
+ final String missingField = missingFieldIterator.next();
+ if (axTask.getInputFields().get(missingField).getOptional()) {
+ missingTaskInputFields.remove(missingField);
+ }
+ }
+ if (!missingTaskInputFields.isEmpty()) {
+ throw new StateMachineException("task input fields \"" + missingTaskInputFields
+ + "\" are missing for task \"" + axTask.getKey().getID() + "\"");
+ }
+
+ // Record the incoming fields
+ this.incomingFields = newIncomingFields;
+
+ // Initiate the outgoing fields
+ outgoingFields = new TreeMap<>();
+ for (final String outputFieldName : getSubject().getOutputFields().keySet()) {
+ outgoingFields.put(outputFieldName, null);
+ }
+
+ // Get task context object
+ executionContext =
+ new TaskExecutionContext(this, executionID, getSubject(), getIncoming(), getOutgoing(), getContext());
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.onap.policy.apex.core.engine.executor.Executor#executePost(boolean)
+ */
+ @Override
+ public final void executePost(final boolean returnValue) throws StateMachineException, ContextException {
+ if (!returnValue) {
+ String errorMessage = "execute-post: task logic execution failure on task \"" + axTask.getKey().getName()
+ + "\" in model " + internalContext.getKey().getID();
+ if (executionContext.getMessage() != null) {
+ errorMessage += ", user message: " + executionContext.getMessage();
+ }
+ LOGGER.warn(errorMessage);
+ throw new StateMachineException(errorMessage);
+ }
+
+ // Copy any unset fields from the input to the output if their data type and names are identical
+ for (final String field : axTask.getOutputFields().keySet()) {
+ // Check if the field exists and is not set on the output
+ if (!getOutgoing().containsKey(field) || getOutgoing().get(field) != null) {
+ continue;
+ }
+
+ // This field is not in the output, check if it's on the input and is the same type (Note here, the output
+ // field definition has to exist so it's not
+ // null checked)
+ final AxInputField inputFieldDef = axTask.getInputFields().get(field);
+ final AxOutputField outputFieldDef = axTask.getOutputFields().get(field);
+ if (inputFieldDef == null || !inputFieldDef.getSchema().equals(outputFieldDef.getSchema())) {
+ continue;
+ }
+
+ // We have an input field that matches our output field, copy the value across
+ getOutgoing().put(field, getIncoming().get(field));
+ }
+
+ // Finally, check that the outgoing fields have all the output fields defined for this state and, if not, output
+ // a list of missing fields
+ final Set<String> missingTaskOutputFields = new TreeSet<>(axTask.getOutputFields().keySet());
+ missingTaskOutputFields.removeAll(outgoingFields.keySet());
+
+ // Remove fields from the set that are optional
+ for (final Iterator<String> missingFieldIterator = missingTaskOutputFields.iterator(); missingFieldIterator
+ .hasNext();) {
+ final String missingField = missingFieldIterator.next();
+ if (axTask.getInputFields().get(missingField).getOptional()) {
+ missingTaskOutputFields.remove(missingField);
+ }
+ }
+ if (!missingTaskOutputFields.isEmpty()) {
+ throw new StateMachineException("task output fields \"" + missingTaskOutputFields
+ + "\" are missing for task \"" + axTask.getKey().getID() + "\"");
+ }
+
+ // Finally, check that the outgoing field map don't have any extra fields, if present, raise exception with the
+ // list of extra fields
+ final Set<String> extraTaskOutputFields = new TreeSet<>(outgoingFields.keySet());
+ extraTaskOutputFields.removeAll(axTask.getOutputFields().keySet());
+ if (!extraTaskOutputFields.isEmpty()) {
+ throw new StateMachineException("task output fields \"" + extraTaskOutputFields
+ + "\" are unwanted for task \"" + axTask.getKey().getID() + "\"");
+ }
+
+ LOGGER.debug("execute-post:" + axTask.getKey().getID() + ", returning fields " + outgoingFields.toString());
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.onap.policy.apex.core.engine.executor.Executor#cleanUp()
+ */
+ @Override
+ public void cleanUp() throws StateMachineException {
+ throw new StateMachineException("cleanUp() not implemented on class");
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.onap.policy.apex.core.engine.executor.Executor#getKey()
+ */
+ @Override
+ public AxArtifactKey getKey() {
+ return axTask.getKey();
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.onap.policy.apex.core.engine.executor.Executor#getParent()
+ */
+ @Override
+ public Executor<?, ?, ?, ?> getParent() {
+ return parent;
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.onap.policy.apex.core.engine.executor.Executor#getSubject()
+ */
+ @Override
+ public AxTask getSubject() {
+ return axTask;
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.onap.policy.apex.core.engine.executor.Executor#getContext()
+ */
+ @Override
+ public ApexInternalContext getContext() {
+ return internalContext;
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.onap.policy.apex.core.engine.executor.Executor#getIncoming()
+ */
+ @Override
+ public Map<String, Object> getIncoming() {
+ return incomingFields;
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.onap.policy.apex.core.engine.executor.Executor#getOutgoing()
+ */
+ @Override
+ public Map<String, Object> getOutgoing() {
+ return outgoingFields;
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see
+ * org.onap.policy.apex.core.engine.executor.Executor#setNext(org.onap.policy.apex.core.engine.executor.Executor)
+ */
+ @Override
+ public void setNext(
+ final Executor<Map<String, Object>, Map<String, Object>, AxTask, ApexInternalContext> newNextExecutor) {
+ this.nextExecutor = newNextExecutor;
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.onap.policy.apex.core.engine.executor.Executor#getNext()
+ */
+ @Override
+ public Executor<Map<String, Object>, Map<String, Object>, AxTask, ApexInternalContext> getNext() {
+ return nextExecutor;
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.onap.policy.apex.core.engine.executor.Executor#setParameters(org.onap.policy.apex.core.engine.
+ * ExecutorParameters)
+ */
+ @Override
+ public void setParameters(final ExecutorParameters parameters) {}
+}
diff --git a/core/core-engine/src/main/java/org/onap/policy/apex/core/engine/executor/TaskSelectExecutor.java b/core/core-engine/src/main/java/org/onap/policy/apex/core/engine/executor/TaskSelectExecutor.java
new file mode 100644
index 000000000..1aaa5ccf5
--- /dev/null
+++ b/core/core-engine/src/main/java/org/onap/policy/apex/core/engine/executor/TaskSelectExecutor.java
@@ -0,0 +1,263 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * Copyright (C) 2016-2018 Ericsson. All rights reserved.
+ * ================================================================================
+ * 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;
+
+import static org.onap.policy.apex.model.utilities.Assertions.argumentNotNull;
+
+import org.onap.policy.apex.context.ContextException;
+import org.onap.policy.apex.core.engine.ExecutorParameters;
+import org.onap.policy.apex.core.engine.context.ApexInternalContext;
+import org.onap.policy.apex.core.engine.event.EnEvent;
+import org.onap.policy.apex.core.engine.executor.context.TaskSelectionExecutionContext;
+import org.onap.policy.apex.core.engine.executor.exception.StateMachineException;
+import org.onap.policy.apex.model.basicmodel.concepts.AxArtifactKey;
+import org.onap.policy.apex.model.basicmodel.concepts.AxReferenceKey;
+import org.onap.policy.apex.model.policymodel.concepts.AxState;
+import org.slf4j.ext.XLogger;
+import org.slf4j.ext.XLoggerFactory;
+
+/**
+ * This abstract class executes a the task selection logic of a state of an Apex policy and is specialized by classes
+ * that implement execution of task selection logic.
+ *
+ * @author Sven van der Meer (sven.van.der.meer@ericsson.com)
+ * @author Liam Fallon (liam.fallon@ericsson.com)
+ */
+public abstract class TaskSelectExecutor implements Executor<EnEvent, AxArtifactKey, AxState, ApexInternalContext> {
+ // Logger for this class
+ private static final XLogger LOGGER = XLoggerFactory.getXLogger(TaskSelectExecutor.class);
+
+ // Hold the state and context definitions for this task selector
+ private Executor<?, ?, ?, ?> parent = null;
+ private AxState axState = null;
+ private ApexInternalContext context = null;
+
+ // Holds the incoming event and outgoing task keys
+ private EnEvent incomingEvent = null;
+ private AxArtifactKey outgoingTaskKey = null;
+
+ // The next task selection executor
+ private Executor<EnEvent, AxArtifactKey, AxState, ApexInternalContext> nextExecutor = null;
+
+ // The task selection execution context; contains the facades for events and context to be used by tasks executed by
+ // this task selection executor
+ private TaskSelectionExecutionContext executionContext;
+
+ /**
+ * Gets the execution context.
+ *
+ * @return the execution context
+ */
+ protected TaskSelectionExecutionContext getExecutionContext() {
+ return executionContext;
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see
+ * org.onap.policy.apex.core.engine.executor.Executor#setContext(org.onap.policy.apex.core.engine.executor.Executor,
+ * java.lang.Object, java.lang.Object)
+ */
+ @Override
+ public void setContext(final Executor<?, ?, ?, ?> newParent, final AxState newAxState,
+ final ApexInternalContext newContext) {
+ this.parent = newParent;
+ this.axState = newAxState;
+ this.context = newContext;
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.onap.policy.apex.core.engine.executor.Executor#prepare()
+ */
+ @Override
+ public void prepare() throws StateMachineException {
+ LOGGER.debug("prepare:" + axState.getKey().getID() + "," + axState.getTaskSelectionLogic().getLogicFlavour()
+ + "," + axState.getTaskSelectionLogic().getLogic());
+ argumentNotNull(axState.getTaskSelectionLogic().getLogic(), "task selection logic cannot be null.");
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.onap.policy.apex.core.engine.executor.Executor#execute(java.lang.long, java.lang.Object)
+ */
+ @Override
+ public AxArtifactKey execute(final long executionID, final EnEvent newIncomingEvent)
+ throws StateMachineException, ContextException {
+ throw new StateMachineException("execute() not implemented on class");
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.onap.policy.apex.core.engine.executor.Executor#executePre(java.lang.long, java.lang.Object)
+ */
+ @Override
+ public final void executePre(final long executionID, final EnEvent newIncomingEvent) throws StateMachineException {
+ LOGGER.debug("execute-pre:" + axState.getKey().getID() + "," + axState.getTaskSelectionLogic().getLogicFlavour()
+ + "," + axState.getTaskSelectionLogic().getLogic());
+
+ this.incomingEvent = newIncomingEvent;
+
+ // Initialize the returned task object so it can be set
+ outgoingTaskKey = new AxArtifactKey();
+
+ // Get task selection context object
+ executionContext = new TaskSelectionExecutionContext(this, executionID, getSubject(), getIncoming(),
+ getOutgoing(), getContext());
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.onap.policy.apex.core.engine.executor.Executor#executePost(boolean)
+ */
+ @Override
+ public final void executePost(final boolean returnValue) throws StateMachineException {
+ if (!returnValue) {
+ String errorMessage =
+ "execute-post: task selection logic failed on state \"" + axState.getKey().getID() + "\"";
+ if (executionContext.getMessage() != null) {
+ errorMessage += ", user message: " + executionContext.getMessage();
+ }
+ LOGGER.warn(errorMessage);
+ throw new StateMachineException(errorMessage);
+ }
+
+ if (outgoingTaskKey == null || AxArtifactKey.getNullKey().getName().equals(outgoingTaskKey.getName())) {
+ outgoingTaskKey = axState.getDefaultTask();
+ LOGGER.debug("execute-post:" + axState.getKey().getID() + ", returning default task");
+ return;
+ }
+
+ if (!axState.getTaskReferences().containsKey(outgoingTaskKey)) {
+ LOGGER.error("execute-post: task \"" + outgoingTaskKey.getID()
+ + "\" returned by task selection logic not defined on state \"" + axState.getKey().getID() + "\"");
+ throw new StateMachineException("task \"" + outgoingTaskKey.getID()
+ + "\" returned by task selection logic not defined on state \"" + axState.getKey().getID() + "\"");
+ }
+
+ LOGGER.debug("execute-post:" + axState.getKey().getID() + "," + ", returning task " + outgoingTaskKey.getID());
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.onap.policy.apex.core.engine.executor.Executor#cleanUp()
+ */
+ @Override
+ public void cleanUp() throws StateMachineException {
+ throw new StateMachineException("cleanUp() not implemented on class");
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.onap.policy.apex.core.engine.executor.Executor#getKey()
+ */
+ @Override
+ public AxReferenceKey getKey() {
+ return axState.getKey();
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.onap.policy.apex.core.engine.executor.Executor#getParent()
+ */
+ @Override
+ public Executor<?, ?, ?, ?> getParent() {
+ return parent;
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.onap.policy.apex.core.engine.executor.Executor#getSubject()
+ */
+ @Override
+ public AxState getSubject() {
+ return axState;
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.onap.policy.apex.core.engine.executor.Executor#getContext()
+ */
+ @Override
+ public ApexInternalContext getContext() {
+ return context;
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see
+ * org.onap.policy.apex.core.engine.executor.Executor#setNext(org.onap.policy.apex.core.engine.executor.Executor)
+ */
+ @Override
+ public void setNext(final Executor<EnEvent, AxArtifactKey, AxState, ApexInternalContext> newNextExecutor) {
+ this.nextExecutor = newNextExecutor;
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.onap.policy.apex.core.engine.executor.Executor#getNext()
+ */
+ @Override
+ public Executor<EnEvent, AxArtifactKey, AxState, ApexInternalContext> getNext() {
+ return nextExecutor;
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.onap.policy.apex.core.engine.executor.Executor#getIncoming()
+ */
+ @Override
+ public EnEvent getIncoming() {
+ return incomingEvent;
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.onap.policy.apex.core.engine.executor.Executor#getOutgoing()
+ */
+ @Override
+ public AxArtifactKey getOutgoing() {
+ return outgoingTaskKey;
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.onap.policy.apex.core.engine.executor.Executor#setParameters(org.onap.policy.apex.core.engine.
+ * ExecutorParameters)
+ */
+ @Override
+ public void setParameters(final ExecutorParameters parameters) {}
+}
diff --git a/core/core-engine/src/main/java/org/onap/policy/apex/core/engine/executor/context/AxStateFacade.java b/core/core-engine/src/main/java/org/onap/policy/apex/core/engine/executor/context/AxStateFacade.java
new file mode 100644
index 000000000..226f06ade
--- /dev/null
+++ b/core/core-engine/src/main/java/org/onap/policy/apex/core/engine/executor/context/AxStateFacade.java
@@ -0,0 +1,110 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * Copyright (C) 2016-2018 Ericsson. All rights reserved.
+ * ================================================================================
+ * 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.List;
+import java.util.Set;
+
+import org.onap.policy.apex.model.basicmodel.concepts.AxArtifactKey;
+import org.onap.policy.apex.model.basicmodel.service.ModelService;
+import org.onap.policy.apex.model.policymodel.concepts.AxState;
+import org.onap.policy.apex.model.policymodel.concepts.AxTasks;
+
+/**
+ * The Class AxStateFacade acts as a facade into the AxState class so that task logic can easily access information in
+ * an AxState instance.
+ *
+ * @author Sven van der Meer (sven.van.der.meer@ericsson.com)
+ */
+public class AxStateFacade {
+ // CHECKSTYLE:OFF: checkstyle:visibilityModifier Logic has access to this field
+
+ /** The full definition information for the state. */
+ public AxState state;
+
+ // CHECKSTYLE:ON: checkstyle:visibilityModifier
+
+ /**
+ * Instantiates a new AxState facade.
+ *
+ * @param state the state for which a facade is being presented
+ */
+ public AxStateFacade(final AxState state) {
+ this.state = state;
+ }
+
+ /**
+ * Gets the default task key of the state.
+ *
+ * @return the default task key
+ */
+ public AxArtifactKey getDefaultTaskKey() {
+ return state.getDefaultTask();
+ }
+
+ /**
+ * Gets the ID of the state.
+ *
+ * @return the ID
+ */
+ public String getId() {
+ return state.getKey().getID();
+ }
+
+ /**
+ * Gets the name of the state.
+ *
+ * @return the state name
+ */
+ public String getStateName() {
+ return state.getKey().getLocalName();
+ }
+
+ /**
+ * Check if a task is defined for a given task name on a state and, if so, return its key.
+ *
+ * @param taskName the name of the task to get
+ * @return the task key or null if it does not exist
+ */
+ public AxArtifactKey getTaskKey(final String taskName) {
+ if (taskName == null) {
+ return null;
+ }
+
+ return ModelService.getModel(AxTasks.class).get(taskName).getKey();
+ }
+
+ /**
+ * Check if a task is defined for a given task name on a state and, if so, return its key.
+ *
+ * @return unmodifiable list of names of tasks available
+ */
+ public List<String> getTaskNames() {
+ final Set<AxArtifactKey> tasks = state.getTaskReferences().keySet();
+ final List<String> ret = new ArrayList<>(tasks.size());
+ for (final AxArtifactKey task : tasks) {
+ ret.add(task.getName());
+ }
+ return Collections.unmodifiableList(ret);
+ }
+}
diff --git a/core/core-engine/src/main/java/org/onap/policy/apex/core/engine/executor/context/AxTaskFacade.java b/core/core-engine/src/main/java/org/onap/policy/apex/core/engine/executor/context/AxTaskFacade.java
new file mode 100644
index 000000000..015f3ae80
--- /dev/null
+++ b/core/core-engine/src/main/java/org/onap/policy/apex/core/engine/executor/context/AxTaskFacade.java
@@ -0,0 +1,131 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * Copyright (C) 2016-2018 Ericsson. All rights reserved.
+ * ================================================================================
+ * 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 org.onap.policy.apex.context.ContextRuntimeException;
+import org.onap.policy.apex.context.SchemaHelper;
+import org.onap.policy.apex.context.impl.schema.SchemaHelperFactory;
+import org.onap.policy.apex.core.engine.event.EnException;
+import org.onap.policy.apex.core.engine.executor.exception.StateMachineRuntimeException;
+import org.onap.policy.apex.model.eventmodel.concepts.AxField;
+import org.onap.policy.apex.model.policymodel.concepts.AxTask;
+import org.slf4j.ext.XLogger;
+import org.slf4j.ext.XLoggerFactory;
+
+/**
+ * The Class AxTaskFacade acts as a facade into the AxTask class so that task logic can easily access information in an
+ * AxTask instance.
+ *
+ * @author Sven van der Meer (sven.van.der.meer@ericsson.com)
+ */
+public class AxTaskFacade {
+ // Logger for this class
+ private static final XLogger LOGGER = XLoggerFactory.getXLogger(AxTaskFacade.class);
+
+ // CHECKSTYLE:OFF: checkstyle:visibilityModifier Logic has access to this field
+
+ /**
+ * The full definition of the task we are presenting a facade to, executing logic has full access to the task
+ * definition.
+ */
+ public AxTask task;
+
+ // CHECKSTYLE:ON: checkstyle:visibilityModifier
+
+ /**
+ * Instantiates a new AxTask facade.
+ *
+ * @param task the task for which a facade is being presented
+ */
+ public AxTaskFacade(final AxTask task) {
+ this.task = task;
+ }
+
+ /**
+ * Gets the name of the task.
+ *
+ * @return the task name
+ */
+ public String getTaskName() {
+ return task.getKey().getName();
+ }
+
+ /**
+ * Gets the task ID.
+ *
+ * @return the task ID
+ */
+ public String getId() {
+ return task.getID();
+ }
+
+ /**
+ * Creates a schema helper for an incoming field of this task.
+ *
+ * @param fieldName The name of the field to get a schema helper for
+ * @return the schema helper for this field
+ */
+ public SchemaHelper getInFieldSchemaHelper(final String fieldName) {
+ // Find the field for the field name
+ return getFieldSchemaHelper(fieldName, task.getInputFields().get(fieldName), "incoming");
+ }
+
+ /**
+ * Creates a schema helper for an outgoing field of this task.
+ *
+ * @param fieldName The name of the field to get a schema helper for
+ * @return the schema helper for this field
+ */
+ public SchemaHelper getOutFieldSchemaHelper(final String fieldName) {
+ // Find the field for the field name
+ return getFieldSchemaHelper(fieldName, task.getOutputFields().get(fieldName), "outgoing");
+ }
+
+ /**
+ * Creates a schema helper for an incoming field of this task.
+ *
+ * @param fieldName The name of the field to get a schema helper for
+ * @param field the field
+ * @param directionString the direction string
+ * @return the schema helper for this field
+ */
+ private SchemaHelper getFieldSchemaHelper(final String fieldName, final AxField field,
+ final String directionString) {
+ // Find the field for the field name
+ if (field == null) {
+ final String message = "no " + directionString + " field with name \"" + fieldName + "\" defined on task \""
+ + task.getID() + "\"";
+ LOGGER.warn(message);
+ throw new StateMachineRuntimeException(message);
+ }
+
+ // Get a schema helper to handle translations of fields to and from the schema
+ try {
+ return new SchemaHelperFactory().createSchemaHelper(field.getKey(), field.getSchema());
+ } catch (final ContextRuntimeException e) {
+ final String message = "schema helper cannot be created for task field \"" + fieldName + "\" with key \""
+ + field.getID() + "\" with schema \"" + field.getSchema() + "\"";
+ LOGGER.warn(message, e);
+ throw new EnException(message, e);
+ }
+ }
+
+}
diff --git a/core/core-engine/src/main/java/org/onap/policy/apex/core/engine/executor/context/StateFinalizerExecutionContext.java b/core/core-engine/src/main/java/org/onap/policy/apex/core/engine/executor/context/StateFinalizerExecutionContext.java
new file mode 100644
index 000000000..2e5971142
--- /dev/null
+++ b/core/core-engine/src/main/java/org/onap/policy/apex/core/engine/executor/context/StateFinalizerExecutionContext.java
@@ -0,0 +1,194 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * Copyright (C) 2016-2018 Ericsson. All rights reserved.
+ * ================================================================================
+ * 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.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.TreeMap;
+
+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.StateFinalizerExecutor;
+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.AxState;
+import org.slf4j.ext.XLogger;
+import org.slf4j.ext.XLoggerFactory;
+
+/**
+ * Container class for the execution context for state finalizer logic executions in a state being executed in an Apex
+ * engine. The state finalizer must have easy access to the state definition, the fields, as well as the policy, global,
+ * and external context.
+ *
+ * @author Sven van der Meer (sven.van.der.meer@ericsson.com)
+ */
+public class StateFinalizerExecutionContext {
+ /**
+ * Logger for state finalizer execution, state finalizer logic can use this field to access and log to Apex logging.
+ */
+ private static final XLogger EXCEUTION_LOGGER =
+ XLoggerFactory.getXLogger("org.onap.policy.apex.executionlogging.StateFinalizerExecutionLogging");
+
+ // CHECKSTYLE:OFF: checkstyle:VisibilityModifier Logic has access to these field
+
+ /** A facade to the full state definition for the state finalizer logic being executed. */
+ public final AxStateFacade subject;
+
+ /** the execution ID for the current APEX policy execution instance. */
+ public final Long executionID;
+
+ /**
+ * The list of state outputs for this state finalizer. The purpose of a state finalizer is to select a state output
+ * for a state from this list of state output names.
+ */
+ public final Set<String> stateOutputNames;
+
+ /**
+ * The fields of this state finalizer. A state finalizer receives this list of fields from a task and may use these
+ * fields to determine what state output to select. Once a state finalizer has selected a state output, it must
+ * marshal these fields so that they match the fields required for the event defined in the state output.
+ */
+ public Map<String, Object> fields;
+
+ // A message specified in the logic
+ private String message;
+
+ /**
+ * The state output that the state finalizer logic has selected for a state. The state finalizer logic sets this
+ * field in its logic after executing and the Apex engine uses this state output for this state.
+ */
+ private String selectedStateOutputName;
+
+ /**
+ * Logger for state finalizer execution, state finalizer logic can use this field to access and log to Apex logging.
+ */
+ public final XLogger logger = EXCEUTION_LOGGER;
+
+ // CHECKSTYLE:ON: checkstyle:visibilityModifier
+
+ // All available context albums
+ private final Map<String, ContextAlbum> context;
+
+ /**
+ * Instantiates a new state finalizer execution context.
+ *
+ * @param stateFinalizerExecutor the state finalizer executor that requires context
+ * @param executionID the execution ID for the current APEX policy execution instance
+ * @param axState the state definition that is the subject of execution
+ * @param fields the fields to be manipulated by the state finalizer
+ * @param stateOutputNames the state output names, one of which will be selected by the state finalizer
+ * @param internalContext the execution context of the Apex engine in which the task is being executed
+ */
+ public StateFinalizerExecutionContext(final StateFinalizerExecutor stateFinalizerExecutor, final long executionID,
+ final AxState axState, final Map<String, Object> fields, final Set<String> stateOutputNames,
+ final ApexInternalContext internalContext) {
+ subject = new AxStateFacade(axState);
+
+ // Execution ID is the current policy execution instance
+ this.executionID = executionID;
+
+ this.fields = fields;
+ this.stateOutputNames = stateOutputNames;
+
+ // Set up the context albums for this task
+ context = new TreeMap<>();
+ for (final AxArtifactKey mapKey : subject.state.getContextAlbumReferences()) {
+ context.put(mapKey.getName(), internalContext.getContextAlbums().get(mapKey));
+ }
+
+ // Get the artifact stack of the users of the policy
+ final List<AxConcept> usedArtifactStack = new ArrayList<>();
+ for (Executor<?, ?, ?, ?> parent = stateFinalizerExecutor.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
+ // Set the user of the context
+ for (final ContextAlbum contextAlbum : context.values()) {
+ contextAlbum.setUserArtifactStack(usedArtifactStackArray);
+ }
+ }
+
+ /**
+ * Return a context album if it exists in the context definition of this state.
+ *
+ * @param contextAlbumName The context album name
+ * @return The context album
+ * @throws ContextRuntimeException if the context album does not exist on the state for this executor
+ */
+ public ContextAlbum getContextAlbum(final String contextAlbumName) throws ContextRuntimeException {
+ // 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 state \"" + subject.getId() + "\"");
+ }
+ }
+
+ /**
+ * Return the state output name selected by the state finalizer logic.
+ *
+ * @return the state output name
+ */
+ public String getSelectedStateOutputName() {
+ return selectedStateOutputName;
+ }
+
+ /**
+ * Set the state output name selected by the state finalizer logic.
+ *
+ * @param selectedStateOutputName the state output name
+ */
+ public void setSelectedStateOutputName(final String selectedStateOutputName) {
+ this.selectedStateOutputName = selectedStateOutputName;
+ }
+
+ /**
+ * Gets the user message.
+ *
+ * @return the user message
+ */
+ public String getMessage() {
+ return message;
+ }
+
+ /**
+ * Sets the user message.
+ *
+ * @param message the message
+ */
+ public void setMessage(final String message) {
+ this.message = message;
+ }
+}
diff --git a/core/core-engine/src/main/java/org/onap/policy/apex/core/engine/executor/context/TaskExecutionContext.java b/core/core-engine/src/main/java/org/onap/policy/apex/core/engine/executor/context/TaskExecutionContext.java
new file mode 100644
index 000000000..2251cf5c1
--- /dev/null
+++ b/core/core-engine/src/main/java/org/onap/policy/apex/core/engine/executor/context/TaskExecutionContext.java
@@ -0,0 +1,174 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * Copyright (C) 2016-2018 Ericsson. All rights reserved.
+ * ================================================================================
+ * 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.List;
+import java.util.Map;
+import java.util.TreeMap;
+
+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.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)
+ */
+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 TRUE = true;
+
+ /** A constant <code>boolean false</code> value available for reuse e.g., for the return value */
+ public final Boolean FALSE = 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
+ private String message;
+
+ /**
+ * 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 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 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);
+
+ // Execution ID is the current policy execution instance
+ this.executionID = executionID;
+
+ // 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);
+ }
+ }
+
+ /**
+ * 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) throws ContextRuntimeException {
+ // 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() + "\"");
+ }
+ }
+
+ /**
+ * Get the user message.
+ *
+ * @return the user message
+ */
+ public String getMessage() {
+ return message;
+ }
+
+ /**
+ * Sets the user message.
+ *
+ * @param message the message
+ */
+ public void setMessage(final String message) {
+ this.message = message;
+ }
+}
diff --git a/core/core-engine/src/main/java/org/onap/policy/apex/core/engine/executor/context/TaskSelectionExecutionContext.java b/core/core-engine/src/main/java/org/onap/policy/apex/core/engine/executor/context/TaskSelectionExecutionContext.java
new file mode 100644
index 000000000..a196e360e
--- /dev/null
+++ b/core/core-engine/src/main/java/org/onap/policy/apex/core/engine/executor/context/TaskSelectionExecutionContext.java
@@ -0,0 +1,180 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * Copyright (C) 2016-2018 Ericsson. All rights reserved.
+ * ================================================================================
+ * 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.List;
+import java.util.Map;
+import java.util.TreeMap;
+
+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.event.EnEvent;
+import org.onap.policy.apex.core.engine.executor.Executor;
+import org.onap.policy.apex.core.engine.executor.TaskSelectExecutor;
+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.AxState;
+import org.slf4j.ext.XLogger;
+import org.slf4j.ext.XLoggerFactory;
+
+/**
+ * Container class for the execution context for Task Selection logic executions in a task being executed in an Apex
+ * engine. The task must have easy access to the state definition, the incoming and outgoing event contexts, as well as
+ * the policy, global, and external context.
+ *
+ * @author Sven van der Meer (sven.van.der.meer@ericsson.com)
+ */
+public class TaskSelectionExecutionContext {
+ // Logger for task execution
+ private static final XLogger EXECUTION_LOGGER =
+ XLoggerFactory.getXLogger("org.onap.policy.apex.executionlogging.TaskSelectionExecutionLogging");
+
+ // 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 TRUE = true;
+
+ /** A constant <code>boolean false</code> value available for reuse e.g., for the return value */
+ public final Boolean FALSE = false;
+
+ /** A facade to the full state definition for the task selection logic being executed. */
+ public final AxStateFacade subject;
+
+ /** the execution ID for the current APEX policy execution instance. */
+ public final Long executionID;
+
+ /**
+ * The incoming fields from the trigger event for the state. The task selection logic can access these fields to
+ * decide what task to select for the state.
+ */
+ public final Map<String, Object> inFields;
+
+ /**
+ * The task that the task selection logic has selected for a state. The task selection logic sets this field in its
+ * logic prior to executing and the Apex engine executes this task as the task for this state.
+ */
+ public final AxArtifactKey selectedTask;
+
+ /**
+ * Logger for task selection execution, task selection 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;
+
+ // A message specified in the logic
+ private String message;
+
+ /**
+ * Instantiates a new task selection execution context.
+ *
+ * @param taskSelectExecutor the task selection executor that requires context
+ * @param executionID the execution identifier
+ * @param axState the state definition that is the subject of execution
+ * @param incomingEvent the incoming event for the state
+ * @param outgoingKey the outgoing key for the task to execute in this state
+ * @param internalContext the execution context of the Apex engine in which the task is being executed
+ */
+ public TaskSelectionExecutionContext(final TaskSelectExecutor taskSelectExecutor, final long executionID,
+ final AxState axState, final EnEvent incomingEvent, final AxArtifactKey outgoingKey,
+ final ApexInternalContext internalContext) {
+ // The subject is the state definition
+ subject = new AxStateFacade(axState);
+
+ // Execution ID is the current policy execution instance
+ this.executionID = executionID;
+
+ // The events
+ inFields = incomingEvent;
+ selectedTask = outgoingKey;
+
+ // Set up the context albums for this task
+ // Set up the context albums for this task
+ context = new TreeMap<>();
+ for (final AxArtifactKey mapKey : subject.state.getContextAlbumReferences()) {
+ context.put(mapKey.getName(), internalContext.getContextAlbums().get(mapKey));
+ }
+
+ // Get the artifact stack of the users of the policy
+ final List<AxConcept> usedArtifactStack = new ArrayList<>();
+ for (Executor<?, ?, ?, ?> parent = taskSelectExecutor.getParent(); parent != null; parent =
+ parent.getParent()) {
+ // Add each parent to the top of the stack
+ usedArtifactStack.add(0, parent.getKey());
+ }
+
+ // Add the events to the artifact stack
+ usedArtifactStack.add(incomingEvent.getKey());
+
+ // Change the stack to an array
+ final AxConcept[] usedArtifactStackArray = usedArtifactStack.toArray(new AxConcept[usedArtifactStack.size()]);
+
+ // Set the user of the context
+ // Set the user of the context
+ for (final ContextAlbum contextAlbum : context.values()) {
+ contextAlbum.setUserArtifactStack(usedArtifactStackArray);
+ }
+ incomingEvent.setUserArtifactStack(usedArtifactStackArray);
+ }
+
+ /**
+ * Return a context album if it exists in the context definition of this state.
+ *
+ * @param contextAlbumName The context album name
+ * @return The context albumxxxxxx
+ * @throws ContextRuntimeException if the context album does not exist on the state for this executor
+ */
+ public ContextAlbum getContextAlbum(final String contextAlbumName) throws ContextRuntimeException {
+ // 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 state \"" + subject.getId() + "\"");
+ }
+ }
+
+ /**
+ * Gets the user message.
+ *
+ * @return the user message
+ */
+ public String getMessage() {
+ return message;
+ }
+
+ /**
+ * Sets the user message.
+ *
+ * @param message the message
+ */
+ public void setMessage(final String message) {
+ this.message = message;
+ }
+}
diff --git a/core/core-engine/src/main/java/org/onap/policy/apex/core/engine/executor/context/package-info.java b/core/core-engine/src/main/java/org/onap/policy/apex/core/engine/executor/context/package-info.java
new file mode 100644
index 000000000..6dc555107
--- /dev/null
+++ b/core/core-engine/src/main/java/org/onap/policy/apex/core/engine/executor/context/package-info.java
@@ -0,0 +1,33 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * Copyright (C) 2016-2018 Ericsson. All rights reserved.
+ * ================================================================================
+ * 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=========================================================
+ */
+
+/**
+ * Provides context and facades for executing tasks, task selection logic, and state finalizer logic. The public fields
+ * and methods of {@link TaskExecutionContext}, {@link TaskSelectionExecutionContext} and
+ * {@link StateFinalizerExecutionContext} are available to task logic, task selection logic, and state finalizer logic
+ * respectively when that logic is executing in an executor plugin under the control of an APEX engine.
+ *
+ * The {@link AxStateFacade} and {@link AxTaskFacade} classes provide facades and convenience methods for state and task
+ * definition information for logic at execution time.
+ *
+ * @author Liam Fallon (liam.fallon@ericsson.com)
+ */
+
+package org.onap.policy.apex.core.engine.executor.context;
diff --git a/core/core-engine/src/main/java/org/onap/policy/apex/core/engine/executor/exception/StateMachineException.java b/core/core-engine/src/main/java/org/onap/policy/apex/core/engine/executor/exception/StateMachineException.java
new file mode 100644
index 000000000..9d6c55900
--- /dev/null
+++ b/core/core-engine/src/main/java/org/onap/policy/apex/core/engine/executor/exception/StateMachineException.java
@@ -0,0 +1,51 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * Copyright (C) 2016-2018 Ericsson. All rights reserved.
+ * ================================================================================
+ * 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.exception;
+
+import org.onap.policy.apex.model.basicmodel.concepts.ApexException;
+
+/**
+ * This class will be called if an error occurs in an Apex state machine.
+ *
+ * @author Liam Fallon (liam.fallon@ericsson.com)
+ */
+public class StateMachineException extends ApexException {
+ private static final long serialVersionUID = -4245694568321686450L;
+
+ /**
+ * Instantiates a new state machine exception.
+ *
+ * @param message the message
+ */
+ public StateMachineException(final String message) {
+ super(message);
+ }
+
+ /**
+ * Instantiates a new state machine exception.
+ *
+ * @param message the message
+ * @param e the e
+ */
+ public StateMachineException(final String message, final Exception e) {
+ super(message, e);
+ }
+}
diff --git a/core/core-engine/src/main/java/org/onap/policy/apex/core/engine/executor/exception/StateMachineRuntimeException.java b/core/core-engine/src/main/java/org/onap/policy/apex/core/engine/executor/exception/StateMachineRuntimeException.java
new file mode 100644
index 000000000..9ce2d7499
--- /dev/null
+++ b/core/core-engine/src/main/java/org/onap/policy/apex/core/engine/executor/exception/StateMachineRuntimeException.java
@@ -0,0 +1,51 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * Copyright (C) 2016-2018 Ericsson. All rights reserved.
+ * ================================================================================
+ * 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.exception;
+
+import org.onap.policy.apex.model.basicmodel.concepts.ApexRuntimeException;
+
+/**
+ * This class will be called if a runtime error occurs in an Apex state machine.
+ *
+ * @author Liam Fallon (liam.fallon@ericsson.com)
+ */
+public class StateMachineRuntimeException extends ApexRuntimeException {
+ private static final long serialVersionUID = -4245694568321686450L;
+
+ /**
+ * Instantiates a new state machine exception.
+ *
+ * @param message the message
+ */
+ public StateMachineRuntimeException(final String message) {
+ super(message);
+ }
+
+ /**
+ * Instantiates a new state machine exception.
+ *
+ * @param message the message
+ * @param e the e
+ */
+ public StateMachineRuntimeException(final String message, final Exception e) {
+ super(message, e);
+ }
+}
diff --git a/core/core-engine/src/main/java/org/onap/policy/apex/core/engine/executor/exception/package-info.java b/core/core-engine/src/main/java/org/onap/policy/apex/core/engine/executor/exception/package-info.java
new file mode 100644
index 000000000..1cb433946
--- /dev/null
+++ b/core/core-engine/src/main/java/org/onap/policy/apex/core/engine/executor/exception/package-info.java
@@ -0,0 +1,27 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * Copyright (C) 2016-2018 Ericsson. All rights reserved.
+ * ================================================================================
+ * 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=========================================================
+ */
+
+/**
+ * Contains exceptions that may be thrown during execution of an APEX engine.
+ *
+ * @author Liam Fallon (liam.fallon@ericsson.com)
+ */
+
+package org.onap.policy.apex.core.engine.executor.exception;
diff --git a/core/core-engine/src/main/java/org/onap/policy/apex/core/engine/executor/impl/ExecutorFactoryImpl.java b/core/core-engine/src/main/java/org/onap/policy/apex/core/engine/executor/impl/ExecutorFactoryImpl.java
new file mode 100644
index 000000000..58ee4c6cc
--- /dev/null
+++ b/core/core-engine/src/main/java/org/onap/policy/apex/core/engine/executor/impl/ExecutorFactoryImpl.java
@@ -0,0 +1,235 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * Copyright (C) 2016-2018 Ericsson. All rights reserved.
+ * ================================================================================
+ * 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.impl;
+
+import java.util.Map;
+import java.util.Map.Entry;
+import java.util.TreeMap;
+
+import org.onap.policy.apex.core.engine.EngineParameters;
+import org.onap.policy.apex.core.engine.ExecutorParameters;
+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.ExecutorFactory;
+import org.onap.policy.apex.core.engine.executor.StateFinalizerExecutor;
+import org.onap.policy.apex.core.engine.executor.TaskExecutor;
+import org.onap.policy.apex.core.engine.executor.TaskSelectExecutor;
+import org.onap.policy.apex.core.engine.executor.exception.StateMachineException;
+import org.onap.policy.apex.core.engine.executor.exception.StateMachineRuntimeException;
+import org.onap.policy.apex.model.basicmodel.service.ParameterService;
+import org.onap.policy.apex.model.policymodel.concepts.AxState;
+import org.onap.policy.apex.model.policymodel.concepts.AxStateFinalizerLogic;
+import org.onap.policy.apex.model.policymodel.concepts.AxTask;
+import org.onap.policy.apex.model.utilities.Assertions;
+import org.slf4j.ext.XLogger;
+import org.slf4j.ext.XLoggerFactory;
+
+/**
+ * The Class ExecutorFactoryImpl is a factory class that returns task selection logic and task logic executors depending
+ * on the type of logic executor has been specified for the task selection logic in a state or task logic in a task.
+ *
+ * @author Liam Fallon (liam.fallon@ericsson.com)
+ */
+public class ExecutorFactoryImpl extends ExecutorFactory {
+ // Get a reference to the logger
+ private static final XLogger LOGGER = XLoggerFactory.getXLogger(ExecutorFactoryImpl.class);
+
+ // A map of logic flavours mapped to executor classes for plugins to executors for those logic flavours
+ private Map<String, Class<Executor<?, ?, ?, ?>>> taskExecutorPluginClassMap =
+ new TreeMap<String, Class<Executor<?, ?, ?, ?>>>();
+ private Map<String, Class<Executor<?, ?, ?, ?>>> taskSelectionExecutorPluginClassMap =
+ new TreeMap<String, Class<Executor<?, ?, ?, ?>>>();
+ private Map<String, Class<Executor<?, ?, ?, ?>>> stateFinalizerExecutorPluginClassMap =
+ new TreeMap<String, Class<Executor<?, ?, ?, ?>>>();
+
+ // A map of parameters for executors
+ private final Map<String, ExecutorParameters> implementationParameterMap =
+ new TreeMap<String, ExecutorParameters>();
+
+ /**
+ * Constructor, builds the class map for executors.
+ *
+ * @throws StateMachineException on plugin creation errors
+ */
+ public ExecutorFactoryImpl() throws StateMachineException {
+ final EngineParameters engineParameters = ParameterService.getParameters(EngineParameters.class);
+
+ Assertions.argumentNotNull(engineParameters, StateMachineException.class,
+ "Parameter \"engineParameters\" may not be null");
+
+ // Instantiate each executor class map entry
+ for (final Entry<String, ExecutorParameters> executorParameterEntry : engineParameters.getExecutorParameterMap()
+ .entrySet()) {
+ // Get classes for all types of executors for this logic type
+ taskExecutorPluginClassMap.put(executorParameterEntry.getKey(),
+ getExecutorPluginClass(executorParameterEntry.getValue().getTaskExecutorPluginClass()));
+ taskSelectionExecutorPluginClassMap.put(executorParameterEntry.getKey(),
+ getExecutorPluginClass(executorParameterEntry.getValue().getTaskSelectionExecutorPluginClass()));
+ stateFinalizerExecutorPluginClassMap.put(executorParameterEntry.getKey(),
+ getExecutorPluginClass(executorParameterEntry.getValue().getStateFinalizerExecutorPluginClass()));
+
+ // Save the executor implementation parameters
+ implementationParameterMap.put(executorParameterEntry.getKey(), executorParameterEntry.getValue());
+ }
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see
+ * org.onap.policy.apex.core.engine.executor.ExecutorFactory#getTaskSelectionExecutor(org.onap.policy.apex.core.
+ * model. concepts.AxState, org.onap.policy.apex.core.engine.context.Context)
+ */
+ @Override
+ public TaskSelectExecutor getTaskSelectionExecutor(final Executor<?, ?, ?, ?> parentExecutor, final AxState state,
+ final ApexInternalContext context) {
+ if (!state.checkSetTaskSelectionLogic()) {
+ return null;
+ }
+
+ // Create task selection executor
+ final TaskSelectExecutor tsExecutor =
+ (TaskSelectExecutor) createExecutor(state.getTaskSelectionLogic().getLogicFlavour(),
+ taskSelectionExecutorPluginClassMap.get(state.getTaskSelectionLogic().getLogicFlavour()),
+ TaskSelectExecutor.class);
+ tsExecutor.setParameters(implementationParameterMap.get(state.getTaskSelectionLogic().getLogicFlavour()));
+ tsExecutor.setContext(parentExecutor, state, context);
+
+ return tsExecutor;
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.onap.policy.apex.core.engine.executor.ExecutorFactory#getTaskExecutor(org.onap.policy.apex.core.model.
+ * concepts. AxTask, org.onap.policy.apex.core.engine.context.Context)
+ */
+ @Override
+ public TaskExecutor getTaskExecutor(final Executor<?, ?, ?, ?> parentExecutor, final AxTask task,
+ final ApexInternalContext context) {
+ // Create task executor
+ final TaskExecutor taskExecutor = (TaskExecutor) createExecutor(task.getTaskLogic().getLogicFlavour(),
+ taskExecutorPluginClassMap.get(task.getTaskLogic().getLogicFlavour()), TaskExecutor.class);
+ taskExecutor.setParameters(implementationParameterMap.get(task.getTaskLogic().getLogicFlavour()));
+ taskExecutor.setContext(parentExecutor, task, context);
+
+ return taskExecutor;
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see
+ * org.onap.policy.apex.core.engine.executor.ExecutorFactory#getStateFinalizerExecutor(org.onap.policy.apex.core.
+ * engine. executor.Executor, org.onap.policy.apex.core.policymodel.concepts.AxStateFinalizerLogic,
+ * org.onap.policy.apex.core.engine.context.ApexInternalContext)
+ */
+ @Override
+ public StateFinalizerExecutor getStateFinalizerExecutor(final Executor<?, ?, ?, ?> parentExecutor,
+ final AxStateFinalizerLogic logic, final ApexInternalContext context) {
+ // Create state finalizer executor
+ final StateFinalizerExecutor sfExecutor = (StateFinalizerExecutor) createExecutor(logic.getLogicFlavour(),
+ stateFinalizerExecutorPluginClassMap.get(logic.getLogicFlavour()), StateFinalizerExecutor.class);
+ sfExecutor.setParameters(implementationParameterMap.get(logic.getLogicFlavour()));
+ sfExecutor.setContext(parentExecutor, logic, context);
+
+ return sfExecutor;
+ }
+
+ /**
+ * Get an executor class for a given executor plugin class name.
+ *
+ * @param executorClassName The name of the executor plugin class
+ * @return an executor class
+ * @throws StateMachineException on plugin instantiation errors
+ */
+ @SuppressWarnings("unchecked")
+ private Class<Executor<?, ?, ?, ?>> getExecutorPluginClass(final String executorClassName)
+ throws StateMachineException {
+ // It's OK for an executor class not to be defined as long as it's not called
+ if (executorClassName == null) {
+ return null;
+ }
+
+ // Get the class for the executor using reflection
+ Class<? extends Object> executorPluginClass = null;
+ try {
+ executorPluginClass = Class.forName(executorClassName);
+ } catch (final ClassNotFoundException e) {
+ LOGGER.error("Apex executor class not found for executor plugin \"" + executorClassName + "\"", e);
+ throw new StateMachineException(
+ "Apex executor class not found for executor plugin \"" + executorClassName + "\"", e);
+ }
+
+ // Check the class is an executor
+ if (!Executor.class.isAssignableFrom(executorPluginClass)) {
+ LOGGER.error("Specified Apex executor plugin class \"" + executorClassName
+ + "\" does not implment the Executor interface");
+ throw new StateMachineException("Specified Apex executor plugin class \"" + executorClassName
+ + "\" does not implment the Executor interface");
+ }
+
+ return (Class<Executor<?, ?, ?, ?>>) executorPluginClass;
+ }
+
+ /**
+ * Get an instance of an executor plugin class of the specified type and super type.
+ *
+ * @param logicFlavour The logic flavour of the logic
+ * @param executorClass The sub-class of the executor type to be instantiated
+ * @param executorSuperClass The super type of the class of executor to be instantiated
+ * @return The instantiated class
+ */
+ private Executor<?, ?, ?, ?> createExecutor(final String logicFlavour,
+ final Class<Executor<?, ?, ?, ?>> executorClass,
+ final Class<? extends Executor<?, ?, ?, ?>> executorSuperClass) {
+ // It's OK for an executor class not to be defined but it's not all right to try and create a non-defined
+ // executor class
+ if (executorClass == null) {
+ final String errorMessage = "Executor plugin class not defined for \"" + logicFlavour
+ + "\" executor of type \"" + executorSuperClass.getCanonicalName() + "\"";
+ LOGGER.error(errorMessage);
+ throw new StateMachineRuntimeException(errorMessage);
+ }
+
+ // Create an executor for the specified logic flavour
+ Object executorObject = null;
+ try {
+ executorObject = executorClass.newInstance();
+ } catch (InstantiationException | IllegalAccessException e) {
+ final String errorMessage = "Instantiation error on \"" + logicFlavour + "\" executor of type \""
+ + executorClass.getCanonicalName() + "\"";
+ LOGGER.error(errorMessage, e);
+ throw new StateMachineRuntimeException(errorMessage, e);
+ }
+
+ // Check the class is a Task Selection Executor
+ if (!(executorSuperClass.isAssignableFrom(executorObject.getClass()))) {
+ final String errorMessage = "Executor on \"" + logicFlavour + "\" of type \"" + executorClass
+ + "\" is not an instance of \"" + executorSuperClass.getCanonicalName() + "\"";
+
+ LOGGER.error(errorMessage);
+ throw new StateMachineRuntimeException(errorMessage);
+ }
+
+ return (Executor<?, ?, ?, ?>) executorObject;
+ }
+}
diff --git a/core/core-engine/src/main/java/org/onap/policy/apex/core/engine/executor/impl/package-info.java b/core/core-engine/src/main/java/org/onap/policy/apex/core/engine/executor/impl/package-info.java
new file mode 100644
index 000000000..66e23e667
--- /dev/null
+++ b/core/core-engine/src/main/java/org/onap/policy/apex/core/engine/executor/impl/package-info.java
@@ -0,0 +1,27 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * Copyright (C) 2016-2018 Ericsson. All rights reserved.
+ * ================================================================================
+ * 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=========================================================
+ */
+
+/**
+ * Contains factories for creating executors for tasks, state fianlizers, and task selectors.
+ *
+ * @author Liam Fallon (liam.fallon@ericsson.com)
+ */
+
+package org.onap.policy.apex.core.engine.executor.impl;
diff --git a/core/core-engine/src/main/java/org/onap/policy/apex/core/engine/executor/package-info.java b/core/core-engine/src/main/java/org/onap/policy/apex/core/engine/executor/package-info.java
new file mode 100644
index 000000000..062e1ae49
--- /dev/null
+++ b/core/core-engine/src/main/java/org/onap/policy/apex/core/engine/executor/package-info.java
@@ -0,0 +1,27 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * Copyright (C) 2016-2018 Ericsson. All rights reserved.
+ * ================================================================================
+ * 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=========================================================
+ */
+
+/**
+ * Implements state, task, task selection, and state finalizer execution for the APEX engine.
+ *
+ * @author Liam Fallon (liam.fallon@ericsson.com)
+ */
+
+package org.onap.policy.apex.core.engine.executor;
diff --git a/core/core-engine/src/main/java/org/onap/policy/apex/core/engine/monitoring/EventMonitor.java b/core/core-engine/src/main/java/org/onap/policy/apex/core/engine/monitoring/EventMonitor.java
new file mode 100644
index 000000000..9710b106e
--- /dev/null
+++ b/core/core-engine/src/main/java/org/onap/policy/apex/core/engine/monitoring/EventMonitor.java
@@ -0,0 +1,114 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * Copyright (C) 2016-2018 Ericsson. All rights reserved.
+ * ================================================================================
+ * 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.monitoring;
+
+import org.onap.policy.apex.model.basicmodel.concepts.AxArtifactKey;
+import org.onap.policy.apex.model.basicmodel.concepts.AxConcept;
+import org.onap.policy.apex.model.basicmodel.concepts.AxReferenceKey;
+import org.onap.policy.apex.model.eventmodel.concepts.AxField;
+import org.slf4j.ext.XLogger;
+import org.slf4j.ext.XLoggerFactory;
+
+/**
+ * This class is used to monitor event parameter gets and sets.
+ *
+ * @author Liam Fallon (liam.fallon@ericsson.com)
+ */
+public class EventMonitor {
+ // Logger for this class
+ private static final XLogger LOGGER = XLoggerFactory.getXLogger(EventMonitor.class);
+
+ /**
+ * Monitor get on an event parameter.
+ *
+ * @param eventParameter The event parameter to monitor
+ * @param value the value of the event parameter
+ * @param userArtifactStack the keys of the artifacts using the event at the moment
+ */
+ public void monitorGet(final AxField eventParameter, final Object value, final AxConcept[] userArtifactStack) {
+ LOGGER.trace(monitor("GET", userArtifactStack, eventParameter, value));
+ }
+
+ /**
+ * Monitor set on an event parameter.
+ *
+ * @param eventParameter The event parameter to monitor
+ * @param value the value of the event parameter
+ * @param userArtifactStack the keys of the artifacts using the event at the moment
+ */
+ public void monitorSet(final AxField eventParameter, final Object value, final AxConcept[] userArtifactStack) {
+ LOGGER.trace(monitor("SET", userArtifactStack, eventParameter, value));
+ }
+
+ /**
+ * Monitor remove on an event parameter.
+ *
+ * @param eventParameter The event parameter to monitor
+ * @param removedValue the value of the event parameter
+ * @param userArtifactStack the keys of the artifacts using the event at the moment
+ */
+ public void monitorRemove(final AxField eventParameter, final Object removedValue,
+ final AxConcept[] userArtifactStack) {
+ LOGGER.trace(monitor("REMOVE", userArtifactStack, eventParameter, removedValue));
+ }
+
+ /**
+ * Monitor the user artifact stack.
+ *
+ * @param preamble the preamble
+ * @param userArtifactStack The user stack to print
+ * @param eventParameter The event parameter that we are monitoring
+ * @param value The value of the target object
+ * @return the string
+ */
+ private String monitor(final String preamble, final AxConcept[] userArtifactStack, final AxField eventParameter,
+ final Object value) {
+ final StringBuilder builder = new StringBuilder();
+
+ builder.append(preamble);
+ builder.append(",[");
+
+ if (userArtifactStack != null) {
+ boolean first = true;
+ for (final AxConcept stackKey : userArtifactStack) {
+ if (first) {
+ first = false;
+ } else {
+ builder.append(',');
+ }
+ if (stackKey instanceof AxArtifactKey) {
+ builder.append(((AxArtifactKey) stackKey).getID());
+ } else if (stackKey instanceof AxReferenceKey) {
+ builder.append(((AxReferenceKey) stackKey).getID());
+ } else {
+ builder.append(stackKey.toString());
+ }
+ }
+ }
+ builder.append("],");
+
+ builder.append(eventParameter.toString());
+ builder.append("=");
+ builder.append(value);
+
+ return builder.toString();
+ }
+}
diff --git a/core/core-engine/src/main/java/org/onap/policy/apex/core/engine/monitoring/package-info.java b/core/core-engine/src/main/java/org/onap/policy/apex/core/engine/monitoring/package-info.java
new file mode 100644
index 000000000..530041a23
--- /dev/null
+++ b/core/core-engine/src/main/java/org/onap/policy/apex/core/engine/monitoring/package-info.java
@@ -0,0 +1,28 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * Copyright (C) 2016-2018 Ericsson. All rights reserved.
+ * ================================================================================
+ * 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=========================================================
+ */
+
+/**
+ * Provides monitoring of APEX policy execution. It monitors events as they trigger Apex policies, pass between the
+ * various states of a policy, and are emitted by a policy.
+ *
+ * @author Liam Fallon (liam.fallon@ericsson.com)
+ */
+
+package org.onap.policy.apex.core.engine.monitoring;
diff --git a/core/core-engine/src/main/java/org/onap/policy/apex/core/engine/package-info.java b/core/core-engine/src/main/java/org/onap/policy/apex/core/engine/package-info.java
new file mode 100644
index 000000000..a836cd949
--- /dev/null
+++ b/core/core-engine/src/main/java/org/onap/policy/apex/core/engine/package-info.java
@@ -0,0 +1,30 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * Copyright (C) 2016-2018 Ericsson. All rights reserved.
+ * ================================================================================
+ * 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=========================================================
+ */
+
+/**
+ * Provides the core engine implementation for Apex. It builds a state machine for execution for each policy in its
+ * policy model. It provides the infrastructure for running policies and their states, for running executors provided by
+ * executor plugins, for supplying events and context to running policies, states, and tasks, and for handling event
+ * transmission into and out of policies and between states in policies.
+ *
+ * @author Liam Fallon (liam.fallon@ericsson.com)
+ */
+
+package org.onap.policy.apex.core.engine;