Elffuss BraidHub

kikocis/java-driver public

86638feb1f1b · 6.4 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.*;
19
20import 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 */
37public 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}