1 .. This work is licensed under a
2 .. Creative Commons Attribution 4.0 International License.
3 .. http://creativecommons.org/licenses/by/4.0
5 .. _property-configuration:
7 Property-configuration mechanisms
8 #################################
13 This article explains how to implement handling and validation of common parameter into the Policy Framework Components.
15 Not Spring boot framework
16 *************************
17 The application should have a ParameterHandler class to support the map values from Json to a POJO, so it should be load the file, convert it performing all type conversion.
19 The code below shown an example of ParameterHandler:
23 public class PapParameterHandler {
25 private static final Logger LOGGER = LoggerFactory.getLogger(PapParameterHandler.class);
27 private static final Coder CODER = new StandardCoder();
29 public PapParameterGroup getParameters(final PapCommandLineArguments arguments) throws PolicyPapException {
30 PapParameterGroup papParameterGroup = null;
33 var file = new File(arguments.getFullConfigurationFilePath());
34 papParameterGroup = CODER.decode(file, PapParameterGroup.class);
35 } catch (final CoderException e) {
36 final String errorMessage = "error reading parameters from \"" + arguments.getConfigurationFilePath()
37 + "\"\n" + "(" + e.getClass().getSimpleName() + ")";
38 throw new PolicyPapException(errorMessage, e);
41 if (papParameterGroup == null) {
42 final String errorMessage = "no parameters found in \"" + arguments.getConfigurationFilePath() + "\"";
43 LOGGER.error(errorMessage);
44 throw new PolicyPapException(errorMessage);
47 final ValidationResult validationResult = papParameterGroup.validate();
48 if (!validationResult.isValid()) {
49 String returnMessage =
50 "validation error(s) on parameters from \"" + arguments.getConfigurationFilePath() + "\"\n";
51 returnMessage += validationResult.getResult();
53 LOGGER.error(returnMessage);
54 throw new PolicyPapException(returnMessage);
57 return papParameterGroup;
62 The POJO have to implement **org.onap.policy.common.parameters.ParameterGroup** interface or eventually extend **org.onap.policy.common.parameters.ParameterGroupImpl**. The last one already implements **validate()** method that performs error checking using validation **org.onap.policy.common.parameters.annotations**.
64 The code below shown an example of POJO:
71 public class PapParameterGroup extends ParameterGroupImpl {
73 private RestServerParameters restServerParameters;
75 private PdpParameters pdpParameters;
77 private PolicyModelsProviderParameters databaseProviderParameters;
78 private boolean savePdpStatisticsInDb;
80 private TopicParameterGroup topicParameterGroup;
82 private List<@NotNull @Valid RestClientParameters> healthCheckRestClientParameters;
84 public PapParameterGroup(final String name) {
90 The code shows below, is an example of Unit Test validation of the POJO PapParameterGroup:
94 private static final Coder coder = new StandardCoder();
97 void testPapParameterGroup_NullName() throws Exception {
98 String json = commonTestData.getPapParameterGroupAsString(1).replace("\"PapGroup\"", "null");
99 final PapParameterGroup papParameters = coder.decode(json, PapParameterGroup.class);
100 final ValidationResult validationResult = papParameters.validate();
101 assertFalse(validationResult.isValid());
102 assertEquals(null, papParameters.getName());
103 assertThat(validationResult.getResult()).contains("is null");
107 Using Spring boot framework
108 ***************************
109 Spring loads automatically the property file and put it available under the **org.springframework.core.env.Environment** Spring component.
113 A component can use Environment component directly.
115 Environment component is not a good approach because there is not type conversion and error checking, but it could be useful when the name of the property you need to access changes dynamically.
120 @RequiredArgsConstructor
121 public class Example {
123 private Environment env;
126 public void method(String pathPropertyName) {
128 String path = env.getProperty(pathPropertyName);
132 Annotation-based Spring configuration
133 +++++++++++++++++++++++++++++++++++++
134 All annotation-based Spring configurations support the Spring Expression Language (SpEL), a powerful expression language that supports querying and manipulating an object graph at runtime.
135 A documentation about SpEL could be found here: https://docs.spring.io/spring-framework/docs/3.0.x/reference/expressions.html.
137 A component can use **org.springframework.beans.factory.annotation.Value**, which reads from properties, performs a type conversion and injects the value into the filed. There is not error checking, but it can assign default value if the property is not defined.
141 @Value("${security.enable-csrf:true}")
142 private boolean csrfEnabled = true;
145 The code below shows how to inject a value of a property into @Scheduled configuration.
150 fixedRateString = "${runtime.participantParameters.heartBeatMs}",
151 initialDelayString = "${runtime.participantParameters.heartBeatMs}")
152 public void schedule() {
155 ConfigurationProperties
156 +++++++++++++++++++++++
157 @ConfigurationProperties can be used to map values from .properties( .yml also supported) to a POJO. It performs all type conversion and error checking using validation **javax.validation.constraints**.
164 @ConfigurationProperties(prefix = "runtime")
165 public class ClRuntimeParameterGroup {
167 private long heartBeatMs;
171 private long reportingTimeIntervalMs;
175 private ParticipantUpdateParameters updateParameters;
178 private String description;
181 In a scenario that we need to include into a POJO shown before, a class that implement **ParameterGroup** interface, we need to add the **org.onap.policy.common.parameters.validation.ParameterGroupConstraint** annotation. That annotation is configured to use **ParameterGroupValidator** that handles the conversion of a **org.onap.policy.common.parameters.BeanValidationResult** to a Spring validation.
183 The code below shown how to add TopicParameterGroup parameter into ClRuntimeParameterGroup:
188 @ParameterGroupConstraint
189 private TopicParameterGroup topicParameterGroup;
192 A bean configured with ConfigurationProperties, is automatically a Spring component and could be injected into other Spring components. The code below shown an example:
197 @RequiredArgsConstructor
198 public class Example {
200 private ClRuntimeParameterGroup parameters;
203 public void method() {
205 long heartBeatMs = parameters.getHeartBeatMs();
209 The code shows below, is an example of Unit Test validation of the POJO ClRuntimeParameterGroup:
213 private ValidatorFactory validatorFactory = Validation.buildDefaultValidatorFactory();
216 void testParameters_NullTopicParameterGroup() {
217 final ClRuntimeParameterGroup parameters = CommonTestData.geParameterGroup();
218 parameters.setTopicParameterGroup(null);
219 assertThat(validatorFactory.getValidator().validate(parameters)).isNotEmpty();