Elffuss BraidHub

kikocis/java-driver public

Merge pull request #716 from datastax/java1237

JAVA-1237: Add JSON examples
Changeset30a0b78ca19db1f9c1e9e7a7b1ca412b9e10a228bb73f23c684acd3bd8b8ba3d
AuthorOlivier Michallat <olim7t@users.noreply.github.com> · 2016-07-27 11:56 -07:00
CommitterGitHub <noreply@github.com> · 2016-07-27 11:56 -07:00
Parents6795b189968d, 9a14ec6dfb6f

Browse the files at this changeset

16 files changed

modified driver-core/src/main/java/com/datastax/driver/core/querybuilder/BuiltStatement.java +9 −6
@@ -21,7 +21,6 @@
2121
2222 import java.nio.ByteBuffer;
2323 import java.util.ArrayList;
24-import java.util.Arrays;
2524 import java.util.List;
2625 import java.util.Map;
2726 import java.util.regex.Pattern;
@@ -297,12 +296,16 @@
297296 @Override
298297 public String toString() {
299298 try {
300- if (forceNoValues) {
301- return getQueryString();
299+ try {
300+ if (forceNoValues)
301+ return getQueryString();
302+ // 1) try first with all values inlined (will not work if some values require custom codecs)
303+ return maybeAddSemicolon(buildQueryString(null, CodecRegistry.DEFAULT_INSTANCE)).toString();
304+ } catch (CodecNotFoundException e) {
305+ // 2) try next with bind markers for all values to avoid usage of custom codecs
306+ return maybeAddSemicolon(buildQueryString(new ArrayList<Object>(), CodecRegistry.DEFAULT_INSTANCE)).toString();
302307 }
303- StringBuilder queryString = buildQueryString(null, CodecRegistry.DEFAULT_INSTANCE);
304- return maybeAddSemicolon(queryString).toString();
305- } catch (CodecNotFoundException e) {
308+ } catch (RuntimeException e) {
306309 // Ugly but we have absolutely no context to get the registry from
307310 return String.format("built query (could not generate with default codec registry: %s)", e.getMessage());
308311 }
modified driver-core/src/main/java/com/datastax/driver/core/querybuilder/Insert.java +24 −13
@@ -94,7 +94,7 @@
9494 * @param name the name of the column to insert/update.
9595 * @param value the value to insert/update for {@code name}.
9696 * @return this INSERT statement.
97- * @throws IllegalStateException if this method is called and the {@link #json(String)}
97+ * @throws IllegalStateException if this method is called and the {@link #json(Object)}
9898 * method has been called before, because it's not possible
9999 * to mix {@code INSERT JSON} syntax with regular {@code INSERT} syntax.
100100 */
@@ -118,7 +118,7 @@
118118 * in {@code names}.
119119 * @return this INSERT statement.
120120 * @throws IllegalArgumentException if {@code names.length != values.length}.
121- * @throws IllegalStateException if this method is called and the {@link #json(String)}
121+ * @throws IllegalStateException if this method is called and the {@link #json(Object)}
122122 * method has been called before, because it's not possible
123123 * to mix {@code INSERT JSON} syntax with regular {@code INSERT} syntax.
124124 */
@@ -135,7 +135,7 @@
135135 * in {@code names}.
136136 * @return this INSERT statement.
137137 * @throws IllegalArgumentException if {@code names.size() != values.size()}.
138- * @throws IllegalStateException if this method is called and the {@link #json(String)}
138+ * @throws IllegalStateException if this method is called and the {@link #json(Object)}
139139 * method has been called before, because it's not possible
140140 * to mix {@code INSERT JSON} syntax with regular {@code INSERT} syntax.
141141 */
@@ -156,20 +156,30 @@
156156 }
157157
158158 /**
159- * Inserts the provided JSON string, using the {@code INSERT INTO ... JSON} syntax introduced
159+ * Inserts the provided object, using the {@code INSERT INTO ... JSON} syntax introduced
160160 * in Cassandra 2.2.
161161 * <p/>
162- * With INSERT statements, the new {@code JSON} keyword can be used to enable inserting a
163- * JSON encoded map as a single row.
162+ * With INSERT statements, the new {@code JSON} keyword can be used to enable inserting a JSON
163+ * structure as a single row.
164164 * <p/>
165- * <strong>The provided JSON string will be appended to the query string as is.
166- * It should NOT be surrounded by single quotes.</strong>
165+ * The provided object can be of the following types:
166+ * <ol>
167+ * <li>A raw string. In this case, it will be appended to the query string as is.
168+ * <strong>It should NOT be surrounded by single quotes.</strong>
167169 * Its format should generally match that returned by a
168170 * {@code SELECT JSON} statement on the same table.
169- * <p/>
170- * Note that it is not possible to insert function calls nor bind markers in the JSON string.
171+ * Note that it is not possible to insert function calls nor bind markers in a JSON string.</li>
172+ * <li>A {@link QueryBuilder#bindMarker() bind marker}. In this case, the statement is meant to be prepared
173+ * and no JSON string will be appended to the query string, only a bind marker for the whole JSON parameter.</li>
174+ * <li>Any object that can be serialized to JSON. Such objects can be used provided that
175+ * a matching {@link com.datastax.driver.core.TypeCodec codec} is registered with the
176+ * {@link CodecRegistry} in use. This allows the usage of JSON libraries, such
177+ * as the <a href="https://jcp.org/en/jsr/detail?id=353">Java API for JSON processing</a>,
178+ * the popular <a href="http://wiki.fasterxml.com/JacksonHome">Jackson</a> library, or
179+ * Google's <a href="https://github.com/google/gson">Gson</a> library, for instance.</li>
180+ * </ol>
171181 * <h3>Case-sensitive column names</h3>
172- * Users are required to handle case-sensitive column names
182+ * When passing raw strings to this method, users are required to handle case-sensitive column names
173183 * by surrounding them with double quotes.
174184 * <p/>
175185 * For example, to insert into a table with two columns named “myKey” and “value”,
@@ -182,7 +192,8 @@
182192 * INSERT INTO mytable JSON '{"\"myKey\"": 0, "value": 0}';
183193 * </pre>
184194 * <h3>Escaping quotes in column values</h3>
185- * Double quotes should be escaped with a backslash, but single quotes should be escaped in
195+ * When passing raw strings to this method, double quotes should be escaped with a backslash,
196+ * but single quotes should be escaped in
186197 * the CQL manner, i.e. by another single quote. For example, the column value
187198 * {@code foo"'bar} should be inserted in the JSON string
188199 * as {@code "foo\"''bar"}.
@@ -191,7 +202,7 @@
191202 * Any columns which are omitted from the JSON string will be defaulted to a {@code NULL} value
192203 * (which will result in a tombstone being created).
193204 *
194- * @param json the JSON string, or a bind marker.
205+ * @param json the JSON string, or a bind marker, or a JSON object handled by a specific {@link com.datastax.driver.core.TypeCodec codec}.
195206 * @return this INSERT statement.
196207 * @throws IllegalStateException if this method is called and any of the {@code value} or {@code values}
197208 * methods have been called before, because it's not possible
modified driver-core/src/main/java/com/datastax/driver/core/querybuilder/QueryBuilder.java +24 −8
@@ -1057,23 +1057,39 @@
10571057 * Support for JSON functions has been added in Cassandra 2.2.
10581058 * The {@code fromJson()} function is similar to {@code INSERT JSON} statements,
10591059 * but applies to a single column value instead of the entire row, and
1060- * converts a JSON-encoded string into the normal Cassandra column value.
1060+ * converts a JSON object into the normal Cassandra column value.
10611061 * <p/>
10621062 * It may be used in {@code INSERT} and {@code UPDATE} statements,
10631063 * but NOT in the selection clause of a {@code SELECT} statement.
10641064 * <p/>
1065- * <strong>The provided JSON string will be appended to the query string as is.
1066- * It should NOT be surrounded by single quotes.</strong>
1065+ * The provided object can be of the following types:
1066+ * <ol>
1067+ * <li>A raw string. In this case, it will be appended to the query string as is.
1068+ * <strong>It should NOT be surrounded by single quotes.</strong>
1069+ * Its format should generally match that returned by a
1070+ * {@code SELECT JSON} statement on the same table.
1071+ * Note that it is not possible to insert function calls nor bind markers in a JSON string.</li>
1072+ * <li>A {@link QueryBuilder#bindMarker() bind marker}. In this case, the statement is meant to be prepared
1073+ * and no JSON string will be appended to the query string, only a bind marker for the whole JSON parameter.</li>
1074+ * <li>Any object that can be serialized to JSON. Such objects can be used provided that
1075+ * a matching {@link com.datastax.driver.core.TypeCodec codec} is registered with the
1076+ * {@link com.datastax.driver.core.CodecRegistry CodecRegistry} in use. This allows the usage of JSON libraries, such
1077+ * as the <a href="https://jcp.org/en/jsr/detail?id=353">Java API for JSON processing</a>,
1078+ * the popular <a href="http://wiki.fasterxml.com/JacksonHome">Jackson</a> library, or
1079+ * Google's <a href="https://github.com/google/gson">Gson</a> library, for instance.</li>
1080+ * </ol>
10671081 * <p/>
1068- * String values should be enclosed in double quotes.
1069- * Double quotes appearing inside strings should be escaped with a backslash,
1082+ * When passing raw strings to this method, the following rules apply:
1083+ * <ol>
1084+ * <li>String values should be enclosed in double quotes.</li>
1085+ * <li>Double quotes appearing inside strings should be escaped with a backslash,
10701086 * but single quotes should be escaped in
10711087 * the CQL manner, i.e. by another single quote. For example, the column value
10721088 * {@code foo"'bar} should be inserted in the JSON string
1073- * as {@code "foo\"''bar"}.
1074- * <p/>
1075- * Note that it is not possible to insert function calls nor bind markers in the JSON string.
1089+ * as {@code "foo\"''bar"}.</li>
1090+ * </ol>
10761091 *
1092+ * @param json the JSON string, or a bind marker, or a JSON object handled by a specific {@link com.datastax.driver.core.TypeCodec codec}.
10771093 * @return the function call.
10781094 * @see <a href="http://cassandra.apache.org/doc/cql3/CQL-2.2.html#json">JSON Support for CQL</a>
10791095 * @see <a href="http://www.datastax.com/dev/blog/whats-new-in-cassandra-2-2-json-support">JSON Support in Cassandra 2.2</a>
modified driver-examples/pom.xml +31 −0
@@ -41,10 +41,41 @@
4141 <version>${project.parent.version}</version>
4242 </dependency>
4343
44+ <dependency>
45+ <groupId>com.datastax.cassandra</groupId>
46+ <artifactId>cassandra-driver-extras</artifactId>
47+ <version>${project.parent.version}</version>
48+ <optional>true</optional>
49+ </dependency>
50+
51+ <dependency>
52+ <groupId>com.fasterxml.jackson.core</groupId>
53+ <artifactId>jackson-databind</artifactId>
54+ <version>${jackson.version}</version>
55+ <optional>true</optional>
56+ </dependency>
57+
58+ <dependency>
59+ <groupId>javax.json</groupId>
60+ <artifactId>javax.json-api</artifactId>
61+ <version>${jsr353-api.version}</version>
62+ <optional>true</optional>
63+ </dependency>
64+
65+ <dependency>
66+ <groupId>org.glassfish</groupId>
67+ <artifactId>javax.json</artifactId>
68+ <version>${jsr353-ri.version}</version>
69+ <optional>true</optional>
70+ <scope>runtime</scope>
71+ </dependency>
72+
73+ <!-- driver logs -->
4474 <dependency>
4575 <groupId>ch.qos.logback</groupId>
4676 <artifactId>logback-classic</artifactId>
4777 <version>1.1.3</version>
78+ <scope>runtime</scope>
4879 </dependency>
4980
5081 </dependencies>
modified driver-examples/src/main/java/com/datastax/driver/examples/basic/CreateAndPopulateKeyspace.java +1 −1
@@ -27,7 +27,7 @@
2727 * - a Cassandra cluster is running and accessible through the contacts points identified by CONTACT_POINTS and PORT.
2828 * <p/>
2929 * Side effects:
30- * - creates a new keyspace "simplex" in the cluster. It a keyspace with this name already exists, it will be reused;
30+ * - creates a new keyspace "simplex" in the cluster. If a keyspace with this name already exists, it will be reused;
3131 * - creates two tables "simplex.songs" and "simplex.playlists". If they exist already, they will be reused;
3232 * - inserts a row in each table.
3333 *
modified driver-examples/src/main/java/com/datastax/driver/examples/datatypes/Blobs.java +1 −1
@@ -37,7 +37,7 @@
3737 * - FILE references an existing file.
3838 * <p/>
3939 * Side effects:
40- * - creates a new keyspace "examples" in the cluster. It a keyspace with this name already exists, it will be reused;
40+ * - creates a new keyspace "examples" in the cluster. If a keyspace with this name already exists, it will be reused;
4141 * - creates a table "examples.blobs". If it already exists, it will be reused;
4242 * - inserts data in the table.
4343 */
added driver-examples/src/main/java/com/datastax/driver/examples/json/JacksonJsonColumn.java +170 −0
@@ -0,0 +1,170 @@
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.examples.json;
17+
18+import com.datastax.driver.core.*;
19+import com.datastax.driver.extras.codecs.json.JacksonJsonCodec;
20+import com.fasterxml.jackson.annotation.JsonCreator;
21+import com.fasterxml.jackson.annotation.JsonProperty;
22+
23+import static com.datastax.driver.core.querybuilder.QueryBuilder.*;
24+
25+/**
26+ * Illustrates how to map a single table column of type {@code VARCHAR},
27+ * containing JSON payloads, into a Java object using
28+ * the <a href="http://wiki.fasterxml.com/JacksonHome">Jackson</a> library.
29+ * <p/>
30+ * This example makes usage of a custom {@link TypeCodec codec},
31+ * {@link JacksonJsonCodec}, which is declared in the driver-extras module.
32+ * If you plan to follow this example, make sure to include the following
33+ * Maven dependencies in your project:
34+ * <pre>{@code
35+ * <dependency>
36+ * <groupId>com.datastax.cassandra</groupId>
37+ * <artifactId>cassandra-driver-extras</artifactId>
38+ * <version>${driver.version}</version>
39+ * </dependency>
40+ *
41+ * <dependency>
42+ * <groupId>com.fasterxml.jackson.core</groupId>
43+ * <artifactId>jackson-databind</artifactId>
44+ * <version>${jackson.version}</version>
45+ * </dependency>
46+ * }</pre>
47+ * This example also uses the {@link com.datastax.driver.core.querybuilder.QueryBuilder QueryBuilder};
48+ * for examples using the "core" API, see {@link PlainTextJson} (they are easily translatable to the
49+ * queries in this class).
50+ * <p/>
51+ * Preconditions:
52+ * - a Cassandra cluster is running and accessible through the contacts points identified by CONTACT_POINTS and PORT;
53+ * <p/>
54+ * Side effects:
55+ * - creates a new keyspace "examples" in the cluster. If a keyspace with this name already exists, it will be reused;
56+ * - creates a table "examples.json_jackson_column". If it already exists, it will be reused;
57+ * - inserts data in the table.
58+ */
59+public class JacksonJsonColumn {
60+
61+ static String[] CONTACT_POINTS = {"127.0.0.1"};
62+ static int PORT = 9042;
63+
64+ public static void main(String[] args) {
65+ Cluster cluster = null;
66+ try {
67+
68+ // A codec to convert JSON payloads into User instances;
69+ // this codec is declared in the driver-extras module
70+ TypeCodec<User> userCodec = new JacksonJsonCodec<User>(User.class);
71+
72+ cluster = Cluster.builder()
73+ .addContactPoints(CONTACT_POINTS).withPort(PORT)
74+ .withCodecRegistry(new CodecRegistry().register(userCodec))
75+ .build();
76+
77+ Session session = cluster.connect();
78+
79+ createSchema(session);
80+ insertJsonColumn(session);
81+ selectJsonColumn(session);
82+
83+ } finally {
84+ if (cluster != null) cluster.close();
85+ }
86+ }
87+
88+ private static void createSchema(Session session) {
89+ session.execute("CREATE KEYSPACE IF NOT EXISTS examples " +
90+ "WITH replication = {'class': 'SimpleStrategy', 'replication_factor': 1}");
91+ session.execute("CREATE TABLE IF NOT EXISTS examples.json_jackson_column(" +
92+ "id int PRIMARY KEY, json text)");
93+ }
94+
95+ // Mapping a User instance to a table column
96+ private static void insertJsonColumn(Session session) {
97+
98+ User alice = new User("alice", 30);
99+ User bob = new User("bob", 35);
100+
101+ // Build and execute a simple statement
102+ Statement stmt = insertInto("examples", "json_jackson_column")
103+ .value("id", 1)
104+ // the User object will be converted into a String and persisted into the VARCHAR column "json"
105+ .value("json", alice);
106+ session.execute(stmt);
107+
108+ // The JSON object can be a bound value if the statement is prepared
109+ // (we use a local variable here for the sake of example, but in a real application you would cache and reuse
110+ // the prepared statement)
111+ PreparedStatement pst = session.prepare(
112+ insertInto("examples", "json_jackson_column")
113+ .value("id", bindMarker("id"))
114+ .value("json", bindMarker("json")));
115+ session.execute(pst.bind()
116+ .setInt("id", 2)
117+ .set("json", bob, User.class));
118+ }
119+
120+ // Retrieving User instances from a table column
121+ private static void selectJsonColumn(Session session) {
122+
123+ Statement stmt = select()
124+ .from("examples", "json_jackson_column")
125+ .where(in("id", 1, 2));
126+
127+ ResultSet rows = session.execute(stmt);
128+
129+ for (Row row : rows) {
130+ int id = row.getInt("id");
131+ // retrieve the JSON payload and convert it to a User instance
132+ User user = row.get("json", User.class);
133+ // it is also possible to retrieve the raw JSON payload
134+ String json = row.getString("json");
135+ System.out.printf("Retrieved row:%n" +
136+ "id %d%n" +
137+ "user %s%n" +
138+ "user (raw) %s%n%n",
139+ id, user, json);
140+
141+ }
142+ }
143+
144+ @SuppressWarnings("unused")
145+ public static class User {
146+
147+ private final String name;
148+
149+ private final int age;
150+
151+ @JsonCreator
152+ public User(@JsonProperty("name") String name, @JsonProperty("age") int age) {
153+ this.name = name;
154+ this.age = age;
155+ }
156+
157+ public String getName() {
158+ return name;
159+ }
160+
161+ public int getAge() {
162+ return age;
163+ }
164+
165+ @Override
166+ public String toString() {
167+ return String.format("%s (%s)", name, age);
168+ }
169+ }
170+}
added driver-examples/src/main/java/com/datastax/driver/examples/json/JacksonJsonFunction.java +214 −0
@@ -0,0 +1,214 @@
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.examples.json;
17+
18+import com.datastax.driver.core.*;
19+import com.datastax.driver.extras.codecs.json.JacksonJsonCodec;
20+import com.fasterxml.jackson.annotation.JsonCreator;
21+import com.fasterxml.jackson.annotation.JsonProperty;
22+import com.fasterxml.jackson.databind.JsonNode;
23+import com.fasterxml.jackson.databind.node.JsonNodeFactory;
24+import com.fasterxml.jackson.databind.node.ObjectNode;
25+
26+import static com.datastax.driver.core.querybuilder.QueryBuilder.*;
27+
28+/**
29+ * Illustrates how to map a single table column of an arbitrary type
30+ * to a Java object using
31+ * the <a href="http://wiki.fasterxml.com/JacksonHome">Jackson</a> library,
32+ * and leveraging the {@code toJson()} and {@code fromJson()} functions
33+ * introduced in Cassandra 2.2.
34+ * <p/>
35+ * This example makes usage of a custom {@link TypeCodec codec},
36+ * {@link JacksonJsonCodec}, which is declared in the driver-extras module.
37+ * If you plan to follow this example, make sure to include the following
38+ * Maven dependencies in your project:
39+ * <pre>{@code
40+ * <dependency>
41+ * <groupId>com.datastax.cassandra</groupId>
42+ * <artifactId>cassandra-driver-extras</artifactId>
43+ * <version>${driver.version}</version>
44+ * </dependency>
45+ *
46+ * <dependency>
47+ * <groupId>com.fasterxml.jackson.core</groupId>
48+ * <artifactId>jackson-databind</artifactId>
49+ * <version>${jackson.version}</version>
50+ * </dependency>
51+ * }</pre>
52+ * This example also uses the {@link com.datastax.driver.core.querybuilder.QueryBuilder QueryBuilder};
53+ * for examples using the "core" API, see {@link PlainTextJson} (they are easily translatable to the
54+ * queries in this class).
55+ * <p/>
56+ * Preconditions:
57+ * - a Cassandra cluster is running and accessible through the contacts points identified by CONTACT_POINTS and PORT;
58+ * <p/>
59+ * Side effects:
60+ * - creates a new keyspace "examples" in the cluster. If a keyspace with this name already exists, it will be reused;
61+ * - creates a user-defined type (UDT) "examples.json_jackson_function_user". If it already exists, it will be reused;
62+ * - creates a table "examples.json_jackson_function". If it already exists, it will be reused;
63+ * - inserts data in the table.
64+ *
65+ * @see <a href="http://www.datastax.com/dev/blog/whats-new-in-cassandra-2-2-json-support">What’s New in Cassandra 2.2: JSON Support</a>
66+ */
67+public class JacksonJsonFunction {
68+
69+ static String[] CONTACT_POINTS = {"127.0.0.1"};
70+ static int PORT = 9042;
71+
72+ public static void main(String[] args) {
73+ Cluster cluster = null;
74+ try {
75+
76+ // A codec to convert JSON payloads into User instances;
77+ // this codec is declared in the driver-extras module
78+ TypeCodec<User> userCodec = new JacksonJsonCodec<User>(User.class);
79+
80+ // A codec to convert generic JSON payloads into JsonNode instances
81+ TypeCodec<JsonNode> jsonNodeCodec = new JacksonJsonCodec<JsonNode>(JsonNode.class);
82+
83+ cluster = Cluster.builder()
84+ .addContactPoints(CONTACT_POINTS).withPort(PORT)
85+ .withCodecRegistry(new CodecRegistry()
86+ .register(userCodec)
87+ .register(jsonNodeCodec))
88+ .build();
89+
90+ Session session = cluster.connect();
91+
92+ createSchema(session);
93+ insertFromJson(session);
94+ selectToJson(session);
95+
96+ } finally {
97+ if (cluster != null) cluster.close();
98+ }
99+ }
100+
101+ private static void createSchema(Session session) {
102+ session.execute("CREATE KEYSPACE IF NOT EXISTS examples " +
103+ "WITH replication = {'class': 'SimpleStrategy', 'replication_factor': 1}");
104+ session.execute("CREATE TYPE IF NOT EXISTS examples.json_jackson_function_user(" +
105+ "name text, age int)");
106+ session.execute("CREATE TABLE IF NOT EXISTS examples.json_jackson_function(" +
107+ "id int PRIMARY KEY, user frozen<json_jackson_function_user>, scores map<varchar,float>)");
108+ }
109+
110+ // Mapping JSON payloads to table columns of arbitrary types,
111+ // using fromJson() function
112+ private static void insertFromJson(Session session) {
113+
114+ User alice = new User("alice", 30);
115+ User bob = new User("bob", 35);
116+
117+ ObjectNode aliceScores = JsonNodeFactory.instance.objectNode()
118+ .put("call_of_duty", 4.8)
119+ .put("pokemon_go", 9.7);
120+ ObjectNode bobScores = JsonNodeFactory.instance.objectNode()
121+ .put("zelda", 8.3)
122+ .put("pokemon_go", 12.4);
123+
124+ // Build and execute a simple statement
125+ Statement stmt = insertInto("examples", "json_jackson_function")
126+ .value("id", 1)
127+ // client-side, the User object will be converted into a JSON String;
128+ // then, server-side, the fromJson() function will convert that JSON string
129+ // into an instance of the json_jackson_function_user user-defined type (UDT),
130+ // which will be persisted into the column "user"
131+ .value("user", fromJson(alice))
132+ // same thing, but this time converting from
133+ // a generic JsonNode to a JSON string, then from this string to a map<varchar,float>
134+ .value("scores", fromJson(aliceScores));
135+ session.execute(stmt);
136+
137+ // The JSON object can be a bound value if the statement is prepared
138+ // (we use a local variable here for the sake of example, but in a real application you would cache and reuse
139+ // the prepared statement)
140+ PreparedStatement pst = session.prepare(
141+ insertInto("examples", "json_jackson_function")
142+ .value("id", bindMarker("id"))
143+ .value("user", fromJson(bindMarker("user")))
144+ .value("scores", fromJson(bindMarker("scores"))));
145+ session.execute(pst.bind()
146+ .setInt("id", 2)
147+ .set("user", bob, User.class)
148+ // note that the codec requires that the type passed to the set() method
149+ // be always JsonNode, and not a subclass of it, such as ObjectNode
150+ .set("scores", bobScores, JsonNode.class));
151+ }
152+
153+ // Retrieving JSON payloads from table columns of arbitrary types,
154+ // using toJson() function
155+ private static void selectToJson(Session session) {
156+
157+ Statement stmt = select()
158+ .column("id")
159+ .toJson("user").as("user")
160+ .toJson("scores").as("scores")
161+ .from("examples", "json_jackson_function")
162+ .where(in("id", 1, 2));
163+
164+ ResultSet rows = session.execute(stmt);
165+
166+ for (Row row : rows) {
167+ int id = row.getInt("id");
168+ // retrieve the JSON payload and convert it to a User instance
169+ User user = row.get("user", User.class);
170+ // it is also possible to retrieve the raw JSON payload
171+ String userJson = row.getString("user");
172+ // retrieve the JSON payload and convert it to a JsonNode instance
173+ // note that the codec requires that the type passed to the get() method
174+ // be always JsonNode, and not a subclass of it, such as ObjectNode
175+ JsonNode scores = row.get("scores", JsonNode.class);
176+ // it is also possible to retrieve the raw JSON payload
177+ String scoresJson = row.getString("scores");
178+ System.out.printf("Retrieved row:%n" +
179+ "id %d%n" +
180+ "user %s%n" +
181+ "user (raw) %s%n" +
182+ "scores %s%n" +
183+ "scores (raw) %s%n%n",
184+ id, user, userJson, scores, scoresJson);
185+ }
186+ }
187+
188+ @SuppressWarnings("unused")
189+ public static class User {
190+
191+ private final String name;
192+
193+ private final int age;
194+
195+ @JsonCreator
196+ public User(@JsonProperty("name") String name, @JsonProperty("age") int age) {
197+ this.name = name;
198+ this.age = age;
199+ }
200+
201+ public String getName() {
202+ return name;
203+ }
204+
205+ public int getAge() {
206+ return age;
207+ }
208+
209+ @Override
210+ public String toString() {
211+ return String.format("%s (%s)", name, age);
212+ }
213+ }
214+}
added driver-examples/src/main/java/com/datastax/driver/examples/json/JacksonJsonRow.java +165 −0
@@ -0,0 +1,165 @@
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.examples.json;
17+
18+import com.datastax.driver.core.*;
19+import com.datastax.driver.extras.codecs.json.JacksonJsonCodec;
20+import com.fasterxml.jackson.annotation.JsonCreator;
21+import com.fasterxml.jackson.annotation.JsonProperty;
22+
23+import static com.datastax.driver.core.querybuilder.QueryBuilder.*;
24+
25+/**
26+ * Illustrates how to map an entire table row to a Java object using
27+ * the <a href="http://wiki.fasterxml.com/JacksonHome">Jackson</a> library,
28+ * and leveraging the {@code SELECT JSON} and {@code INSERT JSON} syntaxes
29+ * introduced in Cassandra 2.2.
30+ * <p/>
31+ * This example makes usage of a custom {@link TypeCodec codec},
32+ * {@link JacksonJsonCodec}, which is declared in the driver-extras module.
33+ * If you plan to follow this example, make sure to include the following
34+ * Maven dependencies in your project:
35+ * <pre>{@code
36+ * <dependency>
37+ * <groupId>com.datastax.cassandra</groupId>
38+ * <artifactId>cassandra-driver-extras</artifactId>
39+ * <version>${driver.version}</version>
40+ * </dependency>
41+ *
42+ * <dependency>
43+ * <groupId>com.fasterxml.jackson.core</groupId>
44+ * <artifactId>jackson-databind</artifactId>
45+ * <version>${jackson.version}</version>
46+ * </dependency>
47+ * }</pre>
48+ * This example also uses the {@link com.datastax.driver.core.querybuilder.QueryBuilder QueryBuilder};
49+ * for examples using the "core" API, see {@link PlainTextJson} (they are easily translatable to the
50+ * queries in this class).
51+ * <p/>
52+ * Preconditions:
53+ * - a Cassandra 2.2+ cluster is running and accessible through the contacts points identified by CONTACT_POINTS and PORT;
54+ * <p/>
55+ * Side effects:
56+ * - creates a new keyspace "examples" in the cluster. If a keyspace with this name already exists, it will be reused;
57+ * - creates a table "examples.json_jackson_row". If it already exists, it will be reused;
58+ * - inserts data in the table.
59+ *
60+ * @see <a href="http://www.datastax.com/dev/blog/whats-new-in-cassandra-2-2-json-support">What’s New in Cassandra 2.2: JSON Support</a>
61+ */
62+public class JacksonJsonRow {
63+
64+ static String[] CONTACT_POINTS = {"127.0.0.1"};
65+ static int PORT = 9042;
66+
67+ public static void main(String[] args) {
68+ Cluster cluster = null;
69+ try {
70+
71+ // A codec to convert JSON payloads into User instances;
72+ // this codec is declared in the driver-extras module
73+ TypeCodec<User> userCodec = new JacksonJsonCodec<User>(User.class);
74+
75+ cluster = Cluster.builder()
76+ .addContactPoints(CONTACT_POINTS).withPort(PORT)
77+ .withCodecRegistry(new CodecRegistry().register(userCodec))
78+ .build();
79+
80+ Session session = cluster.connect();
81+
82+ createSchema(session);
83+ insertJsonRow(session);
84+ selectJsonRow(session);
85+
86+ } finally {
87+ if (cluster != null) cluster.close();
88+ }
89+ }
90+
91+ private static void createSchema(Session session) {
92+ session.execute("CREATE KEYSPACE IF NOT EXISTS examples " +
93+ "WITH replication = {'class': 'SimpleStrategy', 'replication_factor': 1}");
94+ session.execute("CREATE TABLE IF NOT EXISTS examples.json_jackson_row(" +
95+ "id int PRIMARY KEY, name text, age int)");
96+ }
97+
98+ // Mapping a User instance to a table row using INSERT JSON
99+ private static void insertJsonRow(Session session) {
100+ // Build and execute a simple statement
101+ Statement stmt = insertInto("examples", "json_jackson_row")
102+ .json(new User(1, "alice", 30));
103+ session.execute(stmt);
104+
105+ // The JSON object can be a bound value if the statement is prepared
106+ // (we use a local variable here for the sake of example, but in a real application you would cache and reuse
107+ // the prepared statement)
108+ PreparedStatement pst = session.prepare(
109+ insertInto("examples", "json_jackson_row").json(bindMarker("user")));
110+ session.execute(pst.bind()
111+ .set("user", new User(2, "bob", 35), User.class));
112+ }
113+
114+ // Retrieving User instances from table rows using SELECT JSON
115+ private static void selectJsonRow(Session session) {
116+
117+ // Reading the whole row as a JSON object
118+ Statement stmt = select().json()
119+ .from("examples", "json_jackson_row")
120+ .where(in("id", 1, 2));
121+
122+ ResultSet rows = session.execute(stmt);
123+
124+ for (Row row : rows) {
125+ // SELECT JSON returns only one column for each row, of type VARCHAR,
126+ // containing the row as a JSON payload
127+ User user = row.get(0, User.class);
128+ System.out.printf("Retrieved user: %s%n", user);
129+ }
130+ }
131+
132+ @SuppressWarnings("unused")
133+ public static class User {
134+
135+ private final int id;
136+
137+ private final String name;
138+
139+ private final int age;
140+
141+ @JsonCreator
142+ public User(@JsonProperty("id") int id, @JsonProperty("name") String name, @JsonProperty("age") int age) {
143+ this.id = id;
144+ this.name = name;
145+ this.age = age;
146+ }
147+
148+ public int getId() {
149+ return id;
150+ }
151+
152+ public String getName() {
153+ return name;
154+ }
155+
156+ public int getAge() {
157+ return age;
158+ }
159+
160+ @Override
161+ public String toString() {
162+ return String.format("%s (id %d, age %d)", name, id, age);
163+ }
164+ }
165+}
added driver-examples/src/main/java/com/datastax/driver/examples/json/Jsr353JsonColumn.java +164 −0
@@ -0,0 +1,164 @@
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.examples.json;
17+
18+import com.datastax.driver.core.*;
19+import com.datastax.driver.extras.codecs.json.Jsr353JsonCodec;
20+
21+import javax.json.Json;
22+import javax.json.JsonObject;
23+import javax.json.JsonStructure;
24+
25+import static com.datastax.driver.core.querybuilder.QueryBuilder.*;
26+
27+/**
28+ * Illustrates how to map a single table column of type {@code VARCHAR},
29+ * containing JSON payloads, into a Java object using
30+ * the <a href="https://jcp.org/en/jsr/detail?id=353">Java API for JSON processing</a>.
31+ * <p/>
32+ * This example makes usage of a custom {@link TypeCodec codec},
33+ * {@link Jsr353JsonCodec}, which is declared in the driver-extras module.
34+ * If you plan to follow this example, make sure to include the following
35+ * Maven dependencies in your project:
36+ * <pre>{@code
37+ * <dependency>
38+ * <groupId>com.datastax.cassandra</groupId>
39+ * <artifactId>cassandra-driver-extras</artifactId>
40+ * <version>${driver.version}</version>
41+ * </dependency>
42+ *
43+ * <dependency>
44+ * <groupId>javax.json</groupId>
45+ * <artifactId>javax.json-api</artifactId>
46+ * <version>${jsr353-api.version}</version>
47+ * </dependency>
48+ *
49+ * <dependency>
50+ * <groupId>org.glassfish</groupId>
51+ * <artifactId>javax.json</artifactId>
52+ * <version>${jsr353-ri.version}</version>
53+ * <scope>runtime</scope>
54+ * </dependency>
55+ * }</pre>
56+ * This example also uses the {@link com.datastax.driver.core.querybuilder.QueryBuilder QueryBuilder};
57+ * for examples using the "core" API, see {@link PlainTextJson} (they are easily translatable to the
58+ * queries in this class).
59+ * <p/>
60+ * Preconditions:
61+ * - a Cassandra cluster is running and accessible through the contacts points identified by CONTACT_POINTS and PORT;
62+ * <p/>
63+ * Side effects:
64+ * - creates a new keyspace "examples" in the cluster. If a keyspace with this name already exists, it will be reused;
65+ * - creates a table "examples.json_jsr353_column". If it already exists, it will be reused;
66+ * - inserts data in the table.
67+ */
68+public class Jsr353JsonColumn {
69+
70+ static String[] CONTACT_POINTS = {"127.0.0.1"};
71+ static int PORT = 9042;
72+
73+ public static void main(String[] args) {
74+ Cluster cluster = null;
75+ try {
76+
77+ // A codec to convert JSON payloads into JsonObject instances;
78+ // this codec is declared in the driver-extras module
79+ Jsr353JsonCodec userCodec = new Jsr353JsonCodec();
80+
81+ cluster = Cluster.builder()
82+ .addContactPoints(CONTACT_POINTS).withPort(PORT)
83+ .withCodecRegistry(new CodecRegistry().register(userCodec))
84+ .build();
85+
86+ Session session = cluster.connect();
87+
88+ createSchema(session);
89+ insertJsonColumn(session);
90+ selectJsonColumn(session);
91+
92+ } finally {
93+ if (cluster != null) cluster.close();
94+ }
95+ }
96+
97+ private static void createSchema(Session session) {
98+ session.execute("CREATE KEYSPACE IF NOT EXISTS examples " +
99+ "WITH replication = {'class': 'SimpleStrategy', 'replication_factor': 1}");
100+ session.execute("CREATE TABLE IF NOT EXISTS examples.json_jsr353_column(" +
101+ "id int PRIMARY KEY, json text)");
102+ }
103+
104+ // Mapping a JSON object to a table column
105+ private static void insertJsonColumn(Session session) {
106+
107+ JsonObject alice = Json.createObjectBuilder()
108+ .add("name", "alice")
109+ .add("age", 30)
110+ .build();
111+
112+ JsonObject bob = Json.createObjectBuilder()
113+ .add("name", "bob")
114+ .add("age", 35)
115+ .build();
116+
117+ // Build and execute a simple statement
118+ Statement stmt = insertInto("examples", "json_jsr353_column")
119+ .value("id", 1)
120+ // the JSON object will be converted into a String and persisted into the VARCHAR column "json"
121+ .value("json", alice);
122+ session.execute(stmt);
123+
124+ // The JSON object can be a bound value if the statement is prepared
125+ // (we use a local variable here for the sake of example, but in a real application you would cache and reuse
126+ // the prepared statement)
127+ PreparedStatement pst = session.prepare(
128+ insertInto("examples", "json_jsr353_column")
129+ .value("id", bindMarker("id"))
130+ .value("json", bindMarker("json")));
131+ session.execute(pst.bind()
132+ .setInt("id", 2)
133+ // note that the codec requires that the type passed to the set() method
134+ // be always JsonStructure, and not a subclass of it, such as JsonObject
135+ .set("json", bob, JsonStructure.class));
136+ }
137+
138+ // Retrieving JSON objects from a table column
139+ private static void selectJsonColumn(Session session) {
140+
141+ Statement stmt = select()
142+ .from("examples", "json_jsr353_column")
143+ .where(in("id", 1, 2));
144+
145+ ResultSet rows = session.execute(stmt);
146+
147+ for (Row row : rows) {
148+ int id = row.getInt("id");
149+ // retrieve the JSON payload and convert it to a JsonObject instance
150+ // note that the codec requires that the type passed to the get() method
151+ // be always JsonStructure, and not a subclass of it, such as JsonObject,
152+ // hence the need to downcast to JsonObject manually
153+ JsonObject user = (JsonObject) row.get("json", JsonStructure.class);
154+ // it is also possible to retrieve the raw JSON payload
155+ String json = row.getString("json");
156+ System.out.printf("Retrieved row:%n" +
157+ "id %d%n" +
158+ "user %s%n" +
159+ "user (raw) %s%n%n",
160+ id, user, json);
161+ }
162+ }
163+
164+}
added driver-examples/src/main/java/com/datastax/driver/examples/json/Jsr353JsonFunction.java +201 −0
@@ -0,0 +1,201 @@
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.examples.json;
17+
18+import com.datastax.driver.core.*;
19+import com.datastax.driver.extras.codecs.json.Jsr353JsonCodec;
20+
21+import javax.json.Json;
22+import javax.json.JsonObject;
23+import javax.json.JsonStructure;
24+
25+import static com.datastax.driver.core.querybuilder.QueryBuilder.*;
26+
27+/**
28+ * Illustrates how to map a single table column of an arbitrary type
29+ * to a Java object using
30+ * the <a href="https://jcp.org/en/jsr/detail?id=353">Java API for JSON processing</a>,
31+ * and leveraging the {@code toJson()} and {@code fromJson()} functions
32+ * introduced in Cassandra 2.2.
33+ * <p/>
34+ * This example makes usage of a custom {@link TypeCodec codec},
35+ * {@link Jsr353JsonCodec}, which is declared in the driver-extras module.
36+ * If you plan to follow this example, make sure to include the following
37+ * Maven dependencies in your project:
38+ * <pre>{@code
39+ * <dependency>
40+ * <groupId>com.datastax.cassandra</groupId>
41+ * <artifactId>cassandra-driver-extras</artifactId>
42+ * <version>${driver.version}</version>
43+ * </dependency>
44+ *
45+ * <dependency>
46+ * <groupId>javax.json</groupId>
47+ * <artifactId>javax.json-api</artifactId>
48+ * <version>${jsr353-api.version}</version>
49+ * </dependency>
50+ *
51+ * <dependency>
52+ * <groupId>org.glassfish</groupId>
53+ * <artifactId>javax.json</artifactId>
54+ * <version>${jsr353-ri.version}</version>
55+ * <scope>runtime</scope>
56+ * </dependency>
57+ * }</pre>
58+ * This example also uses the {@link com.datastax.driver.core.querybuilder.QueryBuilder QueryBuilder};
59+ * for examples using the "core" API, see {@link PlainTextJson} (they are easily translatable to the
60+ * queries in this class).
61+ * <p/>
62+ * Preconditions:
63+ * - a Cassandra cluster is running and accessible through the contacts points identified by CONTACT_POINTS and PORT;
64+ * <p/>
65+ * Side effects:
66+ * - creates a new keyspace "examples" in the cluster. If a keyspace with this name already exists, it will be reused;
67+ * - creates a user-defined type (UDT) "examples.json_jsr353_function_user". If it already exists, it will be reused;
68+ * - creates a table "examples.json_jsr353_function". If it already exists, it will be reused;
69+ * - inserts data in the table.
70+ *
71+ * @see <a href="http://www.datastax.com/dev/blog/whats-new-in-cassandra-2-2-json-support">What’s New in Cassandra 2.2: JSON Support</a>
72+ */
73+public class Jsr353JsonFunction {
74+
75+ static String[] CONTACT_POINTS = {"127.0.0.1"};
76+ static int PORT = 9042;
77+
78+ public static void main(String[] args) {
79+ Cluster cluster = null;
80+ try {
81+
82+ // A codec to convert JSON payloads into JsonObject instances;
83+ // this codec is declared in the driver-extras module
84+ Jsr353JsonCodec userCodec = new Jsr353JsonCodec();
85+
86+ cluster = Cluster.builder()
87+ .addContactPoints(CONTACT_POINTS).withPort(PORT)
88+ .withCodecRegistry(new CodecRegistry()
89+ .register(userCodec))
90+ .build();
91+
92+ Session session = cluster.connect();
93+
94+ createSchema(session);
95+ insertFromJson(session);
96+ selectToJson(session);
97+
98+ } finally {
99+ if (cluster != null) cluster.close();
100+ }
101+ }
102+
103+ private static void createSchema(Session session) {
104+ session.execute("CREATE KEYSPACE IF NOT EXISTS examples " +
105+ "WITH replication = {'class': 'SimpleStrategy', 'replication_factor': 1}");
106+ session.execute("CREATE TYPE IF NOT EXISTS examples.json_jsr353_function_user(" +
107+ "name text, age int)");
108+ session.execute("CREATE TABLE IF NOT EXISTS examples.json_jsr353_function(" +
109+ "id int PRIMARY KEY, user frozen<json_jsr353_function_user>, scores map<varchar,float>)");
110+ }
111+
112+ // Mapping JSON payloads to table columns of arbitrary types,
113+ // using fromJson() function
114+ private static void insertFromJson(Session session) {
115+
116+ JsonObject alice = Json.createObjectBuilder()
117+ .add("name", "alice")
118+ .add("age", 30)
119+ .build();
120+
121+ JsonObject bob = Json.createObjectBuilder()
122+ .add("name", "bob")
123+ .add("age", 35)
124+ .build();
125+
126+ JsonObject aliceScores = Json.createObjectBuilder()
127+ .add("call_of_duty", 4.8)
128+ .add("pokemon_go", 9.7)
129+ .build();
130+
131+ JsonObject bobScores = Json.createObjectBuilder()
132+ .add("zelda", 8.3)
133+ .add("pokemon_go", 12.4)
134+ .build();
135+
136+ // Build and execute a simple statement
137+ Statement stmt = insertInto("examples", "json_jsr353_function")
138+ .value("id", 1)
139+ // client-side, the JsonObject will be converted into a JSON String;
140+ // then, server-side, the fromJson() function will convert that JSON string
141+ // into an instance of the json_jsr353_function_user user-defined type (UDT),
142+ // which will be persisted into the column "user"
143+ .value("user", fromJson(alice))
144+ // same thing, but this time converting from
145+ // a JsonObject to a JSON string, then from this string to a map<varchar,float>
146+ .value("scores", fromJson(aliceScores));
147+ session.execute(stmt);
148+
149+ // The JSON object can be a bound value if the statement is prepared
150+ // (we use a local variable here for the sake of example, but in a real application you would cache and reuse
151+ // the prepared statement)
152+ PreparedStatement pst = session.prepare(
153+ insertInto("examples", "json_jsr353_function")
154+ .value("id", bindMarker("id"))
155+ .value("user", fromJson(bindMarker("user")))
156+ .value("scores", fromJson(bindMarker("scores"))));
157+ session.execute(pst.bind()
158+ .setInt("id", 2)
159+ // note that the codec requires that the type passed to the set() method
160+ // be always JsonStructure, and not a subclass of it, such as JsonObject
161+ .set("user", bob, JsonStructure.class)
162+ .set("scores", bobScores, JsonStructure.class));
163+ }
164+
165+ // Retrieving JSON payloads from table columns of arbitrary types,
166+ // using toJson() function
167+ private static void selectToJson(Session session) {
168+
169+ Statement stmt = select()
170+ .column("id")
171+ .toJson("user").as("user")
172+ .toJson("scores").as("scores")
173+ .from("examples", "json_jsr353_function")
174+ .where(in("id", 1, 2));
175+
176+ ResultSet rows = session.execute(stmt);
177+
178+ for (Row row : rows) {
179+ int id = row.getInt("id");
180+ // retrieve the JSON payload and convert it to a JsonObject instance
181+ // note that the codec requires that the type passed to the get() method
182+ // be always JsonStructure, and not a subclass of it, such as JsonObject,
183+ // hence the need to downcast to JsonObject manually
184+ JsonObject user = (JsonObject) row.get("user", JsonStructure.class);
185+ // it is also possible to retrieve the raw JSON payload
186+ String userJson = row.getString("user");
187+ // retrieve the JSON payload and convert it to a JsonObject instance
188+ JsonObject scores = (JsonObject) row.get("scores", JsonStructure.class);
189+ // it is also possible to retrieve the raw JSON payload
190+ String scoresJson = row.getString("scores");
191+ System.out.printf("Retrieved row:%n" +
192+ "id %d%n" +
193+ "user %s%n" +
194+ "user (raw) %s%n" +
195+ "scores %s%n" +
196+ "scores (raw) %s%n%n",
197+ id, user, userJson, scores, scoresJson);
198+ }
199+ }
200+
201+}
added driver-examples/src/main/java/com/datastax/driver/examples/json/Jsr353JsonRow.java +159 −0
@@ -0,0 +1,159 @@
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.examples.json;
17+
18+import com.datastax.driver.core.*;
19+import com.datastax.driver.extras.codecs.json.Jsr353JsonCodec;
20+
21+import javax.json.Json;
22+import javax.json.JsonObject;
23+import javax.json.JsonStructure;
24+
25+import static com.datastax.driver.core.querybuilder.QueryBuilder.*;
26+
27+/**
28+ * Illustrates how to map an entire table row to a Java object using
29+ * the <a href="https://jcp.org/en/jsr/detail?id=353">Java API for JSON processing</a>,
30+ * and leveraging the {@code SELECT JSON} and {@code INSERT JSON} syntaxes
31+ * introduced in Cassandra 2.2.
32+ * <p/>
33+ * This example makes usage of a custom {@link TypeCodec codec},
34+ * {@link Jsr353JsonCodec}, which is declared in the driver-extras module.
35+ * If you plan to follow this example, make sure to include the following
36+ * Maven dependencies in your project:
37+ * <pre>{@code
38+ * <dependency>
39+ * <groupId>com.datastax.cassandra</groupId>
40+ * <artifactId>cassandra-driver-extras</artifactId>
41+ * <version>${driver.version}</version>
42+ * </dependency>
43+ *
44+ * <dependency>
45+ * <groupId>javax.json</groupId>
46+ * <artifactId>javax.json-api</artifactId>
47+ * <version>${jsr353-api.version}</version>
48+ * </dependency>
49+ *
50+ * <dependency>
51+ * <groupId>org.glassfish</groupId>
52+ * <artifactId>javax.json</artifactId>
53+ * <version>${jsr353-ri.version}</version>
54+ * <scope>runtime</scope>
55+ * </dependency>
56+ * }</pre>
57+ * This example also uses the {@link com.datastax.driver.core.querybuilder.QueryBuilder QueryBuilder};
58+ * for examples using the "core" API, see {@link PlainTextJson} (they are easily translatable to the
59+ * queries in this class).
60+ * <p/>
61+ * Preconditions:
62+ * - a Cassandra 2.2+ cluster is running and accessible through the contacts points identified by CONTACT_POINTS and PORT;
63+ * <p/>
64+ * Side effects:
65+ * - creates a new keyspace "examples" in the cluster. If a keyspace with this name already exists, it will be reused;
66+ * - creates a table "examples.json_jsr353_row". If it already exists, it will be reused;
67+ * - inserts data in the table.
68+ *
69+ * @see <a href="http://www.datastax.com/dev/blog/whats-new-in-cassandra-2-2-json-support">What’s New in Cassandra 2.2: JSON Support</a>
70+ */
71+public class Jsr353JsonRow {
72+
73+ static String[] CONTACT_POINTS = {"127.0.0.1"};
74+ static int PORT = 9042;
75+
76+ public static void main(String[] args) {
77+ Cluster cluster = null;
78+ try {
79+
80+ // A codec to convert JSON payloads into JsonObject instances;
81+ // this codec is declared in the driver-extras module
82+ Jsr353JsonCodec userCodec = new Jsr353JsonCodec();
83+
84+ cluster = Cluster.builder()
85+ .addContactPoints(CONTACT_POINTS).withPort(PORT)
86+ .withCodecRegistry(new CodecRegistry().register(userCodec))
87+ .build();
88+
89+ Session session = cluster.connect();
90+
91+ createSchema(session);
92+ insertJsonRow(session);
93+ selectJsonRow(session);
94+
95+ } finally {
96+ if (cluster != null) cluster.close();
97+ }
98+ }
99+
100+ private static void createSchema(Session session) {
101+ session.execute("CREATE KEYSPACE IF NOT EXISTS examples " +
102+ "WITH replication = {'class': 'SimpleStrategy', 'replication_factor': 1}");
103+ session.execute("CREATE TABLE IF NOT EXISTS examples.json_jsr353_row(" +
104+ "id int PRIMARY KEY, name text, age int)");
105+ }
106+
107+ // Mapping a User instance to a table row using INSERT JSON
108+ private static void insertJsonRow(Session session) {
109+
110+ JsonObject alice = Json.createObjectBuilder()
111+ .add("id", 1)
112+ .add("name", "alice")
113+ .add("age", 30)
114+ .build();
115+
116+ JsonObject bob = Json.createObjectBuilder()
117+ .add("id", 2)
118+ .add("name", "bob")
119+ .add("age", 35)
120+ .build();
121+
122+ // Build and execute a simple statement
123+ Statement stmt = insertInto("examples", "json_jsr353_row")
124+ .json(alice);
125+ session.execute(stmt);
126+
127+ // The JSON object can be a bound value if the statement is prepared
128+ // (we use a local variable here for the sake of example, but in a real application you would cache and reuse
129+ // the prepared statement)
130+ PreparedStatement pst = session.prepare(
131+ insertInto("examples", "json_jsr353_row").json(bindMarker("user")));
132+ session.execute(pst.bind()
133+ // note that the codec requires that the type passed to the set() method
134+ // be always JsonStructure, and not a subclass of it, such as JsonObject
135+ .set("user", bob, JsonStructure.class));
136+ }
137+
138+ // Retrieving User instances from table rows using SELECT JSON
139+ private static void selectJsonRow(Session session) {
140+
141+ // Reading the whole row as a JSON object
142+ Statement stmt = select().json()
143+ .from("examples", "json_jsr353_row")
144+ .where(in("id", 1, 2));
145+
146+ ResultSet rows = session.execute(stmt);
147+
148+ for (Row row : rows) {
149+ // SELECT JSON returns only one column for each row, of type VARCHAR,
150+ // containing the row as a JSON payload.
151+ // Note that the codec requires that the type passed to the get() method
152+ // be always JsonStructure, and not a subclass of it, such as JsonObject,
153+ // hence the need to downcast to JsonObject manually
154+ JsonObject user = (JsonObject) row.get(0, JsonStructure.class);
155+ System.out.printf("Retrieved user: %s%n", user);
156+ }
157+ }
158+
159+}
added driver-examples/src/main/java/com/datastax/driver/examples/json/PlainTextJson.java +152 −0
@@ -0,0 +1,152 @@
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.examples.json;
17+
18+import com.datastax.driver.core.*;
19+
20+import static com.datastax.driver.core.querybuilder.QueryBuilder.*;
21+
22+/**
23+ * Illustrates basic JSON support with plain JSON strings. For more advanced examples using complex objects and custom
24+ * codecs, refer to the other examples in this package.
25+ * <p/>
26+ * Preconditions:
27+ * - a Cassandra 2.2+ cluster is running and accessible through the contacts points identified by CONTACT_POINTS and
28+ * PORT;
29+ * <p/>
30+ * Side effects:
31+ * - creates a new keyspace "examples" in the cluster. If a keyspace with this name already exists, it will be reused;
32+ * - creates a table "examples.querybuilder_json". If it already exists, it will be reused;
33+ * - inserts data in the table.
34+ *
35+ * @see <a href="http://www.datastax.com/dev/blog/whats-new-in-cassandra-2-2-json-support">What’s New in Cassandra 2.2: JSON Support</a>
36+ */
37+public class PlainTextJson {
38+
39+ static String[] CONTACT_POINTS = {"127.0.0.1"};
40+ static int PORT = 9042;
41+
42+ public static void main(String[] args) {
43+ Cluster cluster = null;
44+ try {
45+ cluster = Cluster.builder()
46+ .addContactPoints(CONTACT_POINTS).withPort(PORT)
47+ .build();
48+ Session session = cluster.connect();
49+
50+ createSchema(session);
51+
52+ insertWithCoreApi(session);
53+ selectWithCoreApi(session);
54+
55+ insertWithQueryBuilder(session);
56+ selectWithQueryBuilder(session);
57+ } finally {
58+ if (cluster != null) cluster.close();
59+ }
60+ }
61+
62+ private static void createSchema(Session session) {
63+ session.execute("CREATE KEYSPACE IF NOT EXISTS examples " +
64+ "WITH replication = {'class': 'SimpleStrategy', 'replication_factor': 1}");
65+ session.execute("CREATE TABLE IF NOT EXISTS examples.querybuilder_json(" +
66+ "id int PRIMARY KEY, name text, specs map<text, text>)");
67+ }
68+
69+ /**
70+ * Demonstrates data insertion with the "core" API, i.e. providing the full query strings.
71+ */
72+ private static void insertWithCoreApi(Session session) {
73+ // Bind in a simple statement:
74+ session.execute("INSERT INTO examples.querybuilder_json JSON ?",
75+ "{ \"id\": 1, \"name\": \"Mouse\", \"specs\": { \"color\": \"silver\" } }");
76+
77+ // Bind in a prepared statement:
78+ // (we use a local variable here for the sake of example, but in a real application you would cache and reuse
79+ // the prepared statement)
80+ PreparedStatement pst = session.prepare("INSERT INTO examples.querybuilder_json JSON :payload");
81+ session.execute(pst.bind()
82+ .setString("payload", "{ \"id\": 2, \"name\": \"Keyboard\", \"specs\": { \"layout\": \"qwerty\" } }"));
83+
84+ // fromJson lets you provide individual columns as JSON:
85+ session.execute("INSERT INTO examples.querybuilder_json " +
86+ "(id, name, specs) VALUES (?, ?, fromJson(?))",
87+ 3, "Screen", "{ \"size\": \"24-inch\" }");
88+ }
89+
90+ /**
91+ * Demonstrates data retrieval with the "core" API, i.e. providing the full query strings.
92+ */
93+ private static void selectWithCoreApi(Session session) {
94+ // Reading the whole row as a JSON object:
95+ Row row = session.execute("SELECT JSON * FROM examples.querybuilder_json WHERE id = ?", 1).one();
96+ System.out.printf("Entry #1 as JSON: %s%n", row.getString("[json]"));
97+
98+ // Extracting a particular column as JSON:
99+ row = session.execute("SELECT id, toJson(specs) AS json_specs FROM examples.querybuilder_json WHERE id = ?", 2)
100+ .one();
101+ System.out.printf("Entry #%d's specs as JSON: %s%n",
102+ row.getInt("id"), row.getString("json_specs"));
103+ }
104+
105+ /**
106+ * Same as {@link #insertWithCoreApi(Session)}, but using {@link com.datastax.driver.core.querybuilder.QueryBuilder}
107+ * to construct the queries.
108+ */
109+ private static void insertWithQueryBuilder(Session session) {
110+ // Simple statement:
111+ Statement stmt = insertInto("examples", "querybuilder_json")
112+ .json("{ \"id\": 1, \"name\": \"Mouse\", \"specs\": { \"color\": \"silver\" } }");
113+ session.execute(stmt);
114+
115+ // Prepare and bind:
116+ // (again, cache the prepared statement in a real application)
117+ PreparedStatement pst = session.prepare(
118+ insertInto("examples", "querybuilder_json").json(bindMarker("payload")));
119+ session.execute(pst.bind()
120+ .setString("payload", "{ \"id\": 2, \"name\": \"Keyboard\", \"specs\": { \"layout\": \"qwerty\" } }"));
121+
122+ // fromJson on a single column:
123+ stmt = insertInto("examples", "querybuilder_json")
124+ .value("id", 3)
125+ .value("name", "Screen")
126+ .value("specs", fromJson("{ \"size\": \"24-inch\" }"));
127+ session.execute(stmt);
128+ }
129+
130+ /**
131+ * Same as {@link #selectWithCoreApi(Session)}, but using {@link com.datastax.driver.core.querybuilder.QueryBuilder}
132+ * to construct the queries.
133+ */
134+ private static void selectWithQueryBuilder(Session session) {
135+ // Reading the whole row as a JSON object:
136+ Statement stmt = select().json()
137+ .from("examples", "querybuilder_json")
138+ .where(eq("id", 1));
139+ Row row = session.execute(stmt).one();
140+ System.out.printf("Entry #1 as JSON: %s%n", row.getString("[json]"));
141+
142+ // Extracting a particular column as JSON:
143+ stmt = select()
144+ .column("id")
145+ .toJson("specs").as("json_specs")
146+ .from("examples", "querybuilder_json")
147+ .where(eq("id", 2));
148+ row = session.execute(stmt).one();
149+ System.out.printf("Entry #%d's specs as JSON: %s%n",
150+ row.getInt("id"), row.getString("json_specs"));
151+ }
152+}
modified driver-extras/src/main/java/com/datastax/driver/extras/codecs/json/JacksonJsonCodec.java +40 −2
@@ -25,6 +25,7 @@
2525 import com.fasterxml.jackson.databind.JavaType;
2626 import com.fasterxml.jackson.databind.ObjectMapper;
2727 import com.fasterxml.jackson.databind.type.TypeFactory;
28+import com.google.common.reflect.TypeToken;
2829
2930 import java.io.IOException;
3031 import java.nio.ByteBuffer;
@@ -50,10 +51,47 @@
5051 */
5152 public class JacksonJsonCodec<T> extends TypeCodec<T> {
5253
53- private final ObjectMapper objectMapper = new ObjectMapper();
54+ private final ObjectMapper objectMapper;
5455
55- public JacksonJsonCodec(Class<T> javaType) {
56+ /**
57+ * Creates a new instance for the provided {@code javaClass},
58+ * using a default, newly-allocated {@link ObjectMapper}.
59+ *
60+ * @param javaClass the Java class this codec maps to.
61+ */
62+ public JacksonJsonCodec(Class<T> javaClass) {
63+ this(javaClass, new ObjectMapper());
64+ }
65+
66+ /**
67+ * Creates a new instance for the provided {@code javaType},
68+ * using a default, newly-allocated {@link ObjectMapper}.
69+ *
70+ * @param javaType the Java type this codec maps to.
71+ */
72+ public JacksonJsonCodec(TypeToken<T> javaType) {
73+ this(javaType, new ObjectMapper());
74+ }
75+
76+ /**
77+ * Creates a new instance for the provided {@code javaClass},
78+ * and using the provided {@link ObjectMapper}.
79+ *
80+ * @param javaClass the Java class this codec maps to.
81+ */
82+ public JacksonJsonCodec(Class<T> javaClass, ObjectMapper objectMapper) {
83+ this(TypeToken.of(javaClass), objectMapper);
84+ }
85+
86+ /**
87+ * Creates a new instance for the provided {@code javaType},
88+ * and using the provided {@link ObjectMapper}.
89+ *
90+ * @param javaType the Java type this codec maps to.
91+ */
92+ public JacksonJsonCodec(TypeToken<T> javaType, ObjectMapper objectMapper) {
5693 super(DataType.varchar(), javaType);
94+ this.objectMapper = objectMapper;
5795 }
5896
5997 @Override
modified driver-extras/src/main/java/com/datastax/driver/extras/codecs/json/Jsr353JsonCodec.java +9 −1
@@ -65,7 +65,7 @@
6565 * <artifactId>javax.json-api</artifactId>
6666 * <version>1.0</version>
6767 * </dependency>
68- * <p/>
68+ *
6969 * <dependency>
7070 * <groupId>org.glassfish</groupId>
7171 * <artifactId>javax.json</artifactId>
@@ -79,10 +79,18 @@
7979
8080 private final JsonWriterFactory writerFactory;
8181
82+ /**
83+ * Creates a new instance using a default configuration.
84+ */
8285 public Jsr353JsonCodec() {
8386 this(null);
8487 }
8588
89+ /**
90+ * Creates a new instance using the provided configuration.
91+ *
92+ * @param config A map of provider-specific configuration properties. May be empty or {@code null}.
93+ */
8694 public Jsr353JsonCodec(Map<String, ?> config) {
8795 super(DataType.varchar(), JsonStructure.class);
8896 readerFactory = Json.createReaderFactory(config);
modified driver-extras/src/test/java/com/datastax/driver/extras/codecs/json/Jsr353JsonCodecTest.java +1 −1
@@ -70,7 +70,7 @@
7070 @Override
7171 public Cluster.Builder createClusterBuilder() {
7272 return Cluster.builder().withCodecRegistry(
73- new CodecRegistry().register(jsonCodec) // global User <-> varchar codec
73+ new CodecRegistry().register(jsonCodec) // global JsonStructure <-> varchar codec
7474 );
7575 }
7676