Elffuss BraidHub

kikocis/java-driver public

da3bbee57066 · 8.8 KiBRawPermalink
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 */
16package com.datastax.driver.examples.json;
17
18import com.datastax.driver.core.*;
19import com.datastax.driver.extras.codecs.json.JacksonJsonCodec;
20import com.fasterxml.jackson.annotation.JsonCreator;
21import com.fasterxml.jackson.annotation.JsonProperty;
22import com.fasterxml.jackson.databind.JsonNode;
23import com.fasterxml.jackson.databind.node.JsonNodeFactory;
24import com.fasterxml.jackson.databind.node.ObjectNode;
25
26import 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 */
67public 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}