Elffuss BraidHub

kikocis/java-driver public

JAVA-742: Codec support for JSON.

This commit introduces two codecs:

- a new JacksonJsonCodec that automatically maps JSON structures to CQL varchar types leveraging the popular Jackson framework.
- a new Jsr353JsonCodec that automatically maps JSON structures to CQL varchar types using JSR 353.
Changeset12354430b10c3bfda0d2d828ed4e283892a154eb3d59b8ecf42299ff0d137800
AuthorAlexandre Dutra <alexandre.dutra@datastax.com> · 2015-10-26 17:36 +01:00
CommitterAlexandre Dutra <alexandre.dutra@datastax.com> · 2015-11-17 14:51 +01:00
Parents56ebe0d224e9

Browse the files at this changeset

10 files changed

modified changelog/README.md +1 −0
@@ -15,6 +15,7 @@
1515 - [improvement] JAVA-917: Document SSL configuration.
1616 - [improvement] JAVA-936: Adapt schema metadata parsing logic to new storage format of CQL types in C* 3.0.
1717 - [new feature] JAVA-846: Provide custom codecs library as an extra module.
18+- [new feature] JAVA-742: Codec Support for JSON.
1819
1920 Merged from 2.1 branch:
2021
deleted driver-core/src/test/java/com/datastax/driver/core/JsonCodec.java +0 −95
@@ -1,95 +0,0 @@
1-/*
2- * Copyright (C) 2012-2015 DataStax Inc.
3- *
4- * Licensed under the Apache License, Version 2.0 (the "License");
5- * you may not use this file except in compliance with the License.
6- * You may obtain a copy of the License at
7- *
8- * http://www.apache.org/licenses/LICENSE-2.0
9- *
10- * Unless required by applicable law or agreed to in writing, software
11- * distributed under the License is distributed on an "AS IS" BASIS,
12- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13- * See the License for the specific language governing permissions and
14- * limitations under the License.
15- */
16-package com.datastax.driver.core;
17-
18-import java.io.IOException;
19-import java.nio.ByteBuffer;
20-
21-import com.fasterxml.jackson.core.JsonProcessingException;
22-import com.fasterxml.jackson.databind.JavaType;
23-import com.fasterxml.jackson.databind.ObjectMapper;
24-import com.fasterxml.jackson.databind.type.TypeFactory;
25-
26-import com.datastax.driver.core.exceptions.InvalidTypeException;
27-import com.datastax.driver.core.utils.Bytes;
28-
29-/**
30- * A simple Json codec for TypeCodec tests that uses Jackson to perform serialization and deserialization.
31- */
32-public class JsonCodec<T> extends TypeCodec<T> {
33-
34- private final ObjectMapper objectMapper = new ObjectMapper();
35-
36- public JsonCodec(Class<T> javaType) {
37- super(DataType.varchar(), javaType);
38- }
39-
40- @Override
41- public ByteBuffer serialize(T value, ProtocolVersion protocolVersion) throws InvalidTypeException {
42- if (value == null)
43- return null;
44- try {
45- return ByteBuffer.wrap(objectMapper.writeValueAsBytes(value));
46- } catch (JsonProcessingException e) {
47- throw new InvalidTypeException(e.getMessage(), e);
48- }
49- }
50-
51- @Override
52- @SuppressWarnings("unchecked")
53- public T deserialize(ByteBuffer bytes, ProtocolVersion protocolVersion) throws InvalidTypeException {
54- if (bytes == null)
55- return null;
56- try {
57- return (T)objectMapper.readValue(Bytes.getArray(bytes), toJacksonJavaType());
58- } catch (IOException e) {
59- throw new InvalidTypeException(e.getMessage(), e);
60- }
61- }
62-
63- @Override
64- public String format(T value) throws InvalidTypeException {
65- if (value == null)
66- return "NULL";
67- String json;
68- try {
69- json = objectMapper.writeValueAsString(value);
70- } catch (IOException e) {
71- throw new InvalidTypeException(e.getMessage(), e);
72- }
73- return '\'' + json.replace("\'", "''") + '\'';
74- }
75-
76- @Override
77- @SuppressWarnings("unchecked")
78- public T parse(String value) throws InvalidTypeException {
79- if (value == null || value.isEmpty() || value.equalsIgnoreCase("NULL"))
80- return null;
81- if (value.charAt(0) != '\'' || value.charAt(value.length() - 1) != '\'')
82- throw new InvalidTypeException("JSON strings must be enclosed by single quotes");
83- String json = value.substring(1, value.length() - 1).replace("''", "'");
84- try {
85- return (T)objectMapper.readValue(json, toJacksonJavaType());
86- } catch (IOException e) {
87- throw new InvalidTypeException(e.getMessage(), e);
88- }
89- }
90-
91- protected JavaType toJacksonJavaType() {
92- return TypeFactory.defaultInstance().constructType(getJavaType().getType());
93- }
94-
95-}
deleted driver-core/src/test/java/com/datastax/driver/core/TypeCodecJsonIntegrationTest.java +0 −154
@@ -1,154 +0,0 @@
1-/*
2- * Copyright (C) 2012-2015 DataStax Inc.
3- *
4- * Licensed under the Apache License, Version 2.0 (the "License");
5- * you may not use this file except in compliance with the License.
6- * You may obtain a copy of the License at
7- *
8- * http://www.apache.org/licenses/LICENSE-2.0
9- *
10- * Unless required by applicable law or agreed to in writing, software
11- * distributed under the License is distributed on an "AS IS" BASIS,
12- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13- * See the License for the specific language governing permissions and
14- * limitations under the License.
15- */
16-package com.datastax.driver.core;
17-
18-import java.util.ArrayList;
19-import java.util.Collection;
20-
21-import com.google.common.collect.Lists;
22-import org.testng.annotations.Test;
23-
24-import static org.assertj.core.api.Assertions.assertThat;
25-
26-import com.datastax.driver.core.TypeCodecTest.User;
27-import com.datastax.driver.core.querybuilder.BuiltStatement;
28-import com.datastax.driver.core.querybuilder.QueryBuilder;
29-import com.datastax.driver.core.utils.CassandraVersion;
30-
31-import static com.datastax.driver.core.querybuilder.QueryBuilder.bindMarker;
32-import static com.datastax.driver.core.querybuilder.QueryBuilder.eq;
33-
34-public class TypeCodecJsonIntegrationTest extends CCMBridge.PerClassSingleNodeCluster {
35-
36- private static final JsonCodec<User> jsonCodec = new JsonCodec<User>(User.class);
37-
38- private static final User alice = new User(1, "Alice");
39- private static final User bob = new User(2, "Bob");
40- private static final User charlie = new User(3, "Charlie");
41-
42- private static final String bobJson = "{\"id\":2,\"name\":\"Bob\"}";
43- private static final String charlieJson = "{\"id\":3,\"name\":\"Charlie\"}";
44- private static final String aliceJson = "{\"id\":1,\"name\":\"Alice\"}";
45-
46- private static final ArrayList<User> bobAndCharlie = Lists.newArrayList(bob, charlie);
47-
48- private static final String insertQuery = "INSERT INTO \"myTable\" (c1, c2, c3) VALUES (?, ?, ?)";
49- private static final String selectQuery = "SELECT c1, c2, c3 FROM \"myTable\" WHERE c1 = ? and c2 = ?";
50-
51- private static final String notAJsonString = "this text is not json";
52-
53- @Override
54- protected Collection<String> getTableDefinitions() {
55- return Lists.newArrayList(
56- "CREATE TABLE \"myTable\" (c1 text, c2 text, c3 list<text>, PRIMARY KEY (c1, c2))"
57- );
58- }
59-
60- @Override
61- protected Cluster.Builder configure(Cluster.Builder builder) {
62- return builder.withCodecRegistry(
63- new CodecRegistry().register(jsonCodec) // global User <-> varchar codec
64- );
65- }
66-
67- @Test(groups = "short")
68- @CassandraVersion(major=2.0)
69- public void should_use_custom_codec_with_simple_statements() {
70- session.execute(insertQuery, notAJsonString, alice, bobAndCharlie);
71- ResultSet rows = session.execute(selectQuery, notAJsonString, alice);
72- Row row = rows.one();
73- assertRow(row);
74- }
75-
76- @Test(groups = "short")
77- public void should_use_custom_codec_with_built_statements_1() {
78- BuiltStatement insertStmt = new QueryBuilder(cluster).insertInto("\"myTable\"")
79- .value("c1", bindMarker())
80- .value("c2", bindMarker())
81- .value("c3", bindMarker());
82- BuiltStatement selectStmt = new QueryBuilder(cluster).select("c1", "c2", "c3")
83- .from("\"myTable\"")
84- .where(eq("c1", bindMarker()))
85- .and(eq("c2", bindMarker()));
86- session.execute(session.prepare(insertStmt).bind(notAJsonString, alice, bobAndCharlie));
87- ResultSet rows = session.execute(session.prepare(selectStmt).bind(notAJsonString, alice));
88- Row row = rows.one();
89- assertRow(row);
90- }
91-
92- @Test(groups = "short")
93- public void should_use_custom_codec_with_built_statements_2() {
94- BuiltStatement insertStmt = new QueryBuilder(cluster).insertInto("\"myTable\"")
95- .value("c1", notAJsonString)
96- .value("c2", alice)
97- .value("c3", bobAndCharlie);
98- BuiltStatement selectStmt =
99- new QueryBuilder(cluster).select("c1", "c2", "c3")
100- .from("\"myTable\"")
101- .where(eq("c1", notAJsonString))
102- .and(eq("c2", alice));
103- session.execute(insertStmt);
104- ResultSet rows = session.execute(selectStmt);
105- Row row = rows.one();
106- assertRow(row);
107- }
108-
109- @Test(groups = "short")
110- public void should_use_custom_codec_with_prepared_statements_1() {
111- session.execute(session.prepare(insertQuery).bind(notAJsonString, alice, bobAndCharlie));
112- PreparedStatement ps = session.prepare(selectQuery);
113- // this bind() method does not convey information about the java type of alice
114- // so the registry will look for a codec accepting varchar <-> ANY
115- // and will find jsonCodec because it is the first registered
116- ResultSet rows = session.execute(ps.bind(notAJsonString, alice));
117- Row row = rows.one();
118- assertRow(row);
119- }
120-
121- @Test(groups = "short")
122- public void should_use_custom_codec_with_prepared_statements_2() {
123- session.execute(session.prepare(insertQuery).bind()
124- .setString(0, notAJsonString)
125- .set(1, alice, User.class)
126- .setList(2, bobAndCharlie, User.class)
127- );
128- PreparedStatement ps = session.prepare(selectQuery);
129- ResultSet rows = session.execute(ps.bind()
130- .setString(0, notAJsonString)
131- // this set() method conveys information about the java type of alice
132- // so the registry will look for a codec accepting varchar <-> User
133- // and will find jsonCodec because it is the only matching one
134- .set(1, alice, User.class)
135- );
136- Row row = rows.one();
137- assertRow(row);
138- }
139-
140- private void assertRow(Row row) {
141- // getString requires a codec accepting varchar <-> String, so VarcharCodec is used
142- assertThat(row.getString(0)).isEqualTo(notAJsonString);
143- // getObject requires a codec accepting varchar <-> ANY;
144- // the first codec that accepts that is jsonCodec, so it is used
145- assertThat(row.getObject(1)).isEqualTo(aliceJson);
146- // getObject uses the default codec VarcharCodec
147- assertThat(row.get(1, User.class)).isEqualTo(alice);
148- // we still can get the column as a string using VarcharCodec.instance behind the scenes
149- assertThat(row.getString(1)).isEqualTo(aliceJson);
150- assertThat(row.getList(2, User.class)).containsExactly(bob, charlie);
151- // we still can get the column as a List<String>
152- assertThat(row.getList(2, String.class)).containsExactly(bobJson, charlieJson);
153- }
154-}
modified driver-core/src/test/java/com/datastax/driver/core/TypeCodecTest.java +1 −62
@@ -18,11 +18,8 @@
1818 import java.nio.ByteBuffer;
1919 import java.util.*;
2020
21-import com.fasterxml.jackson.annotation.JsonCreator;
22-import com.fasterxml.jackson.annotation.JsonProperty;
2321 import com.google.common.base.Function;
2422 import com.google.common.base.Joiner;
25-import com.google.common.base.Objects;
2623 import com.google.common.base.Strings;
2724 import com.google.common.collect.Lists;
2825 import com.google.common.reflect.TypeToken;
@@ -90,18 +87,6 @@
9087 codec.serialize(list, ProtocolVersion.V2);
9188 }
9289
93- @Test(groups = "unit")
94- public void test_cql_text_to_json() {
95- JsonCodec<User> codec = new JsonCodec<User>(User.class);
96- // the codec is expected to format json objects as json strings enclosed in single quotes,
97- // as it is required for CQL literals of varchar type.
98- String json = "'{\"id\":1,\"name\":\"John Doe\"}'";
99- User user = new User(1, "John Doe");
100- assertThat(codec.format(user)).isEqualTo(json);
101- assertThat(codec.parse(json)).isEqualToComparingFieldByField(user);
102- assertThat(codec).canSerialize(user);
103- }
104-
10590 @Test(groups = "unit")
10691 public void test_cql_list_varchar_to_list_list_integer() {
10792 ListVarcharToListListInteger codec = new ListVarcharToListListInteger();
@@ -309,53 +294,7 @@
309294 throw new UnsupportedOperationException();
310295 }
311296 }
312-
313- @SuppressWarnings("unused")
314- public static class User {
315-
316- private int id;
317-
318- private String name;
319-
320- @JsonCreator
321- public User(@JsonProperty("id") int id, @JsonProperty("name") String name) {
322- this.id = id;
323- this.name = name;
324- }
325-
326- public int getId() {
327- return id;
328- }
329-
330- public void setId(int id) {
331- this.id = id;
332- }
333-
334- public String getName() {
335- return name;
336- }
337-
338- public void setName(String name) {
339- this.name = name;
340- }
341-
342- @Override
343- public boolean equals(Object o) {
344- if (this == o)
345- return true;
346- if (o == null || getClass() != o.getClass())
347- return false;
348- User user = (User)o;
349- return Objects.equal(id, user.id) &&
350- Objects.equal(name, user.name);
351- }
352-
353- @Override
354- public int hashCode() {
355- return Objects.hashCode(id, name);
356- }
357- }
358-
297+
359298 class A {
360299
361300 int i = 0;
modified driver-extras/pom.xml +14 −0
@@ -65,6 +65,13 @@
6565 <optional>true</optional>
6666 </dependency>
6767
68+ <dependency>
69+ <groupId>javax.json</groupId>
70+ <artifactId>javax.json-api</artifactId>
71+ <version>1.0</version>
72+ <optional>true</optional>
73+ </dependency>
74+
6875 <dependency>
6976 <groupId>com.datastax.cassandra</groupId>
7077 <artifactId>cassandra-driver-core</artifactId>
@@ -108,6 +115,13 @@
108115 <scope>test</scope>
109116 </dependency>
110117
118+ <dependency>
119+ <groupId>org.glassfish</groupId>
120+ <artifactId>javax.json</artifactId>
121+ <version>1.0.4</version>
122+ <scope>test</scope>
123+ </dependency>
124+
111125 </dependencies>
112126
113127 <build>
added driver-extras/src/main/java/com/datastax/driver/extras/codecs/json/JacksonJsonCodec.java +109 −0
@@ -0,0 +1,109 @@
1+/*
2+ * Copyright (C) 2012-2015 DataStax Inc.
3+ *
4+ * Licensed under the Apache License, Version 2.0 (the "License");
5+ * you may not use this file except in compliance with the License.
6+ * You may obtain a copy of the License at
7+ *
8+ * http://www.apache.org/licenses/LICENSE-2.0
9+ *
10+ * Unless required by applicable law or agreed to in writing, software
11+ * distributed under the License is distributed on an "AS IS" BASIS,
12+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+ * See the License for the specific language governing permissions and
14+ * limitations under the License.
15+ */
16+package com.datastax.driver.extras.codecs.json;
17+
18+import java.io.IOException;
19+import java.nio.ByteBuffer;
20+
21+import com.fasterxml.jackson.core.JsonProcessingException;
22+import com.fasterxml.jackson.databind.JavaType;
23+import com.fasterxml.jackson.databind.ObjectMapper;
24+import com.fasterxml.jackson.databind.type.TypeFactory;
25+
26+import com.datastax.driver.core.DataType;
27+import com.datastax.driver.core.ParseUtils;
28+import com.datastax.driver.core.ProtocolVersion;
29+import com.datastax.driver.core.TypeCodec;
30+import com.datastax.driver.core.exceptions.InvalidTypeException;
31+import com.datastax.driver.core.utils.Bytes;
32+
33+/**
34+ * A JSON codec that uses the <a href="http://wiki.fasterxml.com/JacksonHome">Jackson</a>
35+ * library to perform serialization and deserialization of JSON objects.
36+ * <p>
37+ * Note that this codec maps a single object to a single JSON structure at a time;
38+ * mapping of arrays or collections to root-level JSON arrays is not supported,
39+ * but such a codec can be easily crafted after this one.
40+ */
41+public class JacksonJsonCodec<T> extends TypeCodec<T> {
42+
43+ private final ObjectMapper objectMapper = new ObjectMapper();
44+
45+ public JacksonJsonCodec(Class<T> javaType) {
46+ super(DataType.varchar(), javaType);
47+ }
48+
49+ @Override
50+ public ByteBuffer serialize(T value, ProtocolVersion protocolVersion) throws InvalidTypeException {
51+ if (value == null)
52+ return null;
53+ try {
54+ return ByteBuffer.wrap(objectMapper.writeValueAsBytes(value));
55+ } catch (JsonProcessingException e) {
56+ throw new InvalidTypeException(e.getMessage(), e);
57+ }
58+ }
59+
60+ @Override
61+ @SuppressWarnings("unchecked")
62+ public T deserialize(ByteBuffer bytes, ProtocolVersion protocolVersion) throws InvalidTypeException {
63+ if (bytes == null)
64+ return null;
65+ try {
66+ return (T)objectMapper.readValue(Bytes.getArray(bytes), toJacksonJavaType());
67+ } catch (IOException e) {
68+ throw new InvalidTypeException(e.getMessage(), e);
69+ }
70+ }
71+
72+ @Override
73+ public String format(T value) throws InvalidTypeException {
74+ if (value == null)
75+ return "NULL";
76+ String json;
77+ try {
78+ json = objectMapper.writeValueAsString(value);
79+ } catch (IOException e) {
80+ throw new InvalidTypeException(e.getMessage(), e);
81+ }
82+ return ParseUtils.quote(json);
83+ }
84+
85+ @Override
86+ @SuppressWarnings("unchecked")
87+ public T parse(String value) throws InvalidTypeException {
88+ if (value == null || value.isEmpty() || value.equalsIgnoreCase("NULL"))
89+ return null;
90+ if (!ParseUtils.isQuoted(value))
91+ throw new InvalidTypeException("JSON strings must be enclosed by single quotes");
92+ String json = ParseUtils.unquote(value);
93+ try {
94+ return (T)objectMapper.readValue(json, toJacksonJavaType());
95+ } catch (IOException e) {
96+ throw new InvalidTypeException(e.getMessage(), e);
97+ }
98+ }
99+
100+ /**
101+ * This method acts as a bridge between Guava's {@link com.google.common.reflect.TypeToken TypeToken} API, which is used
102+ * by the driver, and Jackson's {@link JavaType} API.
103+ * @return A {@link JavaType} instance corresponding to the codec's {@link #getJavaType() Java type}.
104+ */
105+ protected JavaType toJacksonJavaType() {
106+ return TypeFactory.defaultInstance().constructType(getJavaType().getType());
107+ }
108+
109+}
added driver-extras/src/main/java/com/datastax/driver/extras/codecs/json/Jsr353JsonCodec.java +162 −0
@@ -0,0 +1,162 @@
1+/*
2+ * Copyright (C) 2012-2015 DataStax Inc.
3+ *
4+ * Licensed under the Apache License, Version 2.0 (the "License");
5+ * you may not use this file except in compliance with the License.
6+ * You may obtain a copy of the License at
7+ *
8+ * http://www.apache.org/licenses/LICENSE-2.0
9+ *
10+ * Unless required by applicable law or agreed to in writing, software
11+ * distributed under the License is distributed on an "AS IS" BASIS,
12+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+ * See the License for the specific language governing permissions and
14+ * limitations under the License.
15+ */
16+package com.datastax.driver.extras.codecs.json;
17+
18+import java.io.*;
19+import java.nio.ByteBuffer;
20+import java.util.Map;
21+
22+import javax.json.*;
23+
24+import com.datastax.driver.core.DataType;
25+import com.datastax.driver.core.ParseUtils;
26+import com.datastax.driver.core.ProtocolVersion;
27+import com.datastax.driver.core.TypeCodec;
28+import com.datastax.driver.core.exceptions.InvalidTypeException;
29+import com.datastax.driver.core.utils.Bytes;
30+
31+/**
32+ * A JSON codec that uses the
33+ * <a href="https://jcp.org/en/jsr/detail?id=353">Java API for JSON processing</a>
34+ * to perform serialization and deserialization of JSON structures.
35+ * <p>
36+ * More specifically, this codec maps an arbitrary {@link JsonStructure} to
37+ * a CQL {@code varchar} column.
38+ * <p>
39+ * Note that this codec handles the Java type {@link JsonStructure}.
40+ * It is therefore required that values are set and retrieved using that exact Java type;
41+ * users should manually downcast to either {@link JsonObject} or {@link JsonArray},
42+ * as in the example below:
43+ * <pre>{@code
44+ *
45+ * // setting values
46+ * JsonObject myObject = ...
47+ * PreparedStatement ps = ...
48+ * // set values using JsonStructure
49+ * BoundStatement bs = ps.bind().set(1, myObject, JsonStructure.class);
50+ *
51+ * // retrieving values
52+ * Row row = session.execute(bs).one();
53+ * // use JsonStructure to retrieve values
54+ * JsonStructure json = row.get(0, JsonStructure.class);
55+ * if (json instanceof JsonObject) {
56+ * myObject = (JsonObject) json;
57+ * ...
58+ * }
59+ * }</pre>
60+ *
61+ */
62+public class Jsr353JsonCodec extends TypeCodec<JsonStructure> {
63+
64+ private final JsonReaderFactory readerFactory;
65+
66+ private final JsonWriterFactory writerFactory;
67+
68+ public Jsr353JsonCodec() {
69+ this(null);
70+ }
71+
72+ public Jsr353JsonCodec(Map<String, ?> config) {
73+ super(DataType.varchar(), JsonStructure.class);
74+ readerFactory = Json.createReaderFactory(config);
75+ writerFactory = Json.createWriterFactory(config);
76+ }
77+
78+ @Override
79+ public ByteBuffer serialize(JsonStructure value, ProtocolVersion protocolVersion) throws InvalidTypeException {
80+ if (value == null)
81+ return null;
82+ ByteArrayOutputStream baos = new ByteArrayOutputStream();
83+ try {
84+ JsonWriter writer = writerFactory.createWriter(baos);
85+ writer.write(value);
86+ return ByteBuffer.wrap(baos.toByteArray());
87+ } catch (JsonException e) {
88+ throw new InvalidTypeException(e.getMessage(), e);
89+ } finally {
90+ try {
91+ baos.close();
92+ } catch (IOException e) {
93+ // cannot happen
94+ throw new InvalidTypeException(e.getMessage(), e);
95+ }
96+ }
97+ }
98+
99+ @Override
100+ @SuppressWarnings("unchecked")
101+ public JsonStructure deserialize(ByteBuffer bytes, ProtocolVersion protocolVersion) throws InvalidTypeException {
102+ if (bytes == null)
103+ return null;
104+ ByteArrayInputStream bais = new ByteArrayInputStream(Bytes.getArray(bytes));
105+ try {
106+ JsonReader reader = readerFactory.createReader(bais);
107+ return reader.read();
108+ } catch (JsonException e) {
109+ throw new InvalidTypeException(e.getMessage(), e);
110+ } finally {
111+ try {
112+ bais.close();
113+ } catch (IOException e) {
114+ // cannot happen
115+ throw new InvalidTypeException(e.getMessage(), e);
116+ }
117+ }
118+ }
119+
120+ @Override
121+ public String format(JsonStructure value) throws InvalidTypeException {
122+ if (value == null)
123+ return "NULL";
124+ String json;
125+ StringWriter sw = new StringWriter();
126+ try {
127+ JsonWriter writer = writerFactory.createWriter(sw);
128+ writer.write(value);
129+ json = sw.toString();
130+ } catch (JsonException e) {
131+ throw new InvalidTypeException(e.getMessage(), e);
132+ } finally {
133+ try {
134+ sw.close();
135+ } catch (IOException e) {
136+ // cannot happen
137+ throw new InvalidTypeException(e.getMessage(), e);
138+ }
139+ }
140+ return ParseUtils.quote(json);
141+ }
142+
143+ @Override
144+ @SuppressWarnings("unchecked")
145+ public JsonStructure parse(String value) throws InvalidTypeException {
146+ if (value == null || value.isEmpty() || value.equalsIgnoreCase("NULL"))
147+ return null;
148+ if (!ParseUtils.isQuoted(value))
149+ throw new InvalidTypeException("JSON strings must be enclosed by single quotes");
150+ String json = ParseUtils.unquote(value);
151+ StringReader sr = new StringReader(json);
152+ try {
153+ JsonReader reader = readerFactory.createReader(sr);
154+ return reader.read();
155+ } catch (JsonException e) {
156+ throw new InvalidTypeException(e.getMessage(), e);
157+ } finally {
158+ sr.close();
159+ }
160+ }
161+
162+}
added driver-extras/src/main/java/com/datastax/driver/extras/codecs/json/package-info.java +46 −0
@@ -0,0 +1,46 @@
1+/*
2+ * Copyright (C) 2012-2015 DataStax Inc.
3+ *
4+ * Licensed under the Apache License, Version 2.0 (the "License");
5+ * you may not use this file except in compliance with the License.
6+ * You may obtain a copy of the License at
7+ *
8+ * http://www.apache.org/licenses/LICENSE-2.0
9+ *
10+ * Unless required by applicable law or agreed to in writing, software
11+ * distributed under the License is distributed on an "AS IS" BASIS,
12+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+ * See the License for the specific language governing permissions and
14+ * limitations under the License.
15+ */
16+
17+/**
18+ * This package contains a collection of convenience
19+ * {@link com.datastax.driver.core.TypeCodec} instances useful for
20+ * serializing JSON structures.
21+ * <p>
22+ * The codecs in this class provide support for the following mappings
23+ * and frameworks:
24+ *
25+ * <table summary="Supported Mappings">
26+ * <tr>
27+ * <th>Codec</th>
28+ * <th>CQL type</th>
29+ * <th>Java type</th>
30+ * <th>JSON Framework</th>
31+ * </tr>
32+ * <tr>
33+ * <td>{@link com.datastax.driver.extras.codecs.json.JacksonJsonCodec}</td>
34+ * <td>{@link com.datastax.driver.core.DataType#varchar() varchar}</td>
35+ * <td>Any</td>
36+ * <td><a href="http://wiki.fasterxml.com/JacksonHome">Jackson</a></td>
37+ * </tr>
38+ * <tr>
39+ * <td>{@link com.datastax.driver.extras.codecs.json.Jsr353JsonCodec}</td>
40+ * <td>{@link com.datastax.driver.core.DataType#varchar() varchar}</td>
41+ * <td>{@link javax.json.JsonStructure JsonStructure}</td>
42+ * <td><a href="https://jcp.org/en/jsr/detail?id=353">Java API for JSON processing</a> (JSR 353)</td>
43+ * </tr>
44+ * </table>
45+ */
46+package com.datastax.driver.extras.codecs.json;
added driver-extras/src/test/java/com/datastax/driver/extras/codecs/json/JacksonJsonCodecTest.java +222 −0
@@ -0,0 +1,222 @@
1+/*
2+ * Copyright (C) 2012-2015 DataStax Inc.
3+ *
4+ * Licensed under the Apache License, Version 2.0 (the "License");
5+ * you may not use this file except in compliance with the License.
6+ * You may obtain a copy of the License at
7+ *
8+ * http://www.apache.org/licenses/LICENSE-2.0
9+ *
10+ * Unless required by applicable law or agreed to in writing, software
11+ * distributed under the License is distributed on an "AS IS" BASIS,
12+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+ * See the License for the specific language governing permissions and
14+ * limitations under the License.
15+ */
16+package com.datastax.driver.extras.codecs.json;
17+
18+import java.util.ArrayList;
19+import java.util.Collection;
20+
21+import com.fasterxml.jackson.annotation.JsonCreator;
22+import com.fasterxml.jackson.annotation.JsonProperty;
23+import com.google.common.base.Objects;
24+import com.google.common.collect.Lists;
25+import org.testng.annotations.Test;
26+
27+import static org.assertj.core.api.Assertions.assertThat;
28+
29+import com.datastax.driver.core.*;
30+import com.datastax.driver.core.querybuilder.BuiltStatement;
31+import com.datastax.driver.core.querybuilder.QueryBuilder;
32+import com.datastax.driver.core.utils.CassandraVersion;
33+import com.datastax.driver.extras.codecs.json.JacksonJsonCodec;
34+
35+import static com.datastax.driver.core.querybuilder.QueryBuilder.bindMarker;
36+import static com.datastax.driver.core.querybuilder.QueryBuilder.eq;
37+
38+public class JacksonJsonCodecTest extends CCMBridge.PerClassSingleNodeCluster {
39+
40+ private static final JacksonJsonCodec<User> jsonCodec = new JacksonJsonCodec<User>(User.class);
41+
42+ private static final User alice = new User(1, "Alice");
43+ private static final User bob = new User(2, "Bob");
44+ private static final User charlie = new User(3, "Charlie");
45+
46+ private static final String bobJson = "{\"id\":2,\"name\":\"Bob\"}";
47+ private static final String charlieJson = "{\"id\":3,\"name\":\"Charlie\"}";
48+ private static final String aliceJson = "{\"id\":1,\"name\":\"Alice\"}";
49+
50+ private static final ArrayList<User> bobAndCharlie = Lists.newArrayList(bob, charlie);
51+
52+ private static final String insertQuery = "INSERT INTO t1 (c1, c2, c3) VALUES (?, ?, ?)";
53+ private static final String selectQuery = "SELECT c1, c2, c3 FROM t1 WHERE c1 = ? and c2 = ?";
54+
55+ private static final String notAJsonString = "this text is not json";
56+
57+ @Override
58+ protected Collection<String> getTableDefinitions() {
59+ return Lists.newArrayList(
60+ "CREATE TABLE t1 (c1 text, c2 text, c3 list<text>, PRIMARY KEY (c1, c2))"
61+ );
62+ }
63+
64+ @Override
65+ protected Cluster.Builder configure(Cluster.Builder builder) {
66+ return builder.withCodecRegistry(
67+ new CodecRegistry().register(jsonCodec) // global User <-> varchar codec
68+ );
69+ }
70+
71+ @Test(groups = "unit")
72+ public void test_cql_text_to_json() {
73+ JacksonJsonCodec<User> codec = new JacksonJsonCodec<User>(User.class);
74+ // the codec is expected to format json objects as json strings enclosed in single quotes,
75+ // as it is required for CQL literals of varchar type.
76+ String json = "'{\"id\":1,\"name\":\"John Doe\"}'";
77+ User user = new User(1, "John Doe");
78+ assertThat(codec.format(user)).isEqualTo(json);
79+ assertThat(codec.parse(json)).isEqualToComparingFieldByField(user);
80+ }
81+
82+ @Test(groups = "unit")
83+ public void test_nulls() {
84+ JacksonJsonCodec<User> codec = new JacksonJsonCodec<User>(User.class);
85+ assertThat(codec.format(null)).isEqualTo("NULL");
86+ assertThat(codec.parse(null)).isNull();
87+ }
88+
89+ @Test(groups = "short")
90+ @CassandraVersion(major=2.0)
91+ public void should_use_custom_codec_with_simple_statements() {
92+ session.execute(insertQuery, notAJsonString, alice, bobAndCharlie);
93+ ResultSet rows = session.execute(selectQuery, notAJsonString, alice);
94+ Row row = rows.one();
95+ assertRow(row);
96+ }
97+
98+ @Test(groups = "short")
99+ public void should_use_custom_codec_with_built_statements_1() {
100+ BuiltStatement insertStmt = new QueryBuilder(cluster).insertInto("t1")
101+ .value("c1", bindMarker())
102+ .value("c2", bindMarker())
103+ .value("c3", bindMarker());
104+ BuiltStatement selectStmt = new QueryBuilder(cluster).select("c1", "c2", "c3")
105+ .from("t1")
106+ .where(eq("c1", bindMarker()))
107+ .and(eq("c2", bindMarker()));
108+ session.execute(session.prepare(insertStmt).bind(notAJsonString, alice, bobAndCharlie));
109+ ResultSet rows = session.execute(session.prepare(selectStmt).bind(notAJsonString, alice));
110+ Row row = rows.one();
111+ assertRow(row);
112+ }
113+
114+ @Test(groups = "short")
115+ public void should_use_custom_codec_with_built_statements_2() {
116+ BuiltStatement insertStmt = new QueryBuilder(cluster).insertInto("t1")
117+ .value("c1", notAJsonString)
118+ .value("c2", alice)
119+ .value("c3", bobAndCharlie);
120+ BuiltStatement selectStmt =
121+ new QueryBuilder(cluster).select("c1", "c2", "c3")
122+ .from("t1")
123+ .where(eq("c1", notAJsonString))
124+ .and(eq("c2", alice));
125+ session.execute(insertStmt);
126+ ResultSet rows = session.execute(selectStmt);
127+ Row row = rows.one();
128+ assertRow(row);
129+ }
130+
131+ @Test(groups = "short")
132+ public void should_use_custom_codec_with_prepared_statements_1() {
133+ session.execute(session.prepare(insertQuery).bind(notAJsonString, alice, bobAndCharlie));
134+ PreparedStatement ps = session.prepare(selectQuery);
135+ // this bind() method does not convey information about the java type of alice
136+ // so the registry will look for a codec accepting varchar <-> ANY
137+ // and will find jsonCodec because it is the first registered
138+ ResultSet rows = session.execute(ps.bind(notAJsonString, alice));
139+ Row row = rows.one();
140+ assertRow(row);
141+ }
142+
143+ @Test(groups = "short")
144+ public void should_use_custom_codec_with_prepared_statements_2() {
145+ session.execute(session.prepare(insertQuery).bind()
146+ .setString(0, notAJsonString)
147+ .set(1, alice, User.class)
148+ .setList(2, bobAndCharlie, User.class)
149+ );
150+ PreparedStatement ps = session.prepare(selectQuery);
151+ ResultSet rows = session.execute(ps.bind()
152+ .setString(0, notAJsonString)
153+ // this set() method conveys information about the java type of alice
154+ // so the registry will look for a codec accepting varchar <-> User
155+ // and will find jsonCodec because it is the only matching one
156+ .set(1, alice, User.class)
157+ );
158+ Row row = rows.one();
159+ assertRow(row);
160+ }
161+
162+ private void assertRow(Row row) {
163+ // getString requires a codec accepting varchar <-> String, so VarcharCodec is used
164+ assertThat(row.getString(0)).isEqualTo(notAJsonString);
165+ // getObject requires a codec accepting varchar <-> ANY;
166+ // the first codec that accepts that is jsonCodec, so it is used
167+ assertThat(row.getObject(1)).isEqualTo(aliceJson);
168+ // getObject uses the default codec VarcharCodec
169+ assertThat(row.get(1, User.class)).isEqualTo(alice);
170+ // we still can get the column as a string using VarcharCodec.instance behind the scenes
171+ assertThat(row.getString(1)).isEqualTo(aliceJson);
172+ assertThat(row.getList(2, User.class)).containsExactly(bob, charlie);
173+ // we still can get the column as a List<String>
174+ assertThat(row.getList(2, String.class)).containsExactly(bobJson, charlieJson);
175+ }
176+
177+ @SuppressWarnings("unused")
178+ public static class User {
179+
180+ private int id;
181+
182+ private String name;
183+
184+ @JsonCreator
185+ public User(@JsonProperty("id") int id, @JsonProperty("name") String name) {
186+ this.id = id;
187+ this.name = name;
188+ }
189+
190+ public int getId() {
191+ return id;
192+ }
193+
194+ public void setId(int id) {
195+ this.id = id;
196+ }
197+
198+ public String getName() {
199+ return name;
200+ }
201+
202+ public void setName(String name) {
203+ this.name = name;
204+ }
205+
206+ @Override
207+ public boolean equals(Object o) {
208+ if (this == o)
209+ return true;
210+ if (o == null || getClass() != o.getClass())
211+ return false;
212+ User user = (User)o;
213+ return Objects.equal(id, user.id) &&
214+ Objects.equal(name, user.name);
215+ }
216+
217+ @Override
218+ public int hashCode() {
219+ return Objects.hashCode(id, name);
220+ }
221+ }
222+}
added driver-extras/src/test/java/com/datastax/driver/extras/codecs/json/Jsr353JsonCodecTest.java +168 −0
@@ -0,0 +1,168 @@
1+/*
2+ * Copyright (C) 2012-2015 DataStax Inc.
3+ *
4+ * Licensed under the Apache License, Version 2.0 (the "License");
5+ * you may not use this file except in compliance with the License.
6+ * You may obtain a copy of the License at
7+ *
8+ * http://www.apache.org/licenses/LICENSE-2.0
9+ *
10+ * Unless required by applicable law or agreed to in writing, software
11+ * distributed under the License is distributed on an "AS IS" BASIS,
12+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+ * See the License for the specific language governing permissions and
14+ * limitations under the License.
15+ */
16+package com.datastax.driver.extras.codecs.json;
17+
18+import java.io.IOException;
19+import java.io.StringWriter;
20+import java.util.Collection;
21+
22+import com.google.common.collect.Lists;
23+import javax.json.*;
24+import org.testng.annotations.DataProvider;
25+import org.testng.annotations.Test;
26+
27+import static org.assertj.core.api.Assertions.assertThat;
28+
29+import com.datastax.driver.core.*;
30+import com.datastax.driver.core.querybuilder.BuiltStatement;
31+import com.datastax.driver.core.querybuilder.QueryBuilder;
32+import com.datastax.driver.core.utils.CassandraVersion;
33+import com.datastax.driver.extras.codecs.json.Jsr353JsonCodec;
34+
35+import static com.datastax.driver.core.querybuilder.QueryBuilder.bindMarker;
36+import static com.datastax.driver.core.querybuilder.QueryBuilder.eq;
37+
38+public class Jsr353JsonCodecTest extends CCMBridge.PerClassSingleNodeCluster {
39+
40+ private static final Jsr353JsonCodec jsonCodec = new Jsr353JsonCodec();
41+
42+ private static final JsonObject alice = Json.createObjectBuilder().add("id", 1).add("name", "Alice") .build();
43+ private static final JsonObject bob = Json.createObjectBuilder().add("id", 2).add("name", "Bob") .build();
44+ private static final JsonObject charlie = Json.createObjectBuilder().add("id", 3).add("name", "Charlie").build();
45+
46+ private static final JsonArray bobAndCharlie = Json.createArrayBuilder().add(bob).add(charlie).build();
47+
48+ private static final String insertQuery = "INSERT INTO t1 (c1, c2) VALUES (?, ?)";
49+ private static final String selectQuery = "SELECT c1, c2 FROM t1 WHERE c1 = ? and c2 = ?";
50+
51+ private static final String notAJsonString = "this text is not json";
52+
53+ @Override
54+ protected Collection<String> getTableDefinitions() {
55+ return Lists.newArrayList(
56+ "CREATE TABLE t1 (c1 text, c2 text, PRIMARY KEY (c1, c2))"
57+ );
58+ }
59+
60+ @Override
61+ protected Cluster.Builder configure(Cluster.Builder builder) {
62+ return builder.withCodecRegistry(
63+ new CodecRegistry().register(jsonCodec) // global User <-> varchar codec
64+ );
65+ }
66+
67+ @DataProvider(name = "Jsr353JsonCodecTest")
68+ public static Object[][] parameters() {
69+ return new Object[][] {
70+ { alice },
71+ { bobAndCharlie }
72+ };
73+ }
74+
75+ @Test(groups = "unit")
76+ public void test_cql_text_to_json() {
77+ Jsr353JsonCodec codec = new Jsr353JsonCodec();
78+ String json = "'{\"id\":1,\"name\":\"John Doe\"}'";
79+ JsonObject object = Json.createObjectBuilder().add("id", 1).add("name", "John Doe").build();
80+ assertThat(codec.format(object)).isEqualTo(json);
81+ assertThat(codec.parse(json)).isEqualTo(object);
82+ }
83+
84+ @Test(groups = "unit")
85+ public void test_nulls() {
86+ Jsr353JsonCodec codec = new Jsr353JsonCodec();
87+ assertThat(codec.format(null)).isEqualTo("NULL");
88+ assertThat(codec.parse(null)).isNull();
89+ }
90+
91+ @Test(groups = "short", dataProvider = "Jsr353JsonCodecTest")
92+ @CassandraVersion(major=2.0)
93+ public void should_use_custom_codec_with_simple_statements(JsonStructure object) throws IOException {
94+ session.execute(insertQuery, notAJsonString, object);
95+ ResultSet rows = session.execute(selectQuery, notAJsonString, object);
96+ Row row = rows.one();
97+ assertRow(row, object);
98+ }
99+
100+ @Test(groups = "short", dataProvider = "Jsr353JsonCodecTest")
101+ public void should_use_custom_codec_with_built_statements_1(JsonStructure object) throws IOException {
102+ BuiltStatement insertStmt = new QueryBuilder(cluster).insertInto("t1")
103+ .value("c1", bindMarker())
104+ .value("c2", bindMarker());
105+ BuiltStatement selectStmt = new QueryBuilder(cluster).select("c1", "c2")
106+ .from("t1")
107+ .where(eq("c1", bindMarker()))
108+ .and(eq("c2", bindMarker()));
109+ session.execute(session.prepare(insertStmt).bind(notAJsonString, object));
110+ ResultSet rows = session.execute(session.prepare(selectStmt).bind(notAJsonString, object));
111+ Row row = rows.one();
112+ assertRow(row, object);
113+ }
114+
115+ @Test(groups = "short", dataProvider = "Jsr353JsonCodecTest")
116+ public void should_use_custom_codec_with_built_statements_2(JsonStructure object) throws IOException {
117+ BuiltStatement insertStmt = new QueryBuilder(cluster).insertInto("t1")
118+ .value("c1", notAJsonString)
119+ .value("c2", object);
120+ BuiltStatement selectStmt =
121+ new QueryBuilder(cluster).select("c1", "c2")
122+ .from("t1")
123+ .where(eq("c1", notAJsonString))
124+ .and(eq("c2", object));
125+ session.execute(insertStmt);
126+ ResultSet rows = session.execute(selectStmt);
127+ Row row = rows.one();
128+ assertRow(row, object);
129+ }
130+
131+ @Test(groups = "short", dataProvider = "Jsr353JsonCodecTest")
132+ public void should_use_custom_codec_with_prepared_statements_1(JsonStructure object) throws IOException {
133+ session.execute(session.prepare(insertQuery).bind(notAJsonString, object));
134+ PreparedStatement ps = session.prepare(selectQuery);
135+ ResultSet rows = session.execute(ps.bind(notAJsonString, object));
136+ Row row = rows.one();
137+ assertRow(row, object);
138+ }
139+
140+ @Test(groups = "short", dataProvider = "Jsr353JsonCodecTest")
141+ public void should_use_custom_codec_with_prepared_statements_2(JsonStructure object) throws IOException {
142+ session.execute(session.prepare(insertQuery).bind()
143+ .setString(0, notAJsonString)
144+ .set(1, object, JsonStructure.class)
145+ );
146+ PreparedStatement ps = session.prepare(selectQuery);
147+ ResultSet rows = session.execute(ps.bind()
148+ .setString(0, notAJsonString)
149+ .set(1, object, JsonStructure.class)
150+ );
151+ Row row = rows.one();
152+ assertRow(row, object);
153+ }
154+
155+ private void assertRow(Row row, JsonStructure object) throws IOException {
156+ String json;
157+ StringWriter sw = new StringWriter();
158+ JsonWriter writer = Json.createWriter(sw);
159+ writer.write(object);
160+ json = sw.toString();
161+ assertThat(row.getString(0)).isEqualTo(notAJsonString);
162+ assertThat(row.getObject(1)).isEqualTo(json);
163+ assertThat(row.getString(1)).isEqualTo(json);
164+ assertThat(row.get(1, String.class)).isEqualTo(json);
165+ assertThat(row.get(1, JsonStructure.class)).isEqualTo(object);
166+ }
167+
168+}