Changes for checkstyle 8.32
[policy/apex-pdp.git] / core / core-engine / src / main / java / org / onap / policy / apex / core / engine / executor / impl / ExecutorFactoryImpl.java
1 /*-
2  * ============LICENSE_START=======================================================
3  *  Copyright (C) 2016-2018 Ericsson. All rights reserved.
4  *  Modifications Copyright (C) 2019-2020 Nordix Foundation.
5  * ================================================================================
6  * Licensed under the Apache License, Version 2.0 (the "License");
7  * you may not use this file except in compliance with the License.
8  * You may obtain a copy of the License at
9  *
10  *      http://www.apache.org/licenses/LICENSE-2.0
11  *
12  * Unless required by applicable law or agreed to in writing, software
13  * distributed under the License is distributed on an "AS IS" BASIS,
14  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15  * See the License for the specific language governing permissions and
16  * limitations under the License.
17  *
18  * SPDX-License-Identifier: Apache-2.0
19  * ============LICENSE_END=========================================================
20  */
21
22 package org.onap.policy.apex.core.engine.executor.impl;
23
24 import java.util.Map;
25 import java.util.Map.Entry;
26 import java.util.TreeMap;
27 import org.onap.policy.apex.core.engine.EngineParameterConstants;
28 import org.onap.policy.apex.core.engine.EngineParameters;
29 import org.onap.policy.apex.core.engine.ExecutorParameters;
30 import org.onap.policy.apex.core.engine.context.ApexInternalContext;
31 import org.onap.policy.apex.core.engine.executor.Executor;
32 import org.onap.policy.apex.core.engine.executor.ExecutorFactory;
33 import org.onap.policy.apex.core.engine.executor.StateFinalizerExecutor;
34 import org.onap.policy.apex.core.engine.executor.TaskExecutor;
35 import org.onap.policy.apex.core.engine.executor.TaskSelectExecutor;
36 import org.onap.policy.apex.core.engine.executor.exception.StateMachineException;
37 import org.onap.policy.apex.core.engine.executor.exception.StateMachineRuntimeException;
38 import org.onap.policy.apex.model.policymodel.concepts.AxState;
39 import org.onap.policy.apex.model.policymodel.concepts.AxStateFinalizerLogic;
40 import org.onap.policy.apex.model.policymodel.concepts.AxTask;
41 import org.onap.policy.common.parameters.ParameterService;
42 import org.onap.policy.common.utils.validation.Assertions;
43 import org.slf4j.ext.XLogger;
44 import org.slf4j.ext.XLoggerFactory;
45
46 /**
47  * The Class ExecutorFactoryImpl is a factory class that returns task selection logic and task logic executors depending
48  * on the type of logic executor has been specified for the task selection logic in a state or task logic in a task.
49  *
50  * @author Liam Fallon (liam.fallon@ericsson.com)
51  */
52 public class ExecutorFactoryImpl implements ExecutorFactory {
53     // Get a reference to the logger
54     private static final XLogger LOGGER = XLoggerFactory.getXLogger(ExecutorFactoryImpl.class);
55
56     private final EngineParameters engineParameters;
57     // A map of logic flavours mapped to executor classes for plugins to executors for those logic flavours
58     private Map<String, Class<Executor<?, ?, ?, ?>>> taskExecutorPluginClassMap = new TreeMap<>();
59     private Map<String, Class<Executor<?, ?, ?, ?>>> taskSelectionExecutorPluginClassMap = new TreeMap<>();
60     private Map<String, Class<Executor<?, ?, ?, ?>>> stateFinalizerExecutorPluginClassMap = new TreeMap<>();
61
62     // A map of parameters for executors
63     private final Map<String, ExecutorParameters> implementationParameterMap = new TreeMap<>();
64
65     /**
66      * Constructor, builds the class map for executors.
67      *
68      * @throws StateMachineException on plugin creation errors
69      */
70     public ExecutorFactoryImpl() throws StateMachineException {
71         engineParameters = ParameterService.get(EngineParameterConstants.MAIN_GROUP_NAME);
72
73         Assertions.argumentOfClassNotNull(engineParameters, StateMachineException.class,
74                 "Parameter \"engineParameters\" may not be null");
75
76         // Instantiate each executor class map entry
77         for (final Entry<String, ExecutorParameters> executorParameterEntry : engineParameters.getExecutorParameterMap()
78                 .entrySet()) {
79             // Get classes for all types of executors for this logic type
80             taskExecutorPluginClassMap.put(executorParameterEntry.getKey(),
81                     getExecutorPluginClass(executorParameterEntry.getValue().getTaskExecutorPluginClass()));
82             taskSelectionExecutorPluginClassMap.put(executorParameterEntry.getKey(),
83                     getExecutorPluginClass(executorParameterEntry.getValue().getTaskSelectionExecutorPluginClass()));
84             stateFinalizerExecutorPluginClassMap.put(executorParameterEntry.getKey(),
85                     getExecutorPluginClass(executorParameterEntry.getValue().getStateFinalizerExecutorPluginClass()));
86
87             // Save the executor implementation parameters
88             implementationParameterMap.put(executorParameterEntry.getKey(), executorParameterEntry.getValue());
89         }
90     }
91
92     /**
93      * {@inheritDoc}.
94      */
95     @Override
96     public TaskSelectExecutor getTaskSelectionExecutor(final Executor<?, ?, ?, ?> parentExecutor, final AxState state,
97             final ApexInternalContext context) {
98         if (!state.checkSetTaskSelectionLogic()) {
99             return null;
100         }
101
102         // Create task selection executor
103         final TaskSelectExecutor tsExecutor =
104                 (TaskSelectExecutor) createExecutor(state.getTaskSelectionLogic().getLogicFlavour(),
105                         taskSelectionExecutorPluginClassMap.get(state.getTaskSelectionLogic().getLogicFlavour()),
106                         TaskSelectExecutor.class);
107         tsExecutor.setParameters(implementationParameterMap.get(state.getTaskSelectionLogic().getLogicFlavour()));
108         tsExecutor.setContext(parentExecutor, state, context);
109
110         return tsExecutor;
111     }
112
113     /**
114      * {@inheritDoc}.
115      */
116     @Override
117     public TaskExecutor getTaskExecutor(final Executor<?, ?, ?, ?> parentExecutor, final AxTask task,
118             final ApexInternalContext context) {
119         // Create task executor
120         final TaskExecutor taskExecutor = (TaskExecutor) createExecutor(task.getTaskLogic().getLogicFlavour(),
121                 taskExecutorPluginClassMap.get(task.getTaskLogic().getLogicFlavour()), TaskExecutor.class);
122         taskExecutor.setParameters(implementationParameterMap.get(task.getTaskLogic().getLogicFlavour()));
123         taskExecutor.setContext(parentExecutor, task, context);
124         taskExecutor.updateTaskParameters(engineParameters.getTaskParameters());
125         return taskExecutor;
126     }
127
128     /**
129      * {@inheritDoc}.
130      */
131     @Override
132     public StateFinalizerExecutor getStateFinalizerExecutor(final Executor<?, ?, ?, ?> parentExecutor,
133             final AxStateFinalizerLogic logic, final ApexInternalContext context) {
134         // Create state finalizer executor
135         final StateFinalizerExecutor sfExecutor = (StateFinalizerExecutor) createExecutor(logic.getLogicFlavour(),
136                 stateFinalizerExecutorPluginClassMap.get(logic.getLogicFlavour()), StateFinalizerExecutor.class);
137         sfExecutor.setParameters(implementationParameterMap.get(logic.getLogicFlavour()));
138         sfExecutor.setContext(parentExecutor, logic, context);
139
140         return sfExecutor;
141     }
142
143     /**
144      * Get an executor class for a given executor plugin class name.
145      *
146      * @param executorClassName The name of the executor plugin class
147      * @return an executor class
148      * @throws StateMachineException on plugin instantiation errors
149      */
150     @SuppressWarnings("unchecked")
151     private Class<Executor<?, ?, ?, ?>> getExecutorPluginClass(final String executorClassName)
152             throws StateMachineException {
153         // It's OK for an executor class not to be defined as long as it's not called
154         if (executorClassName == null) {
155             return null;
156         }
157
158         // Get the class for the executor using reflection
159         Class<? extends Object> executorPluginClass = null;
160         try {
161             executorPluginClass = Class.forName(executorClassName);
162         } catch (final ClassNotFoundException e) {
163             LOGGER.error("Apex executor class not found for executor plugin \"" + executorClassName + "\"", e);
164             throw new StateMachineException(
165                     "Apex executor class not found for executor plugin \"" + executorClassName + "\"", e);
166         }
167
168         // Check the class is an executor
169         if (!Executor.class.isAssignableFrom(executorPluginClass)) {
170             LOGGER.error("Specified Apex executor plugin class \"{}\" does not implment the Executor interface",
171                     executorClassName);
172             throw new StateMachineException("Specified Apex executor plugin class \"" + executorClassName
173                     + "\" does not implment the Executor interface");
174         }
175
176         return (Class<Executor<?, ?, ?, ?>>) executorPluginClass;
177     }
178
179     /**
180      * Get an instance of an executor plugin class of the specified type and super type.
181      *
182      * @param logicFlavour The logic flavour of the logic
183      * @param executorClass The sub-class of the executor type to be instantiated
184      * @param executorSuperClass The super type of the class of executor to be instantiated
185      * @return The instantiated class
186      */
187     private Executor<?, ?, ?, ?> createExecutor(final String logicFlavour,
188             final Class<Executor<?, ?, ?, ?>> executorClass,
189             final Class<? extends Executor<?, ?, ?, ?>> executorSuperClass) {
190         // It's OK for an executor class not to be defined but it's not all right to try and create
191         // a non-defined
192         // executor class
193         if (executorClass == null) {
194             final String errorMessage = "Executor plugin class not defined for \"" + logicFlavour
195                     + "\" executor of type \"" + executorSuperClass.getName() + "\"";
196             LOGGER.error(errorMessage);
197             throw new StateMachineRuntimeException(errorMessage);
198         }
199
200         // Create an executor for the specified logic flavour
201         Object executorObject = null;
202         try {
203             executorObject = executorClass.getDeclaredConstructor().newInstance();
204         } catch (final Exception e) {
205             final String errorMessage = "Instantiation error on \"" + logicFlavour + "\" executor of type \""
206                     + executorClass.getName() + "\"";
207             LOGGER.error(errorMessage, e);
208             throw new StateMachineRuntimeException(errorMessage, e);
209         }
210
211         // Check the class is the correct type of executor
212         if (!(executorSuperClass.isAssignableFrom(executorObject.getClass()))) {
213             final String errorMessage = "Executor on \"" + logicFlavour + "\" of type \"" + executorClass
214                     + "\" is not an instance of \"" + executorSuperClass.getName() + "\"";
215
216             LOGGER.error(errorMessage);
217             throw new StateMachineRuntimeException(errorMessage);
218         }
219
220         return (Executor<?, ?, ?, ?>) executorObject;
221     }
222 }