diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar deleted file mode 100644 index e708b1c023..0000000000 Binary files a/gradle/wrapper/gradle-wrapper.jar and /dev/null differ diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties deleted file mode 100644 index da9702f9e7..0000000000 --- a/gradle/wrapper/gradle-wrapper.properties +++ /dev/null @@ -1,5 +0,0 @@ -distributionBase=GRADLE_USER_HOME -distributionPath=wrapper/dists -distributionUrl=https\://services.gradle.org/distributions/gradle-6.8-bin.zip -zipStoreBase=GRADLE_USER_HOME -zipStorePath=wrapper/dists diff --git a/jackson-modules/jackson-annotations/README.md b/jackson-modules/jackson-annotations/README.md deleted file mode 100644 index 783a06605b..0000000000 --- a/jackson-modules/jackson-annotations/README.md +++ /dev/null @@ -1,9 +0,0 @@ -## Jackson Annotations - -This module contains articles about Jackson annotations. - -### Relevant Articles: -- [Guide to @JsonFormat in Jackson](https://www.baeldung.com/jackson-jsonformat) -- [More Jackson Annotations](https://www.baeldung.com/jackson-advanced-annotations) -- [Jackson – Bidirectional Relationships](https://www.baeldung.com/jackson-bidirectional-relationships-and-infinite-recursion) -- [Jackson JSON Views](https://www.baeldung.com/jackson-json-view-annotation) diff --git a/jackson-modules/jackson-annotations/pom.xml b/jackson-modules/jackson-annotations/pom.xml deleted file mode 100644 index 0da73e5791..0000000000 --- a/jackson-modules/jackson-annotations/pom.xml +++ /dev/null @@ -1,50 +0,0 @@ - - - 4.0.0 - jackson-annotations - 0.0.1-SNAPSHOT - jackson-annotations - - - com.ossez - jackson-modules - 0.0.2-SNAPSHOT - - - - - com.fasterxml.jackson.module - jackson-module-jsonSchema - ${jackson.version} - - - io.rest-assured - json-path - ${rest-assured.version} - test - - - org.assertj - assertj-core - ${assertj.version} - test - - - - - jackson-annotations - - - src/main/resources - true - - - - - - 3.1.1 - - - \ No newline at end of file diff --git a/jackson-modules/jackson-annotations/src/main/java/com/ossez/jackson/bidirection/CustomListDeserializer.java b/jackson-modules/jackson-annotations/src/main/java/com/ossez/jackson/bidirection/CustomListDeserializer.java deleted file mode 100644 index 5e46c0abd5..0000000000 --- a/jackson-modules/jackson-annotations/src/main/java/com/ossez/jackson/bidirection/CustomListDeserializer.java +++ /dev/null @@ -1,29 +0,0 @@ -package com.ossez.jackson.bidirection; - -import java.io.IOException; -import java.util.ArrayList; -import java.util.List; - -import com.fasterxml.jackson.core.JsonParser; -import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.databind.DeserializationContext; -import com.fasterxml.jackson.databind.deser.std.StdDeserializer; - -public class CustomListDeserializer extends StdDeserializer> { - - private static final long serialVersionUID = 1095767961632979804L; - - public CustomListDeserializer() { - this(null); - } - - public CustomListDeserializer(final Class vc) { - super(vc); - } - - @Override - public List deserialize(final JsonParser jsonparser, final DeserializationContext context) throws IOException, JsonProcessingException { - return new ArrayList(); - } - -} \ No newline at end of file diff --git a/jackson-modules/jackson-annotations/src/main/java/com/ossez/jackson/bidirection/CustomListSerializer.java b/jackson-modules/jackson-annotations/src/main/java/com/ossez/jackson/bidirection/CustomListSerializer.java deleted file mode 100644 index 376aba09e3..0000000000 --- a/jackson-modules/jackson-annotations/src/main/java/com/ossez/jackson/bidirection/CustomListSerializer.java +++ /dev/null @@ -1,32 +0,0 @@ -package com.ossez.jackson.bidirection; - -import java.io.IOException; -import java.util.ArrayList; -import java.util.List; - -import com.fasterxml.jackson.core.JsonGenerator; -import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.databind.SerializerProvider; -import com.fasterxml.jackson.databind.ser.std.StdSerializer; - -public class CustomListSerializer extends StdSerializer> { - - private static final long serialVersionUID = 3698763098000900856L; - - public CustomListSerializer() { - this(null); - } - - public CustomListSerializer(final Class> t) { - super(t); - } - - @Override - public void serialize(final List items, final JsonGenerator generator, final SerializerProvider provider) throws IOException, JsonProcessingException { - final List ids = new ArrayList(); - for (final ItemWithSerializer item : items) { - ids.add(item.id); - } - generator.writeObject(ids); - } -} diff --git a/jackson-modules/jackson-annotations/src/main/java/com/ossez/jackson/bidirection/Item.java b/jackson-modules/jackson-annotations/src/main/java/com/ossez/jackson/bidirection/Item.java deleted file mode 100644 index a3bc3af89d..0000000000 --- a/jackson-modules/jackson-annotations/src/main/java/com/ossez/jackson/bidirection/Item.java +++ /dev/null @@ -1,17 +0,0 @@ -package com.ossez.jackson.bidirection; - -public class Item { - public int id; - public String itemName; - public User owner; - - public Item() { - super(); - } - - public Item(final int id, final String itemName, final User owner) { - this.id = id; - this.itemName = itemName; - this.owner = owner; - } -} diff --git a/jackson-modules/jackson-annotations/src/main/java/com/ossez/jackson/bidirection/ItemWithIdentity.java b/jackson-modules/jackson-annotations/src/main/java/com/ossez/jackson/bidirection/ItemWithIdentity.java deleted file mode 100644 index d2ca1392ed..0000000000 --- a/jackson-modules/jackson-annotations/src/main/java/com/ossez/jackson/bidirection/ItemWithIdentity.java +++ /dev/null @@ -1,21 +0,0 @@ -package com.ossez.jackson.bidirection; - -import com.fasterxml.jackson.annotation.JsonIdentityInfo; -import com.fasterxml.jackson.annotation.ObjectIdGenerators; - -@JsonIdentityInfo(generator = ObjectIdGenerators.PropertyGenerator.class, property = "id") -public class ItemWithIdentity { - public int id; - public String itemName; - public UserWithIdentity owner; - - public ItemWithIdentity() { - super(); - } - - public ItemWithIdentity(final int id, final String itemName, final UserWithIdentity owner) { - this.id = id; - this.itemName = itemName; - this.owner = owner; - } -} diff --git a/jackson-modules/jackson-annotations/src/main/java/com/ossez/jackson/bidirection/ItemWithIgnore.java b/jackson-modules/jackson-annotations/src/main/java/com/ossez/jackson/bidirection/ItemWithIgnore.java deleted file mode 100644 index 9cfa9e6056..0000000000 --- a/jackson-modules/jackson-annotations/src/main/java/com/ossez/jackson/bidirection/ItemWithIgnore.java +++ /dev/null @@ -1,17 +0,0 @@ -package com.ossez.jackson.bidirection; - -public class ItemWithIgnore { - public int id; - public String itemName; - public UserWithIgnore owner; - - public ItemWithIgnore() { - super(); - } - - public ItemWithIgnore(final int id, final String itemName, final UserWithIgnore owner) { - this.id = id; - this.itemName = itemName; - this.owner = owner; - } -} diff --git a/jackson-modules/jackson-annotations/src/main/java/com/ossez/jackson/bidirection/ItemWithRef.java b/jackson-modules/jackson-annotations/src/main/java/com/ossez/jackson/bidirection/ItemWithRef.java deleted file mode 100644 index 5db219f428..0000000000 --- a/jackson-modules/jackson-annotations/src/main/java/com/ossez/jackson/bidirection/ItemWithRef.java +++ /dev/null @@ -1,21 +0,0 @@ -package com.ossez.jackson.bidirection; - -import com.fasterxml.jackson.annotation.JsonBackReference; - -public class ItemWithRef { - public int id; - public String itemName; - - @JsonBackReference - public UserWithRef owner; - - public ItemWithRef() { - super(); - } - - public ItemWithRef(final int id, final String itemName, final UserWithRef owner) { - this.id = id; - this.itemName = itemName; - this.owner = owner; - } -} diff --git a/jackson-modules/jackson-annotations/src/main/java/com/ossez/jackson/bidirection/ItemWithSerializer.java b/jackson-modules/jackson-annotations/src/main/java/com/ossez/jackson/bidirection/ItemWithSerializer.java deleted file mode 100644 index dc889d49e8..0000000000 --- a/jackson-modules/jackson-annotations/src/main/java/com/ossez/jackson/bidirection/ItemWithSerializer.java +++ /dev/null @@ -1,17 +0,0 @@ -package com.ossez.jackson.bidirection; - -public class ItemWithSerializer { - public int id; - public String itemName; - public UserWithSerializer owner; - - public ItemWithSerializer() { - super(); - } - - public ItemWithSerializer(final int id, final String itemName, final UserWithSerializer owner) { - this.id = id; - this.itemName = itemName; - this.owner = owner; - } -} diff --git a/jackson-modules/jackson-annotations/src/main/java/com/ossez/jackson/bidirection/ItemWithView.java b/jackson-modules/jackson-annotations/src/main/java/com/ossez/jackson/bidirection/ItemWithView.java deleted file mode 100644 index c22a765b7c..0000000000 --- a/jackson-modules/jackson-annotations/src/main/java/com/ossez/jackson/bidirection/ItemWithView.java +++ /dev/null @@ -1,26 +0,0 @@ -package com.ossez.jackson.bidirection; - -import com.ossez.jackson.bidirection.jsonview.Views; - -import com.fasterxml.jackson.annotation.JsonView; - -public class ItemWithView { - @JsonView(Views.Public.class) - public int id; - - @JsonView(Views.Public.class) - public String itemName; - - @JsonView(Views.Public.class) - public UserWithView owner; - - public ItemWithView() { - super(); - } - - public ItemWithView(final int id, final String itemName, final UserWithView owner) { - this.id = id; - this.itemName = itemName; - this.owner = owner; - } -} diff --git a/jackson-modules/jackson-annotations/src/main/java/com/ossez/jackson/bidirection/User.java b/jackson-modules/jackson-annotations/src/main/java/com/ossez/jackson/bidirection/User.java deleted file mode 100644 index 4f7cfadc05..0000000000 --- a/jackson-modules/jackson-annotations/src/main/java/com/ossez/jackson/bidirection/User.java +++ /dev/null @@ -1,24 +0,0 @@ -package com.ossez.jackson.bidirection; - -import java.util.ArrayList; -import java.util.List; - -public class User { - public int id; - public String name; - public List userItems; - - public User() { - super(); - } - - public User(final int id, final String name) { - this.id = id; - this.name = name; - userItems = new ArrayList(); - } - - public void addItem(final Item item) { - userItems.add(item); - } -} diff --git a/jackson-modules/jackson-annotations/src/main/java/com/ossez/jackson/bidirection/UserWithIdentity.java b/jackson-modules/jackson-annotations/src/main/java/com/ossez/jackson/bidirection/UserWithIdentity.java deleted file mode 100644 index 90baaca4db..0000000000 --- a/jackson-modules/jackson-annotations/src/main/java/com/ossez/jackson/bidirection/UserWithIdentity.java +++ /dev/null @@ -1,28 +0,0 @@ -package com.ossez.jackson.bidirection; - -import java.util.ArrayList; -import java.util.List; - -import com.fasterxml.jackson.annotation.JsonIdentityInfo; -import com.fasterxml.jackson.annotation.ObjectIdGenerators; - -@JsonIdentityInfo(generator = ObjectIdGenerators.PropertyGenerator.class, property = "id") -public class UserWithIdentity { - public int id; - public String name; - public List userItems; - - public UserWithIdentity() { - super(); - } - - public UserWithIdentity(final int id, final String name) { - this.id = id; - this.name = name; - userItems = new ArrayList(); - } - - public void addItem(final ItemWithIdentity item) { - userItems.add(item); - } -} diff --git a/jackson-modules/jackson-annotations/src/main/java/com/ossez/jackson/bidirection/UserWithIgnore.java b/jackson-modules/jackson-annotations/src/main/java/com/ossez/jackson/bidirection/UserWithIgnore.java deleted file mode 100644 index 19fb6b63fe..0000000000 --- a/jackson-modules/jackson-annotations/src/main/java/com/ossez/jackson/bidirection/UserWithIgnore.java +++ /dev/null @@ -1,28 +0,0 @@ -package com.ossez.jackson.bidirection; - -import java.util.ArrayList; -import java.util.List; - -import com.fasterxml.jackson.annotation.JsonIgnore; - -public class UserWithIgnore { - public int id; - public String name; - - @JsonIgnore - public List userItems; - - public UserWithIgnore() { - super(); - } - - public UserWithIgnore(final int id, final String name) { - this.id = id; - this.name = name; - userItems = new ArrayList(); - } - - public void addItem(final ItemWithIgnore item) { - userItems.add(item); - } -} diff --git a/jackson-modules/jackson-annotations/src/main/java/com/ossez/jackson/bidirection/UserWithRef.java b/jackson-modules/jackson-annotations/src/main/java/com/ossez/jackson/bidirection/UserWithRef.java deleted file mode 100644 index 8236103627..0000000000 --- a/jackson-modules/jackson-annotations/src/main/java/com/ossez/jackson/bidirection/UserWithRef.java +++ /dev/null @@ -1,28 +0,0 @@ -package com.ossez.jackson.bidirection; - -import java.util.ArrayList; -import java.util.List; - -import com.fasterxml.jackson.annotation.JsonManagedReference; - -public class UserWithRef { - public int id; - public String name; - - @JsonManagedReference - public List userItems; - - public UserWithRef() { - super(); - } - - public UserWithRef(final int id, final String name) { - this.id = id; - this.name = name; - userItems = new ArrayList<>(); - } - - public void addItem(final ItemWithRef item) { - userItems.add(item); - } -} diff --git a/jackson-modules/jackson-annotations/src/main/java/com/ossez/jackson/bidirection/UserWithSerializer.java b/jackson-modules/jackson-annotations/src/main/java/com/ossez/jackson/bidirection/UserWithSerializer.java deleted file mode 100644 index 7b4f2d01d3..0000000000 --- a/jackson-modules/jackson-annotations/src/main/java/com/ossez/jackson/bidirection/UserWithSerializer.java +++ /dev/null @@ -1,30 +0,0 @@ -package com.ossez.jackson.bidirection; - -import java.util.ArrayList; -import java.util.List; - -import com.fasterxml.jackson.databind.annotation.JsonDeserialize; -import com.fasterxml.jackson.databind.annotation.JsonSerialize; - -public class UserWithSerializer { - public int id; - public String name; - - @JsonSerialize(using = CustomListSerializer.class) - @JsonDeserialize(using = CustomListDeserializer.class) - public List userItems; - - public UserWithSerializer() { - super(); - } - - public UserWithSerializer(final int id, final String name) { - this.id = id; - this.name = name; - userItems = new ArrayList(); - } - - public void addItem(final ItemWithSerializer item) { - userItems.add(item); - } -} diff --git a/jackson-modules/jackson-annotations/src/main/java/com/ossez/jackson/bidirection/UserWithView.java b/jackson-modules/jackson-annotations/src/main/java/com/ossez/jackson/bidirection/UserWithView.java deleted file mode 100644 index d1835e6a4e..0000000000 --- a/jackson-modules/jackson-annotations/src/main/java/com/ossez/jackson/bidirection/UserWithView.java +++ /dev/null @@ -1,33 +0,0 @@ -package com.ossez.jackson.bidirection; - -import java.util.ArrayList; -import java.util.List; - -import com.ossez.jackson.bidirection.jsonview.Views; - -import com.fasterxml.jackson.annotation.JsonView; - -public class UserWithView { - @JsonView(Views.Public.class) - public int id; - - @JsonView(Views.Public.class) - public String name; - - @JsonView(Views.Internal.class) - public List userItems; - - public UserWithView() { - super(); - } - - public UserWithView(final int id, final String name) { - this.id = id; - this.name = name; - userItems = new ArrayList(); - } - - public void addItem(final ItemWithView item) { - userItems.add(item); - } -} diff --git a/jackson-modules/jackson-annotations/src/main/java/com/ossez/jackson/bidirection/jsonview/Views.java b/jackson-modules/jackson-annotations/src/main/java/com/ossez/jackson/bidirection/jsonview/Views.java deleted file mode 100644 index 5f1dea2908..0000000000 --- a/jackson-modules/jackson-annotations/src/main/java/com/ossez/jackson/bidirection/jsonview/Views.java +++ /dev/null @@ -1,9 +0,0 @@ -package com.ossez.jackson.bidirection.jsonview; - -public class Views { - public static class Public { - } - - public static class Internal extends Public { - } -} diff --git a/jackson-modules/jackson-annotations/src/main/java/com/ossez/jackson/domain/Person.java b/jackson-modules/jackson-annotations/src/main/java/com/ossez/jackson/domain/Person.java deleted file mode 100644 index 026d52cfaa..0000000000 --- a/jackson-modules/jackson-annotations/src/main/java/com/ossez/jackson/domain/Person.java +++ /dev/null @@ -1,30 +0,0 @@ -package com.ossez.jackson.domain; - -public class Person { - - private String firstName; - private String lastName; - - public Person(String firstName, String lastName) { - super(); - this.firstName = firstName; - this.lastName = lastName; - } - - public String getFirstName() { - return firstName; - } - - public void setFirstName(String firstName) { - this.firstName = firstName; - } - - public String getLastName() { - return lastName; - } - - public void setLastName(String lastName) { - this.lastName = lastName; - } -} - diff --git a/jackson-modules/jackson-annotations/src/main/java/com/ossez/jackson/format/User.java b/jackson-modules/jackson-annotations/src/main/java/com/ossez/jackson/format/User.java deleted file mode 100644 index 6a18331273..0000000000 --- a/jackson-modules/jackson-annotations/src/main/java/com/ossez/jackson/format/User.java +++ /dev/null @@ -1,37 +0,0 @@ -package com.ossez.jackson.format; - -import java.util.Date; - -import com.ossez.jackson.domain.Person; -import com.fasterxml.jackson.annotation.JsonFormat; - -/** - * @author Jay Sridhar - * @version 1.0 - */ -public class User extends Person { - private String firstName; - private String lastName; - - @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd@HH:mm:ss.SSSZ") - private Date createdDate; - - public User(String firstName, String lastName) { - super(firstName, lastName); - this.createdDate = new Date(); - } - - public Date getCreatedDate() { - return createdDate; - } - - @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd@HH:mm:ss.SSSZ", locale = "en_GB") - public Date getCurrentDate() { - return new Date(); - } - - @JsonFormat(shape = JsonFormat.Shape.NUMBER) - public Date getDateNum() { - return new Date(); - } -} diff --git a/jackson-modules/jackson-annotations/src/main/java/com/ossez/jackson/jsonview/Item.java b/jackson-modules/jackson-annotations/src/main/java/com/ossez/jackson/jsonview/Item.java deleted file mode 100644 index 2d9fe2c1c6..0000000000 --- a/jackson-modules/jackson-annotations/src/main/java/com/ossez/jackson/jsonview/Item.java +++ /dev/null @@ -1,36 +0,0 @@ -package com.ossez.jackson.jsonview; - -import com.fasterxml.jackson.annotation.JsonView; - -public class Item { - @JsonView(Views.Public.class) - public int id; - - @JsonView(Views.Public.class) - public String itemName; - - @JsonView(Views.Internal.class) - public String ownerName; - - public Item() { - super(); - } - - public Item(final int id, final String itemName, final String ownerName) { - this.id = id; - this.itemName = itemName; - this.ownerName = ownerName; - } - - public int getId() { - return id; - } - - public String getItemName() { - return itemName; - } - - public String getOwnerName() { - return ownerName; - } -} diff --git a/jackson-modules/jackson-annotations/src/main/java/com/ossez/jackson/jsonview/MyBeanSerializerModifier.java b/jackson-modules/jackson-annotations/src/main/java/com/ossez/jackson/jsonview/MyBeanSerializerModifier.java deleted file mode 100644 index 5dd24a7790..0000000000 --- a/jackson-modules/jackson-annotations/src/main/java/com/ossez/jackson/jsonview/MyBeanSerializerModifier.java +++ /dev/null @@ -1,22 +0,0 @@ -package com.ossez.jackson.jsonview; - -import java.util.List; - -import com.fasterxml.jackson.databind.BeanDescription; -import com.fasterxml.jackson.databind.SerializationConfig; -import com.fasterxml.jackson.databind.ser.BeanPropertyWriter; -import com.fasterxml.jackson.databind.ser.BeanSerializerModifier; - -public class MyBeanSerializerModifier extends BeanSerializerModifier { - - @Override - public List changeProperties(final SerializationConfig config, final BeanDescription beanDesc, final List beanProperties) { - for (int i = 0; i < beanProperties.size(); i++) { - final BeanPropertyWriter beanPropertyWriter = beanProperties.get(i); - if (beanPropertyWriter.getName() == "name") { - beanProperties.set(i, new UpperCasingWriter(beanPropertyWriter)); - } - } - return beanProperties; - } -} \ No newline at end of file diff --git a/jackson-modules/jackson-annotations/src/main/java/com/ossez/jackson/jsonview/UpperCasingWriter.java b/jackson-modules/jackson-annotations/src/main/java/com/ossez/jackson/jsonview/UpperCasingWriter.java deleted file mode 100644 index 95dc39bc46..0000000000 --- a/jackson-modules/jackson-annotations/src/main/java/com/ossez/jackson/jsonview/UpperCasingWriter.java +++ /dev/null @@ -1,21 +0,0 @@ -package com.ossez.jackson.jsonview; - -import com.fasterxml.jackson.core.JsonGenerator; -import com.fasterxml.jackson.databind.SerializerProvider; -import com.fasterxml.jackson.databind.ser.BeanPropertyWriter; - -public class UpperCasingWriter extends BeanPropertyWriter { - final BeanPropertyWriter _writer; - - public UpperCasingWriter(final BeanPropertyWriter w) { - super(w); - _writer = w; - } - - @Override - public void serializeAsField(final Object bean, final JsonGenerator gen, final SerializerProvider prov) throws Exception { - String value = ((User) bean).name; - value = (value == null) ? "" : value.toUpperCase(); - gen.writeStringField("name", value); - } -} diff --git a/jackson-modules/jackson-annotations/src/main/java/com/ossez/jackson/jsonview/User.java b/jackson-modules/jackson-annotations/src/main/java/com/ossez/jackson/jsonview/User.java deleted file mode 100644 index 2f602c8e1b..0000000000 --- a/jackson-modules/jackson-annotations/src/main/java/com/ossez/jackson/jsonview/User.java +++ /dev/null @@ -1,27 +0,0 @@ -package com.ossez.jackson.jsonview; - -import com.fasterxml.jackson.annotation.JsonView; - -public class User { - public int id; - - @JsonView(Views.Public.class) - public String name; - - public User() { - super(); - } - - public User(final int id, final String name) { - this.id = id; - this.name = name; - } - - public int getId() { - return id; - } - - public String getName() { - return name; - } -} diff --git a/jackson-modules/jackson-annotations/src/main/java/com/ossez/jackson/jsonview/Views.java b/jackson-modules/jackson-annotations/src/main/java/com/ossez/jackson/jsonview/Views.java deleted file mode 100644 index 26e3c91a66..0000000000 --- a/jackson-modules/jackson-annotations/src/main/java/com/ossez/jackson/jsonview/Views.java +++ /dev/null @@ -1,9 +0,0 @@ -package com.ossez.jackson.jsonview; - -public class Views { - public static class Public { - } - - public static class Internal extends Public { - } -} diff --git a/jackson-modules/jackson-annotations/src/test/java/com/ossez/jackson/advancedannotations/AdvancedAnnotationsUnitTest.java b/jackson-modules/jackson-annotations/src/test/java/com/ossez/jackson/advancedannotations/AdvancedAnnotationsUnitTest.java deleted file mode 100644 index f610d69724..0000000000 --- a/jackson-modules/jackson-annotations/src/test/java/com/ossez/jackson/advancedannotations/AdvancedAnnotationsUnitTest.java +++ /dev/null @@ -1,133 +0,0 @@ -package com.ossez.jackson.advancedannotations; - -import static org.hamcrest.CoreMatchers.containsString; -import static org.hamcrest.CoreMatchers.instanceOf; -import static org.hamcrest.CoreMatchers.not; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertThat; - -import org.junit.Test; - -import java.io.IOException; -import java.util.ArrayList; -import java.util.List; - -import com.ossez.jackson.advancedannotations.AppendBeans.BeanWithAppend; -import com.ossez.jackson.advancedannotations.AppendBeans.BeanWithoutAppend; -import com.ossez.jackson.advancedannotations.IdentityReferenceBeans.BeanWithIdentityReference; -import com.ossez.jackson.advancedannotations.IdentityReferenceBeans.BeanWithoutIdentityReference; -import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.databind.ObjectMapper; -import com.fasterxml.jackson.databind.ObjectMapper.DefaultTyping; -import com.fasterxml.jackson.databind.ObjectWriter; -import com.fasterxml.jackson.module.jsonSchema.JsonSchema; -import com.fasterxml.jackson.module.jsonSchema.factories.SchemaFactoryWrapper; - -public class AdvancedAnnotationsUnitTest { - @Test - public void whenNotUsingJsonIdentityReferenceAnnotation_thenCorrect() throws JsonProcessingException { - ObjectMapper mapper = new ObjectMapper(); - BeanWithoutIdentityReference bean = new BeanWithoutIdentityReference(1, "Bean Without Identity Reference Annotation"); - String jsonString = mapper.writeValueAsString(bean); - - assertThat(jsonString, containsString("Bean Without Identity Reference Annotation")); - } - - @Test - public void whenUsingJsonIdentityReferenceAnnotation_thenCorrect() throws JsonProcessingException { - ObjectMapper mapper = new ObjectMapper(); - BeanWithIdentityReference bean = new BeanWithIdentityReference(1, "Bean With Identity Reference Annotation"); - String jsonString = mapper.writeValueAsString(bean); - - assertEquals("1", jsonString); - } - - @Test - public void whenNotUsingJsonAppendAnnotation_thenCorrect() throws JsonProcessingException { - ObjectMapper mapper = new ObjectMapper(); - - BeanWithoutAppend bean = new BeanWithoutAppend(2, "Bean Without Append Annotation"); - ObjectWriter writer = mapper.writerFor(BeanWithoutAppend.class) - .withAttribute("version", "1.0"); - String jsonString = writer.writeValueAsString(bean); - - assertThat(jsonString, not(containsString("version"))); - assertThat(jsonString, not(containsString("1.0"))); - } - - @Test - public void whenUsingJsonAppendAnnotation_thenCorrect() throws JsonProcessingException { - ObjectMapper mapper = new ObjectMapper(); - - BeanWithAppend bean = new BeanWithAppend(2, "Bean With Append Annotation"); - ObjectWriter writer = mapper.writerFor(BeanWithAppend.class) - .withAttribute("version", "1.0"); - String jsonString = writer.writeValueAsString(bean); - - assertThat(jsonString, containsString("version")); - assertThat(jsonString, containsString("1.0")); - } - - @Test - public void whenUsingJsonNamingAnnotation_thenCorrect() throws JsonProcessingException { - ObjectMapper mapper = new ObjectMapper(); - NamingBean bean = new NamingBean(3, "Naming Bean"); - String jsonString = mapper.writeValueAsString(bean); - - assertThat(jsonString, containsString("bean_name")); - } - - @Test - public void whenUsingJsonPropertyDescriptionAnnotation_thenCorrect() throws JsonProcessingException { - ObjectMapper mapper = new ObjectMapper(); - SchemaFactoryWrapper wrapper = new SchemaFactoryWrapper(); - mapper.acceptJsonFormatVisitor(PropertyDescriptionBean.class, wrapper); - JsonSchema jsonSchema = wrapper.finalSchema(); - String jsonString = mapper.writeValueAsString(jsonSchema); - System.out.println(jsonString); - assertThat(jsonString, containsString("This is a description of the name property")); - } - - @Test - public void whenUsingJsonPOJOBuilderAnnotation_thenCorrect() throws IOException { - ObjectMapper mapper = new ObjectMapper(); - String jsonString = "{\"id\":5,\"name\":\"POJO Builder Bean\"}"; - POJOBuilderBean bean = mapper.readValue(jsonString, POJOBuilderBean.class); - - assertEquals(5, bean.getIdentity()); - assertEquals("POJO Builder Bean", bean.getBeanName()); - } - - @Test - public void whenUsingJsonTypeIdAnnotation_thenCorrect() throws JsonProcessingException { - ObjectMapper mapper = new ObjectMapper(); - mapper.enableDefaultTyping(DefaultTyping.NON_FINAL); - TypeIdBean bean = new TypeIdBean(6, "Type Id Bean"); - String jsonString = mapper.writeValueAsString(bean); - - assertThat(jsonString, containsString("Type Id Bean")); - } - - @Test - public void whenUsingJsonTypeIdResolverAnnotation_thenCorrect() throws IOException { - TypeIdResolverStructure.FirstBean bean1 = new TypeIdResolverStructure.FirstBean(1, "Bean 1"); - TypeIdResolverStructure.LastBean bean2 = new TypeIdResolverStructure.LastBean(2, "Bean 2"); - - List beans = new ArrayList<>(); - beans.add(bean1); - beans.add(bean2); - - TypeIdResolverStructure.BeanContainer serializedContainer = new TypeIdResolverStructure.BeanContainer(); - serializedContainer.setBeans(beans); - - ObjectMapper mapper = new ObjectMapper(); - String jsonString = mapper.writeValueAsString(serializedContainer); - assertThat(jsonString, containsString("bean1")); - assertThat(jsonString, containsString("bean2")); - - TypeIdResolverStructure.BeanContainer deserializedContainer = mapper.readValue(jsonString, TypeIdResolverStructure.BeanContainer.class); - List beanList = deserializedContainer.getBeans(); - assertThat(beanList.get(0), instanceOf(TypeIdResolverStructure.FirstBean.class)); - assertThat(beanList.get(1), instanceOf(TypeIdResolverStructure.LastBean.class)); - } -} \ No newline at end of file diff --git a/jackson-modules/jackson-annotations/src/test/java/com/ossez/jackson/advancedannotations/AppendBeans.java b/jackson-modules/jackson-annotations/src/test/java/com/ossez/jackson/advancedannotations/AppendBeans.java deleted file mode 100644 index 6f28dbe42b..0000000000 --- a/jackson-modules/jackson-annotations/src/test/java/com/ossez/jackson/advancedannotations/AppendBeans.java +++ /dev/null @@ -1,58 +0,0 @@ -package com.ossez.jackson.advancedannotations; - -import com.fasterxml.jackson.databind.annotation.JsonAppend; - -public class AppendBeans { - public static class BeanWithoutAppend { - private int id; - private String name; - - public BeanWithoutAppend(int id, String name) { - this.id = id; - this.name = name; - } - - public int getId() { - return id; - } - - public void setId(int id) { - this.id = id; - } - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - } - - @JsonAppend(attrs = { @JsonAppend.Attr(value = "version") }) - public static class BeanWithAppend { - private int id; - private String name; - - public BeanWithAppend(int id, String name) { - this.id = id; - this.name = name; - } - - public int getId() { - return id; - } - - public void setId(int id) { - this.id = id; - } - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - } -} \ No newline at end of file diff --git a/jackson-modules/jackson-annotations/src/test/java/com/ossez/jackson/advancedannotations/IdentityReferenceBeans.java b/jackson-modules/jackson-annotations/src/test/java/com/ossez/jackson/advancedannotations/IdentityReferenceBeans.java deleted file mode 100644 index a825b7c19c..0000000000 --- a/jackson-modules/jackson-annotations/src/test/java/com/ossez/jackson/advancedannotations/IdentityReferenceBeans.java +++ /dev/null @@ -1,62 +0,0 @@ -package com.ossez.jackson.advancedannotations; - -import com.fasterxml.jackson.annotation.JsonIdentityInfo; -import com.fasterxml.jackson.annotation.JsonIdentityReference; -import com.fasterxml.jackson.annotation.ObjectIdGenerators; - -public class IdentityReferenceBeans { - @JsonIdentityInfo(generator = ObjectIdGenerators.PropertyGenerator.class, property = "id") - public static class BeanWithoutIdentityReference { - private int id; - private String name; - - public BeanWithoutIdentityReference(int id, String name) { - this.id = id; - this.name = name; - } - - public int getId() { - return id; - } - - public void setId(int id) { - this.id = id; - } - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - } - - @JsonIdentityInfo(generator = ObjectIdGenerators.PropertyGenerator.class, property = "id") - @JsonIdentityReference(alwaysAsId = true) - public static class BeanWithIdentityReference { - private int id; - private String name; - - public BeanWithIdentityReference(int id, String name) { - this.id = id; - this.name = name; - } - - public int getId() { - return id; - } - - public void setId(int id) { - this.id = id; - } - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - } -} \ No newline at end of file diff --git a/jackson-modules/jackson-annotations/src/test/java/com/ossez/jackson/advancedannotations/NamingBean.java b/jackson-modules/jackson-annotations/src/test/java/com/ossez/jackson/advancedannotations/NamingBean.java deleted file mode 100644 index 93b84b1c2a..0000000000 --- a/jackson-modules/jackson-annotations/src/test/java/com/ossez/jackson/advancedannotations/NamingBean.java +++ /dev/null @@ -1,31 +0,0 @@ -package com.ossez.jackson.advancedannotations; - -import com.fasterxml.jackson.databind.PropertyNamingStrategy; -import com.fasterxml.jackson.databind.annotation.JsonNaming; - -@JsonNaming(PropertyNamingStrategy.SnakeCaseStrategy.class) -public class NamingBean { - private int id; - private String beanName; - - public NamingBean(int id, String beanName) { - this.id = id; - this.beanName = beanName; - } - - public int getId() { - return id; - } - - public void setId(int id) { - this.id = id; - } - - public String getBeanName() { - return beanName; - } - - public void setBeanName(String beanName) { - this.beanName = beanName; - } -} \ No newline at end of file diff --git a/jackson-modules/jackson-annotations/src/test/java/com/ossez/jackson/advancedannotations/POJOBuilderBean.java b/jackson-modules/jackson-annotations/src/test/java/com/ossez/jackson/advancedannotations/POJOBuilderBean.java deleted file mode 100644 index 682917edc5..0000000000 --- a/jackson-modules/jackson-annotations/src/test/java/com/ossez/jackson/advancedannotations/POJOBuilderBean.java +++ /dev/null @@ -1,51 +0,0 @@ -package com.ossez.jackson.advancedannotations; - -import com.fasterxml.jackson.databind.annotation.JsonDeserialize; -import com.fasterxml.jackson.databind.annotation.JsonPOJOBuilder; - -@JsonDeserialize(builder = POJOBuilderBean.BeanBuilder.class) -public class POJOBuilderBean { - private int identity; - private String beanName; - - @JsonPOJOBuilder(buildMethodName = "createBean", withPrefix = "construct") - public static class BeanBuilder { - private int idValue; - private String nameValue; - - public BeanBuilder constructId(int id) { - idValue = id; - return this; - } - - public BeanBuilder constructName(String name) { - nameValue = name; - return this; - } - - public POJOBuilderBean createBean() { - return new POJOBuilderBean(idValue, nameValue); - } - } - - public POJOBuilderBean(int identity, String beanName) { - this.identity = identity; - this.beanName = beanName; - } - - public int getIdentity() { - return identity; - } - - public void setIdentity(int identity) { - this.identity = identity; - } - - public String getBeanName() { - return beanName; - } - - public void setBeanName(String beanName) { - this.beanName = beanName; - } -} \ No newline at end of file diff --git a/jackson-modules/jackson-annotations/src/test/java/com/ossez/jackson/advancedannotations/PropertyDescriptionBean.java b/jackson-modules/jackson-annotations/src/test/java/com/ossez/jackson/advancedannotations/PropertyDescriptionBean.java deleted file mode 100644 index b9178a2777..0000000000 --- a/jackson-modules/jackson-annotations/src/test/java/com/ossez/jackson/advancedannotations/PropertyDescriptionBean.java +++ /dev/null @@ -1,25 +0,0 @@ -package com.ossez.jackson.advancedannotations; - -import com.fasterxml.jackson.annotation.JsonPropertyDescription; - -public class PropertyDescriptionBean { - private int id; - @JsonPropertyDescription("This is a description of the name property") - private String name; - - public int getId() { - return id; - } - - public void setId(int id) { - this.id = id; - } - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } -} \ No newline at end of file diff --git a/jackson-modules/jackson-annotations/src/test/java/com/ossez/jackson/advancedannotations/TypeIdBean.java b/jackson-modules/jackson-annotations/src/test/java/com/ossez/jackson/advancedannotations/TypeIdBean.java deleted file mode 100644 index 532941c551..0000000000 --- a/jackson-modules/jackson-annotations/src/test/java/com/ossez/jackson/advancedannotations/TypeIdBean.java +++ /dev/null @@ -1,30 +0,0 @@ -package com.ossez.jackson.advancedannotations; - -import com.fasterxml.jackson.annotation.JsonTypeId; - -public class TypeIdBean { - private int id; - @JsonTypeId - private String name; - - public TypeIdBean(int id, String name) { - this.id = id; - this.name = name; - } - - public int getId() { - return id; - } - - public void setId(int id) { - this.id = id; - } - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } -} \ No newline at end of file diff --git a/jackson-modules/jackson-annotations/src/test/java/com/ossez/jackson/advancedannotations/TypeIdResolverStructure.java b/jackson-modules/jackson-annotations/src/test/java/com/ossez/jackson/advancedannotations/TypeIdResolverStructure.java deleted file mode 100644 index eb65f1df70..0000000000 --- a/jackson-modules/jackson-annotations/src/test/java/com/ossez/jackson/advancedannotations/TypeIdResolverStructure.java +++ /dev/null @@ -1,130 +0,0 @@ -package com.ossez.jackson.advancedannotations; - -import java.util.List; - -import com.fasterxml.jackson.annotation.JsonTypeInfo; -import com.fasterxml.jackson.annotation.JsonTypeInfo.Id; -import com.fasterxml.jackson.databind.DatabindContext; -import com.fasterxml.jackson.databind.JavaType; -import com.fasterxml.jackson.databind.annotation.JsonTypeIdResolver; -import com.fasterxml.jackson.databind.jsontype.impl.TypeIdResolverBase; - -public class TypeIdResolverStructure { - public static class BeanContainer { - private List beans; - - public List getBeans() { - return beans; - } - - public void setBeans(List beans) { - this.beans = beans; - } - } - - @JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "@type") - @JsonTypeIdResolver(BeanIdResolver.class) - public static class AbstractBean { - private int id; - - protected AbstractBean() { - } - - protected AbstractBean(int id) { - this.id = id; - } - - public int getId() { - return id; - } - - public void setId(int id) { - this.id = id; - } - } - - public static class FirstBean extends AbstractBean { - String firstName; - - public FirstBean() { - } - - public FirstBean(int id, String name) { - super(id); - setFirstName(name); - } - - public String getFirstName() { - return firstName; - } - - public void setFirstName(String name) { - firstName = name; - } - } - - public static class LastBean extends AbstractBean { - String lastName; - - public LastBean() { - } - - public LastBean(int id, String name) { - super(id); - setLastName(name); - } - - public String getLastName() { - return lastName; - } - - public void setLastName(String name) { - lastName = name; - } - } - - public static class BeanIdResolver extends TypeIdResolverBase { - private JavaType superType; - - @Override - public void init(JavaType baseType) { - superType = baseType; - } - - @Override - public Id getMechanism() { - return Id.NAME; - } - - @Override - public String idFromValue(Object obj) { - return idFromValueAndType(obj, obj.getClass()); - } - - @Override - public String idFromValueAndType(Object obj, Class subType) { - String typeId = null; - switch (subType.getSimpleName()) { - case "FirstBean": - typeId = "bean1"; - break; - case "LastBean": - typeId = "bean2"; - } - return typeId; - } - - @Override - public JavaType typeFromId(DatabindContext context, String id) { - Class subType = null; - switch (id) { - case "bean1": - subType = FirstBean.class; - break; - case "bean2": - subType = LastBean.class; - } - return context.constructSpecializedType(superType, subType); - } - } -} \ No newline at end of file diff --git a/jackson-modules/jackson-annotations/src/test/java/com/ossez/jackson/bidirection/JacksonBidirectionRelationUnitTest.java b/jackson-modules/jackson-annotations/src/test/java/com/ossez/jackson/bidirection/JacksonBidirectionRelationUnitTest.java deleted file mode 100644 index b04ac4da9d..0000000000 --- a/jackson-modules/jackson-annotations/src/test/java/com/ossez/jackson/bidirection/JacksonBidirectionRelationUnitTest.java +++ /dev/null @@ -1,152 +0,0 @@ -package com.ossez.jackson.bidirection; - -import static org.hamcrest.Matchers.containsString; -import static org.hamcrest.Matchers.is; -import static org.hamcrest.Matchers.not; -import static org.hamcrest.Matchers.nullValue; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertThat; - -import java.io.IOException; - -import com.ossez.jackson.bidirection.jsonview.Views; -import org.junit.Test; - -import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.databind.JsonMappingException; -import com.fasterxml.jackson.databind.ObjectMapper; - -public class JacksonBidirectionRelationUnitTest { - - @Test (expected = JsonMappingException.class) - public void givenBidirectionRelation_whenSerializing_thenException() throws JsonProcessingException { - final User user = new User(1, "John"); - final Item item = new Item(2, "book", user); - user.addItem(item); - - new ObjectMapper().writeValueAsString(item); - } - - @Test - public void givenBidirectionRelation_whenUsingJacksonReferenceAnnotationWithSerialization_thenCorrect() throws JsonProcessingException { - final UserWithRef user = new UserWithRef(1, "John"); - final ItemWithRef item = new ItemWithRef(2, "book", user); - user.addItem(item); - - final String itemJson = new ObjectMapper().writeValueAsString(item); - final String userJson = new ObjectMapper().writeValueAsString(user); - - assertThat(itemJson, containsString("book")); - assertThat(itemJson, not(containsString("John"))); - - assertThat(userJson, containsString("John")); - assertThat(userJson, containsString("userItems")); - assertThat(userJson, containsString("book")); - } - - @Test - public void givenBidirectionRelation_whenUsingJacksonReferenceAnnotationWithDeserialization_thenCorrect() throws JsonProcessingException { - final UserWithRef user = new UserWithRef(1, "John"); - final ItemWithRef item = new ItemWithRef(2, "book", user); - user.addItem(item); - - final String itemJson = new ObjectMapper().writeValueAsString(item); - final String userJson = new ObjectMapper().writeValueAsString(user); - - final ItemWithRef itemRead = new ObjectMapper().readValue(itemJson, ItemWithRef.class); - final UserWithRef userRead = new ObjectMapper().readValue(userJson, UserWithRef.class); - - assertThat(itemRead.itemName, is("book")); - assertThat(itemRead.owner, nullValue()); - - assertThat(userRead.name, is("John")); - assertThat(userRead.userItems.get(0).itemName, is("book")); - } - - @Test - public void givenBidirectionRelation_whenUsingJsonIdentityInfo_thenCorrect() throws JsonProcessingException { - final UserWithIdentity user = new UserWithIdentity(1, "John"); - final ItemWithIdentity item = new ItemWithIdentity(2, "book", user); - user.addItem(item); - - final String result = new ObjectMapper().writeValueAsString(item); - - assertThat(result, containsString("book")); - assertThat(result, containsString("John")); - assertThat(result, containsString("userItems")); - } - - @Test - public void givenBidirectionRelation_whenUsingJsonIgnore_thenCorrect() throws JsonProcessingException { - final UserWithIgnore user = new UserWithIgnore(1, "John"); - final ItemWithIgnore item = new ItemWithIgnore(2, "book", user); - user.addItem(item); - - final String result = new ObjectMapper().writeValueAsString(item); - - assertThat(result, containsString("book")); - assertThat(result, containsString("John")); - assertThat(result, not(containsString("userItems"))); - } - - @Test - public void givenBidirectionRelation_whenUsingCustomSerializer_thenCorrect() throws JsonProcessingException { - final UserWithSerializer user = new UserWithSerializer(1, "John"); - final ItemWithSerializer item = new ItemWithSerializer(2, "book", user); - user.addItem(item); - - final String result = new ObjectMapper().writeValueAsString(item); - - assertThat(result, containsString("book")); - assertThat(result, containsString("John")); - assertThat(result, containsString("userItems")); - } - - @Test - public void givenBidirectionRelation_whenDeserializingUsingIdentity_thenCorrect() throws JsonProcessingException, IOException { - final String json = "{\"id\":2,\"itemName\":\"book\",\"owner\":{\"id\":1,\"name\":\"John\",\"userItems\":[2]}}"; - - final ItemWithIdentity item = new ObjectMapper().readerFor(ItemWithIdentity.class) - .readValue(json); - - assertEquals(2, item.id); - assertEquals("book", item.itemName); - assertEquals("John", item.owner.name); - } - - @Test - public void givenBidirectionRelation_whenUsingCustomDeserializer_thenCorrect() throws JsonProcessingException, IOException { - final String json = "{\"id\":2,\"itemName\":\"book\",\"owner\":{\"id\":1,\"name\":\"John\",\"userItems\":[2]}}"; - - final ItemWithSerializer item = new ObjectMapper().readerFor(ItemWithSerializer.class) - .readValue(json); - assertEquals(2, item.id); - assertEquals("book", item.itemName); - assertEquals("John", item.owner.name); - } - - @Test - public void givenBidirectionRelation_whenUsingPublicJsonView_thenCorrect() throws JsonProcessingException { - final UserWithView user = new UserWithView(1, "John"); - final ItemWithView item = new ItemWithView(2, "book", user); - user.addItem(item); - - final String result = new ObjectMapper().writerWithView(Views.Public.class) - .writeValueAsString(item); - - assertThat(result, containsString("book")); - assertThat(result, containsString("John")); - assertThat(result, not(containsString("userItems"))); - } - - @Test(expected = JsonMappingException.class) - public void givenBidirectionRelation_whenUsingInternalJsonView_thenException() throws JsonProcessingException { - final UserWithView user = new UserWithView(1, "John"); - final ItemWithView item = new ItemWithView(2, "book", user); - user.addItem(item); - - new ObjectMapper().writerWithView(Views.Internal.class) - .writeValueAsString(item); - } - -} \ No newline at end of file diff --git a/jackson-modules/jackson-annotations/src/test/java/com/ossez/jackson/format/JsonFormatUnitTest.java b/jackson-modules/jackson-annotations/src/test/java/com/ossez/jackson/format/JsonFormatUnitTest.java deleted file mode 100644 index 5771df25f7..0000000000 --- a/jackson-modules/jackson-annotations/src/test/java/com/ossez/jackson/format/JsonFormatUnitTest.java +++ /dev/null @@ -1,37 +0,0 @@ -package com.ossez.jackson.format; - -import java.util.Date; - -import com.fasterxml.jackson.core.JsonProcessingException; - -import com.fasterxml.jackson.databind.ObjectMapper; - -import org.junit.Test; - -import static io.restassured.path.json.JsonPath.from; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.data.Percentage.withPercentage; - -/** - * @author Jay Sridhar - * @version 1.0 - */ -public class JsonFormatUnitTest { - - @Test - public void whenSerializedDateFormat_thenCorrect() throws JsonProcessingException { - - User user = new User("Jay", "Sridhar"); - - String result = new ObjectMapper().writeValueAsString(user); - - // Expected to match: "2016-12-19@09:34:42.628+0000" - assertThat(from(result).getString("createdDate")).matches("\\d{4}\\-\\d{2}\\-\\d{2}@\\d{2}:\\d{2}:\\d{2}\\.\\d{3}\\+\\d{4}"); - - // Expected to be close to current time - long now = new Date().getTime(); - assertThat(from(result).getLong("dateNum")).isCloseTo(now, withPercentage(10.0)); - - } -} diff --git a/jackson-modules/jackson-annotations/src/test/java/com/ossez/jackson/jsonview/JacksonJsonViewUnitTest.java b/jackson-modules/jackson-annotations/src/test/java/com/ossez/jackson/jsonview/JacksonJsonViewUnitTest.java deleted file mode 100644 index e658982009..0000000000 --- a/jackson-modules/jackson-annotations/src/test/java/com/ossez/jackson/jsonview/JacksonJsonViewUnitTest.java +++ /dev/null @@ -1,88 +0,0 @@ -package com.ossez.jackson.jsonview; - -import static org.hamcrest.Matchers.containsString; -import static org.hamcrest.Matchers.not; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertThat; - -import java.io.IOException; - -import org.junit.Test; - -import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.databind.MapperFeature; -import com.fasterxml.jackson.databind.ObjectMapper; -import com.fasterxml.jackson.databind.ser.BeanSerializerFactory; -import com.fasterxml.jackson.databind.ser.SerializerFactory; - -public class JacksonJsonViewUnitTest { - - @Test - public void whenUseJsonViewToSerialize_thenCorrect() throws JsonProcessingException { - final User user = new User(1, "John"); - - final ObjectMapper mapper = new ObjectMapper(); - mapper.disable(MapperFeature.DEFAULT_VIEW_INCLUSION); - - final String result = mapper.writerWithView(Views.Public.class) - .writeValueAsString(user); - - assertThat(result, containsString("John")); - assertThat(result, not(containsString("1"))); - } - - @Test - public void whenUsePublicView_thenOnlyPublicSerialized() throws JsonProcessingException { - final Item item = new Item(2, "book", "John"); - - final ObjectMapper mapper = new ObjectMapper(); - final String result = mapper.writerWithView(Views.Public.class) - .writeValueAsString(item); - - assertThat(result, containsString("book")); - assertThat(result, containsString("2")); - - assertThat(result, not(containsString("John"))); - } - - @Test - public void whenUseInternalView_thenAllSerialized() throws JsonProcessingException { - final Item item = new Item(2, "book", "John"); - - final ObjectMapper mapper = new ObjectMapper(); - final String result = mapper.writerWithView(Views.Internal.class) - .writeValueAsString(item); - - assertThat(result, containsString("book")); - assertThat(result, containsString("2")); - - assertThat(result, containsString("John")); - } - - @Test - public void whenUseJsonViewToDeserialize_thenCorrect() throws IOException { - final String json = "{\"id\":1,\"name\":\"John\"}"; - - final ObjectMapper mapper = new ObjectMapper(); - - final User user = mapper.readerWithView(Views.Public.class) - .forType(User.class) - .readValue(json); - assertEquals(1, user.getId()); - assertEquals("John", user.getName()); - } - - @Test - public void whenUseCustomJsonViewToSerialize_thenCorrect() throws JsonProcessingException { - final User user = new User(1, "John"); - final SerializerFactory serializerFactory = BeanSerializerFactory.instance.withSerializerModifier(new MyBeanSerializerModifier()); - - final ObjectMapper mapper = new ObjectMapper(); - mapper.setSerializerFactory(serializerFactory); - - final String result = mapper.writerWithView(Views.Public.class) - .writeValueAsString(user); - assertThat(result, containsString("JOHN")); - assertThat(result, containsString("1")); - } -} diff --git a/jackson-modules/jackson-conversions-2/README.md b/jackson-modules/jackson-conversions-2/README.md deleted file mode 100644 index ca81512fa3..0000000000 --- a/jackson-modules/jackson-conversions-2/README.md +++ /dev/null @@ -1,13 +0,0 @@ -## Jackson 转换 - -本模块中包含有关 Jackson 转换(Jackson conversions)有关的文章。 - -### 相关文章: -- [Mapping a Dynamic JSON Object with Jackson](https://www.baeldung.com/jackson-mapping-dynamic-object) -- [Mapping Multiple JSON Fields to a Single Java Field](https://www.baeldung.com/json-multiple-fields-single-java-field) -- [Convert XML to JSON Using Jackson](https://www.baeldung.com/jackson-convert-xml-json) -- [Converting JSON to CSV in Java](https://www.baeldung.com/java-converting-json-to-csv) -- [How to Process YAML with Jackson](https://www.baeldung.com/jackson-yaml) -- [Jackson Streaming API](https://www.baeldung.com/jackson-streaming-api) -- [Jackson: java.util.LinkedHashMap cannot be cast to X](https://www.baeldung.com/jackson-linkedhashmap-cannot-be-cast) -- More articles: [[<-- prev]](../jackson-conversions) diff --git a/jackson-modules/jackson-conversions-2/pom.xml b/jackson-modules/jackson-conversions-2/pom.xml deleted file mode 100644 index 58de10fbd9..0000000000 --- a/jackson-modules/jackson-conversions-2/pom.xml +++ /dev/null @@ -1,57 +0,0 @@ - - - 4.0.0 - jackson-conversions-2 - 0.0.1-SNAPSHOT - jackson-conversions-2 - - - com.ossez - jackson-modules - 0.0.2-SNAPSHOT - - - - - - com.fasterxml.jackson.dataformat - jackson-dataformat-yaml - ${jackson.version} - - - - com.fasterxml.jackson.datatype - jackson-datatype-jsr310 - ${jackson-datatype.version} - - - - com.fasterxml.jackson.dataformat - jackson-dataformat-csv - ${jackson.version} - - - org.assertj - assertj-core - ${assertj.version} - test - - - - - jackson-conversions-2 - - - src/main/resources - true - - - - - - 2.9.8 - - - \ No newline at end of file diff --git a/jackson-modules/jackson-conversions-2/src/main/java/com/ossez/jackson/csv/JsonCsvConverter.java b/jackson-modules/jackson-conversions-2/src/main/java/com/ossez/jackson/csv/JsonCsvConverter.java deleted file mode 100644 index b907b9301f..0000000000 --- a/jackson-modules/jackson-conversions-2/src/main/java/com/ossez/jackson/csv/JsonCsvConverter.java +++ /dev/null @@ -1,57 +0,0 @@ -package com.ossez.jackson.csv; - -import java.io.File; -import java.io.IOException; - -import com.fasterxml.jackson.databind.JsonNode; -import com.fasterxml.jackson.databind.MappingIterator; -import com.fasterxml.jackson.databind.ObjectMapper; -import com.fasterxml.jackson.databind.SerializationFeature; -import com.fasterxml.jackson.dataformat.csv.CsvMapper; -import com.fasterxml.jackson.dataformat.csv.CsvSchema; -import com.fasterxml.jackson.dataformat.csv.CsvSchema.Builder; - -public class JsonCsvConverter { - - public static void JsonToCsv(File jsonFile, File csvFile) throws IOException { - JsonNode jsonTree = new ObjectMapper().readTree(jsonFile); - - Builder csvSchemaBuilder = CsvSchema.builder(); - JsonNode firstObject = jsonTree.elements().next(); - firstObject.fieldNames().forEachRemaining(fieldName -> {csvSchemaBuilder.addColumn(fieldName);} ); - CsvSchema csvSchema = csvSchemaBuilder - .build() - .withHeader(); - - CsvMapper csvMapper = new CsvMapper(); - csvMapper.writerFor(JsonNode.class) - .with(csvSchema) - .writeValue(csvFile, jsonTree); - } - - public static void csvToJson(File csvFile, File jsonFile) throws IOException { - CsvSchema orderLineSchema = CsvSchema.emptySchema().withHeader(); - CsvMapper csvMapper = new CsvMapper(); - MappingIterator orderLines = csvMapper.readerFor(OrderLine.class) - .with(orderLineSchema) - .readValues(csvFile); - - new ObjectMapper() - .configure(SerializationFeature.INDENT_OUTPUT, true) - .writeValue(jsonFile, orderLines.readAll()); - } - - public static void JsonToFormattedCsv(File jsonFile, File csvFile) throws IOException { - CsvMapper csvMapper = new CsvMapper(); - CsvSchema csvSchema = csvMapper - .schemaFor(OrderLineForCsv.class) - .withHeader(); - csvMapper.addMixIn(OrderLine.class, OrderLineForCsv.class); - - OrderLine[] orderLines = new ObjectMapper() - .readValue(jsonFile, OrderLine[].class); - csvMapper.writerFor(OrderLine[].class) - .with(csvSchema) - .writeValue(csvFile, orderLines); - } -} diff --git a/jackson-modules/jackson-conversions-2/src/main/java/com/ossez/jackson/csv/OrderLine.java b/jackson-modules/jackson-conversions-2/src/main/java/com/ossez/jackson/csv/OrderLine.java deleted file mode 100644 index 7c028aa70c..0000000000 --- a/jackson-modules/jackson-conversions-2/src/main/java/com/ossez/jackson/csv/OrderLine.java +++ /dev/null @@ -1,49 +0,0 @@ -package com.ossez.jackson.csv; - -import java.math.BigDecimal; - -public class OrderLine { - private String item; - private int quantity; - private BigDecimal unitPrice; - - public OrderLine() { - - } - - public OrderLine(String item, int quantity, BigDecimal unitPrice) { - super(); - this.item = item; - this.quantity = quantity; - this.unitPrice = unitPrice; - } - - public String getItem() { - return item; - } - - public void setItem(String item) { - this.item = item; - } - - public int getQuantity() { - return quantity; - } - - public void setQuantity(int quantity) { - this.quantity = quantity; - } - - public BigDecimal getUnitPrice() { - return unitPrice; - } - - public void setUnitPrice(BigDecimal unitPrice) { - this.unitPrice = unitPrice; - } - - @Override - public String toString() { - return "OrderLine [item=" + item + ", quantity=" + quantity + ", unitPrice=" + unitPrice + "]"; - } -} diff --git a/jackson-modules/jackson-conversions-2/src/main/java/com/ossez/jackson/csv/OrderLineForCsv.java b/jackson-modules/jackson-conversions-2/src/main/java/com/ossez/jackson/csv/OrderLineForCsv.java deleted file mode 100644 index 7e89d12a1c..0000000000 --- a/jackson-modules/jackson-conversions-2/src/main/java/com/ossez/jackson/csv/OrderLineForCsv.java +++ /dev/null @@ -1,25 +0,0 @@ -package com.ossez.jackson.csv; - -import java.math.BigDecimal; - -import com.fasterxml.jackson.annotation.JsonIgnore; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.annotation.JsonPropertyOrder; - -@JsonPropertyOrder({ - "count", - "name" -}) -public abstract class OrderLineForCsv { - - @JsonProperty("name") - private String item; - - @JsonProperty("count") - private int quantity; - - @JsonIgnore - private BigDecimal unitPrice; - - -} diff --git a/jackson-modules/jackson-conversions-2/src/main/java/com/ossez/jackson/dynamicobject/Product.java b/jackson-modules/jackson-conversions-2/src/main/java/com/ossez/jackson/dynamicobject/Product.java deleted file mode 100644 index 2b1b5b995e..0000000000 --- a/jackson-modules/jackson-conversions-2/src/main/java/com/ossez/jackson/dynamicobject/Product.java +++ /dev/null @@ -1,39 +0,0 @@ -package com.ossez.jackson.dynamicobject; - -import java.util.LinkedHashMap; -import java.util.Map; - -import com.fasterxml.jackson.annotation.JsonAnySetter; - -public class Product { - - private String name; - private String category; - private Map details = new LinkedHashMap<>(); - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public String getCategory() { - return category; - } - - public void setCategory(String category) { - this.category = category; - } - - public Map getDetails() { - return details; - } - - @JsonAnySetter - public void setDetail(String key, Object value) { - details.put(key, value); - } - -} diff --git a/jackson-modules/jackson-conversions-2/src/main/java/com/ossez/jackson/dynamicobject/ProductJsonNode.java b/jackson-modules/jackson-conversions-2/src/main/java/com/ossez/jackson/dynamicobject/ProductJsonNode.java deleted file mode 100644 index 5c399a8411..0000000000 --- a/jackson-modules/jackson-conversions-2/src/main/java/com/ossez/jackson/dynamicobject/ProductJsonNode.java +++ /dev/null @@ -1,35 +0,0 @@ -package com.ossez.jackson.dynamicobject; - -import com.fasterxml.jackson.databind.JsonNode; - -public class ProductJsonNode { - - private String name; - private String category; - private JsonNode details; - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public String getCategory() { - return category; - } - - public void setCategory(String category) { - this.category = category; - } - - public JsonNode getDetails() { - return details; - } - - public void setDetails(JsonNode details) { - this.details = details; - } - -} diff --git a/jackson-modules/jackson-conversions-2/src/main/java/com/ossez/jackson/dynamicobject/ProductMap.java b/jackson-modules/jackson-conversions-2/src/main/java/com/ossez/jackson/dynamicobject/ProductMap.java deleted file mode 100644 index 290bb50ef6..0000000000 --- a/jackson-modules/jackson-conversions-2/src/main/java/com/ossez/jackson/dynamicobject/ProductMap.java +++ /dev/null @@ -1,35 +0,0 @@ -package com.ossez.jackson.dynamicobject; - -import java.util.Map; - -public class ProductMap { - - private String name; - private String category; - private Map details; - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public String getCategory() { - return category; - } - - public void setCategory(String category) { - this.category = category; - } - - public Map getDetails() { - return details; - } - - public void setDetails(Map details) { - this.details = details; - } - -} diff --git a/jackson-modules/jackson-conversions-2/src/main/java/com/ossez/jackson/multiplefields/Weather.java b/jackson-modules/jackson-conversions-2/src/main/java/com/ossez/jackson/multiplefields/Weather.java deleted file mode 100644 index 45d0322bfa..0000000000 --- a/jackson-modules/jackson-conversions-2/src/main/java/com/ossez/jackson/multiplefields/Weather.java +++ /dev/null @@ -1,44 +0,0 @@ -package com.ossez.jackson.multiplefields; - -import com.fasterxml.jackson.annotation.JsonAlias; -import com.fasterxml.jackson.annotation.JsonProperty; - -public class Weather { - - @JsonProperty("location") - @JsonAlias("place") - private String location; - - @JsonProperty("temp") - @JsonAlias("temperature") - private int temp; - - @JsonProperty("outlook") - @JsonAlias("weather") - private String outlook; - - public String getLocation() { - return location; - } - - public void setLocation(String location) { - this.location = location; - } - - public int getTemp() { - return temp; - } - - public void setTemp(int temp) { - this.temp = temp; - } - - public String getOutlook() { - return outlook; - } - - public void setOutlook(String outlook) { - this.outlook = outlook; - } - -} diff --git a/jackson-modules/jackson-conversions-2/src/main/java/com/ossez/jackson/tocollection/Book.java b/jackson-modules/jackson-conversions-2/src/main/java/com/ossez/jackson/tocollection/Book.java deleted file mode 100644 index 9f0dd4db28..0000000000 --- a/jackson-modules/jackson-conversions-2/src/main/java/com/ossez/jackson/tocollection/Book.java +++ /dev/null @@ -1,70 +0,0 @@ -package com.ossez.jackson.tocollection; - - -import java.util.Objects; - -public class Book { - private Integer bookId; - private String title; - private String author; - - public Book() {} - - public Book(Integer bookId, String title, String author) { - this.bookId = bookId; - this.title = title; - this.author = author; - } - - @Override - public boolean equals(Object o) { - if (this == o) { - return true; - } - if (!(o instanceof Book)) { - return false; - } - - Book book = (Book) o; - - if (!Objects.equals(bookId, book.bookId)) { - return false; - } - if (!Objects.equals(title, book.title)) { - return false; - } - return Objects.equals(author, book.author); - } - - @Override - public int hashCode() { - int result = bookId != null ? bookId.hashCode() : 0; - result = 31 * result + (title != null ? title.hashCode() : 0); - result = 31 * result + (author != null ? author.hashCode() : 0); - return result; - } - - public Integer getBookId() { - return bookId; - } - - public void setBookId(Integer bookId) { - this.bookId = bookId; - } - - public String getTitle() { - return title; - } - - public void setTitle(String title) { - this.title = title; - } - - public String getAuthor() { - return author; - } - - public void setAuthor(String author) { - this.author = author; - } -} diff --git a/jackson-modules/jackson-conversions-2/src/main/java/com/ossez/jackson/tocollection/JsonToCollectionUtil.java b/jackson-modules/jackson-conversions-2/src/main/java/com/ossez/jackson/tocollection/JsonToCollectionUtil.java deleted file mode 100644 index f60a3cde5a..0000000000 --- a/jackson-modules/jackson-conversions-2/src/main/java/com/ossez/jackson/tocollection/JsonToCollectionUtil.java +++ /dev/null @@ -1,24 +0,0 @@ -package com.ossez.jackson.tocollection; - -import com.fasterxml.jackson.core.type.TypeReference; -import com.fasterxml.jackson.databind.ObjectMapper; -import com.fasterxml.jackson.databind.type.CollectionType; - -import java.io.IOException; -import java.util.ArrayList; -import java.util.List; - -public class JsonToCollectionUtil { - - private JsonToCollectionUtil(){} - - public static List jsonArrayToList(String json, Class elementClass) throws IOException { - ObjectMapper objectMapper = new ObjectMapper(); - CollectionType listType = objectMapper.getTypeFactory().constructCollectionType(ArrayList.class, elementClass); - return objectMapper.readValue(json, listType); - } - - public static List jsonArrayToList2(String json, Class elementClass) throws IOException { - return new ObjectMapper().readValue(json, new TypeReference>() {}); - } -} diff --git a/jackson-modules/jackson-conversions-2/src/main/java/com/ossez/jackson/xmlToJson/Color.java b/jackson-modules/jackson-conversions-2/src/main/java/com/ossez/jackson/xmlToJson/Color.java deleted file mode 100644 index da3c3fa590..0000000000 --- a/jackson-modules/jackson-conversions-2/src/main/java/com/ossez/jackson/xmlToJson/Color.java +++ /dev/null @@ -1,5 +0,0 @@ -package com.ossez.jackson.xmlToJson; - -public enum Color { - PINK, BLUE, YELLOW, RED; -} diff --git a/jackson-modules/jackson-conversions-2/src/main/java/com/ossez/jackson/xmlToJson/Flower.java b/jackson-modules/jackson-conversions-2/src/main/java/com/ossez/jackson/xmlToJson/Flower.java deleted file mode 100644 index 8963c52c27..0000000000 --- a/jackson-modules/jackson-conversions-2/src/main/java/com/ossez/jackson/xmlToJson/Flower.java +++ /dev/null @@ -1,42 +0,0 @@ -package com.ossez.jackson.xmlToJson; - -public class Flower { - - private String name; - - private Color color; - - private Integer petals; - - public Flower() { } - - public Flower(String name, Color color, Integer petals) { - this.name = name; - this.color = color; - this.petals = petals; - } - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public Color getColor() { - return color; - } - - public void setColor(Color color) { - this.color = color; - } - - public Integer getPetals() { - return petals; - } - - public void setPetals(Integer petals) { - this.petals = petals; - } -} diff --git a/jackson-modules/jackson-conversions-2/src/main/java/com/ossez/jackson/yaml/Order.java b/jackson-modules/jackson-conversions-2/src/main/java/com/ossez/jackson/yaml/Order.java deleted file mode 100644 index b9739544e9..0000000000 --- a/jackson-modules/jackson-conversions-2/src/main/java/com/ossez/jackson/yaml/Order.java +++ /dev/null @@ -1,68 +0,0 @@ -package com.ossez.jackson.yaml; - -import java.time.LocalDate; -import java.util.ArrayList; -import java.util.List; - -public class Order { - private String orderNo; - private LocalDate date; - private String customerName; - private List orderLines; - - public Order() { - - } - - public Order(String orderNo, LocalDate date, String customerName, List orderLines) { - super(); - this.orderNo = orderNo; - this.date = date; - this.customerName = customerName; - this.orderLines = orderLines; - } - - public String getOrderNo() { - return orderNo; - } - - public void setOrderNo(String orderNo) { - this.orderNo = orderNo; - } - - public LocalDate getDate() { - return date; - } - - public void setDate(LocalDate date) { - this.date = date; - } - - public String getCustomerName() { - return customerName; - } - - public void setCustomerName(String customerName) { - this.customerName = customerName; - } - - public List getOrderLines() { - if (orderLines == null) { - orderLines = new ArrayList<>(); - } - return orderLines; - } - - public void setOrderLines(List orderLines) { - if (orderLines == null) { - orderLines = new ArrayList<>(); - } - this.orderLines = orderLines; - } - - @Override - public String toString() { - return "Order [orderNo=" + orderNo + ", date=" + date + ", customerName=" + customerName + ", orderLines=" + orderLines + "]"; - } - -} diff --git a/jackson-modules/jackson-conversions-2/src/main/java/com/ossez/jackson/yaml/OrderLine.java b/jackson-modules/jackson-conversions-2/src/main/java/com/ossez/jackson/yaml/OrderLine.java deleted file mode 100644 index c30a5fd120..0000000000 --- a/jackson-modules/jackson-conversions-2/src/main/java/com/ossez/jackson/yaml/OrderLine.java +++ /dev/null @@ -1,49 +0,0 @@ -package com.ossez.jackson.yaml; - -import java.math.BigDecimal; - -public class OrderLine { - private String item; - private int quantity; - private BigDecimal unitPrice; - - public OrderLine() { - - } - - public OrderLine(String item, int quantity, BigDecimal unitPrice) { - super(); - this.item = item; - this.quantity = quantity; - this.unitPrice = unitPrice; - } - - public String getItem() { - return item; - } - - public void setItem(String item) { - this.item = item; - } - - public int getQuantity() { - return quantity; - } - - public void setQuantity(int quantity) { - this.quantity = quantity; - } - - public BigDecimal getUnitPrice() { - return unitPrice; - } - - public void setUnitPrice(BigDecimal unitPrice) { - this.unitPrice = unitPrice; - } - - @Override - public String toString() { - return "OrderLine [item=" + item + ", quantity=" + quantity + ", unitPrice=" + unitPrice + "]"; - } -} diff --git a/jackson-modules/jackson-conversions-2/src/main/resources/csv/orderLines.csv b/jackson-modules/jackson-conversions-2/src/main/resources/csv/orderLines.csv deleted file mode 100644 index e15e12f2bf..0000000000 --- a/jackson-modules/jackson-conversions-2/src/main/resources/csv/orderLines.csv +++ /dev/null @@ -1,3 +0,0 @@ -item,quantity,unitPrice -"No. 9 Sprockets",12,1.23 -"Widget (10mm)",4,3.45 diff --git a/jackson-modules/jackson-conversions-2/src/main/resources/csv/orderLines.json b/jackson-modules/jackson-conversions-2/src/main/resources/csv/orderLines.json deleted file mode 100644 index 64f18e1673..0000000000 --- a/jackson-modules/jackson-conversions-2/src/main/resources/csv/orderLines.json +++ /dev/null @@ -1,9 +0,0 @@ -[ { - "item" : "No. 9 Sprockets", - "quantity" : 12, - "unitPrice" : 1.23 -}, { - "item" : "Widget (10mm)", - "quantity" : 4, - "unitPrice" : 3.45 -} ] \ No newline at end of file diff --git a/jackson-modules/jackson-conversions-2/src/main/resources/to-java-collection/books.json b/jackson-modules/jackson-conversions-2/src/main/resources/to-java-collection/books.json deleted file mode 100644 index 6daf426736..0000000000 --- a/jackson-modules/jackson-conversions-2/src/main/resources/to-java-collection/books.json +++ /dev/null @@ -1,13 +0,0 @@ -[ { - "bookId" : 1, - "title" : "A Song of Ice and Fire", - "author" : "George R. R. Martin" -}, { - "bookId" : 2, - "title" : "The Hitchhiker's Guide to the Galaxy", - "author" : "Douglas Adams" -}, { - "bookId" : 3, - "title" : "Hackers And Painters", - "author" : "Paul Graham" -} ] diff --git a/jackson-modules/jackson-conversions-2/src/main/resources/to-java-collection/books.xml b/jackson-modules/jackson-conversions-2/src/main/resources/to-java-collection/books.xml deleted file mode 100644 index b2f951315b..0000000000 --- a/jackson-modules/jackson-conversions-2/src/main/resources/to-java-collection/books.xml +++ /dev/null @@ -1,17 +0,0 @@ - - - 1 - A Song of Ice and Fire - George R. R. Martin - - - 2 - The Hitchhiker's Guide to the Galaxy - Douglas Adams - - - 3 - Hackers And Painters - Paul Graham - - diff --git a/jackson-modules/jackson-conversions-2/src/test/java/com/ossez/jackson/csv/CsvUnitTest.java b/jackson-modules/jackson-conversions-2/src/test/java/com/ossez/jackson/csv/CsvUnitTest.java deleted file mode 100644 index 31f49da723..0000000000 --- a/jackson-modules/jackson-conversions-2/src/test/java/com/ossez/jackson/csv/CsvUnitTest.java +++ /dev/null @@ -1,65 +0,0 @@ -package com.ossez.jackson.csv; - -import static org.junit.Assert.assertEquals; - -import java.io.File; -import java.io.IOException; -import java.nio.charset.Charset; -import java.util.List; - -import org.junit.After; -import org.junit.Before; -import org.junit.Test; - -import com.fasterxml.jackson.core.JsonParseException; -import com.fasterxml.jackson.databind.JsonMappingException; -import com.google.common.io.Files; - -public class CsvUnitTest { - - private File csvFromJson; - private File jsonFromCsv; - private File formattedCsvFromJson; - - @Before - public void setup() { - csvFromJson = new File("src/main/resources/csv/csvFromJson.csv"); - jsonFromCsv = new File("src/main/resources/csv/jsonFromCsv.json"); - formattedCsvFromJson = new File("src/main/resources/csv/formattedCsvFromJson.csv"); - } - - @After - public void cleanup() { - csvFromJson.deleteOnExit(); - jsonFromCsv.deleteOnExit(); - formattedCsvFromJson.deleteOnExit(); - } - - @Test - public void givenJsonInput_thenWriteCsv() throws JsonParseException, JsonMappingException, IOException { - JsonCsvConverter.JsonToCsv(new File("src/main/resources/csv/orderLines.json"), csvFromJson); - - assertEquals(readFile(csvFromJson.getAbsolutePath()), readFile("src/test/resources/csv/expectedCsvFromJson.csv")); - } - - @Test - public void givenCsvInput_thenWritesJson() throws JsonParseException, JsonMappingException, IOException { - JsonCsvConverter.csvToJson(new File("src/main/resources/csv/orderLines.csv"), jsonFromCsv); - - assertEquals(readFile(jsonFromCsv.getAbsolutePath()), readFile("src/test/resources/csv/expectedJsonFromCsv.json")); - - } - - @Test - public void givenJsonInput_thenWriteFormattedCsvOutput() throws JsonParseException, JsonMappingException, IOException { - JsonCsvConverter.JsonToFormattedCsv(new File("src/main/resources/csv/orderLines.json"), formattedCsvFromJson); - - assertEquals(readFile(formattedCsvFromJson.getAbsolutePath()), readFile("src/test/resources/csv/expectedFormattedCsvFromJson.csv")); - - } - - private List readFile(String filename) throws IOException { - return Files.readLines(new File(filename), Charset.forName("utf-8")); - } - -}; \ No newline at end of file diff --git a/jackson-modules/jackson-conversions-2/src/test/java/com/ossez/jackson/dynamicobject/DynamicObjectDeserializationUnitTest.java b/jackson-modules/jackson-conversions-2/src/test/java/com/ossez/jackson/dynamicobject/DynamicObjectDeserializationUnitTest.java deleted file mode 100644 index f037bb398f..0000000000 --- a/jackson-modules/jackson-conversions-2/src/test/java/com/ossez/jackson/dynamicobject/DynamicObjectDeserializationUnitTest.java +++ /dev/null @@ -1,69 +0,0 @@ -package com.ossez.jackson.dynamicobject; - -import static org.assertj.core.api.Assertions.assertThat; - -import java.io.IOException; -import java.util.Scanner; - -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; - -import com.fasterxml.jackson.core.JsonParseException; -import com.fasterxml.jackson.databind.JsonMappingException; -import com.fasterxml.jackson.databind.ObjectMapper; - -public class DynamicObjectDeserializationUnitTest { - - private ObjectMapper objectMapper; - - @BeforeEach - void setup() { - objectMapper = new ObjectMapper(); - } - - private String readResource(String path) { - try (Scanner scanner = new Scanner(getClass().getResourceAsStream(path), "UTF-8")) { - return scanner.useDelimiter("\\A").next(); - } - } - - @Test - void givenJsonString_whenParsingToJsonNode_thenItMustContainDynamicProperties() throws JsonParseException, JsonMappingException, IOException { - // given - String json = readResource("/deserialize-dynamic-object/embedded.json"); - - // when - ProductJsonNode product = objectMapper.readValue(json, ProductJsonNode.class); - - // then - assertThat(product.getName()).isEqualTo("Pear yPhone 72"); - assertThat(product.getDetails().get("audioConnector").asText()).isEqualTo("none"); - } - - @Test - void givenJsonString_whenParsingToMap_thenItMustContainDynamicProperties() throws JsonParseException, JsonMappingException, IOException { - // given - String json = readResource("/deserialize-dynamic-object/embedded.json"); - - // when - ProductMap product = objectMapper.readValue(json, ProductMap.class); - - // then - assertThat(product.getName()).isEqualTo("Pear yPhone 72"); - assertThat(product.getDetails().get("audioConnector")).isEqualTo("none"); - } - - @Test - void givenJsonString_whenParsingWithJsonAnySetter_thenItMustContainDynamicProperties() throws JsonParseException, JsonMappingException, IOException { - // given - String json = readResource("/deserialize-dynamic-object/flat.json"); - - // when - Product product = objectMapper.readValue(json, Product.class); - - // then - assertThat(product.getName()).isEqualTo("Pear yPhone 72"); - assertThat(product.getDetails().get("audioConnector")).isEqualTo("none"); - } - -} diff --git a/jackson-modules/jackson-conversions-2/src/test/java/com/ossez/jackson/multiplefields/MapMultipleFieldsToSingleFieldUnitTest.java b/jackson-modules/jackson-conversions-2/src/test/java/com/ossez/jackson/multiplefields/MapMultipleFieldsToSingleFieldUnitTest.java deleted file mode 100644 index fa8659bacd..0000000000 --- a/jackson-modules/jackson-conversions-2/src/test/java/com/ossez/jackson/multiplefields/MapMultipleFieldsToSingleFieldUnitTest.java +++ /dev/null @@ -1,37 +0,0 @@ -package com.ossez.jackson.multiplefields; - -import static org.junit.Assert.assertEquals; - -import org.junit.Test; - -import com.fasterxml.jackson.databind.ObjectMapper; - -public class MapMultipleFieldsToSingleFieldUnitTest { - - @Test - public void givenTwoJsonFormats_whenDeserialized_thenWeatherObjectsCreated() throws Exception { - - ObjectMapper mapper = new ObjectMapper(); - - Weather weather = mapper.readValue("{" + - "\"location\": \"London\"," + - "\"temp\": 15," + - "\"weather\": \"Cloudy\"" + - "}", Weather.class); - - assertEquals("London", weather.getLocation()); - assertEquals("Cloudy", weather.getOutlook()); - assertEquals(15, weather.getTemp()); - - weather = mapper.readValue("{" + - "\"place\": \"Lisbon\"," + - "\"temperature\": 35," + - "\"outlook\": \"Sunny\"" + - "}", Weather.class); - - assertEquals("Lisbon", weather.getLocation()); - assertEquals("Sunny", weather.getOutlook()); - assertEquals(35, weather.getTemp()); - - } -} diff --git a/jackson-modules/jackson-conversions-2/src/test/java/com/ossez/jackson/streaming/StreamingAPIUnitTest.java b/jackson-modules/jackson-conversions-2/src/test/java/com/ossez/jackson/streaming/StreamingAPIUnitTest.java deleted file mode 100644 index 4e987a9d7c..0000000000 --- a/jackson-modules/jackson-conversions-2/src/test/java/com/ossez/jackson/streaming/StreamingAPIUnitTest.java +++ /dev/null @@ -1,118 +0,0 @@ -package com.ossez.jackson.streaming; - -import com.fasterxml.jackson.core.*; -import org.junit.Test; - -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.util.Arrays; -import java.util.LinkedList; -import java.util.List; - -import static junit.framework.Assert.assertNull; -import static junit.framework.Assert.assertTrue; -import static junit.framework.TestCase.assertEquals; - -public class StreamingAPIUnitTest { - - @Test - public void givenJsonGenerator_whenAppendJsonToIt_thenGenerateJson() throws IOException { - // given - ByteArrayOutputStream stream = new ByteArrayOutputStream(); - JsonFactory jfactory = new JsonFactory(); - JsonGenerator jGenerator = jfactory.createGenerator(stream, JsonEncoding.UTF8); - - // when - jGenerator.writeStartObject(); - jGenerator.writeStringField("name", "Tom"); - jGenerator.writeNumberField("age", 25); - jGenerator.writeFieldName("address"); - jGenerator.writeStartArray(); - jGenerator.writeString("Poland"); - jGenerator.writeString("5th avenue"); - jGenerator.writeEndArray(); - jGenerator.writeEndObject(); - jGenerator.close(); - - // then - String json = new String(stream.toByteArray(), "UTF-8"); - assertEquals(json, "{\"name\":\"Tom\",\"age\":25,\"address\":[\"Poland\",\"5th avenue\"]}"); - } - - @Test - public void givenJson_whenReadItUsingStreamAPI_thenShouldCreateProperJsonObject() throws IOException { - // given - String json = "{\"name\":\"Tom\",\"age\":25,\"address\":[\"Poland\",\"5th avenue\"]}"; - JsonFactory jfactory = new JsonFactory(); - JsonParser jParser = jfactory.createParser(json); - - String parsedName = null; - Integer parsedAge = null; - List addresses = new LinkedList<>(); - - // when - while (jParser.nextToken() != JsonToken.END_OBJECT) { - - String fieldname = jParser.getCurrentName(); - if ("name".equals(fieldname)) { - jParser.nextToken(); - parsedName = jParser.getText(); - - } - - if ("age".equals(fieldname)) { - jParser.nextToken(); - parsedAge = jParser.getIntValue(); - - } - - if ("address".equals(fieldname)) { - jParser.nextToken(); - - while (jParser.nextToken() != JsonToken.END_ARRAY) { - addresses.add(jParser.getText()); - } - } - - } - jParser.close(); - - // then - assertEquals(parsedName, "Tom"); - assertEquals(parsedAge, (Integer) 25); - assertEquals(addresses, Arrays.asList("Poland", "5th avenue")); - - } - - @Test - public void givenJson_whenWantToExtractPartOfIt_thenShouldExtractOnlyNeededFieldWithoutGoingThroughWholeJSON() throws IOException { - // given - String json = "{\"name\":\"Tom\",\"age\":25,\"address\":[\"Poland\",\"5th avenue\"]}"; - JsonFactory jfactory = new JsonFactory(); - JsonParser jParser = jfactory.createParser(json); - - String parsedName = null; - Integer parsedAge = null; - List addresses = new LinkedList<>(); - - // when - while (jParser.nextToken() != JsonToken.END_OBJECT) { - - String fieldname = jParser.getCurrentName(); - - if ("age".equals(fieldname)) { - jParser.nextToken(); - parsedAge = jParser.getIntValue(); - return; - } - - } - jParser.close(); - - // then - assertNull(parsedName); - assertEquals(parsedAge, (Integer) 25); - assertTrue(addresses.isEmpty()); - - } -} diff --git a/jackson-modules/jackson-conversions-2/src/test/java/com/ossez/jackson/tocollection/DeserializeToJavaCollectionUnitTest.java b/jackson-modules/jackson-conversions-2/src/test/java/com/ossez/jackson/tocollection/DeserializeToJavaCollectionUnitTest.java deleted file mode 100644 index bf340fbb74..0000000000 --- a/jackson-modules/jackson-conversions-2/src/test/java/com/ossez/jackson/tocollection/DeserializeToJavaCollectionUnitTest.java +++ /dev/null @@ -1,130 +0,0 @@ -package com.ossez.jackson.tocollection; - -import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.core.type.TypeReference; -import com.fasterxml.jackson.databind.JsonNode; -import com.fasterxml.jackson.databind.ObjectMapper; -import com.fasterxml.jackson.databind.type.CollectionType; -import com.fasterxml.jackson.dataformat.xml.XmlMapper; -import org.assertj.core.util.Lists; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; - -import java.util.ArrayList; -import java.util.List; -import java.util.Scanner; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatExceptionOfType; - -public class DeserializeToJavaCollectionUnitTest { - private ObjectMapper objectMapper; - private XmlMapper xmlMapper; - private List expectedBookList; - - - @BeforeEach - void setup() { - objectMapper = new ObjectMapper(); - xmlMapper = new XmlMapper(); - expectedBookList = Lists.newArrayList( - new Book(1, "A Song of Ice and Fire", "George R. R. Martin"), - new Book(2, "The Hitchhiker's Guide to the Galaxy", "Douglas Adams"), - new Book(3, "Hackers And Painters", "Paul Graham")); - } - - private String readFile(String path) { - try (Scanner scanner = new Scanner(getClass().getResourceAsStream(path), "UTF-8")) { - return scanner.useDelimiter("\\A").next(); - } - } - - /*==================== - * JSON tests - *==================== - */ - @Test - void givenJsonString_whenDeserializingToList_thenThrowingClassCastException() throws JsonProcessingException { - String jsonString = readFile("/to-java-collection/books.json"); - List bookList = objectMapper.readValue(jsonString, ArrayList.class); - assertThat(bookList).size().isEqualTo(3); - assertThatExceptionOfType(ClassCastException.class) - .isThrownBy(() -> bookList.get(0).getBookId()) - .withMessageMatching(".*java.util.LinkedHashMap cannot be cast to .*com.baeldung.jackson.tocollection.Book.*"); - } - - @Test - void givenJsonString_whenDeserializingWithTypeReference_thenGetExpectedList() throws JsonProcessingException { - String jsonString = readFile("/to-java-collection/books.json"); - List bookList = objectMapper.readValue(jsonString, new TypeReference>() {}); - assertThat(bookList.get(0)).isInstanceOf(Book.class); - assertThat(bookList).isEqualTo(expectedBookList); - } - - @Test - void givenJsonString_whenDeserializingWithJavaType_thenGetExpectedList() throws JsonProcessingException { - String jsonString = readFile("/to-java-collection/books.json"); - CollectionType listType = objectMapper.getTypeFactory().constructCollectionType(ArrayList.class, Book.class); - List bookList = objectMapper.readValue(jsonString, listType); - assertThat(bookList.get(0)).isInstanceOf(Book.class); - assertThat(bookList).isEqualTo(expectedBookList); - } - - @Test - void givenJsonString_whenDeserializingWithConvertValueAndTypeReference_thenGetExpectedList() throws JsonProcessingException { - String jsonString = readFile("/to-java-collection/books.json"); - JsonNode jsonNode = objectMapper.readTree(jsonString); - List bookList = objectMapper.convertValue(jsonNode, new TypeReference>() {}); - assertThat(bookList.get(0)).isInstanceOf(Book.class); - assertThat(bookList).isEqualTo(expectedBookList); - } - - @Test - void givenJsonString_whenDeserializingWithConvertValueAndJavaType_thenGetExpectedList() throws JsonProcessingException { - String jsonString = readFile("/to-java-collection/books.json"); - JsonNode jsonNode = objectMapper.readTree(jsonString); - List bookList = objectMapper.convertValue(jsonNode, objectMapper.getTypeFactory().constructCollectionType(ArrayList.class, Book.class)); - assertThat(bookList.get(0)).isInstanceOf(Book.class); - assertThat(bookList).isEqualTo(expectedBookList); - } - - /*==================== - * XML tests - *==================== - */ - @Test - void givenXml_whenDeserializingToList_thenThrowingClassCastException() throws JsonProcessingException { - String xml = readFile("/to-java-collection/books.xml"); - List bookList = xmlMapper.readValue(xml, ArrayList.class); - assertThat(bookList).size().isEqualTo(3); - assertThatExceptionOfType(ClassCastException.class) - .isThrownBy(() -> bookList.get(0).getBookId()) - .withMessageMatching(".*java.util.LinkedHashMap cannot be cast to .*com.baeldung.jackson.tocollection.Book.*"); - } - - @Test - void givenXml_whenDeserializingWithTypeReference_thenGetExpectedList() throws JsonProcessingException { - String xml = readFile("/to-java-collection/books.xml"); - List bookList = xmlMapper.readValue(xml, new TypeReference>() {}); - assertThat(bookList.get(0)).isInstanceOf(Book.class); - assertThat(bookList).isEqualTo(expectedBookList); - } - - @Test - void givenXml_whenDeserializingWithConvertValueAndTypeReference_thenGetExpectedList() throws JsonProcessingException { - String xml = readFile("/to-java-collection/books.xml"); - List node = xmlMapper.readValue(xml, List.class); - List bookList = xmlMapper.convertValue(node, new TypeReference>() {}); - assertThat(bookList.get(0)).isInstanceOf(Book.class); - assertThat(bookList).isEqualTo(expectedBookList); - } - - @Test - void givenXml_whenDeserializingWithConvertValueAndJavaType_thenGetExpectedList() throws JsonProcessingException { - String xml = readFile("/to-java-collection/books.xml"); - List node = xmlMapper.readValue(xml, List.class); - List bookList = xmlMapper.convertValue(node, objectMapper.getTypeFactory().constructCollectionType(ArrayList.class, Book.class)); - assertThat(bookList.get(0)).isInstanceOf(Book.class); - assertThat(bookList).isEqualTo(expectedBookList); - } -} diff --git a/jackson-modules/jackson-conversions-2/src/test/java/com/ossez/jackson/tocollection/JsonToCollectionUtilUnitTest.java b/jackson-modules/jackson-conversions-2/src/test/java/com/ossez/jackson/tocollection/JsonToCollectionUtilUnitTest.java deleted file mode 100644 index 1cd14f3504..0000000000 --- a/jackson-modules/jackson-conversions-2/src/test/java/com/ossez/jackson/tocollection/JsonToCollectionUtilUnitTest.java +++ /dev/null @@ -1,51 +0,0 @@ -package com.ossez.jackson.tocollection; - -import org.assertj.core.util.Lists; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; - -import java.io.IOException; -import java.util.List; -import java.util.Scanner; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatExceptionOfType; - -class JsonToCollectionUtilUnitTest { - - private List expectedBookList; - - - @BeforeEach - void setup() { - expectedBookList = Lists.newArrayList( - new Book(1, "A Song of Ice and Fire", "George R. R. Martin"), - new Book(2, "The Hitchhiker's Guide to the Galaxy", "Douglas Adams"), - new Book(3, "Hackers And Painters", "Paul Graham")); - } - - private String readFile(String path) { - try (Scanner scanner = new Scanner(getClass().getResourceAsStream(path), "UTF-8")) { - return scanner.useDelimiter("\\A").next(); - } - } - - @Test - void givenJsonString_whenCalljsonArrayToList_thenGetExpectedList() throws IOException { - String jsonString = readFile("/to-java-collection/books.json"); - List bookList = JsonToCollectionUtil.jsonArrayToList(jsonString, Book.class); - assertThat(bookList.get(0)).isInstanceOf(Book.class); - assertThat(bookList).isEqualTo(expectedBookList); - } - - @Test - void givenJsonString_whenCalljsonArrayToList2_thenGetException() throws IOException { - String jsonString = readFile("/to-java-collection/books.json"); - List bookList = JsonToCollectionUtil.jsonArrayToList2(jsonString, Book.class); - assertThat(bookList).size().isEqualTo(3); - assertThatExceptionOfType(ClassCastException.class) - .isThrownBy(() -> bookList.get(0).getBookId()) - .withMessageMatching(".*java.util.LinkedHashMap cannot be cast to .*com.baeldung.jackson.tocollection.Book.*"); - } - -} diff --git a/jackson-modules/jackson-conversions-2/src/test/java/com/ossez/jackson/xmlToJson/XmlToJsonUnitTest.java b/jackson-modules/jackson-conversions-2/src/test/java/com/ossez/jackson/xmlToJson/XmlToJsonUnitTest.java deleted file mode 100644 index 170b1db71e..0000000000 --- a/jackson-modules/jackson-conversions-2/src/test/java/com/ossez/jackson/xmlToJson/XmlToJsonUnitTest.java +++ /dev/null @@ -1,43 +0,0 @@ -package com.ossez.jackson.xmlToJson; - -import com.fasterxml.jackson.databind.JsonNode; -import com.fasterxml.jackson.databind.ObjectMapper; -import com.fasterxml.jackson.dataformat.xml.XmlMapper; -import org.junit.Test; - -import static org.junit.Assert.*; - -import java.io.IOException; - -public class XmlToJsonUnitTest { - - @Test - public void givenAnXML_whenUseDataBidingToConvertToJSON_thenReturnDataOK() throws IOException{ - String flowerXML = "PoppyRED9"; - - XmlMapper xmlMapper = new XmlMapper(); - Flower poppy = xmlMapper.readValue(flowerXML, Flower.class); - - assertEquals(poppy.getName(), "Poppy"); - assertEquals(poppy.getColor(), Color.RED); - assertEquals(poppy.getPetals(), new Integer(9)); - - ObjectMapper mapper = new ObjectMapper(); - String json = mapper.writeValueAsString(poppy); - - assertEquals(json, "{\"name\":\"Poppy\",\"color\":\"RED\",\"petals\":9}"); - } - - @Test - public void givenAnXML_whenUseATreeConvertToJSON_thenReturnDataOK() throws IOException { - String flowerXML = "PoppyRED9"; - - XmlMapper xmlMapper = new XmlMapper(); - JsonNode node = xmlMapper.readTree(flowerXML.getBytes()); - - ObjectMapper jsonMapper = new ObjectMapper(); - String json = jsonMapper.writeValueAsString(node); - - assertEquals(json, "{\"name\":\"Poppy\",\"color\":\"RED\",\"petals\":\"9\"}"); - } -} diff --git a/jackson-modules/jackson-conversions-2/src/test/java/com/ossez/jackson/yaml/YamlUnitTest.java b/jackson-modules/jackson-conversions-2/src/test/java/com/ossez/jackson/yaml/YamlUnitTest.java deleted file mode 100644 index 92a008d17e..0000000000 --- a/jackson-modules/jackson-conversions-2/src/test/java/com/ossez/jackson/yaml/YamlUnitTest.java +++ /dev/null @@ -1,69 +0,0 @@ -package com.ossez.jackson.yaml; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; - -import java.io.File; -import java.io.IOException; -import java.math.BigDecimal; -import java.math.RoundingMode; -import java.time.LocalDate; -import java.time.format.DateTimeFormatter; -import java.util.ArrayList; -import java.util.List; - -import org.junit.After; -import org.junit.Before; -import org.junit.Test; - -import com.fasterxml.jackson.core.JsonGenerationException; -import com.fasterxml.jackson.core.JsonParseException; -import com.fasterxml.jackson.databind.JsonMappingException; -import com.fasterxml.jackson.databind.ObjectMapper; -import com.fasterxml.jackson.databind.SerializationFeature; -import com.fasterxml.jackson.dataformat.yaml.YAMLFactory; -import com.fasterxml.jackson.dataformat.yaml.YAMLGenerator.Feature; - -public class YamlUnitTest { - private ObjectMapper mapper; - private File orderOutput; - - @Before - public void setup() { - mapper = new ObjectMapper(new YAMLFactory().disable(Feature.WRITE_DOC_START_MARKER)); - mapper.findAndRegisterModules(); - mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS); - orderOutput = new File("src/test/resources/yaml/orderOutput.yaml"); - } - - @After - public void cleanup() { - orderOutput.deleteOnExit(); - } - - @Test - public void givenYamlInput_ObjectCreated() throws JsonParseException, JsonMappingException, IOException { - Order order = mapper.readValue(new File("src/test/resources/yaml/orderInput.yaml"), Order.class); - assertEquals("A001", order.getOrderNo()); - assertEquals(LocalDate.parse("2019-04-17", DateTimeFormatter.ISO_DATE), order.getDate()); - assertEquals("Customer, Joe", order.getCustomerName()); - assertEquals(2, order.getOrderLines() - .size()); - } - - @Test - public void givenYamlObject_FileWritten() throws JsonGenerationException, JsonMappingException, IOException { - List lines = new ArrayList<>(); - lines.add(new OrderLine("Copper Wire (200ft)", 1, new BigDecimal(50.67).setScale(2, RoundingMode.HALF_UP))); - lines.add(new OrderLine("Washers (1/4\")", 24, new BigDecimal(.15).setScale(2, RoundingMode.HALF_UP))); - Order order = new Order( - "B-9910", - LocalDate.parse("2019-04-18", DateTimeFormatter.ISO_DATE), - "Customer, Jane", - lines); - mapper.writeValue(orderOutput, order); - - File outputYaml = new File(orderOutput.getAbsolutePath()); - assertTrue(outputYaml.exists()); - } -} diff --git a/jackson-modules/jackson-conversions-2/src/test/resources/csv/expectedCsvFromJson.csv b/jackson-modules/jackson-conversions-2/src/test/resources/csv/expectedCsvFromJson.csv deleted file mode 100644 index e15e12f2bf..0000000000 --- a/jackson-modules/jackson-conversions-2/src/test/resources/csv/expectedCsvFromJson.csv +++ /dev/null @@ -1,3 +0,0 @@ -item,quantity,unitPrice -"No. 9 Sprockets",12,1.23 -"Widget (10mm)",4,3.45 diff --git a/jackson-modules/jackson-conversions-2/src/test/resources/csv/expectedFormattedCsvFromJson.csv b/jackson-modules/jackson-conversions-2/src/test/resources/csv/expectedFormattedCsvFromJson.csv deleted file mode 100644 index 5a60ba602a..0000000000 --- a/jackson-modules/jackson-conversions-2/src/test/resources/csv/expectedFormattedCsvFromJson.csv +++ /dev/null @@ -1,3 +0,0 @@ -count,name -12,"No. 9 Sprockets" -4,"Widget (10mm)" diff --git a/jackson-modules/jackson-conversions-2/src/test/resources/csv/expectedJsonFromCsv.json b/jackson-modules/jackson-conversions-2/src/test/resources/csv/expectedJsonFromCsv.json deleted file mode 100644 index 64f18e1673..0000000000 --- a/jackson-modules/jackson-conversions-2/src/test/resources/csv/expectedJsonFromCsv.json +++ /dev/null @@ -1,9 +0,0 @@ -[ { - "item" : "No. 9 Sprockets", - "quantity" : 12, - "unitPrice" : 1.23 -}, { - "item" : "Widget (10mm)", - "quantity" : 4, - "unitPrice" : 3.45 -} ] \ No newline at end of file diff --git a/jackson-modules/jackson-conversions-2/src/test/resources/deserialize-dynamic-object/embedded.json b/jackson-modules/jackson-conversions-2/src/test/resources/deserialize-dynamic-object/embedded.json deleted file mode 100644 index e4f11f7f1f..0000000000 --- a/jackson-modules/jackson-conversions-2/src/test/resources/deserialize-dynamic-object/embedded.json +++ /dev/null @@ -1,8 +0,0 @@ -{ - "name": "Pear yPhone 72", - "category": "cellphone", - "details": { - "displayAspectRatio": "97:3", - "audioConnector": "none" - } -} \ No newline at end of file diff --git a/jackson-modules/jackson-conversions-2/src/test/resources/deserialize-dynamic-object/flat.json b/jackson-modules/jackson-conversions-2/src/test/resources/deserialize-dynamic-object/flat.json deleted file mode 100644 index 799ea9339d..0000000000 --- a/jackson-modules/jackson-conversions-2/src/test/resources/deserialize-dynamic-object/flat.json +++ /dev/null @@ -1,6 +0,0 @@ -{ - "name": "Pear yPhone 72", - "category": "cellphone", - "displayAspectRatio": "97:3", - "audioConnector": "none" -} \ No newline at end of file diff --git a/jackson-modules/jackson-conversions-2/src/test/resources/yaml/orderInput.yaml b/jackson-modules/jackson-conversions-2/src/test/resources/yaml/orderInput.yaml deleted file mode 100644 index 0aaa6186a2..0000000000 --- a/jackson-modules/jackson-conversions-2/src/test/resources/yaml/orderInput.yaml +++ /dev/null @@ -1,11 +0,0 @@ -orderNo: A001 -date: 2019-04-17 -customerName: Customer, Joe -orderLines: - - item: No. 9 Sprockets - quantity: 12 - unitPrice: 1.23 - - item: Widget (10mm) - quantity: 4 - unitPrice: 3.45 - \ No newline at end of file diff --git a/jackson-modules/jackson-conversions/README.md b/jackson-modules/jackson-conversions/README.md deleted file mode 100644 index 25e299800a..0000000000 --- a/jackson-modules/jackson-conversions/README.md +++ /dev/null @@ -1,16 +0,0 @@ -## Jackson 转换 - -这个模块主要是针对 Jackson 转换(Jackson Conversions) 有关的文章。 - -### Relevant Articles: -- [Jackson – Unmarshall to Collection/Array](https://www.baeldung.com/jackson-collection-array) -- [Jackson Date](https://www.baeldung.com/jackson-serialize-dates) -- [Jackson – Working with Maps and Nulls](https://www.baeldung.com/jackson-map-null-values-or-null-key) -- [Jackson – Decide What Fields Get Serialized/Deserialized](https://www.baeldung.com/jackson-field-serializable-deserializable-or-not) -- [XML Serialization and Deserialization with Jackson](https://www.baeldung.com/jackson-xml-serialization-and-deserialization) -- [Map Serialization and Deserialization with Jackson](https://www.baeldung.com/jackson-map) -- [How to Serialize and Deserialize Enums with Jackson](https://www.baeldung.com/jackson-serialize-enums) -- [使用 Jackson – 将字符串转换为 JsonNode 对象](https://www.ossez.com/t/jackson-jsonnode/13724) -- [Mapping Nested Values with Jackson](https://www.baeldung.com/jackson-nested-values) -- [Deserialize Immutable Objects with Jackson](https://www.baeldung.com/jackson-deserialize-immutable-objects) -- More articles: [[next -->]](../jackson-conversions-2) diff --git a/jackson-modules/jackson-conversions/pom.xml b/jackson-modules/jackson-conversions/pom.xml deleted file mode 100644 index f11e2b35fd..0000000000 --- a/jackson-modules/jackson-conversions/pom.xml +++ /dev/null @@ -1,39 +0,0 @@ - - - 4.0.0 - jackson-conversions - 0.0.1-SNAPSHOT - jackson-conversions - - - com.ossez - jackson-modules - 0.0.2-SNAPSHOT - - - - - com.fasterxml.jackson.datatype - jackson-datatype-joda - ${jackson.version} - - - com.fasterxml.jackson.datatype - jackson-datatype-jsr310 - ${jackson.version} - - - - - jackson-conversions - - - src/main/resources - true - - - - - \ No newline at end of file diff --git a/jackson-modules/jackson-conversions/src/main/java/com/ossez/jackson/date/CustomDateDeserializer.java b/jackson-modules/jackson-conversions/src/main/java/com/ossez/jackson/date/CustomDateDeserializer.java deleted file mode 100644 index 6d0fe42cde..0000000000 --- a/jackson-modules/jackson-conversions/src/main/java/com/ossez/jackson/date/CustomDateDeserializer.java +++ /dev/null @@ -1,36 +0,0 @@ -package com.ossez.jackson.date; - -import java.io.IOException; -import java.text.ParseException; -import java.text.SimpleDateFormat; -import java.util.Date; - -import com.fasterxml.jackson.core.JsonParser; -import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.databind.DeserializationContext; -import com.fasterxml.jackson.databind.deser.std.StdDeserializer; - -public class CustomDateDeserializer extends StdDeserializer { - - private static final long serialVersionUID = -5451717385630622729L; - private SimpleDateFormat formatter = new SimpleDateFormat("dd-MM-yyyy hh:mm:ss"); - - public CustomDateDeserializer() { - this(null); - } - - public CustomDateDeserializer(final Class vc) { - super(vc); - } - - @Override - public Date deserialize(final JsonParser jsonparser, final DeserializationContext context) throws IOException, JsonProcessingException { - final String date = jsonparser.getText(); - try { - return formatter.parse(date); - } catch (final ParseException e) { - throw new RuntimeException(e); - } - } - -} diff --git a/jackson-modules/jackson-conversions/src/main/java/com/ossez/jackson/date/CustomDateSerializer.java b/jackson-modules/jackson-conversions/src/main/java/com/ossez/jackson/date/CustomDateSerializer.java deleted file mode 100644 index db5d68c746..0000000000 --- a/jackson-modules/jackson-conversions/src/main/java/com/ossez/jackson/date/CustomDateSerializer.java +++ /dev/null @@ -1,29 +0,0 @@ -package com.ossez.jackson.date; - -import java.io.IOException; -import java.text.SimpleDateFormat; -import java.util.Date; - -import com.fasterxml.jackson.core.JsonGenerator; -import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.databind.SerializerProvider; -import com.fasterxml.jackson.databind.ser.std.StdSerializer; - -public class CustomDateSerializer extends StdSerializer { - - private static final long serialVersionUID = -2894356342227378312L; - private SimpleDateFormat formatter = new SimpleDateFormat("dd-MM-yyyy hh:mm:ss"); - - public CustomDateSerializer() { - this(null); - } - - public CustomDateSerializer(final Class t) { - super(t); - } - - @Override - public void serialize(final Date value, final JsonGenerator gen, final SerializerProvider arg2) throws IOException, JsonProcessingException { - gen.writeString(formatter.format(value)); - } -} diff --git a/jackson-modules/jackson-conversions/src/main/java/com/ossez/jackson/date/CustomDateTimeSerializer.java b/jackson-modules/jackson-conversions/src/main/java/com/ossez/jackson/date/CustomDateTimeSerializer.java deleted file mode 100644 index 9d72a89292..0000000000 --- a/jackson-modules/jackson-conversions/src/main/java/com/ossez/jackson/date/CustomDateTimeSerializer.java +++ /dev/null @@ -1,32 +0,0 @@ -package com.ossez.jackson.date; - -import java.io.IOException; - -import org.joda.time.DateTime; -import org.joda.time.format.DateTimeFormat; -import org.joda.time.format.DateTimeFormatter; - -import com.fasterxml.jackson.core.JsonGenerator; -import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.databind.SerializerProvider; -import com.fasterxml.jackson.databind.ser.std.StdSerializer; - -public class CustomDateTimeSerializer extends StdSerializer { - - private static final long serialVersionUID = -3927232057990121460L; - - public CustomDateTimeSerializer() { - this(null); - } - - public CustomDateTimeSerializer(final Class t) { - super(t); - } - - private static DateTimeFormatter formatter = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm"); - - @Override - public void serialize(final DateTime value, final JsonGenerator gen, final SerializerProvider arg2) throws IOException, JsonProcessingException { - gen.writeString(formatter.print(value)); - } -} \ No newline at end of file diff --git a/jackson-modules/jackson-conversions/src/main/java/com/ossez/jackson/date/CustomLocalDateTimeSerializer.java b/jackson-modules/jackson-conversions/src/main/java/com/ossez/jackson/date/CustomLocalDateTimeSerializer.java deleted file mode 100644 index e6fea554d3..0000000000 --- a/jackson-modules/jackson-conversions/src/main/java/com/ossez/jackson/date/CustomLocalDateTimeSerializer.java +++ /dev/null @@ -1,29 +0,0 @@ -package com.ossez.jackson.date; - -import java.io.IOException; -import java.time.LocalDateTime; -import java.time.format.DateTimeFormatter; - -import com.fasterxml.jackson.core.JsonGenerator; -import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.databind.SerializerProvider; -import com.fasterxml.jackson.databind.ser.std.StdSerializer; - -public class CustomLocalDateTimeSerializer extends StdSerializer { - - private static final long serialVersionUID = -7449444168934819290L; - private static DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm"); - - public CustomLocalDateTimeSerializer() { - this(null); - } - - public CustomLocalDateTimeSerializer(final Class t) { - super(t); - } - - @Override - public void serialize(final LocalDateTime value, final JsonGenerator gen, final SerializerProvider arg2) throws IOException, JsonProcessingException { - gen.writeString(formatter.format(value)); - } -} \ No newline at end of file diff --git a/jackson-modules/jackson-conversions/src/main/java/com/ossez/jackson/date/Event.java b/jackson-modules/jackson-conversions/src/main/java/com/ossez/jackson/date/Event.java deleted file mode 100644 index 7762d5907b..0000000000 --- a/jackson-modules/jackson-conversions/src/main/java/com/ossez/jackson/date/Event.java +++ /dev/null @@ -1,25 +0,0 @@ -package com.ossez.jackson.date; - -import java.util.Date; - -public class Event { - public String name; - public Date eventDate; - - public Event() { - super(); - } - - public Event(final String name, final Date eventDate) { - this.name = name; - this.eventDate = eventDate; - } - - public Date getEventDate() { - return eventDate; - } - - public String getName() { - return name; - } -} diff --git a/jackson-modules/jackson-conversions/src/main/java/com/ossez/jackson/date/EventWithFormat.java b/jackson-modules/jackson-conversions/src/main/java/com/ossez/jackson/date/EventWithFormat.java deleted file mode 100644 index fe73f551c7..0000000000 --- a/jackson-modules/jackson-conversions/src/main/java/com/ossez/jackson/date/EventWithFormat.java +++ /dev/null @@ -1,29 +0,0 @@ -package com.ossez.jackson.date; - -import java.util.Date; - -import com.fasterxml.jackson.annotation.JsonFormat; - -public class EventWithFormat { - public String name; - - @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "dd-MM-yyyy hh:mm:ss") - public Date eventDate; - - public EventWithFormat() { - super(); - } - - public EventWithFormat(final String name, final Date eventDate) { - this.name = name; - this.eventDate = eventDate; - } - - public Date getEventDate() { - return eventDate; - } - - public String getName() { - return name; - } -} diff --git a/jackson-modules/jackson-conversions/src/main/java/com/ossez/jackson/date/EventWithJodaTime.java b/jackson-modules/jackson-conversions/src/main/java/com/ossez/jackson/date/EventWithJodaTime.java deleted file mode 100644 index b9e0a8672f..0000000000 --- a/jackson-modules/jackson-conversions/src/main/java/com/ossez/jackson/date/EventWithJodaTime.java +++ /dev/null @@ -1,29 +0,0 @@ -package com.ossez.jackson.date; - -import org.joda.time.DateTime; - -import com.fasterxml.jackson.databind.annotation.JsonSerialize; - -public class EventWithJodaTime { - public String name; - - @JsonSerialize(using = CustomDateTimeSerializer.class) - public DateTime eventDate; - - public EventWithJodaTime() { - super(); - } - - public EventWithJodaTime(final String name, final DateTime eventDate) { - this.name = name; - this.eventDate = eventDate; - } - - public DateTime getEventDate() { - return eventDate; - } - - public String getName() { - return name; - } -} diff --git a/jackson-modules/jackson-conversions/src/main/java/com/ossez/jackson/date/EventWithLocalDate.java b/jackson-modules/jackson-conversions/src/main/java/com/ossez/jackson/date/EventWithLocalDate.java deleted file mode 100644 index 1562987b5b..0000000000 --- a/jackson-modules/jackson-conversions/src/main/java/com/ossez/jackson/date/EventWithLocalDate.java +++ /dev/null @@ -1,33 +0,0 @@ -package com.ossez.jackson.date; - -import com.fasterxml.jackson.annotation.JsonFormat; -import com.fasterxml.jackson.databind.annotation.JsonDeserialize; -import com.fasterxml.jackson.databind.annotation.JsonSerialize; -import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateDeserializer; -import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateSerializer; - -import java.time.LocalDate; - -public class EventWithLocalDate { - public String name; - - @JsonDeserialize(using = LocalDateDeserializer.class) - @JsonSerialize(using = LocalDateSerializer.class) - @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "dd-MM-yyyy") - public LocalDate eventDate; - - public EventWithLocalDate() {} - - public EventWithLocalDate(final String name, final LocalDate eventDate) { - this.name = name; - this.eventDate = eventDate; - } - - public LocalDate getEventDate() { - return eventDate; - } - - public String getName() { - return name; - } -} diff --git a/jackson-modules/jackson-conversions/src/main/java/com/ossez/jackson/date/EventWithLocalDateTime.java b/jackson-modules/jackson-conversions/src/main/java/com/ossez/jackson/date/EventWithLocalDateTime.java deleted file mode 100644 index f5d048fa93..0000000000 --- a/jackson-modules/jackson-conversions/src/main/java/com/ossez/jackson/date/EventWithLocalDateTime.java +++ /dev/null @@ -1,29 +0,0 @@ -package com.ossez.jackson.date; - -import java.time.LocalDateTime; - -import com.fasterxml.jackson.databind.annotation.JsonSerialize; - -public class EventWithLocalDateTime { - public String name; - - @JsonSerialize(using = CustomLocalDateTimeSerializer.class) - public LocalDateTime eventDate; - - public EventWithLocalDateTime() { - super(); - } - - public EventWithLocalDateTime(final String name, final LocalDateTime eventDate) { - this.name = name; - this.eventDate = eventDate; - } - - public LocalDateTime getEventDate() { - return eventDate; - } - - public String getName() { - return name; - } -} diff --git a/jackson-modules/jackson-conversions/src/main/java/com/ossez/jackson/date/EventWithSerializer.java b/jackson-modules/jackson-conversions/src/main/java/com/ossez/jackson/date/EventWithSerializer.java deleted file mode 100644 index 595bcb8f76..0000000000 --- a/jackson-modules/jackson-conversions/src/main/java/com/ossez/jackson/date/EventWithSerializer.java +++ /dev/null @@ -1,31 +0,0 @@ -package com.ossez.jackson.date; - -import java.util.Date; - -import com.fasterxml.jackson.databind.annotation.JsonDeserialize; -import com.fasterxml.jackson.databind.annotation.JsonSerialize; - -public class EventWithSerializer { - public String name; - - @JsonDeserialize(using = CustomDateDeserializer.class) - @JsonSerialize(using = CustomDateSerializer.class) - public Date eventDate; - - public EventWithSerializer() { - super(); - } - - public EventWithSerializer(final String name, final Date eventDate) { - this.name = name; - this.eventDate = eventDate; - } - - public Date getEventDate() { - return eventDate; - } - - public String getName() { - return name; - } -} diff --git a/jackson-modules/jackson-conversions/src/main/java/com/ossez/jackson/enums/deserialization/City.java b/jackson-modules/jackson-conversions/src/main/java/com/ossez/jackson/enums/deserialization/City.java deleted file mode 100644 index c86868de6e..0000000000 --- a/jackson-modules/jackson-conversions/src/main/java/com/ossez/jackson/enums/deserialization/City.java +++ /dev/null @@ -1,15 +0,0 @@ -package com.ossez.jackson.enums.deserialization; - -public class City { - - private Distance distance; - - public Distance getDistance() { - return distance; - } - - public void setDistance(Distance distance) { - this.distance = distance; - } - -} diff --git a/jackson-modules/jackson-conversions/src/main/java/com/ossez/jackson/enums/deserialization/Distance.java b/jackson-modules/jackson-conversions/src/main/java/com/ossez/jackson/enums/deserialization/Distance.java deleted file mode 100644 index 96829dc3c9..0000000000 --- a/jackson-modules/jackson-conversions/src/main/java/com/ossez/jackson/enums/deserialization/Distance.java +++ /dev/null @@ -1,31 +0,0 @@ -package com.ossez.jackson.enums.deserialization; - -public enum Distance { - - KILOMETER("km", 1000), MILE("miles", 1609.34), METER("meters", 1), INCH("inches", 0.0254), CENTIMETER("cm", 0.01), MILLIMETER("mm", 0.001); - - private String unit; - private double meters; - - private Distance(String unit, double meters) { - this.unit = unit; - this.meters = meters; - } - - public void setMeters(double meters) { - this.meters = meters; - } - - public double getMeters() { - return meters; - } - - public String getUnit() { - return unit; - } - - public void setUnit(String unit) { - this.unit = unit; - } -} - diff --git a/jackson-modules/jackson-conversions/src/main/java/com/ossez/jackson/enums/deserialization/customdeserializer/City.java b/jackson-modules/jackson-conversions/src/main/java/com/ossez/jackson/enums/deserialization/customdeserializer/City.java deleted file mode 100644 index 42425f8c07..0000000000 --- a/jackson-modules/jackson-conversions/src/main/java/com/ossez/jackson/enums/deserialization/customdeserializer/City.java +++ /dev/null @@ -1,15 +0,0 @@ -package com.ossez.jackson.enums.deserialization.customdeserializer; - -public class City { - - private Distance distance; - - public Distance getDistance() { - return distance; - } - - public void setDistance(Distance distance) { - this.distance = distance; - } - -} diff --git a/jackson-modules/jackson-conversions/src/main/java/com/ossez/jackson/enums/deserialization/customdeserializer/CustomEnumDeserializer.java b/jackson-modules/jackson-conversions/src/main/java/com/ossez/jackson/enums/deserialization/customdeserializer/CustomEnumDeserializer.java deleted file mode 100644 index bb26606741..0000000000 --- a/jackson-modules/jackson-conversions/src/main/java/com/ossez/jackson/enums/deserialization/customdeserializer/CustomEnumDeserializer.java +++ /dev/null @@ -1,42 +0,0 @@ -package com.ossez.jackson.enums.deserialization.customdeserializer; - -import java.io.IOException; -import com.fasterxml.jackson.core.JsonParser; -import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.databind.DeserializationContext; -import com.fasterxml.jackson.databind.JsonNode; -import com.fasterxml.jackson.databind.deser.std.StdDeserializer; - -public class CustomEnumDeserializer extends StdDeserializer { - - private static final long serialVersionUID = -1166032307856492833L; - - public CustomEnumDeserializer() { - this(null); - } - - public CustomEnumDeserializer(Class c) { - super(c); - } - - @Override - public Distance deserialize(JsonParser jsonParser, DeserializationContext ctxt) throws IOException, JsonProcessingException { - - JsonNode node = jsonParser.getCodec().readTree(jsonParser); - - String unit = node.get("unit").asText(); - double meters = node.get("meters").asDouble(); - - for (Distance distance : Distance.values()) { - - if (distance.getUnit().equals(unit) && - Double.compare(distance.getMeters(), meters) == 0) { - - return distance; - } - } - - return null; - } - -} diff --git a/jackson-modules/jackson-conversions/src/main/java/com/ossez/jackson/enums/deserialization/customdeserializer/Distance.java b/jackson-modules/jackson-conversions/src/main/java/com/ossez/jackson/enums/deserialization/customdeserializer/Distance.java deleted file mode 100644 index b6053f01d8..0000000000 --- a/jackson-modules/jackson-conversions/src/main/java/com/ossez/jackson/enums/deserialization/customdeserializer/Distance.java +++ /dev/null @@ -1,33 +0,0 @@ -package com.ossez.jackson.enums.deserialization.customdeserializer; - -import com.fasterxml.jackson.databind.annotation.JsonDeserialize; - -@JsonDeserialize(using = CustomEnumDeserializer.class) -public enum Distance { - - KILOMETER("km", 1000), MILE("miles", 1609.34), METER("meters", 1), INCH("inches", 0.0254), CENTIMETER("cm", 0.01), MILLIMETER("mm", 0.001); - - private String unit; - private double meters; - - private Distance(String unit, double meters) { - this.unit = unit; - this.meters = meters; - } - - public double getMeters() { - return meters; - } - - public void setMeters(double meters) { - this.meters = meters; - } - - public String getUnit() { - return unit; - } - - public void setUnit(String unit) { - this.unit = unit; - } -} \ No newline at end of file diff --git a/jackson-modules/jackson-conversions/src/main/java/com/ossez/jackson/enums/deserialization/jsoncreator/City.java b/jackson-modules/jackson-conversions/src/main/java/com/ossez/jackson/enums/deserialization/jsoncreator/City.java deleted file mode 100644 index 734af4e548..0000000000 --- a/jackson-modules/jackson-conversions/src/main/java/com/ossez/jackson/enums/deserialization/jsoncreator/City.java +++ /dev/null @@ -1,15 +0,0 @@ -package com.ossez.jackson.enums.deserialization.jsoncreator; - -public class City { - - private Distance distance; - - public Distance getDistance() { - return distance; - } - - public void setDistance(Distance distance) { - this.distance = distance; - } - -} diff --git a/jackson-modules/jackson-conversions/src/main/java/com/ossez/jackson/enums/deserialization/jsoncreator/Distance.java b/jackson-modules/jackson-conversions/src/main/java/com/ossez/jackson/enums/deserialization/jsoncreator/Distance.java deleted file mode 100644 index 1c6bdfaad8..0000000000 --- a/jackson-modules/jackson-conversions/src/main/java/com/ossez/jackson/enums/deserialization/jsoncreator/Distance.java +++ /dev/null @@ -1,48 +0,0 @@ -package com.ossez.jackson.enums.deserialization.jsoncreator; - -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonProperty; - -public enum Distance { - - KILOMETER("km", 1000), MILE("miles", 1609.34), METER("meters", 1), INCH("inches", 0.0254), CENTIMETER("cm", 0.01), MILLIMETER("mm", 0.001); - - private String unit; - private double meters; - - private Distance(String unit, double meters) { - this.unit = unit; - this.meters = meters; - } - - public void setMeters(double meters) { - this.meters = meters; - } - - public double getMeters() { - return meters; - } - - public String getUnit() { - return unit; - } - - public void setUnit(String unit) { - this.unit = unit; - } - - @JsonCreator - public static Distance forValues(@JsonProperty("unit") String unit, @JsonProperty("meters") double meters) { - - for (Distance distance : Distance.values()) { - if (distance.unit.equals(unit) && Double.compare(distance.meters, meters) == 0) { - - return distance; - } - } - - return null; - - } -} - diff --git a/jackson-modules/jackson-conversions/src/main/java/com/ossez/jackson/enums/deserialization/jsonproperty/City.java b/jackson-modules/jackson-conversions/src/main/java/com/ossez/jackson/enums/deserialization/jsonproperty/City.java deleted file mode 100644 index 8d3ce1b326..0000000000 --- a/jackson-modules/jackson-conversions/src/main/java/com/ossez/jackson/enums/deserialization/jsonproperty/City.java +++ /dev/null @@ -1,15 +0,0 @@ -package com.ossez.jackson.enums.deserialization.jsonproperty; - -public class City { - - private Distance distance; - - public Distance getDistance() { - return distance; - } - - public void setDistance(Distance distance) { - this.distance = distance; - } - -} diff --git a/jackson-modules/jackson-conversions/src/main/java/com/ossez/jackson/enums/deserialization/jsonproperty/Distance.java b/jackson-modules/jackson-conversions/src/main/java/com/ossez/jackson/enums/deserialization/jsonproperty/Distance.java deleted file mode 100644 index 656a3dceee..0000000000 --- a/jackson-modules/jackson-conversions/src/main/java/com/ossez/jackson/enums/deserialization/jsonproperty/Distance.java +++ /dev/null @@ -1,51 +0,0 @@ -package com.ossez.jackson.enums.deserialization.jsonproperty; - -import com.fasterxml.jackson.annotation.JsonProperty; - -public enum Distance { - - @JsonProperty("distance-in-km") - KILOMETER("km", 1000), - - @JsonProperty("distance-in-miles") - MILE("miles", 1609.34), - - @JsonProperty("distance-in-meters") - METER("meters", 1), - - @JsonProperty("distance-in-inches") - INCH("inches", 0.0254), - - @JsonProperty("distance-in-cm") - CENTIMETER("cm", 0.01), - - @JsonProperty("distance-in-mm") - MILLIMETER("mm", 0.001); - - private String unit; - private double meters; - - private Distance(String unit, double meters) { - this.unit = unit; - this.meters = meters; - } - - public void setMeters(double meters) { - this.meters = meters; - } - - public double getMeters() { - return meters; - } - - public String getUnit() { - return unit; - } - - public void setUnit(String unit) { - this.unit = unit; - } - -} - - diff --git a/jackson-modules/jackson-conversions/src/main/java/com/ossez/jackson/enums/deserialization/jsonvalue/City.java b/jackson-modules/jackson-conversions/src/main/java/com/ossez/jackson/enums/deserialization/jsonvalue/City.java deleted file mode 100644 index bfe7f3c6e9..0000000000 --- a/jackson-modules/jackson-conversions/src/main/java/com/ossez/jackson/enums/deserialization/jsonvalue/City.java +++ /dev/null @@ -1,15 +0,0 @@ -package com.ossez.jackson.enums.deserialization.jsonvalue; - -public class City { - - private Distance distance; - - public Distance getDistance() { - return distance; - } - - public void setDistance(Distance distance) { - this.distance = distance; - } - -} diff --git a/jackson-modules/jackson-conversions/src/main/java/com/ossez/jackson/enums/deserialization/jsonvalue/Distance.java b/jackson-modules/jackson-conversions/src/main/java/com/ossez/jackson/enums/deserialization/jsonvalue/Distance.java deleted file mode 100644 index 530ddf9047..0000000000 --- a/jackson-modules/jackson-conversions/src/main/java/com/ossez/jackson/enums/deserialization/jsonvalue/Distance.java +++ /dev/null @@ -1,35 +0,0 @@ -package com.ossez.jackson.enums.deserialization.jsonvalue; - -import com.fasterxml.jackson.annotation.JsonValue; - -public enum Distance { - - KILOMETER("km", 1000), MILE("miles", 1609.34), METER("meters", 1), INCH("inches", 0.0254), CENTIMETER("cm", 0.01), MILLIMETER("mm", 0.001); - - private String unit; - private double meters; - - private Distance(String unit, double meters) { - this.unit = unit; - this.meters = meters; - } - - public void setMeters(double meters) { - this.meters = meters; - } - - @JsonValue - public double getMeters() { - return meters; - } - - public String getUnit() { - return unit; - } - - public void setUnit(String unit) { - this.unit = unit; - } - -} - diff --git a/jackson-modules/jackson-conversions/src/main/java/com/ossez/jackson/enums/serialization/Distance.java b/jackson-modules/jackson-conversions/src/main/java/com/ossez/jackson/enums/serialization/Distance.java deleted file mode 100644 index 18ef758dfc..0000000000 --- a/jackson-modules/jackson-conversions/src/main/java/com/ossez/jackson/enums/serialization/Distance.java +++ /dev/null @@ -1,53 +0,0 @@ -package com.ossez.jackson.enums.serialization; - -import com.fasterxml.jackson.databind.annotation.JsonSerialize; - -/** - * Use @JsonFormat to handle representation of Enum as JSON (available since Jackson 2.1.2) - * Use @JsonSerialize to configure a custom Jackson serializer - */ -// @JsonFormat(shape = JsonFormat.Shape.OBJECT) -@JsonSerialize(using = DistanceSerializer.class) -public enum Distance { - KILOMETER("km", 1000), MILE("miles", 1609.34), METER("meters", 1), INCH("inches", 0.0254), CENTIMETER("cm", 0.01), MILLIMETER("mm", 0.001); - - private String unit; - private final double meters; - - private Distance(String unit, double meters) { - this.unit = unit; - this.meters = meters; - } - - /** - * Use @JsonValue to control marshalling output for an enum - */ - // @JsonValue - public double getMeters() { - return meters; - } - - public String getUnit() { - return unit; - } - - public void setUnit(String unit) { - this.unit = unit; - } - - /** - * Usage example: Distance.MILE.convertFromMeters(1205.5); - */ - public double convertFromMeters(double distanceInMeters) { - return distanceInMeters / meters; - - } - - /** - * Usage example: Distance.MILE.convertToMeters(0.5); - */ - public double convertToMeters(double distanceInMeters) { - return distanceInMeters * meters; - } - -} \ No newline at end of file diff --git a/jackson-modules/jackson-conversions/src/main/java/com/ossez/jackson/enums/serialization/DistanceSerializer.java b/jackson-modules/jackson-conversions/src/main/java/com/ossez/jackson/enums/serialization/DistanceSerializer.java deleted file mode 100644 index 8fc9458daf..0000000000 --- a/jackson-modules/jackson-conversions/src/main/java/com/ossez/jackson/enums/serialization/DistanceSerializer.java +++ /dev/null @@ -1,32 +0,0 @@ -package com.ossez.jackson.enums.serialization; - -import java.io.IOException; - -import com.fasterxml.jackson.core.JsonGenerator; -import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.databind.SerializerProvider; -import com.fasterxml.jackson.databind.ser.std.StdSerializer; - -public class DistanceSerializer extends StdSerializer { - - private static final long serialVersionUID = 1376504304439963619L; - - public DistanceSerializer() { - super(Distance.class); - } - - public DistanceSerializer(Class t) { - super(t); - } - - public void serialize(Distance distance, JsonGenerator generator, SerializerProvider provider) throws IOException, JsonProcessingException { - generator.writeStartObject(); - generator.writeFieldName("name"); - generator.writeString(distance.name()); - generator.writeFieldName("unit"); - generator.writeString(distance.getUnit()); - generator.writeFieldName("meters"); - generator.writeNumber(distance.getMeters()); - generator.writeEndObject(); - } -} diff --git a/jackson-modules/jackson-conversions/src/main/java/com/ossez/jackson/enums/withEnum/DistanceEnumSimple.java b/jackson-modules/jackson-conversions/src/main/java/com/ossez/jackson/enums/withEnum/DistanceEnumSimple.java deleted file mode 100644 index a282e9e35f..0000000000 --- a/jackson-modules/jackson-conversions/src/main/java/com/ossez/jackson/enums/withEnum/DistanceEnumSimple.java +++ /dev/null @@ -1,26 +0,0 @@ -package com.ossez.jackson.enums.withEnum; - -public enum DistanceEnumSimple { - KILOMETER("km", 1000), MILE("miles", 1609.34), METER("meters", 1), INCH("inches", 0.0254), CENTIMETER("cm", 0.01), MILLIMETER("mm", 0.001); - - private String unit; - private final double meters; - - private DistanceEnumSimple(String unit, double meters) { - this.unit = unit; - this.meters = meters; - } - - public double getMeters() { - return meters; - } - - public String getUnit() { - return unit; - } - - public void setUnit(String unit) { - this.unit = unit; - } - -} \ No newline at end of file diff --git a/jackson-modules/jackson-conversions/src/main/java/com/ossez/jackson/enums/withEnum/DistanceEnumWithJsonFormat.java b/jackson-modules/jackson-conversions/src/main/java/com/ossez/jackson/enums/withEnum/DistanceEnumWithJsonFormat.java deleted file mode 100644 index c3d0050f31..0000000000 --- a/jackson-modules/jackson-conversions/src/main/java/com/ossez/jackson/enums/withEnum/DistanceEnumWithJsonFormat.java +++ /dev/null @@ -1,29 +0,0 @@ -package com.ossez.jackson.enums.withEnum; - -import com.fasterxml.jackson.annotation.JsonFormat; - -@JsonFormat(shape = JsonFormat.Shape.OBJECT) -public enum DistanceEnumWithJsonFormat { - KILOMETER("km", 1000), MILE("miles", 1609.34), METER("meters", 1), INCH("inches", 0.0254), CENTIMETER("cm", 0.01), MILLIMETER("mm", 0.001); - - private String unit; - private final double meters; - - private DistanceEnumWithJsonFormat(String unit, double meters) { - this.unit = unit; - this.meters = meters; - } - - public double getMeters() { - return meters; - } - - public String getUnit() { - return unit; - } - - public void setUnit(String unit) { - this.unit = unit; - } - -} \ No newline at end of file diff --git a/jackson-modules/jackson-conversions/src/main/java/com/ossez/jackson/enums/withEnum/DistanceEnumWithValue.java b/jackson-modules/jackson-conversions/src/main/java/com/ossez/jackson/enums/withEnum/DistanceEnumWithValue.java deleted file mode 100644 index a94cdde511..0000000000 --- a/jackson-modules/jackson-conversions/src/main/java/com/ossez/jackson/enums/withEnum/DistanceEnumWithValue.java +++ /dev/null @@ -1,29 +0,0 @@ -package com.ossez.jackson.enums.withEnum; - -import com.fasterxml.jackson.annotation.JsonValue; - -public enum DistanceEnumWithValue { - KILOMETER("km", 1000), MILE("miles", 1609.34), METER("meters", 1), INCH("inches", 0.0254), CENTIMETER("cm", 0.01), MILLIMETER("mm", 0.001); - - private String unit; - private final double meters; - - private DistanceEnumWithValue(String unit, double meters) { - this.unit = unit; - this.meters = meters; - } - - @JsonValue - public double getMeters() { - return meters; - } - - public String getUnit() { - return unit; - } - - public void setUnit(String unit) { - this.unit = unit; - } - -} \ No newline at end of file diff --git a/jackson-modules/jackson-conversions/src/main/java/com/ossez/jackson/enums/withEnum/MyDtoWithEnumCustom.java b/jackson-modules/jackson-conversions/src/main/java/com/ossez/jackson/enums/withEnum/MyDtoWithEnumCustom.java deleted file mode 100644 index 9895d03262..0000000000 --- a/jackson-modules/jackson-conversions/src/main/java/com/ossez/jackson/enums/withEnum/MyDtoWithEnumCustom.java +++ /dev/null @@ -1,59 +0,0 @@ -package com.ossez.jackson.enums.withEnum; - -import com.ossez.jackson.enums.serialization.Distance; - -public class MyDtoWithEnumCustom { - - private String stringValue; - private int intValue; - private boolean booleanValue; - private Distance type; - - public MyDtoWithEnumCustom() { - super(); - } - - public MyDtoWithEnumCustom(final String stringValue, final int intValue, final boolean booleanValue, final Distance type) { - super(); - - this.stringValue = stringValue; - this.intValue = intValue; - this.booleanValue = booleanValue; - this.type = type; - } - - // API - - public String getStringValue() { - return stringValue; - } - - public void setStringValue(final String stringValue) { - this.stringValue = stringValue; - } - - public int getIntValue() { - return intValue; - } - - public void setIntValue(final int intValue) { - this.intValue = intValue; - } - - public boolean isBooleanValue() { - return booleanValue; - } - - public void setBooleanValue(final boolean booleanValue) { - this.booleanValue = booleanValue; - } - - public Distance getType() { - return type; - } - - public void setType(final Distance type) { - this.type = type; - } - -} diff --git a/jackson-modules/jackson-conversions/src/main/java/com/ossez/jackson/enums/withEnum/MyDtoWithEnumJsonFormat.java b/jackson-modules/jackson-conversions/src/main/java/com/ossez/jackson/enums/withEnum/MyDtoWithEnumJsonFormat.java deleted file mode 100644 index c58b20b87d..0000000000 --- a/jackson-modules/jackson-conversions/src/main/java/com/ossez/jackson/enums/withEnum/MyDtoWithEnumJsonFormat.java +++ /dev/null @@ -1,57 +0,0 @@ -package com.ossez.jackson.enums.withEnum; - -public class MyDtoWithEnumJsonFormat { - - private String stringValue; - private int intValue; - private boolean booleanValue; - private DistanceEnumWithJsonFormat distanceType; - - public MyDtoWithEnumJsonFormat() { - super(); - } - - public MyDtoWithEnumJsonFormat(final String stringValue, final int intValue, final boolean booleanValue, final DistanceEnumWithJsonFormat type) { - super(); - - this.stringValue = stringValue; - this.intValue = intValue; - this.booleanValue = booleanValue; - this.distanceType = type; - } - - // API - - public String getStringValue() { - return stringValue; - } - - public void setStringValue(final String stringValue) { - this.stringValue = stringValue; - } - - public int getIntValue() { - return intValue; - } - - public void setIntValue(final int intValue) { - this.intValue = intValue; - } - - public boolean isBooleanValue() { - return booleanValue; - } - - public void setBooleanValue(final boolean booleanValue) { - this.booleanValue = booleanValue; - } - - public DistanceEnumWithJsonFormat getDistanceType() { - return distanceType; - } - - public void setDistanceType(final DistanceEnumWithJsonFormat type) { - this.distanceType = type; - } - -} diff --git a/jackson-modules/jackson-conversions/src/main/java/com/ossez/jackson/field/MyDto.java b/jackson-modules/jackson-conversions/src/main/java/com/ossez/jackson/field/MyDto.java deleted file mode 100644 index a4583c8b44..0000000000 --- a/jackson-modules/jackson-conversions/src/main/java/com/ossez/jackson/field/MyDto.java +++ /dev/null @@ -1,47 +0,0 @@ -package com.ossez.jackson.field; - -public class MyDto { - - private String stringValue; - private int intValue; - private boolean booleanValue; - - public MyDto() { - super(); - } - - public MyDto(final String stringValue, final int intValue, final boolean booleanValue) { - super(); - - this.stringValue = stringValue; - this.intValue = intValue; - this.booleanValue = booleanValue; - } - - // API - - public String getStringValue() { - return stringValue; - } - - public void setStringValue(final String stringValue) { - this.stringValue = stringValue; - } - - public int getIntValue() { - return intValue; - } - - public void setIntValue(final int intValue) { - this.intValue = intValue; - } - - public boolean getBooleanValue() { - return booleanValue; - } - - public void setBooleanValue(final boolean booleanValue) { - this.booleanValue = booleanValue; - } - -} diff --git a/jackson-modules/jackson-conversions/src/main/java/com/ossez/jackson/field/MyDtoAccessLevel.java b/jackson-modules/jackson-conversions/src/main/java/com/ossez/jackson/field/MyDtoAccessLevel.java deleted file mode 100644 index 7c0604990f..0000000000 --- a/jackson-modules/jackson-conversions/src/main/java/com/ossez/jackson/field/MyDtoAccessLevel.java +++ /dev/null @@ -1,23 +0,0 @@ -package com.ossez.jackson.field; - -public class MyDtoAccessLevel { - - private String stringValue; - int intValue; - protected float floatValue; - public boolean booleanValue; - - public MyDtoAccessLevel() { - super(); - } - - public MyDtoAccessLevel(final String stringValue, final int intValue, final float floatValue, final boolean booleanValue) { - super(); - - this.stringValue = stringValue; - this.intValue = intValue; - this.floatValue = floatValue; - this.booleanValue = booleanValue; - } - -} diff --git a/jackson-modules/jackson-conversions/src/main/java/com/ossez/jackson/field/MyDtoWithGetter.java b/jackson-modules/jackson-conversions/src/main/java/com/ossez/jackson/field/MyDtoWithGetter.java deleted file mode 100644 index 7d60251959..0000000000 --- a/jackson-modules/jackson-conversions/src/main/java/com/ossez/jackson/field/MyDtoWithGetter.java +++ /dev/null @@ -1,25 +0,0 @@ -package com.ossez.jackson.field; - -public class MyDtoWithGetter { - - private String stringValue; - private int intValue; - - public MyDtoWithGetter() { - super(); - } - - public MyDtoWithGetter(final String stringValue, final int intValue) { - super(); - - this.stringValue = stringValue; - this.intValue = intValue; - } - - // API - - public String getStringValue() { - return stringValue; - } - -} diff --git a/jackson-modules/jackson-conversions/src/main/java/com/ossez/jackson/field/MyDtoWithSetter.java b/jackson-modules/jackson-conversions/src/main/java/com/ossez/jackson/field/MyDtoWithSetter.java deleted file mode 100644 index f32c5d2151..0000000000 --- a/jackson-modules/jackson-conversions/src/main/java/com/ossez/jackson/field/MyDtoWithSetter.java +++ /dev/null @@ -1,29 +0,0 @@ -package com.ossez.jackson.field; - -public class MyDtoWithSetter { - - private int intValue; - public boolean booleanValue; - - public MyDtoWithSetter() { - super(); - } - - public MyDtoWithSetter(final int intValue, final boolean booleanValue) { - super(); - - this.intValue = intValue; - this.booleanValue = booleanValue; - } - - // API - - public void setIntValue(final int intValue) { - this.intValue = intValue; - } - - public int accessIntValue() { - return intValue; - } - -} diff --git a/jackson-modules/jackson-conversions/src/main/java/com/ossez/jackson/immutable/Employee.java b/jackson-modules/jackson-conversions/src/main/java/com/ossez/jackson/immutable/Employee.java deleted file mode 100644 index 46f44161cd..0000000000 --- a/jackson-modules/jackson-conversions/src/main/java/com/ossez/jackson/immutable/Employee.java +++ /dev/null @@ -1,24 +0,0 @@ -package com.ossez.jackson.immutable; - -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonProperty; - -public class Employee { - - private final long id; - private final String name; - - @JsonCreator(mode = JsonCreator.Mode.PROPERTIES) - public Employee(@JsonProperty("id") long id, @JsonProperty("name") String name) { - this.id = id; - this.name = name; - } - - public long getId() { - return id; - } - - public String getName() { - return name; - } -} diff --git a/jackson-modules/jackson-conversions/src/main/java/com/ossez/jackson/immutable/Person.java b/jackson-modules/jackson-conversions/src/main/java/com/ossez/jackson/immutable/Person.java deleted file mode 100644 index 9df9f8c808..0000000000 --- a/jackson-modules/jackson-conversions/src/main/java/com/ossez/jackson/immutable/Person.java +++ /dev/null @@ -1,44 +0,0 @@ -package com.ossez.jackson.immutable; - -import com.fasterxml.jackson.databind.annotation.JsonDeserialize; -import com.fasterxml.jackson.databind.annotation.JsonPOJOBuilder; - -@JsonDeserialize(builder = Person.Builder.class) -public class Person { - - private final String name; - private final Integer age; - - private Person(String name, Integer age) { - this.name = name; - this.age = age; - } - - public String getName() { - return name; - } - - public Integer getAge() { - return age; - } - - @JsonPOJOBuilder - static class Builder { - String name; - Integer age; - - Builder withName(String name) { - this.name = name; - return this; - } - - Builder withAge(Integer age) { - this.age = age; - return this; - } - - Person build() { - return new Person(name, age); - } - } -} diff --git a/jackson-modules/jackson-conversions/src/main/java/com/ossez/jackson/map/ClassWithAMap.java b/jackson-modules/jackson-conversions/src/main/java/com/ossez/jackson/map/ClassWithAMap.java deleted file mode 100644 index 09a9818630..0000000000 --- a/jackson-modules/jackson-conversions/src/main/java/com/ossez/jackson/map/ClassWithAMap.java +++ /dev/null @@ -1,23 +0,0 @@ -package com.ossez.jackson.map; - -import java.util.Map; - -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.databind.annotation.JsonDeserialize; - -public class ClassWithAMap { - - @JsonProperty("map") - @JsonDeserialize(keyUsing = MyPairDeserializer.class) - private final Map map; - - @JsonCreator - public ClassWithAMap(Map map) { - this.map = map; - } - - public Map getMap() { - return map; - } -} \ No newline at end of file diff --git a/jackson-modules/jackson-conversions/src/main/java/com/ossez/jackson/map/MyPair.java b/jackson-modules/jackson-conversions/src/main/java/com/ossez/jackson/map/MyPair.java deleted file mode 100644 index 4578aea4f2..0000000000 --- a/jackson-modules/jackson-conversions/src/main/java/com/ossez/jackson/map/MyPair.java +++ /dev/null @@ -1,80 +0,0 @@ -package com.ossez.jackson.map; - -import com.fasterxml.jackson.annotation.JsonValue; - -public class MyPair { - - private String first; - private String second; - - public MyPair(String first, String second) { - this.first = first; - this.second = second; - } - - public MyPair(String both) { - String[] pairs = both.split("and"); - this.first = pairs[0].trim(); - this.second = pairs[1].trim(); - } - - @Override - @JsonValue - public String toString() { - return first + " and " + second; - } - - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + ((first == null) ? 0 : first.hashCode()); - result = prime * result + ((second == null) ? 0 : second.hashCode()); - return result; - } - - @Override - public boolean equals(Object obj) { - if (this == obj) { - return true; - } - if (obj == null) { - return false; - } - if (!(obj instanceof MyPair)) { - return false; - } - MyPair other = (MyPair) obj; - if (first == null) { - if (other.first != null) { - return false; - } - } else if (!first.equals(other.first)) { - return false; - } - if (second == null) { - if (other.second != null) { - return false; - } - } else if (!second.equals(other.second)) { - return false; - } - return true; - } - - public String getFirst() { - return first; - } - - public void setFirst(String first) { - this.first = first; - } - - public String getSecond() { - return second; - } - - public void setSecond(String second) { - this.second = second; - } -} \ No newline at end of file diff --git a/jackson-modules/jackson-conversions/src/main/java/com/ossez/jackson/map/MyPairDeserializer.java b/jackson-modules/jackson-conversions/src/main/java/com/ossez/jackson/map/MyPairDeserializer.java deleted file mode 100644 index 5feb836b11..0000000000 --- a/jackson-modules/jackson-conversions/src/main/java/com/ossez/jackson/map/MyPairDeserializer.java +++ /dev/null @@ -1,16 +0,0 @@ -package com.ossez.jackson.map; - -import java.io.IOException; - -import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.databind.DeserializationContext; -import com.fasterxml.jackson.databind.KeyDeserializer; - -public class MyPairDeserializer extends KeyDeserializer { - - @Override - public MyPair deserializeKey(String key, DeserializationContext ctxt) throws IOException, JsonProcessingException { - - return new MyPair(key); - } -} \ No newline at end of file diff --git a/jackson-modules/jackson-conversions/src/main/java/com/ossez/jackson/map/MyPairSerializer.java b/jackson-modules/jackson-conversions/src/main/java/com/ossez/jackson/map/MyPairSerializer.java deleted file mode 100644 index 4fe480ff0d..0000000000 --- a/jackson-modules/jackson-conversions/src/main/java/com/ossez/jackson/map/MyPairSerializer.java +++ /dev/null @@ -1,22 +0,0 @@ -package com.ossez.jackson.map; - -import java.io.IOException; -import java.io.StringWriter; - -import com.fasterxml.jackson.core.JsonGenerator; -import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.databind.JsonSerializer; -import com.fasterxml.jackson.databind.ObjectMapper; -import com.fasterxml.jackson.databind.SerializerProvider; - -public class MyPairSerializer extends JsonSerializer { - - private final ObjectMapper mapper = new ObjectMapper(); - - @Override - public void serialize(MyPair value, JsonGenerator gen, SerializerProvider serializers) throws IOException, JsonProcessingException { - StringWriter writer = new StringWriter(); - mapper.writeValue(writer, value); - gen.writeFieldName(writer.toString()); - } -} \ No newline at end of file diff --git a/jackson-modules/jackson-conversions/src/main/java/com/ossez/jackson/mapnull/MyDto.java b/jackson-modules/jackson-conversions/src/main/java/com/ossez/jackson/mapnull/MyDto.java deleted file mode 100644 index 202c4c9aea..0000000000 --- a/jackson-modules/jackson-conversions/src/main/java/com/ossez/jackson/mapnull/MyDto.java +++ /dev/null @@ -1,54 +0,0 @@ -package com.ossez.jackson.mapnull; - -public class MyDto { - - private String stringValue; - private int intValue; - private boolean booleanValue; - - public MyDto() { - super(); - } - - public MyDto(final String stringValue, final int intValue, final boolean booleanValue) { - super(); - - this.stringValue = stringValue; - this.intValue = intValue; - this.booleanValue = booleanValue; - } - - // API - - public String getStringValue() { - return stringValue; - } - - public void setStringValue(final String stringValue) { - this.stringValue = stringValue; - } - - public int getIntValue() { - return intValue; - } - - public void setIntValue(final int intValue) { - this.intValue = intValue; - } - - public boolean isBooleanValue() { - return booleanValue; - } - - public void setBooleanValue(final boolean booleanValue) { - this.booleanValue = booleanValue; - } - - // - - @Override - public String toString() { - return "MyDto [stringValue=" + stringValue + ", intValue=" + intValue + ", booleanValue=" + booleanValue + "]"; - } - -} diff --git a/jackson-modules/jackson-conversions/src/main/java/com/ossez/jackson/mapnull/MyDtoNullKeySerializer.java b/jackson-modules/jackson-conversions/src/main/java/com/ossez/jackson/mapnull/MyDtoNullKeySerializer.java deleted file mode 100644 index 299ef45305..0000000000 --- a/jackson-modules/jackson-conversions/src/main/java/com/ossez/jackson/mapnull/MyDtoNullKeySerializer.java +++ /dev/null @@ -1,27 +0,0 @@ -package com.ossez.jackson.mapnull; - -import java.io.IOException; - -import com.fasterxml.jackson.core.JsonGenerator; -import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.databind.SerializerProvider; -import com.fasterxml.jackson.databind.ser.std.StdSerializer; - -public class MyDtoNullKeySerializer extends StdSerializer { - - private static final long serialVersionUID = -4478531309177369056L; - - public MyDtoNullKeySerializer() { - this(null); - } - - public MyDtoNullKeySerializer(final Class t) { - super(t); - } - - @Override - public void serialize(final Object value, final JsonGenerator jgen, final SerializerProvider provider) throws IOException, JsonProcessingException { - jgen.writeFieldName(""); - } - -} diff --git a/jackson-modules/jackson-conversions/src/main/java/com/ossez/jackson/tocollection/MyDto.java b/jackson-modules/jackson-conversions/src/main/java/com/ossez/jackson/tocollection/MyDto.java deleted file mode 100644 index 9b005299f0..0000000000 --- a/jackson-modules/jackson-conversions/src/main/java/com/ossez/jackson/tocollection/MyDto.java +++ /dev/null @@ -1,54 +0,0 @@ -package com.ossez.jackson.tocollection; - -public class MyDto { - - private String stringValue; - private int intValue; - private boolean booleanValue; - - public MyDto() { - super(); - } - - public MyDto(final String stringValue, final int intValue, final boolean booleanValue) { - super(); - - this.stringValue = stringValue; - this.intValue = intValue; - this.booleanValue = booleanValue; - } - - // API - - public String getStringValue() { - return stringValue; - } - - public void setStringValue(final String stringValue) { - this.stringValue = stringValue; - } - - public int getIntValue() { - return intValue; - } - - public void setIntValue(final int intValue) { - this.intValue = intValue; - } - - public boolean isBooleanValue() { - return booleanValue; - } - - public void setBooleanValue(final boolean booleanValue) { - this.booleanValue = booleanValue; - } - - // - - @Override - public String toString() { - return "MyDto [stringValue=" + stringValue + ", intValue=" + intValue + ", booleanValue=" + booleanValue + "]"; - } - -} diff --git a/jackson-modules/jackson-conversions/src/main/java/com/ossez/jackson/xml/Address.java b/jackson-modules/jackson-conversions/src/main/java/com/ossez/jackson/xml/Address.java deleted file mode 100644 index fcf78d025b..0000000000 --- a/jackson-modules/jackson-conversions/src/main/java/com/ossez/jackson/xml/Address.java +++ /dev/null @@ -1,33 +0,0 @@ -package com.ossez.jackson.xml; - -public class Address { - - String streetNumber; - String streetName; - String city; - - public String getStreetNumber() { - return streetNumber; - } - - public void setStreetNumber(String streetNumber) { - this.streetNumber = streetNumber; - } - - public String getStreetName() { - return streetName; - } - - public void setStreetName(String streetName) { - this.streetName = streetName; - } - - public String getCity() { - return city; - } - - public void setCity(String city) { - this.city = city; - } - -} diff --git a/jackson-modules/jackson-conversions/src/main/java/com/ossez/jackson/xml/Person.java b/jackson-modules/jackson-conversions/src/main/java/com/ossez/jackson/xml/Person.java deleted file mode 100644 index 08ea503ccc..0000000000 --- a/jackson-modules/jackson-conversions/src/main/java/com/ossez/jackson/xml/Person.java +++ /dev/null @@ -1,47 +0,0 @@ -package com.ossez.jackson.xml; - -import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlRootElement; - -import java.util.ArrayList; -import java.util.List; - -@JacksonXmlRootElement(localName = "person") -public final class Person { - private String firstName; - private String lastName; - private List phoneNumbers = new ArrayList<>(); - private List
address = new ArrayList<>(); - - public List
getAddress() { - return address; - } - - public void setAddress(List
address) { - this.address = address; - } - - public String getFirstName() { - return firstName; - } - - public void setFirstName(String firstName) { - this.firstName = firstName; - } - - public String getLastName() { - return lastName; - } - - public void setLastName(String lastName) { - this.lastName = lastName; - } - - public List getPhoneNumbers() { - return phoneNumbers; - } - - public void setPhoneNumbers(List phoneNumbers) { - this.phoneNumbers = phoneNumbers; - } - -} \ No newline at end of file diff --git a/jackson-modules/jackson-conversions/src/test/java/com/ossez/jackson/date/JacksonDateUnitTest.java b/jackson-modules/jackson-conversions/src/test/java/com/ossez/jackson/date/JacksonDateUnitTest.java deleted file mode 100644 index 1171c9e432..0000000000 --- a/jackson-modules/jackson-conversions/src/test/java/com/ossez/jackson/date/JacksonDateUnitTest.java +++ /dev/null @@ -1,212 +0,0 @@ -package com.ossez.jackson.date; - -import static org.hamcrest.Matchers.containsString; -import static org.hamcrest.CoreMatchers.*; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertThat; - -import java.io.IOException; -import java.text.ParseException; -import java.text.SimpleDateFormat; -import java.time.LocalDate; -import java.time.LocalDateTime; -import java.time.ZoneId; -import java.time.ZonedDateTime; -import java.util.Date; -import java.util.TimeZone; - -import org.joda.time.DateTime; -import org.joda.time.DateTimeZone; -import org.junit.Test; - -import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.databind.ObjectMapper; -import com.fasterxml.jackson.databind.SerializationFeature; -import com.fasterxml.jackson.databind.util.StdDateFormat; -import com.fasterxml.jackson.datatype.joda.JodaModule; -import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule; - -public class JacksonDateUnitTest { - - @Test - public void whenSerializingDateWithJackson_thenSerializedToTimestamp() throws JsonProcessingException, ParseException { - final SimpleDateFormat df = new SimpleDateFormat("dd-MM-yyyy hh:mm"); - df.setTimeZone(TimeZone.getTimeZone("UTC")); - - final String toParse = "01-01-1970 01:00"; - final Date date = df.parse(toParse); - final Event event = new Event("party", date); - - final ObjectMapper mapper = new ObjectMapper(); - final String result = mapper.writeValueAsString(event); - assertThat(result, containsString("3600000")); - } - - @Test - public void whenSerializingDateToISO8601_thenSerializedToText() throws JsonProcessingException, ParseException { - final SimpleDateFormat df = new SimpleDateFormat("dd-MM-yyyy hh:mm"); - df.setTimeZone(TimeZone.getTimeZone("UTC")); - - final String toParse = "01-01-1970 02:30"; - final Date date = df.parse(toParse); - final Event event = new Event("party", date); - - final ObjectMapper mapper = new ObjectMapper(); - mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS); - - // StdDateFormat is ISO8601 since jackson 2.9 - mapper.setDateFormat(new StdDateFormat().withColonInTimeZone(true)); - - final String result = mapper.writeValueAsString(event); - assertThat(result, containsString("1970-01-01T02:30:00.000+00:00")); - } - - @Test - public void whenDeserialisingZonedDateTimeWithDefaults_thenNotCorrect() - throws IOException { - ObjectMapper objectMapper = new ObjectMapper(); - objectMapper.findAndRegisterModules(); - objectMapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS); - ZonedDateTime now = ZonedDateTime.now(ZoneId.of("UTC")); - String converted = objectMapper.writeValueAsString(now); - - ZonedDateTime restored = objectMapper.readValue(converted, ZonedDateTime.class); - System.out.println("serialized: " + now); - System.out.println("restored: " + restored); - assertThat(now, is(restored)); - } - - @Test - public void whenSettingObjectMapperDateFormat_thenCorrect() throws JsonProcessingException, ParseException { - final SimpleDateFormat df = new SimpleDateFormat("dd-MM-yyyy hh:mm"); - - final String toParse = "20-12-2014 02:30"; - final Date date = df.parse(toParse); - final Event event = new Event("party", date); - - final ObjectMapper mapper = new ObjectMapper(); - mapper.setDateFormat(df); - - final String result = mapper.writeValueAsString(event); - assertThat(result, containsString(toParse)); - } - - @Test - public void whenUsingJsonFormatAnnotationToFormatDate_thenCorrect() throws JsonProcessingException, ParseException { - final SimpleDateFormat df = new SimpleDateFormat("dd-MM-yyyy hh:mm:ss"); - df.setTimeZone(TimeZone.getTimeZone("UTC")); - - final String toParse = "20-12-2014 02:30:00"; - final Date date = df.parse(toParse); - final EventWithFormat event = new EventWithFormat("party", date); - - final ObjectMapper mapper = new ObjectMapper(); - final String result = mapper.writeValueAsString(event); - assertThat(result, containsString(toParse)); - } - - @Test - public void whenUsingCustomDateSerializer_thenCorrect() throws JsonProcessingException, ParseException { - final SimpleDateFormat df = new SimpleDateFormat("dd-MM-yyyy hh:mm:ss"); - - final String toParse = "20-12-2014 02:30:00"; - final Date date = df.parse(toParse); - final EventWithSerializer event = new EventWithSerializer("party", date); - - final ObjectMapper mapper = new ObjectMapper(); - final String result = mapper.writeValueAsString(event); - assertThat(result, containsString(toParse)); - } - - @Test - public void whenSerializingJodaTimeWithJackson_thenCorrect() throws JsonProcessingException { - final DateTime date = new DateTime(2014, 12, 20, 2, 30); - final EventWithJodaTime event = new EventWithJodaTime("party", date); - - final ObjectMapper mapper = new ObjectMapper(); - final String result = mapper.writeValueAsString(event); - assertThat(result, containsString("2014-12-20 02:30")); - } - - @Test - public void whenSerializingJava8DateWithCustomSerializer_thenCorrect() throws JsonProcessingException { - final LocalDateTime date = LocalDateTime.of(2014, 12, 20, 2, 30); - final EventWithLocalDateTime event = new EventWithLocalDateTime("party", date); - - final ObjectMapper mapper = new ObjectMapper(); - final String result = mapper.writeValueAsString(event); - assertThat(result, containsString("2014-12-20 02:30")); - } - - @Test - public void whenDeserializingDateWithJackson_thenCorrect() throws IOException { - final String json = "{\"name\":\"party\",\"eventDate\":\"20-12-2014 02:30:00\"}"; - - final SimpleDateFormat df = new SimpleDateFormat("dd-MM-yyyy hh:mm:ss"); - final ObjectMapper mapper = new ObjectMapper(); - mapper.setDateFormat(df); - - final Event event = mapper.readerFor(Event.class) - .readValue(json); - assertEquals("20-12-2014 02:30:00", df.format(event.eventDate)); - } - - @Test - public void whenDeserializingDateUsingCustomDeserializer_thenCorrect() throws IOException { - final String json = "{\"name\":\"party\",\"eventDate\":\"20-12-2014 02:30:00\"}"; - - final SimpleDateFormat df = new SimpleDateFormat("dd-MM-yyyy hh:mm:ss"); - final ObjectMapper mapper = new ObjectMapper(); - - final EventWithSerializer event = mapper.readerFor(EventWithSerializer.class) - .readValue(json); - assertEquals("20-12-2014 02:30:00", df.format(event.eventDate)); - } - - @Test - public void whenSerializingJava8Date_thenCorrect() throws JsonProcessingException { - final LocalDateTime date = LocalDateTime.of(2014, 12, 20, 2, 30); - - final ObjectMapper mapper = new ObjectMapper(); - mapper.registerModule(new JavaTimeModule()); - mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS); - - final String result = mapper.writeValueAsString(date); - assertThat(result, containsString("2014-12-20T02:30")); - } - - @Test - public void whenSerializingJava8DateAndReadingValue_thenCorrect() throws IOException { - String stringDate = "\"2014-12-20\""; - - ObjectMapper mapper = new ObjectMapper(); - mapper.registerModule(new JavaTimeModule()); - mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS); - - LocalDate result = mapper.readValue(stringDate, LocalDate.class); - assertThat(result.toString(), containsString("2014-12-20")); - } - - @Test - public void whenSerializingJava8DateAndReadingFromEntity_thenCorrect() throws IOException { - String json = "{\"name\":\"party\",\"eventDate\":\"20-12-2014\"}"; - - ObjectMapper mapper = new ObjectMapper(); - - EventWithLocalDate result = mapper.readValue(json, EventWithLocalDate.class); - assertThat(result.getEventDate().toString(), containsString("2014-12-20")); - } - - @Test - public void whenSerializingJodaTime_thenCorrect() throws JsonProcessingException { - final DateTime date = new DateTime(2014, 12, 20, 2, 30, DateTimeZone.forID("Europe/London")); - - final ObjectMapper mapper = new ObjectMapper(); - mapper.registerModule(new JodaModule()); - mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS); - - final String result = mapper.writeValueAsString(date); - assertThat(result, containsString("2014-12-20T02:30:00.000Z")); - } - -} \ No newline at end of file diff --git a/jackson-modules/jackson-conversions/src/test/java/com/ossez/jackson/enums/deserialization/DefaultEnumDeserializationUnitTest.java b/jackson-modules/jackson-conversions/src/test/java/com/ossez/jackson/enums/deserialization/DefaultEnumDeserializationUnitTest.java deleted file mode 100644 index 12596336cc..0000000000 --- a/jackson-modules/jackson-conversions/src/test/java/com/ossez/jackson/enums/deserialization/DefaultEnumDeserializationUnitTest.java +++ /dev/null @@ -1,20 +0,0 @@ -package com.ossez.jackson.enums.deserialization; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import java.io.IOException; - -import org.junit.Test; -import com.fasterxml.jackson.core.JsonParseException; -import com.fasterxml.jackson.databind.ObjectMapper; - -public class DefaultEnumDeserializationUnitTest { - - @Test - public void givenEnum_whenDeserializingJson_thenCorrectRepresentation() throws JsonParseException, IOException { - String json = "{\"distance\":\"KILOMETER\"}"; - City city = new ObjectMapper().readValue(json, City.class); - - assertEquals(Distance.KILOMETER, city.getDistance()); - } - -} diff --git a/jackson-modules/jackson-conversions/src/test/java/com/ossez/jackson/enums/deserialization/customdeserializer/EnumCustomDeserializationUnitTest.java b/jackson-modules/jackson-conversions/src/test/java/com/ossez/jackson/enums/deserialization/customdeserializer/EnumCustomDeserializationUnitTest.java deleted file mode 100644 index f3f561e021..0000000000 --- a/jackson-modules/jackson-conversions/src/test/java/com/ossez/jackson/enums/deserialization/customdeserializer/EnumCustomDeserializationUnitTest.java +++ /dev/null @@ -1,19 +0,0 @@ -package com.ossez.jackson.enums.deserialization.customdeserializer; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import java.io.IOException; - -import org.junit.Test; -import com.fasterxml.jackson.core.JsonParseException; -import com.fasterxml.jackson.databind.ObjectMapper; - -public class EnumCustomDeserializationUnitTest { - - @Test - public void givenEnumWithCustomDeserializer_whenDeserializingJson_thenCorrectRepresentation() throws JsonParseException, IOException { - String json = "{\"distance\": {\"unit\":\"miles\",\"meters\":1609.34}}"; - - City city = new ObjectMapper().readValue(json, City.class); - assertEquals(Distance.MILE, city.getDistance()); - } -} diff --git a/jackson-modules/jackson-conversions/src/test/java/com/ossez/jackson/enums/deserialization/jsoncreator/EnumDeserializationUsingJsonCreatorUnitTest.java b/jackson-modules/jackson-conversions/src/test/java/com/ossez/jackson/enums/deserialization/jsoncreator/EnumDeserializationUsingJsonCreatorUnitTest.java deleted file mode 100644 index 239e36b261..0000000000 --- a/jackson-modules/jackson-conversions/src/test/java/com/ossez/jackson/enums/deserialization/jsoncreator/EnumDeserializationUsingJsonCreatorUnitTest.java +++ /dev/null @@ -1,20 +0,0 @@ -package com.ossez.jackson.enums.deserialization.jsoncreator; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import java.io.IOException; - -import org.junit.Test; -import com.fasterxml.jackson.core.JsonParseException; -import com.fasterxml.jackson.databind.ObjectMapper; - -public class EnumDeserializationUsingJsonCreatorUnitTest { - - @Test - public void givenEnumWithJsonCreator_whenDeserializingJson_thenCorrectRepresentation() throws JsonParseException, IOException { - String json = "{\"distance\": {\"unit\":\"miles\",\"meters\":1609.34}}"; - - City city = new ObjectMapper().readValue(json, City.class); - assertEquals(Distance.MILE, city.getDistance()); - } - -} diff --git a/jackson-modules/jackson-conversions/src/test/java/com/ossez/jackson/enums/deserialization/jsonproperty/EnumDeserializationUsingJsonPropertyUnitTest.java b/jackson-modules/jackson-conversions/src/test/java/com/ossez/jackson/enums/deserialization/jsonproperty/EnumDeserializationUsingJsonPropertyUnitTest.java deleted file mode 100644 index 883e1d7d57..0000000000 --- a/jackson-modules/jackson-conversions/src/test/java/com/ossez/jackson/enums/deserialization/jsonproperty/EnumDeserializationUsingJsonPropertyUnitTest.java +++ /dev/null @@ -1,21 +0,0 @@ -package com.ossez.jackson.enums.deserialization.jsonproperty; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import java.io.IOException; - -import org.junit.Test; -import com.fasterxml.jackson.core.JsonParseException; -import com.fasterxml.jackson.databind.ObjectMapper; - -public class EnumDeserializationUsingJsonPropertyUnitTest { - - @Test - public void givenEnumWithJsonProperty_whenDeserializingJson_thenCorrectRepresentation() throws JsonParseException, IOException { - String json = "{\"distance\": \"distance-in-km\"}"; - - City city = new ObjectMapper().readValue(json, City.class); - assertEquals(Distance.KILOMETER, city.getDistance()); - - } - -} diff --git a/jackson-modules/jackson-conversions/src/test/java/com/ossez/jackson/enums/deserialization/jsonvalue/EnumDeserializationUsingJsonValueUnitTest.java b/jackson-modules/jackson-conversions/src/test/java/com/ossez/jackson/enums/deserialization/jsonvalue/EnumDeserializationUsingJsonValueUnitTest.java deleted file mode 100644 index 1b38340684..0000000000 --- a/jackson-modules/jackson-conversions/src/test/java/com/ossez/jackson/enums/deserialization/jsonvalue/EnumDeserializationUsingJsonValueUnitTest.java +++ /dev/null @@ -1,20 +0,0 @@ -package com.ossez.jackson.enums.deserialization.jsonvalue; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import java.io.IOException; - -import org.junit.Test; -import com.fasterxml.jackson.core.JsonParseException; -import com.fasterxml.jackson.databind.ObjectMapper; - -public class EnumDeserializationUsingJsonValueUnitTest { - - @Test - public void givenEnumWithJsonValue_whenDeserializingJson_thenCorrectRepresentation() throws JsonParseException, IOException { - String json = "{\"distance\": \"0.0254\"}"; - - City city = new ObjectMapper().readValue(json, City.class); - assertEquals(Distance.INCH, city.getDistance()); - } - -} diff --git a/jackson-modules/jackson-conversions/src/test/java/com/ossez/jackson/enums/serialization/JacksonEnumSerializationUnitTest.java b/jackson-modules/jackson-conversions/src/test/java/com/ossez/jackson/enums/serialization/JacksonEnumSerializationUnitTest.java deleted file mode 100644 index f3f0440a92..0000000000 --- a/jackson-modules/jackson-conversions/src/test/java/com/ossez/jackson/enums/serialization/JacksonEnumSerializationUnitTest.java +++ /dev/null @@ -1,20 +0,0 @@ -package com.ossez.jackson.enums.serialization; - -import static org.hamcrest.Matchers.containsString; -import static org.junit.Assert.assertThat; -import java.io.IOException; - -import org.junit.Test; -import com.fasterxml.jackson.core.JsonParseException; -import com.fasterxml.jackson.databind.ObjectMapper; - -public class JacksonEnumSerializationUnitTest { - - @Test - public final void givenEnum_whenSerializingJson_thenCorrectRepresentation() throws JsonParseException, IOException { - final String dtoAsString = new ObjectMapper().writeValueAsString(Distance.MILE); - - assertThat(dtoAsString, containsString("1609.34")); - } - -} diff --git a/jackson-modules/jackson-conversions/src/test/java/com/ossez/jackson/enums/serialization/JacksonSerializationEnumsUnitTest.java b/jackson-modules/jackson-conversions/src/test/java/com/ossez/jackson/enums/serialization/JacksonSerializationEnumsUnitTest.java deleted file mode 100644 index fc9064c3c1..0000000000 --- a/jackson-modules/jackson-conversions/src/test/java/com/ossez/jackson/enums/serialization/JacksonSerializationEnumsUnitTest.java +++ /dev/null @@ -1,77 +0,0 @@ -package com.ossez.jackson.enums.serialization; - -import static org.hamcrest.Matchers.containsString; -import static org.hamcrest.Matchers.is; -import static org.junit.Assert.assertThat; - -import java.io.IOException; - -import org.junit.Test; - -import com.ossez.jackson.enums.withEnum.DistanceEnumSimple; -import com.ossez.jackson.enums.withEnum.DistanceEnumWithJsonFormat; -import com.ossez.jackson.enums.withEnum.DistanceEnumWithValue; -import com.ossez.jackson.enums.withEnum.MyDtoWithEnumCustom; -import com.ossez.jackson.enums.withEnum.MyDtoWithEnumJsonFormat; -import com.fasterxml.jackson.core.JsonParseException; -import com.fasterxml.jackson.databind.ObjectMapper; - -public class JacksonSerializationEnumsUnitTest { - - // tests - simple enum - - @Test - public final void whenSerializingASimpleEnum_thenCorrect() throws JsonParseException, IOException { - final ObjectMapper mapper = new ObjectMapper(); - final String enumAsString = mapper.writeValueAsString(DistanceEnumSimple.MILE); - - assertThat(enumAsString, containsString("MILE")); - } - - // tests - enum with main value - - @Test - public final void whenSerializingAEnumWithValue_thenCorrect() throws JsonParseException, IOException { - final ObjectMapper mapper = new ObjectMapper(); - final String enumAsString = mapper.writeValueAsString(DistanceEnumWithValue.MILE); - - assertThat(enumAsString, is("1609.34")); - } - - // tests - enum - - @Test - public final void whenSerializingAnEnum_thenCorrect() throws JsonParseException, IOException { - final ObjectMapper mapper = new ObjectMapper(); - final String enumAsString = mapper.writeValueAsString(DistanceEnumWithJsonFormat.MILE); - - assertThat(enumAsString, containsString("\"meters\":1609.34")); - } - - @Test - public final void whenSerializingEntityWithEnum_thenCorrect() throws JsonParseException, IOException { - final ObjectMapper mapper = new ObjectMapper(); - final String enumAsString = mapper.writeValueAsString(new MyDtoWithEnumJsonFormat("a", 1, true, DistanceEnumWithJsonFormat.MILE)); - - assertThat(enumAsString, containsString("\"meters\":1609.34")); - } - - @Test - public final void whenSerializingArrayOfEnums_thenCorrect() throws JsonParseException, IOException { - final ObjectMapper mapper = new ObjectMapper(); - final String json = mapper.writeValueAsString(new DistanceEnumWithJsonFormat[] { DistanceEnumWithJsonFormat.MILE, DistanceEnumWithJsonFormat.KILOMETER }); - - assertThat(json, containsString("\"meters\":1609.34")); - } - - // tests - enum with custom serializer - - @Test - public final void givenCustomSerializer_whenSerializingEntityWithEnum_thenCorrect() throws JsonParseException, IOException { - final ObjectMapper mapper = new ObjectMapper(); - final String enumAsString = mapper.writeValueAsString(new MyDtoWithEnumCustom("a", 1, true, Distance.MILE)); - - assertThat(enumAsString, containsString("\"meters\":1609.34")); - } - -} diff --git a/jackson-modules/jackson-conversions/src/test/java/com/ossez/jackson/field/JacksonFieldUnitTest.java b/jackson-modules/jackson-conversions/src/test/java/com/ossez/jackson/field/JacksonFieldUnitTest.java deleted file mode 100644 index d3054aa483..0000000000 --- a/jackson-modules/jackson-conversions/src/test/java/com/ossez/jackson/field/JacksonFieldUnitTest.java +++ /dev/null @@ -1,92 +0,0 @@ -package com.ossez.jackson.field; - -import static org.hamcrest.Matchers.containsString; -import static org.hamcrest.Matchers.equalTo; -import static org.hamcrest.Matchers.not; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertThat; - -import java.io.IOException; -import org.junit.Test; - -import com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility; -import com.fasterxml.jackson.annotation.PropertyAccessor; -import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.databind.ObjectMapper; - -public class JacksonFieldUnitTest { - - @Test - public final void givenDifferentAccessLevels_whenPublic_thenSerializable() throws JsonProcessingException { - final ObjectMapper mapper = new ObjectMapper(); - - final MyDtoAccessLevel dtoObject = new MyDtoAccessLevel(); - - final String dtoAsString = mapper.writeValueAsString(dtoObject); - assertThat(dtoAsString, not(containsString("stringValue"))); - assertThat(dtoAsString, not(containsString("intValue"))); - assertThat(dtoAsString, not(containsString("floatValue"))); - assertThat(dtoAsString, containsString("booleanValue")); - System.out.println(dtoAsString); - } - - @Test - public final void givenDifferentAccessLevels_whenGetterAdded_thenSerializable() throws JsonProcessingException { - final ObjectMapper mapper = new ObjectMapper(); - - final MyDtoWithGetter dtoObject = new MyDtoWithGetter(); - - final String dtoAsString = mapper.writeValueAsString(dtoObject); - assertThat(dtoAsString, containsString("stringValue")); - assertThat(dtoAsString, not(containsString("intValue"))); - System.out.println(dtoAsString); - } - - @Test - public final void givenDifferentAccessLevels_whenGetterAdded_thenDeserializable() throws IOException { - final String jsonAsString = "{\"stringValue\":\"dtoString\"}"; - final ObjectMapper mapper = new ObjectMapper(); - - final MyDtoWithGetter dtoObject = mapper.readValue(jsonAsString, MyDtoWithGetter.class); - - assertNotNull(dtoObject); - assertThat(dtoObject.getStringValue(), equalTo("dtoString")); - } - - @Test - public final void givenDifferentAccessLevels_whenSetterAdded_thenDeserializable() throws IOException { - final String jsonAsString = "{\"intValue\":1}"; - final ObjectMapper mapper = new ObjectMapper(); - - final MyDtoWithSetter dtoObject = mapper.readValue(jsonAsString, MyDtoWithSetter.class); - - assertNotNull(dtoObject); - assertThat(dtoObject.accessIntValue(), equalTo(1)); - } - - @Test - public final void givenDifferentAccessLevels_whenSetterAdded_thenStillNotSerializable() throws IOException { - final ObjectMapper mapper = new ObjectMapper(); - - final MyDtoWithSetter dtoObject = new MyDtoWithSetter(); - - final String dtoAsString = mapper.writeValueAsString(dtoObject); - assertThat(dtoAsString, not(containsString("intValue"))); - System.out.println(dtoAsString); - } - - @Test - public final void givenDifferentAccessLevels_whenSetVisibility_thenSerializable() throws IOException { - final ObjectMapper mapper = new ObjectMapper(); - mapper.setVisibility(PropertyAccessor.FIELD, Visibility.ANY); - - final MyDtoAccessLevel dtoObject = new MyDtoAccessLevel(); - - final String dtoAsString = mapper.writeValueAsString(dtoObject); - assertThat(dtoAsString, containsString("stringValue")); - assertThat(dtoAsString, containsString("intValue")); - assertThat(dtoAsString, containsString("booleanValue")); - System.out.println(dtoAsString); - } - -} diff --git a/jackson-modules/jackson-conversions/src/test/java/com/ossez/jackson/immutable/ImmutableObjectDeserializationUnitTest.java b/jackson-modules/jackson-conversions/src/test/java/com/ossez/jackson/immutable/ImmutableObjectDeserializationUnitTest.java deleted file mode 100644 index de21167fb0..0000000000 --- a/jackson-modules/jackson-conversions/src/test/java/com/ossez/jackson/immutable/ImmutableObjectDeserializationUnitTest.java +++ /dev/null @@ -1,38 +0,0 @@ -package com.ossez.jackson.immutable; - -import com.fasterxml.jackson.databind.ObjectMapper; -import org.junit.Test; - -import java.io.IOException; - -import static org.junit.Assert.*; - -public class ImmutableObjectDeserializationUnitTest { - - @Test - public void whenPublicConstructorIsUsed_thenObjectIsDeserialized() throws IOException { - final String json = "{\"name\":\"Frank\",\"id\":5000}"; - Employee employee = new ObjectMapper().readValue(json, Employee.class); - - assertEquals("Frank", employee.getName()); - assertEquals(5000, employee.getId()); - } - - @Test - public void whenBuilderIsUsedAndFieldIsNull_thenObjectIsDeserialized() throws IOException { - final String json = "{\"name\":\"Frank\"}"; - Person person = new ObjectMapper().readValue(json, Person.class); - - assertEquals("Frank", person.getName()); - assertNull(person.getAge()); - } - - @Test - public void whenBuilderIsUsedAndAllFieldsPresent_thenObjectIsDeserialized() throws IOException { - final String json = "{\"name\":\"Frank\",\"age\":50}"; - Person person = new ObjectMapper().readValue(json, Person.class); - - assertEquals("Frank", person.getName()); - assertEquals(50, (int) person.getAge()); - } -} diff --git a/jackson-modules/jackson-conversions/src/test/java/com/ossez/jackson/map/JacksonMapDeserializeUnitTest.java b/jackson-modules/jackson-conversions/src/test/java/com/ossez/jackson/map/JacksonMapDeserializeUnitTest.java deleted file mode 100644 index dd3db4703d..0000000000 --- a/jackson-modules/jackson-conversions/src/test/java/com/ossez/jackson/map/JacksonMapDeserializeUnitTest.java +++ /dev/null @@ -1,62 +0,0 @@ -package com.ossez.jackson.map; - -import java.io.IOException; -import java.util.HashMap; -import java.util.Map; - -import org.junit.Assert; -import org.junit.Test; - -import com.fasterxml.jackson.core.JsonParseException; -import com.fasterxml.jackson.core.type.TypeReference; -import com.fasterxml.jackson.databind.JsonMappingException; -import com.fasterxml.jackson.databind.ObjectMapper; - -public class JacksonMapDeserializeUnitTest { - - private Map map; - private Map cmap; - final ObjectMapper mapper = new ObjectMapper(); - - @Test - public void whenSimpleMapDeserialize_thenCorrect() throws JsonParseException, JsonMappingException, IOException { - - final String jsonInput = "{\"key\": \"value\"}"; - TypeReference> typeRef = new TypeReference>() { - }; - - final Map map = mapper.readValue(jsonInput, typeRef); - - Assert.assertEquals("value", map.get("key")); - } - - @Test - public void whenObjectStringMapDeserialize_thenCorrect() throws JsonParseException, JsonMappingException, IOException { - - final String jsonInput = "{\"Abbott and Costello\":\"Comedy\"}"; - - TypeReference> typeRef = new TypeReference>() { - }; - - map = mapper.readValue(jsonInput, typeRef); - - Assert.assertEquals("Comedy", map.get(new MyPair("Abbott", "Costello"))); - - ClassWithAMap classWithMap = mapper.readValue(jsonInput, ClassWithAMap.class); - - Assert.assertEquals("Comedy", classWithMap.getMap() - .get(new MyPair("Abbott", "Costello"))); - } - - @Test - public void whenObjectObjectMapDeserialize_thenCorrect() throws JsonParseException, JsonMappingException, IOException { - - final String jsonInput = "{\"Abbott and Costello\" : \"Comedy and 1940s\"}"; - TypeReference> typeRef = new TypeReference>() { - }; - - cmap = mapper.readValue(jsonInput, typeRef); - - Assert.assertEquals(new MyPair("Comedy", "1940s"), cmap.get(new MyPair("Abbott", "Costello"))); - } -} diff --git a/jackson-modules/jackson-conversions/src/test/java/com/ossez/jackson/map/JacksonMapSerializeUnitTest.java b/jackson-modules/jackson-conversions/src/test/java/com/ossez/jackson/map/JacksonMapSerializeUnitTest.java deleted file mode 100644 index af8bcfb083..0000000000 --- a/jackson-modules/jackson-conversions/src/test/java/com/ossez/jackson/map/JacksonMapSerializeUnitTest.java +++ /dev/null @@ -1,65 +0,0 @@ -package com.ossez.jackson.map; - -import java.util.HashMap; -import java.util.Map; - -import org.junit.Assert; -import org.junit.Test; - -import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.databind.ObjectMapper; -import com.fasterxml.jackson.databind.annotation.JsonSerialize; -import com.fasterxml.jackson.databind.ser.std.MapSerializer; - -public class JacksonMapSerializeUnitTest { - - @JsonSerialize(keyUsing = MyPairSerializer.class) - private Map map; - - @JsonSerialize(keyUsing = MapSerializer.class) - private Map cmap; - - @JsonSerialize(keyUsing = MyPairSerializer.class) - private MyPair mapKey; - - @JsonSerialize(keyUsing = MyPairSerializer.class) - private MyPair mapValue; - - final ObjectMapper mapper = new ObjectMapper(); - - @Test - public void whenSimpleMapSerialize_thenCorrect() throws JsonProcessingException { - - Map map = new HashMap<>(); - map.put("key", "value"); - - final String jsonResult = mapper.writeValueAsString(map); - - Assert.assertEquals("{\"key\":\"value\"}", jsonResult); - } - - @Test - public void whenCustomObjectStringMapSerialize_thenCorrect() throws JsonProcessingException { - - map = new HashMap<>(); - MyPair key = new MyPair("Abbott", "Costello"); - map.put(key, "Comedy"); - - final String jsonResult = mapper.writeValueAsString(map); - - Assert.assertEquals("{\"Abbott and Costello\":\"Comedy\"}", jsonResult); - } - - @Test - public void whenCustomObjectObjectMapSerialize_thenCorrect() throws JsonProcessingException { - - cmap = new HashMap<>(); - mapKey = new MyPair("Abbott", "Costello"); - mapValue = new MyPair("Comedy", "1940's"); - cmap.put(mapKey, mapValue); - - final String jsonResult = mapper.writeValueAsString(cmap); - - Assert.assertEquals("{\"Abbott and Costello\":\"Comedy and 1940's\"}", jsonResult); - } -} diff --git a/jackson-modules/jackson-conversions/src/test/java/com/ossez/jackson/mapnull/JacksonMapNullUnitTest.java b/jackson-modules/jackson-conversions/src/test/java/com/ossez/jackson/mapnull/JacksonMapNullUnitTest.java deleted file mode 100644 index 3d65b2397b..0000000000 --- a/jackson-modules/jackson-conversions/src/test/java/com/ossez/jackson/mapnull/JacksonMapNullUnitTest.java +++ /dev/null @@ -1,99 +0,0 @@ -package com.ossez.jackson.mapnull; - -import com.fasterxml.jackson.annotation.JsonInclude.Include; -import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.databind.ObjectMapper; -import org.junit.Test; - -import java.util.HashMap; -import java.util.Map; - -import static org.hamcrest.Matchers.containsString; -import static org.hamcrest.Matchers.not; -import static org.junit.Assert.assertThat; - -public class JacksonMapNullUnitTest { - - @Test - public final void givenIgnoringMapNullValue_whenWritingMapObjectWithNullValue_thenIgnored() throws JsonProcessingException { - final ObjectMapper mapper = new ObjectMapper(); - // mapper.configure(SerializationFeature.WRITE_NULL_MAP_VALUES, false); - mapper.setSerializationInclusion(Include.NON_NULL); - - final MyDto dtoObject1 = new MyDto(); - - final Map dtoMap = new HashMap(); - dtoMap.put("dtoObject1", dtoObject1); - dtoMap.put("dtoObject2", null); - - final String dtoMapAsString = mapper.writeValueAsString(dtoMap); - - assertThat(dtoMapAsString, containsString("dtoObject1")); - assertThat(dtoMapAsString, not(containsString("dtoObject2"))); - System.out.println(dtoMapAsString); - } - - @Test - public final void givenIgnoringMapValueObjectWithNullField_whenWritingMapValueObjectWithNullField_thenIgnored() throws JsonProcessingException { - final ObjectMapper mapper = new ObjectMapper(); - mapper.setSerializationInclusion(Include.NON_NULL); - - final MyDto dtoObject = new MyDto(); - - final Map dtoMap = new HashMap(); - dtoMap.put("dtoObject", dtoObject); - - final String dtoMapAsString = mapper.writeValueAsString(dtoMap); - - assertThat(dtoMapAsString, containsString("dtoObject")); - assertThat(dtoMapAsString, not(containsString("stringValue"))); - System.out.println(dtoMapAsString); - } - - @Test - public final void givenAllowingMapObjectWithNullKey_whenWriting_thenCorrect() throws JsonProcessingException { - final ObjectMapper mapper = new ObjectMapper(); - mapper.getSerializerProvider() - .setNullKeySerializer(new MyDtoNullKeySerializer()); - - final MyDto dtoObject1 = new MyDto(); - dtoObject1.setStringValue("dtoObjectString1"); - final MyDto dtoObject2 = new MyDto(); - dtoObject2.setStringValue("dtoObjectString2"); - - final Map dtoMap = new HashMap(); - dtoMap.put(null, dtoObject1); - dtoMap.put("obj2", dtoObject2); - - final String dtoMapAsString = mapper.writeValueAsString(dtoMap); - - System.out.println(dtoMapAsString); - assertThat(dtoMapAsString, containsString("\"\"")); - assertThat(dtoMapAsString, containsString("dtoObjectString1")); - assertThat(dtoMapAsString, containsString("obj2")); - } - - @Test - public final void givenAllowingMapObjectOneNullKey_whenWritingMapObjectWithTwoNullKeys_thenOverride() throws JsonProcessingException { - final ObjectMapper mapper = new ObjectMapper(); - mapper.getSerializerProvider() - .setNullKeySerializer(new MyDtoNullKeySerializer()); - - final MyDto dtoObject1 = new MyDto(); - dtoObject1.setStringValue("dtoObject1String"); - - final MyDto dtoObject2 = new MyDto(); - dtoObject2.setStringValue("dtoObject2String"); - - final Map dtoMap = new HashMap(); - dtoMap.put(null, dtoObject1); - dtoMap.put(null, dtoObject2); - - final String dtoMapAsString = mapper.writeValueAsString(dtoMap); - - assertThat(dtoMapAsString, not(containsString("dtoObject1String"))); - assertThat(dtoMapAsString, containsString("dtoObject2String")); - System.out.println(dtoMapAsString); - } - -} diff --git a/jackson-modules/jackson-conversions/src/test/java/com/ossez/jackson/nested/DeserializeWithNestedPropertiesUnitTest.java b/jackson-modules/jackson-conversions/src/test/java/com/ossez/jackson/nested/DeserializeWithNestedPropertiesUnitTest.java deleted file mode 100644 index e6b6e0b8d7..0000000000 --- a/jackson-modules/jackson-conversions/src/test/java/com/ossez/jackson/nested/DeserializeWithNestedPropertiesUnitTest.java +++ /dev/null @@ -1,70 +0,0 @@ -package com.ossez.jackson.nested; - -import static org.junit.Assert.*; - -import java.io.IOException; - -import org.junit.Test; - -import com.fasterxml.jackson.databind.JsonNode; -import com.fasterxml.jackson.databind.ObjectMapper; -import com.fasterxml.jackson.databind.module.SimpleModule; - -public class DeserializeWithNestedPropertiesUnitTest { - - private String SOURCE_JSON = "{\"id\":\"957c43f2-fa2e-42f9-bf75-6e3d5bb6960a\",\"name\":\"The Best Product\",\"brand\":{\"id\":\"9bcd817d-0141-42e6-8f04-e5aaab0980b6\",\"name\":\"ACME Products\",\"owner\":{\"id\":\"b21a80b1-0c09-4be3-9ebd-ea3653511c13\",\"name\":\"Ultimate Corp, Inc.\"}}}"; - - @Test - public void whenUsingAnnotations_thenOk() throws IOException { - Product product = new ObjectMapper().readerFor(Product.class) - .readValue(SOURCE_JSON); - - assertEquals(product.getName(), "The Best Product"); - assertEquals(product.getBrandName(), "ACME Products"); - assertEquals(product.getOwnerName(), "Ultimate Corp, Inc."); - } - - @Test - public void whenUsingJsonNode_thenOk() throws IOException { - JsonNode productNode = new ObjectMapper().readTree(SOURCE_JSON); - - Product product = new Product(); - product.setId(productNode.get("id") - .textValue()); - product.setName(productNode.get("name") - .textValue()); - product.setBrandName(productNode.get("brand") - .get("name") - .textValue()); - product.setOwnerName(productNode.get("brand") - .get("owner") - .get("name") - .textValue()); - - assertEquals(product.getName(), "The Best Product"); - assertEquals(product.getBrandName(), "ACME Products"); - assertEquals(product.getOwnerName(), "Ultimate Corp, Inc."); - } - - @Test - public void whenUsingDeserializerManuallyRegistered_thenOk() throws IOException { - ObjectMapper mapper = new ObjectMapper(); - SimpleModule module = new SimpleModule(); - module.addDeserializer(Product.class, new ProductDeserializer()); - mapper.registerModule(module); - - Product product = mapper.readValue(SOURCE_JSON, Product.class); - assertEquals(product.getName(), "The Best Product"); - assertEquals(product.getBrandName(), "ACME Products"); - assertEquals(product.getOwnerName(), "Ultimate Corp, Inc."); - } - - @Test - public void whenUsingDeserializerAutoRegistered_thenOk() throws IOException { - ObjectMapper mapper = new ObjectMapper(); - Product product = mapper.readValue(SOURCE_JSON, Product.class); - assertEquals(product.getName(), "The Best Product"); - assertEquals(product.getBrandName(), "ACME Products"); - assertEquals(product.getOwnerName(), "Ultimate Corp, Inc."); - } -} diff --git a/jackson-modules/jackson-conversions/src/test/java/com/ossez/jackson/nested/Product.java b/jackson-modules/jackson-conversions/src/test/java/com/ossez/jackson/nested/Product.java deleted file mode 100644 index 07c21e71ba..0000000000 --- a/jackson-modules/jackson-conversions/src/test/java/com/ossez/jackson/nested/Product.java +++ /dev/null @@ -1,55 +0,0 @@ -package com.ossez.jackson.nested; - -import java.util.Map; - -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.databind.annotation.JsonDeserialize; - -@JsonDeserialize(using = ProductDeserializer.class) -public class Product { - - private String id; - private String name; - private String brandName; - private String ownerName; - - public String getId() { - return id; - } - - public void setId(String id) { - this.id = id; - } - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public String getBrandName() { - return brandName; - } - - public void setBrandName(String brandName) { - this.brandName = brandName; - } - - public String getOwnerName() { - return ownerName; - } - - public void setOwnerName(String ownerName) { - this.ownerName = ownerName; - } - - @SuppressWarnings("unchecked") - @JsonProperty("brand") - private void unpackNested(Map brand) { - this.brandName = (String) brand.get("name"); - Map owner = (Map) brand.get("owner"); - this.ownerName = owner.get("name"); - } -} \ No newline at end of file diff --git a/jackson-modules/jackson-conversions/src/test/java/com/ossez/jackson/nested/ProductDeserializer.java b/jackson-modules/jackson-conversions/src/test/java/com/ossez/jackson/nested/ProductDeserializer.java deleted file mode 100644 index e25c254d47..0000000000 --- a/jackson-modules/jackson-conversions/src/test/java/com/ossez/jackson/nested/ProductDeserializer.java +++ /dev/null @@ -1,40 +0,0 @@ -package com.ossez.jackson.nested; - -import java.io.IOException; - -import com.fasterxml.jackson.core.JsonParser; -import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.databind.DeserializationContext; -import com.fasterxml.jackson.databind.JsonNode; -import com.fasterxml.jackson.databind.deser.std.StdDeserializer; - -@SuppressWarnings("serial") -public class ProductDeserializer extends StdDeserializer { - - public ProductDeserializer() { - this(null); - } - - public ProductDeserializer(Class vc) { - super(vc); - } - - @Override - public Product deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException { - JsonNode productNode = jp.getCodec() - .readTree(jp); - Product product = new Product(); - product.setId(productNode.get("id") - .textValue()); - product.setName(productNode.get("name") - .textValue()); - product.setBrandName(productNode.get("brand") - .get("name") - .textValue()); - product.setOwnerName(productNode.get("brand") - .get("owner") - .get("name") - .textValue()); - return product; - } -} diff --git a/jackson-modules/jackson-conversions/src/test/java/com/ossez/jackson/tocollection/JacksonCollectionDeserializationUnitTest.java b/jackson-modules/jackson-conversions/src/test/java/com/ossez/jackson/tocollection/JacksonCollectionDeserializationUnitTest.java deleted file mode 100644 index f0f22b4533..0000000000 --- a/jackson-modules/jackson-conversions/src/test/java/com/ossez/jackson/tocollection/JacksonCollectionDeserializationUnitTest.java +++ /dev/null @@ -1,75 +0,0 @@ -package com.ossez.jackson.tocollection; - -import static org.hamcrest.Matchers.instanceOf; -import static org.junit.Assert.assertThat; - -import java.io.IOException; -import java.util.LinkedHashMap; -import java.util.List; -import org.junit.Test; - -import com.fasterxml.jackson.core.JsonParseException; -import com.fasterxml.jackson.core.type.TypeReference; -import com.fasterxml.jackson.databind.JsonMappingException; -import com.fasterxml.jackson.databind.ObjectMapper; -import com.fasterxml.jackson.databind.type.CollectionType; -import com.google.common.collect.Lists; - -public class JacksonCollectionDeserializationUnitTest { - - // tests - json to multiple entity - - @Test - public final void givenJsonArray_whenDeserializingAsArray_thenCorrect() throws JsonParseException, JsonMappingException, IOException { - final ObjectMapper mapper = new ObjectMapper(); - - final List listOfDtos = Lists.newArrayList(new MyDto("a", 1, true), new MyDto("bc", 3, false)); - listOfDtos - final String jsonArray = mapper.writeValueAsString(listOfDtos); - // [{"stringValue":"a","intValue":1,"booleanValue":true},{"stringValue":"bc","intValue":3,"booleanValue":false}] - - final MyDto[] asArray = mapper.readValue(jsonArray, MyDto[].class); - assertThat(asArray[0], instanceOf(MyDto.class)); - } - - @Test - public final void givenJsonArray_whenDeserializingAsListWithNoTypeInfo_thenNotCorrect() throws JsonParseException, JsonMappingException, IOException { - final ObjectMapper mapper = new ObjectMapper(); - - final List listOfDtos = Lists.newArrayList(new MyDto("a", 1, true), new MyDto("bc", 3, false)); - final String jsonArray = mapper.writeValueAsString(listOfDtos); - // [{"stringValue":"a","intValue":1,"booleanValue":true},{"stringValue":"bc","intValue":3,"booleanValue":false}] - - final List asList = mapper.readValue(jsonArray, List.class); - assertThat((Object) asList.get(0), instanceOf(LinkedHashMap.class)); - } - - @Test - public final void givenJsonArray_whenDeserializingAsListWithTypeReferenceHelp_thenCorrect() throws JsonParseException, JsonMappingException, IOException { - final ObjectMapper mapper = new ObjectMapper(); - - final List listOfDtos = Lists.newArrayList(new MyDto("a", 1, true), new MyDto("bc", 3, false)); - final String jsonArray = mapper.writeValueAsString(listOfDtos); - // [{"stringValue":"a","intValue":1,"booleanValue":true},{"stringValue":"bc","intValue":3,"booleanValue":false}] - - final List asList = mapper.readValue(jsonArray, new TypeReference>() { - }); - assertThat(asList.get(0), instanceOf(MyDto.class)); - } - - @Test - public final void givenJsonArray_whenDeserializingAsListWithJavaTypeHelp_thenCorrect() throws JsonParseException, JsonMappingException, IOException { - final ObjectMapper mapper = new ObjectMapper(); - - final List listOfDtos = Lists.newArrayList(new MyDto("a", 1, true), new MyDto("bc", 3, false)); - final String jsonArray = mapper.writeValueAsString(listOfDtos); - // [{"stringValue":"a","intValue":1,"booleanValue":true},{"stringValue":"bc","intValue":3,"booleanValue":false}] - - final CollectionType javaType = mapper.getTypeFactory() - .constructCollectionType(List.class, MyDto.class); - final List asList = mapper.readValue(jsonArray, javaType); - assertThat(asList.get(0), instanceOf(MyDto.class)); - } - -} -// a (private) no-args constructor is required (simulate without) diff --git a/jackson-modules/jackson-conversions/src/test/java/com/ossez/jackson/tojsonnode/StringToJsonNodeUnitTest.java b/jackson-modules/jackson-conversions/src/test/java/com/ossez/jackson/tojsonnode/StringToJsonNodeUnitTest.java deleted file mode 100644 index 9cc438c259..0000000000 --- a/jackson-modules/jackson-conversions/src/test/java/com/ossez/jackson/tojsonnode/StringToJsonNodeUnitTest.java +++ /dev/null @@ -1,51 +0,0 @@ -package com.ossez.jackson.tojsonnode; - -import com.fasterxml.jackson.core.JsonFactory; -import com.fasterxml.jackson.core.JsonParseException; -import com.fasterxml.jackson.core.JsonParser; -import org.junit.Test; - -import java.io.IOException; - -import static org.hamcrest.Matchers.equalTo; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertThat; -import com.fasterxml.jackson.databind.JsonNode; -import com.fasterxml.jackson.databind.ObjectMapper; - -public class StringToJsonNodeUnitTest { - - @Test - public final void whenParsingJsonStringIntoJsonNode_thenCorrect() throws JsonParseException, IOException { - final String jsonString = "{\"k1\":\"v1\",\"k2\":\"v2\"}"; - - final ObjectMapper mapper = new ObjectMapper(); - final JsonNode actualObj = mapper.readTree(jsonString); - - assertNotNull(actualObj); - } - - @Test - public final void givenUsingLowLevelDetails_whenParsingJsonStringIntoJsonNode_thenCorrect() throws JsonParseException, IOException { - final String jsonString = "{\"k1\":\"v1\",\"k2\":\"v2\"}"; - - final ObjectMapper mapper = new ObjectMapper(); - final JsonFactory factory = mapper.getFactory(); - final JsonParser parser = factory.createParser(jsonString); - final JsonNode actualObj = mapper.readTree(parser); - - assertNotNull(actualObj); - } - - @Test - public final void givenTheJsonNode_whenRetrievingDataFromId_thenCorrect() throws JsonParseException, IOException { - final String jsonString = "{\"k1\":\"v1\",\"k2\":\"v2\"}"; - final ObjectMapper mapper = new ObjectMapper(); - final JsonNode actualObj = mapper.readTree(jsonString); - - // When - final JsonNode jsonNode1 = actualObj.get("k1"); - assertThat(jsonNode1.textValue(), equalTo("v1")); - } - -} diff --git a/jackson-modules/jackson-conversions/src/test/java/com/ossez/jackson/xml/XMLSerializeDeserializeUnitTest.java b/jackson-modules/jackson-conversions/src/test/java/com/ossez/jackson/xml/XMLSerializeDeserializeUnitTest.java deleted file mode 100644 index e4d879a319..0000000000 --- a/jackson-modules/jackson-conversions/src/test/java/com/ossez/jackson/xml/XMLSerializeDeserializeUnitTest.java +++ /dev/null @@ -1,182 +0,0 @@ -package com.ossez.jackson.xml; - -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; -import static org.junit.jupiter.api.Assertions.assertEquals; - -import java.io.BufferedReader; -import java.io.ByteArrayOutputStream; -import java.io.File; -import java.io.FileInputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.util.ArrayList; -import java.util.List; - -import org.junit.Test; - -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.dataformat.xml.XmlMapper; - -public class XMLSerializeDeserializeUnitTest { - - @Test - public void whenJavaSerializedToXmlStr_thenCorrect() throws JsonProcessingException { - XmlMapper xmlMapper = new XmlMapper(); - String xml = xmlMapper.writeValueAsString(new SimpleBean()); - assertNotNull(xml); - } - - @Test - public void whenJavaSerializedToXmlFile_thenCorrect() throws IOException { - XmlMapper xmlMapper = new XmlMapper(); - xmlMapper.writeValue(new File("target/simple_bean.xml"), new SimpleBean()); - File file = new File("target/simple_bean.xml"); - assertNotNull(file); - } - - @Test - public void whenJavaGotFromXmlStr_thenCorrect() throws IOException { - XmlMapper xmlMapper = new XmlMapper(); - SimpleBean value = xmlMapper.readValue("12", SimpleBean.class); - assertTrue(value.getX() == 1 && value.getY() == 2); - } - - @Test - public void whenJavaGotFromXmlFile_thenCorrect() throws IOException { - File file = new File("src/test/resources/simple_bean.xml"); - XmlMapper xmlMapper = new XmlMapper(); - String xml = inputStreamToString(new FileInputStream(file)); - SimpleBean value = xmlMapper.readValue(xml, SimpleBean.class); - assertTrue(value.getX() == 1 && value.getY() == 2); - } - - @Test - public void whenJavaGotFromXmlStrWithCapitalElem_thenCorrect() throws IOException { - XmlMapper xmlMapper = new XmlMapper(); - SimpleBeanForCapitalizedFields value = xmlMapper.readValue("12", SimpleBeanForCapitalizedFields.class); - assertTrue(value.getX() == 1 && value.getY() == 2); - } - - @Test - public void whenJavaSerializedToXmlFileWithCapitalizedField_thenCorrect() throws IOException { - XmlMapper xmlMapper = new XmlMapper(); - xmlMapper.writeValue(new File("target/simple_bean_capitalized.xml"), new SimpleBeanForCapitalizedFields()); - File file = new File("target/simple_bean_capitalized.xml"); - assertNotNull(file); - } - - @Test - public void whenJavaDeserializedFromXmlFile_thenCorrect() throws IOException { - XmlMapper xmlMapper = new XmlMapper(); - - String xml = "RohanDaye99110347319911033478
1Name1City1
2Name2City2
"; - Person value = xmlMapper.readValue(xml, Person.class); - - assertTrue(value.getAddress() - .get(0) - .getCity() - .equalsIgnoreCase("city1") - && value.getAddress() - .get(1) - .getCity() - .equalsIgnoreCase("city2")); - } - - @Test - public void whenJavaSerializedToXmlFile_thenSuccess() throws IOException { - XmlMapper xmlMapper = new XmlMapper(); - - String expectedXml = "RohanDaye99110347319911033478
1Name1City1
2Name2City2
"; - - Person person = new Person(); - - person.setFirstName("Rohan"); - person.setLastName("Daye"); - - List ph = new ArrayList<>(); - ph.add("9911034731"); - ph.add("9911033478"); - person.setPhoneNumbers(ph); - - List
addresses = new ArrayList<>(); - - Address address1 = new Address(); - address1.setStreetNumber("1"); - address1.setStreetName("Name1"); - address1.setCity("City1"); - - Address address2 = new Address(); - address2.setStreetNumber("2"); - address2.setStreetName("Name2"); - address2.setCity("City2"); - - addresses.add(address1); - addresses.add(address2); - - person.setAddress(addresses); - - ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); - xmlMapper.writeValue(byteArrayOutputStream, person); - assertEquals(expectedXml, byteArrayOutputStream.toString()); - } - - private static String inputStreamToString(InputStream is) throws IOException { - BufferedReader br; - StringBuilder sb = new StringBuilder(); - - String line; - br = new BufferedReader(new InputStreamReader(is)); - while ((line = br.readLine()) != null) { - sb.append(line); - } - br.close(); - return sb.toString(); - } -} - -class SimpleBean { - private int x = 1; - private int y = 2; - - public int getX() { - return x; - } - - public void setX(int x) { - this.x = x; - } - - public int getY() { - return y; - } - - public void setY(int y) { - this.y = y; - } - -} - -class SimpleBeanForCapitalizedFields { - @JsonProperty("X") - private int x = 1; - private int y = 2; - - public int getX() { - return x; - } - - public void setX(int x) { - this.x = x; - } - - public int getY() { - return y; - } - - public void setY(int y) { - this.y = y; - } -} \ No newline at end of file diff --git a/jackson-modules/jackson-conversions/src/test/resources/simple_bean.xml b/jackson-modules/jackson-conversions/src/test/resources/simple_bean.xml deleted file mode 100644 index 7829ea35a4..0000000000 --- a/jackson-modules/jackson-conversions/src/test/resources/simple_bean.xml +++ /dev/null @@ -1,4 +0,0 @@ - - 1 - 2 - \ No newline at end of file diff --git a/jackson-modules/jackson-custom-conversions/README.md b/jackson-modules/jackson-custom-conversions/README.md deleted file mode 100644 index 68e9a6d50d..0000000000 --- a/jackson-modules/jackson-custom-conversions/README.md +++ /dev/null @@ -1,9 +0,0 @@ -## Jackson Custom Conversions - -This module contains articles about Jackson custom conversions. - -### Relevant Articles: -- [Jackson – Custom Serializer](https://www.baeldung.com/jackson-custom-serialization) -- [Getting Started with Custom Deserialization in Jackson](https://www.baeldung.com/jackson-deserialization) -- [Serialize Only Fields that meet a Custom Criteria with Jackson](https://www.baeldung.com/jackson-serialize-field-custom-criteria) -- [Calling Default Serializer from Custom Serializer in Jackson](https://www.baeldung.com/jackson-call-default-serializer-from-custom-serializer) diff --git a/jackson-modules/jackson-custom-conversions/pom.xml b/jackson-modules/jackson-custom-conversions/pom.xml deleted file mode 100644 index 8772558bf3..0000000000 --- a/jackson-modules/jackson-custom-conversions/pom.xml +++ /dev/null @@ -1,44 +0,0 @@ - - - 4.0.0 - jackson-custom-conversions - 0.0.1-SNAPSHOT - jackson-custom-conversions - - - com.ossez - jackson-modules - 0.0.2-SNAPSHOT - - - - - com.fasterxml.jackson.datatype - jackson-datatype-jsr310 - ${jackson.version} - - - com.fasterxml.jackson.datatype - jackson-datatype-joda - ${jackson.version} - - - com.fasterxml.jackson.core - jackson-core - ${jackson.version} - - - - - jackson-custom-conversions - - - src/main/resources - true - - - - - \ No newline at end of file diff --git a/jackson-modules/jackson-custom-conversions/src/main/java/com/baeldung/defaultserializercustomserializer/File.java b/jackson-modules/jackson-custom-conversions/src/main/java/com/baeldung/defaultserializercustomserializer/File.java deleted file mode 100644 index 791ad3a466..0000000000 --- a/jackson-modules/jackson-custom-conversions/src/main/java/com/baeldung/defaultserializercustomserializer/File.java +++ /dev/null @@ -1,25 +0,0 @@ -package com.baeldung.defaultserializercustomserializer; - -public class File { - - private Long id; - - private String name; - - public Long getId() { - return id; - } - - public void setId(Long id) { - this.id = id; - } - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - -} \ No newline at end of file diff --git a/jackson-modules/jackson-custom-conversions/src/main/java/com/baeldung/defaultserializercustomserializer/Folder.java b/jackson-modules/jackson-custom-conversions/src/main/java/com/baeldung/defaultserializercustomserializer/Folder.java deleted file mode 100644 index 6f423059a2..0000000000 --- a/jackson-modules/jackson-custom-conversions/src/main/java/com/baeldung/defaultserializercustomserializer/Folder.java +++ /dev/null @@ -1,82 +0,0 @@ -package com.baeldung.defaultserializercustomserializer; - -import java.util.ArrayList; -import java.util.Date; -import java.util.List; - -import com.fasterxml.jackson.annotation.JsonIgnore; - -public class Folder { - - private Long id; - - private String name; - - private String owner; - - private Date created; - - private Date modified; - - private Date lastAccess; - - @JsonIgnore - private List files = new ArrayList<>(); - - public Long getId() { - return id; - } - - public void setId(Long id) { - this.id = id; - } - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public String getOwner() { - return owner; - } - - public void setOwner(String owner) { - this.owner = owner; - } - - public Date getCreated() { - return created; - } - - public void setCreated(Date created) { - this.created = created; - } - - public Date getModified() { - return modified; - } - - public void setModified(Date modified) { - this.modified = modified; - } - - public Date getLastAccess() { - return lastAccess; - } - - public void setLastAccess(Date lastAccess) { - this.lastAccess = lastAccess; - } - - public List getFiles() { - return files; - } - - public void setFiles(List files) { - this.files = files; - } - -} \ No newline at end of file diff --git a/jackson-modules/jackson-custom-conversions/src/main/java/com/baeldung/defaultserializercustomserializer/FolderBeanSerializerModifier.java b/jackson-modules/jackson-custom-conversions/src/main/java/com/baeldung/defaultserializercustomserializer/FolderBeanSerializerModifier.java deleted file mode 100644 index 819971939c..0000000000 --- a/jackson-modules/jackson-custom-conversions/src/main/java/com/baeldung/defaultserializercustomserializer/FolderBeanSerializerModifier.java +++ /dev/null @@ -1,20 +0,0 @@ -package com.baeldung.defaultserializercustomserializer; - -import com.fasterxml.jackson.databind.BeanDescription; -import com.fasterxml.jackson.databind.JsonSerializer; -import com.fasterxml.jackson.databind.SerializationConfig; -import com.fasterxml.jackson.databind.ser.BeanSerializerModifier; - -public class FolderBeanSerializerModifier extends BeanSerializerModifier { - - @Override - public JsonSerializer modifySerializer(SerializationConfig config, BeanDescription beanDesc, JsonSerializer serializer) { - - if (beanDesc.getBeanClass().equals(Folder.class)) { - return new FolderSerializerWithDefaultSerializerStored((JsonSerializer) serializer); - } - - return serializer; - } - -} diff --git a/jackson-modules/jackson-custom-conversions/src/main/java/com/baeldung/defaultserializercustomserializer/FolderSerializer.java b/jackson-modules/jackson-custom-conversions/src/main/java/com/baeldung/defaultserializercustomserializer/FolderSerializer.java deleted file mode 100644 index 3869ab15d8..0000000000 --- a/jackson-modules/jackson-custom-conversions/src/main/java/com/baeldung/defaultserializercustomserializer/FolderSerializer.java +++ /dev/null @@ -1,34 +0,0 @@ -package com.baeldung.defaultserializercustomserializer; - -import java.io.IOException; - -import com.fasterxml.jackson.core.JsonGenerator; -import com.fasterxml.jackson.databind.SerializerProvider; -import com.fasterxml.jackson.databind.ser.std.StdSerializer; - -public class FolderSerializer extends StdSerializer { - - public FolderSerializer() { - super(Folder.class); - } - - @Override - public void serialize(Folder value, JsonGenerator gen, SerializerProvider provider) throws IOException { - - gen.writeStartObject(); - gen.writeStringField("name", value.getName()); - - gen.writeArrayFieldStart("files"); - for (File file : value.getFiles()) { - gen.writeStartObject(); - gen.writeNumberField("id", file.getId()); - gen.writeStringField("name", file.getName()); - gen.writeEndObject(); - } - gen.writeEndArray(); - - gen.writeEndObject(); - - } - -} diff --git a/jackson-modules/jackson-custom-conversions/src/main/java/com/baeldung/defaultserializercustomserializer/FolderSerializerWithCallingOwnSerializer.java b/jackson-modules/jackson-custom-conversions/src/main/java/com/baeldung/defaultserializercustomserializer/FolderSerializerWithCallingOwnSerializer.java deleted file mode 100644 index 544a4c6d1a..0000000000 --- a/jackson-modules/jackson-custom-conversions/src/main/java/com/baeldung/defaultserializercustomserializer/FolderSerializerWithCallingOwnSerializer.java +++ /dev/null @@ -1,29 +0,0 @@ -package com.baeldung.defaultserializercustomserializer; - -import java.io.IOException; - -import com.fasterxml.jackson.core.JsonGenerator; -import com.fasterxml.jackson.databind.SerializerProvider; -import com.fasterxml.jackson.databind.ser.std.StdSerializer; - -public class FolderSerializerWithCallingOwnSerializer extends StdSerializer { - - public FolderSerializerWithCallingOwnSerializer() { - super(Folder.class); - } - - @Override - public void serialize(Folder value, JsonGenerator gen, SerializerProvider provider) throws IOException { - - gen.writeStartObject(); - gen.writeStringField("name", value.getName()); - - provider.defaultSerializeField("files", value.getFiles(), gen); - - provider.defaultSerializeField("details", value, gen); - - gen.writeEndObject(); - - } - -} diff --git a/jackson-modules/jackson-custom-conversions/src/main/java/com/baeldung/defaultserializercustomserializer/FolderSerializerWithDefaultSerializerStored.java b/jackson-modules/jackson-custom-conversions/src/main/java/com/baeldung/defaultserializercustomserializer/FolderSerializerWithDefaultSerializerStored.java deleted file mode 100644 index 558b303301..0000000000 --- a/jackson-modules/jackson-custom-conversions/src/main/java/com/baeldung/defaultserializercustomserializer/FolderSerializerWithDefaultSerializerStored.java +++ /dev/null @@ -1,34 +0,0 @@ -package com.baeldung.defaultserializercustomserializer; - -import java.io.IOException; - -import com.fasterxml.jackson.core.JsonGenerator; -import com.fasterxml.jackson.databind.JsonSerializer; -import com.fasterxml.jackson.databind.SerializerProvider; -import com.fasterxml.jackson.databind.ser.std.StdSerializer; - -public class FolderSerializerWithDefaultSerializerStored extends StdSerializer { - - private final JsonSerializer defaultSerializer; - - public FolderSerializerWithDefaultSerializerStored(JsonSerializer defaultSerializer) { - super(Folder.class); - this.defaultSerializer = defaultSerializer; - } - - @Override - public void serialize(Folder value, JsonGenerator gen, SerializerProvider provider) throws IOException { - - gen.writeStartObject(); - gen.writeStringField("name", value.getName()); - - provider.defaultSerializeField("files", value.getFiles(), gen); - - gen.writeFieldName("details"); - defaultSerializer.serialize(value, gen, provider); - - gen.writeEndObject(); - - } - -} diff --git a/jackson-modules/jackson-custom-conversions/src/main/java/com/baeldung/defaultserializercustomserializer/FolderSerializerWithInternalObjectMapper.java b/jackson-modules/jackson-custom-conversions/src/main/java/com/baeldung/defaultserializercustomserializer/FolderSerializerWithInternalObjectMapper.java deleted file mode 100644 index 1ad51c63c0..0000000000 --- a/jackson-modules/jackson-custom-conversions/src/main/java/com/baeldung/defaultserializercustomserializer/FolderSerializerWithInternalObjectMapper.java +++ /dev/null @@ -1,33 +0,0 @@ -package com.baeldung.defaultserializercustomserializer; - -import java.io.IOException; - -import com.fasterxml.jackson.core.JsonGenerator; -import com.fasterxml.jackson.databind.ObjectMapper; -import com.fasterxml.jackson.databind.SerializerProvider; -import com.fasterxml.jackson.databind.ser.std.StdSerializer; - -public class FolderSerializerWithInternalObjectMapper extends StdSerializer { - - public FolderSerializerWithInternalObjectMapper() { - super(Folder.class); - } - - @Override - public void serialize(Folder value, JsonGenerator gen, SerializerProvider provider) throws IOException { - - gen.writeStartObject(); - gen.writeStringField("name", value.getName()); - - // we access internal mapper to delegate the serialization of File list - ObjectMapper mapper = (ObjectMapper) gen.getCodec(); - - gen.writeFieldName("files"); - String stringValue = mapper.writeValueAsString(value.getFiles()); - gen.writeRawValue(stringValue); - - gen.writeEndObject(); - - } - -} diff --git a/jackson-modules/jackson-custom-conversions/src/main/java/com/baeldung/defaultserializercustomserializer/FolderSerializerWithSerializerProvider.java b/jackson-modules/jackson-custom-conversions/src/main/java/com/baeldung/defaultserializercustomserializer/FolderSerializerWithSerializerProvider.java deleted file mode 100644 index 8aeb28b3d0..0000000000 --- a/jackson-modules/jackson-custom-conversions/src/main/java/com/baeldung/defaultserializercustomserializer/FolderSerializerWithSerializerProvider.java +++ /dev/null @@ -1,28 +0,0 @@ -package com.baeldung.defaultserializercustomserializer; - -import java.io.IOException; - -import com.fasterxml.jackson.core.JsonGenerator; -import com.fasterxml.jackson.databind.SerializerProvider; -import com.fasterxml.jackson.databind.ser.std.StdSerializer; - -public class FolderSerializerWithSerializerProvider extends StdSerializer { - - public FolderSerializerWithSerializerProvider() { - super(Folder.class); - } - - @Override - public void serialize(Folder value, JsonGenerator gen, SerializerProvider provider) throws IOException { - - gen.writeStartObject(); - gen.writeStringField("name", value.getName()); - - // we delegate the File list serialization to its default serializer - provider.defaultSerializeField("files", value.getFiles(), gen); - - gen.writeEndObject(); - - } - -} \ No newline at end of file diff --git a/jackson-modules/jackson-custom-conversions/src/main/java/com/baeldung/deserialization/ActorJackson.java b/jackson-modules/jackson-custom-conversions/src/main/java/com/baeldung/deserialization/ActorJackson.java deleted file mode 100644 index 4bf3bc57f6..0000000000 --- a/jackson-modules/jackson-custom-conversions/src/main/java/com/baeldung/deserialization/ActorJackson.java +++ /dev/null @@ -1,61 +0,0 @@ -package com.baeldung.deserialization; - -import java.text.DateFormat; -import java.text.SimpleDateFormat; -import java.util.Date; -import java.util.List; -import java.util.Locale; -import java.util.TimeZone; - -public class ActorJackson { - - private String imdbId; - private Date dateOfBirth; - private List filmography; - - public ActorJackson() { - super(); - } - - public ActorJackson(String imdbId, Date dateOfBirth, List filmography) { - super(); - this.imdbId = imdbId; - this.dateOfBirth = dateOfBirth; - this.filmography = filmography; - } - - @Override - public String toString() { - return "ActorJackson [imdbId=" + imdbId + ", dateOfBirth=" + formatDateOfBirth() + ", filmography=" + filmography + "]"; - } - - public String getImdbId() { - return imdbId; - } - - public void setImdbId(String imdbId) { - this.imdbId = imdbId; - } - - public Date getDateOfBirth() { - return dateOfBirth; - } - - public void setDateOfBirth(Date dateOfBirth) { - this.dateOfBirth = dateOfBirth; - } - - public List getFilmography() { - return filmography; - } - - public void setFilmography(List filmography) { - this.filmography = filmography; - } - - private String formatDateOfBirth() { - final DateFormat formatter = new SimpleDateFormat("EEE MMM dd hh:mm:ss zzz yyyy", Locale.US); - formatter.setTimeZone(TimeZone.getTimeZone("GMT")); - return formatter.format(dateOfBirth); - } -} diff --git a/jackson-modules/jackson-custom-conversions/src/main/java/com/baeldung/deserialization/Item.java b/jackson-modules/jackson-custom-conversions/src/main/java/com/baeldung/deserialization/Item.java deleted file mode 100644 index e6234bb6e9..0000000000 --- a/jackson-modules/jackson-custom-conversions/src/main/java/com/baeldung/deserialization/Item.java +++ /dev/null @@ -1,32 +0,0 @@ -package com.baeldung.deserialization; - -public class Item { - public int id; - public String itemName; - public User owner; - - public Item() { - super(); - } - - public Item(final int id, final String itemName, final User owner) { - this.id = id; - this.itemName = itemName; - this.owner = owner; - } - - // API - - public int getId() { - return id; - } - - public String getItemName() { - return itemName; - } - - public User getOwner() { - return owner; - } - -} \ No newline at end of file diff --git a/jackson-modules/jackson-custom-conversions/src/main/java/com/baeldung/deserialization/ItemDeserializer.java b/jackson-modules/jackson-custom-conversions/src/main/java/com/baeldung/deserialization/ItemDeserializer.java deleted file mode 100644 index 7ae2faa04d..0000000000 --- a/jackson-modules/jackson-custom-conversions/src/main/java/com/baeldung/deserialization/ItemDeserializer.java +++ /dev/null @@ -1,39 +0,0 @@ -package com.baeldung.deserialization; - -import java.io.IOException; - -import com.fasterxml.jackson.core.JsonParser; -import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.databind.DeserializationContext; -import com.fasterxml.jackson.databind.JsonNode; -import com.fasterxml.jackson.databind.deser.std.StdDeserializer; -import com.fasterxml.jackson.databind.node.IntNode; - -public class ItemDeserializer extends StdDeserializer { - - private static final long serialVersionUID = 1883547683050039861L; - - public ItemDeserializer() { - this(null); - } - - public ItemDeserializer(final Class vc) { - super(vc); - } - - /** - * {"id":1,"itemNr":"theItem","owner":2} - */ - @Override - public Item deserialize(final JsonParser jp, final DeserializationContext ctxt) throws IOException, JsonProcessingException { - final JsonNode node = jp.getCodec() - .readTree(jp); - final int id = (Integer) ((IntNode) node.get("id")).numberValue(); - final String itemName = node.get("itemName") - .asText(); - final int userId = (Integer) ((IntNode) node.get("createdBy")).numberValue(); - - return new Item(id, itemName, new User(userId, null)); - } - -} \ No newline at end of file diff --git a/jackson-modules/jackson-custom-conversions/src/main/java/com/baeldung/deserialization/ItemDeserializerOnClass.java b/jackson-modules/jackson-custom-conversions/src/main/java/com/baeldung/deserialization/ItemDeserializerOnClass.java deleted file mode 100644 index b9db114c4a..0000000000 --- a/jackson-modules/jackson-custom-conversions/src/main/java/com/baeldung/deserialization/ItemDeserializerOnClass.java +++ /dev/null @@ -1,39 +0,0 @@ -package com.baeldung.deserialization; - -import java.io.IOException; - -import com.fasterxml.jackson.core.JsonParser; -import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.databind.DeserializationContext; -import com.fasterxml.jackson.databind.JsonNode; -import com.fasterxml.jackson.databind.deser.std.StdDeserializer; -import com.fasterxml.jackson.databind.node.IntNode; - -public class ItemDeserializerOnClass extends StdDeserializer { - - private static final long serialVersionUID = 5579141241817332594L; - - public ItemDeserializerOnClass() { - this(null); - } - - public ItemDeserializerOnClass(final Class vc) { - super(vc); - } - - /** - * {"id":1,"itemNr":"theItem","owner":2} - */ - @Override - public ItemWithDeserializer deserialize(final JsonParser jp, final DeserializationContext ctxt) throws IOException, JsonProcessingException { - final JsonNode node = jp.getCodec() - .readTree(jp); - final int id = (Integer) ((IntNode) node.get("id")).numberValue(); - final String itemName = node.get("itemName") - .asText(); - final int userId = (Integer) ((IntNode) node.get("owner")).numberValue(); - - return new ItemWithDeserializer(id, itemName, new User(userId, null)); - } - -} \ No newline at end of file diff --git a/jackson-modules/jackson-custom-conversions/src/main/java/com/baeldung/deserialization/ItemWithDeserializer.java b/jackson-modules/jackson-custom-conversions/src/main/java/com/baeldung/deserialization/ItemWithDeserializer.java deleted file mode 100644 index 1ab36e4acd..0000000000 --- a/jackson-modules/jackson-custom-conversions/src/main/java/com/baeldung/deserialization/ItemWithDeserializer.java +++ /dev/null @@ -1,31 +0,0 @@ -package com.baeldung.deserialization; - -import com.fasterxml.jackson.databind.annotation.JsonDeserialize; - -@JsonDeserialize(using = ItemDeserializerOnClass.class) -public class ItemWithDeserializer { - public final int id; - public final String itemName; - public final User owner; - - public ItemWithDeserializer(final int id, final String itemName, final User owner) { - this.id = id; - this.itemName = itemName; - this.owner = owner; - } - - // API - - public int getId() { - return id; - } - - public String getItemName() { - return itemName; - } - - public User getOwner() { - return owner; - } - -} \ No newline at end of file diff --git a/jackson-modules/jackson-custom-conversions/src/main/java/com/baeldung/deserialization/Movie.java b/jackson-modules/jackson-custom-conversions/src/main/java/com/baeldung/deserialization/Movie.java deleted file mode 100644 index fdb107dca2..0000000000 --- a/jackson-modules/jackson-custom-conversions/src/main/java/com/baeldung/deserialization/Movie.java +++ /dev/null @@ -1,50 +0,0 @@ -package com.baeldung.deserialization; - -import java.util.List; - -public class Movie { - - private String imdbId; - private String director; - private List actors; - - public Movie(String imdbId, String director, List actors) { - super(); - this.imdbId = imdbId; - this.director = director; - this.actors = actors; - } - - public Movie() { - super(); - } - - @Override - public String toString() { - return "Movie [imdbId=" + imdbId + ", director=" + director + ", actors=" + actors + "]"; - } - - public String getImdbId() { - return imdbId; - } - - public void setImdbId(String imdbId) { - this.imdbId = imdbId; - } - - public String getDirector() { - return director; - } - - public void setDirector(String director) { - this.director = director; - } - - public List getActors() { - return actors; - } - - public void setActors(List actors) { - this.actors = actors; - } -} \ No newline at end of file diff --git a/jackson-modules/jackson-custom-conversions/src/main/java/com/baeldung/deserialization/User.java b/jackson-modules/jackson-custom-conversions/src/main/java/com/baeldung/deserialization/User.java deleted file mode 100644 index d22a85aafd..0000000000 --- a/jackson-modules/jackson-custom-conversions/src/main/java/com/baeldung/deserialization/User.java +++ /dev/null @@ -1,26 +0,0 @@ -package com.baeldung.deserialization; - -public class User { - public int id; - public String name; - - public User() { - super(); - } - - public User(final int id, final String name) { - this.id = id; - this.name = name; - } - - // API - - public int getId() { - return id; - } - - public String getName() { - return name; - } - -} \ No newline at end of file diff --git a/jackson-modules/jackson-custom-conversions/src/main/java/com/baeldung/serialization/Item.java b/jackson-modules/jackson-custom-conversions/src/main/java/com/baeldung/serialization/Item.java deleted file mode 100644 index 52a73b048c..0000000000 --- a/jackson-modules/jackson-custom-conversions/src/main/java/com/baeldung/serialization/Item.java +++ /dev/null @@ -1,32 +0,0 @@ -package com.baeldung.serialization; - -public class Item { - public int id; - public String itemName; - public User owner; - - public Item() { - super(); - } - - public Item(final int id, final String itemName, final User owner) { - this.id = id; - this.itemName = itemName; - this.owner = owner; - } - - // API - - public int getId() { - return id; - } - - public String getItemName() { - return itemName; - } - - public User getOwner() { - return owner; - } - -} \ No newline at end of file diff --git a/jackson-modules/jackson-custom-conversions/src/main/java/com/baeldung/serialization/ItemSerializer.java b/jackson-modules/jackson-custom-conversions/src/main/java/com/baeldung/serialization/ItemSerializer.java deleted file mode 100644 index dc0b5e1c88..0000000000 --- a/jackson-modules/jackson-custom-conversions/src/main/java/com/baeldung/serialization/ItemSerializer.java +++ /dev/null @@ -1,31 +0,0 @@ -package com.baeldung.serialization; - -import java.io.IOException; - -import com.fasterxml.jackson.core.JsonGenerator; -import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.databind.SerializerProvider; -import com.fasterxml.jackson.databind.ser.std.StdSerializer; - -public class ItemSerializer extends StdSerializer { - - private static final long serialVersionUID = 6739170890621978901L; - - public ItemSerializer() { - this(null); - } - - public ItemSerializer(final Class t) { - super(t); - } - - @Override - public final void serialize(final Item value, final JsonGenerator jgen, final SerializerProvider provider) throws IOException, JsonProcessingException { - jgen.writeStartObject(); - jgen.writeNumberField("id", value.id); - jgen.writeStringField("itemName", value.itemName); - jgen.writeNumberField("owner", value.owner.id); - jgen.writeEndObject(); - } - -} \ No newline at end of file diff --git a/jackson-modules/jackson-custom-conversions/src/main/java/com/baeldung/serialization/ItemSerializerOnClass.java b/jackson-modules/jackson-custom-conversions/src/main/java/com/baeldung/serialization/ItemSerializerOnClass.java deleted file mode 100644 index 8f56c349f2..0000000000 --- a/jackson-modules/jackson-custom-conversions/src/main/java/com/baeldung/serialization/ItemSerializerOnClass.java +++ /dev/null @@ -1,31 +0,0 @@ -package com.baeldung.serialization; - -import java.io.IOException; - -import com.fasterxml.jackson.core.JsonGenerator; -import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.databind.SerializerProvider; -import com.fasterxml.jackson.databind.ser.std.StdSerializer; - -public class ItemSerializerOnClass extends StdSerializer { - - private static final long serialVersionUID = -1760959597313610409L; - - public ItemSerializerOnClass() { - this(null); - } - - public ItemSerializerOnClass(final Class t) { - super(t); - } - - @Override - public final void serialize(final ItemWithSerializer value, final JsonGenerator jgen, final SerializerProvider provider) throws IOException, JsonProcessingException { - jgen.writeStartObject(); - jgen.writeNumberField("id", value.id); - jgen.writeStringField("itemName", value.itemName); - jgen.writeNumberField("owner", value.owner.id); - jgen.writeEndObject(); - } - -} \ No newline at end of file diff --git a/jackson-modules/jackson-custom-conversions/src/main/java/com/baeldung/serialization/ItemWithSerializer.java b/jackson-modules/jackson-custom-conversions/src/main/java/com/baeldung/serialization/ItemWithSerializer.java deleted file mode 100644 index 5b38ad1af6..0000000000 --- a/jackson-modules/jackson-custom-conversions/src/main/java/com/baeldung/serialization/ItemWithSerializer.java +++ /dev/null @@ -1,32 +0,0 @@ -package com.baeldung.serialization; - -import com.fasterxml.jackson.databind.annotation.JsonDeserialize; -import com.fasterxml.jackson.databind.annotation.JsonSerialize; - -@JsonSerialize(using = ItemSerializerOnClass.class) -public class ItemWithSerializer { - public final int id; - public final String itemName; - public final User owner; - - public ItemWithSerializer(final int id, final String itemName, final User owner) { - this.id = id; - this.itemName = itemName; - this.owner = owner; - } - - // API - - public int getId() { - return id; - } - - public String getItemName() { - return itemName; - } - - public User getOwner() { - return owner; - } - -} \ No newline at end of file diff --git a/jackson-modules/jackson-custom-conversions/src/main/java/com/baeldung/serialization/User.java b/jackson-modules/jackson-custom-conversions/src/main/java/com/baeldung/serialization/User.java deleted file mode 100644 index b01ccc9ffb..0000000000 --- a/jackson-modules/jackson-custom-conversions/src/main/java/com/baeldung/serialization/User.java +++ /dev/null @@ -1,26 +0,0 @@ -package com.baeldung.serialization; - -public class User { - public int id; - public String name; - - public User() { - super(); - } - - public User(final int id, final String name) { - this.id = id; - this.name = name; - } - - // API - - public int getId() { - return id; - } - - public String getName() { - return name; - } - -} \ No newline at end of file diff --git a/jackson-modules/jackson-custom-conversions/src/main/java/com/baeldung/skipfields/Address.java b/jackson-modules/jackson-custom-conversions/src/main/java/com/baeldung/skipfields/Address.java deleted file mode 100644 index a394bbc180..0000000000 --- a/jackson-modules/jackson-custom-conversions/src/main/java/com/baeldung/skipfields/Address.java +++ /dev/null @@ -1,40 +0,0 @@ -package com.baeldung.skipfields; - -public class Address implements Hidable { - private String city; - private String country; - private boolean hidden; - - public Address(final String city, final String country, final boolean hidden) { - super(); - this.city = city; - this.country = country; - this.hidden = hidden; - } - - public String getCity() { - return city; - } - - public void setCity(final String city) { - this.city = city; - } - - public String getCountry() { - return country; - } - - public void setCountry(final String country) { - this.country = country; - } - - @Override - public boolean isHidden() { - return hidden; - } - - public void setHidden(final boolean hidden) { - this.hidden = hidden; - } - -} diff --git a/jackson-modules/jackson-custom-conversions/src/main/java/com/baeldung/skipfields/Hidable.java b/jackson-modules/jackson-custom-conversions/src/main/java/com/baeldung/skipfields/Hidable.java deleted file mode 100644 index fff7f81d1e..0000000000 --- a/jackson-modules/jackson-custom-conversions/src/main/java/com/baeldung/skipfields/Hidable.java +++ /dev/null @@ -1,8 +0,0 @@ -package com.baeldung.skipfields; - -import com.fasterxml.jackson.annotation.JsonIgnoreProperties; - -@JsonIgnoreProperties("hidden") -public interface Hidable { - boolean isHidden(); -} diff --git a/jackson-modules/jackson-custom-conversions/src/main/java/com/baeldung/skipfields/HidableSerializer.java b/jackson-modules/jackson-custom-conversions/src/main/java/com/baeldung/skipfields/HidableSerializer.java deleted file mode 100644 index 8b300444c0..0000000000 --- a/jackson-modules/jackson-custom-conversions/src/main/java/com/baeldung/skipfields/HidableSerializer.java +++ /dev/null @@ -1,29 +0,0 @@ -package com.baeldung.skipfields; - -import java.io.IOException; - -import com.fasterxml.jackson.core.JsonGenerator; -import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.databind.JsonSerializer; -import com.fasterxml.jackson.databind.SerializerProvider; - -public class HidableSerializer extends JsonSerializer { - - private JsonSerializer defaultSerializer; - - public HidableSerializer(final JsonSerializer serializer) { - defaultSerializer = serializer; - } - - @Override - public void serialize(final Hidable value, final JsonGenerator jgen, final SerializerProvider provider) throws IOException, JsonProcessingException { - if (value.isHidden()) - return; - defaultSerializer.serialize(value, jgen, provider); - } - - @Override - public boolean isEmpty(final SerializerProvider provider, final Hidable value) { - return (value == null || value.isHidden()); - } -} diff --git a/jackson-modules/jackson-custom-conversions/src/main/java/com/baeldung/skipfields/MyDtoWithFilter.java b/jackson-modules/jackson-custom-conversions/src/main/java/com/baeldung/skipfields/MyDtoWithFilter.java deleted file mode 100644 index 50492c337a..0000000000 --- a/jackson-modules/jackson-custom-conversions/src/main/java/com/baeldung/skipfields/MyDtoWithFilter.java +++ /dev/null @@ -1,50 +0,0 @@ -package com.baeldung.skipfields; - -import com.fasterxml.jackson.annotation.JsonFilter; - -@JsonFilter("myFilter") -public class MyDtoWithFilter { - - private String stringValue; - private int intValue; - private boolean booleanValue; - - public MyDtoWithFilter() { - super(); - } - - public MyDtoWithFilter(final String stringValue, final int intValue, final boolean booleanValue) { - super(); - - this.stringValue = stringValue; - this.intValue = intValue; - this.booleanValue = booleanValue; - } - - // API - - public String getStringValue() { - return stringValue; - } - - public void setStringValue(final String stringValue) { - this.stringValue = stringValue; - } - - public int getIntValue() { - return intValue; - } - - public void setIntValue(final int intValue) { - this.intValue = intValue; - } - - public boolean isBooleanValue() { - return booleanValue; - } - - public void setBooleanValue(final boolean booleanValue) { - this.booleanValue = booleanValue; - } - -} diff --git a/jackson-modules/jackson-custom-conversions/src/main/java/com/baeldung/skipfields/Person.java b/jackson-modules/jackson-custom-conversions/src/main/java/com/baeldung/skipfields/Person.java deleted file mode 100644 index e1501947d3..0000000000 --- a/jackson-modules/jackson-custom-conversions/src/main/java/com/baeldung/skipfields/Person.java +++ /dev/null @@ -1,40 +0,0 @@ -package com.baeldung.skipfields; - -public class Person implements Hidable { - private String name; - private Address address; - private boolean hidden; - - public Person(final String name, final Address address, final boolean hidden) { - super(); - this.name = name; - this.address = address; - this.hidden = hidden; - } - - public String getName() { - return name; - } - - public void setName(final String name) { - this.name = name; - } - - public Address getAddress() { - return address; - } - - public void setAddress(final Address address) { - this.address = address; - } - - @Override - public boolean isHidden() { - return hidden; - } - - public void setHidden(final boolean hidden) { - this.hidden = hidden; - } - -} diff --git a/jackson-modules/jackson-custom-conversions/src/test/java/com/baeldung/defaultserializercustomserializer/CallingDefaultSerializerUnitTest.java b/jackson-modules/jackson-custom-conversions/src/test/java/com/baeldung/defaultserializercustomserializer/CallingDefaultSerializerUnitTest.java deleted file mode 100644 index c8b4ec7e1a..0000000000 --- a/jackson-modules/jackson-custom-conversions/src/test/java/com/baeldung/defaultserializercustomserializer/CallingDefaultSerializerUnitTest.java +++ /dev/null @@ -1,164 +0,0 @@ -package com.baeldung.defaultserializercustomserializer; - -import static org.junit.Assert.assertTrue; -import static org.junit.jupiter.api.Assertions.assertEquals; - -import java.io.IOException; -import java.time.Instant; -import java.util.ArrayList; -import java.util.Date; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import org.junit.Before; -import org.junit.Test; - -import com.fasterxml.jackson.core.type.TypeReference; -import com.fasterxml.jackson.databind.ObjectMapper; -import com.fasterxml.jackson.databind.module.SimpleModule; - -public class CallingDefaultSerializerUnitTest { - - private ObjectMapper mapper; - private Folder mockFolder; - private TypeReference> mapType; - - @Before - public void setup() { - - mapType = new TypeReference>() { - }; - - mapper = new ObjectMapper(); - - mockFolder = new Folder(); - mockFolder.setId(1L); - mockFolder.setName("Root Folder"); - mockFolder.setOwner("root"); - mockFolder.setCreated(Date.from(Instant.now().minusSeconds(60))); - mockFolder.setModified(Date.from(Instant.now().minusSeconds(30))); - mockFolder.setLastAccess(Date.from(Instant.now())); - - File file1 = new File(); - file1.setId(1L); - file1.setName("File 1"); - - File file2 = new File(); - file2.setId(2L); - file2.setName("File 2"); - - List files = new ArrayList<>(); - files.add(file1); - files.add(file2); - mockFolder.setFiles(files); - - } - - @Test - public void givenFolder_whenSerialized_onlyNameAndFilesFieldsSerialized() throws IOException { - - SimpleModule module = new SimpleModule(); - module.addSerializer(new FolderSerializer()); - mapper.registerModule(module); - - String json = mapper.writeValueAsString(mockFolder); - - HashMap actual = mapper.readValue(json, mapType); - - assertTrue(actual.containsKey("name")); - assertTrue(actual.containsKey("files")); - assertEquals(mockFolder.getName(), actual.get("name")); - - List actualFiles = (List) actual.get("files"); - assertEquals(mockFolder.getFiles().size(), actualFiles.size()); - - } - - @Test - public void givenFolder_whenSerializedWithSerializerProvider_onlyNameAndFilesFieldsSerialized() throws IOException { - - SimpleModule module = new SimpleModule(); - module.addSerializer(new FolderSerializerWithSerializerProvider()); - mapper.registerModule(module); - - String json = mapper.writeValueAsString(mockFolder); - - HashMap actual = mapper.readValue(json, mapType); - - assertTrue(actual.containsKey("name")); - assertTrue(actual.containsKey("files")); - assertEquals(mockFolder.getName(), actual.get("name")); - - List actualFiles = (List) actual.get("files"); - assertEquals(mockFolder.getFiles().size(), actualFiles.size()); - - } - - @Test - public void givenFolder_whenSerializedWithInternalObjectMapper_onlyNameAndFilesFieldsSerialized() throws IOException { - - SimpleModule module = new SimpleModule(); - module.addSerializer(new FolderSerializerWithInternalObjectMapper()); - mapper.registerModule(module); - - String json = mapper.writeValueAsString(mockFolder); - - HashMap actual = mapper.readValue(json, mapType); - - assertTrue(actual.containsKey("name")); - assertTrue(actual.containsKey("files")); - assertEquals(mockFolder.getName(), actual.get("name")); - - List actualFiles = (List) actual.get("files"); - assertEquals(mockFolder.getFiles().size(), actualFiles.size()); - - } - - @Test(expected = StackOverflowError.class) - public void givenFolder_whenSerializedWithCallingOwnSerializer_exceptionOccured() throws IOException { - - SimpleModule module = new SimpleModule(); - module.addSerializer(new FolderSerializerWithCallingOwnSerializer()); - mapper.registerModule(module); - - mapper.writeValueAsString(mockFolder); - - } - - @Test - public void givenFolder_whenSerializedWithDefaultSerializerStored_NameAndFilesAndDetailsFieldsSerialized() throws IOException { - - SimpleModule module = new SimpleModule(); - module.setSerializerModifier(new FolderBeanSerializerModifier()); - mapper.registerModule(module); - - String json = mapper.writeValueAsString(mockFolder); - - HashMap actual = mapper.readValue(json, mapType); - - assertTrue(actual.containsKey("name")); - assertTrue(actual.containsKey("files")); - assertEquals(mockFolder.getName(), actual.get("name")); - - List actualFiles = (List) actual.get("files"); - assertEquals(mockFolder.getFiles().size(), actualFiles.size()); - - Map actualDetails = (Map) actual.get("details"); - assertTrue(actualDetails.containsKey("id")); - assertTrue(actualDetails.containsKey("name")); - assertTrue(actualDetails.containsKey("owner")); - assertTrue(actualDetails.containsKey("created")); - assertTrue(actualDetails.containsKey("modified")); - assertTrue(actualDetails.containsKey("lastAccess")); - - assertEquals(mockFolder.getId().longValue(), ((Number)actualDetails.get("id")).longValue()); - assertEquals(mockFolder.getName(), actualDetails.get("name")); - assertEquals(mockFolder.getOwner(), actualDetails.get("owner")); - assertEquals(mockFolder.getCreated(), new Date((long) actualDetails.get("created"))); - assertEquals(mockFolder.getModified(), new Date((long) actualDetails.get("modified"))); - assertEquals(mockFolder.getLastAccess(), new Date((long) actualDetails.get("lastAccess"))); - - } - -} diff --git a/jackson-modules/jackson-custom-conversions/src/test/java/com/baeldung/deserialization/CustomDeserializationUnitTest.java b/jackson-modules/jackson-custom-conversions/src/test/java/com/baeldung/deserialization/CustomDeserializationUnitTest.java deleted file mode 100644 index 17016149a2..0000000000 --- a/jackson-modules/jackson-custom-conversions/src/test/java/com/baeldung/deserialization/CustomDeserializationUnitTest.java +++ /dev/null @@ -1,81 +0,0 @@ -package com.baeldung.deserialization; - -import com.fasterxml.jackson.core.JsonParseException; -import com.fasterxml.jackson.databind.DeserializationFeature; -import com.fasterxml.jackson.databind.JsonMappingException; -import com.fasterxml.jackson.databind.ObjectMapper; -import com.fasterxml.jackson.databind.SerializationFeature; -import com.fasterxml.jackson.databind.module.SimpleModule; -import org.junit.Test; - -import java.io.IOException; -import java.time.ZoneId; -import java.time.ZonedDateTime; - -import static org.hamcrest.CoreMatchers.is; -import static org.hamcrest.CoreMatchers.not; -import static org.hamcrest.Matchers.equalTo; -import static org.hamcrest.Matchers.notNullValue; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertThat; - -public class CustomDeserializationUnitTest { - - @Test - public final void whenDeserializingTheStandardRepresentation_thenCorrect() throws JsonParseException, JsonMappingException, IOException { - final String json = "{\"id\":1,\"itemName\":\"theItem\",\"owner\":{\"id\":2,\"name\":\"theUser\"}}"; - - final Item readValue = new ObjectMapper().readValue(json, Item.class); - assertThat(readValue, notNullValue()); - } - - @Test - public final void whenDeserializingANonStandardRepresentation_thenCorrect() throws JsonParseException, JsonMappingException, IOException { - final String json = "{\"id\":1,\"itemName\":\"theItem\",\"createdBy\":2}"; - final ObjectMapper mapper = new ObjectMapper(); - - final SimpleModule module = new SimpleModule(); - module.addDeserializer(Item.class, new ItemDeserializer()); - mapper.registerModule(module); - - final Item readValue = mapper.readValue(json, Item.class); - assertThat(readValue, notNullValue()); - } - - @Test - public final void givenDeserializerIsOnClass_whenDeserializingCustomRepresentation_thenCorrect() throws JsonParseException, JsonMappingException, IOException { - final String json = "{\"id\":1,\"itemName\":\"theItem\",\"owner\":2}"; - - final ItemWithDeserializer readValue = new ObjectMapper().readValue(json, ItemWithDeserializer.class); - assertThat(readValue, notNullValue()); - } - - @Test - public void whenDeserialisingZonedDateTimeWithDefaults_thenTimeZoneIsNotPreserved() throws IOException { - ObjectMapper objectMapper = new ObjectMapper(); - objectMapper.findAndRegisterModules(); - objectMapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS); - // construct a new instance of ZonedDateTime - ZonedDateTime now = ZonedDateTime.now(ZoneId.of("Europe/Berlin")); - String converted = objectMapper.writeValueAsString(now); - // restore an instance of ZonedDateTime from String - ZonedDateTime restored = objectMapper.readValue(converted, ZonedDateTime.class); - assertThat(now, is(not(restored))); - } - - @Test - public void whenDeserialisingZonedDateTimeWithFeaturesDisabled_thenTimeZoneIsPreserved() throws IOException { - ObjectMapper objectMapper = new ObjectMapper(); - objectMapper.findAndRegisterModules(); - objectMapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS); - objectMapper.enable(SerializationFeature.WRITE_DATES_WITH_ZONE_ID); - objectMapper.disable(DeserializationFeature.ADJUST_DATES_TO_CONTEXT_TIME_ZONE); - // construct a new instance of ZonedDateTime - ZonedDateTime now = ZonedDateTime.now(ZoneId.of("Europe/Berlin")); - String converted = objectMapper.writeValueAsString(now); - // restore an instance of ZonedDateTime from String - ZonedDateTime restored = objectMapper.readValue(converted, ZonedDateTime.class); - assertThat(restored, is(now)); - } - -} diff --git a/jackson-modules/jackson-custom-conversions/src/test/java/com/baeldung/serialization/CustomSerializationUnitTest.java b/jackson-modules/jackson-custom-conversions/src/test/java/com/baeldung/serialization/CustomSerializationUnitTest.java deleted file mode 100644 index 9c46a86fd8..0000000000 --- a/jackson-modules/jackson-custom-conversions/src/test/java/com/baeldung/serialization/CustomSerializationUnitTest.java +++ /dev/null @@ -1,49 +0,0 @@ -package com.baeldung.serialization; - -import static org.hamcrest.Matchers.containsString; -import static org.hamcrest.Matchers.not; -import static org.hamcrest.Matchers.notNullValue; -import static org.junit.Assert.assertThat; - -import java.io.IOException; -import java.util.List; -import org.junit.Test; - -import com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility; -import com.fasterxml.jackson.annotation.PropertyAccessor; -import com.fasterxml.jackson.core.JsonGenerationException; -import com.fasterxml.jackson.core.JsonParseException; -import com.fasterxml.jackson.databind.JsonMappingException; -import com.fasterxml.jackson.databind.ObjectMapper; -import com.fasterxml.jackson.databind.module.SimpleModule; -import com.google.common.collect.Lists; - -public class CustomSerializationUnitTest { - - @Test - public final void whenSerializing_thenNoExceptions() throws JsonGenerationException, JsonMappingException, IOException { - final Item myItem = new Item(1, "theItem", new User(2, "theUser")); - final String serialized = new ObjectMapper().writeValueAsString(myItem); - } - - @Test - public final void whenSerializingWithCustomSerializer_thenNoExceptions() throws JsonGenerationException, JsonMappingException, IOException { - final Item myItem = new Item(1, "theItem", new User(2, "theUser")); - - final ObjectMapper mapper = new ObjectMapper(); - - final SimpleModule simpleModule = new SimpleModule(); - simpleModule.addSerializer(Item.class, new ItemSerializer()); - mapper.registerModule(simpleModule); - - final String serialized = mapper.writeValueAsString(myItem); - } - - @Test - public final void givenSerializerRegisteredOnClass_whenSerializingWithCustomSerializer_thenNoExceptions() throws JsonGenerationException, JsonMappingException, IOException { - final ItemWithSerializer myItem = new ItemWithSerializer(1, "theItem", new User(2, "theUser")); - - final String serialized = new ObjectMapper().writeValueAsString(myItem); - } - -} diff --git a/jackson-modules/jackson-custom-conversions/src/test/java/com/baeldung/skipfields/IgnoreFieldsWithFilterUnitTest.java b/jackson-modules/jackson-custom-conversions/src/test/java/com/baeldung/skipfields/IgnoreFieldsWithFilterUnitTest.java deleted file mode 100644 index ec753019b2..0000000000 --- a/jackson-modules/jackson-custom-conversions/src/test/java/com/baeldung/skipfields/IgnoreFieldsWithFilterUnitTest.java +++ /dev/null @@ -1,87 +0,0 @@ -package com.baeldung.skipfields; - -import com.fasterxml.jackson.annotation.JsonInclude.Include; -import com.fasterxml.jackson.core.JsonGenerator; -import com.fasterxml.jackson.core.JsonParseException; -import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.databind.ObjectMapper; -import com.fasterxml.jackson.databind.SerializerProvider; -import com.fasterxml.jackson.databind.ser.BeanPropertyWriter; -import com.fasterxml.jackson.databind.ser.FilterProvider; -import com.fasterxml.jackson.databind.ser.PropertyFilter; -import com.fasterxml.jackson.databind.ser.PropertyWriter; -import com.fasterxml.jackson.databind.ser.impl.SimpleBeanPropertyFilter; -import com.fasterxml.jackson.databind.ser.impl.SimpleFilterProvider; -import org.junit.Test; - -import java.io.IOException; - -import static org.hamcrest.Matchers.containsString; -import static org.hamcrest.Matchers.not; -import static org.junit.Assert.assertThat; - -public class IgnoreFieldsWithFilterUnitTest { - - @Test - public final void givenTypeHasFilterThatIgnoresFieldByName_whenDtoIsSerialized_thenCorrect() throws JsonParseException, IOException { - final ObjectMapper mapper = new ObjectMapper(); - final SimpleBeanPropertyFilter theFilter = SimpleBeanPropertyFilter.serializeAllExcept("intValue"); - final FilterProvider filters = new SimpleFilterProvider().addFilter("myFilter", theFilter); - - final MyDtoWithFilter dtoObject = new MyDtoWithFilter(); - dtoObject.setIntValue(12); - - final String dtoAsString = mapper.writer(filters) - .writeValueAsString(dtoObject); - - assertThat(dtoAsString, not(containsString("intValue"))); - assertThat(dtoAsString, containsString("booleanValue")); - assertThat(dtoAsString, containsString("stringValue")); - } - - @Test - public final void givenTypeHasFilterThatIgnoresNegativeInt_whenDtoIsSerialized_thenCorrect() throws JsonParseException, IOException { - final PropertyFilter theFilter = new SimpleBeanPropertyFilter() { - @Override - public final void serializeAsField(final Object pojo, final JsonGenerator jgen, final SerializerProvider provider, final PropertyWriter writer) throws Exception { - if (include(writer)) { - if (!writer.getName() - .equals("intValue")) { - writer.serializeAsField(pojo, jgen, provider); - return; - } - - final int intValue = ((MyDtoWithFilter) pojo).getIntValue(); - if (intValue >= 0) { - writer.serializeAsField(pojo, jgen, provider); - } - } else if (!jgen.canOmitFields()) { // since 2.3 - writer.serializeAsOmittedField(pojo, jgen, provider); - } - } - - @Override - protected final boolean include(final BeanPropertyWriter writer) { - return true; - } - - @Override - protected final boolean include(final PropertyWriter writer) { - return true; - } - }; - final FilterProvider filters = new SimpleFilterProvider().addFilter("myFilter", theFilter); - - final MyDtoWithFilter dtoObject = new MyDtoWithFilter(); - dtoObject.setIntValue(-1); - - final ObjectMapper mapper = new ObjectMapper(); - final String dtoAsString = mapper.writer(filters) - .writeValueAsString(dtoObject); - - assertThat(dtoAsString, not(containsString("intValue"))); - assertThat(dtoAsString, containsString("booleanValue")); - assertThat(dtoAsString, containsString("stringValue")); - } - -} diff --git a/jackson-modules/jackson-custom-conversions/src/test/java/com/baeldung/skipfields/JacksonDynamicIgnoreUnitTest.java b/jackson-modules/jackson-custom-conversions/src/test/java/com/baeldung/skipfields/JacksonDynamicIgnoreUnitTest.java deleted file mode 100644 index 2fd59e2a82..0000000000 --- a/jackson-modules/jackson-custom-conversions/src/test/java/com/baeldung/skipfields/JacksonDynamicIgnoreUnitTest.java +++ /dev/null @@ -1,88 +0,0 @@ -package com.baeldung.skipfields; - -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; - -import java.util.Arrays; - -import org.junit.Before; -import org.junit.Test; - -import com.fasterxml.jackson.annotation.JsonInclude.Include; -import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.databind.BeanDescription; -import com.fasterxml.jackson.databind.JsonSerializer; -import com.fasterxml.jackson.databind.ObjectMapper; -import com.fasterxml.jackson.databind.SerializationConfig; -import com.fasterxml.jackson.databind.module.SimpleModule; -import com.fasterxml.jackson.databind.ser.BeanSerializerModifier; - -public class JacksonDynamicIgnoreUnitTest { - - private ObjectMapper mapper = new ObjectMapper(); - - @Before - public void setUp() { - mapper.setSerializationInclusion(Include.NON_EMPTY); - mapper.registerModule(new SimpleModule() { - @Override - public void setupModule(final SetupContext context) { - super.setupModule(context); - context.addBeanSerializerModifier(new BeanSerializerModifier() { - @Override - public JsonSerializer modifySerializer(final SerializationConfig config, final BeanDescription beanDesc, final JsonSerializer serializer) { - if (Hidable.class.isAssignableFrom(beanDesc.getBeanClass())) { - return new HidableSerializer((JsonSerializer) serializer); - } - return serializer; - } - }); - } - }); - } - - @Test - public void whenNotHidden_thenCorrect() throws JsonProcessingException { - final Address ad = new Address("ny", "usa", false); - final Person person = new Person("john", ad, false); - final String result = mapper.writeValueAsString(person); - - assertTrue(result.contains("name")); - assertTrue(result.contains("john")); - assertTrue(result.contains("address")); - assertTrue(result.contains("usa")); - } - - @Test - public void whenAddressHidden_thenCorrect() throws JsonProcessingException { - final Address ad = new Address("ny", "usa", true); - final Person person = new Person("john", ad, false); - final String result = mapper.writeValueAsString(person); - - assertTrue(result.contains("name")); - assertTrue(result.contains("john")); - assertFalse(result.contains("address")); - assertFalse(result.contains("usa")); - } - - @Test - public void whenAllHidden_thenCorrect() throws JsonProcessingException { - final Address ad = new Address("ny", "usa", false); - final Person person = new Person("john", ad, true); - final String result = mapper.writeValueAsString(person); - - assertTrue(result.length() == 0); - } - - @Test - public void whenSerializeList_thenCorrect() throws JsonProcessingException { - final Address ad1 = new Address("tokyo", "jp", true); - final Address ad2 = new Address("london", "uk", false); - final Address ad3 = new Address("ny", "usa", false); - final Person p1 = new Person("john", ad1, false); - final Person p2 = new Person("tom", ad2, true); - final Person p3 = new Person("adam", ad3, false); - - final String result = mapper.writeValueAsString(Arrays.asList(p1, p2, p3)); - } -} diff --git a/jackson-modules/jackson-exceptions/README.md b/jackson-modules/jackson-exceptions/README.md deleted file mode 100644 index 6f082aaaa5..0000000000 --- a/jackson-modules/jackson-exceptions/README.md +++ /dev/null @@ -1,7 +0,0 @@ -## Jackson Exceptions - -This module contains articles about Jackson exceptions. - -### Relevant Articles: -- [Jackson Exceptions – Problems and Solutions](https://www.baeldung.com/jackson-exception) -- [Jackson – JsonMappingException (No serializer found for class)](https://www.baeldung.com/jackson-jsonmappingexception) diff --git a/jackson-modules/jackson-exceptions/pom.xml b/jackson-modules/jackson-exceptions/pom.xml deleted file mode 100644 index bb2a9b1810..0000000000 --- a/jackson-modules/jackson-exceptions/pom.xml +++ /dev/null @@ -1,26 +0,0 @@ - - - 4.0.0 - jackson-exceptions - 0.0.1-SNAPSHOT - jackson-exceptions - - - com.ossez - jackson-modules - 0.0.2-SNAPSHOT - - - - jackson-exceptions - - - src/main/resources - true - - - - - \ No newline at end of file diff --git a/jackson-modules/jackson-exceptions/src/main/java/com/baeldung/exceptions/User.java b/jackson-modules/jackson-exceptions/src/main/java/com/baeldung/exceptions/User.java deleted file mode 100644 index e0e77c658e..0000000000 --- a/jackson-modules/jackson-exceptions/src/main/java/com/baeldung/exceptions/User.java +++ /dev/null @@ -1,26 +0,0 @@ -package com.baeldung.exceptions; - -public class User { - public int id; - public String name; - - public User() { - super(); - } - - public User(final int id, final String name) { - this.id = id; - this.name = name; - } - - // API - - public int getId() { - return id; - } - - public String getName() { - return name; - } - -} \ No newline at end of file diff --git a/jackson-modules/jackson-exceptions/src/main/java/com/baeldung/exceptions/UserWithConflict.java b/jackson-modules/jackson-exceptions/src/main/java/com/baeldung/exceptions/UserWithConflict.java deleted file mode 100644 index 5adbb7b01e..0000000000 --- a/jackson-modules/jackson-exceptions/src/main/java/com/baeldung/exceptions/UserWithConflict.java +++ /dev/null @@ -1,25 +0,0 @@ -package com.baeldung.exceptions; - -public class UserWithConflict { - public int id; - public String name; - boolean checked; - - public UserWithConflict() { - super(); - } - - public UserWithConflict(final int id, final String name, final boolean checked) { - this.id = id; - this.name = name; - this.checked = checked; - } - - public boolean getChecked() { - return checked; - } - - public boolean isChecked() { - return checked; - } -} diff --git a/jackson-modules/jackson-exceptions/src/main/java/com/baeldung/exceptions/UserWithNoDefaultConstructor.java b/jackson-modules/jackson-exceptions/src/main/java/com/baeldung/exceptions/UserWithNoDefaultConstructor.java deleted file mode 100644 index c75b06ed6a..0000000000 --- a/jackson-modules/jackson-exceptions/src/main/java/com/baeldung/exceptions/UserWithNoDefaultConstructor.java +++ /dev/null @@ -1,21 +0,0 @@ -package com.baeldung.exceptions; - -public class UserWithNoDefaultConstructor { - - private int id; - private String name; - - public UserWithNoDefaultConstructor(final int id, final String name) { - this.id = id; - this.name = name; - } - - public int getId() { - return id; - } - - public String getName() { - return name; - } - -} \ No newline at end of file diff --git a/jackson-modules/jackson-exceptions/src/main/java/com/baeldung/exceptions/UserWithPrivateFields.java b/jackson-modules/jackson-exceptions/src/main/java/com/baeldung/exceptions/UserWithPrivateFields.java deleted file mode 100644 index c10020bd85..0000000000 --- a/jackson-modules/jackson-exceptions/src/main/java/com/baeldung/exceptions/UserWithPrivateFields.java +++ /dev/null @@ -1,16 +0,0 @@ -package com.baeldung.exceptions; - -public class UserWithPrivateFields { - int id; - String name; - - public UserWithPrivateFields() { - super(); - } - - public UserWithPrivateFields(final int id, final String name) { - this.id = id; - this.name = name; - } - -} diff --git a/jackson-modules/jackson-exceptions/src/main/java/com/baeldung/exceptions/UserWithRoot.java b/jackson-modules/jackson-exceptions/src/main/java/com/baeldung/exceptions/UserWithRoot.java deleted file mode 100644 index cadcd43a72..0000000000 --- a/jackson-modules/jackson-exceptions/src/main/java/com/baeldung/exceptions/UserWithRoot.java +++ /dev/null @@ -1,18 +0,0 @@ -package com.baeldung.exceptions; - -import com.fasterxml.jackson.annotation.JsonRootName; - -@JsonRootName(value = "user") -public class UserWithRoot { - public int id; - public String name; - - public UserWithRoot() { - super(); - } - - public UserWithRoot(final int id, final String name) { - this.id = id; - this.name = name; - } -} diff --git a/jackson-modules/jackson-exceptions/src/main/java/com/baeldung/exceptions/Zoo.java b/jackson-modules/jackson-exceptions/src/main/java/com/baeldung/exceptions/Zoo.java deleted file mode 100644 index 3e729a1d2f..0000000000 --- a/jackson-modules/jackson-exceptions/src/main/java/com/baeldung/exceptions/Zoo.java +++ /dev/null @@ -1,22 +0,0 @@ -package com.baeldung.exceptions; - -public class Zoo { - public Animal animal; - - public Zoo() { - } -} - -abstract class Animal { - public String name; - - public Animal() { - } -} - -class Cat extends Animal { - public int lives; - - public Cat() { - } -} \ No newline at end of file diff --git a/jackson-modules/jackson-exceptions/src/main/java/com/baeldung/exceptions/ZooConfigured.java b/jackson-modules/jackson-exceptions/src/main/java/com/baeldung/exceptions/ZooConfigured.java deleted file mode 100644 index 31c2ce4d4c..0000000000 --- a/jackson-modules/jackson-exceptions/src/main/java/com/baeldung/exceptions/ZooConfigured.java +++ /dev/null @@ -1,25 +0,0 @@ -package com.baeldung.exceptions; - -import com.fasterxml.jackson.databind.annotation.JsonDeserialize; - -public class ZooConfigured { - public AnimalConfigured animal; - - public ZooConfigured() { - } -} - -@JsonDeserialize(as = CatConfigured.class) -abstract class AnimalConfigured { - public String name; - - public AnimalConfigured() { - } -} - -class CatConfigured extends AnimalConfigured { - public int lives; - - public CatConfigured() { - } -} \ No newline at end of file diff --git a/jackson-modules/jackson-exceptions/src/main/java/com/baeldung/mappingexception/MyDtoNoAccessors.java b/jackson-modules/jackson-exceptions/src/main/java/com/baeldung/mappingexception/MyDtoNoAccessors.java deleted file mode 100644 index 17bc5257fb..0000000000 --- a/jackson-modules/jackson-exceptions/src/main/java/com/baeldung/mappingexception/MyDtoNoAccessors.java +++ /dev/null @@ -1,21 +0,0 @@ -package com.baeldung.mappingexception; - -public class MyDtoNoAccessors { - - String stringValue; - int intValue; - boolean booleanValue; - - public MyDtoNoAccessors() { - super(); - } - - public MyDtoNoAccessors(final String stringValue, final int intValue, final boolean booleanValue) { - super(); - - this.stringValue = stringValue; - this.intValue = intValue; - this.booleanValue = booleanValue; - } - -} diff --git a/jackson-modules/jackson-exceptions/src/main/java/com/baeldung/mappingexception/MyDtoNoAccessorsAndFieldVisibility.java b/jackson-modules/jackson-exceptions/src/main/java/com/baeldung/mappingexception/MyDtoNoAccessorsAndFieldVisibility.java deleted file mode 100644 index cf5d5ca500..0000000000 --- a/jackson-modules/jackson-exceptions/src/main/java/com/baeldung/mappingexception/MyDtoNoAccessorsAndFieldVisibility.java +++ /dev/null @@ -1,25 +0,0 @@ -package com.baeldung.mappingexception; - -import com.fasterxml.jackson.annotation.JsonAutoDetect; -import com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility; - -@JsonAutoDetect(fieldVisibility = Visibility.ANY) -public class MyDtoNoAccessorsAndFieldVisibility { - - String stringValue; - int intValue; - boolean booleanValue; - - public MyDtoNoAccessorsAndFieldVisibility() { - super(); - } - - public MyDtoNoAccessorsAndFieldVisibility(final String stringValue, final int intValue, final boolean booleanValue) { - super(); - - this.stringValue = stringValue; - this.intValue = intValue; - this.booleanValue = booleanValue; - } - -} diff --git a/jackson-modules/jackson-exceptions/src/test/java/com/baeldung/exceptions/JacksonExceptionsUnitTest.java b/jackson-modules/jackson-exceptions/src/test/java/com/baeldung/exceptions/JacksonExceptionsUnitTest.java deleted file mode 100644 index 38ef3f9390..0000000000 --- a/jackson-modules/jackson-exceptions/src/test/java/com/baeldung/exceptions/JacksonExceptionsUnitTest.java +++ /dev/null @@ -1,195 +0,0 @@ -package com.baeldung.exceptions; - -import static org.hamcrest.Matchers.containsString; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertThat; - -import java.io.IOException; -import java.util.List; - -import org.junit.Test; - -import com.baeldung.exceptions.User; -import com.baeldung.exceptions.UserWithPrivateFields; -import com.baeldung.exceptions.UserWithRoot; -import com.baeldung.exceptions.Zoo; -import com.baeldung.exceptions.ZooConfigured; -import com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility; -import com.fasterxml.jackson.annotation.PropertyAccessor; -import com.fasterxml.jackson.core.JsonFactory; -import com.fasterxml.jackson.core.JsonParseException; -import com.fasterxml.jackson.core.JsonParser; -import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.core.type.TypeReference; -import com.fasterxml.jackson.databind.DeserializationFeature; -import com.fasterxml.jackson.databind.JsonMappingException; -import com.fasterxml.jackson.databind.ObjectMapper; -import com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException; - -public class JacksonExceptionsUnitTest { - - // JsonMappingException: Can not construct instance of - @Test(expected = JsonMappingException.class) - public void givenAbstractClass_whenDeserializing_thenException() throws IOException { - final String json = "{\"animal\":{\"name\":\"lacy\"}}"; - final ObjectMapper mapper = new ObjectMapper(); - - mapper.reader() - .forType(Zoo.class) - .readValue(json); - } - - @Test - public void givenAbstractClassConfigured_whenDeserializing_thenCorrect() throws IOException { - final String json = "{\"animal\":{\"name\":\"lacy\"}}"; - final ObjectMapper mapper = new ObjectMapper(); - - mapper.reader() - .forType(ZooConfigured.class) - .readValue(json); - } - - // JsonMappingException: No serializer found for class - @Test(expected = JsonMappingException.class) - public void givenClassWithPrivateFields_whenSerializing_thenException() throws IOException { - final UserWithPrivateFields user = new UserWithPrivateFields(1, "John"); - - final ObjectMapper mapper = new ObjectMapper(); - mapper.writer() - .writeValueAsString(user); - } - - @Test - public void givenClassWithPrivateFields_whenConfigureSerializing_thenCorrect() throws IOException { - final UserWithPrivateFields user = new UserWithPrivateFields(1, "John"); - - final ObjectMapper mapper = new ObjectMapper(); - mapper.setVisibility(PropertyAccessor.FIELD, Visibility.ANY); - - final String result = mapper.writer() - .writeValueAsString(user); - assertThat(result, containsString("John")); - } - - // JsonMappingException: No suitable constructor found - @Test(expected = JsonMappingException.class) - public void givenNoDefaultConstructor_whenDeserializing_thenException() throws IOException { - final String json = "{\"id\":1,\"name\":\"John\"}"; - final ObjectMapper mapper = new ObjectMapper(); - - mapper.reader() - .forType(UserWithNoDefaultConstructor.class) - .readValue(json); - } - - @Test - public void givenDefaultConstructor_whenDeserializing_thenCorrect() throws IOException { - final String json = "{\"id\":1,\"name\":\"John\"}"; - final ObjectMapper mapper = new ObjectMapper(); - - final User user = mapper.reader() - .forType(User.class) - .readValue(json); - assertEquals("John", user.name); - } - - // JsonMappingException: Root name does not match expected - @Test(expected = JsonMappingException.class) - public void givenWrappedJsonString_whenDeserializing_thenException() throws IOException { - final String json = "{\"user\":{\"id\":1,\"name\":\"John\"}}"; - - final ObjectMapper mapper = new ObjectMapper(); - mapper.enable(DeserializationFeature.UNWRAP_ROOT_VALUE); - - mapper.reader() - .forType(User.class) - .readValue(json); - } - - @Test - public void givenWrappedJsonStringAndConfigureClass_whenDeserializing_thenCorrect() throws IOException { - final String json = "{\"user\":{\"id\":1,\"name\":\"John\"}}"; - - final ObjectMapper mapper = new ObjectMapper(); - mapper.enable(DeserializationFeature.UNWRAP_ROOT_VALUE); - - final UserWithRoot user = mapper.reader() - .forType(UserWithRoot.class) - .readValue(json); - assertEquals("John", user.name); - } - - // JsonMappingException: Can not deserialize instance of - @Test(expected = JsonMappingException.class) - public void givenJsonOfArray_whenDeserializing_thenException() throws JsonProcessingException, IOException { - final String json = "[{\"id\":1,\"name\":\"John\"},{\"id\":2,\"name\":\"Adam\"}]"; - final ObjectMapper mapper = new ObjectMapper(); - - mapper.reader() - .forType(User.class) - .readValue(json); - } - - @Test - public void givenJsonOfArray_whenDeserializing_thenCorrect() throws JsonProcessingException, IOException { - final String json = "[{\"id\":1,\"name\":\"John\"},{\"id\":2,\"name\":\"Adam\"}]"; - final ObjectMapper mapper = new ObjectMapper(); - - final List users = mapper.reader() - .forType(new TypeReference>() { - }) - .readValue(json); - - assertEquals(2, users.size()); - } - - // UnrecognizedPropertyException - @Test(expected = UnrecognizedPropertyException.class) - public void givenJsonStringWithExtra_whenDeserializing_thenException() throws IOException { - final String json = "{\"id\":1,\"name\":\"John\", \"checked\":true}"; - - final ObjectMapper mapper = new ObjectMapper(); - mapper.reader() - .forType(User.class) - .readValue(json); - } - - @Test - public void givenJsonStringWithExtra_whenConfigureDeserializing_thenCorrect() throws IOException { - final String json = "{\"id\":1,\"name\":\"John\", \"checked\":true}"; - - final ObjectMapper mapper = new ObjectMapper(); - mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES); - - final User user = mapper.reader() - .forType(User.class) - .readValue(json); - assertEquals("John", user.name); - } - - // JsonParseException: Unexpected character (''' (code 39)) - @Test(expected = JsonParseException.class) - public void givenStringWithSingleQuotes_whenDeserializing_thenException() throws JsonProcessingException, IOException { - final String json = "{'id':1,'name':'John'}"; - final ObjectMapper mapper = new ObjectMapper(); - - mapper.reader() - .forType(User.class) - .readValue(json); - } - - @Test - public void givenStringWithSingleQuotes_whenConfigureDeserializing_thenCorrect() throws JsonProcessingException, IOException { - final String json = "{'id':1,'name':'John'}"; - - final JsonFactory factory = new JsonFactory(); - factory.enable(JsonParser.Feature.ALLOW_SINGLE_QUOTES); - final ObjectMapper mapper = new ObjectMapper(factory); - - final User user = mapper.reader() - .forType(User.class) - .readValue(json); - assertEquals("John", user.name); - } - -} diff --git a/jackson-modules/jackson-exceptions/src/test/java/com/baeldung/mappingexception/JacksonMappingExceptionUnitTest.java b/jackson-modules/jackson-exceptions/src/test/java/com/baeldung/mappingexception/JacksonMappingExceptionUnitTest.java deleted file mode 100644 index df35626828..0000000000 --- a/jackson-modules/jackson-exceptions/src/test/java/com/baeldung/mappingexception/JacksonMappingExceptionUnitTest.java +++ /dev/null @@ -1,51 +0,0 @@ -package com.baeldung.mappingexception; - -import static org.hamcrest.Matchers.containsString; -import static org.hamcrest.Matchers.not; -import static org.hamcrest.Matchers.notNullValue; -import static org.junit.Assert.assertThat; - -import java.io.IOException; -import java.util.List; -import org.junit.Test; - -import com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility; -import com.fasterxml.jackson.annotation.PropertyAccessor; -import com.fasterxml.jackson.core.JsonGenerationException; -import com.fasterxml.jackson.core.JsonParseException; -import com.fasterxml.jackson.databind.JsonMappingException; -import com.fasterxml.jackson.databind.ObjectMapper; -import com.fasterxml.jackson.databind.module.SimpleModule; -import com.google.common.collect.Lists; - -public class JacksonMappingExceptionUnitTest { - - @Test(expected = JsonMappingException.class) - public final void givenObjectHasNoAccessors_whenSerializing_thenException() throws JsonParseException, IOException { - final String dtoAsString = new ObjectMapper().writeValueAsString(new MyDtoNoAccessors()); - - assertThat(dtoAsString, notNullValue()); - } - - @Test - public final void givenObjectHasNoAccessors_whenSerializingWithPrivateFieldsVisibility_thenNoException() throws JsonParseException, IOException { - final ObjectMapper objectMapper = new ObjectMapper(); - objectMapper.setVisibility(PropertyAccessor.FIELD, Visibility.ANY); - final String dtoAsString = objectMapper.writeValueAsString(new MyDtoNoAccessors()); - - assertThat(dtoAsString, containsString("intValue")); - assertThat(dtoAsString, containsString("stringValue")); - assertThat(dtoAsString, containsString("booleanValue")); - } - - @Test - public final void givenObjectHasNoAccessorsButHasVisibleFields_whenSerializing_thenNoException() throws JsonParseException, IOException { - final ObjectMapper objectMapper = new ObjectMapper(); - final String dtoAsString = objectMapper.writeValueAsString(new MyDtoNoAccessorsAndFieldVisibility()); - - assertThat(dtoAsString, containsString("intValue")); - assertThat(dtoAsString, containsString("stringValue")); - assertThat(dtoAsString, containsString("booleanValue")); - } - -} diff --git a/jackson-modules/jackson/README.md b/jackson-modules/jackson/README.md deleted file mode 100644 index 5fa0e1e7d9..0000000000 --- a/jackson-modules/jackson/README.md +++ /dev/null @@ -1,14 +0,0 @@ -## Jackson 相关文章和实例 - -这个模块主要是针对 Jackson 有关的文章 - -### 相关课程和讨论 - -有关 "计算机设计相关的课程" :https://www.ossez.com/ - -### 相关文章 -- [Using Optional with Jackson](https://www.baeldung.com/jackson-optional) -- [Compare Two JSON Objects with Jackson](https://www.baeldung.com/jackson-compare-two-json-objects) -- [Jackson vs Gson](https://www.baeldung.com/jackson-vs-gson) -- [Inheritance with Jackson](https://www.baeldung.com/jackson-inheritance) -- [Working with Tree Model Nodes in Jackson](https://www.baeldung.com/jackson-json-node-tree-model) diff --git a/jackson-modules/jackson/pom.xml b/jackson-modules/jackson/pom.xml deleted file mode 100644 index fdf0c30749..0000000000 --- a/jackson-modules/jackson/pom.xml +++ /dev/null @@ -1,73 +0,0 @@ - - - 4.0.0 - jackson - 0.0.1-SNAPSHOT - jackson - - - com.ossez - jackson-modules - 0.0.2-SNAPSHOT - - - - - - com.fasterxml.jackson.datatype - jackson-datatype-jsr310 - ${jackson.version} - - - com.fasterxml.jackson.datatype - jackson-datatype-joda - ${jackson.version} - - - com.fasterxml.jackson.module - jackson-module-jsonSchema - ${jackson.version} - - - com.fasterxml.jackson.datatype - jackson-datatype-jdk8 - ${jackson.version} - - - - io.rest-assured - json-schema-validator - ${rest-assured.version} - test - - - io.rest-assured - json-path - ${rest-assured.version} - test - - - org.assertj - assertj-core - ${assertj.version} - test - - - - - jackson - - - src/main/resources - true - - - - - - - - - \ No newline at end of file diff --git a/jackson-modules/jackson/src/main/java/com/ossez/jackson/deserialization/jacksoninject/Person.java b/jackson-modules/jackson/src/main/java/com/ossez/jackson/deserialization/jacksoninject/Person.java deleted file mode 100644 index 154d994b12..0000000000 --- a/jackson-modules/jackson/src/main/java/com/ossez/jackson/deserialization/jacksoninject/Person.java +++ /dev/null @@ -1,43 +0,0 @@ -package com.ossez.jackson.deserialization.jacksoninject; - -import com.fasterxml.jackson.annotation.JacksonInject; - -import java.util.UUID; - -public class Person { - - @JacksonInject - private UUID id; - private String firstName; - private String lastName; - - public Person() { - - } - - public Person(String firstName, String lastName) { - this.id = UUID.randomUUID(); - this.firstName = firstName; - this.lastName = lastName; - } - - public String getFirstName() { - return firstName; - } - - public void setFirstName(String firstName) { - this.firstName = firstName; - } - - public String getLastName() { - return lastName; - } - - public void setLastName(String lastName) { - this.lastName = lastName; - } - - public UUID getId() { - return id; - } -} diff --git a/jackson-modules/jackson/src/main/java/com/ossez/jackson/deserialization/jsonanysetter/Inventory.java b/jackson-modules/jackson/src/main/java/com/ossez/jackson/deserialization/jsonanysetter/Inventory.java deleted file mode 100644 index 390da8a2e2..0000000000 --- a/jackson-modules/jackson/src/main/java/com/ossez/jackson/deserialization/jsonanysetter/Inventory.java +++ /dev/null @@ -1,20 +0,0 @@ -package com.ossez.jackson.deserialization.jsonanysetter; - -import java.util.HashMap; -import java.util.Map; - -import com.fasterxml.jackson.annotation.JsonAnySetter; - -public class Inventory { - - private Map countryDeliveryCost = new HashMap<>(); - - public Map getCountryDeliveryCost() { - return countryDeliveryCost; - } - - @JsonAnySetter - public void addCountryDeliveryCost(String country, Float cost) { - countryDeliveryCost.put(country, cost); - } -} diff --git a/jackson-modules/jackson/src/main/java/com/ossez/jackson/deserialization/jsondeserialize/Book.java b/jackson-modules/jackson/src/main/java/com/ossez/jackson/deserialization/jsondeserialize/Book.java deleted file mode 100644 index 4d47d79d7b..0000000000 --- a/jackson-modules/jackson/src/main/java/com/ossez/jackson/deserialization/jsondeserialize/Book.java +++ /dev/null @@ -1,75 +0,0 @@ -package com.ossez.jackson.deserialization.jsondeserialize; - -import java.math.BigDecimal; -import java.util.Date; -import java.util.UUID; - -import com.fasterxml.jackson.databind.annotation.JsonDeserialize; - -public class Book { - - private UUID id; - private String title; - private float price; - private String ISBN; - - @JsonDeserialize(using = CustomDateDeserializer.class) - private Date published; - private BigDecimal pages; - - public Book() { - } - - public Book(String title) { - this.id = UUID.randomUUID(); - this.title = title; - } - - public String getISBN() { - return ISBN; - } - - public void setISBN(String ISBN) { - this.ISBN = ISBN; - } - - public Date getPublished() { - return published; - } - - public void setPublished(Date published) { - this.published = published; - } - - public BigDecimal getPages() { - return pages; - } - - public void setPages(BigDecimal pages) { - this.pages = pages; - } - - public UUID getId() { - return id; - } - - public void setId(UUID id) { - this.id = id; - } - - public String getTitle() { - return title; - } - - public void setTitle(String title) { - this.title = title; - } - - public float getPrice() { - return price; - } - - public void setPrice(float price) { - this.price = price; - } -} diff --git a/jackson-modules/jackson/src/main/java/com/ossez/jackson/deserialization/jsondeserialize/CustomDateDeserializer.java b/jackson-modules/jackson/src/main/java/com/ossez/jackson/deserialization/jsondeserialize/CustomDateDeserializer.java deleted file mode 100644 index 762d198457..0000000000 --- a/jackson-modules/jackson/src/main/java/com/ossez/jackson/deserialization/jsondeserialize/CustomDateDeserializer.java +++ /dev/null @@ -1,33 +0,0 @@ -package com.ossez.jackson.deserialization.jsondeserialize; - -import com.fasterxml.jackson.core.JsonParser; -import com.fasterxml.jackson.databind.DeserializationContext; -import com.fasterxml.jackson.databind.deser.std.StdDeserializer; - -import java.io.IOException; -import java.text.ParseException; -import java.text.SimpleDateFormat; -import java.util.Date; - -public class CustomDateDeserializer extends StdDeserializer { - - private static SimpleDateFormat formatter = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss"); - - public CustomDateDeserializer() { - this(null); - } - - public CustomDateDeserializer(Class vc) { - super(vc); - } - - @Override - public Date deserialize(JsonParser jsonparser, DeserializationContext context) throws IOException { - String date = jsonparser.getText(); - try { - return formatter.parse(date); - } catch (ParseException e) { - throw new RuntimeException(e); - } - } -} diff --git a/jackson-modules/jackson/src/main/java/com/ossez/jackson/domain/Person.java b/jackson-modules/jackson/src/main/java/com/ossez/jackson/domain/Person.java deleted file mode 100644 index 026d52cfaa..0000000000 --- a/jackson-modules/jackson/src/main/java/com/ossez/jackson/domain/Person.java +++ /dev/null @@ -1,30 +0,0 @@ -package com.ossez.jackson.domain; - -public class Person { - - private String firstName; - private String lastName; - - public Person(String firstName, String lastName) { - super(); - this.firstName = firstName; - this.lastName = lastName; - } - - public String getFirstName() { - return firstName; - } - - public void setFirstName(String firstName) { - this.firstName = firstName; - } - - public String getLastName() { - return lastName; - } - - public void setLastName(String lastName) { - this.lastName = lastName; - } -} - diff --git a/jackson-modules/jackson/src/main/java/com/ossez/jackson/inheritance/Event.java b/jackson-modules/jackson/src/main/java/com/ossez/jackson/inheritance/Event.java deleted file mode 100644 index 8843bcc287..0000000000 --- a/jackson-modules/jackson/src/main/java/com/ossez/jackson/inheritance/Event.java +++ /dev/null @@ -1,25 +0,0 @@ -package com.ossez.jackson.inheritance; - -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.annotation.JsonTypeInfo; - -@JsonTypeInfo(use = JsonTypeInfo.Id.MINIMAL_CLASS, include = JsonTypeInfo.As.PROPERTY, property = "eventType") -abstract public class Event { - private final String id; - private final Long timestamp; - - @JsonCreator - public Event(@JsonProperty("id") String id, @JsonProperty("timestamp") Long timestamp) { - this.id = id; - this.timestamp = timestamp; - } - - public Long getTimestamp() { - return timestamp; - } - - public String getId() { - return id; - } -} \ No newline at end of file diff --git a/jackson-modules/jackson/src/main/java/com/ossez/jackson/inheritance/IgnoranceAnnotationStructure.java b/jackson-modules/jackson/src/main/java/com/ossez/jackson/inheritance/IgnoranceAnnotationStructure.java deleted file mode 100644 index 87cab760ce..0000000000 --- a/jackson-modules/jackson/src/main/java/com/ossez/jackson/inheritance/IgnoranceAnnotationStructure.java +++ /dev/null @@ -1,96 +0,0 @@ -package com.ossez.jackson.inheritance; - -import com.fasterxml.jackson.annotation.JsonIgnore; -import com.fasterxml.jackson.annotation.JsonIgnoreProperties; - -public class IgnoranceAnnotationStructure { - public static abstract class Vehicle { - private String make; - private String model; - - protected Vehicle() { - } - - protected Vehicle(String make, String model) { - this.make = make; - this.model = model; - } - - public String getMake() { - return make; - } - - public void setMake(String make) { - this.make = make; - } - - public String getModel() { - return model; - } - - public void setModel(String model) { - this.model = model; - } - } - - @JsonIgnoreProperties({ "model", "seatingCapacity" }) - public static abstract class Car extends Vehicle { - private int seatingCapacity; - @JsonIgnore - private double topSpeed; - - protected Car() { - } - - protected Car(String make, String model, int seatingCapacity, double topSpeed) { - super(make, model); - this.seatingCapacity = seatingCapacity; - this.topSpeed = topSpeed; - } - - public int getSeatingCapacity() { - return seatingCapacity; - } - - public void setSeatingCapacity(int seatingCapacity) { - this.seatingCapacity = seatingCapacity; - } - - public double getTopSpeed() { - return topSpeed; - } - - public void setTopSpeed(double topSpeed) { - this.topSpeed = topSpeed; - } - } - - public static class Sedan extends Car { - public Sedan() { - } - - public Sedan(String make, String model, int seatingCapacity, double topSpeed) { - super(make, model, seatingCapacity, topSpeed); - } - } - - public static class Crossover extends Car { - private double towingCapacity; - - public Crossover() { - } - - public Crossover(String make, String model, int seatingCapacity, double topSpeed, double towingCapacity) { - super(make, model, seatingCapacity, topSpeed); - this.towingCapacity = towingCapacity; - } - - public double getTowingCapacity() { - return towingCapacity; - } - - public void setTowingCapacity(double towingCapacity) { - this.towingCapacity = towingCapacity; - } - } -} \ No newline at end of file diff --git a/jackson-modules/jackson/src/main/java/com/ossez/jackson/inheritance/IgnoranceMixinOrIntrospection.java b/jackson-modules/jackson/src/main/java/com/ossez/jackson/inheritance/IgnoranceMixinOrIntrospection.java deleted file mode 100644 index aa352d79a0..0000000000 --- a/jackson-modules/jackson/src/main/java/com/ossez/jackson/inheritance/IgnoranceMixinOrIntrospection.java +++ /dev/null @@ -1,91 +0,0 @@ -package com.ossez.jackson.inheritance; - -public class IgnoranceMixinOrIntrospection { - public static abstract class Vehicle { - private String make; - private String model; - - protected Vehicle() { - } - - protected Vehicle(String make, String model) { - this.make = make; - this.model = model; - } - - public String getMake() { - return make; - } - - public void setMake(String make) { - this.make = make; - } - - public String getModel() { - return model; - } - - public void setModel(String model) { - this.model = model; - } - } - - public static abstract class Car extends Vehicle { - private int seatingCapacity; - private double topSpeed; - - protected Car() { - } - - protected Car(String make, String model, int seatingCapacity, double topSpeed) { - super(make, model); - this.seatingCapacity = seatingCapacity; - this.topSpeed = topSpeed; - } - - public int getSeatingCapacity() { - return seatingCapacity; - } - - public void setSeatingCapacity(int seatingCapacity) { - this.seatingCapacity = seatingCapacity; - } - - public double getTopSpeed() { - return topSpeed; - } - - public void setTopSpeed(double topSpeed) { - this.topSpeed = topSpeed; - } - } - - public static class Sedan extends Car { - public Sedan() { - } - - public Sedan(String make, String model, int seatingCapacity, double topSpeed) { - super(make, model, seatingCapacity, topSpeed); - } - } - - public static class Crossover extends Car { - private double towingCapacity; - - public Crossover() { - } - - public Crossover(String make, String model, int seatingCapacity, double topSpeed, double towingCapacity) { - super(make, model, seatingCapacity, topSpeed); - this.towingCapacity = towingCapacity; - } - - public double getTowingCapacity() { - return towingCapacity; - } - - public void setTowingCapacity(double towingCapacity) { - this.towingCapacity = towingCapacity; - } - } -} \ No newline at end of file diff --git a/jackson-modules/jackson/src/main/java/com/ossez/jackson/inheritance/ItemIdAddedToUser.java b/jackson-modules/jackson/src/main/java/com/ossez/jackson/inheritance/ItemIdAddedToUser.java deleted file mode 100644 index 1a5afa72b1..0000000000 --- a/jackson-modules/jackson/src/main/java/com/ossez/jackson/inheritance/ItemIdAddedToUser.java +++ /dev/null @@ -1,28 +0,0 @@ -package com.ossez.jackson.inheritance; - -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonIgnoreProperties; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.annotation.JsonTypeName; - -@JsonTypeName("itemIdAddedToUser") -@JsonIgnoreProperties("id") -public class ItemIdAddedToUser extends Event { - private final String itemId; - private final Long quantity; - - @JsonCreator - public ItemIdAddedToUser(@JsonProperty("id") String id, @JsonProperty("timestamp") Long timestamp, @JsonProperty("itemId") String itemId, @JsonProperty("quantity") Long quantity) { - super(id, timestamp); - this.itemId = itemId; - this.quantity = quantity; - } - - public String getItemId() { - return itemId; - } - - public Long getQuantity() { - return quantity; - } -} \ No newline at end of file diff --git a/jackson-modules/jackson/src/main/java/com/ossez/jackson/inheritance/ItemIdRemovedFromUser.java b/jackson-modules/jackson/src/main/java/com/ossez/jackson/inheritance/ItemIdRemovedFromUser.java deleted file mode 100644 index 88e2c7968f..0000000000 --- a/jackson-modules/jackson/src/main/java/com/ossez/jackson/inheritance/ItemIdRemovedFromUser.java +++ /dev/null @@ -1,26 +0,0 @@ -package com.ossez.jackson.inheritance; - -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.annotation.JsonTypeName; - -@JsonTypeName("itemIdRemovedFromUser") -public class ItemIdRemovedFromUser extends Event { - private final String itemId; - private final Long quantity; - - @JsonCreator - public ItemIdRemovedFromUser(@JsonProperty("id") String id, @JsonProperty("timestamp") Long timestamp, @JsonProperty("itemId") String itemId, @JsonProperty("quantity") Long quantity) { - super(id, timestamp); - this.itemId = itemId; - this.quantity = quantity; - } - - public String getItemId() { - return itemId; - } - - public Long getQuantity() { - return quantity; - } -} \ No newline at end of file diff --git a/jackson-modules/jackson/src/main/java/com/ossez/jackson/inheritance/SubTypeConstructorStructure.java b/jackson-modules/jackson/src/main/java/com/ossez/jackson/inheritance/SubTypeConstructorStructure.java deleted file mode 100644 index afca1443de..0000000000 --- a/jackson-modules/jackson/src/main/java/com/ossez/jackson/inheritance/SubTypeConstructorStructure.java +++ /dev/null @@ -1,92 +0,0 @@ -package com.ossez.jackson.inheritance; - -import java.util.List; - -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonProperty; - -public class SubTypeConstructorStructure { - public static class Fleet { - private List vehicles; - - public List getVehicles() { - return vehicles; - } - - public void setVehicles(List vehicles) { - this.vehicles = vehicles; - } - } - - public static abstract class Vehicle { - private String make; - private String model; - - protected Vehicle(String make, String model) { - this.make = make; - this.model = model; - } - - public String getMake() { - return make; - } - - public void setMake(String make) { - this.make = make; - } - - public String getModel() { - return model; - } - - public void setModel(String model) { - this.model = model; - } - } - - public static class Car extends Vehicle { - private int seatingCapacity; - private double topSpeed; - - @JsonCreator - public Car(@JsonProperty("make") String make, @JsonProperty("model") String model, @JsonProperty("seating") int seatingCapacity, @JsonProperty("topSpeed") double topSpeed) { - super(make, model); - this.seatingCapacity = seatingCapacity; - this.topSpeed = topSpeed; - } - - public int getSeatingCapacity() { - return seatingCapacity; - } - - public void setSeatingCapacity(int seatingCapacity) { - this.seatingCapacity = seatingCapacity; - } - - public double getTopSpeed() { - return topSpeed; - } - - public void setTopSpeed(double topSpeed) { - this.topSpeed = topSpeed; - } - } - - public static class Truck extends Vehicle { - private double payloadCapacity; - - @JsonCreator - public Truck(@JsonProperty("make") String make, @JsonProperty("model") String model, @JsonProperty("payload") double payloadCapacity) { - super(make, model); - this.payloadCapacity = payloadCapacity; - } - - public double getPayloadCapacity() { - return payloadCapacity; - } - - public void setPayloadCapacity(double payloadCapacity) { - this.payloadCapacity = payloadCapacity; - } - } -} \ No newline at end of file diff --git a/jackson-modules/jackson/src/main/java/com/ossez/jackson/inheritance/SubTypeConversionStructure.java b/jackson-modules/jackson/src/main/java/com/ossez/jackson/inheritance/SubTypeConversionStructure.java deleted file mode 100644 index 006fc79111..0000000000 --- a/jackson-modules/jackson/src/main/java/com/ossez/jackson/inheritance/SubTypeConversionStructure.java +++ /dev/null @@ -1,87 +0,0 @@ -package com.ossez.jackson.inheritance; - -import com.fasterxml.jackson.annotation.JsonIgnore; - -public class SubTypeConversionStructure { - public static abstract class Vehicle { - private String make; - private String model; - - protected Vehicle() { - } - - protected Vehicle(String make, String model) { - this.make = make; - this.model = model; - } - - public String getMake() { - return make; - } - - public void setMake(String make) { - this.make = make; - } - - public String getModel() { - return model; - } - - public void setModel(String model) { - this.model = model; - } - } - - public static class Car extends Vehicle { - @JsonIgnore - private int seatingCapacity; - @JsonIgnore - private double topSpeed; - - public Car() { - } - - public Car(String make, String model, int seatingCapacity, double topSpeed) { - super(make, model); - this.seatingCapacity = seatingCapacity; - this.topSpeed = topSpeed; - } - - public int getSeatingCapacity() { - return seatingCapacity; - } - - public void setSeatingCapacity(int seatingCapacity) { - this.seatingCapacity = seatingCapacity; - } - - public double getTopSpeed() { - return topSpeed; - } - - public void setTopSpeed(double topSpeed) { - this.topSpeed = topSpeed; - } - } - - public static class Truck extends Vehicle { - @JsonIgnore - private double payloadCapacity; - - public Truck() { - } - - public Truck(String make, String model, double payloadCapacity) { - super(make, model); - this.payloadCapacity = payloadCapacity; - } - - public double getPayloadCapacity() { - return payloadCapacity; - } - - public void setPayloadCapacity(double payloadCapacity) { - this.payloadCapacity = payloadCapacity; - } - } -} \ No newline at end of file diff --git a/jackson-modules/jackson/src/main/java/com/ossez/jackson/inheritance/TypeInfoAnnotatedStructure.java b/jackson-modules/jackson/src/main/java/com/ossez/jackson/inheritance/TypeInfoAnnotatedStructure.java deleted file mode 100644 index b9b730f49f..0000000000 --- a/jackson-modules/jackson/src/main/java/com/ossez/jackson/inheritance/TypeInfoAnnotatedStructure.java +++ /dev/null @@ -1,102 +0,0 @@ -package com.ossez.jackson.inheritance; - -import java.util.List; - -import com.fasterxml.jackson.annotation.JsonTypeInfo; -import com.fasterxml.jackson.annotation.JsonSubTypes; -import com.fasterxml.jackson.annotation.JsonSubTypes.Type; - -public class TypeInfoAnnotatedStructure { - public static class Fleet { - private List vehicles; - - public List getVehicles() { - return vehicles; - } - - public void setVehicles(List vehicles) { - this.vehicles = vehicles; - } - } - - @JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "type") - @JsonSubTypes({ @Type(value = Car.class, name = "car"), @Type(value = Truck.class, name = "truck") }) - public static abstract class Vehicle { - private String make; - private String model; - - protected Vehicle() { - } - - protected Vehicle(String make, String model) { - this.make = make; - this.model = model; - } - - public String getMake() { - return make; - } - - public void setMake(String make) { - this.make = make; - } - - public String getModel() { - return model; - } - - public void setModel(String model) { - this.model = model; - } - } - - public static class Car extends Vehicle { - private int seatingCapacity; - private double topSpeed; - - public Car() { - } - - public Car(String make, String model, int seatingCapacity, double topSpeed) { - super(make, model); - this.seatingCapacity = seatingCapacity; - this.topSpeed = topSpeed; - } - - public int getSeatingCapacity() { - return seatingCapacity; - } - - public void setSeatingCapacity(int seatingCapacity) { - this.seatingCapacity = seatingCapacity; - } - - public double getTopSpeed() { - return topSpeed; - } - - public void setTopSpeed(double topSpeed) { - this.topSpeed = topSpeed; - } - } - - public static class Truck extends Vehicle { - private double payloadCapacity; - - public Truck() { - } - - public Truck(String make, String model, double payloadCapacity) { - super(make, model); - this.payloadCapacity = payloadCapacity; - } - - public double getPayloadCapacity() { - return payloadCapacity; - } - - public void setPayloadCapacity(double payloadCapacity) { - this.payloadCapacity = payloadCapacity; - } - } -} \ No newline at end of file diff --git a/jackson-modules/jackson/src/main/java/com/ossez/jackson/inheritance/TypeInfoStructure.java b/jackson-modules/jackson/src/main/java/com/ossez/jackson/inheritance/TypeInfoStructure.java deleted file mode 100644 index d2af497313..0000000000 --- a/jackson-modules/jackson/src/main/java/com/ossez/jackson/inheritance/TypeInfoStructure.java +++ /dev/null @@ -1,96 +0,0 @@ -package com.ossez.jackson.inheritance; - -import java.util.List; - -public class TypeInfoStructure { - public static class Fleet { - private List vehicles; - - public List getVehicles() { - return vehicles; - } - - public void setVehicles(List vehicles) { - this.vehicles = vehicles; - } - } - - public static abstract class Vehicle { - private String make; - private String model; - - protected Vehicle() { - } - - protected Vehicle(String make, String model) { - this.make = make; - this.model = model; - } - - public String getMake() { - return make; - } - - public void setMake(String make) { - this.make = make; - } - - public String getModel() { - return model; - } - - public void setModel(String model) { - this.model = model; - } - } - - public static class Car extends Vehicle { - private int seatingCapacity; - private double topSpeed; - - public Car() { - } - - public Car(String make, String model, int seatingCapacity, double topSpeed) { - super(make, model); - this.seatingCapacity = seatingCapacity; - this.topSpeed = topSpeed; - } - - public int getSeatingCapacity() { - return seatingCapacity; - } - - public void setSeatingCapacity(int seatingCapacity) { - this.seatingCapacity = seatingCapacity; - } - - public double getTopSpeed() { - return topSpeed; - } - - public void setTopSpeed(double topSpeed) { - this.topSpeed = topSpeed; - } - } - - public static class Truck extends Vehicle { - private double payloadCapacity; - - public Truck() { - } - - public Truck(String make, String model, double payloadCapacity) { - super(make, model); - this.payloadCapacity = payloadCapacity; - } - - public double getPayloadCapacity() { - return payloadCapacity; - } - - public void setPayloadCapacity(double payloadCapacity) { - this.payloadCapacity = payloadCapacity; - } - } -} \ No newline at end of file diff --git a/jackson-modules/jackson/src/main/java/com/ossez/jackson/jacksonvsgson/ActorJackson.java b/jackson-modules/jackson/src/main/java/com/ossez/jackson/jacksonvsgson/ActorJackson.java deleted file mode 100644 index 4338159b18..0000000000 --- a/jackson-modules/jackson/src/main/java/com/ossez/jackson/jacksonvsgson/ActorJackson.java +++ /dev/null @@ -1,61 +0,0 @@ -package com.ossez.jackson.jacksonvsgson; - -import java.text.DateFormat; -import java.text.SimpleDateFormat; -import java.util.Date; -import java.util.List; -import java.util.Locale; -import java.util.TimeZone; - -public class ActorJackson { - - private String imdbId; - private Date dateOfBirth; - private List filmography; - - public ActorJackson() { - super(); - } - - public ActorJackson(String imdbId, Date dateOfBirth, List filmography) { - super(); - this.imdbId = imdbId; - this.dateOfBirth = dateOfBirth; - this.filmography = filmography; - } - - @Override - public String toString() { - return "ActorJackson [imdbId=" + imdbId + ", dateOfBirth=" + formatDateOfBirth() + ", filmography=" + filmography + "]"; - } - - public String getImdbId() { - return imdbId; - } - - public void setImdbId(String imdbId) { - this.imdbId = imdbId; - } - - public Date getDateOfBirth() { - return dateOfBirth; - } - - public void setDateOfBirth(Date dateOfBirth) { - this.dateOfBirth = dateOfBirth; - } - - public List getFilmography() { - return filmography; - } - - public void setFilmography(List filmography) { - this.filmography = filmography; - } - - private String formatDateOfBirth() { - final DateFormat formatter = new SimpleDateFormat("EEE MMM dd hh:mm:ss zzz yyyy", Locale.US); - formatter.setTimeZone(TimeZone.getTimeZone("GMT")); - return formatter.format(dateOfBirth); - } -} diff --git a/jackson-modules/jackson/src/main/java/com/ossez/jackson/jacksonvsgson/ActorJacksonSerializer.java b/jackson-modules/jackson/src/main/java/com/ossez/jackson/jacksonvsgson/ActorJacksonSerializer.java deleted file mode 100644 index bb67092bd9..0000000000 --- a/jackson-modules/jackson/src/main/java/com/ossez/jackson/jacksonvsgson/ActorJacksonSerializer.java +++ /dev/null @@ -1,32 +0,0 @@ -package com.ossez.jackson.jacksonvsgson; - -import java.io.IOException; -import java.text.SimpleDateFormat; -import java.util.stream.Collectors; - -import com.fasterxml.jackson.core.JsonGenerator; -import com.fasterxml.jackson.databind.SerializerProvider; -import com.fasterxml.jackson.databind.ser.std.StdSerializer; - -public class ActorJacksonSerializer extends StdSerializer { - - private SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy"); - - public ActorJacksonSerializer(Class t) { - super(t); - } - - @Override - public void serialize(ActorJackson actor, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException { - - jsonGenerator.writeStartObject(); - jsonGenerator.writeStringField("imdbId", actor.getImdbId()); - jsonGenerator.writeObjectField("dateOfBirth", actor.getDateOfBirth() != null ? sdf.format(actor.getDateOfBirth()) : null); - jsonGenerator.writeNumberField("N° Film: ", actor.getFilmography() != null ? actor.getFilmography() - .size() : null); - jsonGenerator.writeStringField("filmography", actor.getFilmography() - .stream() - .collect(Collectors.joining("-"))); - jsonGenerator.writeEndObject(); - } -} \ No newline at end of file diff --git a/jackson-modules/jackson/src/main/java/com/ossez/jackson/jacksonvsgson/Movie.java b/jackson-modules/jackson/src/main/java/com/ossez/jackson/jacksonvsgson/Movie.java deleted file mode 100644 index 6d0feb0a32..0000000000 --- a/jackson-modules/jackson/src/main/java/com/ossez/jackson/jacksonvsgson/Movie.java +++ /dev/null @@ -1,50 +0,0 @@ -package com.ossez.jackson.jacksonvsgson; - -import java.util.List; - -public class Movie { - - private String imdbId; - private String director; - private List actors; - - public Movie(String imdbId, String director, List actors) { - super(); - this.imdbId = imdbId; - this.director = director; - this.actors = actors; - } - - public Movie() { - super(); - } - - @Override - public String toString() { - return "Movie [imdbId=" + imdbId + ", director=" + director + ", actors=" + actors + "]"; - } - - public String getImdbId() { - return imdbId; - } - - public void setImdbId(String imdbId) { - this.imdbId = imdbId; - } - - public String getDirector() { - return director; - } - - public void setDirector(String director) { - this.director = director; - } - - public List getActors() { - return actors; - } - - public void setActors(List actors) { - this.actors = actors; - } -} \ No newline at end of file diff --git a/jackson-modules/jackson/src/main/java/com/ossez/jackson/jacksonvsgson/MovieWithNullValue.java b/jackson-modules/jackson/src/main/java/com/ossez/jackson/jacksonvsgson/MovieWithNullValue.java deleted file mode 100644 index 2f6dceb6fe..0000000000 --- a/jackson-modules/jackson/src/main/java/com/ossez/jackson/jacksonvsgson/MovieWithNullValue.java +++ /dev/null @@ -1,46 +0,0 @@ -package com.ossez.jackson.jacksonvsgson; - -import com.fasterxml.jackson.annotation.JsonIgnore; - -import java.util.List; - -public class MovieWithNullValue { - - private String imdbId; - - @JsonIgnore - private String director; - - private List actors; - - public MovieWithNullValue(String imdbID, String director, List actors) { - super(); - this.imdbId = imdbID; - this.director = director; - this.actors = actors; - } - - public String getImdbID() { - return imdbId; - } - - public void setImdbID(String imdbID) { - this.imdbId = imdbID; - } - - public String getDirector() { - return director; - } - - public void setDirector(String director) { - this.director = director; - } - - public List getActors() { - return actors; - } - - public void setActors(List actors) { - this.actors = actors; - } -} \ No newline at end of file diff --git a/jackson-modules/jackson/src/main/java/com/ossez/jackson/node/JsonNodeIterator.java b/jackson-modules/jackson/src/main/java/com/ossez/jackson/node/JsonNodeIterator.java deleted file mode 100644 index a368e0adb0..0000000000 --- a/jackson-modules/jackson/src/main/java/com/ossez/jackson/node/JsonNodeIterator.java +++ /dev/null @@ -1,62 +0,0 @@ -package com.ossez.jackson.node; - -import java.util.Iterator; -import java.util.Map.Entry; - -import com.fasterxml.jackson.databind.JsonNode; - -public class JsonNodeIterator { - - private static final String NEW_LINE = "\n"; - private static final String FIELD_DELIMITER = ": "; - private static final String ARRAY_PREFIX = "- "; - private static final String YAML_PREFIX = " "; - - public String toYaml(JsonNode root) { - StringBuilder yaml = new StringBuilder(); - processNode(root, yaml, 0); - return yaml.toString(); - } - - private void processNode(JsonNode jsonNode, StringBuilder yaml, int depth) { - if (jsonNode.isValueNode()) { - yaml.append(jsonNode.asText()); - } - else if (jsonNode.isArray()) { - for (JsonNode arrayItem : jsonNode) { - appendNodeToYaml(arrayItem, yaml, depth, true); - } - } - else if (jsonNode.isObject()) { - appendNodeToYaml(jsonNode, yaml, depth, false); - } - } - - private void appendNodeToYaml(JsonNode node, StringBuilder yaml, int depth, boolean isArrayItem) { - Iterator> fields = node.fields(); - boolean isFirst = true; - while (fields.hasNext()) { - Entry jsonField = fields.next(); - addFieldNameToYaml(yaml, jsonField.getKey(), depth, isArrayItem && isFirst); - processNode(jsonField.getValue(), yaml, depth+1); - isFirst = false; - } - - } - - private void addFieldNameToYaml(StringBuilder yaml, String fieldName, int depth, boolean isFirstInArray) { - if (yaml.length()>0) { - yaml.append(NEW_LINE); - int requiredDepth = (isFirstInArray) ? depth-1 : depth; - for(int i = 0; i < requiredDepth; i++) { - yaml.append(YAML_PREFIX); - } - if (isFirstInArray) { - yaml.append(ARRAY_PREFIX); - } - } - yaml.append(fieldName); - yaml.append(FIELD_DELIMITER); - } - -} diff --git a/jackson-modules/jackson/src/main/java/com/ossez/jackson/optionalwithjackson/Book.java b/jackson-modules/jackson/src/main/java/com/ossez/jackson/optionalwithjackson/Book.java deleted file mode 100644 index aeda5c9b92..0000000000 --- a/jackson-modules/jackson/src/main/java/com/ossez/jackson/optionalwithjackson/Book.java +++ /dev/null @@ -1,25 +0,0 @@ -package com.ossez.jackson.optionalwithjackson; - -import java.util.Optional; - -public class Book { - - private String title; - private Optional subTitle; - - public String getTitle() { - return title; - } - - public void setTitle(String title) { - this.title = title; - } - - public Optional getSubTitle() { - return subTitle; - } - - public void setSubTitle(Optional subTitle) { - this.subTitle = subTitle; - } -} diff --git a/jackson-modules/jackson/src/main/resources/example1.json b/jackson-modules/jackson/src/main/resources/example1.json deleted file mode 100644 index 46d2982cec..0000000000 --- a/jackson-modules/jackson/src/main/resources/example1.json +++ /dev/null @@ -1,12 +0,0 @@ -{ - "collection": [ - { - "name": "Test order1", - "detail": "ahk ks" - }, - { - "name": "Test order2", - "detail": "Fisteku" - } - ] -} \ No newline at end of file diff --git a/jackson-modules/jackson/src/main/resources/example2.json b/jackson-modules/jackson/src/main/resources/example2.json deleted file mode 100644 index f4433731e6..0000000000 --- a/jackson-modules/jackson/src/main/resources/example2.json +++ /dev/null @@ -1,10 +0,0 @@ -[ - { - "name": "Test order1", - "detail": "ahk ks" - }, - { - "name": "Test order2", - "detail": "Fisteku" - } -] \ No newline at end of file diff --git a/jackson-modules/jackson/src/main/resources/logback.xml b/jackson-modules/jackson/src/main/resources/logback.xml deleted file mode 100644 index 56af2d397e..0000000000 --- a/jackson-modules/jackson/src/main/resources/logback.xml +++ /dev/null @@ -1,19 +0,0 @@ - - - - - %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n - - - - - - - - - - - - - - \ No newline at end of file diff --git a/jackson-modules/jackson/src/test/java/com/ossez/jackson/dtos/Address.java b/jackson-modules/jackson/src/test/java/com/ossez/jackson/dtos/Address.java deleted file mode 100644 index f0b3b00efe..0000000000 --- a/jackson-modules/jackson/src/test/java/com/ossez/jackson/dtos/Address.java +++ /dev/null @@ -1,33 +0,0 @@ -package com.ossez.jackson.dtos; - -public class Address { - - String streetNumber; - String streetName; - String city; - - public String getStreetNumber() { - return streetNumber; - } - - public void setStreetNumber(String streetNumber) { - this.streetNumber = streetNumber; - } - - public String getStreetName() { - return streetName; - } - - public void setStreetName(String streetName) { - this.streetName = streetName; - } - - public String getCity() { - return city; - } - - public void setCity(String city) { - this.city = city; - } - -} diff --git a/jackson-modules/jackson/src/test/java/com/ossez/jackson/dtos/MyDto.java b/jackson-modules/jackson/src/test/java/com/ossez/jackson/dtos/MyDto.java deleted file mode 100644 index 977358a49b..0000000000 --- a/jackson-modules/jackson/src/test/java/com/ossez/jackson/dtos/MyDto.java +++ /dev/null @@ -1,54 +0,0 @@ -package com.ossez.jackson.dtos; - -public class MyDto { - - private String stringValue; - private int intValue; - private boolean booleanValue; - - public MyDto() { - super(); - } - - public MyDto(final String stringValue, final int intValue, final boolean booleanValue) { - super(); - - this.stringValue = stringValue; - this.intValue = intValue; - this.booleanValue = booleanValue; - } - - // API - - public String getStringValue() { - return stringValue; - } - - public void setStringValue(final String stringValue) { - this.stringValue = stringValue; - } - - public int getIntValue() { - return intValue; - } - - public void setIntValue(final int intValue) { - this.intValue = intValue; - } - - public boolean isBooleanValue() { - return booleanValue; - } - - public void setBooleanValue(final boolean booleanValue) { - this.booleanValue = booleanValue; - } - - // - - @Override - public String toString() { - return "MyDto [stringValue=" + stringValue + ", intValue=" + intValue + ", booleanValue=" + booleanValue + "]"; - } - -} diff --git a/jackson-modules/jackson/src/test/java/com/ossez/jackson/dtos/Person.java b/jackson-modules/jackson/src/test/java/com/ossez/jackson/dtos/Person.java deleted file mode 100644 index 538128de83..0000000000 --- a/jackson-modules/jackson/src/test/java/com/ossez/jackson/dtos/Person.java +++ /dev/null @@ -1,47 +0,0 @@ -package com.ossez.jackson.dtos; - -import java.util.ArrayList; -import java.util.List; - -import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlRootElement; - -@JacksonXmlRootElement(localName = "person") -public final class Person { - private String firstName; - private String lastName; - private List phoneNumbers = new ArrayList<>(); - private List
address = new ArrayList<>(); - - public List
getAddress() { - return address; - } - - public void setAddress(List
address) { - this.address = address; - } - - public String getFirstName() { - return firstName; - } - - public void setFirstName(String firstName) { - this.firstName = firstName; - } - - public String getLastName() { - return lastName; - } - - public void setLastName(String lastName) { - this.lastName = lastName; - } - - public List getPhoneNumbers() { - return phoneNumbers; - } - - public void setPhoneNumbers(List phoneNumbers) { - this.phoneNumbers = phoneNumbers; - } - -} \ No newline at end of file diff --git a/jackson-modules/jackson/src/test/java/com/ossez/jackson/dtos/User.java b/jackson-modules/jackson/src/test/java/com/ossez/jackson/dtos/User.java deleted file mode 100644 index 59a1a19ef0..0000000000 --- a/jackson-modules/jackson/src/test/java/com/ossez/jackson/dtos/User.java +++ /dev/null @@ -1,26 +0,0 @@ -package com.ossez.jackson.dtos; - -public class User { - public int id; - public String name; - - public User() { - super(); - } - - public User(final int id, final String name) { - this.id = id; - this.name = name; - } - - // API - - public int getId() { - return id; - } - - public String getName() { - return name; - } - -} \ No newline at end of file diff --git a/jackson-modules/jackson/src/test/java/com/ossez/jackson/inheritance/IgnoranceUnitTest.java b/jackson-modules/jackson/src/test/java/com/ossez/jackson/inheritance/IgnoranceUnitTest.java deleted file mode 100644 index e0ebbbdb33..0000000000 --- a/jackson-modules/jackson/src/test/java/com/ossez/jackson/inheritance/IgnoranceUnitTest.java +++ /dev/null @@ -1,92 +0,0 @@ -package com.ossez.jackson.inheritance; - -import static org.junit.Assert.assertThat; -import static org.hamcrest.CoreMatchers.containsString; -import static org.hamcrest.CoreMatchers.not; - -import org.junit.Test; - -import java.util.List; -import java.util.ArrayList; - -import com.fasterxml.jackson.annotation.JsonIgnore; -import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.databind.ObjectMapper; -import com.fasterxml.jackson.databind.introspect.AnnotatedMember; -import com.fasterxml.jackson.databind.introspect.JacksonAnnotationIntrospector; - -public class IgnoranceUnitTest { - private static abstract class CarMixIn { - @JsonIgnore - public String make; - @JsonIgnore - public String topSpeed; - } - - private static class IgnoranceIntrospector extends JacksonAnnotationIntrospector { - private static final long serialVersionUID = 1422295680188892323L; - - public boolean hasIgnoreMarker(AnnotatedMember m) { - return m.getDeclaringClass() == IgnoranceMixinOrIntrospection.Vehicle.class && m.getName() == "model" || m.getDeclaringClass() == IgnoranceMixinOrIntrospection.Car.class || m.getName() == "towingCapacity" || super.hasIgnoreMarker(m); - } - } - - @Test - public void givenAnnotations_whenIgnoringProperties_thenCorrect() throws JsonProcessingException { - ObjectMapper mapper = new ObjectMapper(); - - IgnoranceAnnotationStructure.Sedan sedan = new IgnoranceAnnotationStructure.Sedan("Mercedes-Benz", "S500", 5, 250.0); - IgnoranceAnnotationStructure.Crossover crossover = new IgnoranceAnnotationStructure.Crossover("BMW", "X6", 5, 250.0, 6000.0); - - List vehicles = new ArrayList<>(); - vehicles.add(sedan); - vehicles.add(crossover); - - String jsonDataString = mapper.writeValueAsString(vehicles); - - assertThat(jsonDataString, containsString("make")); - assertThat(jsonDataString, not(containsString("model"))); - assertThat(jsonDataString, not(containsString("seatingCapacity"))); - assertThat(jsonDataString, not(containsString("topSpeed"))); - assertThat(jsonDataString, containsString("towingCapacity")); - } - - @Test - public void givenMixIns_whenIgnoringProperties_thenCorrect() throws JsonProcessingException { - ObjectMapper mapper = new ObjectMapper(); - mapper.addMixIn(IgnoranceMixinOrIntrospection.Car.class, CarMixIn.class); - - String jsonDataString = instantiateAndSerializeObjects(mapper); - - assertThat(jsonDataString, not(containsString("make"))); - assertThat(jsonDataString, containsString("model")); - assertThat(jsonDataString, containsString("seatingCapacity")); - assertThat(jsonDataString, not(containsString("topSpeed"))); - assertThat(jsonDataString, containsString("towingCapacity")); - } - - @Test - public void givenIntrospection_whenIgnoringProperties_thenCorrect() throws JsonProcessingException { - ObjectMapper mapper = new ObjectMapper(); - mapper.setAnnotationIntrospector(new IgnoranceIntrospector()); - - String jsonDataString = instantiateAndSerializeObjects(mapper); - - assertThat(jsonDataString, containsString("make")); - assertThat(jsonDataString, not(containsString("model"))); - assertThat(jsonDataString, not(containsString("seatingCapacity"))); - assertThat(jsonDataString, not(containsString("topSpeed"))); - assertThat(jsonDataString, not(containsString("towingCapacity"))); - } - - private String instantiateAndSerializeObjects(ObjectMapper mapper) throws JsonProcessingException { - IgnoranceMixinOrIntrospection.Sedan sedan = new IgnoranceMixinOrIntrospection.Sedan("Mercedes-Benz", "S500", 5, 250.0); - IgnoranceMixinOrIntrospection.Crossover crossover = new IgnoranceMixinOrIntrospection.Crossover("BMW", "X6", 5, 250.0, 6000.0); - - List vehicles = new ArrayList<>(); - vehicles.add(sedan); - vehicles.add(crossover); - - return mapper.writeValueAsString(vehicles); - } -} \ No newline at end of file diff --git a/jackson-modules/jackson/src/test/java/com/ossez/jackson/inheritance/ItemIdRemovedFromUserUnitTest.java b/jackson-modules/jackson/src/test/java/com/ossez/jackson/inheritance/ItemIdRemovedFromUserUnitTest.java deleted file mode 100644 index 6e9c3f5136..0000000000 --- a/jackson-modules/jackson/src/test/java/com/ossez/jackson/inheritance/ItemIdRemovedFromUserUnitTest.java +++ /dev/null @@ -1,41 +0,0 @@ -package com.ossez.jackson.inheritance; - -import com.fasterxml.jackson.databind.ObjectMapper; -import org.junit.Test; - -import java.io.IOException; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; - -public class ItemIdRemovedFromUserUnitTest { - @Test - public void givenRemoveItemJson_whenDeserialize_shouldHaveProperClassType() throws IOException { - // given - Event event = new ItemIdRemovedFromUser("1", 12345567L, "item_1", 2L); - ObjectMapper objectMapper = new ObjectMapper(); - String eventJson = objectMapper.writeValueAsString(event); - - // when - Event result = new ObjectMapper().readValue(eventJson, Event.class); - - // then - assertTrue(result instanceof ItemIdRemovedFromUser); - assertEquals("item_1", ((ItemIdRemovedFromUser) result).getItemId()); - } - - @Test - public void givenAdddItemJson_whenSerialize_shouldIgnoreIdPropertyFromSuperclass() throws IOException { - // given - Event event = new ItemIdAddedToUser("1", 12345567L, "item_1", 2L); - ObjectMapper objectMapper = new ObjectMapper(); - - // when - String eventJson = objectMapper.writeValueAsString(event); - - // then - assertFalse(eventJson.contains("id")); - } - -} \ No newline at end of file diff --git a/jackson-modules/jackson/src/test/java/com/ossez/jackson/inheritance/SubTypeHandlingUnitTest.java b/jackson-modules/jackson/src/test/java/com/ossez/jackson/inheritance/SubTypeHandlingUnitTest.java deleted file mode 100644 index 3b95f7e283..0000000000 --- a/jackson-modules/jackson/src/test/java/com/ossez/jackson/inheritance/SubTypeHandlingUnitTest.java +++ /dev/null @@ -1,43 +0,0 @@ -package com.ossez.jackson.inheritance; - -import static org.junit.Assert.assertEquals; - -import org.junit.Test; - -import java.util.List; -import java.util.ArrayList; -import java.io.IOException; - -import com.fasterxml.jackson.databind.ObjectMapper; - -public class SubTypeHandlingUnitTest { - @Test - public void givenSubTypes_whenConvertingObjects_thenDataValuesArePreserved() { - ObjectMapper mapper = new ObjectMapper(); - - SubTypeConversionStructure.Car car = new SubTypeConversionStructure.Car("Mercedes-Benz", "S500", 5, 250.0); - SubTypeConversionStructure.Truck truck = mapper.convertValue(car, SubTypeConversionStructure.Truck.class); - - assertEquals("Mercedes-Benz", truck.getMake()); - assertEquals("S500", truck.getModel()); - } - - @Test - public void givenSubType_whenNotUsingNoArgsConstructors_thenSucceed() throws IOException { - ObjectMapper mapper = new ObjectMapper(); - mapper.enableDefaultTyping(); - - SubTypeConstructorStructure.Car car = new SubTypeConstructorStructure.Car("Mercedes-Benz", "S500", 5, 250.0); - SubTypeConstructorStructure.Truck truck = new SubTypeConstructorStructure.Truck("Isuzu", "NQR", 7500.0); - - List vehicles = new ArrayList<>(); - vehicles.add(car); - vehicles.add(truck); - - SubTypeConstructorStructure.Fleet serializedFleet = new SubTypeConstructorStructure.Fleet(); - serializedFleet.setVehicles(vehicles); - - String jsonDataString = mapper.writeValueAsString(serializedFleet); - mapper.readValue(jsonDataString, SubTypeConstructorStructure.Fleet.class); - } -} \ No newline at end of file diff --git a/jackson-modules/jackson/src/test/java/com/ossez/jackson/inheritance/TypeInfoInclusionUnitTest.java b/jackson-modules/jackson/src/test/java/com/ossez/jackson/inheritance/TypeInfoInclusionUnitTest.java deleted file mode 100644 index d47a2e4283..0000000000 --- a/jackson-modules/jackson/src/test/java/com/ossez/jackson/inheritance/TypeInfoInclusionUnitTest.java +++ /dev/null @@ -1,61 +0,0 @@ -package com.ossez.jackson.inheritance; - -import static org.junit.Assert.assertThat; -import static org.hamcrest.CoreMatchers.instanceOf; - -import org.junit.Test; - -import java.util.List; -import java.util.ArrayList; -import java.io.IOException; - -import com.fasterxml.jackson.databind.ObjectMapper; - -public class TypeInfoInclusionUnitTest { - @Test - public void givenTypeInfo_whenAnnotatingGlobally_thenTypesAreCorrectlyRecovered() throws IOException { - ObjectMapper mapper = new ObjectMapper(); - mapper.enableDefaultTyping(); - - TypeInfoStructure.Car car = new TypeInfoStructure.Car("Mercedes-Benz", "S500", 5, 250.0); - TypeInfoStructure.Truck truck = new TypeInfoStructure.Truck("Isuzu", "NQR", 7500.0); - - List vehicles = new ArrayList<>(); - vehicles.add(car); - vehicles.add(truck); - - TypeInfoStructure.Fleet serializedFleet = new TypeInfoStructure.Fleet(); - serializedFleet.setVehicles(vehicles); - - String jsonDataString = mapper.writeValueAsString(serializedFleet); - TypeInfoStructure.Fleet deserializedFleet = mapper.readValue(jsonDataString, TypeInfoStructure.Fleet.class); - - assertThat(deserializedFleet.getVehicles() - .get(0), instanceOf(TypeInfoStructure.Car.class)); - assertThat(deserializedFleet.getVehicles() - .get(1), instanceOf(TypeInfoStructure.Truck.class)); - } - - @Test - public void givenTypeInfo_whenAnnotatingPerClass_thenTypesAreCorrectlyRecovered() throws IOException { - ObjectMapper mapper = new ObjectMapper(); - - TypeInfoAnnotatedStructure.Car car = new TypeInfoAnnotatedStructure.Car("Mercedes-Benz", "S500", 5, 250.0); - TypeInfoAnnotatedStructure.Truck truck = new TypeInfoAnnotatedStructure.Truck("Isuzu", "NQR", 7500.0); - - List vehicles = new ArrayList<>(); - vehicles.add(car); - vehicles.add(truck); - - TypeInfoAnnotatedStructure.Fleet serializedFleet = new TypeInfoAnnotatedStructure.Fleet(); - serializedFleet.setVehicles(vehicles); - - String jsonDataString = mapper.writeValueAsString(serializedFleet); - TypeInfoAnnotatedStructure.Fleet deserializedFleet = mapper.readValue(jsonDataString, TypeInfoAnnotatedStructure.Fleet.class); - - assertThat(deserializedFleet.getVehicles() - .get(0), instanceOf(TypeInfoAnnotatedStructure.Car.class)); - assertThat(deserializedFleet.getVehicles() - .get(1), instanceOf(TypeInfoAnnotatedStructure.Truck.class)); - } -} \ No newline at end of file diff --git a/jackson-modules/jackson/src/test/java/com/ossez/jackson/jacksonvsgson/JacksonDeserializeUnitTest.java b/jackson-modules/jackson/src/test/java/com/ossez/jackson/jacksonvsgson/JacksonDeserializeUnitTest.java deleted file mode 100644 index 09ba00bac1..0000000000 --- a/jackson-modules/jackson/src/test/java/com/ossez/jackson/jacksonvsgson/JacksonDeserializeUnitTest.java +++ /dev/null @@ -1,38 +0,0 @@ -package com.ossez.jackson.jacksonvsgson; - -import java.io.IOException; -import java.text.DateFormat; -import java.text.SimpleDateFormat; -import org.junit.Test; -import com.fasterxml.jackson.databind.ObjectMapper; -import static org.junit.Assert.assertEquals; - -public class JacksonDeserializeUnitTest { - - @Test - public void whenSimpleDeserialize_thenCorrect() throws IOException { - - final String jsonInput = "{\"imdbId\":\"tt0472043\",\"actors\":[{\"imdbId\":\"nm2199632\",\"dateOfBirth\":\"1982-09-21T12:00:00+01:00\",\"filmography\":[\"Apocalypto\",\"Beatdown\",\"Wind Walkers\"]}]}"; - final ObjectMapper mapper = new ObjectMapper(); - final Movie movie = mapper.readValue(jsonInput, Movie.class); - - final String expectedOutput = "Movie [imdbId=tt0472043, director=null, actors=[ActorJackson [imdbId=nm2199632, dateOfBirth=Tue Sep 21 11:00:00 GMT 1982, filmography=[Apocalypto, Beatdown, Wind Walkers]]]]"; - assertEquals(expectedOutput, movie.toString()); - } - - @Test - public void whenCustomDeserialize_thenCorrect() throws IOException { - - final String jsonInput = "{\"imdbId\":\"tt0472043\",\"director\":\"Mel Gibson\",\"actors\":[{\"imdbId\":\"nm2199632\",\"dateOfBirth\":\"1982-09-21T12:00:00+01:00\",\"filmography\":[\"Apocalypto\",\"Beatdown\",\"Wind Walkers\"]}]}"; - - final ObjectMapper mapper = new ObjectMapper(); - final DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssXXX"); - mapper.setDateFormat(df); - - final Movie movie = mapper.readValue(jsonInput, Movie.class); - - final String expectedOutput = "Movie [imdbId=tt0472043, director=Mel Gibson, actors=[ActorJackson [imdbId=nm2199632, dateOfBirth=Tue Sep 21 11:00:00 GMT 1982, filmography=[Apocalypto, Beatdown, Wind Walkers]]]]"; - assertEquals(expectedOutput, movie.toString()); - } - -} diff --git a/jackson-modules/jackson/src/test/java/com/ossez/jackson/jacksonvsgson/JacksonSerializeUnitTest.java b/jackson-modules/jackson/src/test/java/com/ossez/jackson/jacksonvsgson/JacksonSerializeUnitTest.java deleted file mode 100644 index dccedfd1be..0000000000 --- a/jackson-modules/jackson/src/test/java/com/ossez/jackson/jacksonvsgson/JacksonSerializeUnitTest.java +++ /dev/null @@ -1,58 +0,0 @@ -package com.ossez.jackson.jacksonvsgson; - -import java.io.IOException; -import java.text.ParseException; -import java.text.SimpleDateFormat; -import java.util.Arrays; -import java.util.TimeZone; - -import org.junit.Assert; -import org.junit.Test; - -import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.core.util.DefaultPrettyPrinter; -import com.fasterxml.jackson.databind.ObjectMapper; -import com.fasterxml.jackson.databind.SerializationFeature; -import com.fasterxml.jackson.databind.module.SimpleModule; - -public class JacksonSerializeUnitTest { - - @Test - public void whenSimpleSerialize_thenCorrect() throws JsonProcessingException, ParseException { - - final SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy"); - sdf.setTimeZone(TimeZone.getTimeZone("GMT")); - - final ActorJackson rudyYoungblood = new ActorJackson("nm2199632", sdf.parse("21-09-1982"), Arrays.asList("Apocalypto", "Beatdown", "Wind Walkers")); - final Movie movie = new Movie("tt0472043", "Mel Gibson", Arrays.asList(rudyYoungblood)); - - final ObjectMapper mapper = new ObjectMapper(); - final String jsonResult = mapper.writeValueAsString(movie); - - final String expectedOutput = "{\"imdbId\":\"tt0472043\",\"director\":\"Mel Gibson\",\"actors\":[{\"imdbId\":\"nm2199632\",\"dateOfBirth\":401414400000,\"filmography\":[\"Apocalypto\",\"Beatdown\",\"Wind Walkers\"]}]}"; - Assert.assertEquals(jsonResult, expectedOutput); - } - - @Test - public void whenCustomSerialize_thenCorrect() throws ParseException, IOException { - - final SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy"); - - final ActorJackson rudyYoungblood = new ActorJackson("nm2199632", sdf.parse("21-09-1982"), Arrays.asList("Apocalypto", "Beatdown", "Wind Walkers")); - final MovieWithNullValue movieWithNullValue = new MovieWithNullValue(null, "Mel Gibson", Arrays.asList(rudyYoungblood)); - - final SimpleModule module = new SimpleModule(); - module.addSerializer(new ActorJacksonSerializer(ActorJackson.class)); - final ObjectMapper mapper = new ObjectMapper(); - - final String jsonResult = mapper.registerModule(module) - .writer(new DefaultPrettyPrinter()) - .writeValueAsString(movieWithNullValue); - - final Object json = mapper.readValue("{\"actors\":[{\"imdbId\":\"nm2199632\",\"dateOfBirth\":\"21-09-1982\",\"N° Film: \":3,\"filmography\":\"Apocalypto-Beatdown-Wind Walkers\"}],\"imdbID\":null}", Object.class); - final String expectedOutput = new ObjectMapper().enable(SerializationFeature.INDENT_OUTPUT) - .writeValueAsString(json); - - Assert.assertEquals(jsonResult, expectedOutput); - } -} diff --git a/jackson-modules/jackson/src/test/java/com/ossez/jackson/jsoncompare/JsonCompareUnitTest.java b/jackson-modules/jackson/src/test/java/com/ossez/jackson/jsoncompare/JsonCompareUnitTest.java deleted file mode 100644 index 7c21b79bc2..0000000000 --- a/jackson-modules/jackson/src/test/java/com/ossez/jackson/jsoncompare/JsonCompareUnitTest.java +++ /dev/null @@ -1,126 +0,0 @@ -package com.ossez.jackson.jsoncompare; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotEquals; -import static org.junit.Assert.assertTrue; - -import java.io.IOException; -import java.util.Comparator; - -import org.junit.Test; - -import com.fasterxml.jackson.databind.JsonNode; -import com.fasterxml.jackson.databind.ObjectMapper; -import com.fasterxml.jackson.databind.node.NumericNode; -import com.fasterxml.jackson.databind.node.TextNode; - -public class JsonCompareUnitTest { - - @Test - public void givenTwoSameJsonDataObjects_whenCompared_thenAreEqual() throws IOException { - ObjectMapper mapper = new ObjectMapper(); - - String s1 = "{\"employee\": {\"id\": \"1212\",\"fullName\": \"John Miles\", \"age\": 34 }}"; - String s2 = "{\"employee\": {\"id\": \"1212\",\"age\": 34, \"fullName\": \"John Miles\" }}"; - - JsonNode actualObj1 = mapper.readTree(s1); - JsonNode actualObj2 = mapper.readTree(s2); - - assertEquals(actualObj1, actualObj2); - - } - - @Test - public void givenTwoSameNestedJsonDataObjects_whenCompared_thenEqual() throws IOException { - ObjectMapper mapper = new ObjectMapper(); - - String s1 = "{\"employee\": {\"id\": \"1212\",\"fullName\": \"John Miles\",\"age\": 34, \"contact\":{\"email\": \"john@xyz.com\",\"phone\": \"9999999999\"} }}"; - String s2 = "{\"employee\": {\"id\": \"1212\",\"fullName\": \"John Miles\",\"age\": 34, \"contact\":{\"email\": \"john@xyz.com\",\"phone\": \"9999999999\"} }}"; - - JsonNode actualObj1 = mapper.readTree(s1); - JsonNode actualObj2 = mapper.readTree(s2); - - assertEquals(actualObj1, actualObj2); - - } - - @Test - public void givenTwoSameListJsonDataObjects_whenCompared_thenEqual() throws IOException { - ObjectMapper mapper = new ObjectMapper(); - - String s1 = "{\"employee\": {\"id\": \"1212\",\"fullName\": \"John Miles\",\"age\": 34, \"skills\":[\"Java\", \"C++\", \"Python\"] }}"; - String s2 = "{\"employee\": {\"id\": \"1212\",\"fullName\": \"John Miles\",\"age\": 34, \"skills\":[\"Java\", \"C++\", \"Python\"] }}"; - - JsonNode actualObj1 = mapper.readTree(s1); - JsonNode actualObj2 = mapper.readTree(s2); - - assertEquals(actualObj1, actualObj2); - - } - - @Test - public void givenTwoJsonDataObjects_whenComparedUsingCustomNumericNodeComparator_thenEqual() throws IOException { - ObjectMapper mapper = new ObjectMapper(); - - String s1 = "{\"name\": \"John\",\"score\":5.0}"; - String s2 = "{\"name\": \"John\",\"score\":5}"; - JsonNode actualObj1 = mapper.readTree(s1); - JsonNode actualObj2 = mapper.readTree(s2); - - NumericNodeComparator cmp = new NumericNodeComparator(); - - assertNotEquals(actualObj1, actualObj2); - assertTrue(actualObj1.equals(cmp, actualObj2)); - - } - - public class NumericNodeComparator implements Comparator { - @Override - public int compare(JsonNode o1, JsonNode o2) { - if (o1.equals(o2)) { - return 0; - } - if ((o1 instanceof NumericNode) && (o2 instanceof NumericNode)) { - Double d1 = ((NumericNode) o1).asDouble(); - Double d2 = ((NumericNode) o2).asDouble(); - if (d1.compareTo(d2) == 0) { - return 0; - } - } - return 1; - } - } - - @Test - public void givenTwoJsonDataObjects_whenComparedUsingCustomTextNodeComparator_thenEqual() throws IOException { - ObjectMapper mapper = new ObjectMapper(); - - String s1 = "{\"name\": \"JOHN\",\"score\":5}"; - String s2 = "{\"name\": \"John\",\"score\":5}"; - JsonNode actualObj1 = mapper.readTree(s1); - JsonNode actualObj2 = mapper.readTree(s2); - - TextNodeComparator cmp = new TextNodeComparator(); - - assertNotEquals(actualObj1, actualObj2); - assertTrue(actualObj1.equals(cmp, actualObj2)); - - } - - public class TextNodeComparator implements Comparator { - @Override - public int compare(JsonNode o1, JsonNode o2) { - if (o1.equals(o2)) { - return 0; - } - if ((o1 instanceof TextNode) && (o2 instanceof TextNode)) { - String s1 = ((TextNode) o1).asText(); - String s2 = ((TextNode) o2).asText(); - if (s1.equalsIgnoreCase(s2)) { - return 0; - } - } - return 1; - } - } -} diff --git a/jackson-modules/jackson/src/test/java/com/ossez/jackson/node/ExampleStructure.java b/jackson-modules/jackson/src/test/java/com/ossez/jackson/node/ExampleStructure.java deleted file mode 100644 index 79fc5760c1..0000000000 --- a/jackson-modules/jackson/src/test/java/com/ossez/jackson/node/ExampleStructure.java +++ /dev/null @@ -1,18 +0,0 @@ -package com.ossez.jackson.node; - -import java.io.IOException; -import java.io.InputStream; - -import com.fasterxml.jackson.databind.JsonNode; -import com.fasterxml.jackson.databind.ObjectMapper; - -public class ExampleStructure { - private static ObjectMapper mapper = new ObjectMapper(); - - static JsonNode getExampleRoot() throws IOException { - InputStream exampleInput = ExampleStructure.class.getClassLoader() - .getResourceAsStream("node_example.json"); - JsonNode rootNode = mapper.readTree(exampleInput); - return rootNode; - } -} \ No newline at end of file diff --git a/jackson-modules/jackson/src/test/java/com/ossez/jackson/node/JsonNodeIteratorUnitTest.java b/jackson-modules/jackson/src/test/java/com/ossez/jackson/node/JsonNodeIteratorUnitTest.java deleted file mode 100644 index b80011e96e..0000000000 --- a/jackson-modules/jackson/src/test/java/com/ossez/jackson/node/JsonNodeIteratorUnitTest.java +++ /dev/null @@ -1,37 +0,0 @@ -package com.ossez.jackson.node; - -import static org.junit.Assert.assertEquals; - -import java.io.IOException; - -import org.junit.Test; - -import com.fasterxml.jackson.databind.JsonNode; - -public class JsonNodeIteratorUnitTest { - - private JsonNodeIterator onTest = new JsonNodeIterator(); - private static String expectedYaml = "name: \n" + - " first: Tatu\n" + - " last: Saloranta\n" + - "title: Jackson founder\n" + - "company: FasterXML\n" + - "pets: \n" + - "- type: dog\n" + - " number: 1\n" + - "- type: fish\n" + - " number: 50"; - -@Test -public void givenANodeTree_whenIteratingSubNodes_thenWeFindExpected() throws IOException { - final JsonNode rootNode = ExampleStructure.getExampleRoot(); - - String yaml = onTest.toYaml(rootNode); - System.out.println(yaml.toString()); - - assertEquals(expectedYaml, yaml); - -} - - -} diff --git a/jackson-modules/jackson/src/test/java/com/ossez/jackson/node/NodeBean.java b/jackson-modules/jackson/src/test/java/com/ossez/jackson/node/NodeBean.java deleted file mode 100644 index bd38487f1f..0000000000 --- a/jackson-modules/jackson/src/test/java/com/ossez/jackson/node/NodeBean.java +++ /dev/null @@ -1,30 +0,0 @@ -package com.ossez.jackson.node; - -public class NodeBean { - private int id; - private String name; - - public NodeBean() { - } - - public NodeBean(int id, String name) { - this.id = id; - this.name = name; - } - - public int getId() { - return id; - } - - public void setId(int id) { - this.id = id; - } - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } -} diff --git a/jackson-modules/jackson/src/test/java/com/ossez/jackson/node/NodeOperationUnitTest.java b/jackson-modules/jackson/src/test/java/com/ossez/jackson/node/NodeOperationUnitTest.java deleted file mode 100644 index 4e801e6ed9..0000000000 --- a/jackson-modules/jackson/src/test/java/com/ossez/jackson/node/NodeOperationUnitTest.java +++ /dev/null @@ -1,119 +0,0 @@ -package com.ossez.jackson.node; - -import static org.hamcrest.CoreMatchers.containsString; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.assertTrue; - -import java.io.FileReader; -import java.io.FileWriter; -import java.io.IOException; -import java.nio.file.Files; -import java.nio.file.Paths; - -import org.junit.Test; - -import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.databind.JsonNode; -import com.fasterxml.jackson.databind.ObjectMapper; -import com.fasterxml.jackson.databind.node.ObjectNode; - -public class NodeOperationUnitTest { - private static ObjectMapper mapper = new ObjectMapper(); - - @Test - public void givenAnObject_whenConvertingIntoNode_thenCorrect() { - final NodeBean fromValue = new NodeBean(2016, "baeldung.com"); - - final JsonNode node = mapper.valueToTree(fromValue); - - assertEquals(2016, node.get("id") - .intValue()); - assertEquals("baeldung.com", node.get("name") - .textValue()); - } - - @Test - public void givenANode_whenWritingOutAsAJsonString_thenCorrect() throws IOException { - final String pathToTestFile = "node_to_json_test.json"; - final char[] characterBuffer = new char[50]; - - final JsonNode node = mapper.createObjectNode(); - ((ObjectNode) node).put("id", 2016); - ((ObjectNode) node).put("name", "baeldung.com"); - - try (FileWriter outputStream = new FileWriter(pathToTestFile)) { - mapper.writeValue(outputStream, node); - } - - try (FileReader inputStreamForAssertion = new FileReader(pathToTestFile)) { - inputStreamForAssertion.read(characterBuffer); - } - final String textContentOfTestFile = new String(characterBuffer); - - assertThat(textContentOfTestFile, containsString("2016")); - assertThat(textContentOfTestFile, containsString("baeldung.com")); - - Files.delete(Paths.get(pathToTestFile)); - } - - @Test - public void givenANode_whenConvertingIntoAnObject_thenCorrect() throws JsonProcessingException { - final JsonNode node = mapper.createObjectNode(); - ((ObjectNode) node).put("id", 2016); - ((ObjectNode) node).put("name", "baeldung.com"); - - final NodeBean toValue = mapper.treeToValue(node, NodeBean.class); - - assertEquals(2016, toValue.getId()); - assertEquals("baeldung.com", toValue.getName()); - } - - @Test - public void givenANode_whenAddingIntoATree_thenCorrect() throws IOException { - final JsonNode rootNode = ExampleStructure.getExampleRoot(); - final ObjectNode addedNode = ((ObjectNode) rootNode).putObject("address"); - addedNode.put("city", "Seattle") - .put("state", "Washington") - .put("country", "United States"); - - assertFalse(rootNode.path("address") - .isMissingNode()); - assertEquals("Seattle", rootNode.path("address") - .path("city") - .textValue()); - assertEquals("Washington", rootNode.path("address") - .path("state") - .textValue()); - assertEquals("United States", rootNode.path("address") - .path("country") - .textValue()); - } - - @Test - public void givenANode_whenModifyingIt_thenCorrect() throws IOException { - final String newString = "{\"nick\": \"cowtowncoder\"}"; - final JsonNode newNode = mapper.readTree(newString); - - final JsonNode rootNode = ExampleStructure.getExampleRoot(); - ((ObjectNode) rootNode).set("name", newNode); - - assertFalse(rootNode.path("name") - .path("nick") - .isMissingNode()); - assertEquals("cowtowncoder", rootNode.path("name") - .path("nick") - .textValue()); - } - - @Test - public void givenANode_whenRemovingFromATree_thenCorrect() throws IOException { - final JsonNode rootNode = ExampleStructure.getExampleRoot(); - ((ObjectNode) rootNode).remove("company"); - - assertTrue(rootNode.path("company") - .isMissingNode()); - } - -} diff --git a/jackson-modules/jackson/src/test/java/com/ossez/jackson/optionalwithjackson/OptionalTypeUnitTest.java b/jackson-modules/jackson/src/test/java/com/ossez/jackson/optionalwithjackson/OptionalTypeUnitTest.java deleted file mode 100644 index 89611a74d0..0000000000 --- a/jackson-modules/jackson/src/test/java/com/ossez/jackson/optionalwithjackson/OptionalTypeUnitTest.java +++ /dev/null @@ -1,61 +0,0 @@ -package com.ossez.jackson.optionalwithjackson; - -import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.databind.ObjectMapper; -import com.fasterxml.jackson.datatype.jdk8.Jdk8Module; -import static io.restassured.path.json.JsonPath.from; -import java.io.IOException; -import java.util.Optional; -import static org.assertj.core.api.Assertions.assertThat; -import org.junit.Test; - -public class OptionalTypeUnitTest { - - ObjectMapper mapper = new ObjectMapper().registerModule(new Jdk8Module()); - - @Test - public void givenPresentOptional_whenSerializing_thenValueInJson() throws JsonProcessingException { - - String subTitle = "The Parish Boy's Progress"; - Book book = new Book(); - book.setTitle("Oliver Twist"); - book.setSubTitle(Optional.of(subTitle)); - - String result = mapper.writeValueAsString(book); - - assertThat(from(result).getString("subTitle")).isEqualTo(subTitle); - } - - @Test - public void givenEmptyOptional_whenSerializing_thenNullValue() throws JsonProcessingException { - - Book book = new Book(); - book.setTitle("Oliver Twist"); - book.setSubTitle(Optional.empty()); - - String result = mapper.writeValueAsString(book); - - assertThat(from(result).getString("subTitle")).isNull(); - } - - @Test - public void givenField_whenDeserializingIntoOptional_thenIsPresentWithValue() throws IOException { - - String subTitle = "The Parish Boy's Progress"; - String book = "{ \"title\": \"Oliver Twist\", \"subTitle\": \"" + subTitle + "\" }"; - - Book result = mapper.readValue(book, Book.class); - - assertThat(result.getSubTitle()).isEqualTo(Optional.of(subTitle)); - } - - @Test - public void givenNullField_whenDeserializingIntoOptional_thenIsEmpty() throws IOException { - - String book = "{ \"title\": \"Oliver Twist\", \"subTitle\": null }"; - - Book result = mapper.readValue(book, Book.class); - - assertThat(result.getSubTitle()).isEmpty(); - } -} diff --git a/jackson-modules/jackson/src/test/java/com/ossez/jackson/sandbox/JacksonPrettyPrintUnitTest.java b/jackson-modules/jackson/src/test/java/com/ossez/jackson/sandbox/JacksonPrettyPrintUnitTest.java deleted file mode 100644 index 81278f2fd0..0000000000 --- a/jackson-modules/jackson/src/test/java/com/ossez/jackson/sandbox/JacksonPrettyPrintUnitTest.java +++ /dev/null @@ -1,50 +0,0 @@ -package com.ossez.jackson.sandbox; - -import java.io.File; -import java.io.IOException; -import java.nio.ByteBuffer; -import java.nio.charset.Charset; -import java.nio.charset.StandardCharsets; -import java.nio.file.Files; -import java.nio.file.Paths; - -import org.junit.Test; - -import com.fasterxml.jackson.core.JsonParseException; -import com.fasterxml.jackson.databind.JsonMappingException; -import com.fasterxml.jackson.databind.ObjectMapper; - -public class JacksonPrettyPrintUnitTest { - - @Test - public final void whenDeserializing_thenCorrect() throws JsonParseException, JsonMappingException, IOException { - // final String fileName = "src/main/resources/example1.json"; - final String fileName = "src/main/resources/example1.json"; - - new File(fileName); - - printJsonFromFile(fileName); - } - - // - - public static void printJsonFromFile(final String fileName) { - System.out.println("-----------------"); - final ObjectMapper mapper = new ObjectMapper(); - try { - final Object json = mapper.readValue(readFile(fileName, StandardCharsets.UTF_8), Object.class); - System.out.println(mapper.writerWithDefaultPrettyPrinter() - .writeValueAsString(json)); - } catch (final IOException e) { - e.printStackTrace(); - } - System.out.println("-----------------"); - } - - static String readFile(final String path, final Charset encoding) throws IOException { - final byte[] encoded = Files.readAllBytes(Paths.get(path)); - return encoding.decode(ByteBuffer.wrap(encoded)) - .toString(); - } - -} diff --git a/jackson-modules/jackson/src/test/java/com/ossez/jackson/sandbox/SandboxUnitTest.java b/jackson-modules/jackson/src/test/java/com/ossez/jackson/sandbox/SandboxUnitTest.java deleted file mode 100644 index 3c67ae9bad..0000000000 --- a/jackson-modules/jackson/src/test/java/com/ossez/jackson/sandbox/SandboxUnitTest.java +++ /dev/null @@ -1,29 +0,0 @@ -package com.ossez.jackson.sandbox; - -import java.io.IOException; - -import org.junit.Test; - -import com.fasterxml.jackson.annotation.JsonAutoDetect; -import com.fasterxml.jackson.core.JsonParseException; -import com.fasterxml.jackson.databind.JsonMappingException; -import com.fasterxml.jackson.databind.ObjectMapper; - -public class SandboxUnitTest { - - @Test - public final void whenDeserializing_thenCorrect() throws JsonParseException, JsonMappingException, IOException { - final TestElement testElement = new TestElement(); - testElement.setX(10); - testElement.setY("adasd"); - final ObjectMapper om = new ObjectMapper(); - om.setVisibility(om.getSerializationConfig() - .getDefaultVisibilityChecker() - .withFieldVisibility(JsonAutoDetect.Visibility.ANY) - .withGetterVisibility(JsonAutoDetect.Visibility.NONE)); - - final String serialized = om.writeValueAsString(testElement); - System.err.println(serialized); - } - -} diff --git a/jackson-modules/jackson/src/test/java/com/ossez/jackson/sandbox/TestElement.java b/jackson-modules/jackson/src/test/java/com/ossez/jackson/sandbox/TestElement.java deleted file mode 100644 index 8d44842054..0000000000 --- a/jackson-modules/jackson/src/test/java/com/ossez/jackson/sandbox/TestElement.java +++ /dev/null @@ -1,25 +0,0 @@ -package com.ossez.jackson.sandbox; - -public class TestElement { - - int x; - - private transient String y; - - public int getX() { - return x; - } - - public void setX(final int x) { - this.x = x; - } - - public String getY() { - return y; - } - - public void setY(final String y) { - this.y = y; - } - -} \ No newline at end of file diff --git a/jackson-modules/jackson/src/test/java/com/ossez/jackson/test/UnitTestSuite.java b/jackson-modules/jackson/src/test/java/com/ossez/jackson/test/UnitTestSuite.java deleted file mode 100644 index 5f715ec599..0000000000 --- a/jackson-modules/jackson/src/test/java/com/ossez/jackson/test/UnitTestSuite.java +++ /dev/null @@ -1,14 +0,0 @@ -package com.ossez.jackson.test; - -import com.ossez.jackson.sandbox.JacksonPrettyPrintUnitTest; -import com.ossez.jackson.sandbox.SandboxUnitTest; -import org.junit.runner.RunWith; -import org.junit.runners.Suite; - -@RunWith(Suite.class) -@Suite.SuiteClasses({ // @formatter:off - JacksonPrettyPrintUnitTest.class - , SandboxUnitTest.class -}) // @formatter:on -public class UnitTestSuite { -} \ No newline at end of file diff --git a/jackson-modules/jackson/src/test/java/com/ossez/jackson/try1/IEntity.java b/jackson-modules/jackson/src/test/java/com/ossez/jackson/try1/IEntity.java deleted file mode 100644 index cc2269ad96..0000000000 --- a/jackson-modules/jackson/src/test/java/com/ossez/jackson/try1/IEntity.java +++ /dev/null @@ -1,5 +0,0 @@ -package com.ossez.jackson.try1; - -public interface IEntity { - public int getId(); -} \ No newline at end of file diff --git a/jackson-modules/jackson/src/test/java/com/ossez/jackson/try1/RestLoaderRequest.java b/jackson-modules/jackson/src/test/java/com/ossez/jackson/try1/RestLoaderRequest.java deleted file mode 100644 index fdeac9b7a3..0000000000 --- a/jackson-modules/jackson/src/test/java/com/ossez/jackson/try1/RestLoaderRequest.java +++ /dev/null @@ -1,38 +0,0 @@ -package com.ossez.jackson.try1; - -import java.io.Serializable; - -import com.fasterxml.jackson.databind.annotation.JsonDeserialize; - -@JsonDeserialize(using = RestLoaderRequestDeserializer.class) -// @Produces(MediaType.APPLICATION_JSON) -public class RestLoaderRequest implements Serializable { - private T entity; // entity to load field to - private String className; // actual class of entity - private String fieldName; // fieldName to lazy REST load - - public String getFieldName() { - return fieldName; - } - - public void setFieldName(final String fieldName) { - this.fieldName = fieldName; - } - - public String getClassName() { - return className; - } - - public void setClassName(final String className) { - this.className = className; - } - - public T getEntity() { - return entity; - } - - public void setEntity(final T entity) { - this.entity = entity; - } - -} \ No newline at end of file diff --git a/jackson-modules/jackson/src/test/java/com/ossez/jackson/try1/RestLoaderRequestDeserializer.java b/jackson-modules/jackson/src/test/java/com/ossez/jackson/try1/RestLoaderRequestDeserializer.java deleted file mode 100644 index b49d6b1d8e..0000000000 --- a/jackson-modules/jackson/src/test/java/com/ossez/jackson/try1/RestLoaderRequestDeserializer.java +++ /dev/null @@ -1,48 +0,0 @@ -package com.ossez.jackson.try1; - -import java.io.IOException; - -import com.fasterxml.jackson.core.JsonParser; -import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.core.ObjectCodec; -import com.fasterxml.jackson.databind.DeserializationContext; -import com.fasterxml.jackson.databind.JsonNode; -import com.fasterxml.jackson.databind.deser.std.StdDeserializer; - -public class RestLoaderRequestDeserializer extends StdDeserializer> { - private static final long serialVersionUID = -4245207329377196889L; - - public RestLoaderRequestDeserializer() { - this(null); - } - - public RestLoaderRequestDeserializer(final Class vc) { - super(vc); - } - - @Override - public RestLoaderRequest deserialize(final JsonParser jp, final DeserializationContext ctxt) throws IOException, JsonProcessingException { - try { - final ObjectCodec objectCodec = jp.getCodec(); - final JsonNode node = objectCodec.readTree(jp); - final String className = node.get("className") - .textValue(); - final String fieldName = node.get("fieldName") - .textValue(); - - final Class clazz = Class.forName(className); - - final JsonNode rawEntityNode = node.get("entity"); - // How to deserialize rawEntityNode to T based on className ? - - final RestLoaderRequest request = new RestLoaderRequest(); - request.setClassName(className); - request.setFieldName(fieldName); - } catch (final ClassNotFoundException e) { - e.printStackTrace(); - } - - return null; - } - -} \ No newline at end of file diff --git a/jackson-modules/jackson/src/test/resources/author-jsonpropertyorder-schema.json b/jackson-modules/jackson/src/test/resources/author-jsonpropertyorder-schema.json deleted file mode 100644 index 8e7a85372c..0000000000 --- a/jackson-modules/jackson/src/test/resources/author-jsonpropertyorder-schema.json +++ /dev/null @@ -1,29 +0,0 @@ -{ - "$schema": "http://json-schema.org/draft-04/schema#", - "title": "Author", - "description": "An author", - "type": "object", - "properties": { - "items": { - "type": "array", - "items": { - "type": "object" - } - }, - "firstName": { - "type": "string" - }, - "lastName": { - "type": "string" - }, - "id": { - "type": "string" - } - }, - "required": [ - "items", - "firstName", - "lastName", - "id" - ] -} \ No newline at end of file diff --git a/jackson-modules/jackson/src/test/resources/node_example-1.json b/jackson-modules/jackson/src/test/resources/node_example-1.json deleted file mode 100644 index e766981a50..0000000000 --- a/jackson-modules/jackson/src/test/resources/node_example-1.json +++ /dev/null @@ -1,65 +0,0 @@ -{ - "rootEquipmentId": "830AFC79-E36E-41A4-8944-BDB71EEEC7AF", - "equipmentId": "7C82F833-A495-42E7-8CBE-2CEC42992DD1", - "startTime": "2021-09-01T00:00:00.000Z", - "endTime": "2021-09-01T03:00:00.000Z", - "testMaxBins": 36, - "testData": [ - { - "version": "v1", - "timestamp": "2021-09-01T00:40:00.000Z", - "event": { - "AlertType": "kpi", - "AlertId": "6B341AB0-971D-494E-9522-A23500BF7C9D", - "SourceAspectId": "80CB7FE9-9762-48C0-8027-CBE3EC517D0D", - "State": "INSUFFICIENT", - "SourceId": "7C82F833-A495-42E7-8CBE-2CEC42992DD1", - "Period": 1800, - "Severity": "1", - "SourceAspectName": "TagName" - } - }, - { - "version": "v1", - "timestamp": "2021-09-01T01:10:00.000Z", - "event": { - "AlertType": "kpi", - "AlertId": "6B341AB0-971D-494E-9522-A23500BF7C9D", - "SourceAspectId": "80CB7FE9-9762-48C0-8027-CBE3EC517D0D", - "State": "INSUFFICIENT", - "SourceId": "7C82F833-A495-42E7-8CBE-2CEC42992DD1", - "Period": 1800, - "Severity": "1", - "SourceAspectName": "TagName" - } - }, - { - "version": "v1", - "timestamp": "2021-09-01T02:10:00.000Z", - "event": { - "AlertType": "kpi", - "AlertId": "6B341AB0-971D-494E-9522-A23500BF7C9D", - "SourceAspectId": "80CB7FE9-9762-48C0-8027-CBE3EC517D0D", - "State": "OK", - "SourceId": "7C82F833-A495-42E7-8CBE-2CEC42992DD1", - "Period": 1800, - "Severity": "1", - "SourceAspectName": "TagName" - } - }, - { - "version": "v1", - "timestamp": "2021-09-01T02:40:00.000Z", - "event": { - "AlertType": "kpi", - "AlertId": "6B341AB0-971D-494E-9522-A23500BF7C9D", - "SourceAspectId": "80CB7FE9-9762-48C0-8027-CBE3EC517D0D", - "State": "OK", - "SourceId": "7C82F833-A495-42E7-8CBE-2CEC42992DD1", - "Period": 1800, - "Severity": "1", - "SourceAspectName": "TagName" - } - } - ] -} diff --git a/jackson-modules/jackson/src/test/resources/node_example.json b/jackson-modules/jackson/src/test/resources/node_example.json deleted file mode 100644 index d57c1df6e3..0000000000 --- a/jackson-modules/jackson/src/test/resources/node_example.json +++ /dev/null @@ -1,18 +0,0 @@ -{ - "name": { - "first": "Tatu", - "last": "Saloranta" - }, - "title": "Jackson founder", - "company": "FasterXML", - "pets": [ - { - "type": "dog", - "number": 1 - }, - { - "type": "fish", - "number": 50 - } - ] -} \ No newline at end of file diff --git a/jackson-modules/pom.xml b/jackson-modules/pom.xml deleted file mode 100644 index 69ac41998d..0000000000 --- a/jackson-modules/pom.xml +++ /dev/null @@ -1,56 +0,0 @@ - - - 4.0.0 - jackson-modules - jackson-modules - pom - - - com.ossez - parent-java - 0.0.2-SNAPSHOT - ../parent-java - - - - jackson - jackson-annotations - jackson-conversions - jackson-conversions-2 - jackson-custom-conversions - jackson-exceptions - - - - - com.fasterxml.jackson.core - jackson-databind - ${jackson.version} - - - - com.fasterxml.jackson.dataformat - jackson-dataformat-xml - ${jackson.version} - - - org.junit.jupiter - junit-jupiter - ${junit-jupiter.version} - - - - org.junit.vintage - junit-vintage-engine - ${junit-jupiter.version} - test - - - - - 5.6.2 - - - \ No newline at end of file diff --git a/jackson-simple/README.md b/jackson-simple/README.md deleted file mode 100644 index 41aee8cac9..0000000000 --- a/jackson-simple/README.md +++ /dev/null @@ -1,19 +0,0 @@ -### Jackson Articles that are also part of the e-book - -This module contains articles about Jackson that are also part of the Jackson Ebook. - -### The Course - -The "REST With Spring" Classes: http://bit.ly/restwithspring - -### Relevant Articles: -- [Jackson Annotation Examples](https://www.baeldung.com/jackson-annotations) -- [Intro to the Jackson ObjectMapper](https://www.baeldung.com/jackson-object-mapper-tutorial) -- [Jackson Ignore Properties on Marshalling](https://www.baeldung.com/jackson-ignore-properties-on-serialization) -- [Ignore Null Fields with Jackson](https://www.baeldung.com/jackson-ignore-null-fields) -- [Jackson – Change Name of Field](https://www.baeldung.com/jackson-name-of-property) -- [Jackson Unmarshalling JSON with Unknown Properties](https://www.baeldung.com/jackson-deserialize-json-unknown-properties) - -### NOTE: - -Since this is a module tied to an e-book, it should **not** be moved or used to store the code for any further article. diff --git a/jackson-simple/pom.xml b/jackson-simple/pom.xml deleted file mode 100644 index 9bc90180fd..0000000000 --- a/jackson-simple/pom.xml +++ /dev/null @@ -1,36 +0,0 @@ - - - 4.0.0 - jackson-simple - 0.0.1-SNAPSHOT - jackson-simple - - - com.ossez - parent-java - 0.0.2-SNAPSHOT - ../parent-java - - - - - - com.fasterxml.jackson.dataformat - jackson-dataformat-xml - ${jackson.version} - - - - - jackson-simple - - - src/main/resources - true - - - - - \ No newline at end of file diff --git a/jackson-simple/src/main/java/com/ossez/jackson/annotation/AliasBean.java b/jackson-simple/src/main/java/com/ossez/jackson/annotation/AliasBean.java deleted file mode 100644 index 34d8fb63b6..0000000000 --- a/jackson-simple/src/main/java/com/ossez/jackson/annotation/AliasBean.java +++ /dev/null @@ -1,31 +0,0 @@ -package com.ossez.jackson.annotation; - -import com.fasterxml.jackson.annotation.JsonAlias; - -public class AliasBean { - - @JsonAlias({ "fName", "f_name" }) - private String firstName; - - private String lastName; - - public AliasBean() { - - } - - public String getFirstName() { - return firstName; - } - - public void setFirstName(String firstName) { - this.firstName = firstName; - } - - public String getLastName() { - return lastName; - } - - public void setLastName(String lastName) { - this.lastName = lastName; - } -} diff --git a/jackson-simple/src/main/java/com/ossez/jackson/annotation/BeanWithCreator.java b/jackson-simple/src/main/java/com/ossez/jackson/annotation/BeanWithCreator.java deleted file mode 100644 index 1474ded43b..0000000000 --- a/jackson-simple/src/main/java/com/ossez/jackson/annotation/BeanWithCreator.java +++ /dev/null @@ -1,15 +0,0 @@ -package com.ossez.jackson.annotation; - -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonProperty; - -public class BeanWithCreator { - public int id; - public String name; - - @JsonCreator - public BeanWithCreator(@JsonProperty("id") final int id, @JsonProperty("theName") final String name) { - this.id = id; - this.name = name; - } -} diff --git a/jackson-simple/src/main/java/com/ossez/jackson/annotation/BeanWithCustomAnnotation.java b/jackson-simple/src/main/java/com/ossez/jackson/annotation/BeanWithCustomAnnotation.java deleted file mode 100644 index f9ad44a0a1..0000000000 --- a/jackson-simple/src/main/java/com/ossez/jackson/annotation/BeanWithCustomAnnotation.java +++ /dev/null @@ -1,37 +0,0 @@ -package com.ossez.jackson.annotation; - -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; -import java.util.Date; - -import com.ossez.jackson.annotation.BeanWithCustomAnnotation.CustomAnnotation; - -import com.fasterxml.jackson.annotation.JacksonAnnotationsInside; -import com.fasterxml.jackson.annotation.JsonInclude; -import com.fasterxml.jackson.annotation.JsonInclude.Include; -import com.fasterxml.jackson.annotation.JsonPropertyOrder; - -@CustomAnnotation -public class BeanWithCustomAnnotation { - public int id; - public String name; - public Date dateCreated; - - public BeanWithCustomAnnotation() { - - } - - public BeanWithCustomAnnotation(final int id, final String name, final Date dateCreated) { - this.id = id; - this.name = name; - this.dateCreated = dateCreated; - } - - @Retention(RetentionPolicy.RUNTIME) - @JacksonAnnotationsInside - @JsonInclude(Include.NON_NULL) - @JsonPropertyOrder({ "name", "id", "dateCreated" }) - public @interface CustomAnnotation { - - } -} diff --git a/jackson-simple/src/main/java/com/ossez/jackson/annotation/BeanWithFilter.java b/jackson-simple/src/main/java/com/ossez/jackson/annotation/BeanWithFilter.java deleted file mode 100644 index 6c8ec92ff1..0000000000 --- a/jackson-simple/src/main/java/com/ossez/jackson/annotation/BeanWithFilter.java +++ /dev/null @@ -1,18 +0,0 @@ -package com.ossez.jackson.annotation; - -import com.fasterxml.jackson.annotation.JsonFilter; - -@JsonFilter("myFilter") -public class BeanWithFilter { - public int id; - public String name; - - public BeanWithFilter() { - - } - - public BeanWithFilter(final int id, final String name) { - this.id = id; - this.name = name; - } -} diff --git a/jackson-simple/src/main/java/com/ossez/jackson/annotation/BeanWithGetter.java b/jackson-simple/src/main/java/com/ossez/jackson/annotation/BeanWithGetter.java deleted file mode 100644 index 169a7cbfbc..0000000000 --- a/jackson-simple/src/main/java/com/ossez/jackson/annotation/BeanWithGetter.java +++ /dev/null @@ -1,31 +0,0 @@ -package com.ossez.jackson.annotation; - -import com.fasterxml.jackson.annotation.JsonGetter; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.annotation.JsonSetter; - -public class BeanWithGetter { - public int id; - private String name; - - public BeanWithGetter() { - - } - - public BeanWithGetter(final int id, final String name) { - this.id = id; - this.name = name; - } - - @JsonProperty("name") - @JsonSetter("name") - public void setTheName(final String name) { - this.name = name; - } - - @JsonProperty("name") - @JsonGetter("name") - public String getTheName() { - return name; - } -} diff --git a/jackson-simple/src/main/java/com/ossez/jackson/annotation/BeanWithIgnore.java b/jackson-simple/src/main/java/com/ossez/jackson/annotation/BeanWithIgnore.java deleted file mode 100644 index 55ae8b79db..0000000000 --- a/jackson-simple/src/main/java/com/ossez/jackson/annotation/BeanWithIgnore.java +++ /dev/null @@ -1,20 +0,0 @@ -package com.ossez.jackson.annotation; - -import com.fasterxml.jackson.annotation.JsonIgnore; -import com.fasterxml.jackson.annotation.JsonIgnoreProperties; - -@JsonIgnoreProperties({ "id" }) -public class BeanWithIgnore { - @JsonIgnore - public int id; - public String name; - - public BeanWithIgnore() { - - } - - public BeanWithIgnore(final int id, final String name) { - this.id = id; - this.name = name; - } -} diff --git a/jackson-simple/src/main/java/com/ossez/jackson/annotation/BeanWithInject.java b/jackson-simple/src/main/java/com/ossez/jackson/annotation/BeanWithInject.java deleted file mode 100644 index f0ea4166a8..0000000000 --- a/jackson-simple/src/main/java/com/ossez/jackson/annotation/BeanWithInject.java +++ /dev/null @@ -1,18 +0,0 @@ -package com.ossez.jackson.annotation; - -import com.fasterxml.jackson.annotation.JacksonInject; - -public class BeanWithInject { - @JacksonInject - public int id; - public String name; - - public BeanWithInject() { - - } - - public BeanWithInject(final int id, final String name) { - this.id = id; - this.name = name; - } -} diff --git a/jackson-simple/src/main/java/com/ossez/jackson/annotation/ExtendableBean.java b/jackson-simple/src/main/java/com/ossez/jackson/annotation/ExtendableBean.java deleted file mode 100644 index 650cc45530..0000000000 --- a/jackson-simple/src/main/java/com/ossez/jackson/annotation/ExtendableBean.java +++ /dev/null @@ -1,31 +0,0 @@ -package com.ossez.jackson.annotation; - -import java.util.HashMap; -import java.util.Map; - -import com.fasterxml.jackson.annotation.JsonAnyGetter; -import com.fasterxml.jackson.annotation.JsonAnySetter; - -public class ExtendableBean { - public String name; - private Map properties; - - public ExtendableBean() { - properties = new HashMap(); - } - - public ExtendableBean(final String name) { - this.name = name; - properties = new HashMap(); - } - - @JsonAnySetter - public void add(final String key, final String value) { - properties.put(key, value); - } - - @JsonAnyGetter - public Map getProperties() { - return properties; - } -} diff --git a/jackson-simple/src/main/java/com/ossez/jackson/annotation/MyBean.java b/jackson-simple/src/main/java/com/ossez/jackson/annotation/MyBean.java deleted file mode 100644 index edb773a6ef..0000000000 --- a/jackson-simple/src/main/java/com/ossez/jackson/annotation/MyBean.java +++ /dev/null @@ -1,33 +0,0 @@ -package com.ossez.jackson.annotation; - -import com.fasterxml.jackson.annotation.JsonGetter; -import com.fasterxml.jackson.annotation.JsonInclude; -import com.fasterxml.jackson.annotation.JsonInclude.Include; -import com.fasterxml.jackson.annotation.JsonPropertyOrder; -import com.fasterxml.jackson.annotation.JsonSetter; - -@JsonInclude(Include.NON_NULL) -@JsonPropertyOrder({ "name", "id" }) -public class MyBean { - public int id; - public String name; - - public MyBean() { - - } - - public MyBean(final int id, final String name) { - this.id = id; - this.name = name; - } - - @JsonGetter("name") - public String getTheName() { - return name; - } - - @JsonSetter("name") - public void setTheName(String name) { - this.name = name; - } -} diff --git a/jackson-simple/src/main/java/com/ossez/jackson/annotation/PrivateBean.java b/jackson-simple/src/main/java/com/ossez/jackson/annotation/PrivateBean.java deleted file mode 100644 index b2bf8782f0..0000000000 --- a/jackson-simple/src/main/java/com/ossez/jackson/annotation/PrivateBean.java +++ /dev/null @@ -1,19 +0,0 @@ -package com.ossez.jackson.annotation; - -import com.fasterxml.jackson.annotation.JsonAutoDetect; -import com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility; - -@JsonAutoDetect(fieldVisibility = Visibility.ANY) -public class PrivateBean { - private int id; - private String name; - - public PrivateBean() { - - } - - public PrivateBean(final int id, final String name) { - this.id = id; - this.name = name; - } -} diff --git a/jackson-simple/src/main/java/com/ossez/jackson/annotation/RawBean.java b/jackson-simple/src/main/java/com/ossez/jackson/annotation/RawBean.java deleted file mode 100644 index 739e556ee0..0000000000 --- a/jackson-simple/src/main/java/com/ossez/jackson/annotation/RawBean.java +++ /dev/null @@ -1,19 +0,0 @@ -package com.ossez.jackson.annotation; - -import com.fasterxml.jackson.annotation.JsonRawValue; - -public class RawBean { - public String name; - - @JsonRawValue - public String json; - - public RawBean() { - - } - - public RawBean(final String name, final String json) { - this.name = name; - this.json = json; - } -} diff --git a/jackson-simple/src/main/java/com/ossez/jackson/annotation/UnwrappedUser.java b/jackson-simple/src/main/java/com/ossez/jackson/annotation/UnwrappedUser.java deleted file mode 100644 index c40f940d1f..0000000000 --- a/jackson-simple/src/main/java/com/ossez/jackson/annotation/UnwrappedUser.java +++ /dev/null @@ -1,34 +0,0 @@ -package com.ossez.jackson.annotation; - -import com.fasterxml.jackson.annotation.JsonUnwrapped; - -public class UnwrappedUser { - public int id; - - @JsonUnwrapped - public Name name; - - public UnwrappedUser() { - - } - - public UnwrappedUser(final int id, final Name name) { - this.id = id; - this.name = name; - } - - public static class Name { - public String firstName; - public String lastName; - - public Name() { - - } - - public Name(final String firstName, final String lastName) { - this.firstName = firstName; - this.lastName = lastName; - } - } - -} diff --git a/jackson-simple/src/main/java/com/ossez/jackson/annotation/UserWithIgnoreType.java b/jackson-simple/src/main/java/com/ossez/jackson/annotation/UserWithIgnoreType.java deleted file mode 100644 index 4145f61122..0000000000 --- a/jackson-simple/src/main/java/com/ossez/jackson/annotation/UserWithIgnoreType.java +++ /dev/null @@ -1,34 +0,0 @@ -package com.ossez.jackson.annotation; - -import com.fasterxml.jackson.annotation.JsonIgnoreType; - -public class UserWithIgnoreType { - public int id; - - public Name name; - - public UserWithIgnoreType() { - - } - - public UserWithIgnoreType(final int id, final Name name) { - this.id = id; - this.name = name; - } - - @JsonIgnoreType - public static class Name { - public String firstName; - public String lastName; - - public Name() { - - } - - public Name(final String firstName, final String lastName) { - this.firstName = firstName; - this.lastName = lastName; - } - } - -} diff --git a/jackson-simple/src/main/java/com/ossez/jackson/annotation/Zoo.java b/jackson-simple/src/main/java/com/ossez/jackson/annotation/Zoo.java deleted file mode 100644 index cbd409137c..0000000000 --- a/jackson-simple/src/main/java/com/ossez/jackson/annotation/Zoo.java +++ /dev/null @@ -1,56 +0,0 @@ -package com.ossez.jackson.annotation; - -import com.fasterxml.jackson.annotation.JsonSubTypes; -import com.fasterxml.jackson.annotation.JsonTypeInfo; -import com.fasterxml.jackson.annotation.JsonTypeInfo.As; -import com.fasterxml.jackson.annotation.JsonTypeName; - -public class Zoo { - public Animal animal; - - public Zoo() { - - } - - public Zoo(final Animal animal) { - this.animal = animal; - } - - @JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = As.PROPERTY, property = "type") - @JsonSubTypes({ @JsonSubTypes.Type(value = Dog.class, name = "dog"), @JsonSubTypes.Type(value = Cat.class, name = "cat") }) - public static class Animal { - public String name; - - public Animal() { - } - - public Animal(final String name) { - this.name = name; - } - } - - @JsonTypeName("dog") - public static class Dog extends Animal { - public double barkVolume; - - public Dog() { - } - - public Dog(final String name) { - this.name = name; - } - } - - @JsonTypeName("cat") - public static class Cat extends Animal { - boolean likesCream; - public int lives; - - public Cat() { - } - - public Cat(final String name) { - this.name = name; - } - } -} \ No newline at end of file diff --git a/jackson-simple/src/main/java/com/ossez/jackson/annotation/bidirection/ItemWithIdentity.java b/jackson-simple/src/main/java/com/ossez/jackson/annotation/bidirection/ItemWithIdentity.java deleted file mode 100644 index cefae1f1ac..0000000000 --- a/jackson-simple/src/main/java/com/ossez/jackson/annotation/bidirection/ItemWithIdentity.java +++ /dev/null @@ -1,21 +0,0 @@ -package com.ossez.jackson.annotation.bidirection; - -import com.fasterxml.jackson.annotation.JsonIdentityInfo; -import com.fasterxml.jackson.annotation.ObjectIdGenerators; - -@JsonIdentityInfo(generator = ObjectIdGenerators.PropertyGenerator.class, property = "id") -public class ItemWithIdentity { - public int id; - public String itemName; - public UserWithIdentity owner; - - public ItemWithIdentity() { - super(); - } - - public ItemWithIdentity(final int id, final String itemName, final UserWithIdentity owner) { - this.id = id; - this.itemName = itemName; - this.owner = owner; - } -} diff --git a/jackson-simple/src/main/java/com/ossez/jackson/annotation/bidirection/ItemWithIgnore.java b/jackson-simple/src/main/java/com/ossez/jackson/annotation/bidirection/ItemWithIgnore.java deleted file mode 100644 index b1cb9c58f8..0000000000 --- a/jackson-simple/src/main/java/com/ossez/jackson/annotation/bidirection/ItemWithIgnore.java +++ /dev/null @@ -1,17 +0,0 @@ -package com.ossez.jackson.annotation.bidirection; - -public class ItemWithIgnore { - public int id; - public String itemName; - public UserWithIgnore owner; - - public ItemWithIgnore() { - super(); - } - - public ItemWithIgnore(final int id, final String itemName, final UserWithIgnore owner) { - this.id = id; - this.itemName = itemName; - this.owner = owner; - } -} diff --git a/jackson-simple/src/main/java/com/ossez/jackson/annotation/bidirection/ItemWithRef.java b/jackson-simple/src/main/java/com/ossez/jackson/annotation/bidirection/ItemWithRef.java deleted file mode 100644 index 658ea4cdb3..0000000000 --- a/jackson-simple/src/main/java/com/ossez/jackson/annotation/bidirection/ItemWithRef.java +++ /dev/null @@ -1,21 +0,0 @@ -package com.ossez.jackson.annotation.bidirection; - -import com.fasterxml.jackson.annotation.JsonManagedReference; - -public class ItemWithRef { - public int id; - public String itemName; - - @JsonManagedReference - public UserWithRef owner; - - public ItemWithRef() { - super(); - } - - public ItemWithRef(final int id, final String itemName, final UserWithRef owner) { - this.id = id; - this.itemName = itemName; - this.owner = owner; - } -} diff --git a/jackson-simple/src/main/java/com/ossez/jackson/annotation/bidirection/UserWithIdentity.java b/jackson-simple/src/main/java/com/ossez/jackson/annotation/bidirection/UserWithIdentity.java deleted file mode 100644 index d607233b9a..0000000000 --- a/jackson-simple/src/main/java/com/ossez/jackson/annotation/bidirection/UserWithIdentity.java +++ /dev/null @@ -1,28 +0,0 @@ -package com.ossez.jackson.annotation.bidirection; - -import java.util.ArrayList; -import java.util.List; - -import com.fasterxml.jackson.annotation.JsonIdentityInfo; -import com.fasterxml.jackson.annotation.ObjectIdGenerators; - -@JsonIdentityInfo(generator = ObjectIdGenerators.PropertyGenerator.class, property = "id") -public class UserWithIdentity { - public int id; - public String name; - public List userItems; - - public UserWithIdentity() { - super(); - } - - public UserWithIdentity(final int id, final String name) { - this.id = id; - this.name = name; - userItems = new ArrayList(); - } - - public void addItem(final ItemWithIdentity item) { - userItems.add(item); - } -} diff --git a/jackson-simple/src/main/java/com/ossez/jackson/annotation/bidirection/UserWithIgnore.java b/jackson-simple/src/main/java/com/ossez/jackson/annotation/bidirection/UserWithIgnore.java deleted file mode 100644 index 8c63cba074..0000000000 --- a/jackson-simple/src/main/java/com/ossez/jackson/annotation/bidirection/UserWithIgnore.java +++ /dev/null @@ -1,28 +0,0 @@ -package com.ossez.jackson.annotation.bidirection; - -import java.util.ArrayList; -import java.util.List; - -import com.fasterxml.jackson.annotation.JsonIgnore; - -public class UserWithIgnore { - public int id; - public String name; - - @JsonIgnore - public List userItems; - - public UserWithIgnore() { - super(); - } - - public UserWithIgnore(final int id, final String name) { - this.id = id; - this.name = name; - userItems = new ArrayList(); - } - - public void addItem(final ItemWithIgnore item) { - userItems.add(item); - } -} diff --git a/jackson-simple/src/main/java/com/ossez/jackson/annotation/bidirection/UserWithRef.java b/jackson-simple/src/main/java/com/ossez/jackson/annotation/bidirection/UserWithRef.java deleted file mode 100644 index 423f3e08fb..0000000000 --- a/jackson-simple/src/main/java/com/ossez/jackson/annotation/bidirection/UserWithRef.java +++ /dev/null @@ -1,28 +0,0 @@ -package com.ossez.jackson.annotation.bidirection; - -import java.util.ArrayList; -import java.util.List; - -import com.fasterxml.jackson.annotation.JsonBackReference; - -public class UserWithRef { - public int id; - public String name; - - @JsonBackReference - public List userItems; - - public UserWithRef() { - super(); - } - - public UserWithRef(final int id, final String name) { - this.id = id; - this.name = name; - userItems = new ArrayList(); - } - - public void addItem(final ItemWithRef item) { - userItems.add(item); - } -} diff --git a/jackson-simple/src/main/java/com/ossez/jackson/annotation/date/CustomDateDeserializer.java b/jackson-simple/src/main/java/com/ossez/jackson/annotation/date/CustomDateDeserializer.java deleted file mode 100644 index e503800d2a..0000000000 --- a/jackson-simple/src/main/java/com/ossez/jackson/annotation/date/CustomDateDeserializer.java +++ /dev/null @@ -1,36 +0,0 @@ -package com.ossez.jackson.annotation.date; - -import java.io.IOException; -import java.text.ParseException; -import java.text.SimpleDateFormat; -import java.util.Date; - -import com.fasterxml.jackson.core.JsonParser; -import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.databind.DeserializationContext; -import com.fasterxml.jackson.databind.deser.std.StdDeserializer; - -public class CustomDateDeserializer extends StdDeserializer { - - private static final long serialVersionUID = -5451717385630622729L; - private SimpleDateFormat formatter = new SimpleDateFormat("dd-MM-yyyy hh:mm:ss"); - - public CustomDateDeserializer() { - this(null); - } - - public CustomDateDeserializer(final Class vc) { - super(vc); - } - - @Override - public Date deserialize(final JsonParser jsonparser, final DeserializationContext context) throws IOException, JsonProcessingException { - final String date = jsonparser.getText(); - try { - return formatter.parse(date); - } catch (final ParseException e) { - throw new RuntimeException(e); - } - } - -} diff --git a/jackson-simple/src/main/java/com/ossez/jackson/annotation/date/CustomDateSerializer.java b/jackson-simple/src/main/java/com/ossez/jackson/annotation/date/CustomDateSerializer.java deleted file mode 100644 index c3e2100820..0000000000 --- a/jackson-simple/src/main/java/com/ossez/jackson/annotation/date/CustomDateSerializer.java +++ /dev/null @@ -1,29 +0,0 @@ -package com.ossez.jackson.annotation.date; - -import java.io.IOException; -import java.text.SimpleDateFormat; -import java.util.Date; - -import com.fasterxml.jackson.core.JsonGenerator; -import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.databind.SerializerProvider; -import com.fasterxml.jackson.databind.ser.std.StdSerializer; - -public class CustomDateSerializer extends StdSerializer { - - private static final long serialVersionUID = -2894356342227378312L; - private SimpleDateFormat formatter = new SimpleDateFormat("dd-MM-yyyy hh:mm:ss"); - - public CustomDateSerializer() { - this(null); - } - - public CustomDateSerializer(final Class t) { - super(t); - } - - @Override - public void serialize(final Date value, final JsonGenerator gen, final SerializerProvider arg2) throws IOException, JsonProcessingException { - gen.writeString(formatter.format(value)); - } -} diff --git a/jackson-simple/src/main/java/com/ossez/jackson/annotation/date/EventWithFormat.java b/jackson-simple/src/main/java/com/ossez/jackson/annotation/date/EventWithFormat.java deleted file mode 100644 index c6dc316517..0000000000 --- a/jackson-simple/src/main/java/com/ossez/jackson/annotation/date/EventWithFormat.java +++ /dev/null @@ -1,29 +0,0 @@ -package com.ossez.jackson.annotation.date; - -import java.util.Date; - -import com.fasterxml.jackson.annotation.JsonFormat; - -public class EventWithFormat { - public String name; - - @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "dd-MM-yyyy hh:mm:ss") - public Date eventDate; - - public EventWithFormat() { - super(); - } - - public EventWithFormat(final String name, final Date eventDate) { - this.name = name; - this.eventDate = eventDate; - } - - public Date getEventDate() { - return eventDate; - } - - public String getName() { - return name; - } -} diff --git a/jackson-simple/src/main/java/com/ossez/jackson/annotation/date/EventWithSerializer.java b/jackson-simple/src/main/java/com/ossez/jackson/annotation/date/EventWithSerializer.java deleted file mode 100644 index 4569ee0f4d..0000000000 --- a/jackson-simple/src/main/java/com/ossez/jackson/annotation/date/EventWithSerializer.java +++ /dev/null @@ -1,31 +0,0 @@ -package com.ossez.jackson.annotation.date; - -import java.util.Date; - -import com.fasterxml.jackson.databind.annotation.JsonDeserialize; -import com.fasterxml.jackson.databind.annotation.JsonSerialize; - -public class EventWithSerializer { - public String name; - - @JsonDeserialize(using = CustomDateDeserializer.class) - @JsonSerialize(using = CustomDateSerializer.class) - public Date eventDate; - - public EventWithSerializer() { - super(); - } - - public EventWithSerializer(final String name, final Date eventDate) { - this.name = name; - this.eventDate = eventDate; - } - - public Date getEventDate() { - return eventDate; - } - - public String getName() { - return name; - } -} diff --git a/jackson-simple/src/main/java/com/ossez/jackson/annotation/deserialization/ItemDeserializerOnClass.java b/jackson-simple/src/main/java/com/ossez/jackson/annotation/deserialization/ItemDeserializerOnClass.java deleted file mode 100644 index b0d74fc78a..0000000000 --- a/jackson-simple/src/main/java/com/ossez/jackson/annotation/deserialization/ItemDeserializerOnClass.java +++ /dev/null @@ -1,41 +0,0 @@ -package com.ossez.jackson.annotation.deserialization; - -import java.io.IOException; - -import com.ossez.jackson.annotation.dtos.ItemWithSerializer; -import com.ossez.jackson.annotation.dtos.User; -import com.fasterxml.jackson.core.JsonParser; -import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.databind.DeserializationContext; -import com.fasterxml.jackson.databind.JsonNode; -import com.fasterxml.jackson.databind.deser.std.StdDeserializer; -import com.fasterxml.jackson.databind.node.IntNode; - -public class ItemDeserializerOnClass extends StdDeserializer { - - private static final long serialVersionUID = 5579141241817332594L; - - public ItemDeserializerOnClass() { - this(null); - } - - public ItemDeserializerOnClass(final Class vc) { - super(vc); - } - - /** - * {"id":1,"itemNr":"theItem","owner":2} - */ - @Override - public ItemWithSerializer deserialize(final JsonParser jp, final DeserializationContext ctxt) throws IOException, JsonProcessingException { - final JsonNode node = jp.getCodec() - .readTree(jp); - final int id = (Integer) ((IntNode) node.get("id")).numberValue(); - final String itemName = node.get("itemName") - .asText(); - final int userId = (Integer) ((IntNode) node.get("owner")).numberValue(); - - return new ItemWithSerializer(id, itemName, new User(userId, null)); - } - -} \ No newline at end of file diff --git a/jackson-simple/src/main/java/com/ossez/jackson/annotation/dtos/Item.java b/jackson-simple/src/main/java/com/ossez/jackson/annotation/dtos/Item.java deleted file mode 100644 index a4592a39d9..0000000000 --- a/jackson-simple/src/main/java/com/ossez/jackson/annotation/dtos/Item.java +++ /dev/null @@ -1,32 +0,0 @@ -package com.ossez.jackson.annotation.dtos; - -public class Item { - public int id; - public String itemName; - public User owner; - - public Item() { - super(); - } - - public Item(final int id, final String itemName, final User owner) { - this.id = id; - this.itemName = itemName; - this.owner = owner; - } - - // API - - public int getId() { - return id; - } - - public String getItemName() { - return itemName; - } - - public User getOwner() { - return owner; - } - -} \ No newline at end of file diff --git a/jackson-simple/src/main/java/com/ossez/jackson/annotation/dtos/ItemWithSerializer.java b/jackson-simple/src/main/java/com/ossez/jackson/annotation/dtos/ItemWithSerializer.java deleted file mode 100644 index ec13bfe3ae..0000000000 --- a/jackson-simple/src/main/java/com/ossez/jackson/annotation/dtos/ItemWithSerializer.java +++ /dev/null @@ -1,36 +0,0 @@ -package com.ossez.jackson.annotation.dtos; - -import com.ossez.jackson.annotation.deserialization.ItemDeserializerOnClass; -import com.ossez.jackson.annotation.serialization.ItemSerializerOnClass; - -import com.fasterxml.jackson.databind.annotation.JsonDeserialize; -import com.fasterxml.jackson.databind.annotation.JsonSerialize; - -@JsonSerialize(using = ItemSerializerOnClass.class) -@JsonDeserialize(using = ItemDeserializerOnClass.class) -public class ItemWithSerializer { - public final int id; - public final String itemName; - public final User owner; - - public ItemWithSerializer(final int id, final String itemName, final User owner) { - this.id = id; - this.itemName = itemName; - this.owner = owner; - } - - // API - - public int getId() { - return id; - } - - public String getItemName() { - return itemName; - } - - public User getOwner() { - return owner; - } - -} \ No newline at end of file diff --git a/jackson-simple/src/main/java/com/ossez/jackson/annotation/dtos/User.java b/jackson-simple/src/main/java/com/ossez/jackson/annotation/dtos/User.java deleted file mode 100644 index cecd65b9af..0000000000 --- a/jackson-simple/src/main/java/com/ossez/jackson/annotation/dtos/User.java +++ /dev/null @@ -1,26 +0,0 @@ -package com.ossez.jackson.annotation.dtos; - -public class User { - public int id; - public String name; - - public User() { - super(); - } - - public User(final int id, final String name) { - this.id = id; - this.name = name; - } - - // API - - public int getId() { - return id; - } - - public String getName() { - return name; - } - -} \ No newline at end of file diff --git a/jackson-simple/src/main/java/com/ossez/jackson/annotation/dtos/withEnum/DistanceEnumWithValue.java b/jackson-simple/src/main/java/com/ossez/jackson/annotation/dtos/withEnum/DistanceEnumWithValue.java deleted file mode 100644 index 0810431e09..0000000000 --- a/jackson-simple/src/main/java/com/ossez/jackson/annotation/dtos/withEnum/DistanceEnumWithValue.java +++ /dev/null @@ -1,29 +0,0 @@ -package com.ossez.jackson.annotation.dtos.withEnum; - -import com.fasterxml.jackson.annotation.JsonValue; - -public enum DistanceEnumWithValue { - KILOMETER("km", 1000), MILE("miles", 1609.34), METER("meters", 1), INCH("inches", 0.0254), CENTIMETER("cm", 0.01), MILLIMETER("mm", 0.001); - - private String unit; - private final double meters; - - private DistanceEnumWithValue(String unit, double meters) { - this.unit = unit; - this.meters = meters; - } - - @JsonValue - public double getMeters() { - return meters; - } - - public String getUnit() { - return unit; - } - - public void setUnit(String unit) { - this.unit = unit; - } - -} \ No newline at end of file diff --git a/jackson-simple/src/main/java/com/ossez/jackson/annotation/exception/UserWithRoot.java b/jackson-simple/src/main/java/com/ossez/jackson/annotation/exception/UserWithRoot.java deleted file mode 100644 index c94f718345..0000000000 --- a/jackson-simple/src/main/java/com/ossez/jackson/annotation/exception/UserWithRoot.java +++ /dev/null @@ -1,18 +0,0 @@ -package com.ossez.jackson.annotation.exception; - -import com.fasterxml.jackson.annotation.JsonRootName; - -@JsonRootName(value = "user") -public class UserWithRoot { - public int id; - public String name; - - public UserWithRoot() { - super(); - } - - public UserWithRoot(final int id, final String name) { - this.id = id; - this.name = name; - } -} diff --git a/jackson-simple/src/main/java/com/ossez/jackson/annotation/exception/UserWithRootNamespace.java b/jackson-simple/src/main/java/com/ossez/jackson/annotation/exception/UserWithRootNamespace.java deleted file mode 100644 index d412df309b..0000000000 --- a/jackson-simple/src/main/java/com/ossez/jackson/annotation/exception/UserWithRootNamespace.java +++ /dev/null @@ -1,18 +0,0 @@ -package com.ossez.jackson.annotation.exception; - -import com.fasterxml.jackson.annotation.JsonRootName; - -@JsonRootName(value = "user", namespace="users") -public class UserWithRootNamespace { - public int id; - public String name; - - public UserWithRootNamespace() { - super(); - } - - public UserWithRootNamespace(final int id, final String name) { - this.id = id; - this.name = name; - } -} diff --git a/jackson-simple/src/main/java/com/ossez/jackson/annotation/ignore/MyMixInForIgnoreType.java b/jackson-simple/src/main/java/com/ossez/jackson/annotation/ignore/MyMixInForIgnoreType.java deleted file mode 100644 index 11f05424ed..0000000000 --- a/jackson-simple/src/main/java/com/ossez/jackson/annotation/ignore/MyMixInForIgnoreType.java +++ /dev/null @@ -1,8 +0,0 @@ -package com.ossez.jackson.annotation.ignore; - -import com.fasterxml.jackson.annotation.JsonIgnoreType; - -@JsonIgnoreType -public class MyMixInForIgnoreType { - // -} diff --git a/jackson-simple/src/main/java/com/ossez/jackson/annotation/jsonview/Item.java b/jackson-simple/src/main/java/com/ossez/jackson/annotation/jsonview/Item.java deleted file mode 100644 index 030a5672d7..0000000000 --- a/jackson-simple/src/main/java/com/ossez/jackson/annotation/jsonview/Item.java +++ /dev/null @@ -1,36 +0,0 @@ -package com.ossez.jackson.annotation.jsonview; - -import com.fasterxml.jackson.annotation.JsonView; - -public class Item { - @JsonView(Views.Public.class) - public int id; - - @JsonView(Views.Public.class) - public String itemName; - - @JsonView(Views.Internal.class) - public String ownerName; - - public Item() { - super(); - } - - public Item(final int id, final String itemName, final String ownerName) { - this.id = id; - this.itemName = itemName; - this.ownerName = ownerName; - } - - public int getId() { - return id; - } - - public String getItemName() { - return itemName; - } - - public String getOwnerName() { - return ownerName; - } -} diff --git a/jackson-simple/src/main/java/com/ossez/jackson/annotation/jsonview/Views.java b/jackson-simple/src/main/java/com/ossez/jackson/annotation/jsonview/Views.java deleted file mode 100644 index 10d6bfcc07..0000000000 --- a/jackson-simple/src/main/java/com/ossez/jackson/annotation/jsonview/Views.java +++ /dev/null @@ -1,9 +0,0 @@ -package com.ossez.jackson.annotation.jsonview; - -public class Views { - public static class Public { - } - - public static class Internal extends Public { - } -} diff --git a/jackson-simple/src/main/java/com/ossez/jackson/annotation/serialization/ItemSerializer.java b/jackson-simple/src/main/java/com/ossez/jackson/annotation/serialization/ItemSerializer.java deleted file mode 100644 index 96d34e3034..0000000000 --- a/jackson-simple/src/main/java/com/ossez/jackson/annotation/serialization/ItemSerializer.java +++ /dev/null @@ -1,32 +0,0 @@ -package com.ossez.jackson.annotation.serialization; - -import java.io.IOException; - -import com.ossez.jackson.annotation.dtos.Item; -import com.fasterxml.jackson.core.JsonGenerator; -import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.databind.SerializerProvider; -import com.fasterxml.jackson.databind.ser.std.StdSerializer; - -public class ItemSerializer extends StdSerializer { - - private static final long serialVersionUID = 6739170890621978901L; - - public ItemSerializer() { - this(null); - } - - public ItemSerializer(final Class t) { - super(t); - } - - @Override - public final void serialize(final Item value, final JsonGenerator jgen, final SerializerProvider provider) throws IOException, JsonProcessingException { - jgen.writeStartObject(); - jgen.writeNumberField("id", value.id); - jgen.writeStringField("itemName", value.itemName); - jgen.writeNumberField("owner", value.owner.id); - jgen.writeEndObject(); - } - -} \ No newline at end of file diff --git a/jackson-simple/src/main/java/com/ossez/jackson/annotation/serialization/ItemSerializerOnClass.java b/jackson-simple/src/main/java/com/ossez/jackson/annotation/serialization/ItemSerializerOnClass.java deleted file mode 100644 index 2ad7569b4e..0000000000 --- a/jackson-simple/src/main/java/com/ossez/jackson/annotation/serialization/ItemSerializerOnClass.java +++ /dev/null @@ -1,32 +0,0 @@ -package com.ossez.jackson.annotation.serialization; - -import java.io.IOException; - -import com.ossez.jackson.annotation.dtos.ItemWithSerializer; -import com.fasterxml.jackson.core.JsonGenerator; -import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.databind.SerializerProvider; -import com.fasterxml.jackson.databind.ser.std.StdSerializer; - -public class ItemSerializerOnClass extends StdSerializer { - - private static final long serialVersionUID = -1760959597313610409L; - - public ItemSerializerOnClass() { - this(null); - } - - public ItemSerializerOnClass(final Class t) { - super(t); - } - - @Override - public final void serialize(final ItemWithSerializer value, final JsonGenerator jgen, final SerializerProvider provider) throws IOException, JsonProcessingException { - jgen.writeStartObject(); - jgen.writeNumberField("id", value.id); - jgen.writeStringField("itemName", value.itemName); - jgen.writeNumberField("owner", value.owner.id); - jgen.writeEndObject(); - } - -} \ No newline at end of file diff --git a/jackson-simple/src/main/java/com/ossez/jackson/ignore/MyDto.java b/jackson-simple/src/main/java/com/ossez/jackson/ignore/MyDto.java deleted file mode 100644 index debaa55c28..0000000000 --- a/jackson-simple/src/main/java/com/ossez/jackson/ignore/MyDto.java +++ /dev/null @@ -1,54 +0,0 @@ -package com.ossez.jackson.ignore; - -public class MyDto { - - private String stringValue; - private int intValue; - private boolean booleanValue; - - public MyDto() { - super(); - } - - public MyDto(final String stringValue, final int intValue, final boolean booleanValue) { - super(); - - this.stringValue = stringValue; - this.intValue = intValue; - this.booleanValue = booleanValue; - } - - // API - - public String getStringValue() { - return stringValue; - } - - public void setStringValue(final String stringValue) { - this.stringValue = stringValue; - } - - public int getIntValue() { - return intValue; - } - - public void setIntValue(final int intValue) { - this.intValue = intValue; - } - - public boolean isBooleanValue() { - return booleanValue; - } - - public void setBooleanValue(final boolean booleanValue) { - this.booleanValue = booleanValue; - } - - // - - @Override - public String toString() { - return "MyDto [stringValue=" + stringValue + ", intValue=" + intValue + ", booleanValue=" + booleanValue + "]"; - } - -} diff --git a/jackson-simple/src/main/java/com/ossez/jackson/ignore/MyDtoIgnoreField.java b/jackson-simple/src/main/java/com/ossez/jackson/ignore/MyDtoIgnoreField.java deleted file mode 100644 index 96a743ace4..0000000000 --- a/jackson-simple/src/main/java/com/ossez/jackson/ignore/MyDtoIgnoreField.java +++ /dev/null @@ -1,42 +0,0 @@ -package com.ossez.jackson.ignore; - -import com.fasterxml.jackson.annotation.JsonIgnore; - -public class MyDtoIgnoreField { - - private String stringValue; - @JsonIgnore - private int intValue; - private boolean booleanValue; - - public MyDtoIgnoreField() { - super(); - } - - // API - - public String getStringValue() { - return stringValue; - } - - public void setStringValue(final String stringValue) { - this.stringValue = stringValue; - } - - public int getIntValue() { - return intValue; - } - - public void setIntValue(final int intValue) { - this.intValue = intValue; - } - - public boolean isBooleanValue() { - return booleanValue; - } - - public void setBooleanValue(final boolean booleanValue) { - this.booleanValue = booleanValue; - } - -} diff --git a/jackson-simple/src/main/java/com/ossez/jackson/ignore/MyDtoIgnoreFieldByName.java b/jackson-simple/src/main/java/com/ossez/jackson/ignore/MyDtoIgnoreFieldByName.java deleted file mode 100644 index f5cbbae005..0000000000 --- a/jackson-simple/src/main/java/com/ossez/jackson/ignore/MyDtoIgnoreFieldByName.java +++ /dev/null @@ -1,42 +0,0 @@ -package com.ossez.jackson.ignore; - -import com.fasterxml.jackson.annotation.JsonIgnoreProperties; - -@JsonIgnoreProperties(value = { "intValue" }) -public class MyDtoIgnoreFieldByName { - - private String stringValue; - private int intValue; - private boolean booleanValue; - - public MyDtoIgnoreFieldByName() { - super(); - } - - // API - - public String getStringValue() { - return stringValue; - } - - public void setStringValue(final String stringValue) { - this.stringValue = stringValue; - } - - public int getIntValue() { - return intValue; - } - - public void setIntValue(final int intValue) { - this.intValue = intValue; - } - - public boolean isBooleanValue() { - return booleanValue; - } - - public void setBooleanValue(final boolean booleanValue) { - this.booleanValue = booleanValue; - } - -} diff --git a/jackson-simple/src/main/java/com/ossez/jackson/ignore/MyDtoIgnoreNull.java b/jackson-simple/src/main/java/com/ossez/jackson/ignore/MyDtoIgnoreNull.java deleted file mode 100644 index 2876a11b51..0000000000 --- a/jackson-simple/src/main/java/com/ossez/jackson/ignore/MyDtoIgnoreNull.java +++ /dev/null @@ -1,51 +0,0 @@ -package com.ossez.jackson.ignore; - -import com.fasterxml.jackson.annotation.JsonInclude; -import com.fasterxml.jackson.annotation.JsonInclude.Include; - -@JsonInclude(Include.NON_NULL) -public class MyDtoIgnoreNull { - - private String stringValue; - private int intValue; - private boolean booleanValue; - - public MyDtoIgnoreNull() { - super(); - } - - public MyDtoIgnoreNull(final String stringValue, final int intValue, final boolean booleanValue) { - super(); - - this.stringValue = stringValue; - this.intValue = intValue; - this.booleanValue = booleanValue; - } - - // API - - public String getStringValue() { - return stringValue; - } - - public void setStringValue(final String stringValue) { - this.stringValue = stringValue; - } - - public int getIntValue() { - return intValue; - } - - public void setIntValue(final int intValue) { - this.intValue = intValue; - } - - public boolean isBooleanValue() { - return booleanValue; - } - - public void setBooleanValue(final boolean booleanValue) { - this.booleanValue = booleanValue; - } - -} diff --git a/jackson-simple/src/main/java/com/ossez/jackson/ignore/MyDtoIncludeNonDefault.java b/jackson-simple/src/main/java/com/ossez/jackson/ignore/MyDtoIncludeNonDefault.java deleted file mode 100644 index 02f90d33c4..0000000000 --- a/jackson-simple/src/main/java/com/ossez/jackson/ignore/MyDtoIncludeNonDefault.java +++ /dev/null @@ -1,43 +0,0 @@ -package com.ossez.jackson.ignore; - -import com.fasterxml.jackson.annotation.JsonInclude; -import com.fasterxml.jackson.annotation.JsonInclude.Include; - -@JsonInclude(Include.NON_DEFAULT) -public class MyDtoIncludeNonDefault { - - private String stringValue; - private int intValue; - private boolean booleanValue; - - public MyDtoIncludeNonDefault() { - super(); - } - - // API - - public String getStringValue() { - return stringValue; - } - - public void setStringValue(final String stringValue) { - this.stringValue = stringValue; - } - - public int getIntValue() { - return intValue; - } - - public void setIntValue(final int intValue) { - this.intValue = intValue; - } - - public boolean isBooleanValue() { - return booleanValue; - } - - public void setBooleanValue(final boolean booleanValue) { - this.booleanValue = booleanValue; - } - -} diff --git a/jackson-simple/src/main/java/com/ossez/jackson/ignore/MyDtoWithFilter.java b/jackson-simple/src/main/java/com/ossez/jackson/ignore/MyDtoWithFilter.java deleted file mode 100644 index 2d1844df60..0000000000 --- a/jackson-simple/src/main/java/com/ossez/jackson/ignore/MyDtoWithFilter.java +++ /dev/null @@ -1,50 +0,0 @@ -package com.ossez.jackson.ignore; - -import com.fasterxml.jackson.annotation.JsonFilter; - -@JsonFilter("myFilter") -public class MyDtoWithFilter { - - private String stringValue; - private int intValue; - private boolean booleanValue; - - public MyDtoWithFilter() { - super(); - } - - public MyDtoWithFilter(final String stringValue, final int intValue, final boolean booleanValue) { - super(); - - this.stringValue = stringValue; - this.intValue = intValue; - this.booleanValue = booleanValue; - } - - // API - - public String getStringValue() { - return stringValue; - } - - public void setStringValue(final String stringValue) { - this.stringValue = stringValue; - } - - public int getIntValue() { - return intValue; - } - - public void setIntValue(final int intValue) { - this.intValue = intValue; - } - - public boolean isBooleanValue() { - return booleanValue; - } - - public void setBooleanValue(final boolean booleanValue) { - this.booleanValue = booleanValue; - } - -} diff --git a/jackson-simple/src/main/java/com/ossez/jackson/ignore/MyDtoWithSpecialField.java b/jackson-simple/src/main/java/com/ossez/jackson/ignore/MyDtoWithSpecialField.java deleted file mode 100644 index 01446af9a0..0000000000 --- a/jackson-simple/src/main/java/com/ossez/jackson/ignore/MyDtoWithSpecialField.java +++ /dev/null @@ -1,54 +0,0 @@ -package com.ossez.jackson.ignore; - -public class MyDtoWithSpecialField { - - private String[] stringValue; - private int intValue; - private boolean booleanValue; - - public MyDtoWithSpecialField() { - super(); - } - - public MyDtoWithSpecialField(final String[] stringValue, final int intValue, final boolean booleanValue) { - super(); - - this.stringValue = stringValue; - this.intValue = intValue; - this.booleanValue = booleanValue; - } - - // API - - public String[] getStringValue() { - return stringValue; - } - - public void setStringValue(final String[] stringValue) { - this.stringValue = stringValue; - } - - public int getIntValue() { - return intValue; - } - - public void setIntValue(final int intValue) { - this.intValue = intValue; - } - - public boolean isBooleanValue() { - return booleanValue; - } - - public void setBooleanValue(final boolean booleanValue) { - this.booleanValue = booleanValue; - } - - // - - @Override - public String toString() { - return "MyDto [stringValue=" + stringValue + ", intValue=" + intValue + ", booleanValue=" + booleanValue + "]"; - } - -} diff --git a/jackson-simple/src/main/java/com/ossez/jackson/ignore/MyMixInForIgnoreType.java b/jackson-simple/src/main/java/com/ossez/jackson/ignore/MyMixInForIgnoreType.java deleted file mode 100644 index 94b2cc986a..0000000000 --- a/jackson-simple/src/main/java/com/ossez/jackson/ignore/MyMixInForIgnoreType.java +++ /dev/null @@ -1,8 +0,0 @@ -package com.ossez.jackson.ignore; - -import com.fasterxml.jackson.annotation.JsonIgnoreType; - -@JsonIgnoreType -public class MyMixInForIgnoreType { - // -} diff --git a/jackson-simple/src/main/java/com/ossez/jackson/ignorenullfields/MyDto.java b/jackson-simple/src/main/java/com/ossez/jackson/ignorenullfields/MyDto.java deleted file mode 100644 index 001d3d22c0..0000000000 --- a/jackson-simple/src/main/java/com/ossez/jackson/ignorenullfields/MyDto.java +++ /dev/null @@ -1,54 +0,0 @@ -package com.ossez.jackson.ignorenullfields; - -public class MyDto { - - private String stringValue; - private int intValue; - private boolean booleanValue; - - public MyDto() { - super(); - } - - public MyDto(final String stringValue, final int intValue, final boolean booleanValue) { - super(); - - this.stringValue = stringValue; - this.intValue = intValue; - this.booleanValue = booleanValue; - } - - // API - - public String getStringValue() { - return stringValue; - } - - public void setStringValue(final String stringValue) { - this.stringValue = stringValue; - } - - public int getIntValue() { - return intValue; - } - - public void setIntValue(final int intValue) { - this.intValue = intValue; - } - - public boolean isBooleanValue() { - return booleanValue; - } - - public void setBooleanValue(final boolean booleanValue) { - this.booleanValue = booleanValue; - } - - // - - @Override - public String toString() { - return "MyDto [stringValue=" + stringValue + ", intValue=" + intValue + ", booleanValue=" + booleanValue + "]"; - } - -} diff --git a/jackson-simple/src/main/java/com/ossez/jackson/ignorenullfields/MyDtoIgnoreNull.java b/jackson-simple/src/main/java/com/ossez/jackson/ignorenullfields/MyDtoIgnoreNull.java deleted file mode 100644 index feab3e1ac5..0000000000 --- a/jackson-simple/src/main/java/com/ossez/jackson/ignorenullfields/MyDtoIgnoreNull.java +++ /dev/null @@ -1,51 +0,0 @@ -package com.ossez.jackson.ignorenullfields; - -import com.fasterxml.jackson.annotation.JsonInclude; -import com.fasterxml.jackson.annotation.JsonInclude.Include; - -@JsonInclude(Include.NON_NULL) -public class MyDtoIgnoreNull { - - private String stringValue; - private int intValue; - private boolean booleanValue; - - public MyDtoIgnoreNull() { - super(); - } - - public MyDtoIgnoreNull(final String stringValue, final int intValue, final boolean booleanValue) { - super(); - - this.stringValue = stringValue; - this.intValue = intValue; - this.booleanValue = booleanValue; - } - - // API - - public String getStringValue() { - return stringValue; - } - - public void setStringValue(final String stringValue) { - this.stringValue = stringValue; - } - - public int getIntValue() { - return intValue; - } - - public void setIntValue(final int intValue) { - this.intValue = intValue; - } - - public boolean isBooleanValue() { - return booleanValue; - } - - public void setBooleanValue(final boolean booleanValue) { - this.booleanValue = booleanValue; - } - -} diff --git a/jackson-simple/src/main/java/com/ossez/jackson/jsonproperty/MyDto.java b/jackson-simple/src/main/java/com/ossez/jackson/jsonproperty/MyDto.java deleted file mode 100644 index fb1d980dd9..0000000000 --- a/jackson-simple/src/main/java/com/ossez/jackson/jsonproperty/MyDto.java +++ /dev/null @@ -1,54 +0,0 @@ -package com.ossez.jackson.jsonproperty; - -public class MyDto { - - private String stringValue; - private int intValue; - private boolean booleanValue; - - public MyDto() { - super(); - } - - public MyDto(final String stringValue, final int intValue, final boolean booleanValue) { - super(); - - this.stringValue = stringValue; - this.intValue = intValue; - this.booleanValue = booleanValue; - } - - // API - - public String getStringValue() { - return stringValue; - } - - public void setStringValue(final String stringValue) { - this.stringValue = stringValue; - } - - public int getIntValue() { - return intValue; - } - - public void setIntValue(final int intValue) { - this.intValue = intValue; - } - - public boolean isBooleanValue() { - return booleanValue; - } - - public void setBooleanValue(final boolean booleanValue) { - this.booleanValue = booleanValue; - } - - // - - @Override - public String toString() { - return "MyDto [stringValue=" + stringValue + ", intValue=" + intValue + ", booleanValue=" + booleanValue + "]"; - } - -} diff --git a/jackson-simple/src/main/java/com/ossez/jackson/jsonproperty/MyDtoFieldNameChanged.java b/jackson-simple/src/main/java/com/ossez/jackson/jsonproperty/MyDtoFieldNameChanged.java deleted file mode 100644 index 1cc87870f1..0000000000 --- a/jackson-simple/src/main/java/com/ossez/jackson/jsonproperty/MyDtoFieldNameChanged.java +++ /dev/null @@ -1,50 +0,0 @@ -package com.ossez.jackson.jsonproperty; - -import com.fasterxml.jackson.annotation.JsonProperty; - -public class MyDtoFieldNameChanged { - - private String stringValue; - private int intValue; - private boolean booleanValue; - - public MyDtoFieldNameChanged() { - super(); - } - - public MyDtoFieldNameChanged(final String stringValue, final int intValue, final boolean booleanValue) { - super(); - - this.stringValue = stringValue; - this.intValue = intValue; - this.booleanValue = booleanValue; - } - - // API - - @JsonProperty("strVal") - public String getStringValue() { - return stringValue; - } - - public void setStringValue(final String stringValue) { - this.stringValue = stringValue; - } - - public int getIntValue() { - return intValue; - } - - public void setIntValue(final int intValue) { - this.intValue = intValue; - } - - public boolean isBooleanValue() { - return booleanValue; - } - - public void setBooleanValue(final boolean booleanValue) { - this.booleanValue = booleanValue; - } - -} diff --git a/jackson-simple/src/main/java/com/ossez/jackson/objectmapper/CustomCarDeserializer.java b/jackson-simple/src/main/java/com/ossez/jackson/objectmapper/CustomCarDeserializer.java deleted file mode 100644 index 724eaf60fe..0000000000 --- a/jackson-simple/src/main/java/com/ossez/jackson/objectmapper/CustomCarDeserializer.java +++ /dev/null @@ -1,42 +0,0 @@ -package com.ossez.jackson.objectmapper; - -import java.io.IOException; - -import com.ossez.jackson.objectmapper.dto.Car; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import com.fasterxml.jackson.core.JsonParser; -import com.fasterxml.jackson.core.ObjectCodec; -import com.fasterxml.jackson.databind.DeserializationContext; -import com.fasterxml.jackson.databind.JsonNode; -import com.fasterxml.jackson.databind.deser.std.StdDeserializer; - -public class CustomCarDeserializer extends StdDeserializer { - - private static final long serialVersionUID = -5918629454846356161L; - private final Logger Logger = LoggerFactory.getLogger(getClass()); - - public CustomCarDeserializer() { - this(null); - } - - public CustomCarDeserializer(final Class vc) { - super(vc); - } - - @Override - public Car deserialize(final JsonParser parser, final DeserializationContext deserializer) throws IOException { - final Car car = new Car(); - final ObjectCodec codec = parser.getCodec(); - final JsonNode node = codec.readTree(parser); - try { - final JsonNode colorNode = node.get("color"); - final String color = colorNode.asText(); - car.setColor(color); - } catch (final Exception e) { - Logger.debug("101_parse_exeption: unknown json."); - } - return car; - } -} diff --git a/jackson-simple/src/main/java/com/ossez/jackson/objectmapper/CustomCarSerializer.java b/jackson-simple/src/main/java/com/ossez/jackson/objectmapper/CustomCarSerializer.java deleted file mode 100644 index 47df3468bb..0000000000 --- a/jackson-simple/src/main/java/com/ossez/jackson/objectmapper/CustomCarSerializer.java +++ /dev/null @@ -1,29 +0,0 @@ -package com.ossez.jackson.objectmapper; - -import java.io.IOException; - -import com.ossez.jackson.objectmapper.dto.Car; -import com.fasterxml.jackson.core.JsonGenerator; -import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.databind.SerializerProvider; -import com.fasterxml.jackson.databind.ser.std.StdSerializer; - -public class CustomCarSerializer extends StdSerializer { - - private static final long serialVersionUID = 1396140685442227917L; - - public CustomCarSerializer() { - this(null); - } - - public CustomCarSerializer(final Class t) { - super(t); - } - - @Override - public void serialize(final Car car, final JsonGenerator jsonGenerator, final SerializerProvider serializer) throws IOException, JsonProcessingException { - jsonGenerator.writeStartObject(); - jsonGenerator.writeStringField("model: ", car.getType()); - jsonGenerator.writeEndObject(); - } -} diff --git a/jackson-simple/src/main/java/com/ossez/jackson/objectmapper/dto/Car.java b/jackson-simple/src/main/java/com/ossez/jackson/objectmapper/dto/Car.java deleted file mode 100644 index 21bf03fff5..0000000000 --- a/jackson-simple/src/main/java/com/ossez/jackson/objectmapper/dto/Car.java +++ /dev/null @@ -1,31 +0,0 @@ -package com.ossez.jackson.objectmapper.dto; - -public class Car { - - private String color; - private String type; - - public Car() { - } - - public Car(final String color, final String type) { - this.color = color; - this.type = type; - } - - public String getColor() { - return color; - } - - public void setColor(final String color) { - this.color = color; - } - - public String getType() { - return type; - } - - public void setType(final String type) { - this.type = type; - } -} diff --git a/jackson-simple/src/main/java/com/ossez/jackson/objectmapper/dto/Request.java b/jackson-simple/src/main/java/com/ossez/jackson/objectmapper/dto/Request.java deleted file mode 100644 index 8d80e16638..0000000000 --- a/jackson-simple/src/main/java/com/ossez/jackson/objectmapper/dto/Request.java +++ /dev/null @@ -1,24 +0,0 @@ -package com.ossez.jackson.objectmapper.dto; - -import java.util.Date; - -public class Request { - Car car; - Date datePurchased; - - public Car getCar() { - return car; - } - - public void setCar(final Car car) { - this.car = car; - } - - public Date getDatePurchased() { - return datePurchased; - } - - public void setDatePurchased(final Date datePurchased) { - this.datePurchased = datePurchased; - } -} \ No newline at end of file diff --git a/jackson-simple/src/main/java/com/ossez/jackson/unknownproperties/MyDto.java b/jackson-simple/src/main/java/com/ossez/jackson/unknownproperties/MyDto.java deleted file mode 100644 index d87f3d5883..0000000000 --- a/jackson-simple/src/main/java/com/ossez/jackson/unknownproperties/MyDto.java +++ /dev/null @@ -1,54 +0,0 @@ -package com.ossez.jackson.unknownproperties; - -public class MyDto { - - private String stringValue; - private int intValue; - private boolean booleanValue; - - public MyDto() { - super(); - } - - public MyDto(final String stringValue, final int intValue, final boolean booleanValue) { - super(); - - this.stringValue = stringValue; - this.intValue = intValue; - this.booleanValue = booleanValue; - } - - // API - - public String getStringValue() { - return stringValue; - } - - public void setStringValue(final String stringValue) { - this.stringValue = stringValue; - } - - public int getIntValue() { - return intValue; - } - - public void setIntValue(final int intValue) { - this.intValue = intValue; - } - - public boolean isBooleanValue() { - return booleanValue; - } - - public void setBooleanValue(final boolean booleanValue) { - this.booleanValue = booleanValue; - } - - // - - @Override - public String toString() { - return "MyDto [stringValue=" + stringValue + ", intValue=" + intValue + ", booleanValue=" + booleanValue + "]"; - } - -} diff --git a/jackson-simple/src/main/java/com/ossez/jackson/unknownproperties/MyDtoIgnoreType.java b/jackson-simple/src/main/java/com/ossez/jackson/unknownproperties/MyDtoIgnoreType.java deleted file mode 100644 index 1cd63192c7..0000000000 --- a/jackson-simple/src/main/java/com/ossez/jackson/unknownproperties/MyDtoIgnoreType.java +++ /dev/null @@ -1,50 +0,0 @@ -package com.ossez.jackson.unknownproperties; - -import com.fasterxml.jackson.annotation.JsonIgnoreProperties; - -@JsonIgnoreProperties(ignoreUnknown = true) -public class MyDtoIgnoreType { - - private String stringValue; - private int intValue; - private boolean booleanValue; - - public MyDtoIgnoreType() { - super(); - } - - public MyDtoIgnoreType(final String stringValue, final int intValue, final boolean booleanValue) { - super(); - - this.stringValue = stringValue; - this.intValue = intValue; - this.booleanValue = booleanValue; - } - - // API - - public String getStringValue() { - return stringValue; - } - - public void setStringValue(final String stringValue) { - this.stringValue = stringValue; - } - - public int getIntValue() { - return intValue; - } - - public void setIntValue(final int intValue) { - this.intValue = intValue; - } - - public boolean isBooleanValue() { - return booleanValue; - } - - public void setBooleanValue(final boolean booleanValue) { - this.booleanValue = booleanValue; - } - -} diff --git a/jackson-simple/src/main/java/com/ossez/jackson/unknownproperties/MyDtoIgnoreUnknown.java b/jackson-simple/src/main/java/com/ossez/jackson/unknownproperties/MyDtoIgnoreUnknown.java deleted file mode 100644 index 97ab600559..0000000000 --- a/jackson-simple/src/main/java/com/ossez/jackson/unknownproperties/MyDtoIgnoreUnknown.java +++ /dev/null @@ -1,50 +0,0 @@ -package com.ossez.jackson.unknownproperties; - -import com.fasterxml.jackson.annotation.JsonIgnoreProperties; - -@JsonIgnoreProperties(ignoreUnknown = true) -public class MyDtoIgnoreUnknown { - - private String stringValue; - private int intValue; - private boolean booleanValue; - - public MyDtoIgnoreUnknown() { - super(); - } - - public MyDtoIgnoreUnknown(final String stringValue, final int intValue, final boolean booleanValue) { - super(); - - this.stringValue = stringValue; - this.intValue = intValue; - this.booleanValue = booleanValue; - } - - // API - - public String getStringValue() { - return stringValue; - } - - public void setStringValue(final String stringValue) { - this.stringValue = stringValue; - } - - public int getIntValue() { - return intValue; - } - - public void setIntValue(final int intValue) { - this.intValue = intValue; - } - - public boolean isBooleanValue() { - return booleanValue; - } - - public void setBooleanValue(final boolean booleanValue) { - this.booleanValue = booleanValue; - } - -} diff --git a/jackson-simple/src/main/resources/logback.xml b/jackson-simple/src/main/resources/logback.xml deleted file mode 100644 index 56af2d397e..0000000000 --- a/jackson-simple/src/main/resources/logback.xml +++ /dev/null @@ -1,19 +0,0 @@ - - - - - %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n - - - - - - - - - - - - - - \ No newline at end of file diff --git a/jackson-simple/src/test/java/com/ossez/jackson/annotation/JacksonAnnotationUnitTest.java b/jackson-simple/src/test/java/com/ossez/jackson/annotation/JacksonAnnotationUnitTest.java deleted file mode 100644 index f4de0c2f7a..0000000000 --- a/jackson-simple/src/test/java/com/ossez/jackson/annotation/JacksonAnnotationUnitTest.java +++ /dev/null @@ -1,406 +0,0 @@ -package com.ossez.jackson.annotation; - -import static org.hamcrest.Matchers.containsString; -import static org.hamcrest.Matchers.is; -import static org.hamcrest.Matchers.not; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertThat; - -import java.io.IOException; -import java.text.ParseException; -import java.text.SimpleDateFormat; -import java.util.Date; -import java.util.TimeZone; - -import com.ossez.jackson.annotation.bidirection.ItemWithIdentity; -import com.ossez.jackson.annotation.bidirection.ItemWithRef; -import com.ossez.jackson.annotation.bidirection.UserWithIdentity; -import com.ossez.jackson.annotation.bidirection.UserWithRef; -import com.ossez.jackson.annotation.date.EventWithFormat; -import com.ossez.jackson.annotation.date.EventWithSerializer; -import com.ossez.jackson.annotation.dtos.User; -import com.ossez.jackson.annotation.dtos.withEnum.DistanceEnumWithValue; -import com.ossez.jackson.annotation.exception.UserWithRoot; -import com.ossez.jackson.annotation.exception.UserWithRootNamespace; -import com.ossez.jackson.annotation.ignore.MyMixInForIgnoreType; -import com.ossez.jackson.annotation.jsonview.Item; -import com.ossez.jackson.annotation.jsonview.Views; -import org.junit.Test; - -import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.databind.InjectableValues; -import com.fasterxml.jackson.databind.MapperFeature; -import com.fasterxml.jackson.databind.ObjectMapper; -import com.fasterxml.jackson.databind.SerializationFeature; -import com.fasterxml.jackson.databind.ser.FilterProvider; -import com.fasterxml.jackson.databind.ser.impl.SimpleBeanPropertyFilter; -import com.fasterxml.jackson.databind.ser.impl.SimpleFilterProvider; -import com.fasterxml.jackson.dataformat.xml.XmlMapper; - -public class JacksonAnnotationUnitTest { - - @Test - public void whenSerializingUsingJsonAnyGetter_thenCorrect() throws JsonProcessingException { - final ExtendableBean bean = new ExtendableBean("My bean"); - bean.add("attr1", "val1"); - bean.add("attr2", "val2"); - - final String result = new ObjectMapper().writeValueAsString(bean); - assertThat(result, containsString("attr1")); - assertThat(result, containsString("val1")); - } - - @Test - public void whenSerializingUsingJsonGetter_thenCorrect() throws JsonProcessingException { - final BeanWithGetter bean = new BeanWithGetter(1, "My bean"); - - final String result = new ObjectMapper().writeValueAsString(bean); - assertThat(result, containsString("My bean")); - assertThat(result, containsString("1")); - } - - @Test - public void whenSerializingUsingJsonPropertyOrder_thenCorrect() throws JsonProcessingException { - final MyBean bean = new MyBean(1, "My bean"); - - final String result = new ObjectMapper().writeValueAsString(bean); - assertThat(result, containsString("My bean")); - assertThat(result, containsString("1")); - } - - @Test - public void whenSerializingUsingJsonRawValue_thenCorrect() throws JsonProcessingException { - final RawBean bean = new RawBean("My bean", "{\"attr\":false}"); - - final String result = new ObjectMapper().writeValueAsString(bean); - assertThat(result, containsString("My bean")); - assertThat(result, containsString("{\"attr\":false}")); - } - - @Test - public void whenSerializingUsingJsonRootName_thenCorrect() throws JsonProcessingException { - final UserWithRoot user = new UserWithRoot(1, "John"); - - final ObjectMapper mapper = new ObjectMapper(); - mapper.enable(SerializationFeature.WRAP_ROOT_VALUE); - final String result = mapper.writeValueAsString(user); - - assertThat(result, containsString("John")); - assertThat(result, containsString("user")); - } - - @Test - public void whenSerializingUsingJsonValue_thenCorrect() throws IOException { - final String enumAsString = new ObjectMapper().writeValueAsString(DistanceEnumWithValue.MILE); - - assertThat(enumAsString, is("1609.34")); - } - - @Test - public void whenSerializingUsingJsonSerialize_thenCorrect() throws JsonProcessingException, ParseException { - final SimpleDateFormat df = new SimpleDateFormat("dd-MM-yyyy hh:mm:ss"); - - final String toParse = "20-12-2014 02:30:00"; - final Date date = df.parse(toParse); - final EventWithSerializer event = new EventWithSerializer("party", date); - - final String result = new ObjectMapper().writeValueAsString(event); - assertThat(result, containsString(toParse)); - } - - // ========================= Deserializing annotations ============================ - - @Test - public void whenDeserializingUsingJsonCreator_thenCorrect() throws IOException { - final String json = "{\"id\":1,\"theName\":\"My bean\"}"; - - final BeanWithCreator bean = new ObjectMapper().readerFor(BeanWithCreator.class) - .readValue(json); - assertEquals("My bean", bean.name); - } - - @Test - public void whenDeserializingUsingJsonInject_thenCorrect() throws IOException { - final String json = "{\"name\":\"My bean\"}"; - final InjectableValues inject = new InjectableValues.Std().addValue(int.class, 1); - - final BeanWithInject bean = new ObjectMapper().reader(inject) - .forType(BeanWithInject.class) - .readValue(json); - assertEquals("My bean", bean.name); - assertEquals(1, bean.id); - } - - @Test - public void whenDeserializingUsingJsonAnySetter_thenCorrect() throws IOException { - final String json = "{\"name\":\"My bean\",\"attr2\":\"val2\",\"attr1\":\"val1\"}"; - - final ExtendableBean bean = new ObjectMapper().readerFor(ExtendableBean.class) - .readValue(json); - assertEquals("My bean", bean.name); - assertEquals("val2", bean.getProperties() - .get("attr2")); - } - - @Test - public void whenDeserializingUsingJsonSetter_thenCorrect() throws IOException { - final String json = "{\"id\":1,\"name\":\"My bean\"}"; - - final BeanWithGetter bean = new ObjectMapper().readerFor(BeanWithGetter.class) - .readValue(json); - assertEquals("My bean", bean.getTheName()); - } - - @Test - public void whenDeserializingUsingJsonDeserialize_thenCorrect() throws IOException { - final String json = "{\"name\":\"party\",\"eventDate\":\"20-12-2014 02:30:00\"}"; - - final SimpleDateFormat df = new SimpleDateFormat("dd-MM-yyyy hh:mm:ss"); - - final EventWithSerializer event = new ObjectMapper().readerFor(EventWithSerializer.class) - .readValue(json); - assertEquals("20-12-2014 02:30:00", df.format(event.eventDate)); - } - - // ========================= Inclusion annotations ============================ - - @Test - public void whenSerializingUsingJsonIgnoreProperties_thenCorrect() throws JsonProcessingException { - final BeanWithIgnore bean = new BeanWithIgnore(1, "My bean"); - - final String result = new ObjectMapper().writeValueAsString(bean); - assertThat(result, containsString("My bean")); - assertThat(result, not(containsString("id"))); - } - - @Test - public void whenSerializingUsingJsonIgnore_thenCorrect() throws JsonProcessingException { - final BeanWithIgnore bean = new BeanWithIgnore(1, "My bean"); - - final String result = new ObjectMapper().writeValueAsString(bean); - assertThat(result, containsString("My bean")); - assertThat(result, not(containsString("id"))); - } - - @Test - public void whenSerializingUsingJsonIgnoreType_thenCorrect() throws JsonProcessingException, ParseException { - final UserWithIgnoreType.Name name = new UserWithIgnoreType.Name("John", "Doe"); - final UserWithIgnoreType user = new UserWithIgnoreType(1, name); - - final String result = new ObjectMapper().writeValueAsString(user); - - assertThat(result, containsString("1")); - assertThat(result, not(containsString("name"))); - assertThat(result, not(containsString("John"))); - } - - @Test - public void whenSerializingUsingJsonInclude_thenCorrect() throws JsonProcessingException { - final MyBean bean = new MyBean(1, null); - - final String result = new ObjectMapper().writeValueAsString(bean); - assertThat(result, containsString("1")); - assertThat(result, not(containsString("name"))); - } - - @Test - public void whenSerializingUsingJsonAutoDetect_thenCorrect() throws JsonProcessingException { - final PrivateBean bean = new PrivateBean(1, "My bean"); - - final String result = new ObjectMapper().writeValueAsString(bean); - assertThat(result, containsString("1")); - assertThat(result, containsString("My bean")); - } - - // ========================= Polymorphic annotations ============================ - - @Test - public void whenSerializingPolymorphic_thenCorrect() throws JsonProcessingException { - final Zoo.Dog dog = new Zoo.Dog("lacy"); - final Zoo zoo = new Zoo(dog); - - final String result = new ObjectMapper().writeValueAsString(zoo); - - assertThat(result, containsString("type")); - assertThat(result, containsString("dog")); - } - - @Test - public void whenDeserializingPolymorphic_thenCorrect() throws IOException { - final String json = "{\"animal\":{\"name\":\"lacy\",\"type\":\"cat\"}}"; - - final Zoo zoo = new ObjectMapper().readerFor(Zoo.class) - .readValue(json); - - assertEquals("lacy", zoo.animal.name); - assertEquals(Zoo.Cat.class, zoo.animal.getClass()); - } - // ========================= General annotations ============================ - - @Test - public void whenUsingJsonProperty_thenCorrect() throws IOException { - final BeanWithGetter bean = new BeanWithGetter(1, "My bean"); - - final String result = new ObjectMapper().writeValueAsString(bean); - assertThat(result, containsString("My bean")); - assertThat(result, containsString("1")); - - final BeanWithGetter resultBean = new ObjectMapper().readerFor(BeanWithGetter.class) - .readValue(result); - assertEquals("My bean", resultBean.getTheName()); - } - - @Test - public void whenSerializingUsingJsonFormat_thenCorrect() throws JsonProcessingException, ParseException { - final SimpleDateFormat df = new SimpleDateFormat("dd-MM-yyyy hh:mm:ss"); - df.setTimeZone(TimeZone.getTimeZone("UTC")); - - final String toParse = "20-12-2014 02:30:00"; - final Date date = df.parse(toParse); - final EventWithFormat event = new EventWithFormat("party", date); - - final String result = new ObjectMapper().writeValueAsString(event); - assertThat(result, containsString(toParse)); - } - - @Test - public void whenSerializingUsingJsonUnwrapped_thenCorrect() throws JsonProcessingException, ParseException { - final UnwrappedUser.Name name = new UnwrappedUser.Name("John", "Doe"); - final UnwrappedUser user = new UnwrappedUser(1, name); - - final String result = new ObjectMapper().writeValueAsString(user); - assertThat(result, containsString("John")); - assertThat(result, not(containsString("name"))); - } - - @Test - public void whenSerializingUsingJsonView_thenCorrect() throws JsonProcessingException, JsonProcessingException { - final Item item = new Item(2, "book", "John"); - - final String result = new ObjectMapper().writerWithView(Views.Public.class) - .writeValueAsString(item); - - assertThat(result, containsString("book")); - assertThat(result, containsString("2")); - assertThat(result, not(containsString("John"))); - } - - @Test - public void whenSerializingUsingJacksonReferenceAnnotation_thenCorrect() throws JsonProcessingException { - final UserWithRef user = new UserWithRef(1, "John"); - final ItemWithRef item = new ItemWithRef(2, "book", user); - user.addItem(item); - - final String result = new ObjectMapper().writeValueAsString(item); - - assertThat(result, containsString("book")); - assertThat(result, containsString("John")); - assertThat(result, not(containsString("userItems"))); - } - - @Test - public void whenSerializingUsingJsonIdentityInfo_thenCorrect() throws JsonProcessingException { - final UserWithIdentity user = new UserWithIdentity(1, "John"); - final ItemWithIdentity item = new ItemWithIdentity(2, "book", user); - user.addItem(item); - - final String result = new ObjectMapper().writeValueAsString(item); - - assertThat(result, containsString("book")); - assertThat(result, containsString("John")); - assertThat(result, containsString("userItems")); - } - - @Test - public void whenSerializingUsingJsonFilter_thenCorrect() throws JsonProcessingException { - final BeanWithFilter bean = new BeanWithFilter(1, "My bean"); - - final FilterProvider filters = new SimpleFilterProvider().addFilter("myFilter", SimpleBeanPropertyFilter.filterOutAllExcept("name")); - - final String result = new ObjectMapper().writer(filters) - .writeValueAsString(bean); - - assertThat(result, containsString("My bean")); - assertThat(result, not(containsString("id"))); - } - - // ========================= - @Test - public void whenSerializingUsingCustomAnnotation_thenCorrect() throws JsonProcessingException { - final BeanWithCustomAnnotation bean = new BeanWithCustomAnnotation(1, "My bean", null); - - final String result = new ObjectMapper().writeValueAsString(bean); - - assertThat(result, containsString("My bean")); - assertThat(result, containsString("1")); - assertThat(result, not(containsString("dateCreated"))); - } - - // @Ignore("Jackson 2.7.1-1 seems to have changed the API regarding mixins") - @Test - public void whenSerializingUsingMixInAnnotation_thenCorrect() throws JsonProcessingException { - final com.ossez.jackson.annotation.dtos.Item item = new com.ossez.jackson.annotation.dtos.Item(1, "book", null); - - String result = new ObjectMapper().writeValueAsString(item); - assertThat(result, containsString("owner")); - - final ObjectMapper mapper = new ObjectMapper(); - mapper.addMixIn(User.class, MyMixInForIgnoreType.class); - - result = mapper.writeValueAsString(item); - assertThat(result, not(containsString("owner"))); - } - - @Test - public void whenDisablingAllAnnotations_thenAllDisabled() throws JsonProcessingException { - final MyBean bean = new MyBean(1, null); - - final ObjectMapper mapper = new ObjectMapper(); - mapper.disable(MapperFeature.USE_ANNOTATIONS); - - final String result = mapper.writeValueAsString(bean); - assertThat(result, containsString("1")); - assertThat(result, containsString("name")); - } - - @Test - public void whenDeserializingUsingJsonAlias_thenCorrect() throws IOException { - - // arrange - String json = "{\"fName\": \"John\", \"lastName\": \"Green\"}"; - - // act - AliasBean aliasBean = new ObjectMapper().readerFor(AliasBean.class).readValue(json); - - // assert - assertThat(aliasBean.getFirstName(), is("John")); - } - - @Test - public void whenSerializingUsingXMLRootNameWithNameSpace_thenCorrect() throws JsonProcessingException { - - // arrange - UserWithRootNamespace author = new UserWithRootNamespace(1, "John"); - - // act - ObjectMapper mapper = new XmlMapper(); - mapper = mapper.enable(SerializationFeature.WRAP_ROOT_VALUE).enable(SerializationFeature.INDENT_OUTPUT); - String result = mapper.writeValueAsString(author); - - // assert - assertThat(result, containsString("")); - - /* - - 3006b44a-cf62-4cfe-b3d8-30dc6c46ea96 - 1 - John - - - */ - - } - - - -} diff --git a/jackson-simple/src/test/java/com/ossez/jackson/ignore/IgnoreFieldsWithFilterUnitTest.java b/jackson-simple/src/test/java/com/ossez/jackson/ignore/IgnoreFieldsWithFilterUnitTest.java deleted file mode 100644 index 777ce8286e..0000000000 --- a/jackson-simple/src/test/java/com/ossez/jackson/ignore/IgnoreFieldsWithFilterUnitTest.java +++ /dev/null @@ -1,87 +0,0 @@ -package com.ossez.jackson.ignore; - -import com.fasterxml.jackson.core.JsonGenerator; -import com.fasterxml.jackson.core.JsonParseException; -import com.fasterxml.jackson.databind.ObjectMapper; -import com.fasterxml.jackson.databind.SerializerProvider; -import com.fasterxml.jackson.databind.ser.BeanPropertyWriter; -import com.fasterxml.jackson.databind.ser.FilterProvider; -import com.fasterxml.jackson.databind.ser.PropertyFilter; -import com.fasterxml.jackson.databind.ser.PropertyWriter; -import com.fasterxml.jackson.databind.ser.impl.SimpleBeanPropertyFilter; -import com.fasterxml.jackson.databind.ser.impl.SimpleFilterProvider; -import org.junit.Test; - -import java.io.IOException; - -import static org.hamcrest.Matchers.containsString; -import static org.hamcrest.Matchers.not; -import static org.junit.Assert.assertThat; - -public class IgnoreFieldsWithFilterUnitTest { - - @Test - public final void givenTypeHasFilterThatIgnoresFieldByName_whenDtoIsSerialized_thenCorrect() throws JsonParseException, IOException { - final ObjectMapper mapper = new ObjectMapper(); - final SimpleBeanPropertyFilter theFilter = SimpleBeanPropertyFilter.serializeAllExcept("intValue"); - final FilterProvider filters = new SimpleFilterProvider().addFilter("myFilter", theFilter); - - final MyDtoWithFilter dtoObject = new MyDtoWithFilter(); - dtoObject.setIntValue(12); - - final String dtoAsString = mapper.writer(filters) - .writeValueAsString(dtoObject); - - assertThat(dtoAsString, not(containsString("intValue"))); - assertThat(dtoAsString, containsString("booleanValue")); - assertThat(dtoAsString, containsString("stringValue")); - System.out.println(dtoAsString); - } - - @Test - public final void givenTypeHasFilterThatIgnoresNegativeInt_whenDtoIsSerialized_thenCorrect() throws JsonParseException, IOException { - final PropertyFilter theFilter = new SimpleBeanPropertyFilter() { - @Override - public final void serializeAsField(final Object pojo, final JsonGenerator jgen, final SerializerProvider provider, final PropertyWriter writer) throws Exception { - if (include(writer)) { - if (!writer.getName() - .equals("intValue")) { - writer.serializeAsField(pojo, jgen, provider); - return; - } - - final int intValue = ((MyDtoWithFilter) pojo).getIntValue(); - if (intValue >= 0) { - writer.serializeAsField(pojo, jgen, provider); - } - } else if (!jgen.canOmitFields()) { // since 2.3 - writer.serializeAsOmittedField(pojo, jgen, provider); - } - } - - @Override - protected final boolean include(final BeanPropertyWriter writer) { - return true; - } - - @Override - protected final boolean include(final PropertyWriter writer) { - return true; - } - }; - final FilterProvider filters = new SimpleFilterProvider().addFilter("myFilter", theFilter); - - final MyDtoWithFilter dtoObject = new MyDtoWithFilter(); - dtoObject.setIntValue(-1); - - final ObjectMapper mapper = new ObjectMapper(); - final String dtoAsString = mapper.writer(filters) - .writeValueAsString(dtoObject); - - assertThat(dtoAsString, not(containsString("intValue"))); - assertThat(dtoAsString, containsString("booleanValue")); - assertThat(dtoAsString, containsString("stringValue")); - System.out.println(dtoAsString); - } - -} diff --git a/jackson-simple/src/test/java/com/ossez/jackson/ignore/JacksonSerializationIgnoreUnitTest.java b/jackson-simple/src/test/java/com/ossez/jackson/ignore/JacksonSerializationIgnoreUnitTest.java deleted file mode 100644 index e8213a463b..0000000000 --- a/jackson-simple/src/test/java/com/ossez/jackson/ignore/JacksonSerializationIgnoreUnitTest.java +++ /dev/null @@ -1,111 +0,0 @@ -package com.ossez.jackson.ignore; - -import static org.hamcrest.Matchers.containsString; -import static org.hamcrest.Matchers.not; -import static org.junit.Assert.assertThat; - -import java.io.IOException; - -import org.junit.Test; - -import com.fasterxml.jackson.annotation.JsonInclude.Include; -import com.fasterxml.jackson.core.JsonParseException; -import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.databind.ObjectMapper; - -public class JacksonSerializationIgnoreUnitTest { - - // tests - single entity to json - - // ignore - - @Test - public final void givenOnlyNonDefaultValuesAreSerializedAndDtoHasOnlyDefaultValues_whenSerializing_thenCorrect() throws JsonParseException, IOException { - final ObjectMapper mapper = new ObjectMapper(); - final String dtoAsString = mapper.writeValueAsString(new MyDtoIncludeNonDefault()); - - assertThat(dtoAsString, not(containsString("intValue"))); - System.out.println(dtoAsString); - } - - @Test - public final void givenOnlyNonDefaultValuesAreSerializedAndDtoHasNonDefaultValue_whenSerializing_thenCorrect() throws JsonParseException, IOException { - final ObjectMapper mapper = new ObjectMapper(); - final MyDtoIncludeNonDefault dtoObject = new MyDtoIncludeNonDefault(); - dtoObject.setBooleanValue(true); - - final String dtoAsString = mapper.writeValueAsString(dtoObject); - - assertThat(dtoAsString, containsString("booleanValue")); - System.out.println(dtoAsString); - } - - @Test - public final void givenFieldIsIgnoredByName_whenDtoIsSerialized_thenCorrect() throws JsonParseException, IOException { - final ObjectMapper mapper = new ObjectMapper(); - final MyDtoIgnoreFieldByName dtoObject = new MyDtoIgnoreFieldByName(); - dtoObject.setBooleanValue(true); - - final String dtoAsString = mapper.writeValueAsString(dtoObject); - - assertThat(dtoAsString, not(containsString("intValue"))); - assertThat(dtoAsString, containsString("booleanValue")); - System.out.println(dtoAsString); - } - - @Test - public final void givenFieldIsIgnoredDirectly_whenDtoIsSerialized_thenCorrect() throws JsonParseException, IOException { - final ObjectMapper mapper = new ObjectMapper(); - final MyDtoIgnoreField dtoObject = new MyDtoIgnoreField(); - - final String dtoAsString = mapper.writeValueAsString(dtoObject); - - assertThat(dtoAsString, not(containsString("intValue"))); - assertThat(dtoAsString, containsString("booleanValue")); - System.out.println(dtoAsString); - } - - // @Ignore("Jackson 2.7.1-1 seems to have changed the API for this case") - @Test - public final void givenFieldTypeIsIgnored_whenDtoIsSerialized_thenCorrect() throws JsonParseException, IOException { - final ObjectMapper mapper = new ObjectMapper(); - mapper.addMixIn(String[].class, MyMixInForIgnoreType.class); - final MyDtoWithSpecialField dtoObject = new MyDtoWithSpecialField(); - dtoObject.setBooleanValue(true); - - final String dtoAsString = mapper.writeValueAsString(dtoObject); - - assertThat(dtoAsString, containsString("intValue")); - assertThat(dtoAsString, containsString("booleanValue")); - assertThat(dtoAsString, not(containsString("stringValue"))); - System.out.println(dtoAsString); - } - - @Test - public final void givenNullsIgnoredOnClass_whenWritingObjectWithNullField_thenIgnored() throws JsonProcessingException { - final ObjectMapper mapper = new ObjectMapper(); - final MyDtoIgnoreNull dtoObject = new MyDtoIgnoreNull(); - - final String dtoAsString = mapper.writeValueAsString(dtoObject); - - assertThat(dtoAsString, containsString("intValue")); - assertThat(dtoAsString, containsString("booleanValue")); - assertThat(dtoAsString, not(containsString("stringValue"))); - System.out.println(dtoAsString); - } - - @Test - public final void givenNullsIgnoredGlobally_whenWritingObjectWithNullField_thenIgnored() throws JsonProcessingException { - final ObjectMapper mapper = new ObjectMapper(); - mapper.setSerializationInclusion(Include.NON_NULL); - final MyDto dtoObject = new MyDto(); - - final String dtoAsString = mapper.writeValueAsString(dtoObject); - - assertThat(dtoAsString, containsString("intValue")); - assertThat(dtoAsString, containsString("booleanValue")); - assertThat(dtoAsString, not(containsString("stringValue"))); - System.out.println(dtoAsString); - } - -} diff --git a/jackson-simple/src/test/java/com/ossez/jackson/ignorenullfields/IgnoreNullFieldsUnitTest.java b/jackson-simple/src/test/java/com/ossez/jackson/ignorenullfields/IgnoreNullFieldsUnitTest.java deleted file mode 100644 index 056c31e9dc..0000000000 --- a/jackson-simple/src/test/java/com/ossez/jackson/ignorenullfields/IgnoreNullFieldsUnitTest.java +++ /dev/null @@ -1,41 +0,0 @@ -package com.ossez.jackson.ignorenullfields; - -import com.fasterxml.jackson.annotation.JsonInclude.Include; -import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.databind.ObjectMapper; -import org.junit.Test; - -import static org.hamcrest.Matchers.containsString; -import static org.hamcrest.Matchers.not; -import static org.junit.Assert.assertThat; - -public class IgnoreNullFieldsUnitTest { - - @Test - public final void givenNullsIgnoredOnClass_whenWritingObjectWithNullField_thenIgnored() throws JsonProcessingException { - final ObjectMapper mapper = new ObjectMapper(); - final MyDtoIgnoreNull dtoObject = new MyDtoIgnoreNull(); - - final String dtoAsString = mapper.writeValueAsString(dtoObject); - - assertThat(dtoAsString, containsString("intValue")); - assertThat(dtoAsString, containsString("booleanValue")); - assertThat(dtoAsString, not(containsString("stringValue"))); - System.out.println(dtoAsString); - } - - @Test - public final void givenNullsIgnoredGlobally_whenWritingObjectWithNullField_thenIgnored() throws JsonProcessingException { - final ObjectMapper mapper = new ObjectMapper(); - mapper.setSerializationInclusion(Include.NON_NULL); - final MyDto dtoObject = new MyDto(); - - final String dtoAsString = mapper.writeValueAsString(dtoObject); - - assertThat(dtoAsString, containsString("intValue")); - assertThat(dtoAsString, containsString("booleanValue")); - assertThat(dtoAsString, not(containsString("stringValue"))); - System.out.println(dtoAsString); - } - -} diff --git a/jackson-simple/src/test/java/com/ossez/jackson/jsonproperty/JsonPropertyUnitTest.java b/jackson-simple/src/test/java/com/ossez/jackson/jsonproperty/JsonPropertyUnitTest.java deleted file mode 100644 index 055c9398e0..0000000000 --- a/jackson-simple/src/test/java/com/ossez/jackson/jsonproperty/JsonPropertyUnitTest.java +++ /dev/null @@ -1,39 +0,0 @@ -package com.ossez.jackson.jsonproperty; - -import static org.hamcrest.Matchers.containsString; -import static org.hamcrest.Matchers.not; -import static org.junit.Assert.assertThat; - -import java.io.IOException; - -import org.junit.Test; - -import com.fasterxml.jackson.core.JsonParseException; -import com.fasterxml.jackson.databind.ObjectMapper; - -public class JsonPropertyUnitTest { - - @Test - public final void whenSerializing_thenCorrect() throws JsonParseException, IOException { - final ObjectMapper mapper = new ObjectMapper(); - final String dtoAsString = mapper.writeValueAsString(new MyDto()); - - assertThat(dtoAsString, containsString("intValue")); - assertThat(dtoAsString, containsString("stringValue")); - assertThat(dtoAsString, containsString("booleanValue")); - } - - @Test - public final void givenNameOfFieldIsChangedViaAnnotationOnGetter_whenSerializing_thenCorrect() throws JsonParseException, IOException { - final ObjectMapper mapper = new ObjectMapper(); - final MyDtoFieldNameChanged dtoObject = new MyDtoFieldNameChanged(); - dtoObject.setStringValue("a"); - - final String dtoAsString = mapper.writeValueAsString(dtoObject); - - assertThat(dtoAsString, not(containsString("stringValue"))); - assertThat(dtoAsString, containsString("strVal")); - System.out.println(dtoAsString); - } - -} diff --git a/jackson-simple/src/test/java/com/ossez/jackson/objectmapper/JavaReadWriteJsonExampleUnitTest.java b/jackson-simple/src/test/java/com/ossez/jackson/objectmapper/JavaReadWriteJsonExampleUnitTest.java deleted file mode 100644 index ac6085dc2e..0000000000 --- a/jackson-simple/src/test/java/com/ossez/jackson/objectmapper/JavaReadWriteJsonExampleUnitTest.java +++ /dev/null @@ -1,114 +0,0 @@ -package com.ossez.jackson.objectmapper; - -import static org.hamcrest.Matchers.containsString; -import static org.hamcrest.Matchers.equalTo; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertThat; - -import java.io.File; -import java.net.URL; -import java.util.List; -import java.util.Map; - -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.TemporaryFolder; - -import com.ossez.jackson.objectmapper.dto.Car; -import com.fasterxml.jackson.core.type.TypeReference; -import com.fasterxml.jackson.databind.JsonNode; -import com.fasterxml.jackson.databind.ObjectMapper; - -public class JavaReadWriteJsonExampleUnitTest { - - @Rule - public TemporaryFolder folder = new TemporaryFolder(); - - final String EXAMPLE_JSON = "{ \"color\" : \"Black\", \"type\" : \"BMW\" }"; - final String LOCAL_JSON = "[{ \"color\" : \"Black\", \"type\" : \"BMW\" }, { \"color\" : \"Red\", \"type\" : \"BMW\" }]"; - - @Test - public void whenWriteJavaToJson_thanCorrect() throws Exception { - final ObjectMapper objectMapper = new ObjectMapper(); - final Car car = new Car("yellow", "renault"); - final String carAsString = objectMapper.writeValueAsString(car); - assertThat(carAsString, containsString("yellow")); - assertThat(carAsString, containsString("renault")); - } - - @Test - public void whenWriteToFile_thanCorrect() throws Exception { - File resultFile = folder.newFile("car.json"); - - ObjectMapper objectMapper = new ObjectMapper(); - Car car = new Car("yellow", "renault"); - objectMapper.writeValue(resultFile, car); - - Car fromFile = objectMapper.readValue(resultFile, Car.class); - assertEquals(car.getType(), fromFile.getType()); - assertEquals(car.getColor(), fromFile.getColor()); - } - - @Test - public void whenReadJsonToJava_thanCorrect() throws Exception { - final ObjectMapper objectMapper = new ObjectMapper(); - final Car car = objectMapper.readValue(EXAMPLE_JSON, Car.class); - assertNotNull(car); - assertThat(car.getColor(), containsString("Black")); - } - - @Test - public void whenReadJsonToJsonNode_thanCorrect() throws Exception { - final ObjectMapper objectMapper = new ObjectMapper(); - final JsonNode jsonNode = objectMapper.readTree(EXAMPLE_JSON); - assertNotNull(jsonNode); - assertThat(jsonNode.get("color") - .asText(), containsString("Black")); - } - - @Test - public void whenReadJsonToList_thanCorrect() throws Exception { - final ObjectMapper objectMapper = new ObjectMapper(); - final List listCar = objectMapper.readValue(LOCAL_JSON, new TypeReference>() { - - }); - for (final Car car : listCar) { - assertNotNull(car); - assertThat(car.getType(), equalTo("BMW")); - } - } - - @Test - public void whenReadJsonToMap_thanCorrect() throws Exception { - final ObjectMapper objectMapper = new ObjectMapper(); - final Map map = objectMapper.readValue(EXAMPLE_JSON, new TypeReference>() { - }); - assertNotNull(map); - for (final String key : map.keySet()) { - assertNotNull(key); - } - } - - @Test - public void wheReadFromFile_thanCorrect() throws Exception { - File resource = new File("src/test/resources/json_car.json"); - - ObjectMapper objectMapper = new ObjectMapper(); - Car fromFile = objectMapper.readValue(resource, Car.class); - - assertEquals("BMW", fromFile.getType()); - assertEquals("Black", fromFile.getColor()); - } - - @Test - public void wheReadFromUrl_thanCorrect() throws Exception { - URL resource = new URL("file:src/test/resources/json_car.json"); - - ObjectMapper objectMapper = new ObjectMapper(); - Car fromFile = objectMapper.readValue(resource, Car.class); - - assertEquals("BMW", fromFile.getType()); - assertEquals("Black", fromFile.getColor()); - } -} diff --git a/jackson-simple/src/test/java/com/ossez/jackson/objectmapper/SerializationDeserializationFeatureUnitTest.java b/jackson-simple/src/test/java/com/ossez/jackson/objectmapper/SerializationDeserializationFeatureUnitTest.java deleted file mode 100644 index 47341c1c79..0000000000 --- a/jackson-simple/src/test/java/com/ossez/jackson/objectmapper/SerializationDeserializationFeatureUnitTest.java +++ /dev/null @@ -1,85 +0,0 @@ -package com.ossez.jackson.objectmapper; - -import com.ossez.jackson.objectmapper.dto.Car; -import com.ossez.jackson.objectmapper.dto.Request; -import com.fasterxml.jackson.core.Version; -import com.fasterxml.jackson.databind.DeserializationFeature; -import com.fasterxml.jackson.databind.JsonNode; -import com.fasterxml.jackson.databind.ObjectMapper; -import com.fasterxml.jackson.databind.module.SimpleModule; -import org.junit.Test; - -import java.text.DateFormat; -import java.text.SimpleDateFormat; -import java.util.Date; - -import static org.hamcrest.Matchers.containsString; -import static org.hamcrest.Matchers.equalTo; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertThat; - -public class SerializationDeserializationFeatureUnitTest { - - final String EXAMPLE_JSON = "{ \"color\" : \"Black\", \"type\" : \"BMW\" }"; - final String JSON_CAR = "{ \"color\" : \"Black\", \"type\" : \"Fiat\", \"year\" : \"1970\" }"; - final String JSON_ARRAY = "[{ \"color\" : \"Black\", \"type\" : \"BMW\" }, { \"color\" : \"Red\", \"type\" : \"BMW\" }]"; - - @Test - public void whenFailOnUnkownPropertiesFalse_thanJsonReadCorrectly() throws Exception { - - final ObjectMapper objectMapper = new ObjectMapper(); - objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); - final Car car = objectMapper.readValue(JSON_CAR, Car.class); - final JsonNode jsonNodeRoot = objectMapper.readTree(JSON_CAR); - final JsonNode jsonNodeYear = jsonNodeRoot.get("year"); - final String year = jsonNodeYear.asText(); - - assertNotNull(car); - assertThat(car.getColor(), equalTo("Black")); - assertThat(year, containsString("1970")); - } - - @Test - public void whenCustomSerializerDeserializer_thanReadWriteCorrect() throws Exception { - final ObjectMapper mapper = new ObjectMapper(); - final SimpleModule serializerModule = new SimpleModule("CustomSerializer", new Version(1, 0, 0, null, null, null)); - serializerModule.addSerializer(Car.class, new CustomCarSerializer()); - mapper.registerModule(serializerModule); - final Car car = new Car("yellow", "renault"); - final String carJson = mapper.writeValueAsString(car); - assertThat(carJson, containsString("renault")); - assertThat(carJson, containsString("model")); - - final SimpleModule deserializerModule = new SimpleModule("CustomCarDeserializer", new Version(1, 0, 0, null, null, null)); - deserializerModule.addDeserializer(Car.class, new CustomCarDeserializer()); - mapper.registerModule(deserializerModule); - final Car carResult = mapper.readValue(EXAMPLE_JSON, Car.class); - assertNotNull(carResult); - assertThat(carResult.getColor(), equalTo("Black")); - } - - @Test - public void whenDateFormatSet_thanSerializedAsExpected() throws Exception { - final ObjectMapper objectMapper = new ObjectMapper(); - final Car car = new Car("yellow", "renault"); - final Request request = new Request(); - request.setCar(car); - request.setDatePurchased(new Date()); - final DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm a z"); - objectMapper.setDateFormat(df); - final String carAsString = objectMapper.writeValueAsString(request); - assertNotNull(carAsString); - assertThat(carAsString, containsString("datePurchased")); - } - - @Test - public void whenUseJavaArrayForJsonArrayTrue_thanJsonReadAsArray() throws Exception { - final ObjectMapper objectMapper = new ObjectMapper(); - objectMapper.configure(DeserializationFeature.USE_JAVA_ARRAY_FOR_JSON_ARRAY, true); - final Car[] cars = objectMapper.readValue(JSON_ARRAY, Car[].class); - for (final Car car : cars) { - assertNotNull(car); - assertThat(car.getType(), equalTo("BMW")); - } - } -} diff --git a/jackson-simple/src/test/java/com/ossez/jackson/unknownproperties/UnknownPropertiesUnitTest.java b/jackson-simple/src/test/java/com/ossez/jackson/unknownproperties/UnknownPropertiesUnitTest.java deleted file mode 100644 index 58df5c49de..0000000000 --- a/jackson-simple/src/test/java/com/ossez/jackson/unknownproperties/UnknownPropertiesUnitTest.java +++ /dev/null @@ -1,80 +0,0 @@ -package com.ossez.jackson.unknownproperties; - -import com.fasterxml.jackson.core.JsonParseException; -import com.fasterxml.jackson.databind.DeserializationFeature; -import com.fasterxml.jackson.databind.JsonMappingException; -import com.fasterxml.jackson.databind.ObjectMapper; -import com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException; -import org.junit.Test; - -import java.io.IOException; - -import static org.hamcrest.Matchers.equalTo; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertThat; - -public class UnknownPropertiesUnitTest { - - @Test - public final void givenNotAllFieldsHaveValuesInJson_whenDeserializingAJsonToAClass_thenCorrect() throws JsonParseException, JsonMappingException, IOException { - final String jsonAsString = "{\"stringValue\":\"a\",\"booleanValue\":true}"; - final ObjectMapper mapper = new ObjectMapper(); - - final MyDto readValue = mapper.readValue(jsonAsString, MyDto.class); - - assertNotNull(readValue); - assertThat(readValue.getStringValue(), equalTo("a")); - assertThat(readValue.isBooleanValue(), equalTo(true)); - } - - // tests - json with unknown fields - - @Test(expected = UnrecognizedPropertyException.class) - public final void givenJsonHasUnknownValues_whenDeserializingAJsonToAClass_thenExceptionIsThrown() throws JsonParseException, JsonMappingException, IOException { - final String jsonAsString = "{\"stringValue\":\"a\",\"intValue\":1,\"booleanValue\":true,\"stringValue2\":\"something\"}"; - final ObjectMapper mapper = new ObjectMapper(); - - final MyDto readValue = mapper.readValue(jsonAsString, MyDto.class); - - assertNotNull(readValue); - assertThat(readValue.getStringValue(), equalTo("a")); - assertThat(readValue.isBooleanValue(), equalTo(true)); - assertThat(readValue.getIntValue(), equalTo(1)); - } - - @Test - public final void givenJsonHasUnknownValuesButJacksonIsIgnoringUnknownFields_whenDeserializing_thenCorrect() throws JsonParseException, JsonMappingException, IOException { - final String jsonAsString = // @formatter:off - "{\"stringValue\":\"a\"," + - "\"intValue\":1," + - "\"booleanValue\":true," + - "\"stringValue2\":\"something\"}"; // @formatter:on - final ObjectMapper mapper = new ObjectMapper(); - mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); - - final MyDto readValue = mapper.readValue(jsonAsString, MyDto.class); - - assertNotNull(readValue); - assertThat(readValue.getStringValue(), equalTo("a")); - assertThat(readValue.isBooleanValue(), equalTo(true)); - assertThat(readValue.getIntValue(), equalTo(1)); - } - - @Test - public final void givenJsonHasUnknownValuesButUnknownFieldsAreIgnoredOnClass_whenDeserializing_thenCorrect() throws JsonParseException, JsonMappingException, IOException { - final String jsonAsString = // @formatter:off - "{\"stringValue\":\"a\"," + - "\"intValue\":1," + - "\"booleanValue\":true," + - "\"stringValue2\":\"something\"}"; // @formatter:on - final ObjectMapper mapper = new ObjectMapper(); - - final MyDtoIgnoreUnknown readValue = mapper.readValue(jsonAsString, MyDtoIgnoreUnknown.class); - - assertNotNull(readValue); - assertThat(readValue.getStringValue(), equalTo("a")); - assertThat(readValue.isBooleanValue(), equalTo(true)); - assertThat(readValue.getIntValue(), equalTo(1)); - } - -} diff --git a/jackson-simple/src/test/resources/json_car.json b/jackson-simple/src/test/resources/json_car.json deleted file mode 100644 index 2f6b35b523..0000000000 --- a/jackson-simple/src/test/resources/json_car.json +++ /dev/null @@ -1,4 +0,0 @@ -{ - "color": "Black", - "type": "BMW" -} \ No newline at end of file diff --git a/spring-batch/.gitignore b/spring-batch/.gitignore deleted file mode 100644 index 0ef6d10b38..0000000000 --- a/spring-batch/.gitignore +++ /dev/null @@ -1 +0,0 @@ -output.csv \ No newline at end of file diff --git a/spring-batch/README.md b/spring-batch/README.md deleted file mode 100644 index 95abbaf931..0000000000 --- a/spring-batch/README.md +++ /dev/null @@ -1,9 +0,0 @@ -## Spring Batch - -This module contains articles about Spring Batch - -### Relevant Articles: -- [Introduction to Spring Batch](https://www.baeldung.com/introduction-to-spring-batch) -- [Spring Batch using Partitioner](https://www.baeldung.com/spring-batch-partitioner) -- [Spring Batch – Tasklets vs Chunks](https://www.baeldung.com/spring-batch-tasklet-chunk) -- [How to Trigger and Stop a Scheduled Spring Batch Job](https://www.baeldung.com/spring-batch-start-stop-job) diff --git a/spring-batch/pom.xml b/spring-batch/pom.xml deleted file mode 100644 index 238f03afd7..0000000000 --- a/spring-batch/pom.xml +++ /dev/null @@ -1,116 +0,0 @@ - - 4.0.0 - - spring-batch - 0.1-SNAPSHOT - - - - org.apache.maven.plugins - maven-compiler-plugin - 3.8.1 - - 11 - 11 - - - - - spring-batch - jar - - - parent-boot-2 - com.ossez - 0.0.1-SNAPSHOT - ../parent-boot-2 - - - - - - - javax.xml.bind - jaxb-api - ${jaxb.version} - - - - org.glassfish.jaxb - jaxb-runtime - ${jaxb.version} - runtime - - - - - org.xerial - sqlite-jdbc - ${sqlite.version} - - - - org.springframework - spring-oxm - ${spring.version} - - - commons-logging - commons-logging - - - - - - org.springframework - spring-jdbc - ${spring.version} - - - - org.springframework.batch - spring-batch-core - ${spring.batch.version} - - - - org.springframework.batch - spring-batch-test - ${spring.batch.version} - - - - com.opencsv - opencsv - ${opencsv.version} - - - - org.springframework.boot - spring-boot-starter-batch - - - - org.hsqldb - hsqldb - runtime - - - - org.awaitility - awaitility - ${awaitility.version} - test - - - - - 5.3.0 - 4.3.0 - 3.15.1 - 4.1 - 2.3.1 - 3.1.1 - - diff --git a/spring-batch/repository.sqlite b/spring-batch/repository.sqlite deleted file mode 100644 index 86cf9c3f9e..0000000000 Binary files a/spring-batch/repository.sqlite and /dev/null differ diff --git a/spring-batch/src/main/java/com/ossez/spring/batch/App.java b/spring-batch/src/main/java/com/ossez/spring/batch/App.java deleted file mode 100644 index e8e46c1cf1..0000000000 --- a/spring-batch/src/main/java/com/ossez/spring/batch/App.java +++ /dev/null @@ -1,45 +0,0 @@ -package com.ossez.spring.batch; - -import org.springframework.batch.core.Job; -import org.springframework.batch.core.JobExecution; -import org.springframework.batch.core.JobParameters; -import org.springframework.batch.core.JobParametersBuilder; -import org.springframework.batch.core.launch.JobLauncher; -import org.springframework.context.annotation.AnnotationConfigApplicationContext; - -public class App { - public static void main(final String[] args) { - // Spring Java config - final AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(); - context.register(SpringConfig.class); - context.register(SpringBatchConfig.class); - context.refresh(); - - // Spring xml config - // ApplicationContext context = new ClassPathXmlApplicationContext("spring-batch.xml"); - - runJob(context, "firstBatchJob"); - runJob(context, "skippingBatchJob"); - runJob(context, "skipPolicyBatchJob"); - } - - private static void runJob(AnnotationConfigApplicationContext context, String batchJobName) { - final JobLauncher jobLauncher = (JobLauncher) context.getBean("jobLauncher"); - final Job job = (Job) context.getBean(batchJobName); - - System.out.println("----------------------------------------"); - System.out.println("Starting the batch job: " + batchJobName); - try { - // To enable multiple execution of a job with the same parameters - JobParameters jobParameters = new JobParametersBuilder() - .addString("jobID", String.valueOf(System.currentTimeMillis())) - .toJobParameters(); - final JobExecution execution = jobLauncher.run(job, jobParameters); - System.out.println("Job Status : " + execution.getStatus()); - System.out.println("Job succeeded"); - } catch (final Exception e) { - e.printStackTrace(); - System.out.println("Job failed"); - } - } -} diff --git a/spring-batch/src/main/java/com/ossez/spring/batch/Application.java b/spring-batch/src/main/java/com/ossez/spring/batch/Application.java deleted file mode 100644 index c73dd19864..0000000000 --- a/spring-batch/src/main/java/com/ossez/spring/batch/Application.java +++ /dev/null @@ -1,12 +0,0 @@ -package com.ossez.spring.batch; - -import org.springframework.boot.SpringApplication; -import org.springframework.boot.autoconfigure.SpringBootApplication; - -@SpringBootApplication -public class Application { - - public static void main(String[] args) throws Exception { - SpringApplication.run(Application.class, args); - } -} diff --git a/spring-batch/src/main/java/com/ossez/spring/batch/SpringBatchConfig.java b/spring-batch/src/main/java/com/ossez/spring/batch/SpringBatchConfig.java deleted file mode 100644 index 73a7858a3e..0000000000 --- a/spring-batch/src/main/java/com/ossez/spring/batch/SpringBatchConfig.java +++ /dev/null @@ -1,145 +0,0 @@ -package com.ossez.spring.batch; - -import com.ossez.spring.batch.model.Transaction; -import com.ossez.spring.batch.service.CustomItemProcessor; -import com.ossez.spring.batch.service.CustomSkipPolicy; -import com.ossez.spring.batch.service.MissingUsernameException; -import com.ossez.spring.batch.service.NegativeAmountException; -import com.ossez.spring.batch.service.RecordFieldSetMapper; -import com.ossez.spring.batch.service.SkippingItemProcessor; -import org.springframework.batch.core.Job; -import org.springframework.batch.core.Step; -import org.springframework.batch.core.configuration.annotation.JobBuilderFactory; -import org.springframework.batch.core.configuration.annotation.StepBuilderFactory; -import org.springframework.batch.item.ItemProcessor; -import org.springframework.batch.item.ItemReader; -import org.springframework.batch.item.ItemWriter; -import org.springframework.batch.item.UnexpectedInputException; -import org.springframework.batch.item.file.FlatFileItemReader; -import org.springframework.batch.item.file.mapping.DefaultLineMapper; -import org.springframework.batch.item.file.transform.DelimitedLineTokenizer; -import org.springframework.batch.item.xml.StaxEventItemWriter; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Qualifier; -import org.springframework.beans.factory.annotation.Value; -import org.springframework.context.annotation.Bean; -import org.springframework.core.io.Resource; -import org.springframework.oxm.Marshaller; -import org.springframework.oxm.jaxb.Jaxb2Marshaller; - -import java.text.ParseException; - -public class SpringBatchConfig { - @Autowired - private JobBuilderFactory jobBuilderFactory; - - @Autowired - private StepBuilderFactory stepBuilderFactory; - - @Value("input/record.csv") - private Resource inputCsv; - - @Value("input/recordWithInvalidData.csv") - private Resource invalidInputCsv; - - @Value("file:xml/output.xml") - private Resource outputXml; - - public ItemReader itemReader(Resource inputData) throws UnexpectedInputException, ParseException { - FlatFileItemReader reader = new FlatFileItemReader<>(); - DelimitedLineTokenizer tokenizer = new DelimitedLineTokenizer(); - String[] tokens = {"username", "userid", "transactiondate", "amount"}; - tokenizer.setNames(tokens); - reader.setResource(inputData); - DefaultLineMapper lineMapper = new DefaultLineMapper<>(); - lineMapper.setLineTokenizer(tokenizer); - lineMapper.setFieldSetMapper(new RecordFieldSetMapper()); - reader.setLinesToSkip(1); - reader.setLineMapper(lineMapper); - return reader; - } - - @Bean - public ItemProcessor itemProcessor() { - return new CustomItemProcessor(); - } - - @Bean - public ItemProcessor skippingItemProcessor() { - return new SkippingItemProcessor(); - } - - @Bean - public ItemWriter itemWriter(Marshaller marshaller) { - StaxEventItemWriter itemWriter = new StaxEventItemWriter<>(); - itemWriter.setMarshaller(marshaller); - itemWriter.setRootTagName("transactionRecord"); - itemWriter.setResource(outputXml); - return itemWriter; - } - - @Bean - public Marshaller marshaller() { - Jaxb2Marshaller marshaller = new Jaxb2Marshaller(); - marshaller.setClassesToBeBound(Transaction.class); - return marshaller; - } - - @Bean - protected Step step1(@Qualifier("itemProcessor") ItemProcessor processor, - ItemWriter writer) throws ParseException { - return stepBuilderFactory.get("step1").chunk(10).reader(itemReader(inputCsv)).processor(processor).writer(writer).build(); - } - - @Bean(name = "firstBatchJob") - public Job job(@Qualifier("step1") Step step1) { - return jobBuilderFactory.get("firstBatchJob").start(step1).build(); - } - - @Bean - public Step skippingStep(@Qualifier("skippingItemProcessor") ItemProcessor processor, - ItemWriter writer) throws ParseException { - return stepBuilderFactory - .get("skippingStep") - .chunk(10) - .reader(itemReader(invalidInputCsv)) - .processor(processor) - .writer(writer) - .faultTolerant() - .skipLimit(2) - .skip(MissingUsernameException.class) - .skip(NegativeAmountException.class) - .build(); - } - - @Bean(name = "skippingBatchJob") - public Job skippingJob(@Qualifier("skippingStep") Step skippingStep) { - return jobBuilderFactory - .get("skippingBatchJob") - .start(skippingStep) - .build(); - } - - @Bean - public Step skipPolicyStep(@Qualifier("skippingItemProcessor") ItemProcessor processor, - ItemWriter writer) throws ParseException { - return stepBuilderFactory - .get("skipPolicyStep") - .chunk(10) - .reader(itemReader(invalidInputCsv)) - .processor(processor) - .writer(writer) - .faultTolerant() - .skipPolicy(new CustomSkipPolicy()) - .build(); - } - - @Bean(name = "skipPolicyBatchJob") - public Job skipPolicyBatchJob(@Qualifier("skipPolicyStep") Step skipPolicyStep) { - return jobBuilderFactory - .get("skipPolicyBatchJob") - .start(skipPolicyStep) - .build(); - } - -} diff --git a/spring-batch/src/main/java/com/ossez/spring/batch/SpringConfig.java b/spring-batch/src/main/java/com/ossez/spring/batch/SpringConfig.java deleted file mode 100644 index 23390fe22f..0000000000 --- a/spring-batch/src/main/java/com/ossez/spring/batch/SpringConfig.java +++ /dev/null @@ -1,78 +0,0 @@ -package com.ossez.spring.batch; - -import java.net.MalformedURLException; - -import javax.sql.DataSource; - -import org.springframework.batch.core.configuration.annotation.EnableBatchProcessing; -import org.springframework.batch.core.launch.JobLauncher; -import org.springframework.batch.core.launch.support.SimpleJobLauncher; -import org.springframework.batch.core.repository.JobRepository; -import org.springframework.batch.core.repository.support.JobRepositoryFactoryBean; -import org.springframework.batch.support.transaction.ResourcelessTransactionManager; -import org.springframework.beans.factory.annotation.Value; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.core.io.Resource; -import org.springframework.jdbc.datasource.DriverManagerDataSource; -import org.springframework.jdbc.datasource.init.DataSourceInitializer; -import org.springframework.jdbc.datasource.init.ResourceDatabasePopulator; -import org.springframework.transaction.PlatformTransactionManager; - -@Configuration -@EnableBatchProcessing -public class SpringConfig { - - @Value("org/springframework/batch/core/schema-drop-sqlite.sql") - private Resource dropReopsitoryTables; - - @Value("org/springframework/batch/core/schema-sqlite.sql") - private Resource dataReopsitorySchema; - - @Bean - public DataSource dataSource() { - DriverManagerDataSource dataSource = new DriverManagerDataSource(); - dataSource.setDriverClassName("org.sqlite.JDBC"); - dataSource.setUrl("jdbc:sqlite:repository.sqlite"); - return dataSource; - } - - @Bean - public DataSourceInitializer dataSourceInitializer(DataSource dataSource) throws MalformedURLException { - ResourceDatabasePopulator databasePopulator = new ResourceDatabasePopulator(); - - databasePopulator.addScript(dropReopsitoryTables); - databasePopulator.addScript(dataReopsitorySchema); - databasePopulator.setIgnoreFailedDrops(true); - - DataSourceInitializer initializer = new DataSourceInitializer(); - initializer.setDataSource(dataSource); - initializer.setDatabasePopulator(databasePopulator); - - return initializer; - } - - private JobRepository getJobRepository() throws Exception { - JobRepositoryFactoryBean factory = new JobRepositoryFactoryBean(); - factory.setDataSource(dataSource()); - factory.setTransactionManager(getTransactionManager()); - // JobRepositoryFactoryBean's methods Throws Generic Exception, - // it would have been better to have a specific one - factory.afterPropertiesSet(); - return (JobRepository) factory.getObject(); - } - - private PlatformTransactionManager getTransactionManager() { - return new ResourcelessTransactionManager(); - } - - public JobLauncher getJobLauncher() throws Exception { - SimpleJobLauncher jobLauncher = new SimpleJobLauncher(); - // SimpleJobLauncher's methods Throws Generic Exception, - // it would have been better to have a specific one - jobLauncher.setJobRepository(getJobRepository()); - jobLauncher.afterPropertiesSet(); - return jobLauncher; - } - -} diff --git a/spring-batch/src/main/java/com/ossez/spring/batch/model/Transaction.java b/spring-batch/src/main/java/com/ossez/spring/batch/model/Transaction.java deleted file mode 100644 index 9349b747a4..0000000000 --- a/spring-batch/src/main/java/com/ossez/spring/batch/model/Transaction.java +++ /dev/null @@ -1,53 +0,0 @@ -package com.ossez.spring.batch.model; - -import javax.xml.bind.annotation.XmlRootElement; -import java.util.Date; - -@SuppressWarnings("restriction") -@XmlRootElement(name = "transactionRecord") -public class Transaction { - private String username; - private int userId; - private Date transactionDate; - private double amount; - - /* getters and setters for the attributes */ - - public String getUsername() { - return username; - } - - public void setUsername(String username) { - this.username = username; - } - - public int getUserId() { - return userId; - } - - public void setUserId(int userId) { - this.userId = userId; - } - - public Date getTransactionDate() { - return transactionDate; - } - - public void setTransactionDate(Date transactionDate) { - this.transactionDate = transactionDate; - } - - public double getAmount() { - return amount; - } - - public void setAmount(double amount) { - this.amount = amount; - } - - @Override - public String toString() { - return "Transaction [username=" + username + ", userId=" + userId + ", transactionDate=" + transactionDate + ", amount=" + amount + "]"; - } - -} diff --git a/spring-batch/src/main/java/com/ossez/spring/batch/partitioner/CustomMultiResourcePartitioner.java b/spring-batch/src/main/java/com/ossez/spring/batch/partitioner/CustomMultiResourcePartitioner.java deleted file mode 100644 index 10c158b3ca..0000000000 --- a/spring-batch/src/main/java/com/ossez/spring/batch/partitioner/CustomMultiResourcePartitioner.java +++ /dev/null @@ -1,77 +0,0 @@ -/* - * Copyright 2006-2013 the original author or 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 com.ossez.spring.batch.partitioner; - -import java.util.HashMap; -import java.util.Map; - -import org.springframework.batch.core.partition.support.Partitioner; -import org.springframework.batch.item.ExecutionContext; -import org.springframework.core.io.Resource; -import org.springframework.util.Assert; - -public class CustomMultiResourcePartitioner implements Partitioner { - - private static final String DEFAULT_KEY_NAME = "fileName"; - - private static final String PARTITION_KEY = "partition"; - - private Resource[] resources = new Resource[0]; - - private String keyName = DEFAULT_KEY_NAME; - - /** - * The resources to assign to each partition. In Spring configuration you - * can use a pattern to select multiple resources. - * @param resources the resources to use - */ - public void setResources(Resource[] resources) { - this.resources = resources; - } - - /** - * The name of the key for the file name in each {@link ExecutionContext}. - * Defaults to "fileName". - * @param keyName the value of the key - */ - public void setKeyName(String keyName) { - this.keyName = keyName; - } - - /** - * Assign the filename of each of the injected resources to an - * {@link ExecutionContext}. - * - * @see Partitioner#partition(int) - */ - @Override - public Map partition(int gridSize) { - Map map = new HashMap(gridSize); - int i = 0, k = 1; - for (Resource resource : resources) { - ExecutionContext context = new ExecutionContext(); - Assert.state(resource.exists(), "Resource does not exist: " + resource); - context.putString(keyName, resource.getFilename()); - context.putString("opFileName", "output" + k++ + ".xml"); - - map.put(PARTITION_KEY + i, context); - i++; - } - return map; - } - -} diff --git a/spring-batch/src/main/java/com/ossez/spring/batch/partitioner/SpringbatchPartitionConfig.java b/spring-batch/src/main/java/com/ossez/spring/batch/partitioner/SpringbatchPartitionConfig.java deleted file mode 100644 index 7bf2977519..0000000000 --- a/spring-batch/src/main/java/com/ossez/spring/batch/partitioner/SpringbatchPartitionConfig.java +++ /dev/null @@ -1,166 +0,0 @@ -package com.ossez.spring.batch.partitioner; - -import com.ossez.spring.batch.model.Transaction; -import com.ossez.spring.batch.service.RecordFieldSetMapper; -import org.springframework.batch.core.Job; -import org.springframework.batch.core.Step; -import org.springframework.batch.core.configuration.annotation.EnableBatchProcessing; -import org.springframework.batch.core.configuration.annotation.JobBuilderFactory; -import org.springframework.batch.core.configuration.annotation.StepBuilderFactory; -import org.springframework.batch.core.configuration.annotation.StepScope; -import org.springframework.batch.core.launch.JobLauncher; -import org.springframework.batch.core.launch.support.SimpleJobLauncher; -import org.springframework.batch.core.repository.JobRepository; -import org.springframework.batch.core.repository.support.JobRepositoryFactoryBean; -import org.springframework.batch.item.UnexpectedInputException; -import org.springframework.batch.item.file.FlatFileItemReader; -import org.springframework.batch.item.file.mapping.DefaultLineMapper; -import org.springframework.batch.item.file.transform.DelimitedLineTokenizer; -import org.springframework.batch.item.xml.StaxEventItemWriter; -import org.springframework.batch.support.transaction.ResourcelessTransactionManager; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Value; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.core.io.ClassPathResource; -import org.springframework.core.io.FileSystemResource; -import org.springframework.core.io.Resource; -import org.springframework.core.io.support.ResourcePatternResolver; -import org.springframework.core.task.TaskExecutor; -import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseBuilder; -import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseType; -import org.springframework.oxm.Marshaller; -import org.springframework.oxm.jaxb.Jaxb2Marshaller; -import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor; -import org.springframework.transaction.PlatformTransactionManager; - -import javax.sql.DataSource; -import java.io.IOException; -import java.net.MalformedURLException; -import java.text.ParseException; - -@Configuration -@EnableBatchProcessing -public class SpringbatchPartitionConfig { - - @Autowired - ResourcePatternResolver resoursePatternResolver; - - @Autowired - private JobBuilderFactory jobs; - - @Autowired - private StepBuilderFactory steps; - - @Bean(name = "partitionerJob") - public Job partitionerJob() throws UnexpectedInputException, MalformedURLException, ParseException { - return jobs.get("partitionerJob") - .start(partitionStep()) - .build(); - } - - @Bean - public Step partitionStep() throws UnexpectedInputException, MalformedURLException, ParseException { - return steps.get("partitionStep") - .partitioner("slaveStep", partitioner()) - .step(slaveStep()) - .taskExecutor(taskExecutor()) - .build(); - } - - @Bean - public Step slaveStep() throws UnexpectedInputException, MalformedURLException, ParseException { - return steps.get("slaveStep") - .chunk(1) - .reader(itemReader(null)) - .writer(itemWriter(marshaller(), null)) - .build(); - } - - @Bean - public CustomMultiResourcePartitioner partitioner() { - CustomMultiResourcePartitioner partitioner = new CustomMultiResourcePartitioner(); - Resource[] resources; - try { - resources = resoursePatternResolver.getResources("file:src/main/resources/input/partitioner/*.csv"); - } catch (IOException e) { - throw new RuntimeException("I/O problems when resolving the input file pattern.", e); - } - partitioner.setResources(resources); - return partitioner; - } - - @Bean - @StepScope - public FlatFileItemReader itemReader(@Value("#{stepExecutionContext[fileName]}") String filename) throws UnexpectedInputException, ParseException { - FlatFileItemReader reader = new FlatFileItemReader<>(); - DelimitedLineTokenizer tokenizer = new DelimitedLineTokenizer(); - String[] tokens = {"username", "userid", "transactiondate", "amount"}; - tokenizer.setNames(tokens); - reader.setResource(new ClassPathResource("input/partitioner/" + filename)); - DefaultLineMapper lineMapper = new DefaultLineMapper<>(); - lineMapper.setLineTokenizer(tokenizer); - lineMapper.setFieldSetMapper(new RecordFieldSetMapper()); - reader.setLinesToSkip(1); - reader.setLineMapper(lineMapper); - return reader; - } - - @Bean(destroyMethod = "") - @StepScope - public StaxEventItemWriter itemWriter(Marshaller marshaller, @Value("#{stepExecutionContext[opFileName]}") String filename) throws MalformedURLException { - StaxEventItemWriter itemWriter = new StaxEventItemWriter<>(); - itemWriter.setMarshaller(marshaller); - itemWriter.setRootTagName("transactionRecord"); - itemWriter.setResource(new FileSystemResource("src/main/resources/output/" + filename)); - return itemWriter; - } - - @Bean - public Marshaller marshaller() { - Jaxb2Marshaller marshaller = new Jaxb2Marshaller(); - marshaller.setClassesToBeBound(Transaction.class); - return marshaller; - } - - @Bean - public TaskExecutor taskExecutor() { - ThreadPoolTaskExecutor taskExecutor = new ThreadPoolTaskExecutor(); - taskExecutor.setMaxPoolSize(5); - taskExecutor.setCorePoolSize(5); - taskExecutor.setQueueCapacity(5); - taskExecutor.afterPropertiesSet(); - return taskExecutor; - } - - private JobRepository getJobRepository() throws Exception { - JobRepositoryFactoryBean factory = new JobRepositoryFactoryBean(); - factory.setDataSource(dataSource()); - factory.setTransactionManager(getTransactionManager()); - // JobRepositoryFactoryBean's methods Throws Generic Exception, - // it would have been better to have a specific one - factory.afterPropertiesSet(); - return factory.getObject(); - } - - private DataSource dataSource() { - EmbeddedDatabaseBuilder builder = new EmbeddedDatabaseBuilder(); - return builder.setType(EmbeddedDatabaseType.HSQL) - .addScript("classpath:org/springframework/batch/core/schema-drop-h2.sql") - .addScript("classpath:org/springframework/batch/core/schema-h2.sql") - .build(); - } - - private PlatformTransactionManager getTransactionManager() { - return new ResourcelessTransactionManager(); - } - - public JobLauncher getJobLauncher() throws Exception { - SimpleJobLauncher jobLauncher = new SimpleJobLauncher(); - // SimpleJobLauncher's methods Throws Generic Exception, - // it would have been better to have a specific one - jobLauncher.setJobRepository(getJobRepository()); - jobLauncher.afterPropertiesSet(); - return jobLauncher; - } -} diff --git a/spring-batch/src/main/java/com/ossez/spring/batch/partitioner/SpringbatchPartitionerApp.java b/spring-batch/src/main/java/com/ossez/spring/batch/partitioner/SpringbatchPartitionerApp.java deleted file mode 100644 index 2896fe8268..0000000000 --- a/spring-batch/src/main/java/com/ossez/spring/batch/partitioner/SpringbatchPartitionerApp.java +++ /dev/null @@ -1,28 +0,0 @@ -package com.ossez.spring.batch.partitioner; - -import org.springframework.batch.core.Job; -import org.springframework.batch.core.JobExecution; -import org.springframework.batch.core.JobParameters; -import org.springframework.batch.core.launch.JobLauncher; -import org.springframework.context.annotation.AnnotationConfigApplicationContext; - -public class SpringbatchPartitionerApp { - public static void main(final String[] args) { - // Spring Java config - final AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(); - context.register(SpringbatchPartitionConfig.class); - context.refresh(); - - final JobLauncher jobLauncher = (JobLauncher) context.getBean("jobLauncher"); - final Job job = (Job) context.getBean("partitionerJob"); - System.out.println("Starting the batch job"); - try { - final JobExecution execution = jobLauncher.run(job, new JobParameters()); - System.out.println("Job Status : " + execution.getStatus()); - System.out.println("Job succeeded"); - } catch (final Exception e) { - e.printStackTrace(); - System.out.println("Job failed"); - } - } -} diff --git a/spring-batch/src/main/java/com/ossez/spring/batch/service/CustomItemProcessor.java b/spring-batch/src/main/java/com/ossez/spring/batch/service/CustomItemProcessor.java deleted file mode 100644 index 451806f856..0000000000 --- a/spring-batch/src/main/java/com/ossez/spring/batch/service/CustomItemProcessor.java +++ /dev/null @@ -1,12 +0,0 @@ -package com.ossez.spring.batch.service; - -import org.baeldung.batch.model.Transaction; -import org.springframework.batch.item.ItemProcessor; - -public class CustomItemProcessor implements ItemProcessor { - - public Transaction process(Transaction item) { - System.out.println("Processing..." + item); - return item; - } -} diff --git a/spring-batch/src/main/java/com/ossez/spring/batch/service/CustomSkipPolicy.java b/spring-batch/src/main/java/com/ossez/spring/batch/service/CustomSkipPolicy.java deleted file mode 100644 index 25be1840bd..0000000000 --- a/spring-batch/src/main/java/com/ossez/spring/batch/service/CustomSkipPolicy.java +++ /dev/null @@ -1,29 +0,0 @@ -package com.ossez.spring.batch.service; - -import org.springframework.batch.core.step.skip.SkipLimitExceededException; -import org.springframework.batch.core.step.skip.SkipPolicy; - -public class CustomSkipPolicy implements SkipPolicy { - - private static final int MAX_SKIP_COUNT = 2; - private static final int INVALID_TX_AMOUNT_LIMIT = -1000; - - @Override - public boolean shouldSkip(Throwable throwable, int skipCount) throws SkipLimitExceededException { - - if (throwable instanceof MissingUsernameException && skipCount < MAX_SKIP_COUNT) { - return true; - } - - if (throwable instanceof NegativeAmountException && skipCount < MAX_SKIP_COUNT ) { - NegativeAmountException ex = (NegativeAmountException) throwable; - if(ex.getAmount() < INVALID_TX_AMOUNT_LIMIT){ - return false; - } else{ - return true; - } - } - - return false; - } -} diff --git a/spring-batch/src/main/java/com/ossez/spring/batch/service/MissingUsernameException.java b/spring-batch/src/main/java/com/ossez/spring/batch/service/MissingUsernameException.java deleted file mode 100644 index 624dcb7ab9..0000000000 --- a/spring-batch/src/main/java/com/ossez/spring/batch/service/MissingUsernameException.java +++ /dev/null @@ -1,4 +0,0 @@ -package com.ossez.spring.batch.service; - -public class MissingUsernameException extends RuntimeException { -} diff --git a/spring-batch/src/main/java/com/ossez/spring/batch/service/NegativeAmountException.java b/spring-batch/src/main/java/com/ossez/spring/batch/service/NegativeAmountException.java deleted file mode 100644 index 125bc0d393..0000000000 --- a/spring-batch/src/main/java/com/ossez/spring/batch/service/NegativeAmountException.java +++ /dev/null @@ -1,14 +0,0 @@ -package com.ossez.spring.batch.service; - -public class NegativeAmountException extends RuntimeException { - - private double amount; - - public NegativeAmountException(double amount){ - this.amount = amount; - } - - public double getAmount() { - return amount; - } -} diff --git a/spring-batch/src/main/java/com/ossez/spring/batch/service/RecordFieldSetMapper.java b/spring-batch/src/main/java/com/ossez/spring/batch/service/RecordFieldSetMapper.java deleted file mode 100644 index 3729b3744f..0000000000 --- a/spring-batch/src/main/java/com/ossez/spring/batch/service/RecordFieldSetMapper.java +++ /dev/null @@ -1,35 +0,0 @@ -package com.ossez.spring.batch.service; - -import java.text.ParseException; -import java.text.SimpleDateFormat; - -import com.ossez.spring.batch.model.Transaction; -import org.springframework.batch.item.file.mapping.FieldSetMapper; -import org.springframework.batch.item.file.transform.FieldSet; -import org.springframework.validation.BindException; - -public class RecordFieldSetMapper implements FieldSetMapper { - - public Transaction mapFieldSet(FieldSet fieldSet) throws BindException { - - SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy"); - Transaction transaction = new Transaction(); - // you can either use the indices or custom names - // I personally prefer the custom names easy for debugging and - // validating the pipelines - transaction.setUsername(fieldSet.readString("username")); - transaction.setUserId(fieldSet.readInt("userid")); - transaction.setAmount(fieldSet.readDouble(3)); - // Converting the date - String dateString = fieldSet.readString(2); - try { - transaction.setTransactionDate(dateFormat.parse(dateString)); - } catch (ParseException e) { - e.printStackTrace(); - } - - return transaction; - - } - -} diff --git a/spring-batch/src/main/java/com/ossez/spring/batch/service/SkippingItemProcessor.java b/spring-batch/src/main/java/com/ossez/spring/batch/service/SkippingItemProcessor.java deleted file mode 100644 index 0333e2561e..0000000000 --- a/spring-batch/src/main/java/com/ossez/spring/batch/service/SkippingItemProcessor.java +++ /dev/null @@ -1,24 +0,0 @@ -package com.ossez.spring.batch.service; - -import com.ossez.spring.batch.model.Transaction; -import org.springframework.batch.item.ItemProcessor; - -public class SkippingItemProcessor implements ItemProcessor { - - @Override - public Transaction process(Transaction transaction) { - - System.out.println("SkippingItemProcessor: " + transaction); - - if (transaction.getUsername() == null || transaction.getUsername().isEmpty()) { - throw new MissingUsernameException(); - } - - double txAmount = transaction.getAmount(); - if (txAmount < 0) { - throw new NegativeAmountException(txAmount); - } - - return transaction; - } -} diff --git a/spring-batch/src/main/java/com/ossez/spring/batchscheduler/SpringBatchScheduler.java b/spring-batch/src/main/java/com/ossez/spring/batchscheduler/SpringBatchScheduler.java deleted file mode 100644 index 4c82bfaddf..0000000000 --- a/spring-batch/src/main/java/com/ossez/spring/batchscheduler/SpringBatchScheduler.java +++ /dev/null @@ -1,172 +0,0 @@ -package com.ossez.spring.batchscheduler; - -import java.util.Date; -import java.util.IdentityHashMap; -import java.util.List; -import java.util.Map; -import java.util.concurrent.ScheduledFuture; -import java.util.concurrent.atomic.AtomicBoolean; -import java.util.concurrent.atomic.AtomicInteger; -import org.baeldung.batchscheduler.model.Book; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.batch.core.Job; -import org.springframework.batch.core.JobExecution; -import org.springframework.batch.core.JobParametersBuilder; -import org.springframework.batch.core.Step; -import org.springframework.batch.core.configuration.annotation.EnableBatchProcessing; -import org.springframework.batch.core.configuration.annotation.JobBuilderFactory; -import org.springframework.batch.core.configuration.annotation.StepBuilderFactory; -import org.springframework.batch.core.launch.JobLauncher; -import org.springframework.batch.core.launch.support.SimpleJobLauncher; -import org.springframework.batch.core.repository.JobRepository; -import org.springframework.batch.core.repository.support.MapJobRepositoryFactoryBean; -import org.springframework.batch.item.ItemWriter; -import org.springframework.batch.item.file.FlatFileItemReader; -import org.springframework.batch.item.file.builder.FlatFileItemReaderBuilder; -import org.springframework.batch.item.file.mapping.BeanWrapperFieldSetMapper; -import org.springframework.batch.support.transaction.ResourcelessTransactionManager; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.core.io.ClassPathResource; -import org.springframework.scheduling.TaskScheduler; -import org.springframework.scheduling.annotation.EnableScheduling; -import org.springframework.scheduling.annotation.Scheduled; -import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler; -import org.springframework.scheduling.support.ScheduledMethodRunnable; - -@Configuration -@EnableBatchProcessing -@EnableScheduling -public class SpringBatchScheduler { - - private final Logger logger = LoggerFactory.getLogger(SpringBatchScheduler.class); - - private AtomicBoolean enabled = new AtomicBoolean(true); - - private AtomicInteger batchRunCounter = new AtomicInteger(0); - - private final Map> scheduledTasks = new IdentityHashMap<>(); - - @Autowired - private JobBuilderFactory jobBuilderFactory; - - @Autowired - private StepBuilderFactory stepBuilderFactory; - - @Scheduled(fixedRate = 2000) - public void launchJob() throws Exception { - Date date = new Date(); - logger.debug("scheduler starts at " + date); - if (enabled.get()) { - JobExecution jobExecution = jobLauncher().run(job(), new JobParametersBuilder().addDate("launchDate", date) - .toJobParameters()); - batchRunCounter.incrementAndGet(); - logger.debug("Batch job ends with status as " + jobExecution.getStatus()); - } - logger.debug("scheduler ends "); - } - - public void stop() { - enabled.set(false); - } - - public void start() { - enabled.set(true); - } - - @Bean - public TaskScheduler poolScheduler() { - return new CustomTaskScheduler(); - } - - private class CustomTaskScheduler extends ThreadPoolTaskScheduler { - - private static final long serialVersionUID = -7142624085505040603L; - - @Override - public ScheduledFuture scheduleAtFixedRate(Runnable task, long period) { - ScheduledFuture future = super.scheduleAtFixedRate(task, period); - - ScheduledMethodRunnable runnable = (ScheduledMethodRunnable) task; - scheduledTasks.put(runnable.getTarget(), future); - - return future; - } - - } - - public void cancelFutureSchedulerTasks() { - scheduledTasks.forEach((k, v) -> { - if (k instanceof SpringBatchScheduler) { - v.cancel(false); - } - }); - } - - @Bean - public Job job() { - return jobBuilderFactory.get("job") - .start(readBooks()) - .build(); - } - - @Bean - public JobLauncher jobLauncher() throws Exception { - SimpleJobLauncher jobLauncher = new SimpleJobLauncher(); - jobLauncher.setJobRepository(jobRepository()); - jobLauncher.afterPropertiesSet(); - return jobLauncher; - } - - @Bean - public JobRepository jobRepository() throws Exception { - MapJobRepositoryFactoryBean factory = new MapJobRepositoryFactoryBean(); - factory.setTransactionManager(new ResourcelessTransactionManager()); - return (JobRepository) factory.getObject(); - } - - @Bean - protected Step readBooks() { - return stepBuilderFactory.get("readBooks") - . chunk(2) - .reader(reader()) - .writer(writer()) - .build(); - } - - @Bean - public FlatFileItemReader reader() { - return new FlatFileItemReaderBuilder().name("bookItemReader") - .resource(new ClassPathResource("books.csv")) - .delimited() - .names(new String[] { "id", "name" }) - .fieldSetMapper(new BeanWrapperFieldSetMapper() { - { - setTargetType(Book.class); - } - }) - .build(); - } - - @Bean - public ItemWriter writer() { - return new ItemWriter() { - - @Override - public void write(List items) throws Exception { - logger.debug("writer..." + items.size()); - for (Book item : items) { - logger.debug(item.toString()); - } - - } - }; - } - - public AtomicInteger getBatchRunCounter() { - return batchRunCounter; - } - -} diff --git a/spring-batch/src/main/java/com/ossez/spring/batchscheduler/model/Book.java b/spring-batch/src/main/java/com/ossez/spring/batchscheduler/model/Book.java deleted file mode 100644 index f992bde20e..0000000000 --- a/spring-batch/src/main/java/com/ossez/spring/batchscheduler/model/Book.java +++ /dev/null @@ -1,35 +0,0 @@ -package org.baeldung.batchscheduler.model; - -public class Book { - private int id; - private String name; - - public Book() {} - - public Book(int id, String name) { - super(); - this.id = id; - this.name = name; - } - - public int getId() { - return id; - } - - public void setId(int id) { - this.id = id; - } - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public String toString() { - return "Book [id=" + id + ", name=" + name + "]"; - } - -} diff --git a/spring-batch/src/main/java/com/ossez/spring/file2db/BatchConfiguration.java b/spring-batch/src/main/java/com/ossez/spring/file2db/BatchConfiguration.java deleted file mode 100644 index 3cad72b8a5..0000000000 --- a/spring-batch/src/main/java/com/ossez/spring/file2db/BatchConfiguration.java +++ /dev/null @@ -1,82 +0,0 @@ -package us.cwiki.spring.batch.processing; - -import javax.sql.DataSource; - -import org.springframework.batch.core.Job; -import org.springframework.batch.core.Step; -import org.springframework.batch.core.configuration.annotation.EnableBatchProcessing; -import org.springframework.batch.core.configuration.annotation.JobBuilderFactory; -import org.springframework.batch.core.configuration.annotation.StepBuilderFactory; -import org.springframework.batch.core.launch.support.RunIdIncrementer; -import org.springframework.batch.item.database.BeanPropertyItemSqlParameterSourceProvider; -import org.springframework.batch.item.database.JdbcBatchItemWriter; -import org.springframework.batch.item.database.builder.JdbcBatchItemWriterBuilder; -import org.springframework.batch.item.file.FlatFileItemReader; -import org.springframework.batch.item.file.builder.FlatFileItemReaderBuilder; -import org.springframework.batch.item.file.mapping.BeanWrapperFieldSetMapper; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.core.io.ClassPathResource; - -@Configuration -@EnableBatchProcessing -public class BatchConfiguration { - - @Autowired - public JobBuilderFactory jobBuilderFactory; - - @Autowired - public StepBuilderFactory stepBuilderFactory; - - // tag::readerwriterprocessor[] - @Bean - public FlatFileItemReader reader() { - return new FlatFileItemReaderBuilder() - .name("personItemReader") - .resource(new ClassPathResource("sample-data.csv")) - .delimited() - .names(new String[]{"firstName", "lastName"}) - .fieldSetMapper(new BeanWrapperFieldSetMapper() {{ - setTargetType(Person.class); - }}) - .build(); - } - - @Bean - public PersonItemProcessor processor() { - return new PersonItemProcessor(); - } - - @Bean - public JdbcBatchItemWriter writer(DataSource dataSource) { - return new JdbcBatchItemWriterBuilder() - .itemSqlParameterSourceProvider(new BeanPropertyItemSqlParameterSourceProvider<>()) - .sql("INSERT INTO people (first_name, last_name) VALUES (:firstName, :lastName)") - .dataSource(dataSource) - .build(); - } - // end::readerwriterprocessor[] - - // tag::jobstep[] - @Bean - public Job importUserJob(JobCompletionNotificationListener listener, Step step1) { - return jobBuilderFactory.get("importUserJob") - .incrementer(new RunIdIncrementer()) - .listener(listener) - .flow(step1) - .end() - .build(); - } - - @Bean - public Step step1(JdbcBatchItemWriter writer) { - return stepBuilderFactory.get("step1") - . chunk(10) - .reader(reader()) - .processor(processor()) - .writer(writer) - .build(); - } - // end::jobstep[] -} diff --git a/spring-batch/src/main/java/com/ossez/spring/file2db/JobCompletionNotificationListener.java b/spring-batch/src/main/java/com/ossez/spring/file2db/JobCompletionNotificationListener.java deleted file mode 100644 index faf14d5188..0000000000 --- a/spring-batch/src/main/java/com/ossez/spring/file2db/JobCompletionNotificationListener.java +++ /dev/null @@ -1,36 +0,0 @@ -package us.cwiki.spring.batch.processing; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.batch.core.BatchStatus; -import org.springframework.batch.core.JobExecution; -import org.springframework.batch.core.listener.JobExecutionListenerSupport; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.jdbc.core.JdbcTemplate; -import org.springframework.stereotype.Component; - -@Component -public class JobCompletionNotificationListener extends JobExecutionListenerSupport { - - private static final Logger log = LoggerFactory.getLogger(JobCompletionNotificationListener.class); - - private final JdbcTemplate jdbcTemplate; - - @Autowired - public JobCompletionNotificationListener(JdbcTemplate jdbcTemplate) { - this.jdbcTemplate = jdbcTemplate; - } - - @Override - public void afterJob(JobExecution jobExecution) { - if(jobExecution.getStatus() == BatchStatus.COMPLETED) { - log.info("!!! JOB FINISHED! Time to verify the results"); - - jdbcTemplate.query("SELECT first_name, last_name FROM people", - (rs, row) -> new Person( - rs.getString(1), - rs.getString(2)) - ).forEach(person -> log.info("Found <" + person + "> in the database.")); - } - } -} diff --git a/spring-batch/src/main/java/com/ossez/spring/file2db/Person.java b/spring-batch/src/main/java/com/ossez/spring/file2db/Person.java deleted file mode 100644 index 8b29f1d6e8..0000000000 --- a/spring-batch/src/main/java/com/ossez/spring/file2db/Person.java +++ /dev/null @@ -1,37 +0,0 @@ -package us.cwiki.spring.batch.processing; - -public class Person { - - private String lastName; - private String firstName; - - public Person() { - } - - public Person(String firstName, String lastName) { - this.firstName = firstName; - this.lastName = lastName; - } - - public void setFirstName(String firstName) { - this.firstName = firstName; - } - - public String getFirstName() { - return firstName; - } - - public String getLastName() { - return lastName; - } - - public void setLastName(String lastName) { - this.lastName = lastName; - } - - @Override - public String toString() { - return "firstName: " + firstName + ", lastName: " + lastName; - } - -} diff --git a/spring-batch/src/main/java/com/ossez/spring/file2db/PersonItemProcessor.java b/spring-batch/src/main/java/com/ossez/spring/file2db/PersonItemProcessor.java deleted file mode 100644 index 7de259e7f6..0000000000 --- a/spring-batch/src/main/java/com/ossez/spring/file2db/PersonItemProcessor.java +++ /dev/null @@ -1,24 +0,0 @@ -package us.cwiki.spring.batch.processing; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import org.springframework.batch.item.ItemProcessor; - -public class PersonItemProcessor implements ItemProcessor { - - private static final Logger log = LoggerFactory.getLogger(PersonItemProcessor.class); - - @Override - public Person process(final Person person) throws Exception { - final String firstName = person.getFirstName().toUpperCase(); - final String lastName = person.getLastName().toUpperCase(); - - final Person transformedPerson = new Person(firstName, lastName); - - log.info("Converting (" + person + ") into (" + transformedPerson + ")"); - - return transformedPerson; - } - -} diff --git a/spring-batch/src/main/java/com/ossez/spring/taskletsvschunks/chunks/LineProcessor.java b/spring-batch/src/main/java/com/ossez/spring/taskletsvschunks/chunks/LineProcessor.java deleted file mode 100644 index 69a0025236..0000000000 --- a/spring-batch/src/main/java/com/ossez/spring/taskletsvschunks/chunks/LineProcessor.java +++ /dev/null @@ -1,36 +0,0 @@ -package com.ossez.spring.taskletsvschunks.chunks; - -import com.ossez.spring.taskletsvschunks.model.Line; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.batch.core.ExitStatus; -import org.springframework.batch.core.StepExecution; -import org.springframework.batch.core.StepExecutionListener; -import org.springframework.batch.item.ItemProcessor; - -import java.time.LocalDate; -import java.time.temporal.ChronoUnit; - -public class LineProcessor implements ItemProcessor, StepExecutionListener { - - private final Logger logger = LoggerFactory.getLogger(LineProcessor.class); - - @Override - public void beforeStep(StepExecution stepExecution) { - logger.debug("Line Processor initialized."); - } - - @Override - public Line process(Line line) throws Exception { - long age = ChronoUnit.YEARS.between(line.getDob(), LocalDate.now()); - logger.debug("Calculated age " + age + " for line " + line.toString()); - line.setAge(age); - return line; - } - - @Override - public ExitStatus afterStep(StepExecution stepExecution) { - logger.debug("Line Processor ended."); - return ExitStatus.COMPLETED; - } -} diff --git a/spring-batch/src/main/java/com/ossez/spring/taskletsvschunks/chunks/LineReader.java b/spring-batch/src/main/java/com/ossez/spring/taskletsvschunks/chunks/LineReader.java deleted file mode 100644 index dc5ff282d8..0000000000 --- a/spring-batch/src/main/java/com/ossez/spring/taskletsvschunks/chunks/LineReader.java +++ /dev/null @@ -1,36 +0,0 @@ -package com.ossez.spring.taskletsvschunks.chunks; - -import com.ossez.spring.taskletsvschunks.model.Line; -import com.ossez.spring.taskletsvschunks.utils.FileUtils; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.batch.core.ExitStatus; -import org.springframework.batch.core.StepExecution; -import org.springframework.batch.core.StepExecutionListener; -import org.springframework.batch.item.ItemReader; - -public class LineReader implements ItemReader, StepExecutionListener { - - private final Logger logger = LoggerFactory.getLogger(LineReader.class); - private FileUtils fu; - - @Override - public void beforeStep(StepExecution stepExecution) { - fu = new FileUtils("taskletsvschunks/input/tasklets-vs-chunks.csv"); - logger.debug("Line Reader initialized."); - } - - @Override - public Line read() throws Exception { - Line line = fu.readLine(); - if (line != null) logger.debug("Read line: " + line.toString()); - return line; - } - - @Override - public ExitStatus afterStep(StepExecution stepExecution) { - fu.closeReader(); - logger.debug("Line Reader ended."); - return ExitStatus.COMPLETED; - } -} diff --git a/spring-batch/src/main/java/com/ossez/spring/taskletsvschunks/chunks/LinesWriter.java b/spring-batch/src/main/java/com/ossez/spring/taskletsvschunks/chunks/LinesWriter.java deleted file mode 100644 index 88ec896fa3..0000000000 --- a/spring-batch/src/main/java/com/ossez/spring/taskletsvschunks/chunks/LinesWriter.java +++ /dev/null @@ -1,40 +0,0 @@ -package com.ossez.spring.taskletsvschunks.chunks; - - -import com.ossez.spring.taskletsvschunks.model.Line; -import com.ossez.spring.taskletsvschunks.utils.FileUtils; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.batch.core.ExitStatus; -import org.springframework.batch.core.StepExecution; -import org.springframework.batch.core.StepExecutionListener; -import org.springframework.batch.item.ItemWriter; - -import java.util.List; - -public class LinesWriter implements ItemWriter, StepExecutionListener { - - private final Logger logger = LoggerFactory.getLogger(LinesWriter.class); - private FileUtils fu; - - @Override - public void beforeStep(StepExecution stepExecution) { - fu = new FileUtils("output.csv"); - logger.debug("Line Writer initialized."); - } - - @Override - public ExitStatus afterStep(StepExecution stepExecution) { - fu.closeWriter(); - logger.debug("Line Writer ended."); - return ExitStatus.COMPLETED; - } - - @Override - public void write(List lines) throws Exception { - for (Line line : lines) { - fu.writeLine(line); - logger.debug("Wrote line " + line.toString()); - } - } -} diff --git a/spring-batch/src/main/java/com/ossez/spring/taskletsvschunks/config/ChunksConfig.java b/spring-batch/src/main/java/com/ossez/spring/taskletsvschunks/config/ChunksConfig.java deleted file mode 100644 index 40e0bbad5b..0000000000 --- a/spring-batch/src/main/java/com/ossez/spring/taskletsvschunks/config/ChunksConfig.java +++ /dev/null @@ -1,91 +0,0 @@ -package com.ossez.spring.taskletsvschunks.config; - -import com.ossez.spring.taskletsvschunks.chunks.LineProcessor; -import com.ossez.spring.taskletsvschunks.chunks.LineReader; -import com.ossez.spring.taskletsvschunks.chunks.LinesWriter; -import com.ossez.spring.taskletsvschunks.model.Line; - -import org.springframework.batch.core.Job; -import org.springframework.batch.core.Step; -import org.springframework.batch.core.configuration.annotation.EnableBatchProcessing; -import org.springframework.batch.core.configuration.annotation.JobBuilderFactory; -import org.springframework.batch.core.configuration.annotation.StepBuilderFactory; -import org.springframework.batch.core.launch.JobLauncher; -import org.springframework.batch.core.launch.support.SimpleJobLauncher; -import org.springframework.batch.core.repository.JobRepository; -import org.springframework.batch.core.repository.support.MapJobRepositoryFactoryBean; -import org.springframework.batch.item.ItemProcessor; -import org.springframework.batch.item.ItemReader; -import org.springframework.batch.item.ItemWriter; -import org.springframework.batch.support.transaction.ResourcelessTransactionManager; -import org.springframework.batch.test.JobLauncherTestUtils; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.transaction.PlatformTransactionManager; - -@Configuration -@EnableBatchProcessing -public class ChunksConfig { - - @Autowired private JobBuilderFactory jobs; - - @Autowired private StepBuilderFactory steps; - - @Bean - public JobLauncherTestUtils jobLauncherTestUtils() { - return new JobLauncherTestUtils(); - } - - @Bean - public JobRepository jobRepository() throws Exception { - MapJobRepositoryFactoryBean factory = new MapJobRepositoryFactoryBean(); - factory.setTransactionManager(transactionManager()); - return (JobRepository) factory.getObject(); - } - - @Bean - public PlatformTransactionManager transactionManager() { - return new ResourcelessTransactionManager(); - } - - @Bean - public JobLauncher jobLauncher() throws Exception { - SimpleJobLauncher jobLauncher = new SimpleJobLauncher(); - jobLauncher.setJobRepository(jobRepository()); - return jobLauncher; - } - - @Bean - public ItemReader itemReader() { - return new LineReader(); - } - - @Bean - public ItemProcessor itemProcessor() { - return new LineProcessor(); - } - - @Bean - public ItemWriter itemWriter() { - return new LinesWriter(); - } - - @Bean - protected Step processLines(ItemReader reader, ItemProcessor processor, ItemWriter writer) { - return steps.get("processLines"). chunk(2) - .reader(reader) - .processor(processor) - .writer(writer) - .build(); - } - - @Bean - public Job job() { - return jobs - .get("chunksJob") - .start(processLines(itemReader(), itemProcessor(), itemWriter())) - .build(); - } - -} diff --git a/spring-batch/src/main/java/com/ossez/spring/taskletsvschunks/config/TaskletsConfig.java b/spring-batch/src/main/java/com/ossez/spring/taskletsvschunks/config/TaskletsConfig.java deleted file mode 100644 index 9988c62990..0000000000 --- a/spring-batch/src/main/java/com/ossez/spring/taskletsvschunks/config/TaskletsConfig.java +++ /dev/null @@ -1,104 +0,0 @@ -package com.ossez.spring.taskletsvschunks.config; - - -import com.ossez.spring.taskletsvschunks.tasklets.LinesWriter; -import com.ossez.spring.taskletsvschunks.tasklets.LinesProcessor; -import com.ossez.spring.taskletsvschunks.tasklets.LinesReader; -import org.springframework.batch.core.Job; -import org.springframework.batch.core.Step; -import org.springframework.batch.core.configuration.annotation.EnableBatchProcessing; -import org.springframework.batch.core.configuration.annotation.JobBuilderFactory; -import org.springframework.batch.core.configuration.annotation.StepBuilderFactory; -import org.springframework.batch.core.launch.JobLauncher; -import org.springframework.batch.core.launch.support.SimpleJobLauncher; -import org.springframework.batch.core.repository.JobRepository; -import org.springframework.batch.core.repository.support.MapJobRepositoryFactoryBean; -import org.springframework.batch.support.transaction.ResourcelessTransactionManager; -import org.springframework.batch.test.JobLauncherTestUtils; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.transaction.PlatformTransactionManager; - -@Configuration -@EnableBatchProcessing -public class TaskletsConfig { - - @Autowired private JobBuilderFactory jobs; - - @Autowired private StepBuilderFactory steps; - - @Bean - public JobLauncherTestUtils jobLauncherTestUtils() { - return new JobLauncherTestUtils(); - } - - @Bean - public JobRepository jobRepository() throws Exception { - MapJobRepositoryFactoryBean factory = new MapJobRepositoryFactoryBean(); - factory.setTransactionManager(transactionManager()); - return (JobRepository) factory.getObject(); - } - - @Bean - public PlatformTransactionManager transactionManager() { - return new ResourcelessTransactionManager(); - } - - @Bean - public JobLauncher jobLauncher() throws Exception { - SimpleJobLauncher jobLauncher = new SimpleJobLauncher(); - jobLauncher.setJobRepository(jobRepository()); - return jobLauncher; - } - - @Bean - public LinesReader linesReader() { - return new LinesReader(); - } - - @Bean - public LinesProcessor linesProcessor() { - return new LinesProcessor(); - } - - @Bean - public LinesWriter linesWriter() { - return new LinesWriter(); - } - - @Bean - protected Step readLines() { - return steps - .get("readLines") - .tasklet(linesReader()) - .build(); - } - - @Bean - protected Step processLines() { - return steps - .get("processLines") - .tasklet(linesProcessor()) - .build(); - } - - @Bean - protected Step writeLines() { - return steps - .get("writeLines") - .tasklet(linesWriter()) - .build(); - } - - @Bean - public Job job() { - return jobs - .get("taskletsJob") - .start(readLines()) - .next(processLines()) - .next(writeLines()) - .build(); - } - -} diff --git a/spring-batch/src/main/java/com/ossez/spring/taskletsvschunks/model/Line.java b/spring-batch/src/main/java/com/ossez/spring/taskletsvschunks/model/Line.java deleted file mode 100644 index 6f34fa7894..0000000000 --- a/spring-batch/src/main/java/com/ossez/spring/taskletsvschunks/model/Line.java +++ /dev/null @@ -1,55 +0,0 @@ -package com.ossez.spring.taskletsvschunks.model; - -import java.io.Serializable; -import java.time.LocalDate; -import java.time.format.DateTimeFormatter; - -public class Line implements Serializable { - - private String name; - private LocalDate dob; - private Long age; - - public Line(String name, LocalDate dob) { - this.name = name; - this.dob = dob; - } - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public LocalDate getDob() { - return dob; - } - - public void setDob(LocalDate dob) { - this.dob = dob; - } - - public Long getAge() { - return age; - } - - public void setAge(Long age) { - this.age = age; - } - - public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append("["); - sb.append(this.name); - sb.append(","); - sb.append(this.dob.format(DateTimeFormatter.ofPattern("MM/dd/yyyy"))); - if (this.age != null) { - sb.append(","); - sb.append(this.age); - } - sb.append("]"); - return sb.toString(); - } -} diff --git a/spring-batch/src/main/java/com/ossez/spring/taskletsvschunks/tasklets/LinesProcessor.java b/spring-batch/src/main/java/com/ossez/spring/taskletsvschunks/tasklets/LinesProcessor.java deleted file mode 100644 index 5a9c1fdd68..0000000000 --- a/spring-batch/src/main/java/com/ossez/spring/taskletsvschunks/tasklets/LinesProcessor.java +++ /dev/null @@ -1,49 +0,0 @@ -package com.ossez.spring.taskletsvschunks.tasklets; - -import com.ossez.spring.taskletsvschunks.model.Line; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.batch.core.ExitStatus; -import org.springframework.batch.core.StepContribution; -import org.springframework.batch.core.StepExecution; -import org.springframework.batch.core.StepExecutionListener; -import org.springframework.batch.core.scope.context.ChunkContext; -import org.springframework.batch.core.step.tasklet.Tasklet; -import org.springframework.batch.item.ExecutionContext; -import org.springframework.batch.repeat.RepeatStatus; - -import java.time.LocalDate; -import java.time.temporal.ChronoUnit; -import java.util.List; - -public class LinesProcessor implements Tasklet, StepExecutionListener { - - private final Logger logger = LoggerFactory.getLogger(LinesProcessor.class); - - private List lines; - - @Override - public RepeatStatus execute(StepContribution stepContribution, ChunkContext chunkContext) throws Exception { - for (Line line : lines) { - long age = ChronoUnit.YEARS.between(line.getDob(), LocalDate.now()); - logger.debug("Calculated age " + age + " for line " + line.toString()); - line.setAge(age); - } - return RepeatStatus.FINISHED; - } - - @Override - public void beforeStep(StepExecution stepExecution) { - ExecutionContext executionContext = stepExecution - .getJobExecution() - .getExecutionContext(); - this.lines = (List) executionContext.get("lines"); - logger.debug("Lines Processor initialized."); - } - - @Override - public ExitStatus afterStep(StepExecution stepExecution) { - logger.debug("Lines Processor ended."); - return ExitStatus.COMPLETED; - } -} diff --git a/spring-batch/src/main/java/com/ossez/spring/taskletsvschunks/tasklets/LinesReader.java b/spring-batch/src/main/java/com/ossez/spring/taskletsvschunks/tasklets/LinesReader.java deleted file mode 100644 index 6ee0a88ce1..0000000000 --- a/spring-batch/src/main/java/com/ossez/spring/taskletsvschunks/tasklets/LinesReader.java +++ /dev/null @@ -1,53 +0,0 @@ -package com.ossez.spring.taskletsvschunks.tasklets; - -import com.ossez.spring.taskletsvschunks.model.Line; -import com.ossez.spring.taskletsvschunks.utils.FileUtils; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.batch.core.ExitStatus; -import org.springframework.batch.core.StepContribution; -import org.springframework.batch.core.StepExecution; -import org.springframework.batch.core.StepExecutionListener; -import org.springframework.batch.core.scope.context.ChunkContext; -import org.springframework.batch.core.step.tasklet.Tasklet; -import org.springframework.batch.repeat.RepeatStatus; - -import java.util.ArrayList; -import java.util.List; - -public class LinesReader implements Tasklet, StepExecutionListener { - - private final Logger logger = LoggerFactory.getLogger(LinesReader.class); - - private List lines; - private FileUtils fu; - - @Override - public void beforeStep(StepExecution stepExecution) { - lines = new ArrayList(); - fu = new FileUtils("taskletsvschunks/input/tasklets-vs-chunks.csv"); - logger.debug("Lines Reader initialized."); - } - - @Override - public RepeatStatus execute(StepContribution stepContribution, ChunkContext chunkContext) throws Exception { - Line line = fu.readLine(); - while (line != null) { - lines.add(line); - logger.debug("Read line: " + line.toString()); - line = fu.readLine(); - } - return RepeatStatus.FINISHED; - } - - @Override - public ExitStatus afterStep(StepExecution stepExecution) { - fu.closeReader(); - stepExecution - .getJobExecution() - .getExecutionContext() - .put("lines", this.lines); - logger.debug("Lines Reader ended."); - return ExitStatus.COMPLETED; - } -} diff --git a/spring-batch/src/main/java/com/ossez/spring/taskletsvschunks/tasklets/LinesWriter.java b/spring-batch/src/main/java/com/ossez/spring/taskletsvschunks/tasklets/LinesWriter.java deleted file mode 100644 index 4a969dbd25..0000000000 --- a/spring-batch/src/main/java/com/ossez/spring/taskletsvschunks/tasklets/LinesWriter.java +++ /dev/null @@ -1,51 +0,0 @@ -package com.ossez.spring.taskletsvschunks.tasklets; - - -import com.ossez.spring.taskletsvschunks.model.Line; -import com.ossez.spring.taskletsvschunks.utils.FileUtils; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.batch.core.ExitStatus; -import org.springframework.batch.core.StepContribution; -import org.springframework.batch.core.StepExecution; -import org.springframework.batch.core.StepExecutionListener; -import org.springframework.batch.core.scope.context.ChunkContext; -import org.springframework.batch.core.step.tasklet.Tasklet; -import org.springframework.batch.item.ExecutionContext; -import org.springframework.batch.repeat.RepeatStatus; - -import java.util.List; - -public class LinesWriter implements Tasklet, StepExecutionListener { - - private final Logger logger = LoggerFactory.getLogger(LinesWriter.class); - - private List lines; - private FileUtils fu; - - @Override - public void beforeStep(StepExecution stepExecution) { - ExecutionContext executionContext = stepExecution - .getJobExecution() - .getExecutionContext(); - this.lines = (List) executionContext.get("lines"); - fu = new FileUtils("output.csv"); - logger.debug("Lines Writer initialized."); - } - - @Override - public RepeatStatus execute(StepContribution stepContribution, ChunkContext chunkContext) throws Exception { - for (Line line : lines) { - fu.writeLine(line); - logger.debug("Wrote line " + line.toString()); - } - return RepeatStatus.FINISHED; - } - - @Override - public ExitStatus afterStep(StepExecution stepExecution) { - fu.closeWriter(); - logger.debug("Lines Writer ended."); - return ExitStatus.COMPLETED; - } -} diff --git a/spring-batch/src/main/java/com/ossez/spring/taskletsvschunks/utils/FileUtils.java b/spring-batch/src/main/java/com/ossez/spring/taskletsvschunks/utils/FileUtils.java deleted file mode 100644 index 46ab5d9304..0000000000 --- a/spring-batch/src/main/java/com/ossez/spring/taskletsvschunks/utils/FileUtils.java +++ /dev/null @@ -1,95 +0,0 @@ -package com.ossez.spring.taskletsvschunks.utils; - -import com.opencsv.CSVReader; -import com.opencsv.CSVWriter; -import com.ossez.spring.taskletsvschunks.model.Line; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import java.io.File; -import java.io.FileReader; -import java.io.FileWriter; -import java.io.IOException; -import java.time.LocalDate; -import java.time.format.DateTimeFormatter; - -public class FileUtils { - - private final Logger logger = LoggerFactory.getLogger(FileUtils.class); - - private String fileName; - private CSVReader CSVReader; - private CSVWriter CSVWriter; - private FileReader fileReader; - private FileWriter fileWriter; - private File file; - - public FileUtils(String fileName) { - this.fileName = fileName; - } - - public Line readLine() { - try { - if (CSVReader == null) initReader(); - String[] line = CSVReader.readNext(); - if (line == null) return null; - return new Line(line[0], LocalDate.parse(line[1], DateTimeFormatter.ofPattern("MM/dd/yyyy"))); - } catch (Exception e) { - logger.error("Error while reading line in file: " + this.fileName); - return null; - } - } - - public void writeLine(Line line) { - try { - if (CSVWriter == null) initWriter(); - String[] lineStr = new String[2]; - lineStr[0] = line.getName(); - lineStr[1] = line - .getAge() - .toString(); - CSVWriter.writeNext(lineStr); - } catch (Exception e) { - logger.error("Error while writing line in file: " + this.fileName); - } - } - - private void initReader() throws Exception { - ClassLoader classLoader = this - .getClass() - .getClassLoader(); - if (file == null) file = new File(classLoader - .getResource(fileName) - .getFile()); - if (fileReader == null) fileReader = new FileReader(file); - if (CSVReader == null) CSVReader = new CSVReader(fileReader); - } - - private void initWriter() throws Exception { - if (file == null) { - file = new File(fileName); - file.createNewFile(); - } - if (fileWriter == null) fileWriter = new FileWriter(file, true); - if (CSVWriter == null) CSVWriter = new CSVWriter(fileWriter); - } - - public void closeWriter() { - try { - CSVWriter.close(); - fileWriter.close(); - } catch (IOException e) { - logger.error("Error while closing writer."); - } - } - - public void closeReader() { - try { - CSVReader.close(); - fileReader.close(); - } catch (IOException e) { - logger.error("Error while closing reader."); - } - } - -} diff --git a/spring-batch/src/main/resources/books.csv b/spring-batch/src/main/resources/books.csv deleted file mode 100644 index af68e986a2..0000000000 --- a/spring-batch/src/main/resources/books.csv +++ /dev/null @@ -1,4 +0,0 @@ -1,SHARP OBJECTS (MOVIE TIE-IN): A NOVEL -2,ARTEMIS: A NOVEL -3,HER PRETTY FACE -4,ALL WE EVER WANTED \ No newline at end of file diff --git a/spring-batch/src/main/resources/input/partitioner/record1.csv b/spring-batch/src/main/resources/input/partitioner/record1.csv deleted file mode 100644 index e554becb2a..0000000000 --- a/spring-batch/src/main/resources/input/partitioner/record1.csv +++ /dev/null @@ -1,4 +0,0 @@ -username, user_id, transaction_date, transaction_amount -devendra, 1234, 31/10/2015, 10000 -john, 2134, 3/12/2015, 12321 -robin, 2134, 2/02/2015, 23411 \ No newline at end of file diff --git a/spring-batch/src/main/resources/input/partitioner/record2.csv b/spring-batch/src/main/resources/input/partitioner/record2.csv deleted file mode 100644 index e554becb2a..0000000000 --- a/spring-batch/src/main/resources/input/partitioner/record2.csv +++ /dev/null @@ -1,4 +0,0 @@ -username, user_id, transaction_date, transaction_amount -devendra, 1234, 31/10/2015, 10000 -john, 2134, 3/12/2015, 12321 -robin, 2134, 2/02/2015, 23411 \ No newline at end of file diff --git a/spring-batch/src/main/resources/input/partitioner/record3.csv b/spring-batch/src/main/resources/input/partitioner/record3.csv deleted file mode 100644 index e554becb2a..0000000000 --- a/spring-batch/src/main/resources/input/partitioner/record3.csv +++ /dev/null @@ -1,4 +0,0 @@ -username, user_id, transaction_date, transaction_amount -devendra, 1234, 31/10/2015, 10000 -john, 2134, 3/12/2015, 12321 -robin, 2134, 2/02/2015, 23411 \ No newline at end of file diff --git a/spring-batch/src/main/resources/input/partitioner/record4.csv b/spring-batch/src/main/resources/input/partitioner/record4.csv deleted file mode 100644 index e554becb2a..0000000000 --- a/spring-batch/src/main/resources/input/partitioner/record4.csv +++ /dev/null @@ -1,4 +0,0 @@ -username, user_id, transaction_date, transaction_amount -devendra, 1234, 31/10/2015, 10000 -john, 2134, 3/12/2015, 12321 -robin, 2134, 2/02/2015, 23411 \ No newline at end of file diff --git a/spring-batch/src/main/resources/input/partitioner/record5.csv b/spring-batch/src/main/resources/input/partitioner/record5.csv deleted file mode 100644 index e554becb2a..0000000000 --- a/spring-batch/src/main/resources/input/partitioner/record5.csv +++ /dev/null @@ -1,4 +0,0 @@ -username, user_id, transaction_date, transaction_amount -devendra, 1234, 31/10/2015, 10000 -john, 2134, 3/12/2015, 12321 -robin, 2134, 2/02/2015, 23411 \ No newline at end of file diff --git a/spring-batch/src/main/resources/input/record.csv b/spring-batch/src/main/resources/input/record.csv deleted file mode 100644 index e554becb2a..0000000000 --- a/spring-batch/src/main/resources/input/record.csv +++ /dev/null @@ -1,4 +0,0 @@ -username, user_id, transaction_date, transaction_amount -devendra, 1234, 31/10/2015, 10000 -john, 2134, 3/12/2015, 12321 -robin, 2134, 2/02/2015, 23411 \ No newline at end of file diff --git a/spring-batch/src/main/resources/input/recordWithInvalidData.csv b/spring-batch/src/main/resources/input/recordWithInvalidData.csv deleted file mode 100644 index 020edb9826..0000000000 --- a/spring-batch/src/main/resources/input/recordWithInvalidData.csv +++ /dev/null @@ -1,7 +0,0 @@ -username, user_id, transaction_date, transaction_amount -devendra, 1234, 31/10/2015, 10000 -john, 2134, 3/12/2015, 12321 -robin, 2134, 2/02/2015, 23411 -, 2536, 3/10/2019, 100 -mike, 9876, 5/11/2018, -500 -, 3425, 10/10/2017, 100 \ No newline at end of file diff --git a/spring-batch/src/main/resources/logback.xml b/spring-batch/src/main/resources/logback.xml deleted file mode 100644 index 91d4292b8e..0000000000 --- a/spring-batch/src/main/resources/logback.xml +++ /dev/null @@ -1,24 +0,0 @@ - - - - - - %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/spring-batch/src/main/resources/output/output1.xml b/spring-batch/src/main/resources/output/output1.xml deleted file mode 100644 index 194b860813..0000000000 --- a/spring-batch/src/main/resources/output/output1.xml +++ /dev/null @@ -1,21 +0,0 @@ - - - - 10000.0 - 2015-10-31T00:00:00+05:30 - 1234 - devendra - - - 12321.0 - 2015-12-03T00:00:00+05:30 - 2134 - john - - - 23411.0 - 2015-02-02T00:00:00+05:30 - 2134 - robin - - \ No newline at end of file diff --git a/spring-batch/src/main/resources/output/output2.xml b/spring-batch/src/main/resources/output/output2.xml deleted file mode 100644 index 194b860813..0000000000 --- a/spring-batch/src/main/resources/output/output2.xml +++ /dev/null @@ -1,21 +0,0 @@ - - - - 10000.0 - 2015-10-31T00:00:00+05:30 - 1234 - devendra - - - 12321.0 - 2015-12-03T00:00:00+05:30 - 2134 - john - - - 23411.0 - 2015-02-02T00:00:00+05:30 - 2134 - robin - - \ No newline at end of file diff --git a/spring-batch/src/main/resources/output/output3.xml b/spring-batch/src/main/resources/output/output3.xml deleted file mode 100644 index 194b860813..0000000000 --- a/spring-batch/src/main/resources/output/output3.xml +++ /dev/null @@ -1,21 +0,0 @@ - - - - 10000.0 - 2015-10-31T00:00:00+05:30 - 1234 - devendra - - - 12321.0 - 2015-12-03T00:00:00+05:30 - 2134 - john - - - 23411.0 - 2015-02-02T00:00:00+05:30 - 2134 - robin - - \ No newline at end of file diff --git a/spring-batch/src/main/resources/output/output4.xml b/spring-batch/src/main/resources/output/output4.xml deleted file mode 100644 index 194b860813..0000000000 --- a/spring-batch/src/main/resources/output/output4.xml +++ /dev/null @@ -1,21 +0,0 @@ - - - - 10000.0 - 2015-10-31T00:00:00+05:30 - 1234 - devendra - - - 12321.0 - 2015-12-03T00:00:00+05:30 - 2134 - john - - - 23411.0 - 2015-02-02T00:00:00+05:30 - 2134 - robin - - \ No newline at end of file diff --git a/spring-batch/src/main/resources/output/output5.xml b/spring-batch/src/main/resources/output/output5.xml deleted file mode 100644 index 194b860813..0000000000 --- a/spring-batch/src/main/resources/output/output5.xml +++ /dev/null @@ -1,21 +0,0 @@ - - - - 10000.0 - 2015-10-31T00:00:00+05:30 - 1234 - devendra - - - 12321.0 - 2015-12-03T00:00:00+05:30 - 2134 - john - - - 23411.0 - 2015-02-02T00:00:00+05:30 - 2134 - robin - - \ No newline at end of file diff --git a/spring-batch/src/main/resources/spring-batch-intro.xml b/spring-batch/src/main/resources/spring-batch-intro.xml deleted file mode 100644 index 0f76dd50ff..0000000000 --- a/spring-batch/src/main/resources/spring-batch-intro.xml +++ /dev/null @@ -1,57 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - org.baeldung.batch.model.Transaction - - - - - - - - - - - - - diff --git a/spring-batch/src/main/resources/spring.xml b/spring-batch/src/main/resources/spring.xml deleted file mode 100644 index dea261c5e6..0000000000 --- a/spring-batch/src/main/resources/spring.xml +++ /dev/null @@ -1,45 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/spring-batch/src/main/resources/taskletsvschunks/input/tasklets-vs-chunks.csv b/spring-batch/src/main/resources/taskletsvschunks/input/tasklets-vs-chunks.csv deleted file mode 100644 index 214bd3cb70..0000000000 --- a/spring-batch/src/main/resources/taskletsvschunks/input/tasklets-vs-chunks.csv +++ /dev/null @@ -1,6 +0,0 @@ -Mae Hodges,10/22/1972 -Gary Potter,02/22/1953 -Betty Wise,02/17/1968 -Wayne Rose,04/06/1977 -Adam Caldwell,09/27/1995 -Lucille Phillips,05/14/1992 \ No newline at end of file diff --git a/spring-batch/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/spring-batch/src/test/java/org/baeldung/SpringContextIntegrationTest.java deleted file mode 100644 index de9d09d5c5..0000000000 --- a/spring-batch/src/test/java/org/baeldung/SpringContextIntegrationTest.java +++ /dev/null @@ -1,12 +0,0 @@ -package org.baeldung; - -import com.ossez.spring.batch.App; -import org.junit.Test; - -public class SpringContextIntegrationTest { - - @Test - public final void testMain() throws Exception { - App.main(null); - } -} diff --git a/spring-batch/src/test/java/org/baeldung/SpringContextTest.java b/spring-batch/src/test/java/org/baeldung/SpringContextTest.java deleted file mode 100644 index cf706b6072..0000000000 --- a/spring-batch/src/test/java/org/baeldung/SpringContextTest.java +++ /dev/null @@ -1,14 +0,0 @@ -package org.baeldung; - - -import com.ossez.spring.batch.App; - -import org.junit.Test; - -public class SpringContextTest { - - @Test - public final void testMain() throws Exception { - App.main(null); - } -} diff --git a/spring-batch/src/test/java/org/baeldung/batchscheduler/SpringBatchSchedulerIntegrationTest.java b/spring-batch/src/test/java/org/baeldung/batchscheduler/SpringBatchSchedulerIntegrationTest.java deleted file mode 100644 index a3d4e590a8..0000000000 --- a/spring-batch/src/test/java/org/baeldung/batchscheduler/SpringBatchSchedulerIntegrationTest.java +++ /dev/null @@ -1,61 +0,0 @@ -package org.baeldung.batchscheduler; - -import com.ossez.spring.batchscheduler.SpringBatchScheduler; -import org.junit.Assert; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.context.ApplicationContext; -import org.springframework.scheduling.annotation.ScheduledAnnotationBeanPostProcessor; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; - -import static org.awaitility.Awaitility.await; -import static java.util.concurrent.TimeUnit.*; - -@RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration(classes = SpringBatchScheduler.class) -public class SpringBatchSchedulerIntegrationTest { - - @Autowired - private ApplicationContext context; - - @Test - public void stopJobsWhenSchedulerDisabled() throws Exception { - SpringBatchScheduler schedulerBean = context.getBean(SpringBatchScheduler.class); - await().untilAsserted(() -> Assert.assertEquals(2, schedulerBean.getBatchRunCounter() - .get())); - schedulerBean.stop(); - await().atLeast(3, SECONDS); - - Assert.assertEquals(2, schedulerBean.getBatchRunCounter() - .get()); - } - - @Test - public void stopJobSchedulerWhenSchedulerDestroyed() throws Exception { - ScheduledAnnotationBeanPostProcessor bean = context.getBean(ScheduledAnnotationBeanPostProcessor.class); - SpringBatchScheduler schedulerBean = context.getBean(SpringBatchScheduler.class); - await().untilAsserted(() -> Assert.assertEquals(2, schedulerBean.getBatchRunCounter() - .get())); - bean.postProcessBeforeDestruction(schedulerBean, "SpringBatchScheduler"); - await().atLeast(3, SECONDS); - - Assert.assertEquals(2, schedulerBean.getBatchRunCounter() - .get()); - } - - @Test - public void stopJobSchedulerWhenFutureTasksCancelled() throws Exception { - SpringBatchScheduler schedulerBean = context.getBean(SpringBatchScheduler.class); - await().untilAsserted(() -> Assert.assertEquals(2, schedulerBean.getBatchRunCounter() - .get())); - schedulerBean.cancelFutureSchedulerTasks(); - await().atLeast(3, SECONDS); - - Assert.assertEquals(2, schedulerBean.getBatchRunCounter() - .get()); - } - - -} diff --git a/spring-batch/src/test/java/org/baeldung/taskletsvschunks/chunks/ChunksIntegrationTest.java b/spring-batch/src/test/java/org/baeldung/taskletsvschunks/chunks/ChunksIntegrationTest.java deleted file mode 100644 index 6a444cb68a..0000000000 --- a/spring-batch/src/test/java/org/baeldung/taskletsvschunks/chunks/ChunksIntegrationTest.java +++ /dev/null @@ -1,25 +0,0 @@ -package org.baeldung.taskletsvschunks.chunks; - -import com.ossez.spring.taskletsvschunks.config.ChunksConfig; -import org.junit.Assert; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.batch.core.ExitStatus; -import org.springframework.batch.core.JobExecution; -import org.springframework.batch.test.JobLauncherTestUtils; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; - -@RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration(classes = ChunksConfig.class) -public class ChunksIntegrationTest { - - @Autowired private JobLauncherTestUtils jobLauncherTestUtils; - - @Test - public void givenChunksJob_WhenJobEnds_ThenStatusCompleted() throws Exception { - JobExecution jobExecution = jobLauncherTestUtils.launchJob(); - Assert.assertEquals(ExitStatus.COMPLETED, jobExecution.getExitStatus()); - } -} diff --git a/spring-batch/src/test/java/org/baeldung/taskletsvschunks/tasklets/TaskletsIntegrationTest.java b/spring-batch/src/test/java/org/baeldung/taskletsvschunks/tasklets/TaskletsIntegrationTest.java deleted file mode 100644 index 2ae77628e6..0000000000 --- a/spring-batch/src/test/java/org/baeldung/taskletsvschunks/tasklets/TaskletsIntegrationTest.java +++ /dev/null @@ -1,25 +0,0 @@ -package org.baeldung.taskletsvschunks.tasklets; - -import com.ossez.spring.taskletsvschunks.config.TaskletsConfig; -import org.junit.Assert; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.batch.core.ExitStatus; -import org.springframework.batch.core.JobExecution; -import org.springframework.batch.test.JobLauncherTestUtils; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; - -@RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration(classes = TaskletsConfig.class) -public class TaskletsIntegrationTest { - - @Autowired private JobLauncherTestUtils jobLauncherTestUtils; - - @Test - public void givenTaskletsJob_WhenJobEnds_ThenStatusCompleted() throws Exception { - JobExecution jobExecution = jobLauncherTestUtils.launchJob(); - Assert.assertEquals(ExitStatus.COMPLETED, jobExecution.getExitStatus()); - } -} diff --git a/spring-boot-modules/spring-boot-1st/README.md b/spring-boot-modules/spring-boot-1st/README.md deleted file mode 100644 index 06f9ecf87f..0000000000 --- a/spring-boot-modules/spring-boot-1st/README.md +++ /dev/null @@ -1,12 +0,0 @@ -## Spring Boot 文档示例程序 - -这个文档为按照官方的 Spring Boot 文档创建的第一个示例程序 - -### 相关文档: - -- [Spring Boot 第一个示例创建 POM 文件](https://www.ossez.com/t/spring-boot-2-4-pom/1089) -- [Spring Boot 第一个示例程序添加 Classpath 依赖](https://www.ossez.com/t/spring-boot-2-4-classpath/1098) -- [Spring Boot 第一个示例程序书写代码](https://www.ossez.com/t/spring-boot-2-4/1099) -- [Spring Boot 第一个示例的 @RestController 和 @RequestMapping 注解](https://www.ossez.com/t/spring-boot-restcontroller-requestmapping/1100) -- [Spring Boot 第一个示例的 @EnableAutoConfiguration 注解](https://www.ossez.com/t/spring-boot-enableautoconfiguration/1101) -- [Spring Boot 第一个示例创建一个可以执行的 Jar](https://www.ossez.com/t/spring-boot-jar/1111) diff --git a/spring-boot-modules/spring-boot-1st/pom.xml b/spring-boot-modules/spring-boot-1st/pom.xml deleted file mode 100644 index a238b97e5d..0000000000 --- a/spring-boot-modules/spring-boot-1st/pom.xml +++ /dev/null @@ -1,70 +0,0 @@ - - - 4.0.0 - - com.example - myproject - 0.0.1-SNAPSHOT - - - org.springframework.boot - spring-boot-starter-parent - 2.5.0-SNAPSHOT - - - - - org.springframework.boot - spring-boot-starter-web - - - - - - - org.springframework.boot - spring-boot-maven-plugin - - - - - - - - - - - - - - - - - - - - - - spring-snapshots - https://repo.spring.io/snapshot - - true - - - - spring-milestones - https://repo.spring.io/milestone - - - - - spring-snapshots - https://repo.spring.io/snapshot - - - spring-milestones - https://repo.spring.io/milestone - - - \ No newline at end of file diff --git a/spring-boot-modules/spring-boot-1st/src/main/java/Example.java b/spring-boot-modules/spring-boot-1st/src/main/java/Example.java deleted file mode 100644 index 63a4212a19..0000000000 --- a/spring-boot-modules/spring-boot-1st/src/main/java/Example.java +++ /dev/null @@ -1,19 +0,0 @@ -import org.springframework.boot.SpringApplication; -import org.springframework.boot.autoconfigure.EnableAutoConfiguration; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RestController; - -@RestController -@EnableAutoConfiguration -public class Example { - - @RequestMapping("/") - String home() { - return "Hello World!"; - } - - public static void main(String[] args) { - SpringApplication.run(Example.class, args); - } - -} \ No newline at end of file diff --git a/spring-boot-modules/spring-boot-testing/.gitignore b/spring-boot-modules/spring-boot-testing/.gitignore deleted file mode 100644 index da7c2c5c0a..0000000000 --- a/spring-boot-modules/spring-boot-testing/.gitignore +++ /dev/null @@ -1,5 +0,0 @@ -/target/ -.settings/ -.classpath -.project - diff --git a/spring-boot-modules/spring-boot-testing/.mvn/wrapper/maven-wrapper.properties b/spring-boot-modules/spring-boot-testing/.mvn/wrapper/maven-wrapper.properties deleted file mode 100644 index a447c9fa81..0000000000 --- a/spring-boot-modules/spring-boot-testing/.mvn/wrapper/maven-wrapper.properties +++ /dev/null @@ -1 +0,0 @@ -distributionUrl=https://repo1.maven.org/maven2/org/apache/maven/apache-maven/3.5.2/apache-maven-3.5.2-bin.zip \ No newline at end of file diff --git a/spring-boot-modules/spring-boot-testing/README.md b/spring-boot-modules/spring-boot-testing/README.md deleted file mode 100644 index a4b9b383fd..0000000000 --- a/spring-boot-modules/spring-boot-testing/README.md +++ /dev/null @@ -1,12 +0,0 @@ -## Spring Boot 测试 - -本模块中包含了有关如何在 Spring Boot 中进行测试和在测试中遇到的一些问题和解决的文章。 - -- [Testing with Spring and Spock](https://www.baeldung.com/spring-spock-testing) -- [Exclude Auto-Configuration Classes in Spring Boot Tests](https://www.baeldung.com/spring-boot-exclude-auto-configuration-test) -- [Embedded Redis Server with Spring Boot Test](https://www.baeldung.com/spring-embedded-redis) -- [Testing Spring Boot @ConfigurationProperties](https://www.baeldung.com/spring-boot-testing-configurationproperties) -- [Prevent ApplicationRunner or CommandLineRunner Beans From Executing During Junit Testing](https://www.baeldung.com/spring-junit-prevent-runner-beans-testing-execution) -- [Testing in Spring Boot](https://www.baeldung.com/spring-boot-testing) -- [解决在 Spring Boot 中运行 JUnit 测试遇到的 NoSuchMethodError 错误](https://www.ossez.com/t/spring-boot-junit-nosuchmethoderror/14066) -- More articles: [[more -->]](../spring-boot-testing-2) diff --git a/spring-boot-modules/spring-boot-testing/mvnw b/spring-boot-modules/spring-boot-testing/mvnw deleted file mode 100644 index e96ccd5fbb..0000000000 --- a/spring-boot-modules/spring-boot-testing/mvnw +++ /dev/null @@ -1,227 +0,0 @@ -#!/bin/sh -# ---------------------------------------------------------------------------- -# Licensed to the Apache Software Foundation (ASF) under one -# or more contributor license agreements. See the NOTICE file -# distributed with this work for additional information -# regarding copyright ownership. The ASF licenses this file -# to you 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. -# ---------------------------------------------------------------------------- - -# ---------------------------------------------------------------------------- -# Maven2 Start Up Batch script -# -# Required ENV vars: -# ------------------ -# JAVA_HOME - location of a JDK home dir -# -# Optional ENV vars -# ----------------- -# M2_HOME - location of maven2's installed home dir -# MAVEN_OPTS - parameters passed to the Java VM when running Maven -# e.g. to debug Maven itself, use -# set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 -# MAVEN_SKIP_RC - flag to disable loading of mavenrc files -# ---------------------------------------------------------------------------- - -if [ -z "$MAVEN_SKIP_RC" ] ; then - - if [ -f /etc/mavenrc ] ; then - . /etc/mavenrc - fi - - if [ -f "$HOME/.mavenrc" ] ; then - . "$HOME/.mavenrc" - fi - -fi - -# OS specific support. $var _must_ be set to either true or false. -cygwin=false; -darwin=false; -mingw=false -case "`uname`" in - CYGWIN*) cygwin=true ;; - MINGW*) mingw=true;; - Darwin*) darwin=true - # Use /usr/libexec/java_home if available, otherwise fall back to /Library/Java/Home - # See https://developer.apple.com/library/mac/qa/qa1170/_index.html - if [ -z "$JAVA_HOME" ]; then - if [ -x "/usr/libexec/java_home" ]; then - export JAVA_HOME="`/usr/libexec/java_home`" - else - export JAVA_HOME="/Library/Java/Home" - fi - fi - ;; -esac - -if [ -z "$JAVA_HOME" ] ; then - if [ -r /etc/gentoo-release ] ; then - JAVA_HOME=`java-config --jre-home` - fi -fi - -if [ -z "$M2_HOME" ] ; then - ## resolve links - $0 may be a link to maven's home - PRG="$0" - - # need this for relative symlinks - while [ -h "$PRG" ] ; do - ls=`ls -ld "$PRG"` - link=`expr "$ls" : '.*-> \(.*\)$'` - if expr "$link" : '/.*' > /dev/null; then - PRG="$link" - else - PRG="`dirname "$PRG"`/$link" - fi - done - - saveddir=`pwd` - - M2_HOME=`dirname "$PRG"`/.. - - # make it fully qualified - M2_HOME=`cd "$M2_HOME" && pwd` - - cd "$saveddir" - # echo Using m2 at $M2_HOME -fi - -# For Cygwin, ensure paths are in UNIX format before anything is touched -if $cygwin ; then - [ -n "$M2_HOME" ] && - M2_HOME=`cygpath --unix "$M2_HOME"` - [ -n "$JAVA_HOME" ] && - JAVA_HOME=`cygpath --unix "$JAVA_HOME"` - [ -n "$CLASSPATH" ] && - CLASSPATH=`cygpath --path --unix "$CLASSPATH"` -fi - -# For Mingw, ensure paths are in UNIX format before anything is touched -if $mingw ; then - [ -n "$M2_HOME" ] && - M2_HOME="`(cd "$M2_HOME"; pwd)`" - [ -n "$JAVA_HOME" ] && - JAVA_HOME="`(cd "$JAVA_HOME"; pwd)`" - # TODO classpath? -fi - -if [ -z "$JAVA_HOME" ]; then - javaExecutable="`which javac`" - if [ -n "$javaExecutable" ] && ! [ "`expr \"$javaExecutable\" : '\([^ ]*\)'`" = "no" ]; then - # readlink(1) is not available as standard on Solaris 10. - readLink=`which readlink` - if [ ! `expr "$readLink" : '\([^ ]*\)'` = "no" ]; then - if $darwin ; then - javaHome="`dirname \"$javaExecutable\"`" - javaExecutable="`cd \"$javaHome\" && pwd -P`/javac" - else - javaExecutable="`readlink -f \"$javaExecutable\"`" - fi - javaHome="`dirname \"$javaExecutable\"`" - javaHome=`expr "$javaHome" : '\(.*\)/bin'` - JAVA_HOME="$javaHome" - export JAVA_HOME - fi - fi -fi - -if [ -z "$JAVACMD" ] ; then - if [ -n "$JAVA_HOME" ] ; then - if [ -x "$JAVA_HOME/jre/sh/java" ] ; then - # IBM's JDK on AIX uses strange locations for the executables - JAVACMD="$JAVA_HOME/jre/sh/java" - else - JAVACMD="$JAVA_HOME/bin/java" - fi - else - JAVACMD="`which java`" - fi -fi - -if [ ! -x "$JAVACMD" ] ; then - echo "Error: JAVA_HOME is not defined correctly." >&2 - echo " We cannot execute $JAVACMD" >&2 - exit 1 -fi - -if [ -z "$JAVA_HOME" ] ; then - echo "Warning: JAVA_HOME environment variable is not set." -fi - -CLASSWORLDS_LAUNCHER=org.codehaus.plexus.classworlds.launcher.Launcher - -# traverses directory structure from process work directory to filesystem root -# first directory with .mvn subdirectory is considered project base directory -find_maven_basedir() { - - if [ -z "$1" ] - then - echo "Path not specified to find_maven_basedir" - return 1 - fi - - basedir="$1" - wdir="$1" - while [ "$wdir" != '/' ] ; do - if [ -d "$wdir"/.mvn ] ; then - basedir=$wdir - break - fi - # workaround for JBEAP-8937 (on Solaris 10/Sparc) - if [ -d "${wdir}" ]; then - wdir=`cd "$wdir/.."; pwd` - fi - # end of workaround - done - echo "${basedir}" -} - -# concatenates all lines of a file -concat_lines() { - if [ -f "$1" ]; then - echo "$(tr -s '\n' ' ' < "$1")" - fi -} - -BASE_DIR=`find_maven_basedir "$(pwd)"` -if [ -z "$BASE_DIR" ]; then - exit 1; -fi - -export MAVEN_PROJECTBASEDIR=${MAVEN_BASEDIR:-"$BASE_DIR"} -if [ "$MVNW_VERBOSE" = true ]; then - echo $MAVEN_PROJECTBASEDIR -fi -MAVEN_OPTS="$(concat_lines "$MAVEN_PROJECTBASEDIR/.mvn/jvm.config") $MAVEN_OPTS" - -# For Cygwin, switch paths to Windows format before running java -if $cygwin; then - [ -n "$M2_HOME" ] && - M2_HOME=`cygpath --path --windows "$M2_HOME"` - [ -n "$JAVA_HOME" ] && - JAVA_HOME=`cygpath --path --windows "$JAVA_HOME"` - [ -n "$CLASSPATH" ] && - CLASSPATH=`cygpath --path --windows "$CLASSPATH"` - [ -n "$MAVEN_PROJECTBASEDIR" ] && - MAVEN_PROJECTBASEDIR=`cygpath --path --windows "$MAVEN_PROJECTBASEDIR"` -fi - -WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain - -exec "$JAVACMD" \ - $MAVEN_OPTS \ - -classpath "$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.jar" \ - "-Dmaven.home=${M2_HOME}" "-Dmaven.multiModuleProjectDirectory=${MAVEN_PROJECTBASEDIR}" \ - ${WRAPPER_LAUNCHER} $MAVEN_CONFIG "$@" diff --git a/spring-boot-modules/spring-boot-testing/mvnw.cmd b/spring-boot-modules/spring-boot-testing/mvnw.cmd deleted file mode 100644 index 6a6eec39ba..0000000000 --- a/spring-boot-modules/spring-boot-testing/mvnw.cmd +++ /dev/null @@ -1,145 +0,0 @@ -@REM ---------------------------------------------------------------------------- -@REM Licensed to the Apache Software Foundation (ASF) under one -@REM or more contributor license agreements. See the NOTICE file -@REM distributed with this work for additional information -@REM regarding copyright ownership. The ASF licenses this file -@REM to you under the Apache License, Version 2.0 (the -@REM "License"); you may not use this file except in compliance -@REM with the License. You may obtain a copy of the License at -@REM -@REM http://www.apache.org/licenses/LICENSE-2.0 -@REM -@REM Unless required by applicable law or agreed to in writing, -@REM software distributed under the License is distributed on an -@REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -@REM KIND, either express or implied. See the License for the -@REM specific language governing permissions and limitations -@REM under the License. -@REM ---------------------------------------------------------------------------- - -@REM ---------------------------------------------------------------------------- -@REM Maven2 Start Up Batch script -@REM -@REM Required ENV vars: -@REM JAVA_HOME - location of a JDK home dir -@REM -@REM Optional ENV vars -@REM M2_HOME - location of maven2's installed home dir -@REM MAVEN_BATCH_ECHO - set to 'on' to enable the echoing of the batch commands -@REM MAVEN_BATCH_PAUSE - set to 'on' to wait for a key stroke before ending -@REM MAVEN_OPTS - parameters passed to the Java VM when running Maven -@REM e.g. to debug Maven itself, use -@REM set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 -@REM MAVEN_SKIP_RC - flag to disable loading of mavenrc files -@REM ---------------------------------------------------------------------------- - -@REM Begin all REM lines with '@' in case MAVEN_BATCH_ECHO is 'on' -@echo off -@REM set title of command window -title %0 -@REM enable echoing my setting MAVEN_BATCH_ECHO to 'on' -@if "%MAVEN_BATCH_ECHO%" == "on" echo %MAVEN_BATCH_ECHO% - -@REM set %HOME% to equivalent of $HOME -if "%HOME%" == "" (set "HOME=%HOMEDRIVE%%HOMEPATH%") - -@REM Execute a user defined script before this one -if not "%MAVEN_SKIP_RC%" == "" goto skipRcPre -@REM check for pre script, once with legacy .bat ending and once with .cmd ending -if exist "%HOME%\mavenrc_pre.bat" call "%HOME%\mavenrc_pre.bat" -if exist "%HOME%\mavenrc_pre.cmd" call "%HOME%\mavenrc_pre.cmd" -:skipRcPre - -@setlocal - -set ERROR_CODE=0 - -@REM To isolate internal variables from possible post scripts, we use another setlocal -@setlocal - -@REM ==== START VALIDATION ==== -if not "%JAVA_HOME%" == "" goto OkJHome - -echo. -echo Error: JAVA_HOME not found in your environment. >&2 -echo Please set the JAVA_HOME variable in your environment to match the >&2 -echo location of your Java installation. >&2 -echo. -goto error - -:OkJHome -if exist "%JAVA_HOME%\bin\java.exe" goto init - -echo. -echo Error: JAVA_HOME is set to an invalid directory. >&2 -echo JAVA_HOME = "%JAVA_HOME%" >&2 -echo Please set the JAVA_HOME variable in your environment to match the >&2 -echo location of your Java installation. >&2 -echo. -goto error - -@REM ==== END VALIDATION ==== - -:init - -@REM Find the project base dir, i.e. the directory that contains the folder ".mvn". -@REM Fallback to current working directory if not found. - -set MAVEN_PROJECTBASEDIR=%MAVEN_BASEDIR% -IF NOT "%MAVEN_PROJECTBASEDIR%"=="" goto endDetectBaseDir - -set EXEC_DIR=%CD% -set WDIR=%EXEC_DIR% -:findBaseDir -IF EXIST "%WDIR%"\.mvn goto baseDirFound -cd .. -IF "%WDIR%"=="%CD%" goto baseDirNotFound -set WDIR=%CD% -goto findBaseDir - -:baseDirFound -set MAVEN_PROJECTBASEDIR=%WDIR% -cd "%EXEC_DIR%" -goto endDetectBaseDir - -:baseDirNotFound -set MAVEN_PROJECTBASEDIR=%EXEC_DIR% -cd "%EXEC_DIR%" - -:endDetectBaseDir - -IF NOT EXIST "%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config" goto endReadAdditionalConfig - -@setlocal EnableExtensions EnableDelayedExpansion -for /F "usebackq delims=" %%a in ("%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config") do set JVM_CONFIG_MAVEN_PROPS=!JVM_CONFIG_MAVEN_PROPS! %%a -@endlocal & set JVM_CONFIG_MAVEN_PROPS=%JVM_CONFIG_MAVEN_PROPS% - -:endReadAdditionalConfig - -SET MAVEN_JAVA_EXE="%JAVA_HOME%\bin\java.exe" - -set WRAPPER_JAR="%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.jar" -set WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain - -%MAVEN_JAVA_EXE% %JVM_CONFIG_MAVEN_PROPS% %MAVEN_OPTS% %MAVEN_DEBUG_OPTS% -classpath %WRAPPER_JAR% "-Dmaven.multiModuleProjectDirectory=%MAVEN_PROJECTBASEDIR%" %WRAPPER_LAUNCHER% %MAVEN_CONFIG% %* -if ERRORLEVEL 1 goto error -goto end - -:error -set ERROR_CODE=1 - -:end -@endlocal & set ERROR_CODE=%ERROR_CODE% - -if not "%MAVEN_SKIP_RC%" == "" goto skipRcPost -@REM check for post script, once with legacy .bat ending and once with .cmd ending -if exist "%HOME%\mavenrc_post.bat" call "%HOME%\mavenrc_post.bat" -if exist "%HOME%\mavenrc_post.cmd" call "%HOME%\mavenrc_post.cmd" -:skipRcPost - -@REM pause the script if MAVEN_BATCH_PAUSE is set to 'on' -if "%MAVEN_BATCH_PAUSE%" == "on" pause - -if "%MAVEN_TERMINATE_CMD%" == "on" exit %ERROR_CODE% - -exit /B %ERROR_CODE% diff --git a/spring-boot-modules/spring-boot-testing/pom.xml b/spring-boot-modules/spring-boot-testing/pom.xml deleted file mode 100644 index fcfc2364ba..0000000000 --- a/spring-boot-modules/spring-boot-testing/pom.xml +++ /dev/null @@ -1,149 +0,0 @@ - - - 4.0.0 - spring-boot-testing - spring-boot-testing - war - This is simple boot application for demonstrating testing features. - - - com.baeldung.spring-boot-modules - spring-boot-modules - 1.0.0-SNAPSHOT - - - - - - org.apache.logging.log4j - log4j-bom - ${log4j2.version} - import - pom - - - - - - - org.springframework.boot - spring-boot-starter-data-redis - - - org.springframework.boot - spring-boot-starter-web - - - org.springframework.boot - spring-boot-starter-validation - - - org.springframework.boot - spring-boot-starter-tomcat - - - org.springframework.boot - spring-boot-starter-security - - - org.springframework.boot - spring-boot-starter-data-jpa - - - com.h2database - h2 - - - org.springframework.boot - spring-boot-starter-test - test - - - - it.ozimov - embedded-redis - ${redis.version} - test - - - - org.spockframework - spock-core - ${spock.version} - test - - - org.spockframework - spock-spring - ${spock.version} - test - - - - - spring-boot-testing - - - src/main/resources - true - - - - - org.apache.maven.plugins - maven-war-plugin - - - pl.project13.maven - git-commit-id-plugin - ${git-commit-id-plugin.version} - - - get-the-git-infos - - revision - - initialize - - - validate-the-git-infos - - validateRevision - - package - - - - true - ${project.build.outputDirectory}/git.properties - - - - org.codehaus.gmavenplus - gmavenplus-plugin - ${gmavenplus-plugin.version} - - - - compileTests - - - - - - - - - - com.baeldung.boot.Application - 2.2.4 - 1.2-groovy-2.4 - 1.6 - 0.7.2 - 2.5.0 - 2.17.1 - - - \ No newline at end of file diff --git a/spring-boot-modules/spring-boot-testing/src/main/java/com/baeldung/boot/Application.java b/spring-boot-modules/spring-boot-testing/src/main/java/com/baeldung/boot/Application.java deleted file mode 100644 index cb0d0c1532..0000000000 --- a/spring-boot-modules/spring-boot-testing/src/main/java/com/baeldung/boot/Application.java +++ /dev/null @@ -1,14 +0,0 @@ -package com.baeldung.boot; - -import org.springframework.boot.SpringApplication; -import org.springframework.boot.autoconfigure.SpringBootApplication; -import org.springframework.context.ApplicationContext; - -@SpringBootApplication -public class Application { - private static ApplicationContext applicationContext; - - public static void main(String[] args) { - applicationContext = SpringApplication.run(Application.class, args); - } -} diff --git a/spring-boot-modules/spring-boot-testing/src/main/java/com/baeldung/boot/configurationproperties/Credentials.java b/spring-boot-modules/spring-boot-testing/src/main/java/com/baeldung/boot/configurationproperties/Credentials.java deleted file mode 100644 index e51937cf57..0000000000 --- a/spring-boot-modules/spring-boot-testing/src/main/java/com/baeldung/boot/configurationproperties/Credentials.java +++ /dev/null @@ -1,28 +0,0 @@ -package com.baeldung.boot.configurationproperties; - -public class Credentials { - - private String username; - private String password; - - public Credentials(String username, String password) { - this.username = username; - this.password = password; - } - - public String getUsername() { - return username; - } - - public void setUsername(String username) { - this.username = username; - } - - public String getPassword() { - return password; - } - - public void setPassword(String password) { - this.password = password; - } -} diff --git a/spring-boot-modules/spring-boot-testing/src/main/java/com/baeldung/boot/configurationproperties/CustomCredentialsConverter.java b/spring-boot-modules/spring-boot-testing/src/main/java/com/baeldung/boot/configurationproperties/CustomCredentialsConverter.java deleted file mode 100644 index ef160c8c9a..0000000000 --- a/spring-boot-modules/spring-boot-testing/src/main/java/com/baeldung/boot/configurationproperties/CustomCredentialsConverter.java +++ /dev/null @@ -1,16 +0,0 @@ -package com.baeldung.boot.configurationproperties; - -import org.springframework.boot.context.properties.ConfigurationPropertiesBinding; -import org.springframework.core.convert.converter.Converter; -import org.springframework.stereotype.Component; - -@Component -@ConfigurationPropertiesBinding -public class CustomCredentialsConverter implements Converter { - - @Override - public Credentials convert(String source) { - String[] data = source.split(","); - return new Credentials(data[0], data[1]); - } -} diff --git a/spring-boot-modules/spring-boot-testing/src/main/java/com/baeldung/boot/configurationproperties/MailServer.java b/spring-boot-modules/spring-boot-testing/src/main/java/com/baeldung/boot/configurationproperties/MailServer.java deleted file mode 100644 index e23b30759b..0000000000 --- a/spring-boot-modules/spring-boot-testing/src/main/java/com/baeldung/boot/configurationproperties/MailServer.java +++ /dev/null @@ -1,59 +0,0 @@ -package com.baeldung.boot.configurationproperties; - -import java.util.Map; - -import javax.validation.Valid; -import javax.validation.constraints.Email; -import javax.validation.constraints.NotBlank; -import javax.validation.constraints.NotEmpty; -import javax.validation.constraints.NotNull; - -import org.springframework.boot.context.properties.ConfigurationProperties; -import org.springframework.context.annotation.Configuration; -import org.springframework.context.annotation.PropertySource; -import org.springframework.validation.annotation.Validated; - -@Configuration -@ConfigurationProperties(prefix = "validate") -@PropertySource("classpath:property-validation.properties") -@Validated -public class MailServer { - - @NotNull - @NotEmpty - private Map propertiesMap; - - @Valid - private MailConfig mailConfig = new MailConfig(); - - public static class MailConfig { - - @NotBlank - @Email - private String address; - - public String getAddress() { - return address; - } - - public void setAddress(String address) { - this.address = address; - } - } - - public Map getPropertiesMap() { - return propertiesMap; - } - - public void setPropertiesMap(Map propertiesMap) { - this.propertiesMap = propertiesMap; - } - - public MailConfig getMailConfig() { - return mailConfig; - } - - public void setMailConfig(MailConfig mailConfig) { - this.mailConfig = mailConfig; - } -} \ No newline at end of file diff --git a/spring-boot-modules/spring-boot-testing/src/main/java/com/baeldung/boot/configurationproperties/PropertyConversion.java b/spring-boot-modules/spring-boot-testing/src/main/java/com/baeldung/boot/configurationproperties/PropertyConversion.java deleted file mode 100644 index 9b2ea39299..0000000000 --- a/spring-boot-modules/spring-boot-testing/src/main/java/com/baeldung/boot/configurationproperties/PropertyConversion.java +++ /dev/null @@ -1,67 +0,0 @@ -package com.baeldung.boot.configurationproperties; - -import java.time.Duration; -import java.time.temporal.ChronoUnit; -import org.springframework.boot.context.properties.ConfigurationProperties; -import org.springframework.boot.convert.DataSizeUnit; -import org.springframework.boot.convert.DurationUnit; -import org.springframework.context.annotation.Configuration; -import org.springframework.util.unit.DataSize; -import org.springframework.util.unit.DataUnit; - -@Configuration -@ConfigurationProperties(prefix = "server") -public class PropertyConversion { - - private DataSize uploadSpeed; - - @DataSizeUnit(DataUnit.GIGABYTES) - private DataSize downloadSpeed; - - private Duration backupDay; - - @DurationUnit(ChronoUnit.HOURS) - private Duration backupHour; - - private Credentials credentials; - - public Duration getBackupDay() { - return backupDay; - } - - public void setBackupDay(Duration backupDay) { - this.backupDay = backupDay; - } - - public Duration getBackupHour() { - return backupHour; - } - - public void setBackupHour(Duration backupHour) { - this.backupHour = backupHour; - } - - public DataSize getUploadSpeed() { - return uploadSpeed; - } - - public void setUploadSpeed(DataSize uploadSpeed) { - this.uploadSpeed = uploadSpeed; - } - - public DataSize getDownloadSpeed() { - return downloadSpeed; - } - - public void setDownloadSpeed(DataSize downloadSpeed) { - this.downloadSpeed = downloadSpeed; - } - - public Credentials getCredentials() { - return credentials; - } - - public void setCredentials(Credentials credentials) { - this.credentials = credentials; - } -} diff --git a/spring-boot-modules/spring-boot-testing/src/main/java/com/baeldung/boot/configurationproperties/ServerConfig.java b/spring-boot-modules/spring-boot-testing/src/main/java/com/baeldung/boot/configurationproperties/ServerConfig.java deleted file mode 100644 index 0c9e62445a..0000000000 --- a/spring-boot-modules/spring-boot-testing/src/main/java/com/baeldung/boot/configurationproperties/ServerConfig.java +++ /dev/null @@ -1,43 +0,0 @@ -package com.baeldung.boot.configurationproperties; - -import java.util.Map; - -import org.springframework.boot.context.properties.ConfigurationProperties; -import org.springframework.context.annotation.Configuration; - -@Configuration -@ConfigurationProperties(prefix = "server") -public class ServerConfig { - - private Address address; - private Map resourcesPath; - - public static class Address { - - private String ip; - - public String getIp() { - return ip; - } - - public void setIp(String ip) { - this.ip = ip; - } - } - - public Address getAddress() { - return address; - } - - public void setAddress(Address address) { - this.address = address; - } - - public Map getResourcesPath() { - return resourcesPath; - } - - public void setResourcesPath(Map resourcesPath) { - this.resourcesPath = resourcesPath; - } -} diff --git a/spring-boot-modules/spring-boot-testing/src/main/java/com/baeldung/boot/configurationproperties/ServerConfigFactory.java b/spring-boot-modules/spring-boot-testing/src/main/java/com/baeldung/boot/configurationproperties/ServerConfigFactory.java deleted file mode 100644 index ca85d59112..0000000000 --- a/spring-boot-modules/spring-boot-testing/src/main/java/com/baeldung/boot/configurationproperties/ServerConfigFactory.java +++ /dev/null @@ -1,15 +0,0 @@ -package com.baeldung.boot.configurationproperties; - -import org.springframework.boot.context.properties.ConfigurationProperties; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; - -@Configuration -public class ServerConfigFactory { - - @Bean(name = "default_bean") - @ConfigurationProperties(prefix = "server.default") - public ServerConfig getDefaultConfigs() { - return new ServerConfig(); - } -} \ No newline at end of file diff --git a/spring-boot-modules/spring-boot-testing/src/main/java/com/baeldung/boot/controller/rest/HomeController.java b/spring-boot-modules/spring-boot-testing/src/main/java/com/baeldung/boot/controller/rest/HomeController.java deleted file mode 100644 index 595c34254b..0000000000 --- a/spring-boot-modules/spring-boot-testing/src/main/java/com/baeldung/boot/controller/rest/HomeController.java +++ /dev/null @@ -1,14 +0,0 @@ -package com.baeldung.boot.controller.rest; - -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.RestController; - -@RestController -public class HomeController { - - @GetMapping("/") - public String salutation() { - return "Welcome !"; - } - -} \ No newline at end of file diff --git a/spring-boot-modules/spring-boot-testing/src/main/java/com/baeldung/boot/controller/rest/WebController.java b/spring-boot-modules/spring-boot-testing/src/main/java/com/baeldung/boot/controller/rest/WebController.java deleted file mode 100644 index 7247ca3dfa..0000000000 --- a/spring-boot-modules/spring-boot-testing/src/main/java/com/baeldung/boot/controller/rest/WebController.java +++ /dev/null @@ -1,36 +0,0 @@ -package com.baeldung.boot.controller.rest; - -import java.util.Optional; - -import org.springframework.http.HttpStatus; -import org.springframework.web.bind.annotation.DeleteMapping; -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.PutMapping; -import org.springframework.web.bind.annotation.RequestBody; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.ResponseStatus; -import org.springframework.web.bind.annotation.RestController; - -@RestController -@RequestMapping("/hello") -public class WebController { - - private String name; - - @GetMapping - public String salutation() { - return "Hello " + Optional.ofNullable(name).orElse("world") + '!'; - } - - @PutMapping - @ResponseStatus(HttpStatus.NO_CONTENT) - public void setName(@RequestBody final String name) { - this.name = name; - } - - @DeleteMapping - @ResponseStatus(HttpStatus.NO_CONTENT) - public void resetToDefault() { - this.name = null; - } -} \ No newline at end of file diff --git a/spring-boot-modules/spring-boot-testing/src/main/java/com/baeldung/boot/embeddedRedis/configuration/RedisConfiguration.java b/spring-boot-modules/spring-boot-testing/src/main/java/com/baeldung/boot/embeddedRedis/configuration/RedisConfiguration.java deleted file mode 100644 index 6b5b20892f..0000000000 --- a/spring-boot-modules/spring-boot-testing/src/main/java/com/baeldung/boot/embeddedRedis/configuration/RedisConfiguration.java +++ /dev/null @@ -1,24 +0,0 @@ -package com.baeldung.boot.embeddedRedis.configuration; - -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory; -import org.springframework.data.redis.core.RedisTemplate; -import org.springframework.data.redis.repository.configuration.EnableRedisRepositories; - -@Configuration -@EnableRedisRepositories -public class RedisConfiguration { - - @Bean - public LettuceConnectionFactory redisConnectionFactory(final RedisProperties redisProperties) { - return new LettuceConnectionFactory(redisProperties.getRedisHost(), redisProperties.getRedisPort()); - } - - @Bean - public RedisTemplate redisTemplate(final LettuceConnectionFactory connectionFactory) { - RedisTemplate template = new RedisTemplate<>(); - template.setConnectionFactory(connectionFactory); - return template; - } -} diff --git a/spring-boot-modules/spring-boot-testing/src/main/java/com/baeldung/boot/embeddedRedis/configuration/RedisProperties.java b/spring-boot-modules/spring-boot-testing/src/main/java/com/baeldung/boot/embeddedRedis/configuration/RedisProperties.java deleted file mode 100644 index 76f2e1bbfe..0000000000 --- a/spring-boot-modules/spring-boot-testing/src/main/java/com/baeldung/boot/embeddedRedis/configuration/RedisProperties.java +++ /dev/null @@ -1,23 +0,0 @@ -package com.baeldung.boot.embeddedRedis.configuration; - -import org.springframework.beans.factory.annotation.Value; -import org.springframework.context.annotation.Configuration; - -@Configuration -public class RedisProperties { - private final int redisPort; - private final String redisHost; - - public RedisProperties(@Value("${spring.redis.port}") final int redisPort, @Value("${spring.redis.host}") final String redisHost) { - this.redisPort = redisPort; - this.redisHost = redisHost; - } - - public int getRedisPort() { - return redisPort; - } - - public String getRedisHost() { - return redisHost; - } -} diff --git a/spring-boot-modules/spring-boot-testing/src/main/java/com/baeldung/boot/embeddedRedis/domain/User.java b/spring-boot-modules/spring-boot-testing/src/main/java/com/baeldung/boot/embeddedRedis/domain/User.java deleted file mode 100644 index 41657aaa66..0000000000 --- a/spring-boot-modules/spring-boot-testing/src/main/java/com/baeldung/boot/embeddedRedis/domain/User.java +++ /dev/null @@ -1,25 +0,0 @@ -package com.baeldung.boot.embeddedRedis.domain; - -import org.springframework.data.annotation.Id; -import org.springframework.data.redis.core.RedisHash; - -import java.util.UUID; - -@RedisHash("user") -public class User { - @Id private UUID id; - private String name; - - public User(UUID id, String name) { - this.id = id; - this.name = name; - } - - public UUID getId() { - return id; - } - - public String getName() { - return name; - } -} diff --git a/spring-boot-modules/spring-boot-testing/src/main/java/com/baeldung/boot/embeddedRedis/domain/repository/UserRepository.java b/spring-boot-modules/spring-boot-testing/src/main/java/com/baeldung/boot/embeddedRedis/domain/repository/UserRepository.java deleted file mode 100644 index 0558bb8482..0000000000 --- a/spring-boot-modules/spring-boot-testing/src/main/java/com/baeldung/boot/embeddedRedis/domain/repository/UserRepository.java +++ /dev/null @@ -1,10 +0,0 @@ -package com.baeldung.boot.embeddedRedis.domain.repository; - -import com.baeldung.boot.embeddedRedis.domain.User; -import org.springframework.data.repository.CrudRepository; - -import java.util.UUID; - -public interface UserRepository extends CrudRepository { - -} diff --git a/spring-boot-modules/spring-boot-testing/src/main/java/com/baeldung/boot/testing/Employee.java b/spring-boot-modules/spring-boot-testing/src/main/java/com/baeldung/boot/testing/Employee.java deleted file mode 100644 index 2921ecc609..0000000000 --- a/spring-boot-modules/spring-boot-testing/src/main/java/com/baeldung/boot/testing/Employee.java +++ /dev/null @@ -1,46 +0,0 @@ -package com.baeldung.boot.testing; - -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; -import javax.persistence.Table; -import javax.validation.constraints.Size; -import java.util.Date; - -@Entity -@Table(name = "person") -public class Employee { - - public Employee() { - } - - public Employee(String name) { - this.name = name; - } - - @Id - @GeneratedValue(strategy = GenerationType.AUTO) - private Long id; - - @Size(min = 3, max = 20) - private String name; - - private Date birthday; - - public Long getId() { - return id; - } - - public void setId(Long id) { - this.id = id; - } - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } -} \ No newline at end of file diff --git a/spring-boot-modules/spring-boot-testing/src/main/java/com/baeldung/boot/testing/EmployeeRepository.java b/spring-boot-modules/spring-boot-testing/src/main/java/com/baeldung/boot/testing/EmployeeRepository.java deleted file mode 100644 index bcef5231e0..0000000000 --- a/spring-boot-modules/spring-boot-testing/src/main/java/com/baeldung/boot/testing/EmployeeRepository.java +++ /dev/null @@ -1,17 +0,0 @@ -package com.baeldung.boot.testing; - -import java.util.List; - -import org.springframework.data.jpa.repository.JpaRepository; -import org.springframework.stereotype.Repository; -import org.springframework.transaction.annotation.Transactional; - -@Repository -@Transactional -public interface EmployeeRepository extends JpaRepository { - - public Employee findByName(String name); - - public List findAll(); - -} diff --git a/spring-boot-modules/spring-boot-testing/src/main/java/com/baeldung/boot/testing/EmployeeRestController.java b/spring-boot-modules/spring-boot-testing/src/main/java/com/baeldung/boot/testing/EmployeeRestController.java deleted file mode 100644 index b52d38e028..0000000000 --- a/spring-boot-modules/spring-boot-testing/src/main/java/com/baeldung/boot/testing/EmployeeRestController.java +++ /dev/null @@ -1,33 +0,0 @@ -package com.baeldung.boot.testing; - -import java.util.List; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.http.HttpStatus; -import org.springframework.http.ResponseEntity; -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.PostMapping; -import org.springframework.web.bind.annotation.RequestBody; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RestController; - -@RestController -@RequestMapping("/api") -public class EmployeeRestController { - - @Autowired - private EmployeeService employeeService; - - @PostMapping("/employees") - public ResponseEntity createEmployee(@RequestBody Employee employee) { - HttpStatus status = HttpStatus.CREATED; - Employee saved = employeeService.save(employee); - return new ResponseEntity<>(saved, status); - } - - @GetMapping("/employees") - public List getAllEmployees() { - return employeeService.getAllEmployees(); - } - -} diff --git a/spring-boot-modules/spring-boot-testing/src/main/java/com/baeldung/boot/testing/EmployeeService.java b/spring-boot-modules/spring-boot-testing/src/main/java/com/baeldung/boot/testing/EmployeeService.java deleted file mode 100644 index 6fc48a3c3d..0000000000 --- a/spring-boot-modules/spring-boot-testing/src/main/java/com/baeldung/boot/testing/EmployeeService.java +++ /dev/null @@ -1,16 +0,0 @@ -package com.baeldung.boot.testing; - -import java.util.List; - -public interface EmployeeService { - - public Employee getEmployeeById(Long id); - - public Employee getEmployeeByName(String name); - - public List getAllEmployees(); - - public boolean exists(String email); - - public Employee save(Employee employee); -} diff --git a/spring-boot-modules/spring-boot-testing/src/main/java/com/baeldung/boot/testing/EmployeeServiceImpl.java b/spring-boot-modules/spring-boot-testing/src/main/java/com/baeldung/boot/testing/EmployeeServiceImpl.java deleted file mode 100644 index 7d5ec4a05d..0000000000 --- a/spring-boot-modules/spring-boot-testing/src/main/java/com/baeldung/boot/testing/EmployeeServiceImpl.java +++ /dev/null @@ -1,43 +0,0 @@ -package com.baeldung.boot.testing; - -import java.util.List; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Service; -import org.springframework.transaction.annotation.Transactional; - -@Service -@Transactional -public class EmployeeServiceImpl implements EmployeeService { - - @Autowired - private EmployeeRepository employeeRepository; - - @Override - public Employee getEmployeeById(Long id) { - return employeeRepository.findById(id).orElse(null); - } - - @Override - public Employee getEmployeeByName(String name) { - return employeeRepository.findByName(name); - } - - @Override - public boolean exists(String name) { - if (employeeRepository.findByName(name) != null) { - return true; - } - return false; - } - - @Override - public Employee save(Employee employee) { - return employeeRepository.save(employee); - } - - @Override - public List getAllEmployees() { - return employeeRepository.findAll(); - } -} diff --git a/spring-boot-modules/spring-boot-testing/src/main/java/com/baeldung/prevent/commandline/application/runner/execution/ApplicationCommandLineRunnerApp.java b/spring-boot-modules/spring-boot-testing/src/main/java/com/baeldung/prevent/commandline/application/runner/execution/ApplicationCommandLineRunnerApp.java deleted file mode 100644 index 76e18dfd2f..0000000000 --- a/spring-boot-modules/spring-boot-testing/src/main/java/com/baeldung/prevent/commandline/application/runner/execution/ApplicationCommandLineRunnerApp.java +++ /dev/null @@ -1,11 +0,0 @@ -package com.baeldung.prevent.commandline.application.runner.execution; - -import org.springframework.boot.SpringApplication; -import org.springframework.boot.autoconfigure.SpringBootApplication; - -@SpringBootApplication -public class ApplicationCommandLineRunnerApp { - public static void main(String[] args) { - SpringApplication.run(ApplicationCommandLineRunnerApp.class, args); - } -} diff --git a/spring-boot-modules/spring-boot-testing/src/main/java/com/baeldung/prevent/commandline/application/runner/execution/ApplicationRunnerTaskExecutor.java b/spring-boot-modules/spring-boot-testing/src/main/java/com/baeldung/prevent/commandline/application/runner/execution/ApplicationRunnerTaskExecutor.java deleted file mode 100644 index 3bf08491bf..0000000000 --- a/spring-boot-modules/spring-boot-testing/src/main/java/com/baeldung/prevent/commandline/application/runner/execution/ApplicationRunnerTaskExecutor.java +++ /dev/null @@ -1,27 +0,0 @@ -package com.baeldung.prevent.commandline.application.runner.execution; - -import org.springframework.boot.ApplicationArguments; -import org.springframework.boot.ApplicationRunner; -import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; -import org.springframework.context.annotation.Profile; -import org.springframework.stereotype.Component; - -@Profile("!test") -@ConditionalOnProperty( - prefix = "application.runner", - value = "enabled", - havingValue = "true", - matchIfMissing = true) -@Component -public class ApplicationRunnerTaskExecutor implements ApplicationRunner { - private TaskService taskService; - - public ApplicationRunnerTaskExecutor(TaskService taskService) { - this.taskService = taskService; - } - - @Override - public void run(ApplicationArguments args) throws Exception { - taskService.execute("application runner task"); - } -} diff --git a/spring-boot-modules/spring-boot-testing/src/main/java/com/baeldung/prevent/commandline/application/runner/execution/CommandLineTaskExecutor.java b/spring-boot-modules/spring-boot-testing/src/main/java/com/baeldung/prevent/commandline/application/runner/execution/CommandLineTaskExecutor.java deleted file mode 100644 index 38fd3b9c0a..0000000000 --- a/spring-boot-modules/spring-boot-testing/src/main/java/com/baeldung/prevent/commandline/application/runner/execution/CommandLineTaskExecutor.java +++ /dev/null @@ -1,26 +0,0 @@ -package com.baeldung.prevent.commandline.application.runner.execution; - -import org.springframework.boot.CommandLineRunner; -import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; -import org.springframework.context.annotation.Profile; -import org.springframework.stereotype.Component; - -@Profile("!test") -@ConditionalOnProperty( - prefix = "command.line.runner", - value = "enabled", - havingValue = "true", - matchIfMissing = true) -@Component -public class CommandLineTaskExecutor implements CommandLineRunner { - private TaskService taskService; - - public CommandLineTaskExecutor(TaskService taskService) { - this.taskService = taskService; - } - - @Override - public void run(String... args) throws Exception { - taskService.execute("command line runner task"); - } -} diff --git a/spring-boot-modules/spring-boot-testing/src/main/java/com/baeldung/prevent/commandline/application/runner/execution/TaskService.java b/spring-boot-modules/spring-boot-testing/src/main/java/com/baeldung/prevent/commandline/application/runner/execution/TaskService.java deleted file mode 100644 index dac437e72d..0000000000 --- a/spring-boot-modules/spring-boot-testing/src/main/java/com/baeldung/prevent/commandline/application/runner/execution/TaskService.java +++ /dev/null @@ -1,14 +0,0 @@ -package com.baeldung.prevent.commandline.application.runner.execution; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.stereotype.Service; - -@Service -public class TaskService { - private static Logger logger = LoggerFactory.getLogger(TaskService.class); - - public void execute(String task) { - logger.info("do " + task); - } -} diff --git a/spring-boot-modules/spring-boot-testing/src/main/resources/application-test.properties b/spring-boot-modules/spring-boot-testing/src/main/resources/application-test.properties deleted file mode 100644 index 8d5e86ba26..0000000000 --- a/spring-boot-modules/spring-boot-testing/src/main/resources/application-test.properties +++ /dev/null @@ -1,3 +0,0 @@ - -# test properties -spring.autoconfigure.exclude=org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration \ No newline at end of file diff --git a/spring-boot-modules/spring-boot-testing/src/main/resources/application.properties b/spring-boot-modules/spring-boot-testing/src/main/resources/application.properties deleted file mode 100644 index 70cae370a4..0000000000 --- a/spring-boot-modules/spring-boot-testing/src/main/resources/application.properties +++ /dev/null @@ -1,8 +0,0 @@ -# embedded redis -spring.redis.host= localhost -spring.redis.port= 6379 - -# security -spring.security.user.name=john -spring.security.user.password=123 - diff --git a/spring-boot-modules/spring-boot-testing/src/main/resources/persistence-generic-entity.properties b/spring-boot-modules/spring-boot-testing/src/main/resources/persistence-generic-entity.properties deleted file mode 100644 index b19304cb1f..0000000000 --- a/spring-boot-modules/spring-boot-testing/src/main/resources/persistence-generic-entity.properties +++ /dev/null @@ -1,8 +0,0 @@ -jdbc.driverClassName=org.h2.Driver -jdbc.url=jdbc:h2:mem:db;DB_CLOSE_DELAY=-1 -jdbc.user=sa -jdbc.pass=sa - -hibernate.dialect=org.hibernate.dialect.H2Dialect -hibernate.show_sql=true -hibernate.hbm2ddl.auto=create-drop diff --git a/spring-boot-modules/spring-boot-testing/src/main/resources/property-validation.properties b/spring-boot-modules/spring-boot-testing/src/main/resources/property-validation.properties deleted file mode 100644 index 6b4c881dc0..0000000000 --- a/spring-boot-modules/spring-boot-testing/src/main/resources/property-validation.properties +++ /dev/null @@ -1,4 +0,0 @@ -validate.propertiesMap.first=prop1 -validate.propertiesMap.second=prop2 - -validate.mail_config.address=user1@test \ No newline at end of file diff --git a/spring-boot-modules/spring-boot-testing/src/test/groovy/com/baeldung/boot/LoadContextTest.groovy b/spring-boot-modules/spring-boot-testing/src/test/groovy/com/baeldung/boot/LoadContextTest.groovy deleted file mode 100644 index 85b0a4b89b..0000000000 --- a/spring-boot-modules/spring-boot-testing/src/test/groovy/com/baeldung/boot/LoadContextTest.groovy +++ /dev/null @@ -1,23 +0,0 @@ -package com.baeldung.boot - -import com.baeldung.boot.controller.rest.WebController -import org.springframework.beans.factory.annotation.Autowired -import org.springframework.boot.test.context.SpringBootTest -import spock.lang.Narrative -import spock.lang.Specification -import spock.lang.Title - -@Title("Application Specification") -@Narrative("Specification which beans are expected") -@SpringBootTest -class LoadContextTest extends Specification { - - @Autowired(required = false) - private WebController webController - - - def "when context is loaded then all expected beans are created"() { - expect: "the WebController is created" - webController - } -} diff --git a/spring-boot-modules/spring-boot-testing/src/test/groovy/com/baeldung/boot/WebControllerTest.groovy b/spring-boot-modules/spring-boot-testing/src/test/groovy/com/baeldung/boot/WebControllerTest.groovy deleted file mode 100644 index fe53abd241..0000000000 --- a/spring-boot-modules/spring-boot-testing/src/test/groovy/com/baeldung/boot/WebControllerTest.groovy +++ /dev/null @@ -1,46 +0,0 @@ -package com.baeldung.boot - -import org.springframework.beans.factory.annotation.Autowired -import org.springframework.boot.autoconfigure.EnableAutoConfiguration -import org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration -import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc -import org.springframework.boot.test.context.SpringBootTest -import org.springframework.test.web.servlet.MockMvc -import org.springframework.test.web.servlet.request.MockMvcRequestBuilders -import org.springframework.test.web.servlet.result.MockMvcResultMatchers -import spock.lang.Narrative -import spock.lang.Specification -import spock.lang.Title - -@Title("WebController Specification") -@Narrative("The Specification of the behaviour of the WebController. It can greet a person, change the name and reset it to 'world'") -@SpringBootTest -@AutoConfigureMockMvc -@EnableAutoConfiguration(exclude= SecurityAutoConfiguration.class) -class WebControllerTest extends Specification { - - @Autowired - private MockMvc mvc - - def "when get is performed then the response has status 200 and content is 'Hello world!'"() { - expect: "Status is 200 and the response is 'Hello world!'" - mvc.perform(MockMvcRequestBuilders.get("/hello")).andExpect(MockMvcResultMatchers.status().isOk()).andReturn().response.contentAsString == "Hello world!" - } - - def "when set and delete are performed then the response has status 204 and content changes as expected"() { - given: "a new name" - def NAME = "Emmy" - - when: "the name is set" - mvc.perform(MockMvcRequestBuilders.put("/hello").content(NAME)).andExpect(MockMvcResultMatchers.status().isNoContent()) - - then: "the salutation uses the new name" - mvc.perform(MockMvcRequestBuilders.get("/hello")).andExpect(MockMvcResultMatchers.status().isOk()).andReturn().response.contentAsString == "Hello $NAME!" - - when: "the name is deleted" - mvc.perform(MockMvcRequestBuilders.delete("/hello")).andExpect(MockMvcResultMatchers.status().isNoContent()) - - then: "the salutation uses the default name" - mvc.perform(MockMvcRequestBuilders.get("/hello")).andExpect(MockMvcResultMatchers.status().isOk()).andReturn().response.contentAsString == "Hello world!" - } -} diff --git a/spring-boot-modules/spring-boot-testing/src/test/groovy/com/baeldung/boot/WebControllerTest.groovy alias b/spring-boot-modules/spring-boot-testing/src/test/groovy/com/baeldung/boot/WebControllerTest.groovy alias deleted file mode 100644 index f2fc2f48e2..0000000000 Binary files a/spring-boot-modules/spring-boot-testing/src/test/groovy/com/baeldung/boot/WebControllerTest.groovy alias and /dev/null differ diff --git a/spring-boot-modules/spring-boot-testing/src/test/java/com/baeldung/autoconfig/exclude/ExcludeAutoConfig1IntegrationTest.java b/spring-boot-modules/spring-boot-testing/src/test/java/com/baeldung/autoconfig/exclude/ExcludeAutoConfig1IntegrationTest.java deleted file mode 100644 index 2ca0c74901..0000000000 --- a/spring-boot-modules/spring-boot-testing/src/test/java/com/baeldung/autoconfig/exclude/ExcludeAutoConfig1IntegrationTest.java +++ /dev/null @@ -1,32 +0,0 @@ -package com.baeldung.autoconfig.exclude; - -import com.baeldung.boot.Application; -import io.restassured.RestAssured; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; -import org.springframework.boot.web.server.LocalServerPort; -import org.springframework.http.HttpStatus; -import org.springframework.test.context.TestPropertySource; -import org.springframework.test.context.junit4.SpringRunner; - -import static org.junit.Assert.assertEquals; - -@RunWith(SpringRunner.class) -@SpringBootTest(classes = Application.class, webEnvironment = WebEnvironment.RANDOM_PORT) -@TestPropertySource(properties = "spring.autoconfigure.exclude=org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration") -public class ExcludeAutoConfig1IntegrationTest { - - /** - * Encapsulates the random port the test server is listening on. - */ - @LocalServerPort - private int port; - - @Test - public void givenSecurityConfigExcluded_whenAccessHome_thenNoAuthenticationRequired() { - int statusCode = RestAssured.get("http://localhost:" + port).statusCode(); - assertEquals(HttpStatus.OK.value(), statusCode); - } -} diff --git a/spring-boot-modules/spring-boot-testing/src/test/java/com/baeldung/autoconfig/exclude/ExcludeAutoConfig2IntegrationTest.java b/spring-boot-modules/spring-boot-testing/src/test/java/com/baeldung/autoconfig/exclude/ExcludeAutoConfig2IntegrationTest.java deleted file mode 100644 index c0bd6570a1..0000000000 --- a/spring-boot-modules/spring-boot-testing/src/test/java/com/baeldung/autoconfig/exclude/ExcludeAutoConfig2IntegrationTest.java +++ /dev/null @@ -1,32 +0,0 @@ -package com.baeldung.autoconfig.exclude; - -import com.baeldung.boot.Application; -import io.restassured.RestAssured; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; -import org.springframework.boot.web.server.LocalServerPort; -import org.springframework.http.HttpStatus; -import org.springframework.test.context.ActiveProfiles; -import org.springframework.test.context.junit4.SpringRunner; - -import static org.junit.Assert.assertEquals; - -@RunWith(SpringRunner.class) -@SpringBootTest(classes = Application.class, webEnvironment = WebEnvironment.RANDOM_PORT) -@ActiveProfiles("test") -public class ExcludeAutoConfig2IntegrationTest { - - /** - * Encapsulates the random port the test server is listening on. - */ - @LocalServerPort - private int port; - - @Test - public void givenSecurityConfigExcluded_whenAccessHome_thenNoAuthenticationRequired() { - int statusCode = RestAssured.get("http://localhost:" + port).statusCode(); - assertEquals(HttpStatus.OK.value(), statusCode); - } -} diff --git a/spring-boot-modules/spring-boot-testing/src/test/java/com/baeldung/autoconfig/exclude/ExcludeAutoConfig3IntegrationTest.java b/spring-boot-modules/spring-boot-testing/src/test/java/com/baeldung/autoconfig/exclude/ExcludeAutoConfig3IntegrationTest.java deleted file mode 100644 index 1642d4b932..0000000000 --- a/spring-boot-modules/spring-boot-testing/src/test/java/com/baeldung/autoconfig/exclude/ExcludeAutoConfig3IntegrationTest.java +++ /dev/null @@ -1,33 +0,0 @@ -package com.baeldung.autoconfig.exclude; - -import com.baeldung.boot.Application; -import io.restassured.RestAssured; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.boot.autoconfigure.EnableAutoConfiguration; -import org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; -import org.springframework.boot.web.server.LocalServerPort; -import org.springframework.http.HttpStatus; -import org.springframework.test.context.junit4.SpringRunner; - -import static org.junit.Assert.assertEquals; - -@RunWith(SpringRunner.class) -@SpringBootTest(classes = Application.class, webEnvironment = WebEnvironment.RANDOM_PORT) -@EnableAutoConfiguration(exclude=SecurityAutoConfiguration.class) -public class ExcludeAutoConfig3IntegrationTest { - - /** - * Encapsulates the random port the test server is listening on. - */ - @LocalServerPort - private int port; - - @Test - public void givenSecurityConfigExcluded_whenAccessHome_thenNoAuthenticationRequired() { - int statusCode = RestAssured.get("http://localhost:" + port).statusCode(); - assertEquals(HttpStatus.OK.value(), statusCode); - } -} diff --git a/spring-boot-modules/spring-boot-testing/src/test/java/com/baeldung/autoconfig/exclude/ExcludeAutoConfig4IntegrationTest.java b/spring-boot-modules/spring-boot-testing/src/test/java/com/baeldung/autoconfig/exclude/ExcludeAutoConfig4IntegrationTest.java deleted file mode 100644 index 1aa453348b..0000000000 --- a/spring-boot-modules/spring-boot-testing/src/test/java/com/baeldung/autoconfig/exclude/ExcludeAutoConfig4IntegrationTest.java +++ /dev/null @@ -1,29 +0,0 @@ -package com.baeldung.autoconfig.exclude; - -import io.restassured.RestAssured; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; -import org.springframework.boot.web.server.LocalServerPort; -import org.springframework.http.HttpStatus; -import org.springframework.test.context.junit4.SpringRunner; - -import static org.junit.Assert.assertEquals; - -@RunWith(SpringRunner.class) -@SpringBootTest(classes = TestApplication.class, webEnvironment = WebEnvironment.RANDOM_PORT) -public class ExcludeAutoConfig4IntegrationTest { - - /** - * Encapsulates the random port the test server is listening on. - */ - @LocalServerPort - private int port; - - @Test - public void givenSecurityConfigExcluded_whenAccessHome_thenNoAuthenticationRequired() { - int statusCode = RestAssured.get("http://localhost:" + port).statusCode(); - assertEquals(HttpStatus.OK.value(), statusCode); - } -} diff --git a/spring-boot-modules/spring-boot-testing/src/test/java/com/baeldung/autoconfig/exclude/TestApplication.java b/spring-boot-modules/spring-boot-testing/src/test/java/com/baeldung/autoconfig/exclude/TestApplication.java deleted file mode 100644 index 7c162f85ab..0000000000 --- a/spring-boot-modules/spring-boot-testing/src/test/java/com/baeldung/autoconfig/exclude/TestApplication.java +++ /dev/null @@ -1,13 +0,0 @@ -package com.baeldung.autoconfig.exclude; - -import org.springframework.boot.SpringApplication; -import org.springframework.boot.autoconfigure.SpringBootApplication; -import org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration; - -@SpringBootApplication(scanBasePackages="com.baeldung.boot", exclude=SecurityAutoConfiguration.class) -public class TestApplication { - - public static void main(String[] args) { - SpringApplication.run(TestApplication.class, args); - } -} diff --git a/spring-boot-modules/spring-boot-testing/src/test/java/com/baeldung/boot/SpringContextTest.java b/spring-boot-modules/spring-boot-testing/src/test/java/com/baeldung/boot/SpringContextTest.java deleted file mode 100644 index f3c8b9a954..0000000000 --- a/spring-boot-modules/spring-boot-testing/src/test/java/com/baeldung/boot/SpringContextTest.java +++ /dev/null @@ -1,15 +0,0 @@ -package com.baeldung.boot; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.test.context.junit4.SpringRunner; - -@RunWith(SpringRunner.class) -@SpringBootTest(classes = Application.class) -public class SpringContextTest { - - @Test - public void whenSpringContextIsBootstrapped_thenNoExceptions() { - } -} diff --git a/spring-boot-modules/spring-boot-testing/src/test/java/com/baeldung/boot/autoconfig/AutoConfigIntegrationTest.java b/spring-boot-modules/spring-boot-testing/src/test/java/com/baeldung/boot/autoconfig/AutoConfigIntegrationTest.java deleted file mode 100644 index 44a02c0c80..0000000000 --- a/spring-boot-modules/spring-boot-testing/src/test/java/com/baeldung/boot/autoconfig/AutoConfigIntegrationTest.java +++ /dev/null @@ -1,36 +0,0 @@ -package com.baeldung.boot.autoconfig; - -import com.baeldung.boot.Application; -import io.restassured.RestAssured; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; -import org.springframework.boot.web.server.LocalServerPort; -import org.springframework.http.HttpStatus; -import org.springframework.test.context.junit4.SpringRunner; - -import static org.junit.Assert.assertEquals; - -@RunWith(SpringRunner.class) -@SpringBootTest(classes = Application.class, webEnvironment = WebEnvironment.RANDOM_PORT) -public class AutoConfigIntegrationTest { - - /** - * Encapsulates the random port the test server is listening on. - */ - @LocalServerPort - private int port; - - @Test - public void givenNoAuthentication_whenAccessHome_thenUnauthorized() { - int statusCode = RestAssured.get("http://localhost:" + port).statusCode(); - assertEquals(HttpStatus.UNAUTHORIZED.value(), statusCode); - } - - @Test - public void givenAuthentication_whenAccessHome_thenOK() { - int statusCode = RestAssured.given().auth().basic("john", "123").get("http://localhost:" + port).statusCode(); - assertEquals(HttpStatus.OK.value(), statusCode); - } -} diff --git a/spring-boot-modules/spring-boot-testing/src/test/java/com/baeldung/boot/configurationproperties/BindingPropertiesToBeanMethodsUnitTest.java b/spring-boot-modules/spring-boot-testing/src/test/java/com/baeldung/boot/configurationproperties/BindingPropertiesToBeanMethodsUnitTest.java deleted file mode 100644 index 82c2a55c32..0000000000 --- a/spring-boot-modules/spring-boot-testing/src/test/java/com/baeldung/boot/configurationproperties/BindingPropertiesToBeanMethodsUnitTest.java +++ /dev/null @@ -1,36 +0,0 @@ -package com.baeldung.boot.configurationproperties; - -import static org.junit.jupiter.api.Assertions.assertEquals; - -import java.util.HashMap; -import java.util.Map; - -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.extension.ExtendWith; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Qualifier; -import org.springframework.boot.context.properties.EnableConfigurationProperties; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.TestPropertySource; -import org.springframework.test.context.junit.jupiter.SpringExtension; - -@ExtendWith(SpringExtension.class) -@EnableConfigurationProperties(value = ServerConfig.class) -@ContextConfiguration(classes = ServerConfigFactory.class) -@TestPropertySource("classpath:server-config-test.properties") -public class BindingPropertiesToBeanMethodsUnitTest { - - @Autowired - @Qualifier("default_bean") - private ServerConfig serverConfig; - - @Test - void givenBeanAnnotatedMethod_whenBindingProperties_thenAllFieldsAreSet() { - assertEquals("192.168.0.2", serverConfig.getAddress() - .getIp()); - - Map expectedResourcesPath = new HashMap<>(); - expectedResourcesPath.put("imgs", "/root/def/imgs"); - assertEquals(expectedResourcesPath, serverConfig.getResourcesPath()); - } -} \ No newline at end of file diff --git a/spring-boot-modules/spring-boot-testing/src/test/java/com/baeldung/boot/configurationproperties/BindingPropertiesToUserDefinedPOJOUnitTest.java b/spring-boot-modules/spring-boot-testing/src/test/java/com/baeldung/boot/configurationproperties/BindingPropertiesToUserDefinedPOJOUnitTest.java deleted file mode 100644 index 9db906fa04..0000000000 --- a/spring-boot-modules/spring-boot-testing/src/test/java/com/baeldung/boot/configurationproperties/BindingPropertiesToUserDefinedPOJOUnitTest.java +++ /dev/null @@ -1,32 +0,0 @@ -package com.baeldung.boot.configurationproperties; - -import static org.junit.jupiter.api.Assertions.assertEquals; - -import java.util.HashMap; -import java.util.Map; - -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.extension.ExtendWith; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.context.properties.EnableConfigurationProperties; -import org.springframework.test.context.TestPropertySource; -import org.springframework.test.context.junit.jupiter.SpringExtension; - -@ExtendWith(SpringExtension.class) -@EnableConfigurationProperties(value = ServerConfig.class) -@TestPropertySource("classpath:server-config-test.properties") -public class BindingPropertiesToUserDefinedPOJOUnitTest { - - @Autowired - private ServerConfig serverConfig; - - @Test - void givenUserDefinedPOJO_whenBindingPropertiesFile_thenAllFieldsAreSet() { - assertEquals("192.168.0.1", serverConfig.getAddress() - .getIp()); - - Map expectedResourcesPath = new HashMap<>(); - expectedResourcesPath.put("imgs", "/root/imgs"); - assertEquals(expectedResourcesPath, serverConfig.getResourcesPath()); - } -} \ No newline at end of file diff --git a/spring-boot-modules/spring-boot-testing/src/test/java/com/baeldung/boot/configurationproperties/BindingYMLPropertiesUnitTest.java b/spring-boot-modules/spring-boot-testing/src/test/java/com/baeldung/boot/configurationproperties/BindingYMLPropertiesUnitTest.java deleted file mode 100644 index 99c128997e..0000000000 --- a/spring-boot-modules/spring-boot-testing/src/test/java/com/baeldung/boot/configurationproperties/BindingYMLPropertiesUnitTest.java +++ /dev/null @@ -1,33 +0,0 @@ -package com.baeldung.boot.configurationproperties; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import java.util.HashMap; -import java.util.Map; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.extension.ExtendWith; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.context.properties.EnableConfigurationProperties; -import org.springframework.boot.test.context.ConfigDataApplicationContextInitializer; -import org.springframework.test.context.ActiveProfiles; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit.jupiter.SpringExtension; - -@ExtendWith(SpringExtension.class) -@ContextConfiguration(initializers = ConfigDataApplicationContextInitializer.class) -@EnableConfigurationProperties(value = ServerConfig.class) -@ActiveProfiles("test") -public class BindingYMLPropertiesUnitTest { - - @Autowired - private ServerConfig serverConfig; - - @Test - void whenBindingYMLConfigFile_thenAllFieldsAreSet() { - assertEquals("192.168.0.4", serverConfig.getAddress() - .getIp()); - - Map expectedResourcesPath = new HashMap<>(); - expectedResourcesPath.put("imgs", "/etc/test/imgs"); - assertEquals(expectedResourcesPath, serverConfig.getResourcesPath()); - } -} \ No newline at end of file diff --git a/spring-boot-modules/spring-boot-testing/src/test/java/com/baeldung/boot/configurationproperties/OverridingConfigurationPropertiesUnitTest.java b/spring-boot-modules/spring-boot-testing/src/test/java/com/baeldung/boot/configurationproperties/OverridingConfigurationPropertiesUnitTest.java deleted file mode 100644 index 2779b0a313..0000000000 --- a/spring-boot-modules/spring-boot-testing/src/test/java/com/baeldung/boot/configurationproperties/OverridingConfigurationPropertiesUnitTest.java +++ /dev/null @@ -1,33 +0,0 @@ -package com.baeldung.boot.configurationproperties; - -import static org.junit.jupiter.api.Assertions.assertEquals; - -import java.util.HashMap; -import java.util.Map; - -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.extension.ExtendWith; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.context.properties.EnableConfigurationProperties; -import org.springframework.test.context.TestPropertySource; -import org.springframework.test.context.junit.jupiter.SpringExtension; - -@ExtendWith(SpringExtension.class) -@EnableConfigurationProperties(value = MailServer.class) -@TestPropertySource(properties = { "validate.mail_config.address=new_user@test" }) -public class OverridingConfigurationPropertiesUnitTest { - - @Autowired - private MailServer mailServer; - - @Test - void givenUsingPropertiesAttribute_whenAssiginingNewValueToProprty_thenSpringUsesNewValue() { - assertEquals("new_user@test", mailServer.getMailConfig() - .getAddress()); - - Map expectedMap = new HashMap<>(); - expectedMap.put("first", "prop1"); - expectedMap.put("second", "prop2"); - assertEquals(expectedMap, mailServer.getPropertiesMap()); - } -} \ No newline at end of file diff --git a/spring-boot-modules/spring-boot-testing/src/test/java/com/baeldung/boot/configurationproperties/PropertyValidationUnitTest.java b/spring-boot-modules/spring-boot-testing/src/test/java/com/baeldung/boot/configurationproperties/PropertyValidationUnitTest.java deleted file mode 100644 index 939471dd67..0000000000 --- a/spring-boot-modules/spring-boot-testing/src/test/java/com/baeldung/boot/configurationproperties/PropertyValidationUnitTest.java +++ /dev/null @@ -1,39 +0,0 @@ -package com.baeldung.boot.configurationproperties; - -import static org.junit.jupiter.api.Assertions.assertEquals; - -import javax.validation.Validation; -import javax.validation.Validator; - -import org.junit.jupiter.api.BeforeAll; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.extension.ExtendWith; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.context.properties.EnableConfigurationProperties; -import org.springframework.test.context.TestPropertySource; -import org.springframework.test.context.junit.jupiter.SpringExtension; - -@ExtendWith(SpringExtension.class) -@EnableConfigurationProperties(value = MailServer.class) -@TestPropertySource("classpath:property-validation-test.properties") -public class PropertyValidationUnitTest { - - @Autowired - private MailServer mailServer; - - private static Validator propertyValidator; - - @BeforeAll - public static void setup() { - propertyValidator = Validation.buildDefaultValidatorFactory() - .getValidator(); - } - - @Test - void whenBindingPropertiesToValidatedBeans_thenConstrainsAreChecked() { - assertEquals(0, propertyValidator.validate(mailServer.getPropertiesMap()) - .size()); - assertEquals(0, propertyValidator.validate(mailServer.getMailConfig()) - .size()); - } -} \ No newline at end of file diff --git a/spring-boot-modules/spring-boot-testing/src/test/java/com/baeldung/boot/configurationproperties/SpringPropertiesConversionUnitTest.java b/spring-boot-modules/spring-boot-testing/src/test/java/com/baeldung/boot/configurationproperties/SpringPropertiesConversionUnitTest.java deleted file mode 100644 index 3f2da2a669..0000000000 --- a/spring-boot-modules/spring-boot-testing/src/test/java/com/baeldung/boot/configurationproperties/SpringPropertiesConversionUnitTest.java +++ /dev/null @@ -1,44 +0,0 @@ -package com.baeldung.boot.configurationproperties; - -import static org.junit.jupiter.api.Assertions.assertEquals; - -import java.time.Duration; - -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.extension.ExtendWith; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.context.properties.EnableConfigurationProperties; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.TestPropertySource; -import org.springframework.test.context.junit.jupiter.SpringExtension; -import org.springframework.util.unit.DataSize; - -@ExtendWith(SpringExtension.class) -@EnableConfigurationProperties(value = PropertyConversion.class) -@ContextConfiguration(classes = CustomCredentialsConverter.class) -@TestPropertySource("classpath:spring-conversion-test.properties") -public class SpringPropertiesConversionUnitTest { - - @Autowired - private PropertyConversion propertyConversion; - - @Test - void whenUsingSpringDefaultSizeConversion_thenDataSizeObjectIsSet() { - assertEquals(DataSize.ofMegabytes(500), propertyConversion.getUploadSpeed()); - assertEquals(DataSize.ofGigabytes(10), propertyConversion.getDownloadSpeed()); - } - - @Test - void whenUsingSpringDefaultDurationConversion_thenDurationObjectIsSet() { - assertEquals(Duration.ofDays(1), propertyConversion.getBackupDay()); - assertEquals(Duration.ofHours(8), propertyConversion.getBackupHour()); - } - - @Test - void whenRegisteringCustomCredentialsConverter_thenCredentialsAreParsed() { - assertEquals("user", propertyConversion.getCredentials() - .getUsername()); - assertEquals("123", propertyConversion.getCredentials() - .getPassword()); - } -} \ No newline at end of file diff --git a/spring-boot-modules/spring-boot-testing/src/test/java/com/baeldung/boot/embeddedRedis/TestRedisConfiguration.java b/spring-boot-modules/spring-boot-testing/src/test/java/com/baeldung/boot/embeddedRedis/TestRedisConfiguration.java deleted file mode 100644 index b4748bcd38..0000000000 --- a/spring-boot-modules/spring-boot-testing/src/test/java/com/baeldung/boot/embeddedRedis/TestRedisConfiguration.java +++ /dev/null @@ -1,28 +0,0 @@ -package com.baeldung.boot.embeddedRedis; - -import com.baeldung.boot.embeddedRedis.configuration.RedisProperties; -import org.springframework.boot.test.context.TestConfiguration; -import redis.embedded.RedisServer; - -import javax.annotation.PostConstruct; -import javax.annotation.PreDestroy; - -@TestConfiguration -public class TestRedisConfiguration { - - private final RedisServer redisServer; - - public TestRedisConfiguration(final RedisProperties redisProperties) { - this.redisServer = new RedisServer(redisProperties.getRedisPort()); - } - - @PostConstruct - public void postConstruct() { - redisServer.start(); - } - - @PreDestroy - public void preDestroy() { - redisServer.stop(); - } -} diff --git a/spring-boot-modules/spring-boot-testing/src/test/java/com/baeldung/boot/embeddedRedis/domain/repository/UserRepositoryIntegrationTest.java b/spring-boot-modules/spring-boot-testing/src/test/java/com/baeldung/boot/embeddedRedis/domain/repository/UserRepositoryIntegrationTest.java deleted file mode 100644 index 9577ccf0e8..0000000000 --- a/spring-boot-modules/spring-boot-testing/src/test/java/com/baeldung/boot/embeddedRedis/domain/repository/UserRepositoryIntegrationTest.java +++ /dev/null @@ -1,31 +0,0 @@ -package com.baeldung.boot.embeddedRedis.domain.repository; - -import com.baeldung.boot.embeddedRedis.TestRedisConfiguration; -import com.baeldung.boot.embeddedRedis.domain.User; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.test.context.junit4.SpringRunner; - -import java.util.UUID; - -import static org.junit.Assert.assertNotNull; - -@RunWith(SpringRunner.class) -@SpringBootTest(classes = TestRedisConfiguration.class) -public class UserRepositoryIntegrationTest { - - @Autowired - private UserRepository userRepository; - - @Test - public void shouldSaveUser_toRedis() { - final UUID id = UUID.randomUUID(); - final User user = new User(id, "name"); - - final User saved = userRepository.save(user); - - assertNotNull(saved); - } -} \ No newline at end of file diff --git a/spring-boot-modules/spring-boot-testing/src/test/java/com/baeldung/boot/testing/EmployeeControllerIntegrationTest.java b/spring-boot-modules/spring-boot-testing/src/test/java/com/baeldung/boot/testing/EmployeeControllerIntegrationTest.java deleted file mode 100644 index c51113a023..0000000000 --- a/spring-boot-modules/spring-boot-testing/src/test/java/com/baeldung/boot/testing/EmployeeControllerIntegrationTest.java +++ /dev/null @@ -1,73 +0,0 @@ -package com.baeldung.boot.testing; - -import static org.hamcrest.CoreMatchers.is; -import static org.hamcrest.Matchers.hasSize; -import static org.mockito.BDDMockito.given; -import static org.mockito.Mockito.reset; -import static org.mockito.Mockito.verify; -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; - -import java.util.Arrays; -import java.util.List; - -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.Mockito; -import org.mockito.internal.verification.VerificationModeFactory; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration; -import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest; -import org.springframework.boot.test.mock.mockito.MockBean; -import org.springframework.http.MediaType; -import org.springframework.test.context.junit4.SpringRunner; -import org.springframework.test.web.servlet.MockMvc; - -import com.baeldung.boot.testing.Employee; -import com.baeldung.boot.testing.EmployeeRestController; -import com.baeldung.boot.testing.EmployeeService; - -@RunWith(SpringRunner.class) -@WebMvcTest(value = EmployeeRestController.class, excludeAutoConfiguration = SecurityAutoConfiguration.class) -public class EmployeeControllerIntegrationTest { - - @Autowired - private MockMvc mvc; - - @MockBean - private EmployeeService service; - - @Before - public void setUp() throws Exception { - } - - @Test - public void whenPostEmployee_thenCreateEmployee() throws Exception { - Employee alex = new Employee("alex"); - given(service.save(Mockito.any())).willReturn(alex); - - mvc.perform(post("/api/employees").contentType(MediaType.APPLICATION_JSON).content(JsonUtil.toJson(alex))).andExpect(status().isCreated()).andExpect(jsonPath("$.name", is("alex"))); - verify(service, VerificationModeFactory.times(1)).save(Mockito.any()); - reset(service); - } - - @Test - public void givenEmployees_whenGetEmployees_thenReturnJsonArray() throws Exception { - Employee alex = new Employee("alex"); - Employee john = new Employee("john"); - Employee bob = new Employee("bob"); - - List allEmployees = Arrays.asList(alex, john, bob); - - given(service.getAllEmployees()).willReturn(allEmployees); - - mvc.perform(get("/api/employees").contentType(MediaType.APPLICATION_JSON)).andExpect(status().isOk()).andExpect(jsonPath("$", hasSize(3))).andExpect(jsonPath("$[0].name", is(alex.getName()))).andExpect(jsonPath("$[1].name", is(john.getName()))) - .andExpect(jsonPath("$[2].name", is(bob.getName()))); - verify(service, VerificationModeFactory.times(1)).getAllEmployees(); - reset(service); - } - -} \ No newline at end of file diff --git a/spring-boot-modules/spring-boot-testing/src/test/java/com/baeldung/boot/testing/EmployeeRepositoryIntegrationTest.java b/spring-boot-modules/spring-boot-testing/src/test/java/com/baeldung/boot/testing/EmployeeRepositoryIntegrationTest.java deleted file mode 100644 index b3a7316764..0000000000 --- a/spring-boot-modules/spring-boot-testing/src/test/java/com/baeldung/boot/testing/EmployeeRepositoryIntegrationTest.java +++ /dev/null @@ -1,72 +0,0 @@ -package com.baeldung.boot.testing; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest; -import org.springframework.boot.test.autoconfigure.orm.jpa.TestEntityManager; -import org.springframework.test.context.junit4.SpringRunner; - -import com.baeldung.boot.testing.Employee; -import com.baeldung.boot.testing.EmployeeRepository; - -import java.util.List; - -import static org.assertj.core.api.Assertions.assertThat; - -@RunWith(SpringRunner.class) -@DataJpaTest -public class EmployeeRepositoryIntegrationTest { - - @Autowired - private TestEntityManager entityManager; - - @Autowired - private EmployeeRepository employeeRepository; - - @Test - public void whenFindByName_thenReturnEmployee() { - Employee alex = new Employee("alex"); - entityManager.persistAndFlush(alex); - - Employee found = employeeRepository.findByName(alex.getName()); - assertThat(found.getName()).isEqualTo(alex.getName()); - } - - @Test - public void whenInvalidName_thenReturnNull() { - Employee fromDb = employeeRepository.findByName("doesNotExist"); - assertThat(fromDb).isNull(); - } - - @Test - public void whenFindById_thenReturnEmployee() { - Employee emp = new Employee("test"); - entityManager.persistAndFlush(emp); - - Employee fromDb = employeeRepository.findById(emp.getId()).orElse(null); - assertThat(fromDb.getName()).isEqualTo(emp.getName()); - } - - @Test - public void whenInvalidId_thenReturnNull() { - Employee fromDb = employeeRepository.findById(-11l).orElse(null); - assertThat(fromDb).isNull(); - } - - @Test - public void givenSetOfEmployees_whenFindAll_thenReturnAllEmployees() { - Employee alex = new Employee("alex"); - Employee ron = new Employee("ron"); - Employee bob = new Employee("bob"); - - entityManager.persist(alex); - entityManager.persist(bob); - entityManager.persist(ron); - entityManager.flush(); - - List allEmployees = employeeRepository.findAll(); - - assertThat(allEmployees).hasSize(3).extracting(Employee::getName).containsOnly(alex.getName(), ron.getName(), bob.getName()); - } -} diff --git a/spring-boot-modules/spring-boot-testing/src/test/java/com/baeldung/boot/testing/EmployeeRestControllerIntegrationTest.java b/spring-boot-modules/spring-boot-testing/src/test/java/com/baeldung/boot/testing/EmployeeRestControllerIntegrationTest.java deleted file mode 100644 index d13fcd79aa..0000000000 --- a/spring-boot-modules/spring-boot-testing/src/test/java/com/baeldung/boot/testing/EmployeeRestControllerIntegrationTest.java +++ /dev/null @@ -1,86 +0,0 @@ -package com.baeldung.boot.testing; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.hamcrest.CoreMatchers.is; -import static org.hamcrest.Matchers.greaterThanOrEqualTo; -import static org.hamcrest.Matchers.hasSize; -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; -import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; - -import java.io.IOException; -import java.util.List; - -import org.junit.After; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.autoconfigure.EnableAutoConfiguration; -import org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration; -import org.springframework.boot.test.autoconfigure.jdbc.AutoConfigureTestDatabase; -import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; -import org.springframework.http.MediaType; -import org.springframework.test.context.junit4.SpringRunner; -import org.springframework.test.web.servlet.MockMvc; - -import com.baeldung.boot.Application; -import com.baeldung.boot.testing.Employee; -import com.baeldung.boot.testing.EmployeeRepository; - -@RunWith(SpringRunner.class) -@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT, classes = Application.class) -@AutoConfigureMockMvc -@EnableAutoConfiguration(exclude=SecurityAutoConfiguration.class) -// @TestPropertySource(locations = "classpath:application-integrationtest.properties") -@AutoConfigureTestDatabase -public class EmployeeRestControllerIntegrationTest { - - @Autowired - private MockMvc mvc; - - @Autowired - private EmployeeRepository repository; - - @After - public void resetDb() { - repository.deleteAll(); - } - - @Test - public void whenValidInput_thenCreateEmployee() throws IOException, Exception { - Employee bob = new Employee("bob"); - mvc.perform(post("/api/employees").contentType(MediaType.APPLICATION_JSON).content(JsonUtil.toJson(bob))); - - List found = repository.findAll(); - assertThat(found).extracting(Employee::getName).containsOnly("bob"); - } - - @Test - public void givenEmployees_whenGetEmployees_thenStatus200() throws Exception { - createTestEmployee("bob"); - createTestEmployee("alex"); - - // @formatter:off - mvc.perform(get("/api/employees").contentType(MediaType.APPLICATION_JSON)) - .andDo(print()) - .andExpect(status().isOk()) - .andExpect(content().contentTypeCompatibleWith(MediaType.APPLICATION_JSON)) - .andExpect(jsonPath("$", hasSize(greaterThanOrEqualTo(2)))) - .andExpect(jsonPath("$[0].name", is("bob"))) - .andExpect(jsonPath("$[1].name", is("alex"))); - // @formatter:on - } - - // - - private void createTestEmployee(String name) { - Employee emp = new Employee(name); - repository.saveAndFlush(emp); - } - -} diff --git a/spring-boot-modules/spring-boot-testing/src/test/java/com/baeldung/boot/testing/EmployeeServiceImplIntegrationTest.java b/spring-boot-modules/spring-boot-testing/src/test/java/com/baeldung/boot/testing/EmployeeServiceImplIntegrationTest.java deleted file mode 100644 index 3176a7c75a..0000000000 --- a/spring-boot-modules/spring-boot-testing/src/test/java/com/baeldung/boot/testing/EmployeeServiceImplIntegrationTest.java +++ /dev/null @@ -1,132 +0,0 @@ -package com.baeldung.boot.testing; - -import static org.assertj.core.api.Assertions.assertThat; - -import java.util.Arrays; -import java.util.List; -import java.util.Optional; - -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.Mockito; -import org.mockito.internal.verification.VerificationModeFactory; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.test.context.TestConfiguration; -import org.springframework.boot.test.mock.mockito.MockBean; -import org.springframework.context.annotation.Bean; -import org.springframework.test.context.junit4.SpringRunner; - -import com.baeldung.boot.testing.Employee; -import com.baeldung.boot.testing.EmployeeRepository; -import com.baeldung.boot.testing.EmployeeService; -import com.baeldung.boot.testing.EmployeeServiceImpl; - -@RunWith(SpringRunner.class) -public class EmployeeServiceImplIntegrationTest { - - @TestConfiguration - static class EmployeeServiceImplTestContextConfiguration { - @Bean - public EmployeeService employeeService() { - return new EmployeeServiceImpl(); - } - } - - @Autowired - private EmployeeService employeeService; - - @MockBean - private EmployeeRepository employeeRepository; - - @Before - public void setUp() { - Employee john = new Employee("john"); - john.setId(11L); - - Employee bob = new Employee("bob"); - Employee alex = new Employee("alex"); - - List allEmployees = Arrays.asList(john, bob, alex); - - Mockito.when(employeeRepository.findByName(john.getName())).thenReturn(john); - Mockito.when(employeeRepository.findByName(alex.getName())).thenReturn(alex); - Mockito.when(employeeRepository.findByName("wrong_name")).thenReturn(null); - Mockito.when(employeeRepository.findById(john.getId())).thenReturn(Optional.of(john)); - Mockito.when(employeeRepository.findAll()).thenReturn(allEmployees); - Mockito.when(employeeRepository.findById(-99L)).thenReturn(Optional.empty()); - } - - @Test - public void whenValidName_thenEmployeeShouldBeFound() { - String name = "alex"; - Employee found = employeeService.getEmployeeByName(name); - - assertThat(found.getName()).isEqualTo(name); - } - - @Test - public void whenInValidName_thenEmployeeShouldNotBeFound() { - Employee fromDb = employeeService.getEmployeeByName("wrong_name"); - assertThat(fromDb).isNull(); - - verifyFindByNameIsCalledOnce("wrong_name"); - } - - @Test - public void whenValidName_thenEmployeeShouldExist() { - boolean doesEmployeeExist = employeeService.exists("john"); - assertThat(doesEmployeeExist).isEqualTo(true); - - verifyFindByNameIsCalledOnce("john"); - } - - @Test - public void whenNonExistingName_thenEmployeeShouldNotExist() { - boolean doesEmployeeExist = employeeService.exists("some_name"); - assertThat(doesEmployeeExist).isEqualTo(false); - - verifyFindByNameIsCalledOnce("some_name"); - } - - @Test - public void whenValidId_thenEmployeeShouldBeFound() { - Employee fromDb = employeeService.getEmployeeById(11L); - assertThat(fromDb.getName()).isEqualTo("john"); - - verifyFindByIdIsCalledOnce(); - } - - @Test - public void whenInValidId_thenEmployeeShouldNotBeFound() { - Employee fromDb = employeeService.getEmployeeById(-99L); - verifyFindByIdIsCalledOnce(); - assertThat(fromDb).isNull(); - } - - @Test - public void given3Employees_whengetAll_thenReturn3Records() { - Employee alex = new Employee("alex"); - Employee john = new Employee("john"); - Employee bob = new Employee("bob"); - - List allEmployees = employeeService.getAllEmployees(); - verifyFindAllEmployeesIsCalledOnce(); - assertThat(allEmployees).hasSize(3).extracting(Employee::getName).contains(alex.getName(), john.getName(), bob.getName()); - } - - private void verifyFindByNameIsCalledOnce(String name) { - Mockito.verify(employeeRepository, VerificationModeFactory.times(1)).findByName(name); - Mockito.reset(employeeRepository); - } - - private void verifyFindByIdIsCalledOnce() { - Mockito.verify(employeeRepository, VerificationModeFactory.times(1)).findById(Mockito.anyLong()); - Mockito.reset(employeeRepository); - } - - private void verifyFindAllEmployeesIsCalledOnce() { - Mockito.verify(employeeRepository, VerificationModeFactory.times(1)).findAll(); - Mockito.reset(employeeRepository); - } -} diff --git a/spring-boot-modules/spring-boot-testing/src/test/java/com/baeldung/boot/testing/JsonUtil.java b/spring-boot-modules/spring-boot-testing/src/test/java/com/baeldung/boot/testing/JsonUtil.java deleted file mode 100644 index 49d018dde8..0000000000 --- a/spring-boot-modules/spring-boot-testing/src/test/java/com/baeldung/boot/testing/JsonUtil.java +++ /dev/null @@ -1,14 +0,0 @@ -package com.baeldung.boot.testing; - -import com.fasterxml.jackson.annotation.JsonInclude; -import com.fasterxml.jackson.databind.ObjectMapper; - -import java.io.IOException; - -class JsonUtil { - static byte[] toJson(Object object) throws IOException { - ObjectMapper mapper = new ObjectMapper(); - mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); - return mapper.writeValueAsBytes(object); - } -} diff --git a/spring-boot-modules/spring-boot-testing/src/test/java/com/baeldung/prevent/commandline/application/runner/execution/LoadSpringContextIntegrationTest.java b/spring-boot-modules/spring-boot-testing/src/test/java/com/baeldung/prevent/commandline/application/runner/execution/LoadSpringContextIntegrationTest.java deleted file mode 100644 index 483c67b7a2..0000000000 --- a/spring-boot-modules/spring-boot-testing/src/test/java/com/baeldung/prevent/commandline/application/runner/execution/LoadSpringContextIntegrationTest.java +++ /dev/null @@ -1,43 +0,0 @@ -package com.baeldung.prevent.commandline.application.runner.execution; - -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.extension.ExtendWith; -import org.springframework.boot.ApplicationRunner; -import org.springframework.boot.CommandLineRunner; -import org.springframework.boot.test.context.ConfigDataApplicationContextInitializer; -import org.springframework.boot.test.mock.mockito.SpyBean; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit.jupiter.SpringExtension; - -import com.baeldung.prevent.commandline.application.runner.execution.ApplicationCommandLineRunnerApp; -import com.baeldung.prevent.commandline.application.runner.execution.TaskService; - -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; - -@ExtendWith(SpringExtension.class) -@ContextConfiguration(classes = { ApplicationCommandLineRunnerApp.class }, - initializers = ConfigDataApplicationContextInitializer.class) -public class LoadSpringContextIntegrationTest { - @SpyBean - TaskService taskService; - - @SpyBean - CommandLineRunner commandLineRunner; - - @SpyBean - ApplicationRunner applicationRunner; - - @Test - void whenContextLoads_thenRunnersDoNotRun() throws Exception { - assertNotNull(taskService); - assertNotNull(commandLineRunner); - assertNotNull(applicationRunner); - - verify(taskService, times(0)).execute(any()); - verify(commandLineRunner, times(0)).run(any()); - verify(applicationRunner, times(0)).run(any()); - } -} diff --git a/spring-boot-modules/spring-boot-testing/src/test/java/com/baeldung/prevent/commandline/application/runner/execution/RunApplicationIntegrationTest.java b/spring-boot-modules/spring-boot-testing/src/test/java/com/baeldung/prevent/commandline/application/runner/execution/RunApplicationIntegrationTest.java deleted file mode 100644 index 26a7339f1d..0000000000 --- a/spring-boot-modules/spring-boot-testing/src/test/java/com/baeldung/prevent/commandline/application/runner/execution/RunApplicationIntegrationTest.java +++ /dev/null @@ -1,26 +0,0 @@ -package com.baeldung.prevent.commandline.application.runner.execution; - -import org.junit.jupiter.api.Test; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.boot.test.mock.mockito.SpyBean; - -import com.baeldung.prevent.commandline.application.runner.execution.ApplicationRunnerTaskExecutor; -import com.baeldung.prevent.commandline.application.runner.execution.CommandLineTaskExecutor; - -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; - -@SpringBootTest -class RunApplicationIntegrationTest { - @SpyBean - ApplicationRunnerTaskExecutor applicationRunnerTaskExecutor; - @SpyBean - CommandLineTaskExecutor commandLineTaskExecutor; - - @Test - void whenContextLoads_thenRunnersRun() throws Exception { - verify(applicationRunnerTaskExecutor, times(1)).run(any()); - verify(commandLineTaskExecutor, times(1)).run(any()); - } -} diff --git a/spring-boot-modules/spring-boot-testing/src/test/java/com/baeldung/prevent/commandline/application/runner/execution/RunApplicationWithTestProfileIntegrationTest.java b/spring-boot-modules/spring-boot-testing/src/test/java/com/baeldung/prevent/commandline/application/runner/execution/RunApplicationWithTestProfileIntegrationTest.java deleted file mode 100644 index 333cd2ab91..0000000000 --- a/spring-boot-modules/spring-boot-testing/src/test/java/com/baeldung/prevent/commandline/application/runner/execution/RunApplicationWithTestProfileIntegrationTest.java +++ /dev/null @@ -1,33 +0,0 @@ -package com.baeldung.prevent.commandline.application.runner.execution; - -import org.junit.jupiter.api.Test; -import org.springframework.beans.factory.NoSuchBeanDefinitionException; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.context.ApplicationContext; -import org.springframework.test.context.ActiveProfiles; - -import com.baeldung.prevent.commandline.application.runner.execution.ApplicationRunnerTaskExecutor; -import com.baeldung.prevent.commandline.application.runner.execution.CommandLineTaskExecutor; -import com.baeldung.prevent.commandline.application.runner.execution.TaskService; - -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertThrows; - -@ActiveProfiles("test") -@SpringBootTest -class RunApplicationWithTestProfileIntegrationTest { - @Autowired - private ApplicationContext context; - - @Test - void whenContextLoads_thenRunnersAreNotLoaded() { - assertNotNull(context.getBean(TaskService.class)); - assertThrows(NoSuchBeanDefinitionException.class, - () -> context.getBean(CommandLineTaskExecutor.class), - "CommandLineRunner should not be loaded during this integration test"); - assertThrows(NoSuchBeanDefinitionException.class, - () -> context.getBean(ApplicationRunnerTaskExecutor.class), - "ApplicationRunner should not be loaded during this integration test"); - } -} diff --git a/spring-boot-modules/spring-boot-testing/src/test/java/com/baeldung/prevent/commandline/application/runner/execution/RunApplicationWithTestPropertiesIntegrationTest.java b/spring-boot-modules/spring-boot-testing/src/test/java/com/baeldung/prevent/commandline/application/runner/execution/RunApplicationWithTestPropertiesIntegrationTest.java deleted file mode 100644 index 264a06a41e..0000000000 --- a/spring-boot-modules/spring-boot-testing/src/test/java/com/baeldung/prevent/commandline/application/runner/execution/RunApplicationWithTestPropertiesIntegrationTest.java +++ /dev/null @@ -1,32 +0,0 @@ -package com.baeldung.prevent.commandline.application.runner.execution; - -import static org.junit.jupiter.api.Assertions.*; - -import org.junit.jupiter.api.Test; -import org.springframework.beans.factory.NoSuchBeanDefinitionException; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.context.ApplicationContext; - -import com.baeldung.prevent.commandline.application.runner.execution.ApplicationRunnerTaskExecutor; -import com.baeldung.prevent.commandline.application.runner.execution.CommandLineTaskExecutor; -import com.baeldung.prevent.commandline.application.runner.execution.TaskService; - -@SpringBootTest(properties = { - "command.line.runner.enabled=false", - "application.runner.enabled=false" }) -class RunApplicationWithTestPropertiesIntegrationTest { - @Autowired - private ApplicationContext context; - - @Test - void whenContextLoads_thenRunnersAreNotLoaded() { - assertNotNull(context.getBean(TaskService.class)); - assertThrows(NoSuchBeanDefinitionException.class, - () -> context.getBean(CommandLineTaskExecutor.class), - "CommandLineRunner should not be loaded during this integration test"); - assertThrows(NoSuchBeanDefinitionException.class, - () -> context.getBean(ApplicationRunnerTaskExecutor.class), - "ApplicationRunner should not be loaded during this integration test"); - } -} diff --git a/spring-boot-modules/spring-boot-testing/src/test/resources/application-integrationtest.properties b/spring-boot-modules/spring-boot-testing/src/test/resources/application-integrationtest.properties deleted file mode 100644 index bcd03226d3..0000000000 --- a/spring-boot-modules/spring-boot-testing/src/test/resources/application-integrationtest.properties +++ /dev/null @@ -1,4 +0,0 @@ -spring.datasource.url=jdbc:mysql://localhost:3306/employee_int_test -spring.datasource.username=root -spring.datasource.password=root - diff --git a/spring-boot-modules/spring-boot-testing/src/test/resources/application-test.properties b/spring-boot-modules/spring-boot-testing/src/test/resources/application-test.properties deleted file mode 100644 index a2c9b6d480..0000000000 --- a/spring-boot-modules/spring-boot-testing/src/test/resources/application-test.properties +++ /dev/null @@ -1,2 +0,0 @@ -# test properties -spring.autoconfigure.exclude=org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration \ No newline at end of file diff --git a/spring-boot-modules/spring-boot-testing/src/test/resources/application.properties b/spring-boot-modules/spring-boot-testing/src/test/resources/application.properties deleted file mode 100644 index 1810c7b1eb..0000000000 --- a/spring-boot-modules/spring-boot-testing/src/test/resources/application.properties +++ /dev/null @@ -1,8 +0,0 @@ -#embedded redis -spring.redis.host= localhost -spring.redis.port= 6370 -# security -spring.security.user.name=john -spring.security.user.password=123 - -spring.main.allow-bean-definition-overriding=true \ No newline at end of file diff --git a/spring-boot-modules/spring-boot-testing/src/test/resources/application.yml b/spring-boot-modules/spring-boot-testing/src/test/resources/application.yml deleted file mode 100644 index 056b5baffc..0000000000 --- a/spring-boot-modules/spring-boot-testing/src/test/resources/application.yml +++ /dev/null @@ -1,19 +0,0 @@ -spring: - config: - activate: - on-profile: test -server: - address: - ip: 192.168.0.4 - resources_path: - imgs: /etc/test/imgs ---- -spring: - config: - activate: - on-profile: dev -server: - address: - ip: 192.168.0.5 - resources_path: - imgs: /etc/dev/imgs \ No newline at end of file diff --git a/spring-boot-modules/spring-boot-testing/src/test/resources/logback-test.xml b/spring-boot-modules/spring-boot-testing/src/test/resources/logback-test.xml deleted file mode 100644 index 9553dcad41..0000000000 --- a/spring-boot-modules/spring-boot-testing/src/test/resources/logback-test.xml +++ /dev/null @@ -1,12 +0,0 @@ - - - - - %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n - - - - - - - diff --git a/spring-boot-modules/spring-boot-testing/src/test/resources/property-validation-test.properties b/spring-boot-modules/spring-boot-testing/src/test/resources/property-validation-test.properties deleted file mode 100644 index 6b4c881dc0..0000000000 --- a/spring-boot-modules/spring-boot-testing/src/test/resources/property-validation-test.properties +++ /dev/null @@ -1,4 +0,0 @@ -validate.propertiesMap.first=prop1 -validate.propertiesMap.second=prop2 - -validate.mail_config.address=user1@test \ No newline at end of file diff --git a/spring-boot-modules/spring-boot-testing/src/test/resources/server-config-test.properties b/spring-boot-modules/spring-boot-testing/src/test/resources/server-config-test.properties deleted file mode 100644 index 62b23ed1d6..0000000000 --- a/spring-boot-modules/spring-boot-testing/src/test/resources/server-config-test.properties +++ /dev/null @@ -1,6 +0,0 @@ -server.address.ip=192.168.0.1 -server.resources_path.imgs=/root/imgs - -# default config -server.default.address.ip=192.168.0.2 -server.default.resources_path.imgs=/root/def/imgs \ No newline at end of file diff --git a/spring-boot-modules/spring-boot-testing/src/test/resources/spring-conversion-test.properties b/spring-boot-modules/spring-boot-testing/src/test/resources/spring-conversion-test.properties deleted file mode 100644 index 87444cee10..0000000000 --- a/spring-boot-modules/spring-boot-testing/src/test/resources/spring-conversion-test.properties +++ /dev/null @@ -1,10 +0,0 @@ -# bandwidth -server.upload_speed=500MB -server.download_speed=10 - -# backup date -server.backup_day=1d -server.backup_hour=8 - -# custom converter -server.credentials=user,123 \ No newline at end of file diff --git a/spring-remoting-modules-3/README.md b/spring-remoting-modules-3/README.md deleted file mode 100644 index 91db561f83..0000000000 --- a/spring-remoting-modules-3/README.md +++ /dev/null @@ -1,13 +0,0 @@ -## Spring Remoting - -This module contains articles about Spring Remoting - - -### Overview -This Maven project contains the Java source code for various modules used in the Spring Remoting series of articles. - -### Building the Project -You can build the project using Maven inside your IDE or from the command line: -``` -mvn clean install -``` diff --git a/spring-remoting-modules-3/pom.xml b/spring-remoting-modules-3/pom.xml deleted file mode 100644 index ea3e6e70f7..0000000000 --- a/spring-remoting-modules-3/pom.xml +++ /dev/null @@ -1,53 +0,0 @@ - - - 4.0.0 - - spring-remoting-modules-3 - 1.0-SNAPSHOT - spring-remoting-modules-3 - pom - Parent for all projects related to Spring Remoting, except remoting-hessian-burlap - - - com.ossez - parent-boot-3 - 0.0.1-SNAPSHOT - parent-boot-3 - - - - remoting-jms-artemis - - - - - - - ${project.groupId} - api - ${project.version} - - - - - - - - org.apache.maven.plugins - maven-compiler-plugin - ${maven-compiler-plugin.version} - - ${maven.compiler.source} - ${maven.compiler.target} - - - - - - 17 - 17 - - - \ No newline at end of file diff --git a/spring-remoting-modules-3/remoting-jms-artemis/.idea/.gitignore b/spring-remoting-modules-3/remoting-jms-artemis/.idea/.gitignore deleted file mode 100644 index 0a8642fac0..0000000000 --- a/spring-remoting-modules-3/remoting-jms-artemis/.idea/.gitignore +++ /dev/null @@ -1,10 +0,0 @@ -# Default ignored files -/shelf/ -/workspace.xml -# Editor-based HTTP Client requests -/httpRequests/ -# Datasource local storage ignored files -/dataSources/ -/dataSources.local.xml -# Zeppelin ignored files -/ZeppelinRemoteNotebooks/ diff --git a/spring-remoting-modules-3/remoting-jms-artemis/.idea/checkstyle-idea.xml b/spring-remoting-modules-3/remoting-jms-artemis/.idea/checkstyle-idea.xml deleted file mode 100644 index f0c49846ff..0000000000 --- a/spring-remoting-modules-3/remoting-jms-artemis/.idea/checkstyle-idea.xml +++ /dev/null @@ -1,16 +0,0 @@ - - - - 10.12.2 - JavaOnly - true - - - \ No newline at end of file diff --git a/spring-remoting-modules-3/remoting-jms-artemis/.idea/compiler.xml b/spring-remoting-modules-3/remoting-jms-artemis/.idea/compiler.xml deleted file mode 100644 index 4352c98059..0000000000 --- a/spring-remoting-modules-3/remoting-jms-artemis/.idea/compiler.xml +++ /dev/null @@ -1,15 +0,0 @@ - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/spring-remoting-modules-3/remoting-jms-artemis/.idea/encodings.xml b/spring-remoting-modules-3/remoting-jms-artemis/.idea/encodings.xml deleted file mode 100644 index 56c6c7bcd3..0000000000 --- a/spring-remoting-modules-3/remoting-jms-artemis/.idea/encodings.xml +++ /dev/null @@ -1,11 +0,0 @@ - - - - - - - - - - - \ No newline at end of file diff --git a/spring-remoting-modules-3/remoting-jms-artemis/.idea/jarRepositories.xml b/spring-remoting-modules-3/remoting-jms-artemis/.idea/jarRepositories.xml deleted file mode 100644 index 1067e4c6b5..0000000000 --- a/spring-remoting-modules-3/remoting-jms-artemis/.idea/jarRepositories.xml +++ /dev/null @@ -1,30 +0,0 @@ - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/spring-remoting-modules-3/remoting-jms-artemis/.idea/jpa-buddy.xml b/spring-remoting-modules-3/remoting-jms-artemis/.idea/jpa-buddy.xml deleted file mode 100644 index 898e07a675..0000000000 --- a/spring-remoting-modules-3/remoting-jms-artemis/.idea/jpa-buddy.xml +++ /dev/null @@ -1,7 +0,0 @@ - - - - - \ No newline at end of file diff --git a/spring-remoting-modules-3/remoting-jms-artemis/.idea/misc.xml b/spring-remoting-modules-3/remoting-jms-artemis/.idea/misc.xml deleted file mode 100644 index a2eb346bb8..0000000000 --- a/spring-remoting-modules-3/remoting-jms-artemis/.idea/misc.xml +++ /dev/null @@ -1,18 +0,0 @@ - - - - - - - - - - - - - \ No newline at end of file diff --git a/spring-remoting-modules-3/remoting-jms-artemis/.idea/uiDesigner.xml b/spring-remoting-modules-3/remoting-jms-artemis/.idea/uiDesigner.xml deleted file mode 100644 index 2b63946d5b..0000000000 --- a/spring-remoting-modules-3/remoting-jms-artemis/.idea/uiDesigner.xml +++ /dev/null @@ -1,124 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/spring-remoting-modules-3/remoting-jms-artemis/.idea/vcs.xml b/spring-remoting-modules-3/remoting-jms-artemis/.idea/vcs.xml deleted file mode 100644 index b2bdec2d71..0000000000 --- a/spring-remoting-modules-3/remoting-jms-artemis/.idea/vcs.xml +++ /dev/null @@ -1,6 +0,0 @@ - - - - - - \ No newline at end of file diff --git a/spring-remoting-modules-3/remoting-jms-artemis/README.md b/spring-remoting-modules-3/remoting-jms-artemis/README.md deleted file mode 100644 index cf86f4adc4..0000000000 --- a/spring-remoting-modules-3/remoting-jms-artemis/README.md +++ /dev/null @@ -1,8 +0,0 @@ -## Remoting JMS Artemis - -This module contains articles about Spring Remoting with Java Message Service (JMS) - -### Relevant Articles: - -- [Spring Remoting with JMS and ActiveMQ](https://www.baeldung.com/spring-remoting-jms) - diff --git a/spring-remoting-modules-3/remoting-jms-artemis/pom.xml b/spring-remoting-modules-3/remoting-jms-artemis/pom.xml deleted file mode 100644 index 0e06f402cf..0000000000 --- a/spring-remoting-modules-3/remoting-jms-artemis/pom.xml +++ /dev/null @@ -1,21 +0,0 @@ - - - 4.0.0 - remoting-jms-artemis - remoting-jms-artemis - pom - - - com.ossez - spring-remoting-modules-3 - 1.0-SNAPSHOT - - - - remoting-jms-artemis-client - remoting-jms-artemis-server - - - \ No newline at end of file diff --git a/spring-remoting-modules-3/remoting-jms-artemis/remoting-jms-artemis-client/pom.xml b/spring-remoting-modules-3/remoting-jms-artemis/remoting-jms-artemis-client/pom.xml deleted file mode 100644 index d0d7cd88bb..0000000000 --- a/spring-remoting-modules-3/remoting-jms-artemis/remoting-jms-artemis-client/pom.xml +++ /dev/null @@ -1,32 +0,0 @@ - - - 4.0.0 - remoting-jms-artemis-client - remoting-jms-client - - - com.ossez - remoting-jms-artemis - 1.0-SNAPSHOT - - - - - org.springframework.boot - spring-boot-starter-artemis - - - org.springframework.boot - spring-boot-starter-tomcat - - - - - org.springframework.boot - spring-boot-autoconfigure - - - - \ No newline at end of file diff --git a/spring-remoting-modules-3/remoting-jms-artemis/remoting-jms-artemis-client/src/main/java/com/ossez/artemis/client/JmsArtemisClientApplication.java b/spring-remoting-modules-3/remoting-jms-artemis/remoting-jms-artemis-client/src/main/java/com/ossez/artemis/client/JmsArtemisClientApplication.java deleted file mode 100644 index 7e6013b88e..0000000000 --- a/spring-remoting-modules-3/remoting-jms-artemis/remoting-jms-artemis-client/src/main/java/com/ossez/artemis/client/JmsArtemisClientApplication.java +++ /dev/null @@ -1,23 +0,0 @@ -package com.ossez.artemis.client; - - -import org.springframework.boot.SpringApplication; -import org.springframework.boot.autoconfigure.SpringBootApplication; - -/** - * JMS Message Producer Application - * - * @author YuCheng Hu - */ - - -@SpringBootApplication -public class JmsArtemisClientApplication { - - public static void main(String[] args) { - JmsProducer jmsProducer = SpringApplication.run(JmsArtemisClientApplication.class, args).getBean(JmsProducer.class); - jmsProducer.send("xxxddx");; - - } - -} diff --git a/spring-remoting-modules-3/remoting-jms-artemis/remoting-jms-artemis-client/src/main/java/com/ossez/artemis/client/JmsProducer.java b/spring-remoting-modules-3/remoting-jms-artemis/remoting-jms-artemis-client/src/main/java/com/ossez/artemis/client/JmsProducer.java deleted file mode 100644 index 4b38e380d7..0000000000 --- a/spring-remoting-modules-3/remoting-jms-artemis/remoting-jms-artemis-client/src/main/java/com/ossez/artemis/client/JmsProducer.java +++ /dev/null @@ -1,23 +0,0 @@ -package com.ossez.artemis.client; - -import org.springframework.jms.core.JmsTemplate; -import org.springframework.stereotype.Component; - -/** - * JmsProducer - * @author YuCheng Hu - */ -@Component -public class JmsProducer { - - private final JmsTemplate jmsTemplate; - - public JmsProducer(JmsTemplate jmsTemplate) { - this.jmsTemplate = jmsTemplate; - } - - public void send(String message) { - jmsTemplate.convertAndSend("remotingQueue", message); - } - -} diff --git a/spring-remoting-modules-3/remoting-jms-artemis/remoting-jms-artemis-client/src/main/java/com/ossez/artemis/client/controller/MQController.java b/spring-remoting-modules-3/remoting-jms-artemis/remoting-jms-artemis-client/src/main/java/com/ossez/artemis/client/controller/MQController.java deleted file mode 100644 index 4a490ed6c1..0000000000 --- a/spring-remoting-modules-3/remoting-jms-artemis/remoting-jms-artemis-client/src/main/java/com/ossez/artemis/client/controller/MQController.java +++ /dev/null @@ -1,30 +0,0 @@ -package com.ossez.artemis.client.controller; - -import com.ossez.artemis.client.JmsProducer; -import lombok.RequiredArgsConstructor; - -import org.springframework.web.bind.annotation.*; - -/** - * 承包商相关 API - * - * @author ForteScarlet - */ -@RestController -@RequiredArgsConstructor -@RequestMapping(MQController.BASE_URL) -public class MQController { - - protected static final String BASE_URL = "/mq"; - - private final JmsProducer jmsProducer; - - @PostMapping("/send") - public String sendToMQ(@RequestBody String request) { - jmsProducer.send(request); - - return "Send"; - } - - -} diff --git a/spring-remoting-modules-3/remoting-jms-artemis/remoting-jms-artemis-client/src/main/resources/application.properties b/spring-remoting-modules-3/remoting-jms-artemis/remoting-jms-artemis-client/src/main/resources/application.properties deleted file mode 100644 index 6a7307708b..0000000000 --- a/spring-remoting-modules-3/remoting-jms-artemis/remoting-jms-artemis-client/src/main/resources/application.properties +++ /dev/null @@ -1,6 +0,0 @@ -spring.artemis.mode=native -spring.artemis.broker-url=tcp://nas1120:61616 -#spring.artemis.host=nas1120 -#spring.artemis.port=61616 -spring.artemis.user=artemis -spring.artemis.password=artemis \ No newline at end of file diff --git a/spring-remoting-modules-3/remoting-jms-artemis/remoting-jms-artemis-client/src/main/resources/logback.xml b/spring-remoting-modules-3/remoting-jms-artemis/remoting-jms-artemis-client/src/main/resources/logback.xml deleted file mode 100644 index 35be7e9f22..0000000000 --- a/spring-remoting-modules-3/remoting-jms-artemis/remoting-jms-artemis-client/src/main/resources/logback.xml +++ /dev/null @@ -1,23 +0,0 @@ - - - - - - - %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n - - - - %d{HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n - - - - - - - - - - - - \ No newline at end of file diff --git a/spring-remoting-modules-3/remoting-jms-artemis/remoting-jms-artemis-client/src/test/java/com/ossez/artemis/SpringContextTest.java b/spring-remoting-modules-3/remoting-jms-artemis/remoting-jms-artemis-client/src/test/java/com/ossez/artemis/SpringContextTest.java deleted file mode 100644 index 149ff0ab41..0000000000 --- a/spring-remoting-modules-3/remoting-jms-artemis/remoting-jms-artemis-client/src/test/java/com/ossez/artemis/SpringContextTest.java +++ /dev/null @@ -1,17 +0,0 @@ -package com.ossez.artemis; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.test.context.junit4.SpringRunner; - -import com.ossez.artemis.client.JmsArtemisClientApplication; - -@SpringBootTest(classes = JmsArtemisClientApplication.class) -@RunWith(SpringRunner.class) -public class SpringContextTest { - - @Test - public void whenSpringContextIsBootstrapped_thenNoExceptions() { - } -} diff --git a/spring-remoting-modules-3/remoting-jms-artemis/remoting-jms-artemis-server/pom.xml b/spring-remoting-modules-3/remoting-jms-artemis/remoting-jms-artemis-server/pom.xml deleted file mode 100644 index 37f1ce4010..0000000000 --- a/spring-remoting-modules-3/remoting-jms-artemis/remoting-jms-artemis-server/pom.xml +++ /dev/null @@ -1,28 +0,0 @@ - - - 4.0.0 - remoting-jms-artemis-server - remoting-jms-server - - - com.ossez - remoting-jms-artemis - 1.0-SNAPSHOT - - - - - org.springframework.boot - spring-boot-starter-artemis - - - org.springframework.boot - spring-boot-starter-tomcat - - - - - - \ No newline at end of file diff --git a/spring-remoting-modules-3/remoting-jms-artemis/remoting-jms-artemis-server/src/main/java/com/ossez/artemis/server/JmsArtemisServerApplication.java b/spring-remoting-modules-3/remoting-jms-artemis/remoting-jms-artemis-server/src/main/java/com/ossez/artemis/server/JmsArtemisServerApplication.java deleted file mode 100644 index 9a8ba8a857..0000000000 --- a/spring-remoting-modules-3/remoting-jms-artemis/remoting-jms-artemis-server/src/main/java/com/ossez/artemis/server/JmsArtemisServerApplication.java +++ /dev/null @@ -1,25 +0,0 @@ -package com.ossez.artemis.server; - -import org.springframework.boot.SpringApplication; -import org.springframework.boot.autoconfigure.SpringBootApplication; -import org.springframework.jms.annotation.JmsListener; - -/** - * JMS Message Consumer Application - * - * @author YuCheng Hu - */ -@SpringBootApplication -public class JmsArtemisServerApplication { - - - @JmsListener(destination = "remotingQueue") - public void receive(String message) { - System.out.println("Received message: " + message); - } - - public static void main(String[] args) { - SpringApplication.run(JmsArtemisServerApplication.class, args); - } - -} diff --git a/spring-remoting-modules-3/remoting-jms-artemis/remoting-jms-artemis-server/src/main/resources/application.properties b/spring-remoting-modules-3/remoting-jms-artemis/remoting-jms-artemis-server/src/main/resources/application.properties deleted file mode 100644 index 1992e49a35..0000000000 --- a/spring-remoting-modules-3/remoting-jms-artemis/remoting-jms-artemis-server/src/main/resources/application.properties +++ /dev/null @@ -1,13 +0,0 @@ -spring.artemis.mode=native -spring.artemis.broker-url=tcp://nas1120:61616 -spring.artemis.user=artemis -spring.artemis.password=artemis -#spring.activemq.packages.trusted=org.springframework.remoting.support,java.lang,com.baeldung.api - -# Logging -logging.pattern.console=%d{mm:ss.SSS} %-5p [%-31t] [%-54logger{0}] %marker%m%ex{full} - %logger - %F:%L%n -logging.level.root=WARN -logging.level.org.apache.activemq=DEBUG -logging.level.org.springframework.jms=DEBUG -logging.level.org.springframework=WARN - diff --git a/spring-remoting-modules-3/remoting-jms-artemis/remoting-jms-artemis-server/src/main/resources/logback.xml b/spring-remoting-modules-3/remoting-jms-artemis/remoting-jms-artemis-server/src/main/resources/logback.xml deleted file mode 100644 index 7d900d8ea8..0000000000 --- a/spring-remoting-modules-3/remoting-jms-artemis/remoting-jms-artemis-server/src/main/resources/logback.xml +++ /dev/null @@ -1,13 +0,0 @@ - - - - - %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n - - - - - - - - \ No newline at end of file diff --git a/spring-remoting-modules-3/remoting-jms-artemis/remoting-jms-artemis-server/src/test/java/com/ossez/artemis/SpringContextLiveTest.java b/spring-remoting-modules-3/remoting-jms-artemis/remoting-jms-artemis-server/src/test/java/com/ossez/artemis/SpringContextLiveTest.java deleted file mode 100644 index c87c582465..0000000000 --- a/spring-remoting-modules-3/remoting-jms-artemis/remoting-jms-artemis-server/src/test/java/com/ossez/artemis/SpringContextLiveTest.java +++ /dev/null @@ -1,23 +0,0 @@ -package com.ossez.artemis; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.test.context.junit4.SpringRunner; - -import com.ossez.artemis.server.JmsArtemisServerApplication; - -/** - * This Live Test requires: - * * the `com.baeldung:remoting-http-api:jar:1.0-SNAPSHOT` artifact accessible. For that we can run `mvn clean install` in the 'spring-remoting/remoting-http/remoting-http-api' module. - * * an ActiveMQ instance running (e.g. `docker run -p 61616:61616 -p 8161:8161 --name bael-activemq rmohr/activemq`) - * - */ -@SpringBootTest(classes = JmsArtemisServerApplication.class) -@RunWith(SpringRunner.class) -public class SpringContextLiveTest { - - @Test - public void whenSpringContextIsBootstrapped_thenNoExceptions() { - } -} diff --git a/spring-remoting-modules/.idea/.gitignore b/spring-remoting-modules/.idea/.gitignore deleted file mode 100644 index 0a8642fac0..0000000000 --- a/spring-remoting-modules/.idea/.gitignore +++ /dev/null @@ -1,10 +0,0 @@ -# Default ignored files -/shelf/ -/workspace.xml -# Editor-based HTTP Client requests -/httpRequests/ -# Datasource local storage ignored files -/dataSources/ -/dataSources.local.xml -# Zeppelin ignored files -/ZeppelinRemoteNotebooks/ diff --git a/spring-remoting-modules/.idea/checkstyle-idea.xml b/spring-remoting-modules/.idea/checkstyle-idea.xml deleted file mode 100644 index f0c49846ff..0000000000 --- a/spring-remoting-modules/.idea/checkstyle-idea.xml +++ /dev/null @@ -1,16 +0,0 @@ - - - - 10.12.2 - JavaOnly - true - - - \ No newline at end of file diff --git a/spring-remoting-modules/.idea/compiler.xml b/spring-remoting-modules/.idea/compiler.xml deleted file mode 100644 index 92b98354bd..0000000000 --- a/spring-remoting-modules/.idea/compiler.xml +++ /dev/null @@ -1,17 +0,0 @@ - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/spring-remoting-modules/.idea/encodings.xml b/spring-remoting-modules/.idea/encodings.xml deleted file mode 100644 index 9635c68aa3..0000000000 --- a/spring-remoting-modules/.idea/encodings.xml +++ /dev/null @@ -1,21 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/spring-remoting-modules/.idea/jarRepositories.xml b/spring-remoting-modules/.idea/jarRepositories.xml deleted file mode 100644 index 1067e4c6b5..0000000000 --- a/spring-remoting-modules/.idea/jarRepositories.xml +++ /dev/null @@ -1,30 +0,0 @@ - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/spring-remoting-modules/.idea/jpa-buddy.xml b/spring-remoting-modules/.idea/jpa-buddy.xml deleted file mode 100644 index 898e07a675..0000000000 --- a/spring-remoting-modules/.idea/jpa-buddy.xml +++ /dev/null @@ -1,7 +0,0 @@ - - - - - \ No newline at end of file diff --git a/spring-remoting-modules/.idea/misc.xml b/spring-remoting-modules/.idea/misc.xml deleted file mode 100644 index a2eb346bb8..0000000000 --- a/spring-remoting-modules/.idea/misc.xml +++ /dev/null @@ -1,18 +0,0 @@ - - - - - - - - - - - - - \ No newline at end of file diff --git a/spring-remoting-modules/.idea/vcs.xml b/spring-remoting-modules/.idea/vcs.xml deleted file mode 100644 index 6c0b863585..0000000000 --- a/spring-remoting-modules/.idea/vcs.xml +++ /dev/null @@ -1,6 +0,0 @@ - - - - - - \ No newline at end of file diff --git a/spring-remoting-modules/README.md b/spring-remoting-modules/README.md deleted file mode 100644 index 91db561f83..0000000000 --- a/spring-remoting-modules/README.md +++ /dev/null @@ -1,13 +0,0 @@ -## Spring Remoting - -This module contains articles about Spring Remoting - - -### Overview -This Maven project contains the Java source code for various modules used in the Spring Remoting series of articles. - -### Building the Project -You can build the project using Maven inside your IDE or from the command line: -``` -mvn clean install -``` diff --git a/spring-remoting-modules/pom.xml b/spring-remoting-modules/pom.xml deleted file mode 100644 index 480e7db21d..0000000000 --- a/spring-remoting-modules/pom.xml +++ /dev/null @@ -1,58 +0,0 @@ - - - 4.0.0 - spring-remoting-modules - 1.0-SNAPSHOT - spring-remoting-modules - pom - Parent for all projects related to Spring Remoting, except remoting-hessian-burlap - - - - - com.ossez - parent-boot-2 - 0.0.2-SNAPSHOT - parent-boot-2 - - - - - remoting-http - - remoting-jms - - - - - - - - ${project.groupId} - api - ${project.version} - - - - - - - - org.apache.maven.plugins - maven-compiler-plugin - ${maven-compiler-plugin.version} - - ${maven.compiler.source} - ${maven.compiler.target} - - - - - - 11 - 11 - - - \ No newline at end of file diff --git a/spring-remoting-modules/remoting-amqp/README.md b/spring-remoting-modules/remoting-amqp/README.md deleted file mode 100644 index b4367f0cd0..0000000000 --- a/spring-remoting-modules/remoting-amqp/README.md +++ /dev/null @@ -1,3 +0,0 @@ -### Relevant Articles - -- [Spring Remoting with AMQP](https://www.baeldung.com/spring-remoting-amqp) diff --git a/spring-remoting-modules/remoting-amqp/pom.xml b/spring-remoting-modules/remoting-amqp/pom.xml deleted file mode 100644 index 7e1aa83cc5..0000000000 --- a/spring-remoting-modules/remoting-amqp/pom.xml +++ /dev/null @@ -1,21 +0,0 @@ - - - 4.0.0 - remoting-amqp - remoting-amqp - pom - - - com.baeldung - spring-remoting-modules - 1.0-SNAPSHOT - - - - remoting-amqp-server - remoting-amqp-client - - - \ No newline at end of file diff --git a/spring-remoting-modules/remoting-amqp/remoting-amqp-client/pom.xml b/spring-remoting-modules/remoting-amqp/remoting-amqp-client/pom.xml deleted file mode 100644 index 1bcab004f1..0000000000 --- a/spring-remoting-modules/remoting-amqp/remoting-amqp-client/pom.xml +++ /dev/null @@ -1,35 +0,0 @@ - - - 4.0.0 - remoting-amqp-client - remoting-amqp-client - jar - http://maven.apache.org - - - com.baeldung - remoting-amqp - 1.0-SNAPSHOT - - - - - org.springframework.boot - spring-boot-starter-amqp - - - org.springframework.boot - spring-boot-starter-tomcat - - - - - com.baeldung - remoting-http-api - ${project.version} - - - - \ No newline at end of file diff --git a/spring-remoting-modules/remoting-amqp/remoting-amqp-client/src/main/java/com/baeldung/client/AmqpClient.java b/spring-remoting-modules/remoting-amqp/remoting-amqp-client/src/main/java/com/baeldung/client/AmqpClient.java deleted file mode 100644 index def80f6b5e..0000000000 --- a/spring-remoting-modules/remoting-amqp/remoting-amqp-client/src/main/java/com/baeldung/client/AmqpClient.java +++ /dev/null @@ -1,46 +0,0 @@ -package com.baeldung.client; - -import com.baeldung.api.BookingException; -import com.baeldung.api.CabBookingService; -import org.springframework.amqp.core.*; -import org.springframework.amqp.rabbit.connection.ConnectionFactory; -import org.springframework.amqp.rabbit.core.RabbitTemplate; -import org.springframework.amqp.remoting.client.AmqpProxyFactoryBean; -import org.springframework.boot.SpringApplication; -import org.springframework.boot.autoconfigure.SpringBootApplication; -import org.springframework.context.annotation.Bean; - -import static java.lang.System.out; - -@SpringBootApplication public class AmqpClient { - - @Bean Queue queue() { - return new Queue("remotingQueue"); - } - - @Bean AmqpProxyFactoryBean amqpFactoryBean(AmqpTemplate amqpTemplate) { - AmqpProxyFactoryBean factoryBean = new AmqpProxyFactoryBean(); - factoryBean.setServiceInterface(CabBookingService.class); - factoryBean.setAmqpTemplate(amqpTemplate); - return factoryBean; - } - - @Bean Exchange directExchange(Queue someQueue) { - DirectExchange exchange = new DirectExchange("remoting.exchange"); - BindingBuilder.bind(someQueue).to(exchange).with("remoting.binding"); - return exchange; - } - - @Bean RabbitTemplate amqpTemplate(ConnectionFactory factory) { - RabbitTemplate template = new RabbitTemplate(factory); - template.setRoutingKey("remoting.binding"); - template.setExchange("remoting.exchange"); - return template; - } - - public static void main(String[] args) throws BookingException { - CabBookingService service = SpringApplication.run(AmqpClient.class, args).getBean(CabBookingService.class); - out.println(service.bookRide("13 Seagate Blvd, Key Largo, FL 33037")); - } - -} diff --git a/spring-remoting-modules/remoting-amqp/remoting-amqp-client/src/main/resources/application.properties b/spring-remoting-modules/remoting-amqp/remoting-amqp-client/src/main/resources/application.properties deleted file mode 100644 index 8df44a7c8d..0000000000 --- a/spring-remoting-modules/remoting-amqp/remoting-amqp-client/src/main/resources/application.properties +++ /dev/null @@ -1,19 +0,0 @@ -# This is true to make SpringBoot to automatically register a bean of type 'org.springframework.amqp.core.AmqpAdmin'. -# Check the org.springframework.boot.autoconfigure.amqp.RabbitAutoConfiguration javadoc for details. -spring.rabbitmq.dynamic=true - -# The port to which the client should connect defaults to 5672. -spring.rabbitmq.port=32769 - -# Username and password -spring.rabbitmq.username=guest -spring.rabbitmq.password=guest - -# The host, defaults to localhost. -spring.rabbitmq.host=192.168.99.100 - -# Logging -logging.pattern.console=%d{mm:ss.SSS} %-5p [%-31t] [%-54logger{0}] %marker%m%ex{full} - %logger - %F:%L%n -logging.level.root=WARN -logging.level.org.springframework.amqp=TRACE - diff --git a/spring-remoting-modules/remoting-amqp/remoting-amqp-client/src/main/resources/logback.xml b/spring-remoting-modules/remoting-amqp/remoting-amqp-client/src/main/resources/logback.xml deleted file mode 100644 index 7d900d8ea8..0000000000 --- a/spring-remoting-modules/remoting-amqp/remoting-amqp-client/src/main/resources/logback.xml +++ /dev/null @@ -1,13 +0,0 @@ - - - - - %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n - - - - - - - - \ No newline at end of file diff --git a/spring-remoting-modules/remoting-amqp/remoting-amqp-client/src/test/java/org/baeldung/SpringContextTest.java b/spring-remoting-modules/remoting-amqp/remoting-amqp-client/src/test/java/org/baeldung/SpringContextTest.java deleted file mode 100644 index fe20382ab4..0000000000 --- a/spring-remoting-modules/remoting-amqp/remoting-amqp-client/src/test/java/org/baeldung/SpringContextTest.java +++ /dev/null @@ -1,17 +0,0 @@ -package org.baeldung; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.test.context.junit4.SpringRunner; - -import com.baeldung.client.AmqpClient; - -@RunWith(SpringRunner.class) -@SpringBootTest(classes = AmqpClient.class) -public class SpringContextTest { - - @Test - public void whenSpringContextIsBootstrapped_thenNoExceptions() { - } -} diff --git a/spring-remoting-modules/remoting-amqp/remoting-amqp-server/pom.xml b/spring-remoting-modules/remoting-amqp/remoting-amqp-server/pom.xml deleted file mode 100644 index 6b6c12b41a..0000000000 --- a/spring-remoting-modules/remoting-amqp/remoting-amqp-server/pom.xml +++ /dev/null @@ -1,38 +0,0 @@ - - - 4.0.0 - remoting-amqp-server - remoting-amqp-server - jar - http://maven.apache.org - - - com.baeldung - remoting-amqp - 1.0-SNAPSHOT - - - - - com.baeldung - remoting-http-api - ${project.version} - - - org.springframework.boot - spring-boot-starter-amqp - - - com.baeldung - remoting-http-server - ${remoting-http-server.version} - - - - - 1.0-SNAPSHOT - - - \ No newline at end of file diff --git a/spring-remoting-modules/remoting-amqp/remoting-amqp-server/src/main/java/com/baeldung/server/AmqpServer.java b/spring-remoting-modules/remoting-amqp/remoting-amqp-server/src/main/java/com/baeldung/server/AmqpServer.java deleted file mode 100644 index f0155b2141..0000000000 --- a/spring-remoting-modules/remoting-amqp/remoting-amqp-server/src/main/java/com/baeldung/server/AmqpServer.java +++ /dev/null @@ -1,53 +0,0 @@ -package com.baeldung.server; - -import com.baeldung.api.CabBookingService; -import org.springframework.amqp.core.AmqpTemplate; -import org.springframework.amqp.core.Queue; -import org.springframework.amqp.rabbit.connection.ConnectionFactory; -import org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer; -import org.springframework.amqp.remoting.service.AmqpInvokerServiceExporter; -import org.springframework.boot.SpringApplication; -import org.springframework.boot.autoconfigure.EnableAutoConfiguration; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.ComponentScan; -import org.springframework.context.annotation.Configuration; - -@Configuration @ComponentScan @EnableAutoConfiguration -public class AmqpServer { - - /* - Please note that - - CachingConnectionFactory - - RabbitAdmin - - AmqpTemplate - are automatically declared by SpringBoot. - */ - - @Bean CabBookingService bookingService() { - return new CabBookingServiceImpl(); - } - - @Bean Queue queue() { - return new Queue("remotingQueue"); - } - - @Bean AmqpInvokerServiceExporter exporter(CabBookingService implementation, AmqpTemplate template) { - AmqpInvokerServiceExporter exporter = new AmqpInvokerServiceExporter(); - exporter.setServiceInterface(CabBookingService.class); - exporter.setService(implementation); - exporter.setAmqpTemplate(template); - return exporter; - } - - @Bean SimpleMessageListenerContainer listener(ConnectionFactory factory, AmqpInvokerServiceExporter exporter, Queue queue) { - SimpleMessageListenerContainer container = new SimpleMessageListenerContainer(factory); - container.setMessageListener(exporter); - container.setQueueNames(queue.getName()); - return container; - } - - public static void main(String[] args) { - SpringApplication.run(AmqpServer.class, args); - } - -} \ No newline at end of file diff --git a/spring-remoting-modules/remoting-amqp/remoting-amqp-server/src/main/resources/application.properties b/spring-remoting-modules/remoting-amqp/remoting-amqp-server/src/main/resources/application.properties deleted file mode 100644 index 8df44a7c8d..0000000000 --- a/spring-remoting-modules/remoting-amqp/remoting-amqp-server/src/main/resources/application.properties +++ /dev/null @@ -1,19 +0,0 @@ -# This is true to make SpringBoot to automatically register a bean of type 'org.springframework.amqp.core.AmqpAdmin'. -# Check the org.springframework.boot.autoconfigure.amqp.RabbitAutoConfiguration javadoc for details. -spring.rabbitmq.dynamic=true - -# The port to which the client should connect defaults to 5672. -spring.rabbitmq.port=32769 - -# Username and password -spring.rabbitmq.username=guest -spring.rabbitmq.password=guest - -# The host, defaults to localhost. -spring.rabbitmq.host=192.168.99.100 - -# Logging -logging.pattern.console=%d{mm:ss.SSS} %-5p [%-31t] [%-54logger{0}] %marker%m%ex{full} - %logger - %F:%L%n -logging.level.root=WARN -logging.level.org.springframework.amqp=TRACE - diff --git a/spring-remoting-modules/remoting-amqp/remoting-amqp-server/src/main/resources/logback.xml b/spring-remoting-modules/remoting-amqp/remoting-amqp-server/src/main/resources/logback.xml deleted file mode 100644 index 7d900d8ea8..0000000000 --- a/spring-remoting-modules/remoting-amqp/remoting-amqp-server/src/main/resources/logback.xml +++ /dev/null @@ -1,13 +0,0 @@ - - - - - %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n - - - - - - - - \ No newline at end of file diff --git a/spring-remoting-modules/remoting-amqp/remoting-amqp-server/src/test/java/org/baeldung/SpringContextManualTest.java b/spring-remoting-modules/remoting-amqp/remoting-amqp-server/src/test/java/org/baeldung/SpringContextManualTest.java deleted file mode 100644 index a6ee0b6000..0000000000 --- a/spring-remoting-modules/remoting-amqp/remoting-amqp-server/src/test/java/org/baeldung/SpringContextManualTest.java +++ /dev/null @@ -1,17 +0,0 @@ -package org.baeldung; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.test.context.junit4.SpringRunner; - -import com.baeldung.server.AmqpServer; - -@RunWith(SpringRunner.class) -@SpringBootTest(classes = AmqpServer.class) -public class SpringContextManualTest { - - @Test - public void whenSpringContextIsBootstrapped_thenNoExceptions() { - } -} diff --git a/spring-remoting-modules/remoting-hessian-burlap/README.md b/spring-remoting-modules/remoting-hessian-burlap/README.md deleted file mode 100644 index cacceddc5a..0000000000 --- a/spring-remoting-modules/remoting-hessian-burlap/README.md +++ /dev/null @@ -1,12 +0,0 @@ -## Spring Remoting with Hessian and Burlap - -This module contains articles about Spring Remoting with Hessian and Burlap - -### Relevant Articles - -- [Spring Remoting with Hessian and Burlap](http://www.baeldung.com/spring-remoting-hessian-burlap) - -### Overview -This Maven project contains the Java source code for the Hessian and Burlap modules - used in the [Spring Remoting](https://github.com/eugenp/tutorials/tree/master/spring-remoting) - series of articles. diff --git a/spring-remoting-modules/remoting-hessian-burlap/pom.xml b/spring-remoting-modules/remoting-hessian-burlap/pom.xml deleted file mode 100644 index e5975b9f37..0000000000 --- a/spring-remoting-modules/remoting-hessian-burlap/pom.xml +++ /dev/null @@ -1,24 +0,0 @@ - - - 4.0.0 - remoting-hessian-burlap - 1.0-SNAPSHOT - remoting-hessian-burlap - pom - - - - com.baeldung - parent-boot-1 - 0.0.1-SNAPSHOT - ../../parent-boot-1 - - - - remoting-hessian-burlap-server - remoting-hessian-burlap-client - - - \ No newline at end of file diff --git a/spring-remoting-modules/remoting-hessian-burlap/remoting-hessian-burlap-client/pom.xml b/spring-remoting-modules/remoting-hessian-burlap/remoting-hessian-burlap-client/pom.xml deleted file mode 100644 index 1939e00386..0000000000 --- a/spring-remoting-modules/remoting-hessian-burlap/remoting-hessian-burlap-client/pom.xml +++ /dev/null @@ -1,79 +0,0 @@ - - - 4.0.0 - remoting-hessian-burlap-client - remoting-hessian-burlap-client - - - com.baeldung - remoting-hessian-burlap - 1.0-SNAPSHOT - - - - - org.springframework.boot - spring-boot-starter-web - - - org.springframework.boot - spring-boot-starter-tomcat - - - - - ${project.groupId} - remoting-http-api - ${project.version} - - - com.caucho - hessian - ${hessian.version} - - - - ${project.groupId} - remoting-hessian-burlap-server - ${project.version} - test - - - javax.servlet - javax.servlet-api - test - - - org.springframework.boot - spring-boot-starter-test - test - - - org.springframework.boot - spring-boot-starter-tomcat - test - - - - - - - - org.apache.maven.plugins - maven-surefire-plugin - - - --add-opens java.base/java.lang=ALL-UNNAMED - - - - - - - - 4.0.38 - - - \ No newline at end of file diff --git a/spring-remoting-modules/remoting-hessian-burlap/remoting-hessian-burlap-client/src/main/java/com/baeldung/client/BurlapClient.java b/spring-remoting-modules/remoting-hessian-burlap/remoting-hessian-burlap-client/src/main/java/com/baeldung/client/BurlapClient.java deleted file mode 100644 index 1079c4163f..0000000000 --- a/spring-remoting-modules/remoting-hessian-burlap/remoting-hessian-burlap-client/src/main/java/com/baeldung/client/BurlapClient.java +++ /dev/null @@ -1,28 +0,0 @@ -package com.baeldung.client; - -import com.baeldung.api.BookingException; -import com.baeldung.api.CabBookingService; -import org.springframework.boot.SpringApplication; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.remoting.caucho.BurlapProxyFactoryBean; - -import static java.lang.System.out; - -@Configuration -public class BurlapClient { - - @Bean - public BurlapProxyFactoryBean burlapInvoker() { - BurlapProxyFactoryBean invoker = new BurlapProxyFactoryBean(); - invoker.setServiceUrl("http://localhost:8032/b_booking"); - invoker.setServiceInterface(CabBookingService.class); - return invoker; - } - - public static void main(String[] args) throws BookingException { - CabBookingService service = SpringApplication.run(BurlapClient.class, args).getBean(CabBookingService.class); - out.println(service.bookRide("13 Seagate Blvd, Key Largo, FL 33037")); - } - -} diff --git a/spring-remoting-modules/remoting-hessian-burlap/remoting-hessian-burlap-client/src/main/java/com/baeldung/client/HessianClient.java b/spring-remoting-modules/remoting-hessian-burlap/remoting-hessian-burlap-client/src/main/java/com/baeldung/client/HessianClient.java deleted file mode 100644 index b2a2f4ffae..0000000000 --- a/spring-remoting-modules/remoting-hessian-burlap/remoting-hessian-burlap-client/src/main/java/com/baeldung/client/HessianClient.java +++ /dev/null @@ -1,28 +0,0 @@ -package com.baeldung.client; - -import com.baeldung.api.BookingException; -import com.baeldung.api.CabBookingService; -import org.springframework.boot.SpringApplication; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.remoting.caucho.HessianProxyFactoryBean; - -import static java.lang.System.out; - -@Configuration -public class HessianClient { - - @Bean - public HessianProxyFactoryBean hessianInvoker() { - HessianProxyFactoryBean invoker = new HessianProxyFactoryBean(); - invoker.setServiceUrl("http://localhost:8032/booking"); - invoker.setServiceInterface(CabBookingService.class); - return invoker; - } - - public static void main(String[] args) throws BookingException { - CabBookingService service = SpringApplication.run(HessianClient.class, args).getBean(CabBookingService.class); - out.println(service.bookRide("13 Seagate Blvd, Key Largo, FL 33037")); - } - -} diff --git a/spring-remoting-modules/remoting-hessian-burlap/remoting-hessian-burlap-client/src/main/resources/logback.xml b/spring-remoting-modules/remoting-hessian-burlap/remoting-hessian-burlap-client/src/main/resources/logback.xml deleted file mode 100644 index 7d900d8ea8..0000000000 --- a/spring-remoting-modules/remoting-hessian-burlap/remoting-hessian-burlap-client/src/main/resources/logback.xml +++ /dev/null @@ -1,13 +0,0 @@ - - - - - %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n - - - - - - - - \ No newline at end of file diff --git a/spring-remoting-modules/remoting-hessian-burlap/remoting-hessian-burlap-client/src/test/java/com/baeldung/client/CabBookingServiceIntegrationTest.java b/spring-remoting-modules/remoting-hessian-burlap/remoting-hessian-burlap-client/src/test/java/com/baeldung/client/CabBookingServiceIntegrationTest.java deleted file mode 100644 index a1fed9637f..0000000000 --- a/spring-remoting-modules/remoting-hessian-burlap/remoting-hessian-burlap-client/src/test/java/com/baeldung/client/CabBookingServiceIntegrationTest.java +++ /dev/null @@ -1,74 +0,0 @@ -package com.baeldung.client; - -import com.baeldung.api.Booking; -import com.baeldung.api.BookingException; -import com.baeldung.api.CabBookingService; -import com.baeldung.server.Server; -import org.junit.AfterClass; -import org.junit.BeforeClass; -import org.junit.runner.RunWith; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Qualifier; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.test.context.junit4.SpringRunner; - -import static java.lang.Thread.sleep; - -@SpringBootTest(classes = {BurlapClient.class, HessianClient.class}) -@RunWith(SpringRunner.class) -public class CabBookingServiceIntegrationTest { - - static Logger log = LoggerFactory.getLogger(CabBookingServiceIntegrationTest.class); - @Autowired @Qualifier("burlapInvoker") CabBookingService burlapClient; - @Autowired @Qualifier("hessianInvoker") CabBookingService hessianClient; - static Thread serverThread; - - @BeforeClass - public static void startServer() throws InterruptedException { - serverThread = serverThread(); - log.info("Starting server."); - serverThread.start(); - // increase this enough to let the server start - sleep(6000); - } - - @org.junit.Test - public void bookACabWithBurlapClient() throws InterruptedException { - bookACab(this.burlapClient); - } - - @org.junit.Test - public void bookACabWithHessianClient() throws InterruptedException { - bookACab(this.hessianClient); - } - - private void bookACab(CabBookingService burlapClient) { - Booking booking; - try { - booking = burlapClient.bookRide("Duomo place"); - log.info("Booking success: {}", booking); - } catch (BookingException e) { - log.info("Booking failed: {}", e.getMessage()); - } - } - - @AfterClass - public static void stopServer() throws InterruptedException { - serverThread.interrupt(); - serverThread.join(); - log.info("Server terminated."); - } - - static Thread serverThread() { - Thread serverThread = new Thread(()-> { - log.info("Starting Burlap and Hessian server"); - Server.main(new String[]{}); - log.info("Burlap and Hessian server terminated"); - }); - serverThread.setDaemon(true); - return serverThread; - } - -} diff --git a/spring-remoting-modules/remoting-hessian-burlap/remoting-hessian-burlap-client/src/test/java/org/baeldung/SpringContextTest.java b/spring-remoting-modules/remoting-hessian-burlap/remoting-hessian-burlap-client/src/test/java/org/baeldung/SpringContextTest.java deleted file mode 100644 index 4325b0ddef..0000000000 --- a/spring-remoting-modules/remoting-hessian-burlap/remoting-hessian-burlap-client/src/test/java/org/baeldung/SpringContextTest.java +++ /dev/null @@ -1,18 +0,0 @@ -package org.baeldung; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.test.context.junit4.SpringRunner; - -import com.baeldung.client.BurlapClient; -import com.baeldung.client.HessianClient; - -@SpringBootTest(classes = {BurlapClient.class, HessianClient.class}) -@RunWith(SpringRunner.class) -public class SpringContextTest { - - @Test - public void whenSpringContextIsBootstrapped_thenNoExceptions() { - } -} diff --git a/spring-remoting-modules/remoting-hessian-burlap/remoting-hessian-burlap-client/src/test/resources/application.properties b/spring-remoting-modules/remoting-hessian-burlap/remoting-hessian-burlap-client/src/test/resources/application.properties deleted file mode 100644 index 13577dc391..0000000000 --- a/spring-remoting-modules/remoting-hessian-burlap/remoting-hessian-burlap-client/src/test/resources/application.properties +++ /dev/null @@ -1 +0,0 @@ -application.properties=9999 \ No newline at end of file diff --git a/spring-remoting-modules/remoting-hessian-burlap/remoting-hessian-burlap-server/pom.xml b/spring-remoting-modules/remoting-hessian-burlap/remoting-hessian-burlap-server/pom.xml deleted file mode 100644 index 68a70f24b6..0000000000 --- a/spring-remoting-modules/remoting-hessian-burlap/remoting-hessian-burlap-server/pom.xml +++ /dev/null @@ -1,50 +0,0 @@ - - - 4.0.0 - remoting-hessian-burlap-server - remoting-hessian-burlap-server - - - com.baeldung - remoting-hessian-burlap - 1.0-SNAPSHOT - - - - - com.baeldung - remoting-http-server - ${project.version} - - - org.springframework.boot - spring-boot-starter-web - - - com.caucho - hessian - ${hessian.version} - - - - - - - org.apache.maven.plugins - maven-surefire-plugin - - - --add-opens java.base/java.lang=ALL-UNNAMED - - - - - - - - 4.0.38 - - - \ No newline at end of file diff --git a/spring-remoting-modules/remoting-hessian-burlap/remoting-hessian-burlap-server/src/main/java/com/baeldung/server/Server.java b/spring-remoting-modules/remoting-hessian-burlap/remoting-hessian-burlap-server/src/main/java/com/baeldung/server/Server.java deleted file mode 100644 index 9c825a2a80..0000000000 --- a/spring-remoting-modules/remoting-hessian-burlap/remoting-hessian-burlap-server/src/main/java/com/baeldung/server/Server.java +++ /dev/null @@ -1,41 +0,0 @@ -package com.baeldung.server; - -import com.baeldung.api.CabBookingService; -import org.springframework.boot.SpringApplication; -import org.springframework.boot.autoconfigure.EnableAutoConfiguration; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.ComponentScan; -import org.springframework.context.annotation.Configuration; -import org.springframework.remoting.caucho.BurlapServiceExporter; -import org.springframework.remoting.caucho.HessianServiceExporter; -import org.springframework.remoting.support.RemoteExporter; - -import java.util.Collections; - -@Configuration @ComponentScan @EnableAutoConfiguration public class Server { - - @Bean CabBookingService bookingService() { - return new CabBookingServiceImpl(); - } - - @Bean(name = "/booking") RemoteExporter hessianService(CabBookingService service) { - HessianServiceExporter exporter = new HessianServiceExporter(); - exporter.setService(bookingService()); - exporter.setServiceInterface(CabBookingService.class); - return exporter; - } - - @Bean(name = "/b_booking") RemoteExporter burlapService(CabBookingService service) { - BurlapServiceExporter exporter = new BurlapServiceExporter(); - exporter.setService(bookingService()); - exporter.setServiceInterface(CabBookingService.class); - return exporter; - } - - public static void main(String[] args) { - SpringApplication app = new SpringApplication(Server.class); - app.setDefaultProperties(Collections.singletonMap("server.port", "8032")); - app.run(args); - } - -} \ No newline at end of file diff --git a/spring-remoting-modules/remoting-hessian-burlap/remoting-hessian-burlap-server/src/main/resources/logback.xml b/spring-remoting-modules/remoting-hessian-burlap/remoting-hessian-burlap-server/src/main/resources/logback.xml deleted file mode 100644 index 7d900d8ea8..0000000000 --- a/spring-remoting-modules/remoting-hessian-burlap/remoting-hessian-burlap-server/src/main/resources/logback.xml +++ /dev/null @@ -1,13 +0,0 @@ - - - - - %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n - - - - - - - - \ No newline at end of file diff --git a/spring-remoting-modules/remoting-hessian-burlap/remoting-hessian-burlap-server/src/test/java/org/baeldung/SpringContextTest.java b/spring-remoting-modules/remoting-hessian-burlap/remoting-hessian-burlap-server/src/test/java/org/baeldung/SpringContextTest.java deleted file mode 100644 index e676bb0ff2..0000000000 --- a/spring-remoting-modules/remoting-hessian-burlap/remoting-hessian-burlap-server/src/test/java/org/baeldung/SpringContextTest.java +++ /dev/null @@ -1,17 +0,0 @@ -package org.baeldung; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.test.context.junit4.SpringRunner; - -import com.baeldung.server.Server; - -@SpringBootTest(classes = Server.class) -@RunWith(SpringRunner.class) -public class SpringContextTest { - - @Test - public void whenSpringContextIsBootstrapped_thenNoExceptions() { - } -} diff --git a/spring-remoting-modules/remoting-http/README.md b/spring-remoting-modules/remoting-http/README.md deleted file mode 100644 index a4f3ea82a9..0000000000 --- a/spring-remoting-modules/remoting-http/README.md +++ /dev/null @@ -1,8 +0,0 @@ -## Remoting HTTP - -This module contains articles about Spring Remoting over HTTP - -### Relevant Articles: - -- [Intro to Spring Remoting with HTTP Invokers](https://www.baeldung.com/spring-remoting-http-invoker) - diff --git a/spring-remoting-modules/remoting-http/pom.xml b/spring-remoting-modules/remoting-http/pom.xml deleted file mode 100644 index cee1d82196..0000000000 --- a/spring-remoting-modules/remoting-http/pom.xml +++ /dev/null @@ -1,23 +0,0 @@ - - - 4.0.0 - remoting-http - remoting-http - pom - Parent for all modules related to HTTP Spring Remoting. - - - com.ossez - spring-remoting-modules - 1.0-SNAPSHOT - - - - remoting-http-server - remoting-http-client - remoting-http-api - - - \ No newline at end of file diff --git a/spring-remoting-modules/remoting-http/remoting-http-api/pom.xml b/spring-remoting-modules/remoting-http/remoting-http-api/pom.xml deleted file mode 100644 index d84d942659..0000000000 --- a/spring-remoting-modules/remoting-http/remoting-http-api/pom.xml +++ /dev/null @@ -1,16 +0,0 @@ - - - 4.0.0 - remoting-http-api - remoting-http-api - API definition shared between client and server. - - - com.ossez - remoting-http - 1.0-SNAPSHOT - - - \ No newline at end of file diff --git a/spring-remoting-modules/remoting-http/remoting-http-api/src/main/java/com/baeldung/api/Booking.java b/spring-remoting-modules/remoting-http/remoting-http-api/src/main/java/com/baeldung/api/Booking.java deleted file mode 100644 index 5d2d3683a1..0000000000 --- a/spring-remoting-modules/remoting-http/remoting-http-api/src/main/java/com/baeldung/api/Booking.java +++ /dev/null @@ -1,17 +0,0 @@ -package com.baeldung.api; - -import java.io.Serializable; - -import static java.lang.String.format; - -public class Booking implements Serializable { - private String bookingCode; - - @Override public String toString() { - return format("Ride confirmed: code '%s'.", bookingCode); - } - - public Booking(String bookingCode) { - this.bookingCode = bookingCode; - } -} diff --git a/spring-remoting-modules/remoting-http/remoting-http-api/src/main/java/com/baeldung/api/BookingException.java b/spring-remoting-modules/remoting-http/remoting-http-api/src/main/java/com/baeldung/api/BookingException.java deleted file mode 100644 index 4099db2908..0000000000 --- a/spring-remoting-modules/remoting-http/remoting-http-api/src/main/java/com/baeldung/api/BookingException.java +++ /dev/null @@ -1,7 +0,0 @@ -package com.baeldung.api; - -public class BookingException extends Exception { - public BookingException(String message) { - super(message); - } -} diff --git a/spring-remoting-modules/remoting-http/remoting-http-api/src/main/java/com/baeldung/api/CabBookingService.java b/spring-remoting-modules/remoting-http/remoting-http-api/src/main/java/com/baeldung/api/CabBookingService.java deleted file mode 100644 index b554415e07..0000000000 --- a/spring-remoting-modules/remoting-http/remoting-http-api/src/main/java/com/baeldung/api/CabBookingService.java +++ /dev/null @@ -1,5 +0,0 @@ -package com.baeldung.api; - -public interface CabBookingService { - Booking bookRide(String pickUpLocation) throws BookingException; -} diff --git a/spring-remoting-modules/remoting-http/remoting-http-client/pom.xml b/spring-remoting-modules/remoting-http/remoting-http-client/pom.xml deleted file mode 100644 index 219319f75d..0000000000 --- a/spring-remoting-modules/remoting-http/remoting-http-client/pom.xml +++ /dev/null @@ -1,34 +0,0 @@ - - - 4.0.0 - remoting-http-client - remoting-http-client - Shows how to invoke a remote service using Spring Remoting HTTP. - - - com.ossez - remoting-http - 1.0-SNAPSHOT - - - - - org.springframework.boot - spring-boot-starter-web - - - org.springframework.boot - spring-boot-starter-tomcat - - - - - ${project.groupId} - remoting-http-api - ${project.version} - - - - \ No newline at end of file diff --git a/spring-remoting-modules/remoting-http/remoting-http-client/src/main/java/com/baeldug/client/Client.java b/spring-remoting-modules/remoting-http/remoting-http-client/src/main/java/com/baeldug/client/Client.java deleted file mode 100644 index 90f6736a43..0000000000 --- a/spring-remoting-modules/remoting-http/remoting-http-client/src/main/java/com/baeldug/client/Client.java +++ /dev/null @@ -1,28 +0,0 @@ -package com.baeldug.client; - -import com.baeldung.api.BookingException; -import com.baeldung.api.CabBookingService; -import org.springframework.boot.SpringApplication; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.remoting.httpinvoker.HttpInvokerProxyFactoryBean; - -import static java.lang.System.out; - -@Configuration -public class Client { - - @Bean - public HttpInvokerProxyFactoryBean invoker() { - HttpInvokerProxyFactoryBean invoker = new HttpInvokerProxyFactoryBean(); - invoker.setServiceUrl("http://localhost:8080/booking"); - invoker.setServiceInterface(CabBookingService.class); - return invoker; - } - - public static void main(String[] args) throws BookingException { - CabBookingService service = SpringApplication.run(Client.class, args).getBean(CabBookingService.class); - out.println(service.bookRide("13 Seagate Blvd, Key Largo, FL 33037")); - } - -} diff --git a/spring-remoting-modules/remoting-http/remoting-http-client/src/main/resources/logback.xml b/spring-remoting-modules/remoting-http/remoting-http-client/src/main/resources/logback.xml deleted file mode 100644 index 7d900d8ea8..0000000000 --- a/spring-remoting-modules/remoting-http/remoting-http-client/src/main/resources/logback.xml +++ /dev/null @@ -1,13 +0,0 @@ - - - - - %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n - - - - - - - - \ No newline at end of file diff --git a/spring-remoting-modules/remoting-http/remoting-http-server/pom.xml b/spring-remoting-modules/remoting-http/remoting-http-server/pom.xml deleted file mode 100644 index 1dd711aedc..0000000000 --- a/spring-remoting-modules/remoting-http/remoting-http-server/pom.xml +++ /dev/null @@ -1,28 +0,0 @@ - - - 4.0.0 - remoting-http-server - remoting-http-server - Shows how to expose a service using Spring Remoting HTTP. - - - com.ossez - remoting-http - 1.0-SNAPSHOT - - - - - org.springframework.boot - spring-boot-starter-web - - - ${project.groupId} - remoting-http-api - ${project.version} - - - - \ No newline at end of file diff --git a/spring-remoting-modules/remoting-http/remoting-http-server/readme.md b/spring-remoting-modules/remoting-http/remoting-http-server/readme.md deleted file mode 100644 index 4a2abb5d03..0000000000 --- a/spring-remoting-modules/remoting-http/remoting-http-server/readme.md +++ /dev/null @@ -1,12 +0,0 @@ -Build and launch with the following command. - - mvn clean package tomcat7:run-war - -Exposed service is available at following URL. - - http://localhost:9090/spring-remoting-http-server/account - -## References - - - diff --git a/spring-remoting-modules/remoting-http/remoting-http-server/src/main/java/com/baeldung/server/CabBookingServiceImpl.java b/spring-remoting-modules/remoting-http/remoting-http-server/src/main/java/com/baeldung/server/CabBookingServiceImpl.java deleted file mode 100644 index 55ec9c5733..0000000000 --- a/spring-remoting-modules/remoting-http/remoting-http-server/src/main/java/com/baeldung/server/CabBookingServiceImpl.java +++ /dev/null @@ -1,16 +0,0 @@ -package com.baeldung.server; - -import com.baeldung.api.Booking; -import com.baeldung.api.BookingException; -import com.baeldung.api.CabBookingService; - -import static java.lang.Math.random; -import static java.util.UUID.randomUUID; - -public class CabBookingServiceImpl implements CabBookingService { - - @Override public Booking bookRide(String pickUpLocation) throws BookingException { - if (random() < 0.3) throw new BookingException("Cab unavailable"); - return new Booking(randomUUID().toString()); - } -} diff --git a/spring-remoting-modules/remoting-http/remoting-http-server/src/main/java/com/baeldung/server/Server.java b/spring-remoting-modules/remoting-http/remoting-http-server/src/main/java/com/baeldung/server/Server.java deleted file mode 100644 index c6b198507f..0000000000 --- a/spring-remoting-modules/remoting-http/remoting-http-server/src/main/java/com/baeldung/server/Server.java +++ /dev/null @@ -1,27 +0,0 @@ -package com.baeldung.server; - -import com.baeldung.api.CabBookingService; -import org.springframework.boot.SpringApplication; -import org.springframework.boot.autoconfigure.EnableAutoConfiguration; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.ComponentScan; -import org.springframework.context.annotation.Configuration; -import org.springframework.remoting.httpinvoker.HttpInvokerServiceExporter; - -@Configuration -@ComponentScan -@EnableAutoConfiguration -public class Server { - - @Bean(name = "/booking") HttpInvokerServiceExporter accountService() { - HttpInvokerServiceExporter exporter = new HttpInvokerServiceExporter(); - exporter.setService( new CabBookingServiceImpl() ); - exporter.setServiceInterface( CabBookingService.class ); - return exporter; - } - - public static void main(String[] args) { - SpringApplication.run(Server.class, args); - } - -} \ No newline at end of file diff --git a/spring-remoting-modules/remoting-http/remoting-http-server/src/main/resources/logback.xml b/spring-remoting-modules/remoting-http/remoting-http-server/src/main/resources/logback.xml deleted file mode 100644 index 7d900d8ea8..0000000000 --- a/spring-remoting-modules/remoting-http/remoting-http-server/src/main/resources/logback.xml +++ /dev/null @@ -1,13 +0,0 @@ - - - - - %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n - - - - - - - - \ No newline at end of file diff --git a/spring-remoting-modules/remoting-http/remoting-http-server/src/test/java/org/baeldung/SpringContextTest.java b/spring-remoting-modules/remoting-http/remoting-http-server/src/test/java/org/baeldung/SpringContextTest.java deleted file mode 100644 index e676bb0ff2..0000000000 --- a/spring-remoting-modules/remoting-http/remoting-http-server/src/test/java/org/baeldung/SpringContextTest.java +++ /dev/null @@ -1,17 +0,0 @@ -package org.baeldung; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.test.context.junit4.SpringRunner; - -import com.baeldung.server.Server; - -@SpringBootTest(classes = Server.class) -@RunWith(SpringRunner.class) -public class SpringContextTest { - - @Test - public void whenSpringContextIsBootstrapped_thenNoExceptions() { - } -} diff --git a/spring-remoting-modules/remoting-jms/README.md b/spring-remoting-modules/remoting-jms/README.md deleted file mode 100644 index 2f48a8f57f..0000000000 --- a/spring-remoting-modules/remoting-jms/README.md +++ /dev/null @@ -1,8 +0,0 @@ -## Remoting JMS - -This module contains articles about Spring Remoting with Java Message Service (JMS) - -### Relevant Articles: - -- [Spring Remoting with JMS and ActiveMQ](https://www.baeldung.com/spring-remoting-jms) - diff --git a/spring-remoting-modules/remoting-jms/pom.xml b/spring-remoting-modules/remoting-jms/pom.xml deleted file mode 100644 index fd63fa01c2..0000000000 --- a/spring-remoting-modules/remoting-jms/pom.xml +++ /dev/null @@ -1,21 +0,0 @@ - - - 4.0.0 - remoting-jms - remoting-jms - pom - - - com.ossez - spring-remoting-modules - 1.0-SNAPSHOT - - - - remoting-jms-client - remoting-jms-server - - - \ No newline at end of file diff --git a/spring-remoting-modules/remoting-jms/remoting-jms-client/pom.xml b/spring-remoting-modules/remoting-jms/remoting-jms-client/pom.xml deleted file mode 100644 index 4ef18620bb..0000000000 --- a/spring-remoting-modules/remoting-jms/remoting-jms-client/pom.xml +++ /dev/null @@ -1,33 +0,0 @@ - - - 4.0.0 - remoting-jms-client - remoting-jms-client - - - com.ossez - remoting-jms - 1.0-SNAPSHOT - - - - - org.springframework.boot - spring-boot-starter-activemq - - - org.springframework.boot - spring-boot-starter-tomcat - - - - - com.ossez - remoting-http-api - ${project.version} - - - - \ No newline at end of file diff --git a/spring-remoting-modules/remoting-jms/remoting-jms-client/src/main/java/com/baeldung/client/JmsClient.java b/spring-remoting-modules/remoting-jms/remoting-jms-client/src/main/java/com/baeldung/client/JmsClient.java deleted file mode 100644 index 0c5d728f07..0000000000 --- a/spring-remoting-modules/remoting-jms/remoting-jms-client/src/main/java/com/baeldung/client/JmsClient.java +++ /dev/null @@ -1,39 +0,0 @@ -package com.baeldung.client; - -import com.baeldung.api.Booking; -import com.baeldung.api.BookingException; -import com.baeldung.api.CabBookingService; -import org.apache.activemq.command.ActiveMQQueue; -import org.springframework.beans.factory.FactoryBean; -import org.springframework.boot.SpringApplication; -import org.springframework.boot.autoconfigure.SpringBootApplication; -import org.springframework.context.annotation.Bean; -import org.springframework.jms.remoting.JmsInvokerProxyFactoryBean; - -import javax.jms.ConnectionFactory; -import javax.jms.Queue; - -@SpringBootApplication -public class JmsClient { - - @Bean Queue queue() { - return new ActiveMQQueue("remotingQueue"); -} - - @Bean FactoryBean invoker(ConnectionFactory factory, Queue queue) { - JmsInvokerProxyFactoryBean factoryBean = new JmsInvokerProxyFactoryBean(); - factoryBean.setConnectionFactory(factory); - factoryBean.setServiceInterface(CabBookingService.class); - factoryBean.setQueue(queue); - return factoryBean; - } - - public static void main(String[] args) throws BookingException { - CabBookingService service = SpringApplication.run(JmsClient.class, args).getBean(CabBookingService.class); - System.out.println("here"); - Booking bookingOutcome = service.bookRide("13 Seagate Blvd, Key Largo, FL 33037"); - System.out.println("there"); - System.out.println(bookingOutcome); - } - -} diff --git a/spring-remoting-modules/remoting-jms/remoting-jms-client/src/main/resources/application.properties b/spring-remoting-modules/remoting-jms/remoting-jms-client/src/main/resources/application.properties deleted file mode 100644 index 738b030a59..0000000000 --- a/spring-remoting-modules/remoting-jms/remoting-jms-client/src/main/resources/application.properties +++ /dev/null @@ -1,10 +0,0 @@ -spring.activemq.broker-url=tcp://127.0.0.1:61616 -spring.activemq.packages.trusted=org.springframework.remoting.support,java.lang,com.baeldung.api - -# Logging -logging.pattern.console=%d{mm:ss.SSS} %-5p [%-31t] [%-54logger{0}] %marker%m%ex{full} - %logger - %F:%L%n -logging.level.root=WARN -logging.level.org.apache.activemq=DEBUG -logging.level.org.springframework.jms=DEBUG -logging.level.org.springframework=WARN - diff --git a/spring-remoting-modules/remoting-jms/remoting-jms-client/src/main/resources/logback.xml b/spring-remoting-modules/remoting-jms/remoting-jms-client/src/main/resources/logback.xml deleted file mode 100644 index 7d900d8ea8..0000000000 --- a/spring-remoting-modules/remoting-jms/remoting-jms-client/src/main/resources/logback.xml +++ /dev/null @@ -1,13 +0,0 @@ - - - - - %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n - - - - - - - - \ No newline at end of file diff --git a/spring-remoting-modules/remoting-jms/remoting-jms-client/src/test/java/org/baeldung/SpringContextTest.java b/spring-remoting-modules/remoting-jms/remoting-jms-client/src/test/java/org/baeldung/SpringContextTest.java deleted file mode 100644 index 95721b6eaa..0000000000 --- a/spring-remoting-modules/remoting-jms/remoting-jms-client/src/test/java/org/baeldung/SpringContextTest.java +++ /dev/null @@ -1,17 +0,0 @@ -package org.baeldung; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.test.context.junit4.SpringRunner; - -import com.baeldung.client.JmsClient; - -@SpringBootTest(classes = JmsClient.class) -@RunWith(SpringRunner.class) -public class SpringContextTest { - - @Test - public void whenSpringContextIsBootstrapped_thenNoExceptions() { - } -} diff --git a/spring-remoting-modules/remoting-jms/remoting-jms-server/pom.xml b/spring-remoting-modules/remoting-jms/remoting-jms-server/pom.xml deleted file mode 100644 index 697c0612e3..0000000000 --- a/spring-remoting-modules/remoting-jms/remoting-jms-server/pom.xml +++ /dev/null @@ -1,33 +0,0 @@ - - - 4.0.0 - remoting-jms-server - remoting-jms-server - - - com.ossez - remoting-jms - 1.0-SNAPSHOT - - - - - org.springframework.boot - spring-boot-starter-activemq - - - org.springframework.boot - spring-boot-starter-tomcat - - - - - com.ossez - remoting-http-api - ${project.version} - - - - \ No newline at end of file diff --git a/spring-remoting-modules/remoting-jms/remoting-jms-server/src/main/java/com/baeldung/server/CabBookingServiceImpl.java b/spring-remoting-modules/remoting-jms/remoting-jms-server/src/main/java/com/baeldung/server/CabBookingServiceImpl.java deleted file mode 100644 index 55ec9c5733..0000000000 --- a/spring-remoting-modules/remoting-jms/remoting-jms-server/src/main/java/com/baeldung/server/CabBookingServiceImpl.java +++ /dev/null @@ -1,16 +0,0 @@ -package com.baeldung.server; - -import com.baeldung.api.Booking; -import com.baeldung.api.BookingException; -import com.baeldung.api.CabBookingService; - -import static java.lang.Math.random; -import static java.util.UUID.randomUUID; - -public class CabBookingServiceImpl implements CabBookingService { - - @Override public Booking bookRide(String pickUpLocation) throws BookingException { - if (random() < 0.3) throw new BookingException("Cab unavailable"); - return new Booking(randomUUID().toString()); - } -} diff --git a/spring-remoting-modules/remoting-jms/remoting-jms-server/src/main/java/com/baeldung/server/JmsServer.java b/spring-remoting-modules/remoting-jms/remoting-jms-server/src/main/java/com/baeldung/server/JmsServer.java deleted file mode 100644 index 8572718042..0000000000 --- a/spring-remoting-modules/remoting-jms/remoting-jms-server/src/main/java/com/baeldung/server/JmsServer.java +++ /dev/null @@ -1,51 +0,0 @@ -package com.baeldung.server; - -import com.baeldung.api.CabBookingService; -import org.apache.activemq.command.ActiveMQQueue; -import org.springframework.boot.SpringApplication; -import org.springframework.boot.autoconfigure.SpringBootApplication; -import org.springframework.context.annotation.Bean; -import org.springframework.jms.listener.SimpleMessageListenerContainer; -import org.springframework.jms.remoting.JmsInvokerServiceExporter; - -import javax.jms.ConnectionFactory; -import javax.jms.Queue; - -@SpringBootApplication public class JmsServer { - - /* - This server needs to be connected to an ActiveMQ server. - To quickly spin up an ActiveMQ server, you can use Docker. - - docker run -p 61616:61616 -p 8161:8161 rmohr/activemq:5.14.3 - */ - - @Bean CabBookingService bookingService() { - return new CabBookingServiceImpl(); - } - - @Bean Queue queue() { - return new ActiveMQQueue("remotingQueue"); -} - - @Bean JmsInvokerServiceExporter exporter(CabBookingService implementation) { - JmsInvokerServiceExporter exporter = new JmsInvokerServiceExporter(); - exporter.setServiceInterface(CabBookingService.class); - exporter.setService(implementation); - return exporter; - } - - @Bean SimpleMessageListenerContainer listener(ConnectionFactory factory, JmsInvokerServiceExporter exporter) { - SimpleMessageListenerContainer container = new SimpleMessageListenerContainer(); - container.setConnectionFactory(factory); - container.setDestinationName("remotingQueue"); - container.setConcurrentConsumers(1); - container.setMessageListener(exporter); - return container; - } - - public static void main(String[] args) { - SpringApplication.run(JmsServer.class, args); - } - -} diff --git a/spring-remoting-modules/remoting-jms/remoting-jms-server/src/main/resources/application.properties b/spring-remoting-modules/remoting-jms/remoting-jms-server/src/main/resources/application.properties deleted file mode 100644 index 738b030a59..0000000000 --- a/spring-remoting-modules/remoting-jms/remoting-jms-server/src/main/resources/application.properties +++ /dev/null @@ -1,10 +0,0 @@ -spring.activemq.broker-url=tcp://127.0.0.1:61616 -spring.activemq.packages.trusted=org.springframework.remoting.support,java.lang,com.baeldung.api - -# Logging -logging.pattern.console=%d{mm:ss.SSS} %-5p [%-31t] [%-54logger{0}] %marker%m%ex{full} - %logger - %F:%L%n -logging.level.root=WARN -logging.level.org.apache.activemq=DEBUG -logging.level.org.springframework.jms=DEBUG -logging.level.org.springframework=WARN - diff --git a/spring-remoting-modules/remoting-jms/remoting-jms-server/src/main/resources/logback.xml b/spring-remoting-modules/remoting-jms/remoting-jms-server/src/main/resources/logback.xml deleted file mode 100644 index 7d900d8ea8..0000000000 --- a/spring-remoting-modules/remoting-jms/remoting-jms-server/src/main/resources/logback.xml +++ /dev/null @@ -1,13 +0,0 @@ - - - - - %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n - - - - - - - - \ No newline at end of file diff --git a/spring-remoting-modules/remoting-jms/remoting-jms-server/src/test/java/com/baeldung/SpringContextLiveTest.java b/spring-remoting-modules/remoting-jms/remoting-jms-server/src/test/java/com/baeldung/SpringContextLiveTest.java deleted file mode 100644 index 4904873be2..0000000000 --- a/spring-remoting-modules/remoting-jms/remoting-jms-server/src/test/java/com/baeldung/SpringContextLiveTest.java +++ /dev/null @@ -1,23 +0,0 @@ -package com.baeldung; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.test.context.junit4.SpringRunner; - -import com.baeldung.server.JmsServer; - -/** - * This Live Test requires: - * * the `com.baeldung:remoting-http-api:jar:1.0-SNAPSHOT` artifact accessible. For that we can run `mvn clean install` in the 'spring-remoting/remoting-http/remoting-http-api' module. - * * an ActiveMQ instance running (e.g. `docker run -p 61616:61616 -p 8161:8161 --name bael-activemq rmohr/activemq`) - * - */ -@SpringBootTest(classes = JmsServer.class) -@RunWith(SpringRunner.class) -public class SpringContextLiveTest { - - @Test - public void whenSpringContextIsBootstrapped_thenNoExceptions() { - } -} diff --git a/spring-remoting-modules/remoting-rmi/README.md b/spring-remoting-modules/remoting-rmi/README.md deleted file mode 100644 index 082b5c37ed..0000000000 --- a/spring-remoting-modules/remoting-rmi/README.md +++ /dev/null @@ -1,7 +0,0 @@ -## Remoting RMI - -This module contains articles about Spring Remoting with Remote Method Invocation (RMI) - -### Relevant Articles: - -- [Spring Remoting with RMI](https://www.baeldung.com/spring-remoting-rmi) \ No newline at end of file diff --git a/spring-remoting-modules/remoting-rmi/pom.xml b/spring-remoting-modules/remoting-rmi/pom.xml deleted file mode 100644 index aece04a64f..0000000000 --- a/spring-remoting-modules/remoting-rmi/pom.xml +++ /dev/null @@ -1,21 +0,0 @@ - - - 4.0.0 - remoting-rmi - remoting-rmi - pom - - - com.baeldung - spring-remoting-modules - 1.0-SNAPSHOT - - - - remoting-rmi-server - remoting-rmi-client - - - \ No newline at end of file diff --git a/spring-remoting-modules/remoting-rmi/remoting-rmi-client/pom.xml b/spring-remoting-modules/remoting-rmi/remoting-rmi-client/pom.xml deleted file mode 100644 index 91630a88e9..0000000000 --- a/spring-remoting-modules/remoting-rmi/remoting-rmi-client/pom.xml +++ /dev/null @@ -1,33 +0,0 @@ - - - 4.0.0 - remoting-rmi-client - remoting-rmi-client - - - com.baeldung - remoting-rmi - 1.0-SNAPSHOT - - - - - org.springframework.boot - spring-boot-starter-activemq - - - org.springframework.boot - spring-boot-starter-tomcat - - - - - com.baeldung - remoting-http-api - ${project.version} - - - - \ No newline at end of file diff --git a/spring-remoting-modules/remoting-rmi/remoting-rmi-client/src/main/java/com/baeldung/client/RmiClient.java b/spring-remoting-modules/remoting-rmi/remoting-rmi-client/src/main/java/com/baeldung/client/RmiClient.java deleted file mode 100644 index a568b749f9..0000000000 --- a/spring-remoting-modules/remoting-rmi/remoting-rmi-client/src/main/java/com/baeldung/client/RmiClient.java +++ /dev/null @@ -1,26 +0,0 @@ -package com.baeldung.client; - -import com.baeldung.api.Booking; -import com.baeldung.api.BookingException; -import com.baeldung.api.CabBookingService; -import org.springframework.boot.SpringApplication; -import org.springframework.boot.autoconfigure.SpringBootApplication; -import org.springframework.context.annotation.Bean; -import org.springframework.remoting.rmi.RmiProxyFactoryBean; - -@SpringBootApplication public class RmiClient { - - @Bean RmiProxyFactoryBean service() { - RmiProxyFactoryBean rmiProxyFactory = new RmiProxyFactoryBean(); - rmiProxyFactory.setServiceUrl("rmi://localhost:1099/CabBookingService"); - rmiProxyFactory.setServiceInterface(CabBookingService.class); - return rmiProxyFactory; - } - - public static void main(String[] args) throws BookingException { - CabBookingService service = SpringApplication.run(RmiClient.class, args).getBean(CabBookingService.class); - Booking bookingOutcome = service.bookRide("13 Seagate Blvd, Key Largo, FL 33037"); - System.out.println(bookingOutcome); - } - -} diff --git a/spring-remoting-modules/remoting-rmi/remoting-rmi-client/src/main/resources/logback.xml b/spring-remoting-modules/remoting-rmi/remoting-rmi-client/src/main/resources/logback.xml deleted file mode 100644 index 7d900d8ea8..0000000000 --- a/spring-remoting-modules/remoting-rmi/remoting-rmi-client/src/main/resources/logback.xml +++ /dev/null @@ -1,13 +0,0 @@ - - - - - %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n - - - - - - - - \ No newline at end of file diff --git a/spring-remoting-modules/remoting-rmi/remoting-rmi-client/src/test/java/com/baeldung/SpringContextLiveTest.java b/spring-remoting-modules/remoting-rmi/remoting-rmi-client/src/test/java/com/baeldung/SpringContextLiveTest.java deleted file mode 100644 index 73f7592dcc..0000000000 --- a/spring-remoting-modules/remoting-rmi/remoting-rmi-client/src/test/java/com/baeldung/SpringContextLiveTest.java +++ /dev/null @@ -1,23 +0,0 @@ -package com.baeldung; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.test.context.junit4.SpringRunner; - -import com.baeldung.client.RmiClient; - -/** - * This Live Test requires: - * * the `com.baeldung:remoting-http-api:jar:1.0-SNAPSHOT` artifact accessible. For that we can run `mvn clean install` in the 'spring-remoting/remoting-http/remoting-http-api' module. - * * the 'spring-remoting\remoting-rmi\remoting-rmi-server' service running - * - */ -@SpringBootTest(classes = RmiClient.class) -@RunWith(SpringRunner.class) -public class SpringContextLiveTest { - - @Test - public void whenSpringContextIsBootstrapped_thenNoExceptions() { - } -} diff --git a/spring-remoting-modules/remoting-rmi/remoting-rmi-server/pom.xml b/spring-remoting-modules/remoting-rmi/remoting-rmi-server/pom.xml deleted file mode 100644 index ecf57018ec..0000000000 --- a/spring-remoting-modules/remoting-rmi/remoting-rmi-server/pom.xml +++ /dev/null @@ -1,33 +0,0 @@ - - - 4.0.0 - remoting-rmi-server - remoting-rmi-server - - - com.baeldung - remoting-rmi - 1.0-SNAPSHOT - - - - - org.springframework.boot - spring-boot-starter-web - - - org.springframework.boot - spring-boot-starter-tomcat - - - - - com.baeldung - remoting-http-api - ${project.version} - - - - \ No newline at end of file diff --git a/spring-remoting-modules/remoting-rmi/remoting-rmi-server/src/main/java/com/baeldung/server/CabBookingServiceImpl.java b/spring-remoting-modules/remoting-rmi/remoting-rmi-server/src/main/java/com/baeldung/server/CabBookingServiceImpl.java deleted file mode 100644 index 55ec9c5733..0000000000 --- a/spring-remoting-modules/remoting-rmi/remoting-rmi-server/src/main/java/com/baeldung/server/CabBookingServiceImpl.java +++ /dev/null @@ -1,16 +0,0 @@ -package com.baeldung.server; - -import com.baeldung.api.Booking; -import com.baeldung.api.BookingException; -import com.baeldung.api.CabBookingService; - -import static java.lang.Math.random; -import static java.util.UUID.randomUUID; - -public class CabBookingServiceImpl implements CabBookingService { - - @Override public Booking bookRide(String pickUpLocation) throws BookingException { - if (random() < 0.3) throw new BookingException("Cab unavailable"); - return new Booking(randomUUID().toString()); - } -} diff --git a/spring-remoting-modules/remoting-rmi/remoting-rmi-server/src/main/java/com/baeldung/server/RmiServer.java b/spring-remoting-modules/remoting-rmi/remoting-rmi-server/src/main/java/com/baeldung/server/RmiServer.java deleted file mode 100644 index 7778c65e85..0000000000 --- a/spring-remoting-modules/remoting-rmi/remoting-rmi-server/src/main/java/com/baeldung/server/RmiServer.java +++ /dev/null @@ -1,34 +0,0 @@ -package com.baeldung.server; - -import com.baeldung.api.CabBookingService; -import org.springframework.boot.SpringApplication; -import org.springframework.boot.autoconfigure.SpringBootApplication; -import org.springframework.context.annotation.Bean; -import org.springframework.remoting.rmi.RmiServiceExporter; - -@SpringBootApplication public class RmiServer { - - @Bean CabBookingService bookingService() { - return new CabBookingServiceImpl(); - } - - @Bean RmiServiceExporter exporter(CabBookingService implementation) { - - // Expose a service via RMI. Remote obect URL is: - // rmi://:/ - // 1099 is the default port - - Class serviceInterface = CabBookingService.class; - RmiServiceExporter exporter = new RmiServiceExporter(); - exporter.setServiceInterface(serviceInterface); - exporter.setService(implementation); - exporter.setServiceName(serviceInterface.getSimpleName()); - exporter.setRegistryPort(1099); - return exporter; - } - - public static void main(String[] args) { - SpringApplication.run(RmiServer.class, args); - } - -} diff --git a/spring-remoting-modules/remoting-rmi/remoting-rmi-server/src/main/resources/logback.xml b/spring-remoting-modules/remoting-rmi/remoting-rmi-server/src/main/resources/logback.xml deleted file mode 100644 index 7d900d8ea8..0000000000 --- a/spring-remoting-modules/remoting-rmi/remoting-rmi-server/src/main/resources/logback.xml +++ /dev/null @@ -1,13 +0,0 @@ - - - - - %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n - - - - - - - - \ No newline at end of file diff --git a/spring-remoting-modules/remoting-rmi/remoting-rmi-server/src/test/java/org/baeldung/SpringContextTest.java b/spring-remoting-modules/remoting-rmi/remoting-rmi-server/src/test/java/org/baeldung/SpringContextTest.java deleted file mode 100644 index 6cae1b66fc..0000000000 --- a/spring-remoting-modules/remoting-rmi/remoting-rmi-server/src/test/java/org/baeldung/SpringContextTest.java +++ /dev/null @@ -1,17 +0,0 @@ -package org.baeldung; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.test.context.junit4.SpringRunner; - -import com.baeldung.server.RmiServer; - -@SpringBootTest(classes = RmiServer.class) -@RunWith(SpringRunner.class) -public class SpringContextTest { - - @Test - public void whenSpringContextIsBootstrapped_thenNoExceptions() { - } -} diff --git a/spring-rest-full/.gitignore b/spring-rest-full/.gitignore deleted file mode 100644 index 83c05e60c8..0000000000 --- a/spring-rest-full/.gitignore +++ /dev/null @@ -1,13 +0,0 @@ -*.class - -#folders# -/target -/neoDb* -/data -/src/main/webapp/WEB-INF/classes -*/META-INF/* - -# Packaged files # -*.jar -*.war -*.ear \ No newline at end of file diff --git a/spring-rest-full/README.md b/spring-rest-full/README.md deleted file mode 100644 index a0ba8df27d..0000000000 --- a/spring-rest-full/README.md +++ /dev/null @@ -1,37 +0,0 @@ -## Spring REST Full - -This module contains articles about REST APIs with Spring - -### Courses - -The "REST With Spring" Classes: http://bit.ly/restwithspring - -The "Learn Spring Security" Classes: http://github.learnspringsecurity.com - -### Relevant Articles: -- [Integration Testing with the Maven Cargo plugin](https://www.baeldung.com/integration-testing-with-the-maven-cargo-plugin) -- [Project Configuration with Spring](https://www.baeldung.com/project-configuration-with-spring) -- [Metrics for your Spring REST API](https://www.baeldung.com/spring-rest-api-metrics) -- [Spring Security Expressions - hasRole Example](https://www.baeldung.com/spring-security-expressions-basic) - - -### Build the Project -``` -mvn clean install -``` - - -### Set up MySQL -``` -mysql -u root -p -> CREATE USER 'tutorialuser'@'localhost' IDENTIFIED BY 'tutorialmy5ql'; -> GRANT ALL PRIVILEGES ON *.* TO 'tutorialuser'@'localhost'; -> FLUSH PRIVILEGES; -``` - - -### Use the REST Service - -``` -curl http://localhost:8082/spring-rest-full/auth/foos -``` diff --git a/spring-rest-full/pom.xml b/spring-rest-full/pom.xml deleted file mode 100644 index 5bc3a70ed5..0000000000 --- a/spring-rest-full/pom.xml +++ /dev/null @@ -1,297 +0,0 @@ - - 4.0.0 - com.baeldung - spring-rest-full - 0.1-SNAPSHOT - spring-rest-full - war - - - parent-boot-2 - com.baeldung - 0.0.1-SNAPSHOT - ../parent-boot-2 - - - - - - - org.springframework.boot - spring-boot-starter-web - - - org.springframework.boot - spring-boot-starter-actuator - - - org.aspectj - aspectjweaver - - - org.apache.tomcat.embed - tomcat-embed-jasper - provided - - - - - - org.springframework - spring-core - - - commons-logging - commons-logging - - - - - org.springframework - spring-context - - - org.springframework - spring-jdbc - - - org.springframework - spring-beans - - - org.springframework - spring-aop - - - org.springframework - spring-tx - - - org.springframework - spring-expression - - - org.springframework - spring-web - - - org.springframework - spring-webmvc - - - org.springframework.data - spring-data-commons - - - - - - org.springframework.boot - spring-boot-starter-tomcat - - - - - - org.apache.httpcomponents - httpclient - - - commons-logging - commons-logging - - - - - org.apache.httpcomponents - httpcore - - - - - - org.springframework - spring-orm - - - org.springframework.data - spring-data-jpa - - - org.hibernate - hibernate-entitymanager - - - xml-apis - xml-apis - - - org.javassist - javassist - ${javassist.version} - - - mysql - mysql-connector-java - runtime - - - com.h2database - h2 - - - - - - javax.servlet - javax.servlet-api - provided - - - javax.servlet - jstl - runtime - - - - - com.fasterxml.jackson.core - jackson-databind - - - - - - com.google.guava - guava - ${guava.version} - - - - - - org.springframework - spring-test - test - - - - - - - - - org.hamcrest - hamcrest-library - test - - - - org.mockito - mockito-core - test - - - - - - spring-rest-full - - - src/main/resources - true - - - - - org.apache.maven.plugins - maven-war-plugin - - - org.codehaus.cargo - cargo-maven2-plugin - ${cargo-maven2-plugin.version} - - true - - jetty8x - embedded - - - - - - - 8082 - - - - - - - com.mysema.maven - apt-maven-plugin - ${apt-maven-plugin.version} - - - - process - - - target/generated-sources/java - com.querydsl.apt.jpa.JPAAnnotationProcessor - - - - - - - - - - live - - - - org.codehaus.cargo - cargo-maven2-plugin - - false - - - - start-server - pre-integration-test - - start - - - - stop-server - post-integration-test - - stop - - - - - - - - - - - - 1.4.9 - - - 19.0 - 3.25.0-GA - - - 1.6.1 - 1.1.3 - - - \ No newline at end of file diff --git a/spring-rest-full/src/main/java/org/baeldung/persistence/IOperations.java b/spring-rest-full/src/main/java/org/baeldung/persistence/IOperations.java deleted file mode 100644 index 0b617bf7ab..0000000000 --- a/spring-rest-full/src/main/java/org/baeldung/persistence/IOperations.java +++ /dev/null @@ -1,22 +0,0 @@ -package org.baeldung.persistence; - -import java.io.Serializable; -import java.util.List; - -public interface IOperations { - - // read - one - - T findOne(final long id); - - // read - all - - List findAll(); - - // write - - T create(final T entity); - - T update(final T entity); - -} diff --git a/spring-rest-full/src/main/java/org/baeldung/persistence/dao/IFooDao.java b/spring-rest-full/src/main/java/org/baeldung/persistence/dao/IFooDao.java deleted file mode 100644 index 230abd0d5f..0000000000 --- a/spring-rest-full/src/main/java/org/baeldung/persistence/dao/IFooDao.java +++ /dev/null @@ -1,11 +0,0 @@ -package org.baeldung.persistence.dao; - -import org.baeldung.persistence.model.Foo; -import org.springframework.data.jpa.repository.JpaRepository; -import org.springframework.data.jpa.repository.Query; -import org.springframework.data.repository.query.Param; -public interface IFooDao extends JpaRepository { - - @Query("SELECT f FROM Foo f WHERE LOWER(f.name) = LOWER(:name)") - Foo retrieveByName(@Param("name") String name); -} diff --git a/spring-rest-full/src/main/java/org/baeldung/persistence/model/Foo.java b/spring-rest-full/src/main/java/org/baeldung/persistence/model/Foo.java deleted file mode 100644 index 8e1dee33e8..0000000000 --- a/spring-rest-full/src/main/java/org/baeldung/persistence/model/Foo.java +++ /dev/null @@ -1,83 +0,0 @@ -package org.baeldung.persistence.model; - -import java.io.Serializable; - -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; - -@Entity -public class Foo implements Serializable { - - @Id - @GeneratedValue(strategy = GenerationType.AUTO) - private long id; - - @Column(nullable = false) - private String name; - - public Foo() { - super(); - } - - public Foo(final String name) { - super(); - - this.name = name; - } - - // API - - public long getId() { - return id; - } - - public void setId(final long id) { - this.id = id; - } - - public String getName() { - return name; - } - - public void setName(final String name) { - this.name = name; - } - - // - - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + ((name == null) ? 0 : name.hashCode()); - return result; - } - - @Override - public boolean equals(final Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (getClass() != obj.getClass()) - return false; - final Foo other = (Foo) obj; - if (name == null) { - if (other.name != null) - return false; - } else if (!name.equals(other.name)) - return false; - return true; - } - - @Override - public String toString() { - final StringBuilder builder = new StringBuilder(); - builder.append("Foo [name=").append(name).append("]"); - return builder.toString(); - } - -} diff --git a/spring-rest-full/src/main/java/org/baeldung/persistence/model/User.java b/spring-rest-full/src/main/java/org/baeldung/persistence/model/User.java deleted file mode 100644 index 670d4a2e74..0000000000 --- a/spring-rest-full/src/main/java/org/baeldung/persistence/model/User.java +++ /dev/null @@ -1,94 +0,0 @@ -package org.baeldung.persistence.model; - -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; - -@Entity -public class User { - - @Id - @GeneratedValue(strategy = GenerationType.AUTO) - private Long id; - - private String firstName; - - private String lastName; - - private String email; - - private int age; - - public User() { - super(); - } - - public Long getId() { - return id; - } - - public void setId(final Long id) { - this.id = id; - } - - public String getFirstName() { - return firstName; - } - - public void setFirstName(final String firstName) { - this.firstName = firstName; - } - - public String getLastName() { - return lastName; - } - - public void setLastName(final String lastName) { - this.lastName = lastName; - } - - public String getEmail() { - return email; - } - - public void setEmail(final String username) { - email = username; - } - - public int getAge() { - return age; - } - - public void setAge(final int age) { - this.age = age; - } - - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + ((email == null) ? 0 : email.hashCode()); - return result; - } - - @Override - public boolean equals(final Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (getClass() != obj.getClass()) - return false; - final User user = (User) obj; - return email.equals(user.email); - } - - @Override - public String toString() { - final StringBuilder builder = new StringBuilder(); - builder.append("User [firstName=").append(firstName).append("]").append("[lastName=").append(lastName).append("]").append("[username").append(email).append("]"); - return builder.toString(); - } - -} \ No newline at end of file diff --git a/spring-rest-full/src/main/java/org/baeldung/persistence/service/IFooService.java b/spring-rest-full/src/main/java/org/baeldung/persistence/service/IFooService.java deleted file mode 100644 index 60d607b9ef..0000000000 --- a/spring-rest-full/src/main/java/org/baeldung/persistence/service/IFooService.java +++ /dev/null @@ -1,10 +0,0 @@ -package org.baeldung.persistence.service; - -import org.baeldung.persistence.IOperations; -import org.baeldung.persistence.model.Foo; - -public interface IFooService extends IOperations { - - Foo retrieveByName(String name); - -} diff --git a/spring-rest-full/src/main/java/org/baeldung/persistence/service/common/AbstractService.java b/spring-rest-full/src/main/java/org/baeldung/persistence/service/common/AbstractService.java deleted file mode 100644 index ceefbbe0e3..0000000000 --- a/spring-rest-full/src/main/java/org/baeldung/persistence/service/common/AbstractService.java +++ /dev/null @@ -1,45 +0,0 @@ -package org.baeldung.persistence.service.common; - -import java.io.Serializable; -import java.util.List; - -import org.baeldung.persistence.IOperations; -import org.springframework.data.repository.PagingAndSortingRepository; -import org.springframework.transaction.annotation.Transactional; - -import com.google.common.collect.Lists; - -@Transactional -public abstract class AbstractService implements IOperations { - - // read - one - - @Override - @Transactional(readOnly = true) - public T findOne(final long id) { - return getDao().findById(id).orElse(null); - } - - // read - all - - @Override - @Transactional(readOnly = true) - public List findAll() { - return Lists.newArrayList(getDao().findAll()); - } - - // write - - @Override - public T create(final T entity) { - return getDao().save(entity); - } - - @Override - public T update(final T entity) { - return getDao().save(entity); - } - - protected abstract PagingAndSortingRepository getDao(); - -} diff --git a/spring-rest-full/src/main/java/org/baeldung/persistence/service/impl/FooService.java b/spring-rest-full/src/main/java/org/baeldung/persistence/service/impl/FooService.java deleted file mode 100644 index 32fe1bd7e0..0000000000 --- a/spring-rest-full/src/main/java/org/baeldung/persistence/service/impl/FooService.java +++ /dev/null @@ -1,37 +0,0 @@ -package org.baeldung.persistence.service.impl; - -import org.baeldung.persistence.dao.IFooDao; -import org.baeldung.persistence.model.Foo; -import org.baeldung.persistence.service.IFooService; -import org.baeldung.persistence.service.common.AbstractService; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.data.repository.PagingAndSortingRepository; -import org.springframework.stereotype.Service; -import org.springframework.transaction.annotation.Transactional; - -@Service -@Transactional -public class FooService extends AbstractService implements IFooService { - - @Autowired - private IFooDao dao; - - public FooService() { - super(); - } - - // API - - @Override - protected PagingAndSortingRepository getDao() { - return dao; - } - - // custom methods - - @Override - public Foo retrieveByName(final String name) { - return dao.retrieveByName(name); - } - -} diff --git a/spring-rest-full/src/main/java/org/baeldung/spring/Application.java b/spring-rest-full/src/main/java/org/baeldung/spring/Application.java deleted file mode 100644 index ca72a4ef56..0000000000 --- a/spring-rest-full/src/main/java/org/baeldung/spring/Application.java +++ /dev/null @@ -1,41 +0,0 @@ -package org.baeldung.spring; - -import javax.servlet.ServletContext; -import javax.servlet.ServletException; - -import org.springframework.boot.SpringApplication; -import org.springframework.boot.autoconfigure.EnableAutoConfiguration; -import org.springframework.boot.autoconfigure.SpringBootApplication; -import org.springframework.boot.builder.SpringApplicationBuilder; -import org.springframework.boot.web.servlet.support.SpringBootServletInitializer; -import org.springframework.context.annotation.ComponentScan; -import org.springframework.scheduling.annotation.EnableScheduling; -import org.springframework.web.context.request.RequestContextListener; - -/** - * Main Application Class - uses Spring Boot. Just run this as a normal Java - * class to run up a Jetty Server (on http://localhost:8082/spring-rest-full) - * - */ -@EnableScheduling -@EnableAutoConfiguration -@ComponentScan("org.baeldung") -@SpringBootApplication -public class Application extends SpringBootServletInitializer { - - @Override - protected SpringApplicationBuilder configure(SpringApplicationBuilder application) { - return application.sources(Application.class); - } - - @Override - public void onStartup(ServletContext sc) throws ServletException { - // Manages the lifecycle of the root application context - sc.addListener(new RequestContextListener()); - } - - public static void main(final String[] args) { - SpringApplication.run(Application.class, args); - } - -} \ No newline at end of file diff --git a/spring-rest-full/src/main/java/org/baeldung/spring/PersistenceConfig.java b/spring-rest-full/src/main/java/org/baeldung/spring/PersistenceConfig.java deleted file mode 100644 index f3a87b189e..0000000000 --- a/spring-rest-full/src/main/java/org/baeldung/spring/PersistenceConfig.java +++ /dev/null @@ -1,85 +0,0 @@ -package org.baeldung.spring; - -import java.util.Properties; - -import javax.sql.DataSource; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.ComponentScan; -import org.springframework.context.annotation.Configuration; -import org.springframework.context.annotation.PropertySource; -import org.springframework.core.env.Environment; -import org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor; -import org.springframework.data.jpa.repository.config.EnableJpaRepositories; -import org.springframework.jdbc.datasource.DriverManagerDataSource; -import org.springframework.orm.jpa.JpaTransactionManager; -import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean; -import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter; -import org.springframework.transaction.PlatformTransactionManager; -import org.springframework.transaction.annotation.EnableTransactionManagement; - -import com.google.common.base.Preconditions; - -@Configuration -@EnableTransactionManagement -@PropertySource({ "classpath:persistence-${envTarget:h2}.properties" }) -@ComponentScan({ "org.baeldung.persistence" }) -// @ImportResource("classpath*:springDataPersistenceConfig.xml") -@EnableJpaRepositories(basePackages = "org.baeldung.persistence.dao") -public class PersistenceConfig { - - @Autowired - private Environment env; - - public PersistenceConfig() { - super(); - } - - @Bean - public LocalContainerEntityManagerFactoryBean entityManagerFactory() { - final LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean(); - em.setDataSource(dataSource()); - em.setPackagesToScan(new String[] { "org.baeldung.persistence.model" }); - - final HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter(); - // vendorAdapter.set - em.setJpaVendorAdapter(vendorAdapter); - em.setJpaProperties(additionalProperties()); - - return em; - } - - @Bean - public DataSource dataSource() { - final DriverManagerDataSource dataSource = new DriverManagerDataSource(); - dataSource.setDriverClassName(Preconditions.checkNotNull(env.getProperty("jdbc.driverClassName"))); - dataSource.setUrl(Preconditions.checkNotNull(env.getProperty("jdbc.url"))); - dataSource.setUsername(Preconditions.checkNotNull(env.getProperty("jdbc.user"))); - dataSource.setPassword(Preconditions.checkNotNull(env.getProperty("jdbc.pass"))); - - return dataSource; - } - - @Bean - public PlatformTransactionManager transactionManager() { - final JpaTransactionManager transactionManager = new JpaTransactionManager(); - transactionManager.setEntityManagerFactory(entityManagerFactory().getObject()); - - return transactionManager; - } - - @Bean - public PersistenceExceptionTranslationPostProcessor exceptionTranslation() { - return new PersistenceExceptionTranslationPostProcessor(); - } - - final Properties additionalProperties() { - final Properties hibernateProperties = new Properties(); - hibernateProperties.setProperty("hibernate.hbm2ddl.auto", env.getProperty("hibernate.hbm2ddl.auto")); - hibernateProperties.setProperty("hibernate.dialect", env.getProperty("hibernate.dialect")); - // hibernateProperties.setProperty("hibernate.globally_quoted_identifiers", "true"); - return hibernateProperties; - } - -} \ No newline at end of file diff --git a/spring-rest-full/src/main/java/org/baeldung/spring/WebConfig.java b/spring-rest-full/src/main/java/org/baeldung/spring/WebConfig.java deleted file mode 100644 index a0db08d93d..0000000000 --- a/spring-rest-full/src/main/java/org/baeldung/spring/WebConfig.java +++ /dev/null @@ -1,36 +0,0 @@ -package org.baeldung.spring; - -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.ComponentScan; -import org.springframework.context.annotation.Configuration; -import org.springframework.web.servlet.ViewResolver; -import org.springframework.web.servlet.config.annotation.EnableWebMvc; -import org.springframework.web.servlet.config.annotation.ViewControllerRegistry; -import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; -import org.springframework.web.servlet.view.InternalResourceViewResolver; - -@Configuration -@ComponentScan("org.baeldung.web") -@EnableWebMvc -public class WebConfig implements WebMvcConfigurer { - - public WebConfig() { - super(); - } - - @Bean - public ViewResolver viewResolver() { - final InternalResourceViewResolver viewResolver = new InternalResourceViewResolver(); - viewResolver.setPrefix("/WEB-INF/view/"); - viewResolver.setSuffix(".jsp"); - return viewResolver; - } - - // API - @Override - public void addViewControllers(final ViewControllerRegistry registry) { - registry.addViewController("/graph.html"); - registry.addViewController("/homepage.html"); - } - -} \ No newline at end of file diff --git a/spring-rest-full/src/main/java/org/baeldung/web/controller/FooController.java b/spring-rest-full/src/main/java/org/baeldung/web/controller/FooController.java deleted file mode 100644 index caaf422410..0000000000 --- a/spring-rest-full/src/main/java/org/baeldung/web/controller/FooController.java +++ /dev/null @@ -1,80 +0,0 @@ -package org.baeldung.web.controller; - -import java.util.List; - -import javax.servlet.http.HttpServletResponse; - -import org.baeldung.persistence.model.Foo; -import org.baeldung.persistence.service.IFooService; -import org.baeldung.web.util.RestPreconditions; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.http.HttpStatus; -import org.springframework.http.MediaType; -import org.springframework.stereotype.Controller; -import org.springframework.web.bind.annotation.PathVariable; -import org.springframework.web.bind.annotation.RequestBody; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestMethod; -import org.springframework.web.bind.annotation.ResponseBody; -import org.springframework.web.bind.annotation.ResponseStatus; - -import com.google.common.base.Preconditions; - -@Controller -@RequestMapping(value = "/auth/foos") -public class FooController { - - @Autowired - private IFooService service; - - public FooController() { - super(); - } - - // API - - @RequestMapping(method = RequestMethod.GET, value = "/count") - @ResponseBody - @ResponseStatus(value = HttpStatus.OK) - public long count() { - return 2l; - } - - // read - one - - @RequestMapping(value = "/{id}", method = RequestMethod.GET) - @ResponseBody - public Foo findById(@PathVariable("id") final Long id, final HttpServletResponse response) { - final Foo resourceById = RestPreconditions.checkFound(service.findOne(id)); - - return resourceById; - } - - // read - all - - @RequestMapping(method = RequestMethod.GET) - @ResponseBody - public List findAll() { - return service.findAll(); - } - - // write - - @RequestMapping(method = RequestMethod.POST) - @ResponseStatus(HttpStatus.CREATED) - @ResponseBody - public Foo create(@RequestBody final Foo resource, final HttpServletResponse response) { - Preconditions.checkNotNull(resource); - final Foo foo = service.create(resource); - - return foo; - } - - @RequestMapping(method = RequestMethod.HEAD) - @ResponseStatus(HttpStatus.OK) - public void head(final HttpServletResponse resp) { - resp.setContentType(MediaType.APPLICATION_JSON_VALUE); - resp.setHeader("bar", "baz"); - } - -} diff --git a/spring-rest-full/src/main/java/org/baeldung/web/controller/HomeController.java b/spring-rest-full/src/main/java/org/baeldung/web/controller/HomeController.java deleted file mode 100644 index 9c4d14cae3..0000000000 --- a/spring-rest-full/src/main/java/org/baeldung/web/controller/HomeController.java +++ /dev/null @@ -1,14 +0,0 @@ -package org.baeldung.web.controller; - -import org.springframework.stereotype.Controller; -import org.springframework.web.bind.annotation.RequestMapping; - -@Controller -@RequestMapping(value = "/") -public class HomeController { - - public String index() { - return "homepage"; - } - -} diff --git a/spring-rest-full/src/main/java/org/baeldung/web/controller/RootController.java b/spring-rest-full/src/main/java/org/baeldung/web/controller/RootController.java deleted file mode 100644 index a66f3d1893..0000000000 --- a/spring-rest-full/src/main/java/org/baeldung/web/controller/RootController.java +++ /dev/null @@ -1,52 +0,0 @@ -package org.baeldung.web.controller; - -import java.util.Map; - -import org.baeldung.web.metric.IActuatorMetricService; -import org.baeldung.web.metric.IMetricService; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Controller; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestMethod; -import org.springframework.web.bind.annotation.ResponseBody; - -@Controller -@RequestMapping(value = "/auth/") -public class RootController { - - @Autowired - private IMetricService metricService; - - @Autowired - private IActuatorMetricService actMetricService; - - public RootController() { - super(); - } - - // API - - @RequestMapping(value = "/metric", method = RequestMethod.GET) - @ResponseBody - public Map getMetric() { - return metricService.getFullMetric(); - } - - @RequestMapping(value = "/status-metric", method = RequestMethod.GET) - @ResponseBody - public Map getStatusMetric() { - return metricService.getStatusMetric(); - } - - @RequestMapping(value = "/metric-graph", method = RequestMethod.GET) - @ResponseBody - public Object[][] drawMetric() { - final Object[][] result = metricService.getGraphData(); - for (int i = 1; i < result[0].length; i++) { - result[0][i] = result[0][i].toString(); - } - return result; - } - - -} diff --git a/spring-rest-full/src/main/java/org/baeldung/web/exception/MyResourceNotFoundException.java b/spring-rest-full/src/main/java/org/baeldung/web/exception/MyResourceNotFoundException.java deleted file mode 100644 index 14b61f9832..0000000000 --- a/spring-rest-full/src/main/java/org/baeldung/web/exception/MyResourceNotFoundException.java +++ /dev/null @@ -1,21 +0,0 @@ -package org.baeldung.web.exception; - -public final class MyResourceNotFoundException extends RuntimeException { - - public MyResourceNotFoundException() { - super(); - } - - public MyResourceNotFoundException(final String message, final Throwable cause) { - super(message, cause); - } - - public MyResourceNotFoundException(final String message) { - super(message); - } - - public MyResourceNotFoundException(final Throwable cause) { - super(cause); - } - -} diff --git a/spring-rest-full/src/main/java/org/baeldung/web/metric/ActuatorMetricService.java b/spring-rest-full/src/main/java/org/baeldung/web/metric/ActuatorMetricService.java deleted file mode 100644 index 4dcec17b9e..0000000000 --- a/spring-rest-full/src/main/java/org/baeldung/web/metric/ActuatorMetricService.java +++ /dev/null @@ -1,110 +0,0 @@ -package org.baeldung.web.metric; - -import java.text.SimpleDateFormat; -import java.util.ArrayList; -import java.util.Date; -import java.util.List; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.scheduling.annotation.Scheduled; -import org.springframework.stereotype.Service; - -import io.micrometer.core.instrument.Counter; -import io.micrometer.core.instrument.Meter; -import io.micrometer.core.instrument.MeterRegistry; - -@Service -public class ActuatorMetricService implements IActuatorMetricService { - - @Autowired - private MeterRegistry publicMetrics; - - private final List> statusMetricsByMinute; - private final List statusList; - private static final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm"); - - public ActuatorMetricService() { - super(); - statusMetricsByMinute = new ArrayList>(); - statusList = new ArrayList(); - } - - @Override - public Object[][] getGraphData() { - final Date current = new Date(); - final int colCount = statusList.size() + 1; - final int rowCount = statusMetricsByMinute.size() + 1; - final Object[][] result = new Object[rowCount][colCount]; - result[0][0] = "Time"; - int j = 1; - - for (final String status : statusList) { - result[0][j] = status; - j++; - } - - for (int i = 1; i < rowCount; i++) { - result[i][0] = dateFormat.format(new Date(current.getTime() - (60000 * (rowCount - i)))); - } - - List minuteOfStatuses; - List last = new ArrayList(); - - for (int i = 1; i < rowCount; i++) { - minuteOfStatuses = statusMetricsByMinute.get(i - 1); - for (j = 1; j <= minuteOfStatuses.size(); j++) { - result[i][j] = minuteOfStatuses.get(j - 1) - (last.size() >= j ? last.get(j - 1) : 0); - } - while (j < colCount) { - result[i][j] = 0; - j++; - } - last = minuteOfStatuses; - } - return result; - } - - // Non - API - - @Scheduled(fixedDelay = 60000) - private void exportMetrics() { - final ArrayList lastMinuteStatuses = initializeStatuses(statusList.size()); - - for (final Meter counterMetric : publicMetrics.getMeters()) { - updateMetrics(counterMetric, lastMinuteStatuses); - } - - statusMetricsByMinute.add(lastMinuteStatuses); - } - - private ArrayList initializeStatuses(final int size) { - final ArrayList counterList = new ArrayList(); - for (int i = 0; i < size; i++) { - counterList.add(0); - } - return counterList; - } - - private void updateMetrics(final Meter counterMetric, final ArrayList statusCount) { - String status = ""; - int index = -1; - int oldCount = 0; - - if (counterMetric.getId().getName().contains("counter.status.")) { - status = counterMetric.getId().getName().substring(15, 18); // example 404, 200 - appendStatusIfNotExist(status, statusCount); - index = statusList.indexOf(status); - oldCount = statusCount.get(index) == null ? 0 : statusCount.get(index); - statusCount.set(index, (int)((Counter) counterMetric).count() + oldCount); - } - } - - private void appendStatusIfNotExist(final String status, final ArrayList statusCount) { - if (!statusList.contains(status)) { - statusList.add(status); - statusCount.add(0); - } - } - - // -} \ No newline at end of file diff --git a/spring-rest-full/src/main/java/org/baeldung/web/metric/CustomActuatorMetricService.java b/spring-rest-full/src/main/java/org/baeldung/web/metric/CustomActuatorMetricService.java deleted file mode 100644 index cf30686e52..0000000000 --- a/spring-rest-full/src/main/java/org/baeldung/web/metric/CustomActuatorMetricService.java +++ /dev/null @@ -1,92 +0,0 @@ -package org.baeldung.web.metric; - -import java.text.SimpleDateFormat; -import java.util.ArrayList; -import java.util.Date; -import java.util.List; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.scheduling.annotation.Scheduled; -import org.springframework.stereotype.Service; - -import io.micrometer.core.instrument.Counter; -import io.micrometer.core.instrument.MeterRegistry; -import io.micrometer.core.instrument.search.Search; - -@Service -public class CustomActuatorMetricService implements ICustomActuatorMetricService { - - @Autowired - private MeterRegistry registry; - - private final List> statusMetricsByMinute; - private final List statusList; - private static final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm"); - - public CustomActuatorMetricService() { - super(); - statusMetricsByMinute = new ArrayList>(); - statusList = new ArrayList(); - } - - // API - - @Override - public void increaseCount(final int status) { - String counterName = "counter.status." + status; - registry.counter(counterName).increment(1); - if (!statusList.contains(counterName)) { - statusList.add(counterName); - } - } - - @Override - public Object[][] getGraphData() { - final Date current = new Date(); - final int colCount = statusList.size() + 1; - final int rowCount = statusMetricsByMinute.size() + 1; - final Object[][] result = new Object[rowCount][colCount]; - result[0][0] = "Time"; - - int j = 1; - for (final String status : statusList) { - result[0][j] = status; - j++; - } - - for (int i = 1; i < rowCount; i++) { - result[i][0] = dateFormat.format(new Date(current.getTime() - (60000 * (rowCount - i)))); - } - - List minuteOfStatuses; - for (int i = 1; i < rowCount; i++) { - minuteOfStatuses = statusMetricsByMinute.get(i - 1); - for (j = 1; j <= minuteOfStatuses.size(); j++) { - result[i][j] = minuteOfStatuses.get(j - 1); - } - while (j < colCount) { - result[i][j] = 0; - j++; - } - } - return result; - } - - // Non - API - - @Scheduled(fixedDelay = 60000) - private void exportMetrics() { - final ArrayList statusCount = new ArrayList(); - for (final String status : statusList) { - Search search = registry.find(status); - if (search != null) { - Counter counter = search.counter(); - statusCount.add(counter != null ? ((int) counter.count()) : 0); - registry.remove(counter); - } else { - statusCount.add(0); - } - } - statusMetricsByMinute.add(statusCount); - } -} \ No newline at end of file diff --git a/spring-rest-full/src/main/java/org/baeldung/web/metric/IActuatorMetricService.java b/spring-rest-full/src/main/java/org/baeldung/web/metric/IActuatorMetricService.java deleted file mode 100644 index 191d347070..0000000000 --- a/spring-rest-full/src/main/java/org/baeldung/web/metric/IActuatorMetricService.java +++ /dev/null @@ -1,5 +0,0 @@ -package org.baeldung.web.metric; - -public interface IActuatorMetricService { - Object[][] getGraphData(); -} diff --git a/spring-rest-full/src/main/java/org/baeldung/web/metric/ICustomActuatorMetricService.java b/spring-rest-full/src/main/java/org/baeldung/web/metric/ICustomActuatorMetricService.java deleted file mode 100644 index 19ab7164ac..0000000000 --- a/spring-rest-full/src/main/java/org/baeldung/web/metric/ICustomActuatorMetricService.java +++ /dev/null @@ -1,8 +0,0 @@ -package org.baeldung.web.metric; - -public interface ICustomActuatorMetricService { - - void increaseCount(final int status); - - Object[][] getGraphData(); -} diff --git a/spring-rest-full/src/main/java/org/baeldung/web/metric/IMetricService.java b/spring-rest-full/src/main/java/org/baeldung/web/metric/IMetricService.java deleted file mode 100644 index 902d6ac811..0000000000 --- a/spring-rest-full/src/main/java/org/baeldung/web/metric/IMetricService.java +++ /dev/null @@ -1,14 +0,0 @@ -package org.baeldung.web.metric; - -import java.util.Map; - -public interface IMetricService { - - void increaseCount(final String request, final int status); - - Map getFullMetric(); - - Map getStatusMetric(); - - Object[][] getGraphData(); -} diff --git a/spring-rest-full/src/main/java/org/baeldung/web/metric/MetricFilter.java b/spring-rest-full/src/main/java/org/baeldung/web/metric/MetricFilter.java deleted file mode 100644 index 6c2fb0cb39..0000000000 --- a/spring-rest-full/src/main/java/org/baeldung/web/metric/MetricFilter.java +++ /dev/null @@ -1,49 +0,0 @@ -package org.baeldung.web.metric; - -import javax.servlet.Filter; -import javax.servlet.FilterChain; -import javax.servlet.FilterConfig; -import javax.servlet.ServletException; -import javax.servlet.ServletRequest; -import javax.servlet.ServletResponse; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Component; -import org.springframework.web.context.support.WebApplicationContextUtils; - -@Component -public class MetricFilter implements Filter { - - @Autowired - private IMetricService metricService; - - @Autowired - private ICustomActuatorMetricService actMetricService; - - @Override - public void init(final FilterConfig config) throws ServletException { - if (metricService == null || actMetricService == null) { - metricService = (IMetricService) WebApplicationContextUtils.getRequiredWebApplicationContext(config.getServletContext()).getBean("metricService"); - actMetricService = WebApplicationContextUtils.getRequiredWebApplicationContext(config.getServletContext()).getBean(CustomActuatorMetricService.class); - } - } - - @Override - public void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain) throws java.io.IOException, ServletException { - final HttpServletRequest httpRequest = ((HttpServletRequest) request); - final String req = httpRequest.getMethod() + " " + httpRequest.getRequestURI(); - - chain.doFilter(request, response); - - final int status = ((HttpServletResponse) response).getStatus(); - metricService.increaseCount(req, status); - actMetricService.increaseCount(status); - } - - @Override - public void destroy() { - - } -} diff --git a/spring-rest-full/src/main/java/org/baeldung/web/metric/MetricService.java b/spring-rest-full/src/main/java/org/baeldung/web/metric/MetricService.java deleted file mode 100644 index 086068ad8f..0000000000 --- a/spring-rest-full/src/main/java/org/baeldung/web/metric/MetricService.java +++ /dev/null @@ -1,122 +0,0 @@ -package org.baeldung.web.metric; - -import java.text.SimpleDateFormat; -import java.util.Date; -import java.util.Map; -import java.util.Map.Entry; -import java.util.Set; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.ConcurrentMap; - -import org.springframework.stereotype.Service; - -@Service -public class MetricService implements IMetricService { - - private ConcurrentMap> metricMap; - private ConcurrentMap statusMetric; - private ConcurrentMap> timeMap; - private static final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm"); - - public MetricService() { - super(); - metricMap = new ConcurrentHashMap>(); - statusMetric = new ConcurrentHashMap(); - timeMap = new ConcurrentHashMap>(); - } - - // API - - @Override - public void increaseCount(final String request, final int status) { - increaseMainMetric(request, status); - increaseStatusMetric(status); - updateTimeMap(status); - } - - @Override - public Map getFullMetric() { - return metricMap; - } - - @Override - public Map getStatusMetric() { - return statusMetric; - } - - @Override - public Object[][] getGraphData() { - final int colCount = statusMetric.keySet().size() + 1; - final Set allStatus = statusMetric.keySet(); - final int rowCount = timeMap.keySet().size() + 1; - - final Object[][] result = new Object[rowCount][colCount]; - result[0][0] = "Time"; - - int j = 1; - for (final int status : allStatus) { - result[0][j] = status; - j++; - } - int i = 1; - ConcurrentMap tempMap; - for (final Entry> entry : timeMap.entrySet()) { - result[i][0] = entry.getKey(); - tempMap = entry.getValue(); - for (j = 1; j < colCount; j++) { - result[i][j] = tempMap.get(result[0][j]); - if (result[i][j] == null) { - result[i][j] = 0; - } - } - i++; - } - - return result; - } - - // NON-API - - private void increaseMainMetric(final String request, final int status) { - ConcurrentHashMap statusMap = metricMap.get(request); - if (statusMap == null) { - statusMap = new ConcurrentHashMap(); - } - - Integer count = statusMap.get(status); - if (count == null) { - count = 1; - } else { - count++; - } - statusMap.put(status, count); - metricMap.put(request, statusMap); - } - - private void increaseStatusMetric(final int status) { - final Integer statusCount = statusMetric.get(status); - if (statusCount == null) { - statusMetric.put(status, 1); - } else { - statusMetric.put(status, statusCount + 1); - } - } - - private void updateTimeMap(final int status) { - final String time = dateFormat.format(new Date()); - ConcurrentHashMap statusMap = timeMap.get(time); - if (statusMap == null) { - statusMap = new ConcurrentHashMap(); - } - - Integer count = statusMap.get(status); - if (count == null) { - count = 1; - } else { - count++; - } - statusMap.put(status, count); - timeMap.put(time, statusMap); - } - -} diff --git a/spring-rest-full/src/main/java/org/baeldung/web/util/RestPreconditions.java b/spring-rest-full/src/main/java/org/baeldung/web/util/RestPreconditions.java deleted file mode 100644 index 4f2dedcfa0..0000000000 --- a/spring-rest-full/src/main/java/org/baeldung/web/util/RestPreconditions.java +++ /dev/null @@ -1,48 +0,0 @@ -package org.baeldung.web.util; - -import org.springframework.http.HttpStatus; - -import org.baeldung.web.exception.MyResourceNotFoundException; - -/** - * Simple static methods to be called at the start of your own methods to verify correct arguments and state. If the Precondition fails, an {@link HttpStatus} code is thrown - */ -public final class RestPreconditions { - - private RestPreconditions() { - throw new AssertionError(); - } - - // API - - /** - * Check if some value was found, otherwise throw exception. - * - * @param expression - * has value true if found, otherwise false - * @throws MyResourceNotFoundException - * if expression is false, means value not found. - */ - public static void checkFound(final boolean expression) { - if (!expression) { - throw new MyResourceNotFoundException(); - } - } - - /** - * Check if some value was found, otherwise throw exception. - * - * @param resource - * has value not null to be returned, otherwise throw exception - * @throws MyResourceNotFoundException - * if resource is null, means value not found. - */ - public static T checkFound(final T resource) { - if (resource == null) { - throw new MyResourceNotFoundException(); - } - - return resource; - } - -} diff --git a/spring-rest-full/src/main/resources/application.properties b/spring-rest-full/src/main/resources/application.properties deleted file mode 100644 index 52d93b4cff..0000000000 --- a/spring-rest-full/src/main/resources/application.properties +++ /dev/null @@ -1,3 +0,0 @@ -server.port=8082 -server.servlet.context-path=/spring-rest-full -endpoints.metrics.enabled=true \ No newline at end of file diff --git a/spring-rest-full/src/main/resources/logback.xml b/spring-rest-full/src/main/resources/logback.xml deleted file mode 100644 index 56af2d397e..0000000000 --- a/spring-rest-full/src/main/resources/logback.xml +++ /dev/null @@ -1,19 +0,0 @@ - - - - - %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n - - - - - - - - - - - - - - \ No newline at end of file diff --git a/spring-rest-full/src/main/resources/persistence-h2.properties b/spring-rest-full/src/main/resources/persistence-h2.properties deleted file mode 100644 index 839a466533..0000000000 --- a/spring-rest-full/src/main/resources/persistence-h2.properties +++ /dev/null @@ -1,22 +0,0 @@ -## jdbc.X -#jdbc.driverClassName=com.mysql.jdbc.Driver -#jdbc.url=jdbc:mysql://localhost:3306/spring_hibernate4_01?createDatabaseIfNotExist=true -#jdbc.user=tutorialuser -#jdbc.pass=tutorialmy5ql -# -## hibernate.X -#hibernate.dialect=org.hibernate.dialect.MySQL5Dialect -#hibernate.show_sql=false -#hibernate.hbm2ddl.auto=create-drop - - -# jdbc.X -jdbc.driverClassName=org.h2.Driver -jdbc.url=jdbc:h2:mem:security_permission;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE -jdbc.user=sa -jdbc.pass= - -# hibernate.X -hibernate.dialect=org.hibernate.dialect.H2Dialect -hibernate.show_sql=false -hibernate.hbm2ddl.auto=create-drop diff --git a/spring-rest-full/src/main/resources/persistence-mysql.properties b/spring-rest-full/src/main/resources/persistence-mysql.properties deleted file mode 100644 index 8263b0d9ac..0000000000 --- a/spring-rest-full/src/main/resources/persistence-mysql.properties +++ /dev/null @@ -1,10 +0,0 @@ -# jdbc.X -jdbc.driverClassName=com.mysql.jdbc.Driver -jdbc.url=jdbc:mysql://localhost:3306/spring_hibernate4_01?createDatabaseIfNotExist=true -jdbc.user=tutorialuser -jdbc.pass=tutorialmy5ql - -# hibernate.X -hibernate.dialect=org.hibernate.dialect.MySQL5Dialect -hibernate.show_sql=false -hibernate.hbm2ddl.auto=create-drop diff --git a/spring-rest-full/src/main/resources/springDataPersistenceConfig.xml b/spring-rest-full/src/main/resources/springDataPersistenceConfig.xml deleted file mode 100644 index d6d0ec6e47..0000000000 --- a/spring-rest-full/src/main/resources/springDataPersistenceConfig.xml +++ /dev/null @@ -1,12 +0,0 @@ - - - - - - \ No newline at end of file diff --git a/spring-rest-full/src/main/webapp/WEB-INF/api-servlet.xml b/spring-rest-full/src/main/webapp/WEB-INF/api-servlet.xml deleted file mode 100644 index 4ba9642448..0000000000 --- a/spring-rest-full/src/main/webapp/WEB-INF/api-servlet.xml +++ /dev/null @@ -1,6 +0,0 @@ - - - - \ No newline at end of file diff --git a/spring-rest-full/src/main/webapp/WEB-INF/view/graph.jsp b/spring-rest-full/src/main/webapp/WEB-INF/view/graph.jsp deleted file mode 100644 index e1d5fdc987..0000000000 --- a/spring-rest-full/src/main/webapp/WEB-INF/view/graph.jsp +++ /dev/null @@ -1,43 +0,0 @@ -<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%> - - -Metric Graph - - - - - -
- - \ No newline at end of file diff --git a/spring-rest-full/src/main/webapp/WEB-INF/view/homepage.jsp b/spring-rest-full/src/main/webapp/WEB-INF/view/homepage.jsp deleted file mode 100644 index 7cc14b5dcd..0000000000 --- a/spring-rest-full/src/main/webapp/WEB-INF/view/homepage.jsp +++ /dev/null @@ -1,7 +0,0 @@ - - - - -

This is the body of the sample view

- - \ No newline at end of file diff --git a/spring-rest-full/src/main/webapp/WEB-INF/web.xml b/spring-rest-full/src/main/webapp/WEB-INF/web.xml deleted file mode 100644 index 5f90c3519f..0000000000 --- a/spring-rest-full/src/main/webapp/WEB-INF/web.xml +++ /dev/null @@ -1,52 +0,0 @@ - - - - Spring REST Application - - - - contextClass - - org.springframework.web.context.support.AnnotationConfigWebApplicationContext - - - - contextConfigLocation - org.baeldung.spring - - - - org.springframework.web.context.ContextLoaderListener - - - - - api - org.springframework.web.servlet.DispatcherServlet - 1 - - - api - / - - - - - metricFilter - org.baeldung.web.metric.MetricFilter - - - - metricFilter - /* - - - - index.html - - - \ No newline at end of file diff --git a/spring-rest-full/src/test/java/org/baeldung/Consts.java b/spring-rest-full/src/test/java/org/baeldung/Consts.java deleted file mode 100644 index e5f0be160f..0000000000 --- a/spring-rest-full/src/test/java/org/baeldung/Consts.java +++ /dev/null @@ -1,5 +0,0 @@ -package org.baeldung; - -public interface Consts { - int APPLICATION_PORT = 8082; -} diff --git a/spring-rest-full/src/test/java/org/baeldung/SpringContextIntegrationTest.java b/spring-rest-full/src/test/java/org/baeldung/SpringContextIntegrationTest.java deleted file mode 100644 index 35939c992f..0000000000 --- a/spring-rest-full/src/test/java/org/baeldung/SpringContextIntegrationTest.java +++ /dev/null @@ -1,16 +0,0 @@ -package org.baeldung; - -import org.baeldung.spring.Application; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.test.context.junit4.SpringRunner; - -@RunWith(SpringRunner.class) -@SpringBootTest(classes = Application.class) -public class SpringContextIntegrationTest { - - @Test - public void whenSpringContextIsBootstrapped_thenNoExceptions() { - } -} diff --git a/spring-rest-full/src/test/java/org/baeldung/SpringContextTest.java b/spring-rest-full/src/test/java/org/baeldung/SpringContextTest.java deleted file mode 100644 index 8debddc40a..0000000000 --- a/spring-rest-full/src/test/java/org/baeldung/SpringContextTest.java +++ /dev/null @@ -1,16 +0,0 @@ -package org.baeldung; - -import org.baeldung.spring.Application; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.test.context.junit4.SpringRunner; - -@RunWith(SpringRunner.class) -@SpringBootTest(classes = Application.class) -public class SpringContextTest { - - @Test - public void whenSpringContextIsBootstrapped_thenNoExceptions() { - } -} diff --git a/spring-rest-full/src/test/java/org/baeldung/persistence/PersistenceTestSuite.java b/spring-rest-full/src/test/java/org/baeldung/persistence/PersistenceTestSuite.java deleted file mode 100644 index fb0fd00bb5..0000000000 --- a/spring-rest-full/src/test/java/org/baeldung/persistence/PersistenceTestSuite.java +++ /dev/null @@ -1,16 +0,0 @@ -package org.baeldung.persistence; - -import org.baeldung.persistence.service.FooServicePersistenceIntegrationTest; -import org.junit.runner.RunWith; -import org.junit.runners.Suite; - -@RunWith(Suite.class) -@Suite.SuiteClasses({ - // @formatter:off - - FooServicePersistenceIntegrationTest.class - -}) // -public class PersistenceTestSuite { - -} diff --git a/spring-rest-full/src/test/java/org/baeldung/persistence/service/AbstractServicePersistenceIntegrationTest.java b/spring-rest-full/src/test/java/org/baeldung/persistence/service/AbstractServicePersistenceIntegrationTest.java deleted file mode 100644 index 79889e0f9e..0000000000 --- a/spring-rest-full/src/test/java/org/baeldung/persistence/service/AbstractServicePersistenceIntegrationTest.java +++ /dev/null @@ -1,255 +0,0 @@ -package org.baeldung.persistence.service; - -import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic; -import static org.hamcrest.Matchers.hasItem; -import static org.hamcrest.Matchers.not; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertThat; - -import java.io.Serializable; -import java.util.List; - -import org.baeldung.persistence.IOperations; -import org.baeldung.persistence.model.Foo; -import org.baeldung.util.IDUtil; -import org.hamcrest.Matchers; -import org.junit.Ignore; -import org.junit.Test; -import org.springframework.dao.DataAccessException; - -public abstract class AbstractServicePersistenceIntegrationTest { - - // tests - - // find - one - - @Test - /**/public final void givenResourceDoesNotExist_whenResourceIsRetrieved_thenNoResourceIsReceived() { - // When - final Foo createdResource = getApi().findOne(IDUtil.randomPositiveLong()); - - // Then - assertNull(createdResource); - } - - @Test - public void givenResourceExists_whenResourceIsRetrieved_thenNoExceptions() { - final Foo existingResource = persistNewEntity(); - getApi().findOne(existingResource.getId()); - } - - @Test - public void givenResourceDoesNotExist_whenResourceIsRetrieved_thenNoExceptions() { - getApi().findOne(IDUtil.randomPositiveLong()); - } - - @Test - public void givenResourceExists_whenResourceIsRetrieved_thenTheResultIsNotNull() { - final Foo existingResource = persistNewEntity(); - final Foo retrievedResource = getApi().findOne(existingResource.getId()); - assertNotNull(retrievedResource); - } - - @Test - public void givenResourceExists_whenResourceIsRetrieved_thenResourceIsRetrievedCorrectly() { - final Foo existingResource = persistNewEntity(); - final Foo retrievedResource = getApi().findOne(existingResource.getId()); - assertEquals(existingResource, retrievedResource); - } - - // find - one - by name - - // find - all - - @Test - /**/public void whenAllResourcesAreRetrieved_thenNoExceptions() { - getApi().findAll(); - } - - @Test - /**/public void whenAllResourcesAreRetrieved_thenTheResultIsNotNull() { - final List resources = getApi().findAll(); - - assertNotNull(resources); - } - - @Test - /**/public void givenAtLeastOneResourceExists_whenAllResourcesAreRetrieved_thenRetrievedResourcesAreNotEmpty() { - persistNewEntity(); - - // When - final List allResources = getApi().findAll(); - - // Then - assertThat(allResources, not(Matchers. empty())); - } - - @Test - /**/public void givenAnResourceExists_whenAllResourcesAreRetrieved_thenTheExistingResourceIsIndeedAmongThem() { - final Foo existingResource = persistNewEntity(); - - final List resources = getApi().findAll(); - - assertThat(resources, hasItem(existingResource)); - } - - @Test - /**/public void whenAllResourcesAreRetrieved_thenResourcesHaveIds() { - persistNewEntity(); - - // When - final List allResources = getApi().findAll(); - - // Then - for (final Foo resource : allResources) { - assertNotNull(resource.getId()); - } - } - - // create - - @Test(expected = RuntimeException.class) - /**/public void whenNullResourceIsCreated_thenException() { - getApi().create(null); - } - - @Test - /**/public void whenResourceIsCreated_thenNoExceptions() { - persistNewEntity(); - } - - @Test - /**/public void whenResourceIsCreated_thenResourceIsRetrievable() { - final Foo existingResource = persistNewEntity(); - - assertNotNull(getApi().findOne(existingResource.getId())); - } - - @Test - /**/public void whenResourceIsCreated_thenSavedResourceIsEqualToOriginalResource() { - final Foo originalResource = createNewEntity(); - final Foo savedResource = getApi().create(originalResource); - - assertEquals(originalResource, savedResource); - } - - @Test(expected = RuntimeException.class) - public void whenResourceWithFailedConstraintsIsCreated_thenException() { - final Foo invalidResource = createNewEntity(); - invalidate(invalidResource); - - getApi().create(invalidResource); - } - - /** - * -- specific to the persistence engine - */ - @Test(expected = DataAccessException.class) - @Ignore("Hibernate simply ignores the id silently and still saved (tracking this)") - public void whenResourceWithIdIsCreated_thenDataAccessException() { - final Foo resourceWithId = createNewEntity(); - resourceWithId.setId(IDUtil.randomPositiveLong()); - - getApi().create(resourceWithId); - } - - // update - - @Test(expected = RuntimeException.class) - /**/public void whenNullResourceIsUpdated_thenException() { - getApi().update(null); - } - - @Test - /**/public void givenResourceExists_whenResourceIsUpdated_thenNoExceptions() { - // Given - final Foo existingResource = persistNewEntity(); - - // When - getApi().update(existingResource); - } - - /** - * - can also be the ConstraintViolationException which now occurs on the update operation will not be translated; as a consequence, it will be a TransactionSystemException - */ - @Test(expected = RuntimeException.class) - public void whenResourceIsUpdatedWithFailedConstraints_thenException() { - final Foo existingResource = persistNewEntity(); - invalidate(existingResource); - - getApi().update(existingResource); - } - - @Test - /**/public void givenResourceExists_whenResourceIsUpdated_thenUpdatesArePersisted() { - // Given - final Foo existingResource = persistNewEntity(); - - // When - change(existingResource); - getApi().update(existingResource); - - final Foo updatedResource = getApi().findOne(existingResource.getId()); - - // Then - assertEquals(existingResource, updatedResource); - } - - // delete - - // @Test(expected = RuntimeException.class) - // public void givenResourceDoesNotExists_whenResourceIsDeleted_thenException() { - // // When - // getApi().delete(IDUtil.randomPositiveLong()); - // } - // - // @Test(expected = RuntimeException.class) - // public void whenResourceIsDeletedByNegativeId_thenException() { - // // When - // getApi().delete(IDUtil.randomNegativeLong()); - // } - // - // @Test - // public void givenResourceExists_whenResourceIsDeleted_thenNoExceptions() { - // // Given - // final Foo existingResource = persistNewEntity(); - // - // // When - // getApi().delete(existingResource.getId()); - // } - // - // @Test - // /**/public final void givenResourceExists_whenResourceIsDeleted_thenResourceNoLongerExists() { - // // Given - // final Foo existingResource = persistNewEntity(); - // - // // When - // getApi().delete(existingResource.getId()); - // - // // Then - // assertNull(getApi().findOne(existingResource.getId())); - // } - - // template method - - protected Foo createNewEntity() { - return new Foo(randomAlphabetic(6)); - } - - protected abstract IOperations getApi(); - - private final void invalidate(final Foo entity) { - entity.setName(null); - } - - private final void change(final Foo entity) { - entity.setName(randomAlphabetic(6)); - } - - protected Foo persistNewEntity() { - return getApi().create(createNewEntity()); - } - -} diff --git a/spring-rest-full/src/test/java/org/baeldung/persistence/service/FooServicePersistenceIntegrationTest.java b/spring-rest-full/src/test/java/org/baeldung/persistence/service/FooServicePersistenceIntegrationTest.java deleted file mode 100644 index 089d2d13a2..0000000000 --- a/spring-rest-full/src/test/java/org/baeldung/persistence/service/FooServicePersistenceIntegrationTest.java +++ /dev/null @@ -1,76 +0,0 @@ -package org.baeldung.persistence.service; - -import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic; -import static org.junit.Assert.assertNotNull; - -import org.baeldung.persistence.IOperations; -import org.baeldung.persistence.model.Foo; -import org.baeldung.spring.PersistenceConfig; -import org.junit.Ignore; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.dao.DataIntegrityViolationException; -import org.springframework.dao.InvalidDataAccessApiUsageException; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import org.springframework.test.context.support.AnnotationConfigContextLoader; - -@RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration(classes = { PersistenceConfig.class }, loader = AnnotationConfigContextLoader.class) -public class FooServicePersistenceIntegrationTest extends AbstractServicePersistenceIntegrationTest { - - @Autowired - private IFooService service; - - // tests - - @Test - public final void whenContextIsBootstrapped_thenNoExceptions() { - // - } - - @Test - public final void whenEntityIsCreated_thenNoExceptions() { - service.create(new Foo(randomAlphabetic(6))); - } - - @Test(expected = DataIntegrityViolationException.class) - public final void whenInvalidEntityIsCreated_thenDataException() { - service.create(new Foo()); - } - - @Test(expected = DataIntegrityViolationException.class) - public final void whenEntityWithLongNameIsCreated_thenDataException() { - service.create(new Foo(randomAlphabetic(2048))); - } - - // custom Query method - - @Test - public final void givenUsingCustomQuery_whenRetrievingEntity_thenFound() { - final String name = randomAlphabetic(6); - service.create(new Foo(name)); - - final Foo retrievedByName = service.retrieveByName(name); - assertNotNull(retrievedByName); - } - - // work in progress - - @Test(expected = InvalidDataAccessApiUsageException.class) - @Ignore("Right now, persist has saveOrUpdate semantics, so this will no longer fail") - public final void whenSameEntityIsCreatedTwice_thenDataException() { - final Foo entity = new Foo(randomAlphabetic(8)); - service.create(entity); - service.create(entity); - } - - // API - - @Override - protected final IOperations getApi() { - return service; - } - -} diff --git a/spring-rest-full/src/test/java/org/baeldung/util/IDUtil.java b/spring-rest-full/src/test/java/org/baeldung/util/IDUtil.java deleted file mode 100644 index 85ab623e5f..0000000000 --- a/spring-rest-full/src/test/java/org/baeldung/util/IDUtil.java +++ /dev/null @@ -1,33 +0,0 @@ -package org.baeldung.util; - -import java.util.Random; - -public final class IDUtil { - - private IDUtil() { - throw new AssertionError(); - } - - // API - - public static String randomPositiveLongAsString() { - return Long.toString(randomPositiveLong()); - } - - public static String randomNegativeLongAsString() { - return Long.toString(randomNegativeLong()); - } - - public static long randomPositiveLong() { - long id = new Random().nextLong() * 10000; - id = (id < 0) ? (-1 * id) : id; - return id; - } - - private static long randomNegativeLong() { - long id = new Random().nextLong() * 10000; - id = (id > 0) ? (-1 * id) : id; - return id; - } - -} diff --git a/spring-rest-full/src/test/resources/.gitignore b/spring-rest-full/src/test/resources/.gitignore deleted file mode 100644 index 83c05e60c8..0000000000 --- a/spring-rest-full/src/test/resources/.gitignore +++ /dev/null @@ -1,13 +0,0 @@ -*.class - -#folders# -/target -/neoDb* -/data -/src/main/webapp/WEB-INF/classes -*/META-INF/* - -# Packaged files # -*.jar -*.war -*.ear \ No newline at end of file diff --git a/spring-rest-full/src/testFile b/spring-rest-full/src/testFile deleted file mode 100644 index 8b13789179..0000000000 --- a/spring-rest-full/src/testFile +++ /dev/null @@ -1 +0,0 @@ -