Skip to content

Commit fd63d97

Browse files
matejspmikelehen
authored andcommitted
Remove Dependency on org.json:json Artifact (#113), Java 11 build problems (#243) (#242)
* Fix Java 11 build problems (#243) * Remove Dependency on org.json:json Artifact (#113)
1 parent 6b46ded commit fd63d97

File tree

6 files changed

+79
-121
lines changed

6 files changed

+79
-121
lines changed

CHANGELOG.md

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
# Unreleased
22

3-
-
3+
- [changed] Removed org.json dependency and replaced with com.google.code.gson.
4+
- [changed] Upgraded Mockito dependency, and fixed the build on Java 11.
45

56
# v6.7.0
67

pom.xml

Lines changed: 1 addition & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -437,11 +437,6 @@
437437
<artifactId>guava</artifactId>
438438
<version>20.0</version>
439439
</dependency>
440-
<dependency>
441-
<groupId>org.json</groupId>
442-
<artifactId>json</artifactId>
443-
<version>20160810</version>
444-
</dependency>
445440
<dependency>
446441
<groupId>org.slf4j</groupId>
447442
<artifactId>slf4j-api</artifactId>
@@ -467,7 +462,7 @@
467462
<dependency>
468463
<groupId>org.mockito</groupId>
469464
<artifactId>mockito-core</artifactId>
470-
<version>2.7.21</version>
465+
<version>2.23.4</version>
471466
<scope>test</scope>
472467
</dependency>
473468
<dependency>

src/main/java/com/google/firebase/database/util/JsonMapper.java

Lines changed: 58 additions & 80 deletions
Original file line numberDiff line numberDiff line change
@@ -16,123 +16,101 @@
1616

1717
package com.google.firebase.database.util;
1818

19+
import com.google.gson.Gson;
20+
import com.google.gson.GsonBuilder;
21+
import com.google.gson.JsonSyntaxException;
22+
import com.google.gson.stream.JsonReader;
23+
import com.google.gson.stream.JsonToken;
1924
import java.io.IOException;
25+
import java.io.StringReader;
2026
import java.util.ArrayList;
21-
import java.util.Collection;
2227
import java.util.HashMap;
23-
import java.util.Iterator;
2428
import java.util.List;
2529
import java.util.Map;
2630

27-
import org.json.JSONArray;
28-
import org.json.JSONException;
29-
import org.json.JSONObject;
30-
import org.json.JSONStringer;
31-
import org.json.JSONTokener;
32-
3331
/**
3432
* Helper class to convert from/to JSON strings. TODO: This class should ideally not live in
3533
* firebase-database-connection, but it's required by both firebase-database and
3634
* firebase-database-connection, so leave it here for now.
3735
*/
3836
public class JsonMapper {
3937

40-
public static String serializeJson(Map<String, Object> object) throws IOException {
41-
return serializeJsonValue(object);
42-
}
43-
44-
@SuppressWarnings("unchecked")
45-
public static String serializeJsonValue(Object object) throws IOException {
46-
if (object == null) {
47-
return "null";
48-
} else if (object instanceof String) {
49-
return JSONObject.quote((String) object);
50-
} else if (object instanceof Number) {
51-
try {
52-
return JSONObject.numberToString((Number) object);
53-
} catch (JSONException e) {
54-
throw new IOException("Could not serialize number", e);
55-
}
56-
} else if (object instanceof Boolean) {
57-
return ((Boolean) object) ? "true" : "false";
58-
} else {
59-
try {
60-
JSONStringer stringer = new JSONStringer();
61-
serializeJsonValue(object, stringer);
62-
return stringer.toString();
63-
} catch (JSONException e) {
64-
throw new IOException("Failed to serialize JSON", e);
65-
}
66-
}
67-
}
38+
private static final Gson GSON = new GsonBuilder().serializeNulls().create();
6839

69-
private static void serializeJsonValue(Object object, JSONStringer stringer)
70-
throws IOException, JSONException {
71-
if (object instanceof Map) {
72-
stringer.object();
73-
@SuppressWarnings("unchecked")
74-
Map<String, Object> map = (Map<String, Object>) object;
75-
for (Map.Entry<String, Object> entry : map.entrySet()) {
76-
stringer.key(entry.getKey());
77-
serializeJsonValue(entry.getValue(), stringer);
78-
}
79-
stringer.endObject();
80-
} else if (object instanceof Collection) {
81-
Collection<?> collection = (Collection<?>) object;
82-
stringer.array();
83-
for (Object entry : collection) {
84-
serializeJsonValue(entry, stringer);
85-
}
86-
stringer.endArray();
87-
} else {
88-
stringer.value(object);
40+
public static String serializeJson(Object object) throws IOException {
41+
try {
42+
return GSON.toJson(object);
43+
} catch (JsonSyntaxException e) {
44+
throw new IOException(e);
8945
}
9046
}
9147

9248
public static Map<String, Object> parseJson(String json) throws IOException {
9349
try {
94-
return unwrapJsonObject(new JSONObject(json));
95-
} catch (JSONException e) {
50+
JsonReader jsonReader = new JsonReader(new StringReader(json));
51+
return unwrapJsonObject(jsonReader);
52+
} catch (IllegalStateException | JsonSyntaxException e) {
9653
throw new IOException(e);
9754
}
9855
}
9956

10057
public static Object parseJsonValue(String json) throws IOException {
10158
try {
102-
return unwrapJson(new JSONTokener(json).nextValue());
103-
} catch (JSONException e) {
59+
JsonReader jsonReader = new JsonReader(new StringReader(json));
60+
jsonReader.setLenient(true);
61+
return unwrapJson(jsonReader);
62+
} catch (IllegalStateException | JsonSyntaxException e) {
10463
throw new IOException(e);
10564
}
10665
}
10766

108-
@SuppressWarnings("unchecked")
109-
private static Map<String, Object> unwrapJsonObject(JSONObject jsonObject) throws JSONException {
110-
Map<String, Object> map = new HashMap<>(jsonObject.length());
111-
Iterator<String> keys = jsonObject.keys();
112-
while (keys.hasNext()) {
113-
String key = keys.next();
114-
map.put(key, unwrapJson(jsonObject.get(key)));
67+
private static Map<String, Object> unwrapJsonObject(JsonReader jsonReader) throws IOException {
68+
Map<String, Object> map = new HashMap<>();
69+
jsonReader.beginObject();
70+
while (jsonReader.peek() != JsonToken.END_OBJECT) {
71+
String key = jsonReader.nextName();
72+
map.put(key, unwrapJson(jsonReader));
11573
}
74+
jsonReader.endObject();
11675
return map;
11776
}
11877

119-
private static List<Object> unwrapJsonArray(JSONArray jsonArray) throws JSONException {
120-
List<Object> list = new ArrayList<>(jsonArray.length());
121-
for (int i = 0; i < jsonArray.length(); i++) {
122-
list.add(unwrapJson(jsonArray.get(i)));
78+
private static List<Object> unwrapJsonArray(JsonReader jsonReader) throws IOException {
79+
List<Object> list = new ArrayList<>();
80+
jsonReader.beginArray();
81+
while (jsonReader.peek() != JsonToken.END_ARRAY) {
82+
list.add(unwrapJson(jsonReader));
12383
}
84+
jsonReader.endArray();
12485
return list;
12586
}
12687

127-
private static Object unwrapJson(Object o) throws JSONException {
128-
if (o instanceof JSONObject) {
129-
return unwrapJsonObject((JSONObject) o);
130-
} else if (o instanceof JSONArray) {
131-
return unwrapJsonArray((JSONArray) o);
132-
} else if (o.equals(JSONObject.NULL)) {
133-
return null;
134-
} else {
135-
return o;
88+
private static Object unwrapJson(JsonReader jsonReader) throws IOException {
89+
switch (jsonReader.peek()) {
90+
case BEGIN_ARRAY:
91+
return unwrapJsonArray(jsonReader);
92+
case BEGIN_OBJECT:
93+
return unwrapJsonObject(jsonReader);
94+
case STRING:
95+
return jsonReader.nextString();
96+
case NUMBER:
97+
String value = jsonReader.nextString();
98+
if (value.matches("-?\\d+")) {
99+
long longValue = Long.parseLong(value);
100+
if (longValue <= Integer.MAX_VALUE && longValue >= Integer.MIN_VALUE) {
101+
return (int) longValue;
102+
}
103+
return Long.valueOf(value);
104+
}
105+
return Double.parseDouble(value);
106+
case BOOLEAN:
107+
return jsonReader.nextBoolean();
108+
case NULL:
109+
jsonReader.nextNull();
110+
return null;
111+
default:
112+
throw new IllegalStateException("unknown type " + jsonReader.peek());
136113
}
137114
}
115+
138116
}

src/test/java/com/google/firebase/database/connection/WebsocketConnectionTest.java

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -112,9 +112,7 @@ public void testReceiveMultipleFrames() {
112112
public void testIncomingMessageIOError() {
113113
MockClientFactory clientFactory = new MockClientFactory();
114114
ImmutableMap<String, Object> data = ImmutableMap.<String, Object>of("key", "value");
115-
Mockito.doThrow(IOException.class).when(clientFactory.delegate).onMessage(data);
116-
clientFactory.eventHandler.onMessage("{\"key\":\"value\"}");
117-
Mockito.verify(clientFactory.delegate, Mockito.times(1)).onMessage(data);
115+
clientFactory.eventHandler.onMessage("ERR{\"key\":\"value\"}");
118116
Mockito.verify(clientFactory.client, Mockito.times(1)).close();
119117
Mockito.verify(clientFactory.delegate, Mockito.times(1)).onDisconnect(false);
120118
}

src/test/java/com/google/firebase/database/core/JvmAuthTokenProviderTest.java

Lines changed: 8 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,7 @@
3030
import com.google.firebase.FirebaseOptions;
3131
import com.google.firebase.TestOnlyImplFirebaseTrampolines;
3232
import com.google.firebase.auth.MockGoogleCredentials;
33+
import com.google.firebase.database.util.JsonMapper;
3334
import com.google.firebase.testing.TestUtils;
3435

3536
import java.io.IOException;
@@ -46,7 +47,6 @@
4647
import java.util.concurrent.atomic.AtomicInteger;
4748
import java.util.concurrent.atomic.AtomicReference;
4849

49-
import org.json.JSONObject;
5050
import org.junit.After;
5151
import org.junit.Test;
5252

@@ -100,7 +100,7 @@ public void testGetTokenNoRefresh() throws IOException, InterruptedException {
100100
}
101101

102102
@Test
103-
public void testGetTokenWithAuthOverrides() throws InterruptedException {
103+
public void testGetTokenWithAuthOverrides() throws InterruptedException, IOException {
104104
MockGoogleCredentials credentials = new MockGoogleCredentials("mock-token");
105105
Map<String, Object> auth = ImmutableMap.<String, Object>of("uid", "test");
106106
FirebaseOptions options = new FirebaseOptions.Builder()
@@ -226,13 +226,15 @@ public void onChanged(OAuth2Credentials credentials) throws IOException {
226226
assertTrue(semaphore.tryAcquire(TestUtils.TEST_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS));
227227
}
228228

229-
private void assertToken(String token, String expectedToken, Map<String, Object> expectedAuth) {
229+
private void assertToken(String token, String expectedToken, Map<String, Object> expectedAuth)
230+
throws IOException {
230231
assertTrue(token.startsWith("gauth|"));
231232
String jsonString = token.substring(6);
232-
JSONObject json = new JSONObject(jsonString);
233-
assertEquals(expectedToken, json.getString("token"));
233+
Map<String, Object> map = JsonMapper.parseJson(jsonString);
234234

235-
Map<String, Object> auth = json.getJSONObject("auth").toMap();
235+
assertEquals(expectedToken, map.get("token"));
236+
237+
Map<String, Object> auth = (Map)map.get("auth");
236238
DeepEquals.deepEquals(expectedAuth, auth);
237239
}
238240

src/test/java/com/google/firebase/database/util/JsonMapperTest.java

Lines changed: 9 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,6 @@
1717
package com.google.firebase.database.util;
1818

1919
import static org.junit.Assert.assertEquals;
20-
import static org.junit.Assert.assertTrue;
2120
import static org.junit.Assert.fail;
2221

2322
import com.google.common.collect.ImmutableList;
@@ -28,55 +27,42 @@
2827
import java.util.List;
2928
import java.util.Map;
3029

31-
import org.json.JSONException;
32-
import org.junit.Ignore;
3330
import org.junit.Test;
3431

3532
public class JsonMapperTest {
3633

3734
@Test
3835
public void testNull() throws IOException {
39-
assertEquals("null", JsonMapper.serializeJsonValue(null));
36+
assertEquals("null", JsonMapper.serializeJson(null));
4037
}
4138

4239
@Test
4340
public void testString() throws IOException {
44-
assertEquals("\"foo\"", JsonMapper.serializeJsonValue("foo"));
41+
assertEquals("\"foo\"", JsonMapper.serializeJson("foo"));
4542
}
4643

4744
@Test
4845
public void testBoolean() throws IOException {
49-
assertEquals("true", JsonMapper.serializeJsonValue(true));
50-
assertEquals("false", JsonMapper.serializeJsonValue(false));
46+
assertEquals("true", JsonMapper.serializeJson(true));
47+
assertEquals("false", JsonMapper.serializeJson(false));
5148
}
5249

5350
@Test
5451
public void testMap() throws IOException {
55-
assertEquals("{\"foo\":\"bar\"}", JsonMapper.serializeJsonValue(ImmutableMap.of("foo", "bar")));
52+
assertEquals("{\"foo\":\"bar\"}", JsonMapper.serializeJson(ImmutableMap.of("foo", "bar")));
5653
}
5754

5855
@Test
5956
public void testList() throws IOException {
60-
assertEquals("[\"foo\",\"bar\"]", JsonMapper.serializeJsonValue(
57+
assertEquals("[\"foo\",\"bar\"]", JsonMapper.serializeJson(
6158
ImmutableList.of("foo", "bar")));
6259
}
6360

64-
@Test
65-
public void testInvalidObject() {
66-
try {
67-
JsonMapper.serializeJsonValue(new Object());
68-
fail("No error thrown for invalid object");
69-
} catch (IOException expected) {
70-
// expected
71-
assertTrue(expected.getCause() instanceof JSONException);
72-
}
73-
}
74-
7561
@Test
7662
public void canConvertLongs() throws IOException {
7763
List<Long> longs = Arrays.asList(Long.MAX_VALUE, Long.MIN_VALUE);
7864
for (Long original : longs) {
79-
String jsonString = JsonMapper.serializeJsonValue(original);
65+
String jsonString = JsonMapper.serializeJson(original);
8066
long converted = (Long) JsonMapper.parseJsonValue(jsonString);
8167
assertEquals((long) original, converted);
8268
}
@@ -86,15 +72,13 @@ public void canConvertLongs() throws IOException {
8672
public void canConvertDoubles() throws IOException {
8773
List<Double> doubles = Arrays.asList(Double.MAX_VALUE, Double.MIN_VALUE, Double.MIN_NORMAL);
8874
for (Double original : doubles) {
89-
String jsonString = JsonMapper.serializeJsonValue(original);
75+
String jsonString = JsonMapper.serializeJson(original);
9076
double converted = (Double) JsonMapper.parseJsonValue(jsonString);
9177
assertEquals(original, converted, 0);
9278
}
9379
}
9480

9581
@Test
96-
@Ignore
97-
// TODO: Stop ignoring this test once JSON parsing has been fixed.
9882
public void canNest33LevelsDeep() throws IOException {
9983
Map<String, Object> root = new HashMap<>();
10084
Map<String, Object> currentMap = root;
@@ -103,7 +87,7 @@ public void canNest33LevelsDeep() throws IOException {
10387
currentMap.put("key", newMap);
10488
currentMap = newMap;
10589
}
106-
String jsonString = JsonMapper.serializeJsonValue(root);
90+
String jsonString = JsonMapper.serializeJson(root);
10791
Object value = JsonMapper.parseJsonValue(jsonString);
10892
assertEquals(root, value);
10993
}

0 commit comments

Comments
 (0)