2 * ============LICENSE_START=======================================================
3 * Copyright (C) 2016-2018 Ericsson. All rights reserved.
4 * Modifications Copyright (C) 2019-2022 Nordix Foundation.
5 * Modifications Copyright (C) 2020-2021 Bell Canada. All rights reserved.
6 * Modifications Copyright (C) 2021 AT&T Intellectual Property. All rights reserved.
7 * ================================================================================
8 * Licensed under the Apache License, Version 2.0 (the "License");
9 * you may not use this file except in compliance with the License.
10 * You may obtain a copy of the License at
12 * http://www.apache.org/licenses/LICENSE-2.0
14 * Unless required by applicable law or agreed to in writing, software
15 * distributed under the License is distributed on an "AS IS" BASIS,
16 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17 * See the License for the specific language governing permissions and
18 * limitations under the License.
20 * SPDX-License-Identifier: Apache-2.0
21 * ============LICENSE_END=========================================================
24 package org.onap.policy.apex.service.parameters;
26 import com.google.gson.GsonBuilder;
27 import com.google.gson.JsonArray;
28 import com.google.gson.JsonElement;
29 import com.google.gson.JsonObject;
30 import java.nio.file.Files;
31 import java.nio.file.Paths;
33 import java.util.Map.Entry;
34 import java.util.Optional;
35 import org.onap.policy.apex.core.engine.EngineParameters;
36 import org.onap.policy.apex.model.basicmodel.concepts.ApexException;
37 import org.onap.policy.apex.service.engine.main.ApexCommandLineArguments;
38 import org.onap.policy.apex.service.parameters.carriertechnology.CarrierTechnologyParameters;
39 import org.onap.policy.apex.service.parameters.carriertechnology.CarrierTechnologyParametersJsonAdapter;
40 import org.onap.policy.apex.service.parameters.engineservice.EngineServiceParametersJsonAdapter;
41 import org.onap.policy.apex.service.parameters.eventprotocol.EventProtocolParameters;
42 import org.onap.policy.apex.service.parameters.eventprotocol.EventProtocolParametersJsonAdapter;
43 import org.onap.policy.common.parameters.ParameterException;
44 import org.onap.policy.common.parameters.ParameterService;
45 import org.onap.policy.common.parameters.ValidationResult;
46 import org.onap.policy.common.utils.coder.CoderException;
47 import org.onap.policy.common.utils.coder.StandardCoder;
48 import org.onap.policy.models.tosca.authorative.concepts.ToscaServiceTemplate;
49 import org.slf4j.ext.XLogger;
50 import org.slf4j.ext.XLoggerFactory;
53 * This class handles reading, parsing and validating of Apex parameters from JSON files.
55 * @author Liam Fallon (liam.fallon@ericsson.com)
57 public class ApexParameterHandler {
58 private static final String EVENT_OUTPUT_PARAMETERS = "eventOutputParameters";
60 private static final String EVENT_INPUT_PARAMETERS = "eventInputParameters";
62 private static final String ENGINE_SERVICE_PARAMETERS = "engineServiceParameters";
64 private static final XLogger LOGGER = XLoggerFactory.getXLogger(ApexParameterHandler.class);
66 private static final String POLICY_TYPE_IMPL = "policy_type_impl";
67 private static final String APEX_POLICY_MODEL = "apexPolicyModel";
68 private static final String METADATA_SET = "metadataSet";
70 private String policyModel;
71 private String apexConfig;
74 * Read the parameters from the parameter file.
76 * @param arguments the arguments passed to Apex
77 * @return the parameters read from the configuration file
78 * @throws ParameterException on parameter exceptions
80 public ApexParameters getParameters(final ApexCommandLineArguments arguments) throws ParameterException {
82 ApexParameters parameters = null;
83 String toscaPolicyFilePath = arguments.getToscaPolicyFilePath();
84 // Read the parameters
86 parseConfigAndModel(toscaPolicyFilePath);
87 // Register the adapters for our carrier technologies and event protocols with GSON
89 final var gson = new GsonBuilder()
90 .registerTypeAdapter(EngineParameters.class,
91 new EngineServiceParametersJsonAdapter())
92 .registerTypeAdapter(CarrierTechnologyParameters.class,
93 new CarrierTechnologyParametersJsonAdapter())
94 .registerTypeAdapter(EventProtocolParameters.class,
95 new EventProtocolParametersJsonAdapter())
98 parameters = gson.fromJson(apexConfig, ApexParameters.class);
99 } catch (final Exception e) {
100 final String errorMessage = "error reading parameters from \"" + toscaPolicyFilePath + "\"\n" + "("
101 + e.getClass().getSimpleName() + "):" + e.getMessage();
102 throw new ParameterException(errorMessage, e);
105 // The JSON processing returns null if there is an empty file
106 if (parameters == null) {
107 final String errorMessage = "no parameters found in \"" + toscaPolicyFilePath + "\"";
108 throw new ParameterException(errorMessage);
111 if (null != parameters.getEngineServiceParameters()) {
112 parameters.getEngineServiceParameters().setPolicyModel(policyModel);
115 // Validate the parameters
116 final ValidationResult validationResult = parameters.validate();
117 if (!validationResult.isValid()) {
118 String returnMessage = "validation error(s) on parameters from \"" + toscaPolicyFilePath + "\"\n";
119 returnMessage += validationResult.getResult();
120 throw new ParameterException(returnMessage);
123 if (!validationResult.isClean()) {
124 String returnMessage = "validation messages(s) on parameters from \"" + toscaPolicyFilePath + "\"\n";
125 returnMessage += validationResult.getResult();
127 LOGGER.info(returnMessage);
134 * Register all the incoming parameters with the parameter service.
136 * @param parameters The parameters to register
138 public void registerParameters(ApexParameters parameters) {
139 ParameterService.register(parameters);
140 ParameterService.register(parameters.getEngineServiceParameters());
141 ParameterService.register(parameters.getEngineServiceParameters().getEngineParameters());
142 ParameterService.register(parameters.getEngineServiceParameters().getEngineParameters().getContextParameters());
143 ParameterService.register(parameters.getEngineServiceParameters().getEngineParameters().getContextParameters()
144 .getSchemaParameters());
145 ParameterService.register(parameters.getEngineServiceParameters().getEngineParameters().getContextParameters()
146 .getDistributorParameters());
147 ParameterService.register(parameters.getEngineServiceParameters().getEngineParameters().getContextParameters()
148 .getLockManagerParameters());
149 ParameterService.register(parameters.getEngineServiceParameters().getEngineParameters().getContextParameters()
150 .getPersistorParameters());
153 private void parseConfigAndModel(final String toscaPolicyFilePath) throws ApexException {
156 final var standardCoder = new StandardCoder();
157 var apexConfigJsonObject = new JsonObject();
159 var toscaServiceTemplate = standardCoder
160 .decode(Files.readString(Paths.get(toscaPolicyFilePath)), ToscaServiceTemplate.class);
161 for (Entry<String, Object> property : toscaServiceTemplate.getToscaTopologyTemplate().getPolicies().get(0)
162 .entrySet().iterator().next().getValue().getProperties().entrySet()) {
163 JsonElement body = null;
164 if ("javaProperties".equals(property.getKey())) {
165 body = standardCoder.convert(property.getValue(), JsonArray.class);
166 } else if (EVENT_INPUT_PARAMETERS.equals(property.getKey())
167 || ENGINE_SERVICE_PARAMETERS.equals(property.getKey())
168 || EVENT_OUTPUT_PARAMETERS.equals(property.getKey())) {
169 body = standardCoder.convert(property.getValue(), JsonObject.class);
170 if (ENGINE_SERVICE_PARAMETERS.equals(property.getKey())) {
171 policyModel = extractPolicyModel(standardCoder, body);
174 apexConfigJsonObject.add(property.getKey(), body);
176 apexConfig = standardCoder.encode(apexConfigJsonObject);
178 // populate policyModel from metadata if present
179 Optional<Map<String, Object>> metadata =
180 Optional.ofNullable(toscaServiceTemplate.getToscaTopologyTemplate().getPolicies().get(0)
181 .entrySet().iterator().next().getValue().getMetadata());
182 if (metadata.isPresent() && metadata.get().containsKey(METADATA_SET)) {
183 JsonElement body = standardCoder.convert(metadata.get(), JsonObject.class);
184 policyModel = extractPolicyModel(standardCoder, body);
186 } catch (Exception e) {
187 throw new ApexException("Parsing config and model from the tosca policy failed.", e);
191 private String extractPolicyModel(StandardCoder standardCoder, JsonElement body) throws CoderException {
192 JsonElement policyTypeImplObject = null;
193 // Check for "policy_type_impl, if not present check for "metadataSet"
194 if (body.getAsJsonObject().has(POLICY_TYPE_IMPL)) {
195 policyTypeImplObject = ((JsonObject) body).get(POLICY_TYPE_IMPL);
196 } else if (body.getAsJsonObject().has(METADATA_SET)) {
197 policyTypeImplObject = ((JsonObject) body).get(METADATA_SET);
199 if (null == policyTypeImplObject) {
203 // "policy_type_impl" found
204 if (policyTypeImplObject instanceof JsonObject) {
206 // Check for "apexPolicyModel", this is used to encapsulate policy models sometimes
207 JsonElement policyModelObject = ((JsonObject) policyTypeImplObject).get(APEX_POLICY_MODEL);
209 if (policyModelObject != null) {
210 // Policy model encased in an "apexPolicyModel" object
211 return standardCoder.encode(policyModelObject);
214 return standardCoder.encode(policyTypeImplObject);
217 return policyTypeImplObject.getAsString();