2e97c54fc188a840bcb5b7d21dfa74f4e58f5582
[policy/apex-pdp.git] /
1 /*-
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
11  *
12  *      http://www.apache.org/licenses/LICENSE-2.0
13  *
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.
19  *
20  * SPDX-License-Identifier: Apache-2.0
21  * ============LICENSE_END=========================================================
22  */
23
24 package org.onap.policy.apex.service.parameters;
25
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;
32 import java.util.Map.Entry;
33 import org.onap.policy.apex.core.engine.EngineParameters;
34 import org.onap.policy.apex.model.basicmodel.concepts.ApexException;
35 import org.onap.policy.apex.service.engine.main.ApexCommandLineArguments;
36 import org.onap.policy.apex.service.parameters.carriertechnology.CarrierTechnologyParameters;
37 import org.onap.policy.apex.service.parameters.carriertechnology.CarrierTechnologyParametersJsonAdapter;
38 import org.onap.policy.apex.service.parameters.engineservice.EngineServiceParametersJsonAdapter;
39 import org.onap.policy.apex.service.parameters.eventprotocol.EventProtocolParameters;
40 import org.onap.policy.apex.service.parameters.eventprotocol.EventProtocolParametersJsonAdapter;
41 import org.onap.policy.common.parameters.ParameterException;
42 import org.onap.policy.common.parameters.ParameterService;
43 import org.onap.policy.common.parameters.ValidationResult;
44 import org.onap.policy.common.utils.coder.CoderException;
45 import org.onap.policy.common.utils.coder.StandardCoder;
46 import org.onap.policy.models.tosca.authorative.concepts.ToscaServiceTemplate;
47 import org.slf4j.ext.XLogger;
48 import org.slf4j.ext.XLoggerFactory;
49
50 /**
51  * This class handles reading, parsing and validating of Apex parameters from JSON files.
52  *
53  * @author Liam Fallon (liam.fallon@ericsson.com)
54  */
55 public class ApexParameterHandler {
56     private static final String EVENT_OUTPUT_PARAMETERS = "eventOutputParameters";
57
58     private static final String EVENT_INPUT_PARAMETERS = "eventInputParameters";
59
60     private static final String ENGINE_SERVICE_PARAMETERS = "engineServiceParameters";
61
62     private static final XLogger LOGGER = XLoggerFactory.getXLogger(ApexParameterHandler.class);
63
64     private static final String POLICY_TYPE_IMPL = "policy_type_impl";
65     private static final String APEX_POLICY_MODEL = "apexPolicyModel";
66
67     private String policyModel;
68     private String apexConfig;
69
70     /**
71      * Read the parameters from the parameter file.
72      *
73      * @param arguments the arguments passed to Apex
74      * @return the parameters read from the configuration file
75      * @throws ParameterException on parameter exceptions
76      */
77     public ApexParameters getParameters(final ApexCommandLineArguments arguments) throws ParameterException {
78
79         ApexParameters parameters = null;
80         String toscaPolicyFilePath = arguments.getToscaPolicyFilePath();
81         // Read the parameters
82         try {
83             parseConfigAndModel(toscaPolicyFilePath);
84             // Register the adapters for our carrier technologies and event protocols with GSON
85             // @formatter:off
86             final var gson = new GsonBuilder()
87                 .registerTypeAdapter(EngineParameters.class,
88                     new EngineServiceParametersJsonAdapter())
89                 .registerTypeAdapter(CarrierTechnologyParameters.class,
90                     new CarrierTechnologyParametersJsonAdapter())
91                 .registerTypeAdapter(EventProtocolParameters.class,
92                     new EventProtocolParametersJsonAdapter())
93                 .create();
94             // @formatter:on
95             parameters = gson.fromJson(apexConfig, ApexParameters.class);
96         } catch (final Exception e) {
97             final String errorMessage = "error reading parameters from \"" + toscaPolicyFilePath + "\"\n" + "("
98                 + e.getClass().getSimpleName() + "):" + e.getMessage();
99             throw new ParameterException(errorMessage, e);
100         }
101
102         // The JSON processing returns null if there is an empty file
103         if (parameters == null) {
104             final String errorMessage = "no parameters found in \"" + toscaPolicyFilePath + "\"";
105             throw new ParameterException(errorMessage);
106         }
107
108         if (null != parameters.getEngineServiceParameters()) {
109             parameters.getEngineServiceParameters().setPolicyModel(policyModel);
110         }
111
112         // Validate the parameters
113         final ValidationResult validationResult = parameters.validate();
114         if (!validationResult.isValid()) {
115             String returnMessage = "validation error(s) on parameters from \"" + toscaPolicyFilePath + "\"\n";
116             returnMessage += validationResult.getResult();
117             throw new ParameterException(returnMessage);
118         }
119
120         if (!validationResult.isClean()) {
121             String returnMessage = "validation messages(s) on parameters from \"" + toscaPolicyFilePath + "\"\n";
122             returnMessage += validationResult.getResult();
123
124             LOGGER.info(returnMessage);
125         }
126
127         return parameters;
128     }
129
130     /**
131      * Register all the incoming parameters with the parameter service.
132      *
133      * @param parameters The parameters to register
134      */
135     public void registerParameters(ApexParameters parameters) {
136         ParameterService.register(parameters);
137         ParameterService.register(parameters.getEngineServiceParameters());
138         ParameterService.register(parameters.getEngineServiceParameters().getEngineParameters());
139         ParameterService.register(parameters.getEngineServiceParameters().getEngineParameters().getContextParameters());
140         ParameterService.register(parameters.getEngineServiceParameters().getEngineParameters().getContextParameters()
141             .getSchemaParameters());
142         ParameterService.register(parameters.getEngineServiceParameters().getEngineParameters().getContextParameters()
143             .getDistributorParameters());
144         ParameterService.register(parameters.getEngineServiceParameters().getEngineParameters().getContextParameters()
145             .getLockManagerParameters());
146         ParameterService.register(parameters.getEngineServiceParameters().getEngineParameters().getContextParameters()
147             .getPersistorParameters());
148     }
149
150     private void parseConfigAndModel(final String toscaPolicyFilePath) throws ApexException {
151         policyModel = null;
152         apexConfig = null;
153         final var standardCoder = new StandardCoder();
154         var apexConfigJsonObject = new JsonObject();
155         try {
156             var toscaServiceTemplate = standardCoder
157                 .decode(Files.readString(Paths.get(toscaPolicyFilePath)), ToscaServiceTemplate.class);
158             for (Entry<String, Object> property : toscaServiceTemplate.getToscaTopologyTemplate().getPolicies().get(0)
159                 .entrySet().iterator().next().getValue().getProperties().entrySet()) {
160                 JsonElement body = null;
161                 if ("javaProperties".equals(property.getKey())) {
162                     body = standardCoder.convert(property.getValue(), JsonArray.class);
163                 } else if (EVENT_INPUT_PARAMETERS.equals(property.getKey())
164                     || ENGINE_SERVICE_PARAMETERS.equals(property.getKey())
165                     || EVENT_OUTPUT_PARAMETERS.equals(property.getKey())) {
166                     body = standardCoder.convert(property.getValue(), JsonObject.class);
167                     if (ENGINE_SERVICE_PARAMETERS.equals(property.getKey())) {
168                         policyModel = extractPolicyModel(standardCoder, body);
169                     }
170                 }
171                 apexConfigJsonObject.add(property.getKey(), body);
172             }
173             apexConfig = standardCoder.encode(apexConfigJsonObject);
174         } catch (Exception e) {
175             throw new ApexException("Parsing config and model from the tosca policy failed.", e);
176         }
177     }
178
179     private String extractPolicyModel(StandardCoder standardCoder, JsonElement body) throws CoderException {
180         // Check for "policy_type_impl"
181         JsonElement policyTypeImplObject = ((JsonObject) body).get(POLICY_TYPE_IMPL);
182         if (null == policyTypeImplObject) {
183             return null;
184         }
185
186         // "policy_type_impl" found
187         if (policyTypeImplObject instanceof JsonObject) {
188
189             // Check for "apexPolicyModel", this is used to encapsulate policy models sometimes
190             JsonElement policyModelObject = ((JsonObject) policyTypeImplObject).get(APEX_POLICY_MODEL);
191
192             if (policyModelObject != null) {
193                 // Policy model encased in an "apexPolicyModel" object
194                 return standardCoder.encode(policyModelObject);
195             } else {
196                 // No encasement
197                 return standardCoder.encode(policyTypeImplObject);
198             }
199         } else {
200             return policyTypeImplObject.getAsString();
201         }
202     }
203 }