Elffuss BraidHub

kikocis/java-driver public

JAVA-1237: Add Jackson JSON examples
Changeseta4b9527bac4a435b735d2e1f0f20dd32ea2458f820b24cd0758311edbf65ee9c
AuthorAlexandre Dutra <alexandre.dutra@datastax.com> · 2016-07-27 14:56 +02:00
Committerolim7t <omichallat+github@gmail.com> · 2016-07-27 11:55 -07:00
Parents924ea7d8c36d

Browse the files at this changeset

4 files changed

modified driver-examples/pom.xml +16 −0
@@ -41,10 +41,26 @@
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+ <!-- driver logs -->
4459 <dependency>
4560 <groupId>ch.qos.logback</groupId>
4661 <artifactId>logback-classic</artifactId>
4762 <version>1.1.3</version>
63+ <scope>runtime</scope>
4864 </dependency>
4965
5066 </dependencies>
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+}