From 3847ef59106534ca83b5a647f8b8677919db6fe1 Mon Sep 17 00:00:00 2001 From: Abid Mehmood Date: Wed, 26 Feb 2020 13:26:38 +0100 Subject: [PATCH] Change empty strings to optional.empty --- .../parser/OptionalTypeAdapterFactory.java | 23 +++++++++++++++++-- 1 file changed, 21 insertions(+), 2 deletions(-) diff --git a/src/main/java/com/suse/salt/netapi/parser/OptionalTypeAdapterFactory.java b/src/main/java/com/suse/salt/netapi/parser/OptionalTypeAdapterFactory.java index 4d244c521..e9ac5b9d9 100644 --- a/src/main/java/com/suse/salt/netapi/parser/OptionalTypeAdapterFactory.java +++ b/src/main/java/com/suse/salt/netapi/parser/OptionalTypeAdapterFactory.java @@ -1,8 +1,11 @@ package com.suse.salt.netapi.parser; import com.google.gson.Gson; +import com.google.gson.JsonElement; +import com.google.gson.JsonSyntaxException; import com.google.gson.TypeAdapter; import com.google.gson.TypeAdapterFactory; +import com.google.gson.internal.bind.TypeAdapters; import com.google.gson.reflect.TypeToken; import com.google.gson.stream.JsonReader; import com.google.gson.stream.JsonToken; @@ -41,8 +44,24 @@ public Optional read(JsonReader in) throws IOException { in.nextNull(); return Optional.empty(); } else { - A value = innerAdapter.read(in); - return Optional.of(value); + JsonElement json = TypeAdapters.JSON_ELEMENT.read(in); + try { + A value = innerAdapter.fromJsonTree(json); + return Optional.of(value); + } + catch (JsonSyntaxException e) { + /** + * Note : This is a workaround and it only exists because salt doesn't differentiate between a + * non-existent grain and a grain which exists but has value set to empty String. + * + * If an object is expected but instead empty string comes in then we return empty Optional. + */ + if (json.isJsonPrimitive() && json.getAsJsonPrimitive().isString() && + json.getAsString().isEmpty()) { + return Optional.empty(); + } + throw e; + } } }