Apply Object Template To Object

27 views Asked by At

I'm writing an application which at some point must build a configuration for a couple of components based on configuration parameters and some execution context.

The input is a JSON (de-serialized into an object) which can be arbitrary complex. The output is defined java POJO with settings the component later checks upon and uses.

My issue is how to map the arbitrary input to the POJO in an elegant way. I would usually just use Jackson or similar to convert the JSON (object) to the correct destination POJO but there is a catch.

The supplied configuration parameters might contain variables that must be replaced. Such variables can either be contained within strings or carry the requirement to replace their "target" in the POJO completely.

Two examples:

#1:

Configuration parameters: { "firstName": "${firstName}", "lastName": "${lastName}" } Context: firstName, a String, which equals "John", lastName, a String, which equals "Doe" Target POJO: e.g. a class User which contains a String firstName, lastName, respective getters, setters, ...

The goal is to create the target POJO with correct first and last name set according to what was resolved from the context. The context offers getVariable functionality to receive a value (Object) for a placeholder.

#2:

Configuration parameters: { "parameters": "${parameters}" } Context: parameters, a map which contains a couple of key-value pairs Target POJO: e.g. a class UserSync which contains an Parameters Object which contains a couple fields, like sync-delay, an Integer, sync-name, a String, ...

The goal is to set the parameters in the POJO according to what was resolved from the context based on the user-input.

This is kinda part of a workflow engine like application, therefore the context.

I'm stuck at the challenge that I would have to somehow (recursively!) iterate over each possible field in the target pojo, check if I have it in my user settings and if so, resolve variables in there, and set the POJO field values correctly. As said, this might be a recursive thing so I would have to look into each Object within the target POJO as well to resolve variables.

Any ideas?

I tried using PropertyAccessor and getDeclaredFields, to go through all fields in the target pojo, check if I find a key with the same name in my settings and if so, check if it is a string or a map so I can look for variables to replace with values from context. It actually works but it's quite the complicated code with lots of ifs and so on ... I somehow hope there is a better method and I'm sure there are enough cases where my code won't work out well.

I figured - maybe convert the user settings to a json string, replace all variables I find in there with the serialized values of the context variable parameters but it's kind ugly as well.

0

There are 0 answers