diff --git a/all/pom.xml b/all/pom.xml index 260dfca..9117611 100644 --- a/all/pom.xml +++ b/all/pom.xml @@ -63,16 +63,11 @@ org.microbule - microbule-gson-core - 0.3.0-SNAPSHOT - - - org.microbule - microbule-gson-time + microbule-jsonb-core 0.3.0-SNAPSHOT @@ -119,7 +114,7 @@ org.microbule - microbule-gson-decorator + microbule-jsonb-decorator 0.3.0-SNAPSHOT diff --git a/config/consul/pom.xml b/config/consul/pom.xml index c4f921b..c2ed1dd 100644 --- a/config/consul/pom.xml +++ b/config/consul/pom.xml @@ -48,13 +48,13 @@ org.microbule - microbule-gson-decorator + microbule-jsonb-decorator 0.3.0-SNAPSHOT test org.microbule - microbule-gson-core + microbule-jsonb-core 0.3.0-SNAPSHOT test diff --git a/config/consul/src/main/java/org/microbule/config/consul/ConsulConfigProvider.java b/config/consul/src/main/java/org/microbule/config/consul/ConsulConfigProvider.java index 0dbbfdc..5fb8146 100644 --- a/config/consul/src/main/java/org/microbule/config/consul/ConsulConfigProvider.java +++ b/config/consul/src/main/java/org/microbule/config/consul/ConsulConfigProvider.java @@ -24,13 +24,15 @@ import javax.inject.Named; import javax.inject.Singleton; +import javax.json.bind.Jsonb; +import javax.json.bind.JsonbBuilder; import javax.ws.rs.client.ClientBuilder; import javax.ws.rs.client.WebTarget; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import com.google.common.base.Charsets; -import com.google.gson.reflect.TypeToken; +import com.google.common.reflect.TypeToken; import org.apache.commons.lang3.StringUtils; import org.microbule.config.api.Config; import org.microbule.config.core.ConfigUtils; @@ -58,6 +60,8 @@ public class ConsulConfigProvider implements ConfigProvider { private final WebTarget baseTarget; + private final Jsonb jsonb = JsonbBuilder.create(); + //---------------------------------------------------------------------------------------------------------------------- // Constructors //---------------------------------------------------------------------------------------------------------------------- @@ -78,7 +82,7 @@ public ConsulConfigProvider(String baseAddress) { public Config getConfig(String... path) { final Response response = extend(baseTarget, path).queryParam(RECURSE_PARAM, Boolean.TRUE).request(MediaType.APPLICATION_JSON_TYPE).get(); final String keyPath = Stream.of(path).collect(Collectors.joining(SEPARATOR)) + SEPARATOR; - return WebTargetUtils.parseJsonResponse(response, TYPE_TOKEN) + return WebTargetUtils.parseResponse(response, jsonb, TYPE_TOKEN) .map(nodes -> nodes.stream().collect(Collectors.toMap(node -> StringUtils.substringAfter(node.getKey(), keyPath), node -> base64Decode(node.getValue())))) .map(map -> (Config)new MapConfig(map, SEPARATOR)) .orElse(EmptyConfig.INSTANCE); diff --git a/config/consul/src/main/java/org/microbule/config/consul/ConsulNode.java b/config/consul/src/main/java/org/microbule/config/consul/ConsulNode.java index 4d2c435..e498cab 100644 --- a/config/consul/src/main/java/org/microbule/config/consul/ConsulNode.java +++ b/config/consul/src/main/java/org/microbule/config/consul/ConsulNode.java @@ -17,17 +17,17 @@ package org.microbule.config.consul; -import com.google.gson.annotations.SerializedName; +import javax.json.bind.annotation.JsonbProperty; public class ConsulNode { //---------------------------------------------------------------------------------------------------------------------- // Fields //---------------------------------------------------------------------------------------------------------------------- - @SerializedName("Key") + @JsonbProperty("Key") private final String key; - @SerializedName("Value") + @JsonbProperty("Value") private final String value; //---------------------------------------------------------------------------------------------------------------------- diff --git a/config/consul/src/test/java/org/microbule/config/consul/ConsulConfigProviderTest.java b/config/consul/src/test/java/org/microbule/config/consul/ConsulConfigProviderTest.java index 9c1e25c..52fbf55 100644 --- a/config/consul/src/test/java/org/microbule/config/consul/ConsulConfigProviderTest.java +++ b/config/consul/src/test/java/org/microbule/config/consul/ConsulConfigProviderTest.java @@ -21,17 +21,19 @@ import java.util.List; import java.util.concurrent.atomic.AtomicReference; +import javax.json.bind.JsonbBuilder; + import com.google.common.base.Charsets; -import com.google.gson.Gson; -import com.google.gson.reflect.TypeToken; +import com.google.common.reflect.TypeToken; import org.junit.Before; import org.junit.Test; import org.microbule.config.api.Config; import org.microbule.config.core.ConfigUtils; import org.microbule.container.core.SimpleContainer; -import org.microbule.gson.core.DefaultGsonService; -import org.microbule.gson.decorator.GsonProxyDecorator; -import org.microbule.gson.decorator.GsonServerDecorator; +import org.microbule.jsonb.api.JsonbFactory; +import org.microbule.jsonb.core.DefaultJsonbFactory; +import org.microbule.jsonb.decorator.JsonbProxyDecorator; +import org.microbule.jsonb.decorator.JsonbServerDecorator; import org.microbule.test.server.JaxrsServerTestCase; public class ConsulConfigProviderTest extends JaxrsServerTestCase { @@ -39,9 +41,9 @@ public class ConsulConfigProviderTest extends JaxrsServerTestCase> response = new AtomicReference<>(); private static final TypeToken> TYPE_TOKEN = new TypeToken>() { }; + private final AtomicReference> response = new AtomicReference<>(); //---------------------------------------------------------------------------------------------------------------------- // Other Methods @@ -49,8 +51,9 @@ public class ConsulConfigProviderTest extends JaxrsServerTestCase T parseResponse(String resourceName, TypeToken type) { - return new Gson().fromJson(new InputStreamReader(getClass().getResourceAsStream(resourceName), Charsets.UTF_8), type.getType()); + return JsonbBuilder.create().fromJson(new InputStreamReader(getClass().getResourceAsStream(resourceName), Charsets.UTF_8), type.getType()); } } \ No newline at end of file diff --git a/config/core/pom.xml b/config/core/pom.xml index fcadccb..054e12e 100644 --- a/config/core/pom.xml +++ b/config/core/pom.xml @@ -46,9 +46,9 @@ 0.3.0-SNAPSHOT - com.google.code.gson - gson - ${gson.version} + javax.json + javax.json-api + ${json.api.version} com.google.guava diff --git a/config/core/src/main/java/org/microbule/config/core/RecordingConfig.java b/config/core/src/main/java/org/microbule/config/core/RecordingConfig.java index 287508f..5cb5bb6 100644 --- a/config/core/src/main/java/org/microbule/config/core/RecordingConfig.java +++ b/config/core/src/main/java/org/microbule/config/core/RecordingConfig.java @@ -2,10 +2,9 @@ import java.util.Optional; -import com.google.gson.JsonElement; -import com.google.gson.JsonNull; -import com.google.gson.JsonObject; -import com.google.gson.JsonPrimitive; +import javax.json.Json; +import javax.json.JsonObject; + import org.microbule.config.api.Config; public class RecordingConfig implements Config { @@ -21,7 +20,7 @@ public class RecordingConfig implements Config { //---------------------------------------------------------------------------------------------------------------------- public RecordingConfig(Config delegate) { - this(delegate, new JsonObject()); + this(delegate, Json.createObjectBuilder().build()); } private RecordingConfig(Config delegate, JsonObject recordedJson) { @@ -37,8 +36,8 @@ private RecordingConfig(Config delegate, JsonObject recordedJson) { public Config filtered(String... paths) { JsonObject filteredJson = recordedJson; for (String path : paths) { - JsonObject sub = new JsonObject(); - filteredJson.add(path, sub); + JsonObject sub = Json.createObjectBuilder().build(); + filteredJson.put(path, sub); filteredJson = sub; } return new RecordingConfig(delegate.filtered(paths), filteredJson); @@ -47,7 +46,7 @@ public Config filtered(String... paths) { @Override public Optional value(String key) { final Optional value = delegate.value(key); - recordedJson.add(key, value.map(JsonPrimitive::new).orElse(JsonNull.INSTANCE)); + recordedJson.put(key, value.map(Json::createValue).orElse(null)); return value; } diff --git a/config/core/src/test/java/org/microbule/config/core/RecordingConfigTest.java b/config/core/src/test/java/org/microbule/config/core/RecordingConfigTest.java index 74e9d39..0d4d24e 100644 --- a/config/core/src/test/java/org/microbule/config/core/RecordingConfigTest.java +++ b/config/core/src/test/java/org/microbule/config/core/RecordingConfigTest.java @@ -1,8 +1,8 @@ package org.microbule.config.core; -import com.google.gson.JsonNull; -import com.google.gson.JsonObject; -import com.google.gson.JsonPrimitive; +import javax.json.Json; +import javax.json.JsonObject; + import org.junit.Test; import org.microbule.config.api.Config; import org.microbule.test.core.MicrobuleTestCase; @@ -16,9 +16,9 @@ public void testWithEmpty() { recording.value("bar"); recording.filtered("baz"); final JsonObject json = recording.getRecordedJson(); - assertEquals(JsonNull.INSTANCE, json.get("foo")); - assertEquals(JsonNull.INSTANCE, json.get("bar")); - assertEquals(new JsonObject(), json.get("baz")); + assertNull(json.get("foo")); + assertNull(json.get("bar")); + assertEquals(Json.createObjectBuilder().build(), json.get("baz")); } @Test @@ -40,15 +40,15 @@ public void testRecording() { final JsonObject json = recording.getRecordedJson(); - assertEquals(new JsonPrimitive("bar"), json.get("foo")); - assertEquals(new JsonPrimitive("12345"), json.get("theint")); - assertEquals(JsonNull.INSTANCE, json.get("baz")); + assertEquals(Json.createValue("bar"), json.get("foo")); + assertEquals(Json.createValue("12345"), json.get("theint")); + assertNull(json.get("baz")); - JsonObject nestedJson = json.getAsJsonObject("nested"); - assertEquals(new JsonPrimitive("world"), nestedJson.get("hello")); - assertEquals(JsonNull.INSTANCE, nestedJson.get("bogus")); + JsonObject nestedJson = json.getJsonObject("nested"); + assertEquals(Json.createValue("world"), nestedJson.get("hello")); + assertNull(nestedJson.get("bogus")); - JsonObject nestedJson2 = nestedJson.getAsJsonObject("nested2"); - assertEquals(new JsonPrimitive("world"), nestedJson2.get("hello")); + JsonObject nestedJson2 = nestedJson.getJsonObject("nested2"); + assertEquals(Json.createValue("world"), nestedJson2.get("hello")); } } \ No newline at end of file diff --git a/config/etcd/pom.xml b/config/etcd/pom.xml index f35d13d..1070971 100644 --- a/config/etcd/pom.xml +++ b/config/etcd/pom.xml @@ -48,13 +48,13 @@ org.microbule - microbule-gson-decorator + microbule-jsonb-decorator 0.3.0-SNAPSHOT test org.microbule - microbule-gson-core + microbule-jsonb-core 0.3.0-SNAPSHOT test diff --git a/config/etcd/src/main/java/org/microbule/config/etcd/EtcdConfigProvider.java b/config/etcd/src/main/java/org/microbule/config/etcd/EtcdConfigProvider.java index 3fae587..88a4a71 100644 --- a/config/etcd/src/main/java/org/microbule/config/etcd/EtcdConfigProvider.java +++ b/config/etcd/src/main/java/org/microbule/config/etcd/EtcdConfigProvider.java @@ -25,6 +25,8 @@ import javax.inject.Named; import javax.inject.Singleton; +import javax.json.bind.Jsonb; +import javax.json.bind.JsonbBuilder; import javax.ws.rs.client.ClientBuilder; import javax.ws.rs.client.WebTarget; import javax.ws.rs.core.MediaType; @@ -53,6 +55,7 @@ public class EtcdConfigProvider implements ConfigProvider { private static final String DEFAULT_BASE_ADDRESS = "http://localhost:2379/v2/keys/microbule"; private final WebTarget baseTarget; + private final Jsonb jsonb = JsonbBuilder.create(); //---------------------------------------------------------------------------------------------------------------------- // Constructors @@ -84,7 +87,7 @@ public String name() { public Config getConfig(String... path) { final Response response = extend(baseTarget, path).queryParam("recursive", "true").request(MediaType.APPLICATION_JSON_TYPE).get(); final String keyPath = Stream.of(path).collect(Collectors.joining(SEPARATOR)) + SEPARATOR; - final Optional etcdResponse = WebTargetUtils.parseJsonResponse(response, EtcdResponse.class); + final Optional etcdResponse = WebTargetUtils.parseResponse(response, jsonb, EtcdResponse.class); return etcdResponse.map(r -> { Map values = new HashMap<>(); fillMap(values, r.getNode(), keyPath); diff --git a/config/etcd/src/test/java/org/microbule/config/etcd/EtcdConfigProviderTest.java b/config/etcd/src/test/java/org/microbule/config/etcd/EtcdConfigProviderTest.java index ff35b3a..23693d2 100644 --- a/config/etcd/src/test/java/org/microbule/config/etcd/EtcdConfigProviderTest.java +++ b/config/etcd/src/test/java/org/microbule/config/etcd/EtcdConfigProviderTest.java @@ -20,16 +20,19 @@ import java.io.InputStreamReader; import java.util.concurrent.atomic.AtomicReference; +import javax.json.bind.JsonbBuilder; + import com.google.common.base.Charsets; -import com.google.gson.Gson; + import org.junit.Before; import org.junit.Test; import org.microbule.config.api.Config; import org.microbule.config.core.ConfigUtils; import org.microbule.container.core.SimpleContainer; -import org.microbule.gson.core.DefaultGsonService; -import org.microbule.gson.decorator.GsonProxyDecorator; -import org.microbule.gson.decorator.GsonServerDecorator; +import org.microbule.jsonb.api.JsonbFactory; +import org.microbule.jsonb.core.DefaultJsonbFactory; +import org.microbule.jsonb.decorator.JsonbProxyDecorator; +import org.microbule.jsonb.decorator.JsonbServerDecorator; import org.microbule.test.server.JaxrsServerTestCase; public class EtcdConfigProviderTest extends JaxrsServerTestCase { @@ -45,8 +48,9 @@ public class EtcdConfigProviderTest extends JaxrsServerTestCase @Override protected void addBeans(SimpleContainer container) { - container.addBean(new GsonServerDecorator(new DefaultGsonService(container))); - container.addBean(new GsonProxyDecorator(new DefaultGsonService(container))); + final JsonbFactory jsonbFactory = new DefaultJsonbFactory(container); + container.addBean(new JsonbServerDecorator(jsonbFactory)); + container.addBean(new JsonbProxyDecorator(jsonbFactory)); } @Override @@ -72,7 +76,7 @@ public void testConfig() { } private T parseResponse(String resourceName, Class type) { - return new Gson().fromJson(new InputStreamReader(getClass().getResourceAsStream(resourceName), Charsets.UTF_8), type); + return JsonbBuilder.create().fromJson(new InputStreamReader(getClass().getResourceAsStream(resourceName), Charsets.UTF_8), type); } } \ No newline at end of file diff --git a/core/pom.xml b/core/pom.xml index 4e2522a..2d80bc9 100644 --- a/core/pom.xml +++ b/core/pom.xml @@ -56,9 +56,9 @@ 0.3.0-SNAPSHOT - com.google.guava - guava - ${guava.version} + javax.json + javax.json-api + ${json.api.version} org.apache.commons diff --git a/core/src/main/java/org/microbule/core/CachedJaxrsProxy.java b/core/src/main/java/org/microbule/core/CachedJaxrsProxy.java index 783ad62..beee8a4 100644 --- a/core/src/main/java/org/microbule/core/CachedJaxrsProxy.java +++ b/core/src/main/java/org/microbule/core/CachedJaxrsProxy.java @@ -1,6 +1,7 @@ package org.microbule.core; -import com.google.gson.JsonObject; + +import javax.json.JsonObject; public class CachedJaxrsProxy { //---------------------------------------------------------------------------------------------------------------------- diff --git a/core/src/main/java/org/microbule/core/JaxrsProxyCache.java b/core/src/main/java/org/microbule/core/JaxrsProxyCache.java index 48f4718..4317206 100644 --- a/core/src/main/java/org/microbule/core/JaxrsProxyCache.java +++ b/core/src/main/java/org/microbule/core/JaxrsProxyCache.java @@ -25,8 +25,6 @@ import com.google.common.cache.LoadingCache; import com.google.common.cache.RemovalListener; import com.google.common.cache.RemovalNotification; -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; import org.microbule.config.api.Config; import org.microbule.scheduler.api.RefreshableReference; import org.microbule.scheduler.api.SchedulerService; @@ -38,7 +36,6 @@ class JaxrsProxyCache implements RemovalListener> load(String address) throws Exc final CachedJaxrsProxy newValue = factory.apply(address); if (currentValue == null) { if (LOGGER.isInfoEnabled()) { - LOGGER.info("Created dynamic proxy for \"{}\" service at address {}:\n\n{}\n", serviceName, address, GSON.toJson(newValue.getConfig())); + LOGGER.info("Created dynamic proxy for \"{}\" service at address {}:\n\n{}\n", serviceName, address, newValue.getConfig()); } return newValue; } else if (currentValue.getConfig().equals(newValue.getConfig())) { @@ -78,7 +75,7 @@ public RefreshableReference> load(String address) throws Exc return currentValue; } else { if (LOGGER.isInfoEnabled()) { - LOGGER.info("Refreshed dynamic proxy for \"{}\" service at address {}:\n\n{}\n", serviceName, address, GSON.toJson(newValue.getConfig())); + LOGGER.info("Refreshed dynamic proxy for \"{}\" service at address {}:\n\n{}\n", serviceName, address, newValue.getConfig()); } return newValue; } diff --git a/features/src/main/resources/features.xml b/features/src/main/resources/features.xml index 7775ee3..73d8e4a 100644 --- a/features/src/main/resources/features.xml +++ b/features/src/main/resources/features.xml @@ -25,7 +25,14 @@ Main Feature ==================================================================================================================== --> + + cxf-jaxrs + cxf-rs-description-swagger2 + microbule-no-cxf + + + microbule-core microbule-errormap microbule-gzip @@ -38,7 +45,7 @@ microbule-timeout microbule-tracer microbule-circuitbreaker - microbule-gson + microbule-jsonb microbule-metrics microbule-version @@ -49,14 +56,15 @@ ==================================================================================================================== --> - cxf-jaxrs - cxf-rs-description-swagger2 + mvn:org.apache.servicemix.bundles/org.apache.servicemix.bundles.cglib/${cglib.version} + mvn:org.apache.geronimo.specs/geronimo-atinject_1.0_spec/1.0 - mvn:com.google.code.gson/gson/${gson.version} + mvn:javax.json/javax.json-api/${json.api.version} + mvn:javax.json.bind/javax.json.bind-api/${json.bind.api.version} mvn:com.google.guava/guava/${guava.version} mvn:org.apache.commons/commons-lang3/${commons.lang3.version} mvn:com.savoirtech.eos/eos-core/${eos.version} @@ -98,14 +106,16 @@ mvn:org.microbule/microbule-errormap-mapper/${project.version} - - mvn:org.microbule/microbule-gson-api/${project.version} - mvn:org.microbule/microbule-gson-spi/${project.version} - mvn:org.microbule/microbule-gson-provider/${project.version} - mvn:org.microbule/microbule-gson-util/${project.version} - mvn:org.microbule/microbule-gson-time/${project.version} - mvn:org.microbule/microbule-gson-core/${project.version} - mvn:org.microbule/microbule-gson-decorator/${project.version} + + mvn:org.apache.johnzon/johnzon-core/${johnzon.version} + mvn:org.apache.johnzon/johnzon-mapper/${johnzon.version} + mvn:org.apache.johnzon/johnzon-jsonb/${johnzon.version} + + mvn:org.microbule/microbule-jsonb-api/${project.version} + mvn:org.microbule/microbule-jsonb-spi/${project.version} + mvn:org.microbule/microbule-jsonb-provider/${project.version} + mvn:org.microbule/microbule-jsonb-core/${project.version} + mvn:org.microbule/microbule-jsonb-decorator/${project.version} diff --git a/gson/api/src/main/java/org/microbule/gson/api/GsonService.java b/gson/api/src/main/java/org/microbule/gson/api/GsonService.java deleted file mode 100644 index d8f330f..0000000 --- a/gson/api/src/main/java/org/microbule/gson/api/GsonService.java +++ /dev/null @@ -1,178 +0,0 @@ -/* - * Copyright (c) 2017 The Microbule Authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package org.microbule.gson.api; - -import java.io.Reader; -import java.lang.reflect.Type; -import java.util.function.Consumer; -import java.util.function.Function; - -import com.google.gson.Gson; -import com.google.gson.JsonElement; - -public interface GsonService { -//---------------------------------------------------------------------------------------------------------------------- -// Other Methods -//---------------------------------------------------------------------------------------------------------------------- - - /** - * Appends an object's JSON value to the supplied {@link Appendable} object. - * - * @param src the object - * @param writer the appendable - * @param the appendable type - * @return the appendable - */ - A append(Object src, A writer); - - /** - * Appends an {@link JsonElement}'s JSON value to the supplied {@link Appendable} object. - * - * @param json the element - * @param writer the appendable - * @param the appendable type - * @return the appendable - */ - A append(JsonElement json, A writer); - - /** - * Appends an object's JSON value to the supplied {@link Appendable} object. - * - * @param src the object - * @param type the object's type (to be used in the case of generics) - * @param writer the appendable - * @param the appendable type - * @return the appendable - */ - A append(Object src, Type type, A writer); - /** - * Allows access to the {@link Gson} instance in order to create some object. Do NOT maintain a reference to the - * {@link Gson} object! - * - * @param function a function - * @param the type to return - * @return the value created by the function - */ - T createWithGson(Function function); - - /** - * Allows access to the {@link Gson} instance. Do NOT maintain a reference to the supplied {@link Gson} object! - * - * @param consumer a consumer - */ - void doWithGson(Consumer consumer); - - /** - * Parses an object from the supplied {@link Reader}. - * - * @param json the reader containing the JSON - * @param type the generic type - * @param the object type to return (uses type inference) - * @return the parsed object - */ - T parse(Reader json, Type type); - - /** - * Parses an object from the supplied {@link JsonElement}. - * - * @param json the JSON element - * @param type the type - * @param the object type - * @return the parsed object - */ - T parse(JsonElement json, Class type); - - /** - * Parses an object from the supplied {@link JsonElement}. - * - * @param json the JSON element - * @param type the generic type - * @param the object type (uses type inference) - * @return the parsed object - */ - T parse(JsonElement json, Type type); - - /** - * Parses an object from the supplied JSON string. - * - * @param json the JSON string - * @param type the type - * @param the object type - * @return the parsed object - */ - T parse(String json, Class type); - - /** - * Parses an object from the supplied JSON string. - * - * @param json the JSON string - * @param type the generic type - * @param the object type - * @return the parsed object - */ - T parse(String json, Type type); - - /** - * Parses an object from the supplied {@link Reader}. - * - * @param json the reader containing the JSON - * @param type the type - * @param the object type to return - * @return the parsed object - */ - T parse(Reader json, Class type); - - /** - * Transforms an input object into a {@link JsonElement}. - * @param src the source object - * @param the JSON element type (uses type inference) - * @return the parsed JSON element - */ - T toJson(Object src); - - /** - * Transforms an input object into a {@link JsonElement}. - * @param src the source object - * @param type the source object's generic type - * @param the JSON element type (uses type inference) - * @return the parsed JSON element - */ - T toJson(Object src, Type type); - - /** - * Transforms an object into its JSON string representation. - * @param src the source object - * @return the JSON string - */ - String toJsonString(Object src); - - /** - * Transforms a {@link JsonElement} into its JSON string representation. - * @param json the JSON element - * @return the JSON string - */ - String toJsonString(JsonElement json); - - /** - * Transforms an object into its JSON string representation. - * @param src the source object - * @param type the source object's generic type - * @return the JSON string - */ - String toJsonString(Object src, Type type); -} diff --git a/gson/core/src/main/java/org/microbule/gson/core/DefaultGsonService.java b/gson/core/src/main/java/org/microbule/gson/core/DefaultGsonService.java deleted file mode 100644 index 89c9d73..0000000 --- a/gson/core/src/main/java/org/microbule/gson/core/DefaultGsonService.java +++ /dev/null @@ -1,194 +0,0 @@ -/* - * Copyright (c) 2017 The Microbule Authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package org.microbule.gson.core; - -import java.io.Reader; -import java.lang.reflect.Type; -import java.util.List; -import java.util.concurrent.CopyOnWriteArrayList; -import java.util.concurrent.atomic.AtomicReference; -import java.util.function.Consumer; -import java.util.function.Function; - -import javax.inject.Inject; -import javax.inject.Named; -import javax.inject.Singleton; - -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; -import com.google.gson.JsonElement; -import org.microbule.container.api.MicrobuleContainer; -import org.microbule.container.api.PluginListener; -import org.microbule.gson.api.GsonService; -import org.microbule.gson.spi.GsonBuilderCustomizer; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -@Singleton -@Named("gsonService") -public class DefaultGsonService implements GsonService { -//---------------------------------------------------------------------------------------------------------------------- -// Fields -//---------------------------------------------------------------------------------------------------------------------- - - private static final Logger LOGGER = LoggerFactory.getLogger(DefaultGsonService.class); - private final List customizers = new CopyOnWriteArrayList<>(); - private final AtomicReference gson = new AtomicReference<>(new GsonBuilder().create()); - -//---------------------------------------------------------------------------------------------------------------------- -// Constructors -//---------------------------------------------------------------------------------------------------------------------- - - @Inject - public DefaultGsonService(MicrobuleContainer container) { - container.addPluginListener(GsonBuilderCustomizer.class, new GsonCustomizerListener()); - } - -//---------------------------------------------------------------------------------------------------------------------- -// GsonService Implementation -//---------------------------------------------------------------------------------------------------------------------- - - @Override - public A append(Object src, A writer) { - getGson().toJson(src, writer); - return writer; - } - - @Override - public A append(JsonElement json, A writer) { - getGson().toJson(json, writer); - return writer; - } - - @Override - public A append(Object src, Type type, A writer) { - getGson().toJson(src, type, writer); - return writer; - } - - @Override - public T createWithGson(Function function) { - return function.apply(getGson()); - } - - @Override - public void doWithGson(Consumer consumer) { - consumer.accept(getGson()); - } - - @Override - public T parse(Reader json, Type type) { - return getGson().fromJson(json, type); - } - - @Override - public T parse(JsonElement json, Class type) { - return getGson().fromJson(json, type); - } - - @Override - public T parse(JsonElement json, Type type) { - return getGson().fromJson(json, type); - } - - @Override - public T parse(String json, Class type) { - return getGson().fromJson(json, type); - } - - @Override - public T parse(String json, Type type) { - return getGson().fromJson(json, type); - } - - @Override - public T parse(Reader json, Class type) { - return getGson().fromJson(json, type); - } - - @Override - @SuppressWarnings("unchecked") - public T toJson(Object src) { - return (T) getGson().toJsonTree(src); - } - - @Override - @SuppressWarnings("unchecked") - public T toJson(Object src, Type type) { - return (T) getGson().toJsonTree(src, type); - } - - @Override - public String toJsonString(Object src) { - return getGson().toJson(src); - } - - @Override - public String toJsonString(JsonElement json) { - return getGson().toJson(json); - } - - @Override - public String toJsonString(Object src, Type type) { - return getGson().toJson(src, type); - } - -//---------------------------------------------------------------------------------------------------------------------- -// Other Methods -//---------------------------------------------------------------------------------------------------------------------- - - Gson getGson() { - return gson.get(); - } - -//---------------------------------------------------------------------------------------------------------------------- -// Inner Classes -//---------------------------------------------------------------------------------------------------------------------- - - private class GsonCustomizerListener implements PluginListener { -//---------------------------------------------------------------------------------------------------------------------- -// PluginListener Implementation -//---------------------------------------------------------------------------------------------------------------------- - - @Override - public boolean registerPlugin(GsonBuilderCustomizer plugin) { - customizers.add(plugin); - LOGGER.debug("Rebuilding GSON instance to include plugin {}.", plugin); - rebuild(); - return true; - } - - @Override - public void unregisterPlugin(GsonBuilderCustomizer plugin) { - customizers.remove(plugin); - LOGGER.debug("Rebuilding GSON instance without plugin {}.", plugin); - rebuild(); - } - -//---------------------------------------------------------------------------------------------------------------------- -// Other Methods -//---------------------------------------------------------------------------------------------------------------------- - - private void rebuild() { - GsonBuilder builder = new GsonBuilder(); - builder.setPrettyPrinting(); - customizers.forEach(customizer -> customizer.customize(builder)); - gson.set(builder.create()); - } - } -} diff --git a/gson/core/src/main/resources/META-INF/beans.xml b/gson/core/src/main/resources/META-INF/beans.xml deleted file mode 100644 index 115b372..0000000 --- a/gson/core/src/main/resources/META-INF/beans.xml +++ /dev/null @@ -1,22 +0,0 @@ - - - - \ No newline at end of file diff --git a/gson/core/src/main/resources/OSGI-INF/blueprint/microbule-gson-core.xml b/gson/core/src/main/resources/OSGI-INF/blueprint/microbule-gson-core.xml deleted file mode 100644 index 9903fc6..0000000 --- a/gson/core/src/main/resources/OSGI-INF/blueprint/microbule-gson-core.xml +++ /dev/null @@ -1,30 +0,0 @@ - - - - - - - - - - - - - - \ No newline at end of file diff --git a/gson/core/src/test/java/org/microbule/gson/core/DefaultGsonServiceTest.java b/gson/core/src/test/java/org/microbule/gson/core/DefaultGsonServiceTest.java deleted file mode 100644 index 5fd7847..0000000 --- a/gson/core/src/test/java/org/microbule/gson/core/DefaultGsonServiceTest.java +++ /dev/null @@ -1,173 +0,0 @@ -/* - * Copyright (c) 2017 The Microbule Authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package org.microbule.gson.core; - -import java.io.StringReader; -import java.io.StringWriter; - -import com.google.gson.GsonBuilder; -import com.google.gson.JsonObject; -import org.junit.Before; -import org.junit.Test; -import org.microbule.container.core.SimpleContainer; -import org.microbule.gson.spi.GsonBuilderCustomizer; -import org.microbule.test.core.MockObjectTestCase; -import org.mockito.Mock; - -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.Mockito.doAnswer; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.verifyNoMoreInteractions; - -public class DefaultGsonServiceTest extends MockObjectTestCase { -//---------------------------------------------------------------------------------------------------------------------- -// Fields -//---------------------------------------------------------------------------------------------------------------------- - - @Mock - private GsonBuilderCustomizer customizer; - private DefaultGsonService service; - -//---------------------------------------------------------------------------------------------------------------------- -// Other Methods -//---------------------------------------------------------------------------------------------------------------------- - - @Before - public void initGsonService() { - final SimpleContainer container = new SimpleContainer(); - service = new DefaultGsonService(container); - container.initialize(); - } - - @Test - public void testDoWithGson() { - service.doWithGson(gson -> { - assertTrue(gson.htmlSafe()); - }); - } - - @Test - public void testAddCustomizer() { - doAnswer(invocation -> { - GsonBuilder builder = invocation.getArgument(0); - builder.disableHtmlEscaping(); - return null; - }).when(customizer).customize(any(GsonBuilder.class)); - final SimpleContainer container = new SimpleContainer(); - final DefaultGsonService service = new DefaultGsonService(container); - container.addBean(customizer); - container.initialize(); - verify(customizer).customize(any(GsonBuilder.class)); - assertFalse(service.getGson().htmlSafe()); - container.shutdown(); - verifyNoMoreInteractions(customizer); - } - - @Test - public void testAppending() { - final Person person = new Person("Hello", "Microbule"); - JsonObject json = service.toJson(person); - - assertEquals(json.toString(), service.append(person, new StringWriter()).toString()); - assertEquals(json.toString(), service.append(person, Person.class.getGenericSuperclass(), new StringWriter()).toString()); - assertEquals(json.toString(), service.append(json, new StringWriter()).toString()); - } - - @Test - public void testCreateWithGson() { - final Person person = new Person("Hello", "Microbule"); - final String json = service.createWithGson(gson -> gson.toJson(person)); - assertEquals(json, service.toJsonString(person)); - } - - @Test - public void testParsing() { - final Person person = new Person("Hello", "Microbule"); - JsonObject json = service.toJson(person); - - assertJsonEquals(person, service.parse(new StringReader(json.toString()), Person.class)); - assertJsonEquals(person, service.parse(new StringReader(json.toString()), Person.class.getGenericSuperclass())); - - assertJsonEquals(person, service.parse(json.toString(), Person.class)); - assertJsonEquals(person, service.parse(json.toString(), Person.class.getGenericSuperclass())); - - assertJsonEquals(person, service.parse(json, Person.class)); - assertJsonEquals(person, service.parse(json, Person.class.getGenericSuperclass())); - } - - private void assertJsonEquals(T expected, T actual) { - assertEquals(service.toJsonString(expected), service.toJsonString(actual)); - } - - @Test - public void testToJson() { - final Person person = new Person("Hello", "Microbule"); - JsonObject json = new JsonObject(); - json.addProperty("firstName", "Hello"); - json.addProperty("lastName", "Microbule"); - - assertEquals(json, service.toJson(person)); - assertEquals(json, service.toJson(person, Person.class.getGenericSuperclass())); - } - - @Test - public void testToJsonString() { - final Person person = new Person("Hello", "Microbule"); - JsonObject json = new JsonObject(); - json.addProperty("firstName", "Hello"); - json.addProperty("lastName", "Microbule"); - - assertEquals(json.toString(), service.toJsonString(person)); - assertEquals(json.toString(), service.toJsonString(person, Person.class.getGenericSuperclass())); - assertEquals(json.toString(), service.toJsonString(json)); - } - -//---------------------------------------------------------------------------------------------------------------------- -// Inner Classes -//---------------------------------------------------------------------------------------------------------------------- - - public static class Person { -//---------------------------------------------------------------------------------------------------------------------- -// Fields -//---------------------------------------------------------------------------------------------------------------------- - - private final String firstName; - private final String lastName; - -//---------------------------------------------------------------------------------------------------------------------- -// Constructors -//---------------------------------------------------------------------------------------------------------------------- - - public Person(String firstName, String lastName) { - this.firstName = firstName; - this.lastName = lastName; - } - -//---------------------------------------------------------------------------------------------------------------------- -// Getter/Setter Methods -//---------------------------------------------------------------------------------------------------------------------- - - public String getFirstName() { - return firstName; - } - - public String getLastName() { - return lastName; - } - } -} \ No newline at end of file diff --git a/gson/decorator/pom.xml b/gson/decorator/pom.xml deleted file mode 100644 index abefa52..0000000 --- a/gson/decorator/pom.xml +++ /dev/null @@ -1,59 +0,0 @@ - - - - - - 4.0.0 - - org.microbule - microbule-gson-parent - 0.3.0-SNAPSHOT - - - microbule-gson-decorator - Microbule :: GSON :: Decorator - bundle - - - com.google.guava - guava - ${guava.version} - - - org.microbule - microbule-gson-provider - 0.3.0-SNAPSHOT - - - org.microbule - microbule-spi - 0.3.0-SNAPSHOT - - - org.microbule - microbule-errormap-spi - 0.3.0-SNAPSHOT - - - org.microbule - microbule-test-core - 0.3.0-SNAPSHOT - test - - - diff --git a/gson/decorator/src/main/resources/META-INF/beans.xml b/gson/decorator/src/main/resources/META-INF/beans.xml deleted file mode 100644 index 115b372..0000000 --- a/gson/decorator/src/main/resources/META-INF/beans.xml +++ /dev/null @@ -1,22 +0,0 @@ - - - - \ No newline at end of file diff --git a/gson/decorator/src/main/resources/OSGI-INF/blueprint/microbule-gson-decorator.xml b/gson/decorator/src/main/resources/OSGI-INF/blueprint/microbule-gson-decorator.xml deleted file mode 100644 index a55afcd..0000000 --- a/gson/decorator/src/main/resources/OSGI-INF/blueprint/microbule-gson-decorator.xml +++ /dev/null @@ -1,36 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/gson/decorator/src/test/java/org/microbule/gson/decorator/GsonProxyDecoratorTest.java b/gson/decorator/src/test/java/org/microbule/gson/decorator/GsonProxyDecoratorTest.java deleted file mode 100644 index 34ad8a0..0000000 --- a/gson/decorator/src/test/java/org/microbule/gson/decorator/GsonProxyDecoratorTest.java +++ /dev/null @@ -1,48 +0,0 @@ -/* - * Copyright (c) 2017 The Microbule Authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package org.microbule.gson.decorator; - -import org.junit.Test; -import org.microbule.gson.api.GsonService; -import org.microbule.gson.provider.GsonProvider; -import org.microbule.spi.JaxrsServiceDescriptor; -import org.microbule.test.core.MockObjectTestCase; -import org.mockito.Mock; - -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.Mockito.verify; - -public class GsonProxyDecoratorTest extends MockObjectTestCase { -//---------------------------------------------------------------------------------------------------------------------- -// Other Methods -//---------------------------------------------------------------------------------------------------------------------- - - @Mock - private GsonService gsonService; - - @Mock - private JaxrsServiceDescriptor descriptor; - - @Test - public void testDecorate() { - final GsonProxyDecorator decorator = new GsonProxyDecorator(gsonService); - assertEquals("gson", decorator.name()); - decorator.decorate(descriptor, null); - verify(descriptor).addProvider(any(GsonProvider.class)); - } -} \ No newline at end of file diff --git a/gson/decorator/src/test/java/org/microbule/gson/decorator/GsonServerDecoratorTest.java b/gson/decorator/src/test/java/org/microbule/gson/decorator/GsonServerDecoratorTest.java deleted file mode 100644 index b499edc..0000000 --- a/gson/decorator/src/test/java/org/microbule/gson/decorator/GsonServerDecoratorTest.java +++ /dev/null @@ -1,48 +0,0 @@ -/* - * Copyright (c) 2017 The Microbule Authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package org.microbule.gson.decorator; - -import org.junit.Test; -import org.microbule.gson.api.GsonService; -import org.microbule.gson.provider.GsonProvider; -import org.microbule.spi.JaxrsServiceDescriptor; -import org.microbule.test.core.MockObjectTestCase; -import org.mockito.Mock; - -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.Mockito.verify; - -public class GsonServerDecoratorTest extends MockObjectTestCase { -//---------------------------------------------------------------------------------------------------------------------- -// Other Methods -//---------------------------------------------------------------------------------------------------------------------- - - @Mock - private GsonService gsonService; - - @Mock - private JaxrsServiceDescriptor descriptor; - - @Test - public void testDecorate() { - final GsonServerDecorator decorator = new GsonServerDecorator(gsonService); - assertEquals("gson", decorator.name()); - decorator.decorate(descriptor, null); - verify(descriptor).addProvider(any(GsonProvider.class)); - } -} \ No newline at end of file diff --git a/gson/provider/pom.xml b/gson/provider/pom.xml deleted file mode 100644 index 82a9730..0000000 --- a/gson/provider/pom.xml +++ /dev/null @@ -1,61 +0,0 @@ - - - - - - 4.0.0 - - org.microbule - microbule-gson-parent - 0.3.0-SNAPSHOT - - - microbule-gson-provider - Microbule :: GSON :: Provider - bundle - - - - org.microbule - microbule-util - 0.3.0-SNAPSHOT - - - com.google.guava - guava - ${guava.version} - - - org.microbule - microbule-gson-api - 0.3.0-SNAPSHOT - - - org.microbule - microbule-test-server - 0.3.0-SNAPSHOT - test - - - org.microbule - microbule-gson-core - 0.3.0-SNAPSHOT - test - - - diff --git a/gson/provider/src/test/java/org/microbule/gson/provider/BadJsonService.java b/gson/provider/src/test/java/org/microbule/gson/provider/BadJsonService.java deleted file mode 100644 index 35df9db..0000000 --- a/gson/provider/src/test/java/org/microbule/gson/provider/BadJsonService.java +++ /dev/null @@ -1,16 +0,0 @@ -package org.microbule.gson.provider; - -import javax.ws.rs.GET; -import javax.ws.rs.Path; -import javax.ws.rs.Produces; -import javax.ws.rs.core.MediaType; -import javax.ws.rs.core.Response; - -@Path("/") -public interface BadJsonService { - - @Produces(MediaType.APPLICATION_JSON) - @GET - @Path("bad") - Response createBadJson(); -} diff --git a/gson/provider/src/test/java/org/microbule/gson/provider/GsonClientProviderTest.java b/gson/provider/src/test/java/org/microbule/gson/provider/GsonClientProviderTest.java deleted file mode 100644 index 44688de..0000000 --- a/gson/provider/src/test/java/org/microbule/gson/provider/GsonClientProviderTest.java +++ /dev/null @@ -1,62 +0,0 @@ -package org.microbule.gson.provider; - -import javax.ws.rs.client.ResponseProcessingException; -import javax.ws.rs.core.MediaType; -import javax.ws.rs.core.Response; - -import org.junit.Test; -import org.microbule.config.api.Config; -import org.microbule.container.core.SimpleContainer; -import org.microbule.gson.api.GsonService; -import org.microbule.gson.core.DefaultGsonService; -import org.microbule.spi.JaxrsProxyDecorator; -import org.microbule.spi.JaxrsServiceDescriptor; -import org.microbule.test.server.JaxrsServerTestCase; - -public class GsonClientProviderTest extends JaxrsServerTestCase { -//---------------------------------------------------------------------------------------------------------------------- -// Other Methods -//---------------------------------------------------------------------------------------------------------------------- - - @Override - protected void addBeans(SimpleContainer container) { - GsonService gsonService = new DefaultGsonService(container); - container.addBean(new JaxrsProxyDecorator() { - @Override - public String name() { - return "gsonTest"; - } - - @Override - public void decorate(JaxrsServiceDescriptor descriptor, Config config) { - descriptor.addProvider(new GsonProvider(gsonService, e -> new JsonResponseParsingException(e))); - } - }); - } - - @Override - protected BadJsonService createImplementation() { - return new BadJsonServiceImpl(); - } - - @Test(expected = ResponseProcessingException.class) - public void testParsingBadResponse() { - final Response response = createProxy().createBadJson(); - response.readEntity(Person.class); - } - -//---------------------------------------------------------------------------------------------------------------------- -// Inner Classes -//---------------------------------------------------------------------------------------------------------------------- - - public static class BadJsonServiceImpl implements BadJsonService { -//---------------------------------------------------------------------------------------------------------------------- -// BadJsonService Implementation -//---------------------------------------------------------------------------------------------------------------------- - - @Override - public Response createBadJson() { - return Response.ok("{{{}}", MediaType.APPLICATION_JSON_TYPE).build(); - } - } -} diff --git a/gson/provider/src/test/java/org/microbule/gson/provider/GsonServerProviderTest.java b/gson/provider/src/test/java/org/microbule/gson/provider/GsonServerProviderTest.java deleted file mode 100644 index 5ef5794..0000000 --- a/gson/provider/src/test/java/org/microbule/gson/provider/GsonServerProviderTest.java +++ /dev/null @@ -1,103 +0,0 @@ -/* - * Copyright (c) 2017 The Microbule Authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package org.microbule.gson.provider; - -import java.util.List; - -import javax.ws.rs.client.Entity; -import javax.ws.rs.core.MediaType; -import javax.ws.rs.core.Response; - -import com.google.common.collect.Lists; -import org.junit.Test; -import org.microbule.config.api.Config; -import org.microbule.container.core.SimpleContainer; -import org.microbule.gson.api.GsonService; -import org.microbule.gson.core.DefaultGsonService; -import org.microbule.spi.JaxrsProxyDecorator; -import org.microbule.spi.JaxrsServerDecorator; -import org.microbule.spi.JaxrsServiceDescriptor; -import org.microbule.test.server.JaxrsServerTestCase; -import org.mockito.Mock; - -import static org.mockito.Mockito.when; - -public class GsonServerProviderTest extends JaxrsServerTestCase { - - @Mock - private PersonService serviceImpl; - - @Override - protected PersonService createImplementation() { - return serviceImpl; - } - - @Override - protected void addBeans(SimpleContainer container) { - GsonService gsonService = new DefaultGsonService(container); - container.addBean(new JaxrsServerDecorator() { - @Override - public String name() { - return "gsonServer"; - } - - @Override - public void decorate(JaxrsServiceDescriptor descriptor, Config config) { - descriptor.addProvider(new GsonProvider(gsonService, e -> new JsonRequestParsingException(e))); - } - }); - - container.addBean(new JaxrsProxyDecorator() { - @Override - public String name() { - return "gsonProxy"; - } - - @Override - public void decorate(JaxrsServiceDescriptor descriptor, Config config) { - descriptor.addProvider(new GsonProvider(gsonService, e -> new JsonResponseParsingException(e))); - } - }); - } - - @Test - public void testGetSize() { - assertEquals(-1, new GsonProvider(null, null).getSize(null, null, null, null, null)); - } - - @Test - public void testWithJsonSyntaxException() { - final Response response = createWebTarget().path("people").request().post(Entity.entity("{{{}", MediaType.APPLICATION_JSON_TYPE)); - assertEquals(500, response.getStatus()); - } - - @Test - public void testBeanSerialization() { - when(serviceImpl.findPerson("Slappy", "White")).thenReturn(new Person("Slappy", "White")); - final Person person = createProxy().findPerson("Slappy", "White"); - assertEquals("Slappy", person.getFirstName()); - assertEquals("White", person.getLastName()); - } - - @Test - public void testGenericTypeSerialization() { - when(serviceImpl.all()).thenReturn(Lists.newArrayList(new Person("Slappy", "White"))); - final List persons = createProxy().all(); - assertEquals(1, persons.size()); - } -} \ No newline at end of file diff --git a/gson/provider/src/test/java/org/microbule/gson/provider/Person.java b/gson/provider/src/test/java/org/microbule/gson/provider/Person.java deleted file mode 100644 index 7a30070..0000000 --- a/gson/provider/src/test/java/org/microbule/gson/provider/Person.java +++ /dev/null @@ -1,48 +0,0 @@ -/* - * Copyright (c) 2017 The Microbule Authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package org.microbule.gson.provider; - -public class Person { -//---------------------------------------------------------------------------------------------------------------------- -// Fields -//---------------------------------------------------------------------------------------------------------------------- - - private final String firstName; - private final String lastName; - -//---------------------------------------------------------------------------------------------------------------------- -// Constructors -//---------------------------------------------------------------------------------------------------------------------- - - public Person(String firstName, String lastName) { - this.firstName = firstName; - this.lastName = lastName; - } - -//---------------------------------------------------------------------------------------------------------------------- -// Getter/Setter Methods -//---------------------------------------------------------------------------------------------------------------------- - - public String getFirstName() { - return firstName; - } - - public String getLastName() { - return lastName; - } -} diff --git a/gson/provider/src/test/java/org/microbule/gson/provider/PersonService.java b/gson/provider/src/test/java/org/microbule/gson/provider/PersonService.java deleted file mode 100644 index b5981f4..0000000 --- a/gson/provider/src/test/java/org/microbule/gson/provider/PersonService.java +++ /dev/null @@ -1,50 +0,0 @@ -/* - * Copyright (c) 2017 The Microbule Authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package org.microbule.gson.provider; - -import java.util.List; - -import javax.ws.rs.Consumes; -import javax.ws.rs.GET; -import javax.ws.rs.POST; -import javax.ws.rs.Path; -import javax.ws.rs.PathParam; -import javax.ws.rs.Produces; -import javax.ws.rs.core.MediaType; - -@Path("/") -public interface PersonService { -//---------------------------------------------------------------------------------------------------------------------- -// Other Methods -//---------------------------------------------------------------------------------------------------------------------- - - @GET - @Path("/people/{firstName}/{lastName}") - @Produces(MediaType.APPLICATION_JSON) - Person findPerson(@PathParam("firstName") String firstName, @PathParam("lastName") String lastName); - - @POST - @Path("/people") - @Consumes(MediaType.APPLICATION_JSON) - void addPerson(Person person); - - @GET - @Path("/people") - @Produces(MediaType.APPLICATION_JSON) - List all(); -} diff --git a/gson/spi/src/main/java/org/microbule/gson/spi/GsonBuilderCustomizer.java b/gson/spi/src/main/java/org/microbule/gson/spi/GsonBuilderCustomizer.java deleted file mode 100644 index 76cc8f6..0000000 --- a/gson/spi/src/main/java/org/microbule/gson/spi/GsonBuilderCustomizer.java +++ /dev/null @@ -1,24 +0,0 @@ -/* - * Copyright (c) 2017 The Microbule Authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package org.microbule.gson.spi; - -import com.google.gson.GsonBuilder; - -public interface GsonBuilderCustomizer { - void customize(GsonBuilder builder); -} diff --git a/gson/time/src/main/java/org/microbule/gson/time/JavaTimeGsonBuilderCustomizer.java b/gson/time/src/main/java/org/microbule/gson/time/JavaTimeGsonBuilderCustomizer.java deleted file mode 100644 index cb65b11..0000000 --- a/gson/time/src/main/java/org/microbule/gson/time/JavaTimeGsonBuilderCustomizer.java +++ /dev/null @@ -1,53 +0,0 @@ -package org.microbule.gson.time; - -import java.time.Duration; -import java.time.Instant; -import java.time.LocalDate; -import java.time.LocalDateTime; -import java.time.LocalTime; -import java.time.MonthDay; -import java.time.OffsetDateTime; -import java.time.OffsetTime; -import java.time.Period; -import java.time.Year; -import java.time.YearMonth; - -import javax.inject.Named; -import javax.inject.Singleton; - -import com.google.gson.GsonBuilder; -import org.microbule.gson.spi.GsonBuilderCustomizer; -import org.microbule.gson.util.StringValueAdapter; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -@Named("javaTimeGsonBuilderCustomizer") -@Singleton -public class JavaTimeGsonBuilderCustomizer implements GsonBuilderCustomizer { -//---------------------------------------------------------------------------------------------------------------------- -// Fields -//---------------------------------------------------------------------------------------------------------------------- - - private static final Logger LOGGER = LoggerFactory.getLogger(JavaTimeGsonBuilderCustomizer.class); - -//---------------------------------------------------------------------------------------------------------------------- -// GsonBuilderCustomizer Implementation -//---------------------------------------------------------------------------------------------------------------------- - - - @Override - public void customize(GsonBuilder builder) { - LOGGER.info("Adding GSON type adapters for JavaSE 8 Date/Time classes..."); - builder.registerTypeAdapter(Duration.class, StringValueAdapter.toStringAdapter(Duration::parse)); - builder.registerTypeAdapter(Instant.class, StringValueAdapter.toStringAdapter(Instant::parse)); - builder.registerTypeAdapter(LocalDate.class, StringValueAdapter.toStringAdapter(LocalDate::parse)); - builder.registerTypeAdapter(LocalDateTime.class, StringValueAdapter.toStringAdapter(LocalDateTime::parse)); - builder.registerTypeAdapter(LocalTime.class, StringValueAdapter.toStringAdapter(LocalTime::parse)); - builder.registerTypeAdapter(MonthDay.class, StringValueAdapter.toStringAdapter(MonthDay::parse)); - builder.registerTypeAdapter(OffsetDateTime.class, StringValueAdapter.toStringAdapter(OffsetDateTime::parse)); - builder.registerTypeAdapter(OffsetTime.class, StringValueAdapter.toStringAdapter(OffsetTime::parse)); - builder.registerTypeAdapter(Period.class, StringValueAdapter.toStringAdapter(Period::parse)); - builder.registerTypeAdapter(Year.class, StringValueAdapter.toStringAdapter(Year::parse)); - builder.registerTypeAdapter(YearMonth.class, StringValueAdapter.toStringAdapter(YearMonth::parse)); - } -} diff --git a/gson/time/src/main/resources/META-INF/beans.xml b/gson/time/src/main/resources/META-INF/beans.xml deleted file mode 100644 index 115b372..0000000 --- a/gson/time/src/main/resources/META-INF/beans.xml +++ /dev/null @@ -1,22 +0,0 @@ - - - - \ No newline at end of file diff --git a/gson/time/src/main/resources/OSGI-INF/blueprint/microbule-gson-time.xml b/gson/time/src/main/resources/OSGI-INF/blueprint/microbule-gson-time.xml deleted file mode 100644 index 1acda0e..0000000 --- a/gson/time/src/main/resources/OSGI-INF/blueprint/microbule-gson-time.xml +++ /dev/null @@ -1,25 +0,0 @@ - - - - - - - - - - \ No newline at end of file diff --git a/gson/time/src/test/java/org/microbule/gson/time/JavaTimeGsonBuilderCustomizerTest.java b/gson/time/src/test/java/org/microbule/gson/time/JavaTimeGsonBuilderCustomizerTest.java deleted file mode 100644 index 2ed854c..0000000 --- a/gson/time/src/test/java/org/microbule/gson/time/JavaTimeGsonBuilderCustomizerTest.java +++ /dev/null @@ -1,62 +0,0 @@ -package org.microbule.gson.time; - -import java.time.Duration; -import java.time.Instant; -import java.time.LocalDate; -import java.time.LocalDateTime; -import java.time.LocalTime; -import java.time.MonthDay; -import java.time.OffsetDateTime; -import java.time.OffsetTime; -import java.time.Period; -import java.time.Year; -import java.time.YearMonth; - -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; -import com.google.gson.JsonPrimitive; -import org.junit.Before; -import org.junit.Test; -import org.microbule.test.core.MicrobuleTestCase; - -public class JavaTimeGsonBuilderCustomizerTest extends MicrobuleTestCase { -//---------------------------------------------------------------------------------------------------------------------- -// Fields -//---------------------------------------------------------------------------------------------------------------------- - - private Gson gson; - -//---------------------------------------------------------------------------------------------------------------------- -// Other Methods -//---------------------------------------------------------------------------------------------------------------------- - - @Before - public void initGson() { - GsonBuilder builder = new GsonBuilder(); - new JavaTimeGsonBuilderCustomizer().customize(builder); - gson = builder.serializeNulls().create(); - } - - @Test - public void testJavaTypesSupported() { - assertTypeSupported(Duration.ofMinutes(5)); - assertTypeSupported(Instant.now()); - assertTypeSupported(LocalDate.now()); - assertTypeSupported(LocalDateTime.now()); - assertTypeSupported(LocalTime.now()); - assertTypeSupported(MonthDay.now()); - assertTypeSupported(OffsetDateTime.now()); - assertTypeSupported(OffsetTime.now()); - assertTypeSupported(Period.ofWeeks(3)); - assertTypeSupported(Year.now()); - assertTypeSupported(YearMonth.now()); - } - - @SuppressWarnings("unchecked") - private void assertTypeSupported(T value) { - final JsonPrimitive jsonValue = (JsonPrimitive)gson.toJsonTree(value); - assertEquals(value.toString(), jsonValue.getAsString()); - T parsed = (T)gson.fromJson(jsonValue, value.getClass()); - assertEquals(value, parsed); - } -} \ No newline at end of file diff --git a/gson/util/src/main/java/org/microbule/gson/util/NullSafeTypeAdapter.java b/gson/util/src/main/java/org/microbule/gson/util/NullSafeTypeAdapter.java deleted file mode 100644 index f936dbe..0000000 --- a/gson/util/src/main/java/org/microbule/gson/util/NullSafeTypeAdapter.java +++ /dev/null @@ -1,39 +0,0 @@ -package org.microbule.gson.util; - -import java.io.IOException; - -import com.google.gson.TypeAdapter; -import com.google.gson.stream.JsonReader; -import com.google.gson.stream.JsonToken; -import com.google.gson.stream.JsonWriter; - -public abstract class NullSafeTypeAdapter extends TypeAdapter { -//---------------------------------------------------------------------------------------------------------------------- -// Abstract Methods -//---------------------------------------------------------------------------------------------------------------------- - - protected abstract T readNonNull(JsonReader var1) throws IOException; - - protected abstract void writeNonNull(JsonWriter var1, T var2) throws IOException; - -//---------------------------------------------------------------------------------------------------------------------- -// Other Methods -//---------------------------------------------------------------------------------------------------------------------- - - public final T read(JsonReader in) throws IOException { - if (in.peek() == JsonToken.NULL) { - in.nextNull(); - return null; - } else { - return this.readNonNull(in); - } - } - - public final void write(JsonWriter out, T value) throws IOException { - if (value == null) { - out.nullValue(); - } else { - this.writeNonNull(out, value); - } - } -} diff --git a/gson/util/src/main/java/org/microbule/gson/util/StringValueAdapter.java b/gson/util/src/main/java/org/microbule/gson/util/StringValueAdapter.java deleted file mode 100644 index 5bb36ee..0000000 --- a/gson/util/src/main/java/org/microbule/gson/util/StringValueAdapter.java +++ /dev/null @@ -1,46 +0,0 @@ -package org.microbule.gson.util; - -import java.io.IOException; -import java.util.function.Function; - -import com.google.gson.TypeAdapter; -import com.google.gson.stream.JsonReader; -import com.google.gson.stream.JsonWriter; - -public class StringValueAdapter extends NullSafeTypeAdapter { -//---------------------------------------------------------------------------------------------------------------------- -// Fields -//---------------------------------------------------------------------------------------------------------------------- - - private final Function formatter; - private final Function parser; - -//---------------------------------------------------------------------------------------------------------------------- -// Static Methods -//---------------------------------------------------------------------------------------------------------------------- - - public static TypeAdapter toStringAdapter(Function parser) { - return new StringValueAdapter<>(Object::toString, parser); - } - -//---------------------------------------------------------------------------------------------------------------------- -// Constructors -//---------------------------------------------------------------------------------------------------------------------- - - public StringValueAdapter(Function formatter, Function parser) { - this.formatter = formatter; - this.parser = parser; - } - -//---------------------------------------------------------------------------------------------------------------------- -// Other Methods -//---------------------------------------------------------------------------------------------------------------------- - - protected final T readNonNull(JsonReader in) throws IOException { - return this.parser.apply(in.nextString()); - } - - protected final void writeNonNull(JsonWriter out, T value) throws IOException { - out.value(formatter.apply(value)); - } -} diff --git a/gson/util/src/test/java/org/microbule/gson/util/StringValueAdapterTest.java b/gson/util/src/test/java/org/microbule/gson/util/StringValueAdapterTest.java deleted file mode 100644 index a778b16..0000000 --- a/gson/util/src/test/java/org/microbule/gson/util/StringValueAdapterTest.java +++ /dev/null @@ -1,75 +0,0 @@ -package org.microbule.gson.util; - -import java.time.LocalDateTime; - -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; -import org.junit.Before; -import org.junit.Test; -import org.microbule.test.core.MicrobuleTestCase; - -public class StringValueAdapterTest extends MicrobuleTestCase { -//---------------------------------------------------------------------------------------------------------------------- -// Fields -//---------------------------------------------------------------------------------------------------------------------- - - private Gson gson; - -//---------------------------------------------------------------------------------------------------------------------- -// Other Methods -//---------------------------------------------------------------------------------------------------------------------- - - @Before - public void initGson() { - final GsonBuilder builder = new GsonBuilder(); - builder.registerTypeAdapter(LocalDateTime.class, StringValueAdapter.toStringAdapter(LocalDateTime::parse)); - gson = builder.serializeNulls().create(); - } - - @Test - public void testReadingNulls() { - final Holder holder = gson.fromJson("{\"now\":null}", Holder.class); - assertNull(holder.now); - } - - @Test - public void testReadingValues() { - final LocalDateTime now = LocalDateTime.now(); - final Holder holder = gson.fromJson(String.format("{\"now\":\"%s\"}", now.toString()), Holder.class); - assertEquals(now, holder.now); - } - - @Test - public void testWritingNulls() { - assertEquals("{\"now\":null}", gson.toJson(new Holder())); - } - - @Test - public void testWritingValues() { - final LocalDateTime now = LocalDateTime.now(); - assertEquals(String.format("{\"now\":\"%s\"}", now.toString()), gson.toJson(new Holder(now))); - } - -//---------------------------------------------------------------------------------------------------------------------- -// Inner Classes -//---------------------------------------------------------------------------------------------------------------------- - - private static class Holder { -//---------------------------------------------------------------------------------------------------------------------- -// Fields -//---------------------------------------------------------------------------------------------------------------------- - - private LocalDateTime now; - -//---------------------------------------------------------------------------------------------------------------------- -// Constructors -//---------------------------------------------------------------------------------------------------------------------- - - public Holder() { - } - - public Holder(LocalDateTime now) { - this.now = now; - } - } -} \ No newline at end of file diff --git a/gson/util/pom.xml b/jsonb/api/pom.xml similarity index 77% rename from gson/util/pom.xml rename to jsonb/api/pom.xml index f4641ff..befc4c0 100644 --- a/gson/util/pom.xml +++ b/jsonb/api/pom.xml @@ -21,20 +21,19 @@ 4.0.0 org.microbule - microbule-gson-parent + microbule-jsonb-parent 0.3.0-SNAPSHOT - microbule-gson-util - Microbule :: GSON :: Utilities + microbule-jsonb-api + Microbule :: JSON-B :: API bundle - org.microbule - microbule-test-core - 0.3.0-SNAPSHOT - test + javax.json.bind + javax.json.bind-api + ${json.bind.api.version} diff --git a/jsonb/api/src/main/java/org/microbule/jsonb/api/JsonbFactory.java b/jsonb/api/src/main/java/org/microbule/jsonb/api/JsonbFactory.java new file mode 100644 index 0000000..8859f8a --- /dev/null +++ b/jsonb/api/src/main/java/org/microbule/jsonb/api/JsonbFactory.java @@ -0,0 +1,11 @@ +package org.microbule.jsonb.api; + +import javax.json.bind.Jsonb; + +public interface JsonbFactory { +//---------------------------------------------------------------------------------------------------------------------- +// Other Methods +//---------------------------------------------------------------------------------------------------------------------- + + Jsonb createJsonb(); +} diff --git a/gson/core/pom.xml b/jsonb/core/pom.xml similarity index 70% rename from gson/core/pom.xml rename to jsonb/core/pom.xml index 1c7606a..7beab54 100644 --- a/gson/core/pom.xml +++ b/jsonb/core/pom.xml @@ -21,12 +21,12 @@ 4.0.0 org.microbule - microbule-gson-parent + microbule-jsonb-parent 0.3.0-SNAPSHOT - microbule-gson-core - Microbule :: GSON :: Core + microbule-jsonb-core + Microbule :: JSON-B :: Core bundle @@ -37,25 +37,18 @@ org.microbule - microbule-gson-api + microbule-jsonb-api 0.3.0-SNAPSHOT org.microbule - microbule-gson-spi + microbule-jsonb-spi 0.3.0-SNAPSHOT - org.microbule - microbule-test-core - 0.3.0-SNAPSHOT - test - - - org.microbule - microbule-container-core - 0.3.0-SNAPSHOT - test + javax.json.bind + javax.json.bind-api + ${json.bind.api.version} diff --git a/jsonb/core/src/main/java/org/microbule/jsonb/core/DefaultJsonbFactory.java b/jsonb/core/src/main/java/org/microbule/jsonb/core/DefaultJsonbFactory.java new file mode 100644 index 0000000..15c7632 --- /dev/null +++ b/jsonb/core/src/main/java/org/microbule/jsonb/core/DefaultJsonbFactory.java @@ -0,0 +1,65 @@ +package org.microbule.jsonb.core; + +import java.util.List; +import java.util.concurrent.CopyOnWriteArrayList; +import java.util.concurrent.atomic.AtomicReference; + +import javax.inject.Inject; +import javax.inject.Named; +import javax.inject.Singleton; +import javax.json.bind.Jsonb; +import javax.json.bind.JsonbBuilder; +import javax.json.bind.JsonbConfig; + +import org.microbule.container.api.MicrobuleContainer; +import org.microbule.container.api.PluginListener; +import org.microbule.jsonb.api.JsonbFactory; +import org.microbule.jsonb.spi.JsonbConfigCustomizer; + +@Singleton +@Named("jsonbFactory") +public class DefaultJsonbFactory implements JsonbFactory { +//---------------------------------------------------------------------------------------------------------------------- +// Fields +//---------------------------------------------------------------------------------------------------------------------- + + private final List customizers = new CopyOnWriteArrayList<>(); + private final AtomicReference jsonbRef = new AtomicReference<>(); + +//---------------------------------------------------------------------------------------------------------------------- +// Constructors +//---------------------------------------------------------------------------------------------------------------------- + + @Inject + public DefaultJsonbFactory(MicrobuleContainer container) { + container.addPluginListener(JsonbConfigCustomizer.class, new PluginListener() { + @Override + public boolean registerPlugin(JsonbConfigCustomizer plugin) { + customizers.add(plugin); + jsonbRef.set(null); + return true; + } + + @Override + public void unregisterPlugin(JsonbConfigCustomizer plugin) { + customizers.remove(plugin); + jsonbRef.set(null); + } + }); + } + +//---------------------------------------------------------------------------------------------------------------------- +// JsonbFactory Implementation +//---------------------------------------------------------------------------------------------------------------------- + + public Jsonb createJsonb() { + return jsonbRef.updateAndGet(prev -> { + if (prev == null) { + final JsonbConfig config = new JsonbConfig().withFormatting(true).withStrictIJSON(true); + customizers.forEach(customizer -> customizer.customize(config)); + return JsonbBuilder.create(config); + } + return prev; + }); + } +} diff --git a/gson/time/pom.xml b/jsonb/decorator/pom.xml similarity index 80% rename from gson/time/pom.xml rename to jsonb/decorator/pom.xml index 31b6180..401a6fa 100644 --- a/gson/time/pom.xml +++ b/jsonb/decorator/pom.xml @@ -21,30 +21,29 @@ 4.0.0 org.microbule - microbule-gson-parent + microbule-jsonb-parent 0.3.0-SNAPSHOT - microbule-gson-time - Microbule :: GSON :: JavaSE 8 Date/Time + microbule-jsonb-decorator + Microbule :: JSON-B :: Decorator bundle org.microbule - microbule-gson-util + microbule-jsonb-provider 0.3.0-SNAPSHOT org.microbule - microbule-gson-spi + microbule-spi 0.3.0-SNAPSHOT org.microbule - microbule-test-core + microbule-jsonb-api 0.3.0-SNAPSHOT - test diff --git a/gson/decorator/src/main/java/org/microbule/gson/decorator/GsonProxyDecorator.java b/jsonb/decorator/src/main/java/org/microbule/jsonb/decorator/JsonbProxyDecorator.java similarity index 67% rename from gson/decorator/src/main/java/org/microbule/gson/decorator/GsonProxyDecorator.java rename to jsonb/decorator/src/main/java/org/microbule/jsonb/decorator/JsonbProxyDecorator.java index a552a09..2ce0119 100644 --- a/gson/decorator/src/main/java/org/microbule/gson/decorator/GsonProxyDecorator.java +++ b/jsonb/decorator/src/main/java/org/microbule/jsonb/decorator/JsonbProxyDecorator.java @@ -1,32 +1,32 @@ -package org.microbule.gson.decorator; +package org.microbule.jsonb.decorator; import javax.inject.Inject; import javax.inject.Named; import javax.inject.Singleton; import org.microbule.config.api.Config; -import org.microbule.gson.api.GsonService; -import org.microbule.gson.provider.GsonProvider; -import org.microbule.gson.provider.JsonResponseParsingException; +import org.microbule.jsonb.api.JsonbFactory; +import org.microbule.jsonb.provider.JsonResponseParsingException; +import org.microbule.jsonb.provider.JsonbProvider; import org.microbule.spi.JaxrsProxyDecorator; import org.microbule.spi.JaxrsServiceDescriptor; -@Named("gsonProxyDecorator") @Singleton -public class GsonProxyDecorator implements JaxrsProxyDecorator { +@Named("jsonbProxyDecorator") +public class JsonbProxyDecorator implements JaxrsProxyDecorator { //---------------------------------------------------------------------------------------------------------------------- // Fields //---------------------------------------------------------------------------------------------------------------------- - private final GsonService gsonService; + private final JsonbFactory jsonbFactory; //---------------------------------------------------------------------------------------------------------------------- // Constructors //---------------------------------------------------------------------------------------------------------------------- @Inject - public GsonProxyDecorator(GsonService gsonService) { - this.gsonService = gsonService; + public JsonbProxyDecorator(JsonbFactory jsonbFactory) { + this.jsonbFactory = jsonbFactory; } //---------------------------------------------------------------------------------------------------------------------- @@ -35,11 +35,11 @@ public GsonProxyDecorator(GsonService gsonService) { @Override public void decorate(JaxrsServiceDescriptor descriptor, Config config) { - descriptor.addProvider(new GsonProvider(gsonService, JsonResponseParsingException::new)); + descriptor.addProvider(new JsonbProvider(jsonbFactory::createJsonb, JsonResponseParsingException::new)); } @Override public String name() { - return "gson"; + return "jsonb"; } } diff --git a/gson/decorator/src/main/java/org/microbule/gson/decorator/GsonServerDecorator.java b/jsonb/decorator/src/main/java/org/microbule/jsonb/decorator/JsonbServerDecorator.java similarity index 61% rename from gson/decorator/src/main/java/org/microbule/gson/decorator/GsonServerDecorator.java rename to jsonb/decorator/src/main/java/org/microbule/jsonb/decorator/JsonbServerDecorator.java index 6a3c66d..bfb138a 100644 --- a/gson/decorator/src/main/java/org/microbule/gson/decorator/GsonServerDecorator.java +++ b/jsonb/decorator/src/main/java/org/microbule/jsonb/decorator/JsonbServerDecorator.java @@ -1,34 +1,32 @@ -package org.microbule.gson.decorator; +package org.microbule.jsonb.decorator; import javax.inject.Inject; import javax.inject.Named; import javax.inject.Singleton; -import javax.ws.rs.core.Response; import org.microbule.config.api.Config; -import org.microbule.errormap.spi.ConstantErrorMapper; -import org.microbule.gson.api.GsonService; -import org.microbule.gson.provider.GsonProvider; -import org.microbule.gson.provider.JsonRequestParsingException; +import org.microbule.jsonb.api.JsonbFactory; +import org.microbule.jsonb.provider.JsonRequestParsingException; +import org.microbule.jsonb.provider.JsonbProvider; import org.microbule.spi.JaxrsServerDecorator; import org.microbule.spi.JaxrsServiceDescriptor; -@Named("gsonServerDecorator") @Singleton -public class GsonServerDecorator implements JaxrsServerDecorator { +@Named("jsonbServerDecorator") +public class JsonbServerDecorator implements JaxrsServerDecorator { //---------------------------------------------------------------------------------------------------------------------- // Fields //---------------------------------------------------------------------------------------------------------------------- - private final GsonService gsonService; + private final JsonbFactory jsonbFactory; //---------------------------------------------------------------------------------------------------------------------- // Constructors //---------------------------------------------------------------------------------------------------------------------- @Inject - public GsonServerDecorator(GsonService gsonService) { - this.gsonService = gsonService; + public JsonbServerDecorator(JsonbFactory jsonbFactory) { + this.jsonbFactory = jsonbFactory; } //---------------------------------------------------------------------------------------------------------------------- @@ -37,12 +35,11 @@ public GsonServerDecorator(GsonService gsonService) { @Override public void decorate(JaxrsServiceDescriptor descriptor, Config config) { - descriptor.addProvider(new GsonProvider(gsonService, JsonRequestParsingException::new)); - descriptor.addProvider(new ConstantErrorMapper(JsonRequestParsingException.class, Response.Status.BAD_REQUEST)); + descriptor.addProvider(new JsonbProvider(jsonbFactory::createJsonb, JsonRequestParsingException::new)); } @Override public String name() { - return "gson"; + return "jsonb"; } } diff --git a/gson/pom.xml b/jsonb/pom.xml similarity index 77% rename from gson/pom.xml rename to jsonb/pom.xml index fe7fd60..4d4b9f3 100644 --- a/gson/pom.xml +++ b/jsonb/pom.xml @@ -25,8 +25,8 @@ 0.3.0-SNAPSHOT - microbule-gson-parent - Microbule :: GSON :: Parent + microbule-jsonb-parent + Microbule :: JSON-B :: Parent pom @@ -35,15 +35,7 @@ core provider decorator - util - time + test - - - com.google.code.gson - gson - ${gson.version} - - diff --git a/gson/spi/pom.xml b/jsonb/provider/pom.xml similarity index 64% rename from gson/spi/pom.xml rename to jsonb/provider/pom.xml index 3e844a3..470cd3a 100644 --- a/gson/spi/pom.xml +++ b/jsonb/provider/pom.xml @@ -21,12 +21,24 @@ 4.0.0 org.microbule - microbule-gson-parent + microbule-jsonb-parent 0.3.0-SNAPSHOT - microbule-gson-spi - Microbule :: GSON :: SPI + microbule-jsonb-provider + Microbule :: JSON-B :: Provider bundle + + + org.microbule + microbule-util + 0.3.0-SNAPSHOT + + + javax.json.bind + javax.json.bind-api + ${json.bind.api.version} + + diff --git a/gson/provider/src/main/java/org/microbule/gson/provider/JsonRequestParsingException.java b/jsonb/provider/src/main/java/org/microbule/jsonb/provider/JsonRequestParsingException.java similarity index 74% rename from gson/provider/src/main/java/org/microbule/gson/provider/JsonRequestParsingException.java rename to jsonb/provider/src/main/java/org/microbule/jsonb/provider/JsonRequestParsingException.java index cbf824a..86d1918 100644 --- a/gson/provider/src/main/java/org/microbule/gson/provider/JsonRequestParsingException.java +++ b/jsonb/provider/src/main/java/org/microbule/jsonb/provider/JsonRequestParsingException.java @@ -1,6 +1,7 @@ -package org.microbule.gson.provider; +package org.microbule.jsonb.provider; + +import javax.json.bind.JsonbException; -import com.google.gson.JsonSyntaxException; import org.microbule.util.exception.MicrobuleException; public class JsonRequestParsingException extends MicrobuleException { @@ -8,7 +9,7 @@ public class JsonRequestParsingException extends MicrobuleException { // Constructors //---------------------------------------------------------------------------------------------------------------------- - public JsonRequestParsingException(JsonSyntaxException e) { + public JsonRequestParsingException(JsonbException e) { super(e, e.getMessage()); } } diff --git a/gson/provider/src/main/java/org/microbule/gson/provider/JsonResponseParsingException.java b/jsonb/provider/src/main/java/org/microbule/jsonb/provider/JsonResponseParsingException.java similarity index 74% rename from gson/provider/src/main/java/org/microbule/gson/provider/JsonResponseParsingException.java rename to jsonb/provider/src/main/java/org/microbule/jsonb/provider/JsonResponseParsingException.java index 097e0af..4b00f9e 100644 --- a/gson/provider/src/main/java/org/microbule/gson/provider/JsonResponseParsingException.java +++ b/jsonb/provider/src/main/java/org/microbule/jsonb/provider/JsonResponseParsingException.java @@ -1,6 +1,7 @@ -package org.microbule.gson.provider; +package org.microbule.jsonb.provider; + +import javax.json.bind.JsonbException; -import com.google.gson.JsonSyntaxException; import org.microbule.util.exception.MicrobuleException; public class JsonResponseParsingException extends MicrobuleException { @@ -8,7 +9,7 @@ public class JsonResponseParsingException extends MicrobuleException { // Constructors //---------------------------------------------------------------------------------------------------------------------- - public JsonResponseParsingException(JsonSyntaxException e) { + public JsonResponseParsingException(JsonbException e) { super(e, e.getMessage()); } } diff --git a/gson/provider/src/main/java/org/microbule/gson/provider/GsonProvider.java b/jsonb/provider/src/main/java/org/microbule/jsonb/provider/JsonbProvider.java similarity index 70% rename from gson/provider/src/main/java/org/microbule/gson/provider/GsonProvider.java rename to jsonb/provider/src/main/java/org/microbule/jsonb/provider/JsonbProvider.java index 35a23ee..fbb9527 100644 --- a/gson/provider/src/main/java/org/microbule/gson/provider/GsonProvider.java +++ b/jsonb/provider/src/main/java/org/microbule/jsonb/provider/JsonbProvider.java @@ -1,4 +1,4 @@ -package org.microbule.gson.provider; +package org.microbule.jsonb.provider; import java.io.IOException; import java.io.InputStream; @@ -7,8 +7,12 @@ import java.io.OutputStreamWriter; import java.lang.annotation.Annotation; import java.lang.reflect.Type; +import java.nio.charset.StandardCharsets; import java.util.function.Function; +import java.util.function.Supplier; +import javax.json.bind.Jsonb; +import javax.json.bind.JsonbException; import javax.ws.rs.Consumes; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; @@ -17,28 +21,25 @@ import javax.ws.rs.ext.MessageBodyWriter; import javax.ws.rs.ext.Provider; -import com.google.common.base.Charsets; -import com.google.gson.JsonSyntaxException; import org.apache.commons.lang3.ObjectUtils; -import org.microbule.gson.api.GsonService; @Provider @Produces(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON) -public class GsonProvider implements MessageBodyReader,MessageBodyWriter { +public class JsonbProvider implements MessageBodyReader, MessageBodyWriter { //---------------------------------------------------------------------------------------------------------------------- // Fields //---------------------------------------------------------------------------------------------------------------------- - private final GsonService gsonService; - private final Function exceptionProvider; + private final Supplier jsonBuilderSupplier; + private final Function exceptionProvider; //---------------------------------------------------------------------------------------------------------------------- // Constructors //---------------------------------------------------------------------------------------------------------------------- - public GsonProvider(GsonService gsonService, Function exceptionProvider) { - this.gsonService = gsonService; + public JsonbProvider(Supplier jsonBuilderSupplier, Function exceptionProvider) { + this.jsonBuilderSupplier = jsonBuilderSupplier; this.exceptionProvider = exceptionProvider; } @@ -53,10 +54,10 @@ public boolean isReadable(Class type, Type genericType, Annotation[] annotati @Override public Object readFrom(Class type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap httpHeaders, InputStream entityStream) throws IOException { - try (InputStreamReader streamReader = new InputStreamReader(entityStream, Charsets.UTF_8)) { + try (InputStreamReader streamReader = new InputStreamReader(entityStream, StandardCharsets.UTF_8)) { try { - return gsonService.parse(streamReader, resolveType(type, genericType)); - } catch (JsonSyntaxException e) { + return jsonBuilderSupplier.get().fromJson(streamReader, resolveType(type, genericType)); + } catch (JsonbException e) { throw exceptionProvider.apply(e); } } @@ -67,7 +68,7 @@ public Object readFrom(Class type, Type genericType, Annotation[] annota //---------------------------------------------------------------------------------------------------------------------- @Override - public long getSize(Object o, Class type, Type genericType, Annotation[] annotations, MediaType mediaType) { + public long getSize(Object object, Class type, Type genericType, Annotation[] annotations, MediaType mediaType) { return -1; } @@ -77,9 +78,9 @@ public boolean isWriteable(Class type, Type genericType, Annotation[] annotat } @Override - public void writeTo(Object o, Class type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap httpHeaders, OutputStream entityStream) throws IOException { - try (OutputStreamWriter writer = new OutputStreamWriter(entityStream, Charsets.UTF_8)) { - gsonService.append(o, resolveType(type, genericType), writer); + public void writeTo(Object object, Class type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap httpHeaders, OutputStream entityStream) throws IOException { + try (OutputStreamWriter writer = new OutputStreamWriter(entityStream, StandardCharsets.UTF_8)) { + jsonBuilderSupplier.get().toJson(object, resolveType(type, genericType), writer); } } diff --git a/gson/api/pom.xml b/jsonb/spi/pom.xml similarity index 73% rename from gson/api/pom.xml rename to jsonb/spi/pom.xml index ff64cb9..694aa46 100644 --- a/gson/api/pom.xml +++ b/jsonb/spi/pom.xml @@ -21,12 +21,19 @@ 4.0.0 org.microbule - microbule-gson-parent + microbule-jsonb-parent 0.3.0-SNAPSHOT - microbule-gson-api - Microbule :: GSON :: API + microbule-jsonb-spi + Microbule :: JSON-B :: SPI bundle + + + javax.json.bind + javax.json.bind-api + ${json.bind.api.version} + + diff --git a/jsonb/spi/src/main/java/org/microbule/jsonb/spi/JsonbConfigCustomizer.java b/jsonb/spi/src/main/java/org/microbule/jsonb/spi/JsonbConfigCustomizer.java new file mode 100644 index 0000000..39ecea7 --- /dev/null +++ b/jsonb/spi/src/main/java/org/microbule/jsonb/spi/JsonbConfigCustomizer.java @@ -0,0 +1,11 @@ +package org.microbule.jsonb.spi; + +import javax.json.bind.JsonbConfig; + +public interface JsonbConfigCustomizer { +//---------------------------------------------------------------------------------------------------------------------- +// Other Methods +//---------------------------------------------------------------------------------------------------------------------- + + void customize(JsonbConfig config); +} diff --git a/jsonb/test/pom.xml b/jsonb/test/pom.xml new file mode 100644 index 0000000..9dcead5 --- /dev/null +++ b/jsonb/test/pom.xml @@ -0,0 +1,49 @@ + + + + + + 4.0.0 + + org.microbule + microbule-jsonb-parent + 0.3.0-SNAPSHOT + + + microbule-jsonb-test + Microbule :: JSON-B :: Test + bundle + + + org.microbule.jsonb.test.JsonbActivator + + + + org.osgi + org.osgi.core + ${osgi.version} + provided + + + javax.json.bind + javax.json.bind-api + ${json.bind.api.version} + + + + diff --git a/jsonb/test/src/main/java/org/microbule/jsonb/test/JsonbActivator.java b/jsonb/test/src/main/java/org/microbule/jsonb/test/JsonbActivator.java new file mode 100644 index 0000000..6de1ff4 --- /dev/null +++ b/jsonb/test/src/main/java/org/microbule/jsonb/test/JsonbActivator.java @@ -0,0 +1,65 @@ +package org.microbule.jsonb.test; + +import javax.json.bind.JsonbBuilder; + +import org.osgi.framework.BundleActivator; +import org.osgi.framework.BundleContext; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class JsonbActivator implements BundleActivator { +//---------------------------------------------------------------------------------------------------------------------- +// Fields +//---------------------------------------------------------------------------------------------------------------------- + + private static final Logger LOGGER = LoggerFactory.getLogger(JsonbActivator.class); + +//---------------------------------------------------------------------------------------------------------------------- +// BundleActivator Implementation +//---------------------------------------------------------------------------------------------------------------------- + + + @Override + public void start(BundleContext context) throws Exception { + LOGGER.info(JsonbBuilder.create().toJson(new Person("Apache", "Johnzon"))); + } + + @Override + public void stop(BundleContext context) throws Exception { + + } + +//---------------------------------------------------------------------------------------------------------------------- +// Inner Classes +//---------------------------------------------------------------------------------------------------------------------- + + public static class Person { +//---------------------------------------------------------------------------------------------------------------------- +// Fields +//---------------------------------------------------------------------------------------------------------------------- + + private final String firstName; + private final String lastName; + +//---------------------------------------------------------------------------------------------------------------------- +// Constructors +//---------------------------------------------------------------------------------------------------------------------- + + public Person(String firstName, String lastName) { + this.firstName = firstName; + this.lastName = lastName; + } + +//---------------------------------------------------------------------------------------------------------------------- +// Getter/Setter Methods +//---------------------------------------------------------------------------------------------------------------------- + + public String getFirstName() { + return firstName; + } + + public String getLastName() { + return lastName; + } + } +} diff --git a/metrics/decorator/pom.xml b/metrics/decorator/pom.xml index 0adb0c8..aee44ba 100644 --- a/metrics/decorator/pom.xml +++ b/metrics/decorator/pom.xml @@ -31,29 +31,34 @@ bundle + + javax.json + javax.json-api + ${json.api.version} + org.microbule - microbule-util + microbule-jsonb-spi 0.3.0-SNAPSHOT org.microbule - microbule-metrics-annotation + microbule-util 0.3.0-SNAPSHOT org.microbule - microbule-metrics-api + microbule-metrics-annotation 0.3.0-SNAPSHOT org.microbule - microbule-spi + microbule-metrics-api 0.3.0-SNAPSHOT org.microbule - microbule-gson-spi + microbule-spi 0.3.0-SNAPSHOT @@ -70,13 +75,13 @@ org.microbule - microbule-gson-decorator + microbule-jsonb-decorator 0.3.0-SNAPSHOT test org.microbule - microbule-gson-core + microbule-jsonb-core 0.3.0-SNAPSHOT test diff --git a/metrics/decorator/src/main/java/org/microbule/metrics/decorator/MetricsGsonBuilderCustomizer.java b/metrics/decorator/src/main/java/org/microbule/metrics/decorator/MetricsGsonBuilderCustomizer.java deleted file mode 100644 index 10b9563..0000000 --- a/metrics/decorator/src/main/java/org/microbule/metrics/decorator/MetricsGsonBuilderCustomizer.java +++ /dev/null @@ -1,75 +0,0 @@ -package org.microbule.metrics.decorator; - -import java.lang.reflect.Type; -import java.util.concurrent.TimeUnit; - -import javax.inject.Named; -import javax.inject.Singleton; - -import com.codahale.metrics.Snapshot; -import com.codahale.metrics.Timer; -import com.google.gson.GsonBuilder; -import com.google.gson.JsonElement; -import com.google.gson.JsonObject; -import com.google.gson.JsonSerializationContext; -import com.google.gson.JsonSerializer; -import org.microbule.gson.spi.GsonBuilderCustomizer; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -@Named("metricsGsonBuilderCustomizer") -@Singleton -public class MetricsGsonBuilderCustomizer implements GsonBuilderCustomizer { -//---------------------------------------------------------------------------------------------------------------------- -// Fields -//---------------------------------------------------------------------------------------------------------------------- - - private static final double DURATION_FACTOR = 1.0 / TimeUnit.SECONDS.toNanos(1); - private static final Logger LOGGER = LoggerFactory.getLogger(MetricsGsonBuilderCustomizer.class); - -//---------------------------------------------------------------------------------------------------------------------- -// GsonBuilderCustomizer Implementation -//---------------------------------------------------------------------------------------------------------------------- - - @Override - public void customize(GsonBuilder builder) { - LOGGER.info("Adding GSON type adapter for DropWizard Metrics' Timer class..."); - builder.registerTypeAdapter(Timer.class, new TimerSerializer()); - } - -//---------------------------------------------------------------------------------------------------------------------- -// Inner Classes -//---------------------------------------------------------------------------------------------------------------------- - - private static class TimerSerializer implements JsonSerializer { -//---------------------------------------------------------------------------------------------------------------------- -// JsonSerializer Implementation -//---------------------------------------------------------------------------------------------------------------------- - - @Override - public JsonElement serialize(Timer timer, Type typeOfSrc, JsonSerializationContext context) { - JsonObject json = new JsonObject(); - final Snapshot snapshot = timer.getSnapshot(); - json.addProperty("count", timer.getCount()); - json.addProperty("max", snapshot.getMax() * DURATION_FACTOR); - json.addProperty("mean", snapshot.getMean() * DURATION_FACTOR); - json.addProperty("min", snapshot.getMin() * DURATION_FACTOR); - - json.addProperty("p50", snapshot.getMedian() * DURATION_FACTOR); - json.addProperty("p75", snapshot.get75thPercentile() * DURATION_FACTOR); - json.addProperty("p95", snapshot.get95thPercentile() * DURATION_FACTOR); - json.addProperty("p98", snapshot.get98thPercentile() * DURATION_FACTOR); - json.addProperty("p99", snapshot.get99thPercentile() * DURATION_FACTOR); - json.addProperty("p999", snapshot.get999thPercentile() * DURATION_FACTOR); - - json.addProperty("stddev", snapshot.getStdDev() * DURATION_FACTOR); - json.addProperty("m15_rate", timer.getFifteenMinuteRate()); - json.addProperty("m1_rate", timer.getOneMinuteRate()); - json.addProperty("m5_rate", timer.getFiveMinuteRate()); - json.addProperty("mean_rate", timer.getMeanRate()); - json.addProperty("duration_units", "seconds"); - json.addProperty("rate_units", "calls/second"); - return json; - } - } -} diff --git a/metrics/decorator/src/main/java/org/microbule/metrics/decorator/MetricsJsonbConfigCustomizer.java b/metrics/decorator/src/main/java/org/microbule/metrics/decorator/MetricsJsonbConfigCustomizer.java new file mode 100644 index 0000000..bc732b1 --- /dev/null +++ b/metrics/decorator/src/main/java/org/microbule/metrics/decorator/MetricsJsonbConfigCustomizer.java @@ -0,0 +1,67 @@ +package org.microbule.metrics.decorator; + +import java.util.concurrent.TimeUnit; + +import javax.inject.Named; +import javax.inject.Singleton; +import javax.json.bind.JsonbConfig; +import javax.json.bind.serializer.JsonbSerializer; +import javax.json.bind.serializer.SerializationContext; +import javax.json.stream.JsonGenerator; + +import com.codahale.metrics.Snapshot; +import com.codahale.metrics.Timer; +import org.microbule.jsonb.spi.JsonbConfigCustomizer; + +@Named("metricsGsonBuilderCustomizer") +@Singleton +public class MetricsJsonbConfigCustomizer implements JsonbConfigCustomizer { +//---------------------------------------------------------------------------------------------------------------------- +// Fields +//---------------------------------------------------------------------------------------------------------------------- + + private static final double DURATION_FACTOR = 1.0 / TimeUnit.SECONDS.toNanos(1); + +//---------------------------------------------------------------------------------------------------------------------- +// JsonbConfigCustomizer Implementation +//---------------------------------------------------------------------------------------------------------------------- + + @Override + public void customize(JsonbConfig config) { + config.withSerializers(new TimerSerializer()); + } + +//---------------------------------------------------------------------------------------------------------------------- +// Inner Classes +//---------------------------------------------------------------------------------------------------------------------- + + private static class TimerSerializer implements JsonbSerializer { +//---------------------------------------------------------------------------------------------------------------------- +// JsonbSerializer Implementation +//---------------------------------------------------------------------------------------------------------------------- + + @Override + public void serialize(Timer timer, JsonGenerator generator, SerializationContext ctx) { + final Snapshot snapshot = timer.getSnapshot(); + generator.write("count", timer.getCount()); + generator.write("max", snapshot.getMax() * DURATION_FACTOR); + generator.write("mean", snapshot.getMean() * DURATION_FACTOR); + generator.write("min", snapshot.getMin() * DURATION_FACTOR); + + generator.write("p50", snapshot.getMedian() * DURATION_FACTOR); + generator.write("p75", snapshot.get75thPercentile() * DURATION_FACTOR); + generator.write("p95", snapshot.get95thPercentile() * DURATION_FACTOR); + generator.write("p98", snapshot.get98thPercentile() * DURATION_FACTOR); + generator.write("p99", snapshot.get99thPercentile() * DURATION_FACTOR); + generator.write("p999", snapshot.get999thPercentile() * DURATION_FACTOR); + + generator.write("stddev", snapshot.getStdDev() * DURATION_FACTOR); + generator.write("m15_rate", timer.getFifteenMinuteRate()); + generator.write("m1_rate", timer.getOneMinuteRate()); + generator.write("m5_rate", timer.getFiveMinuteRate()); + generator.write("mean_rate", timer.getMeanRate()); + generator.write("duration_units", "seconds"); + generator.write("rate_units", "calls/second"); + } + } +} diff --git a/metrics/decorator/src/main/resources/OSGI-INF/blueprint/microbule-metrics-decorator.xml b/metrics/decorator/src/main/resources/OSGI-INF/blueprint/microbule-metrics-decorator.xml index 5fc2c2a..3f1ebb1 100644 --- a/metrics/decorator/src/main/resources/OSGI-INF/blueprint/microbule-metrics-decorator.xml +++ b/metrics/decorator/src/main/resources/OSGI-INF/blueprint/microbule-metrics-decorator.xml @@ -27,7 +27,7 @@ - + - + \ No newline at end of file diff --git a/metrics/decorator/src/test/java/org/microbule/metrics/decorator/MetricsDecoratorTest.java b/metrics/decorator/src/test/java/org/microbule/metrics/decorator/MetricsDecoratorTest.java index 20f0f63..91fac6c 100644 --- a/metrics/decorator/src/test/java/org/microbule/metrics/decorator/MetricsDecoratorTest.java +++ b/metrics/decorator/src/test/java/org/microbule/metrics/decorator/MetricsDecoratorTest.java @@ -9,9 +9,9 @@ import com.codahale.metrics.Timer; import org.junit.Test; import org.microbule.container.core.SimpleContainer; -import org.microbule.gson.core.DefaultGsonService; -import org.microbule.gson.decorator.GsonProxyDecorator; -import org.microbule.gson.decorator.GsonServerDecorator; +import org.microbule.jsonb.core.DefaultJsonbFactory; +import org.microbule.jsonb.decorator.JsonbProxyDecorator; +import org.microbule.jsonb.decorator.JsonbServerDecorator; import org.microbule.metrics.core.DefaultMetricsService; import org.microbule.metrics.core.strategy.ExponentiallyDecayingTimingStrategy; import org.microbule.metrics.core.strategy.SlidingTimeWindowTimingStrategy; @@ -25,7 +25,7 @@ public class MetricsDecoratorTest extends JaxrsServerTestCase { //---------------------------------------------------------------------------------------------------------------------- private DefaultMetricsService metricsService; - private DefaultGsonService gsonService; + private DefaultJsonbFactory jsonbFactory; //---------------------------------------------------------------------------------------------------------------------- // Other Methods @@ -40,11 +40,11 @@ protected void addBeans(SimpleContainer container) { container.addBean(new SlidingWindowTimingStrategy()); container.addBean(new UniformTimingStrategy()); container.addBean(new MetricsDecorator(metricsService)); - gsonService = new DefaultGsonService(container); - container.addBean(gsonService); - container.addBean(new MetricsGsonBuilderCustomizer()); - container.addBean(new GsonServerDecorator(gsonService)); - container.addBean(new GsonProxyDecorator(gsonService)); + jsonbFactory = new DefaultJsonbFactory(container); + container.addBean(jsonbFactory); + container.addBean(new MetricsJsonbConfigCustomizer()); + container.addBean(new JsonbServerDecorator(jsonbFactory)); + container.addBean(new JsonbProxyDecorator(jsonbFactory)); } @Override @@ -72,7 +72,7 @@ public void testDefaultTiming() { public void testMetricsFilter() { Response response = createWebTarget().queryParam("_metrics", "").request(MediaType.APPLICATION_JSON_TYPE).get(); assertEquals(200, response.getStatus()); - MetricsResponse metricsResponse = gsonService.parse(new StringReader(response.readEntity(String.class)), MetricsResponse.class); + MetricsResponse metricsResponse = jsonbFactory.createJsonb().fromJson(new StringReader(response.readEntity(String.class)), MetricsResponse.class); metricsResponse.getTimers().forEach((k,v) -> { assertTrue(k.startsWith("TimedResource")); diff --git a/pom.xml b/pom.xml index 42e1918..23ec271 100644 --- a/pom.xml +++ b/pom.xml @@ -51,7 +51,6 @@ timeout circuitbreaker tracer - gson example features itest @@ -65,6 +64,7 @@ scheduler metrics version + jsonb @@ -84,11 +84,13 @@ 3.2.2 1.1.0 2.2.6 - 2.7 21.0 5.2.4.Final 2.2.5 3.3.0.Final + 1.1.1 + 1.1 + 1.0 4.12 4.1.1 2.7.22 @@ -173,7 +175,12 @@ slf4j-api ${slf4j.version} - + + org.apache.johnzon + johnzon-jsonb + ${johnzon.version} + test + diff --git a/util/pom.xml b/util/pom.xml index 4dcd2a7..d6c4d17 100644 --- a/util/pom.xml +++ b/util/pom.xml @@ -32,9 +32,9 @@ - com.google.code.gson - gson - ${gson.version} + javax.json.bind + javax.json.bind-api + ${json.bind.api.version} com.google.guava diff --git a/util/src/main/java/org/microbule/util/jaxrs/WebTargetUtils.java b/util/src/main/java/org/microbule/util/jaxrs/WebTargetUtils.java index 4d0e00d..fe081c7 100644 --- a/util/src/main/java/org/microbule/util/jaxrs/WebTargetUtils.java +++ b/util/src/main/java/org/microbule/util/jaxrs/WebTargetUtils.java @@ -19,19 +19,14 @@ import java.util.Optional; +import javax.json.bind.Jsonb; import javax.ws.rs.client.WebTarget; import javax.ws.rs.core.Response; -import com.google.gson.Gson; -import com.google.gson.reflect.TypeToken; +import com.google.common.reflect.TypeToken; -public final class WebTargetUtils { -//---------------------------------------------------------------------------------------------------------------------- -// Fields -//---------------------------------------------------------------------------------------------------------------------- - - private static final Gson GSON = new Gson(); +public final class WebTargetUtils { //---------------------------------------------------------------------------------------------------------------------- // Static Methods //---------------------------------------------------------------------------------------------------------------------- @@ -44,17 +39,21 @@ public static WebTarget extend(WebTarget baseTarget, String... paths) { return answer; } - public static Optional parseJsonResponse(Response response, Class type) { - return parseJsonResponse(response, TypeToken.get(type)); - } - - public static Optional parseJsonResponse(Response response, TypeToken token) { + public static Optional parseResponse(Response response, Jsonb jsonb, TypeToken typeToken) { if (Response.Status.OK.getStatusCode() == response.getStatus()) { - return Optional.of(GSON.fromJson(response.readEntity(String.class), token.getType())); + return Optional.of(jsonb.fromJson(response.readEntity(String.class), typeToken.getType())); } return Optional.empty(); } + public static Optional parseResponse(Response response, Jsonb jsonb, Class type) { + return parseResponse(response, jsonb, TypeToken.of(type)); + } + +//---------------------------------------------------------------------------------------------------------------------- +// Constructors +//---------------------------------------------------------------------------------------------------------------------- + private WebTargetUtils() { } diff --git a/util/src/test/java/org/microbule/util/jaxrs/WebTargetUtilsTest.java b/util/src/test/java/org/microbule/util/jaxrs/WebTargetUtilsTest.java index a1631d2..bc7fa20 100644 --- a/util/src/test/java/org/microbule/util/jaxrs/WebTargetUtilsTest.java +++ b/util/src/test/java/org/microbule/util/jaxrs/WebTargetUtilsTest.java @@ -17,14 +17,9 @@ package org.microbule.util.jaxrs; -import java.util.Optional; - import javax.ws.rs.client.ClientBuilder; import javax.ws.rs.client.WebTarget; -import javax.ws.rs.core.MediaType; -import javax.ws.rs.core.Response; -import com.google.gson.Gson; import org.junit.Test; import org.microbule.test.core.MockObjectTestCase; @@ -44,57 +39,4 @@ public void testExtend() { public void testIsUtilClass() throws Exception { assertIsUtilsClass(WebTargetUtils.class); } - - @Test - public void testParseSuccessfulResponse() { - Gson gson = new Gson(); - - final Response response = Response.ok(gson.toJson(new Person("Slappy", "White"))).type(MediaType.APPLICATION_JSON_TYPE).build(); - final Optional personOptional = WebTargetUtils.parseJsonResponse(response, Person.class); - assertTrue(personOptional.isPresent()); - Person person = personOptional.get(); - assertEquals("Slappy", person.getFirstName()); - assertEquals("White", person.getLastName()); - } - - @Test - public void testParseUnsuccessfulResponse() { - final Response response = Response.serverError().build(); - final Optional personOptional = WebTargetUtils.parseJsonResponse(response, Person.class); - assertFalse(personOptional.isPresent()); - } - -//---------------------------------------------------------------------------------------------------------------------- -// Inner Classes -//---------------------------------------------------------------------------------------------------------------------- - - public static class Person { -//---------------------------------------------------------------------------------------------------------------------- -// Fields -//---------------------------------------------------------------------------------------------------------------------- - - private final String firstName; - private final String lastName; - -//---------------------------------------------------------------------------------------------------------------------- -// Constructors -//---------------------------------------------------------------------------------------------------------------------- - - public Person(String firstName, String lastName) { - this.firstName = firstName; - this.lastName = lastName; - } - -//---------------------------------------------------------------------------------------------------------------------- -// Getter/Setter Methods -//---------------------------------------------------------------------------------------------------------------------- - - public String getFirstName() { - return firstName; - } - - public String getLastName() { - return lastName; - } - } } \ No newline at end of file diff --git a/version/pom.xml b/version/pom.xml index 023046e..5abf7a0 100644 --- a/version/pom.xml +++ b/version/pom.xml @@ -48,13 +48,13 @@ org.microbule - microbule-gson-decorator + microbule-jsonb-decorator 0.3.0-SNAPSHOT test org.microbule - microbule-gson-core + microbule-jsonb-core 0.3.0-SNAPSHOT test diff --git a/version/src/test/java/org/microbule/version/decorator/VersionDecoratorTest.java b/version/src/test/java/org/microbule/version/decorator/VersionDecoratorTest.java index 9e93ea8..d0717fd 100644 --- a/version/src/test/java/org/microbule/version/decorator/VersionDecoratorTest.java +++ b/version/src/test/java/org/microbule/version/decorator/VersionDecoratorTest.java @@ -7,23 +7,23 @@ import org.junit.Test; import org.microbule.container.core.SimpleContainer; -import org.microbule.gson.api.GsonService; -import org.microbule.gson.core.DefaultGsonService; -import org.microbule.gson.decorator.GsonProxyDecorator; -import org.microbule.gson.decorator.GsonServerDecorator; +import org.microbule.jsonb.api.JsonbFactory; +import org.microbule.jsonb.core.DefaultJsonbFactory; +import org.microbule.jsonb.decorator.JsonbProxyDecorator; +import org.microbule.jsonb.decorator.JsonbServerDecorator; import org.microbule.test.core.hello.HelloService; import org.microbule.test.server.hello.HelloTestCase; public class VersionDecoratorTest extends HelloTestCase { - private GsonService gsonService; + private JsonbFactory jsonbFactory; @Override protected void addBeans(SimpleContainer container) { - gsonService = new DefaultGsonService(container); - container.addBean(gsonService); - container.addBean(new GsonServerDecorator(gsonService)); - container.addBean(new GsonProxyDecorator(gsonService)); + jsonbFactory = new DefaultJsonbFactory(container); + container.addBean(jsonbFactory); + container.addBean(new JsonbServerDecorator(jsonbFactory)); + container.addBean(new JsonbProxyDecorator(jsonbFactory)); container.addBean(new VersionDecorator()); } @@ -31,7 +31,7 @@ protected void addBeans(SimpleContainer container) { public void testGetVersion() { final Response response = createWebTarget().queryParam("_version", "bogus").request(MediaType.APPLICATION_JSON_TYPE).get(); assertEquals(200, response.getStatus()); - final VersionResponse versionResponse = gsonService.parse(new StringReader(response.readEntity(String.class)), VersionResponse.class); + final VersionResponse versionResponse = jsonbFactory.createJsonb().fromJson(new StringReader(response.readEntity(String.class)), VersionResponse.class); final Package pkg = HelloService.class.getPackage(); assertEquals(pkg.getImplementationVersion(), versionResponse.getVersion()); assertEquals(pkg.getImplementationTitle(), versionResponse.getTitle());