Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

This article explains how to implement handling and validation of common parameter into the Policy Framework Components.

Table of Contents

Not Spring boot framework

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.

...

Code Block
languagejava
@NotNull
@NotBlank
@Getter
public class PapParameterGroup extends ParameterGroupImpl {
    @Valid
    private RestServerParameters restServerParameters;
    @Valid
    private PdpParameters pdpParameters;
    @Valid
    private PolicyModelsProviderParameters databaseProviderParameters;
    private boolean savePdpStatisticsInDb;
    @Valid
    private TopicParameterGroup topicParameterGroup;
    // API, Distribution Health Check REST client parameters.
    private List<@NotNull @Valid RestClientParameters> healthCheckRestClientParameters;

    /**
     * Create the pap parameter group.
     *
     * @param name the parameter group name
     */
    public PapParameterGroup(final String name) {
        super(name);
    }
}


The code shows below, is an example of Unit Test validation of the POJO PapParameterGroup:

Code Block
languagejava
    private static final Coder coder = new StandardCoder();

    @Test
    void testPapParameterGroup_NullName() throws Exception {
        String json = commonTestData.getPapParameterGroupAsString(1).replace("\"PapGroup\"", "null");
        final PapParameterGroup papParameters = coder.decode(json, PapParameterGroup.class);
        final ValidationResult validationResult = papParameters.validate();
        assertFalse(validationResult.isValid());
        assertEquals(null, papParameters.getName());
        assertThat(validationResult.getResult()).contains("is null");
    }


Using Spring boot framework

Spring loads automatically the property file and put it available under the org.springframework.core.env.Environment Spring component. 

Environment

A component can use Environment component directly.

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.

Code Block
languagejava
@Component
@RequiredArgsConstructor
public class Example {

private Environment env;
....

public void method(String pathPropertyName) {
    .....  
    String path = env.getProperty(pathPropertyName);
    .....
}

...

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.

Code Block
languagejava
    @Value("${security.enable-csrf:true}")
    private boolean csrfEnabled = true;

...