| 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 | } |