Issue
I am using:
import io.vertx.core.json.JsonObject;
Say we have a class:
class Foo {
public String barStar;
public boolean myBool;
}
and then we have a JsonObject like so:
var o = new JsonObject(`{"bar_star":"yes","my_bool":true}`);
is there some built-in mechanism to map the JsonObject to the matching fields in the class? I am thinking of some sort of map instance, like so:
Foo f = o.mapTo(Foo.class, Map.of("bar_star","barStar","my_bool","myBool");
so you would pass in a map instance, and that would tell JsonObject how to map the fields? Can somehow show an example of how to do this? I specifically asking how to map the fields before deserializing to a class.
Solution
I created a small application that demonstrates this.
To make sense of everything it's probably best to just have a look at the whole codebase.
Find it at: https://github.com/thokari/epages-app-kickstart
I am posting some code, as is usually required on stackoverflow.
Here is the Model
base class and a class that extends it:
package de.thokari.epages.app.model;
import io.vertx.core.json.Json;
import io.vertx.core.json.JsonObject;
public abstract class Model {
public static <T extends Model> T fromJsonObject(JsonObject source, Class<T> clazz) {
return Json.decodeValue(source.encode(), clazz);
}
public JsonObject toJsonObject() {
return new JsonObject(Json.encode(this));
}
protected static <T> T validate(final String key, final T value) {
if (null == value) {
throw new IllegalArgumentException(key + " must not be null");
} else {
return (T) value;
}
}
public String toString() {
return Json.encode(this);
}
}
package de.thokari.epages.app.model;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.Base64;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import io.vertx.core.MultiMap;
import io.vertx.core.logging.Logger;
import io.vertx.core.logging.LoggerFactory;
public class InstallationRequest extends Model {
private static final Logger LOG = LoggerFactory.getLogger(InstallationRequest.class);
@JsonProperty("code")
public String code;
@JsonProperty("api_url")
public String apiUrl;
@JsonProperty("access_token_url")
public String accessTokenUrl;
@JsonProperty("return_url")
public String returnUrl;
@JsonProperty("token_path")
public String tokenPath;
@JsonProperty("signature")
public String signature;
@JsonCreator
public InstallationRequest(
@JsonProperty("code") String code,
@JsonProperty("api_url") String apiUrl,
@JsonProperty("access_token_url") String accessTokenUrl,
@JsonProperty("return_url") String returnUrl,
@JsonProperty("signature") String signature) {
this.code = validate("code", code);
this.apiUrl = validate("api_url", apiUrl);
this.accessTokenUrl = validate("access_token_url", accessTokenUrl);
this.returnUrl = validate("return_url", returnUrl);
this.signature = validate("signature", signature);
try {
this.tokenPath = accessTokenUrl.substring(apiUrl.length());
} catch (Exception e) {
throw new IllegalArgumentException("access_token_url must contain api_url");
}
}
public static InstallationRequest fromMultiMap(MultiMap source) {
return new InstallationRequest(
source.get("code"), //
source.get("api_url"), //
source.get("access_token_url"), //
source.get("return_url"), //
source.get("signature"));
}
public static InstallationRequest fromCallbackUrl(String callbackUrl) {
String query = callbackUrl.split("\\?")[1];
String[] parameters = query.split("&");
String code = parameters[0].split("=")[1];
String accessTokenUrl = parameters[1].split("=")[1];
String urlEncodedSignature = parameters[2].split("=")[1];
String signature = null;
try {
signature = URLDecoder.decode(urlEncodedSignature, "utf-8");
} catch (UnsupportedEncodingException e) {
LOG.error("Something went wrong because of a programming error");
}
// TODO why is this missing?!
String apiUrl = accessTokenUrl.substring(0, accessTokenUrl.indexOf("/token"));
return new InstallationRequest(code, apiUrl, accessTokenUrl, "not_needed", signature);
}
public Boolean hasValidSignature(String secret) {
String algorithm = "HmacSHA256";
String encoding = "utf-8";
Mac mac;
try {
mac = Mac.getInstance(algorithm);
mac.init(new SecretKeySpec(secret.getBytes(encoding), algorithm));
} catch (NoSuchAlgorithmException | InvalidKeyException | UnsupportedEncodingException e) {
LOG.error("Signature validation failed because of programming error", e);
return false;
}
byte[] rawSignature = mac.doFinal((this.code + ":" + this.accessTokenUrl).getBytes());
String signature = Base64.getEncoder().encodeToString(rawSignature);
return this.signature.equals(signature);
}
}
Answered By - Thomas Hirsch
Answer Checked By - Mildred Charles (JavaFixing Admin)