1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19 package org.eclipse.aether.spi.connector.transport.http.RFC9457;
20
21 import java.lang.reflect.Type;
22 import java.net.URI;
23
24 import com.google.gson.Gson;
25 import com.google.gson.GsonBuilder;
26 import com.google.gson.JsonDeserializationContext;
27 import com.google.gson.JsonDeserializer;
28 import com.google.gson.JsonElement;
29 import com.google.gson.JsonObject;
30 import com.google.gson.JsonParseException;
31
32 public class RFC9457Parser {
33 private static Gson gson = new GsonBuilder()
34 .registerTypeAdapter(RFC9457Payload.class, new RFC9457PayloadAdapter())
35 .create();
36
37 public static RFC9457Payload parse(String data) {
38 return gson.fromJson(data, RFC9457Payload.class);
39 }
40
41 private static class RFC9457PayloadAdapter implements JsonDeserializer<RFC9457Payload> {
42 @Override
43 public RFC9457Payload deserialize(
44 final JsonElement json, final Type typeOfT, final JsonDeserializationContext context)
45 throws JsonParseException {
46 JsonObject asJsonObject = json.getAsJsonObject();
47 URI type = parseNullableURI(asJsonObject, "type", "about:blank");
48 Integer status = parseStatus(asJsonObject);
49 String title = parseNullableString(asJsonObject, "title");
50 String detail = parseNullableString(asJsonObject, "detail");
51 URI instance = parseNullableURI(asJsonObject, "instance", null);
52 return new RFC9457Payload(type, status, title, detail, instance);
53 }
54 }
55
56 private static Integer parseStatus(JsonObject jsonObject) {
57 return jsonObject.get("status") == null || jsonObject.get("status").isJsonNull()
58 ? null
59 : jsonObject.get("status").getAsInt();
60 }
61
62 private static String parseNullableString(JsonObject jsonObject, String key) {
63 return jsonObject.get(key) == null || jsonObject.get(key).isJsonNull()
64 ? null
65 : jsonObject.get(key).getAsString();
66 }
67
68 private static URI parseNullableURI(JsonObject jsonObject, String key, String defaultValue) {
69 return !jsonObject.has(key) || jsonObject.get(key).isJsonNull()
70 ? defaultValue != null ? URI.create(defaultValue) : null
71 : URI.create(jsonObject.get(key).getAsString());
72 }
73 }