Skip to content

Commit f2d957e

Browse files
Merge branch 'master' into Mercator
2 parents d66c39b + 29f7181 commit f2d957e

16 files changed

Lines changed: 248 additions & 34 deletions

File tree

‎core-java/README.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -158,3 +158,4 @@
158158
- [Java Switch Statement](https://www.baeldung.com/java-switch)
159159
- [The Modulo Operator in Java](https://www.baeldung.com/modulo-java)
160160
- [Ternary Operator In Java](https://www.baeldung.com/java-ternary-operator)
161+
- [Merging java.util.Properties Objects](https://www.baeldung.com/java-merging-properties)

‎gson/README.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,3 +8,4 @@
88
- [Jackson vs Gson](http://www.baeldung.com/jackson-vs-gson)
99
- [Exclude Fields from Serialization in Gson](http://www.baeldung.com/gson-exclude-fields-serialization)
1010
- [Save Data to a JSON File with Gson](https://www.baeldung.com/gson-save-file)
11+
- [Convert JSON to a Map Using Gson](https://www.baeldung.com/gson-json-to-map)

gson/src/main/java/org/baeldung/gson/serialization/HashMapDeserializer.java renamed to gson/src/main/java/org/baeldung/gson/serialization/MapDeserializer.java

Lines changed: 12 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -4,28 +4,26 @@
44
import java.math.BigDecimal;
55
import java.util.HashMap;
66
import java.util.Map;
7+
import java.util.stream.Collectors;
78

89
import org.baeldung.gson.entities.Employee;
910

1011
import com.google.gson.*;
1112

12-
public class HashMapDeserializer implements JsonDeserializer<HashMap<String, Object>> {
13+
public class MapDeserializer implements JsonDeserializer<Map<String, Object>> {
1314

1415
@Override
15-
public HashMap<String, Object> deserialize(JsonElement elem, Type type, JsonDeserializationContext context) throws JsonParseException {
16-
HashMap<String, Object> map = new HashMap<>();
17-
for (Map.Entry<String, JsonElement> entry : elem.getAsJsonObject().entrySet()) {
18-
JsonElement jsonValue = entry.getValue();
19-
Object value = null;
20-
if (jsonValue.isJsonPrimitive()) {
21-
value = toPrimitive(jsonValue.getAsJsonPrimitive(), context);
22-
} else {
23-
value = context.deserialize(jsonValue, Employee.class);
24-
}
25-
map.put(entry.getKey(), value);
26-
}
27-
return map;
16+
public Map<String, Object> deserialize(JsonElement elem, Type type, JsonDeserializationContext context) throws JsonParseException {
2817

18+
return elem.getAsJsonObject()
19+
.entrySet()
20+
.stream()
21+
.collect(Collectors.toMap(
22+
Map.Entry::getKey,
23+
e -> e.getValue().isJsonPrimitive() ?
24+
toPrimitive(e.getValue().getAsJsonPrimitive(), context)
25+
: context.deserialize(e.getValue(), Employee.class)
26+
));
2927
}
3028

3129
private Object toPrimitive(JsonPrimitive jsonValue, JsonDeserializationContext context) {
Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
package org.baeldung.gson.serialization;
2+
3+
import java.lang.reflect.Type;
4+
import java.text.ParseException;
5+
import java.text.SimpleDateFormat;
6+
import java.util.Date;
7+
import java.util.Map;
8+
import java.util.stream.Collectors;
9+
10+
import org.slf4j.Logger;
11+
import org.slf4j.LoggerFactory;
12+
13+
import com.google.gson.JsonDeserializationContext;
14+
import com.google.gson.JsonDeserializer;
15+
import com.google.gson.JsonElement;
16+
import com.google.gson.JsonParseException;
17+
18+
public class StringDateMapDeserializer implements JsonDeserializer<Map<String, Date>> {
19+
20+
private static final Logger logger = LoggerFactory.getLogger(StringDateMapDeserializer.class);
21+
22+
private SimpleDateFormat format = new SimpleDateFormat("yyyy/MM/dd");
23+
24+
@Override
25+
public Map<String, Date> deserialize(JsonElement elem, Type type, JsonDeserializationContext jsonDeserializationContext) {
26+
System.out.println("Deserializer called");
27+
logger.info("Deserializer called");
28+
return elem.getAsJsonObject()
29+
.entrySet()
30+
.stream()
31+
.filter(e -> e.getValue().isJsonPrimitive())
32+
.filter(e -> e.getValue().getAsJsonPrimitive().isString())
33+
.collect(Collectors.toMap(Map.Entry::getKey, e -> formatDate(e.getValue())));
34+
}
35+
36+
private Date formatDate(JsonElement value) {
37+
try {
38+
return format.parse(value.getAsString());
39+
} catch (ParseException ex) {
40+
throw new JsonParseException(ex);
41+
}
42+
}
43+
44+
}

gson/src/test/java/org/baeldung/gson/deserialization/HashMapDeserializationUnitTest.java renamed to gson/src/test/java/org/baeldung/gson/deserialization/MapDeserializationUnitTest.java

Lines changed: 38 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,14 @@
11
package org.baeldung.gson.deserialization;
22

33
import java.lang.reflect.Type;
4-
import java.util.HashMap;
4+
import java.text.ParseException;
5+
import java.util.Date;
6+
import java.util.Map;
57

8+
import org.apache.commons.lang3.time.DateUtils;
69
import org.baeldung.gson.entities.Employee;
7-
import org.baeldung.gson.serialization.HashMapDeserializer;
10+
import org.baeldung.gson.serialization.MapDeserializer;
11+
import org.baeldung.gson.serialization.StringDateMapDeserializer;
812
import org.junit.Assert;
913
import org.junit.Test;
1014
import org.slf4j.Logger;
@@ -16,18 +20,18 @@
1620
import com.google.gson.internal.LinkedTreeMap;
1721
import com.google.gson.reflect.TypeToken;
1822

19-
public class HashMapDeserializationUnitTest {
23+
public class MapDeserializationUnitTest {
2024

21-
private static final Logger logger = LoggerFactory.getLogger(HashMapDeserializationUnitTest.class);
25+
private static final Logger logger = LoggerFactory.getLogger(MapDeserializationUnitTest.class);
2226

2327
@Test
24-
public void whenUsingHashMapClass_thenShouldReturnMapWithDefaultClasses() {
28+
public void whenUsingMapClass_thenShouldReturnMapWithDefaultClasses() {
2529

2630
String jsonString = "{'employee.name':'Bob','employee.salary':10000, 'employee.active':true, "
2731
+ "'employee':{'id':10, 'name': 'Bob Willis', 'address':'London'}}";
2832

2933
Gson gson = new Gson();
30-
HashMap map = gson.fromJson(jsonString, HashMap.class);
34+
Map map = gson.fromJson(jsonString, Map.class);
3135

3236
logger.info("The converted map: {}", map);
3337
Assert.assertEquals(4, map.size());
@@ -43,7 +47,7 @@ public void whenUsingJsonStringWithDuplicateKey_thenShouldThrowJsonSyntaxExcepti
4347
+ "'employee.active':true, " + "'employee':{'id':10, 'name': 'Bob Willis', 'address':'London'}}";
4448

4549
Gson gson = new Gson();
46-
HashMap map = gson.fromJson(jsonString, HashMap.class);
50+
Map map = gson.fromJson(jsonString, Map.class);
4751

4852
logger.info("The converted map: {}", map);
4953
}
@@ -56,8 +60,8 @@ public void whenUsingTypeToken_thenShouldReturnMapWithProperClass() {
5660
+ "'Steve':{'id':10, 'name': 'Steven Waugh', 'address':'Australia'}}";
5761

5862
Gson gson = new Gson();
59-
Type empMapType = new TypeToken<HashMap<String, Employee>>(){}.getType();
60-
HashMap<String, Employee> nameEmployeeMap = gson.fromJson(jsonString, empMapType);
63+
Type empMapType = new TypeToken<Map<String, Employee>>(){}.getType();
64+
Map<String, Employee> nameEmployeeMap = gson.fromJson(jsonString, empMapType);
6165

6266
logger.info("The converted map: {}", nameEmployeeMap);
6367
Assert.assertEquals(3, nameEmployeeMap.size());
@@ -70,11 +74,11 @@ public void whenUsingCustomDeserializer_thenShouldReturnMapWithProperClass() {
7074
String jsonString = "{'employee.name':'Bob','employee.salary':10000, 'employee.active':true, "
7175
+ "'employee':{'id':10, 'name': 'Bob Willis', 'address':'London'}}";
7276

73-
Type type = new TypeToken<HashMap<String, Object>>(){}.getType();
77+
Type type = new TypeToken<Map<String, Object>>(){}.getType();
7478
Gson gson = new GsonBuilder()
75-
.registerTypeAdapter(type, new HashMapDeserializer())
79+
.registerTypeAdapter(type, new MapDeserializer())
7680
.create();
77-
HashMap<String, Object> blendedMap = gson.fromJson(jsonString, type);
81+
Map<String, Object> blendedMap = gson.fromJson(jsonString, type);
7882

7983
logger.info("The converted map: {}", blendedMap);
8084
Assert.assertEquals(4, blendedMap.size());
@@ -83,4 +87,26 @@ public void whenUsingCustomDeserializer_thenShouldReturnMapWithProperClass() {
8387

8488
}
8589

90+
@Test
91+
public void whenUsingCustomDateDeserializer_thenShouldReturnMapWithDate() {
92+
String jsonString = "{'Bob': '2017/06/01', 'Jennie':'2015/01/03'}";
93+
Type type = new TypeToken<Map<String, Date>>(){}.getType();
94+
Gson gson = new GsonBuilder()
95+
.registerTypeAdapter(type, new StringDateMapDeserializer())
96+
.create();
97+
Map<String, Date> empJoiningDateMap = gson.fromJson(jsonString, type);
98+
99+
logger.info("The converted map: {}", empJoiningDateMap);
100+
logger.info("The map class {}", empJoiningDateMap.getClass());
101+
Assert.assertEquals(2, empJoiningDateMap.size());
102+
Assert.assertEquals(Date.class, empJoiningDateMap.get("Bob").getClass());
103+
Date dt = null;
104+
try {
105+
dt = DateUtils.parseDate("2017-06-01", "yyyy-MM-dd");
106+
Assert.assertEquals(dt, empJoiningDateMap.get("Bob"));
107+
} catch (ParseException e) {
108+
logger.error("Could not parse date", e);
109+
}
110+
}
111+
86112
}

‎helidon/README.md‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
### Relevant articles
2+
3+
- [Microservices with Oracle Helidon](https://www.baeldung.com/microservices-oracle-helidon)

‎lombok/README.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,3 +4,4 @@
44
- [Using Lombok’s @Getter for Boolean Fields](https://www.baeldung.com/lombok-getter-boolean)
55
- [Lombok @Builder with Inheritance](https://www.baeldung.com/lombok-builder-inheritance)
66
- [Lombok Builder with Default Value](https://www.baeldung.com/lombok-builder-default-value)
7+
- [Lombok Builder with Custom Setter](https://www.baeldung.com/lombok-builder-with-custom-setter)
Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
package com.baeldung.lombok.builder.customsetter;
2+
3+
import java.io.File;
4+
import java.util.List;
5+
6+
import lombok.Builder;
7+
import lombok.Data;
8+
9+
@Builder
10+
@Data
11+
public class Message {
12+
private String sender;
13+
private String recipient;
14+
private String text;
15+
private File file;
16+
17+
public static class MessageBuilder {
18+
private String text;
19+
private File file;
20+
21+
public MessageBuilder text(String text) {
22+
this.text = text;
23+
verifyTextOrFile();
24+
return this;
25+
}
26+
27+
public MessageBuilder file(File file) {
28+
this.file = file;
29+
verifyTextOrFile();
30+
return this;
31+
}
32+
33+
private void verifyTextOrFile() {
34+
if (text != null && file != null) {
35+
throw new IllegalStateException("Cannot send 'text' and 'file'.");
36+
}
37+
}
38+
}
39+
}
Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
package com.baeldung.lombok.builder.customsetter;
2+
3+
import java.io.File;
4+
5+
import org.junit.Test;
6+
7+
public class BuilderWithCustomSetterUnitTest {
8+
9+
@Test
10+
public void givenBuilderWithCustomSetter_TestTextOnly() {
11+
Message message = Message.builder()
12+
.sender("user@somedomain.com")
13+
.recipient("someuser@otherdomain.com")
14+
.text("How are you today?")
15+
.build();
16+
}
17+
18+
@Test
19+
public void givenBuilderWithCustomSetter_TestFileOnly() {
20+
Message message = Message.builder()
21+
.sender("user@somedomain.com")
22+
.recipient("someuser@otherdomain.com")
23+
.file(new File("/path/to/file"))
24+
.build();
25+
}
26+
27+
@Test(expected = IllegalStateException.class)
28+
public void givenBuilderWithCustomSetter_TestTextAndFile() {
29+
Message message = Message.builder()
30+
.sender("user@somedomain.com")
31+
.recipient("someuser@otherdomain.com")
32+
.text("How are you today?")
33+
.file(new File("/path/to/file"))
34+
.build();
35+
}
36+
37+
}

‎parent-boot-1/pom.xml‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -43,6 +43,10 @@
4343
<groupId>org.springframework.boot</groupId>
4444
<artifactId>spring-boot-maven-plugin</artifactId>
4545
<version>${spring-boot.version}</version>
46+
<configuration>
47+
<mainClass>${start-class}</mainClass>
48+
<!-- this is necessary as we're not using the Boot parent -->
49+
</configuration>
4650
</plugin>
4751
</plugins>
4852
</pluginManagement>

0 commit comments

Comments
 (0)