Fork me on GitHub

Example Settings4j

An example how secured-properties can be used with Settings4j.

Description

The following steps are required to initialize settings4j:

  • First get the decrypted password.
  • Store the decrypted password into SystemProperties under the same key.
  • create a PropertyFileConnector
  • Add the PropertyFileConnector to the Settings4j-Repository after the SystemPropertyConnector.
  • FINSHED: use Settings4j as usual.

In this example, the SystemProperties is only a working example to provide the decrypted password. Better would be to use a custom in-memory implementations of the Settings4j-Connector.

The Property File

The example property-file “TestProperties-Valid.properties”:

myTitle = My Test
mySecretPassword={buMkr+yZH9RclafjETtlSQ==}

The Java Code

The java code example:

        // initialization
        File secretKey = new File("src/test/data/secretFileExample.key");
        File propertiesFile = new File("src/test/data/TestProperties-Valid.properties");

        // initialization - get decrypted value
        SecuredPropertiesConfig config = new SecuredPropertiesConfig().withSecretFile(secretKey).initDefault();
        // initialization - auto encrypt values in the property files:
        SecuredProperties.encryptNonEncryptedValues(
                config, propertiesFile, "mySecretPassword");
        // initialization - get decrypted value
        String myPassword = SecuredProperties.getSecretValue(
                config, propertiesFile, "mySecretPassword");
        // initialization - store plane-text-PW into System-Properties
        System.setProperty("mySecretPassword", myPassword);

        // initialization - add custom Settings4j PropertyFileConnector after existing SystemPropertyConnector
        PropertyFileConnector myConnector = new PropertyFileConnector();
        myConnector.setName("myCustomConfig");
        myConnector.setPropertyFromPath(propertiesFile.toURI().toString());
        Settings4j.getSettingsRepository().getSettings().addConnector(myConnector, afterLast(SystemPropertyConnector.class));

        // somewhere in your application:
        assertThat(Settings4j.getString("myTitle"), is("My Test")); // some value from PropertyFile
        assertThat(Settings4j.getString("mySecretPassword"), is("test")); // decrypted Password from SystemProperties.

The complete code is in Settings4jExampleTest.java