kikocis/java-driver public
Changesets · Branches · Tags · Compare
| Changeset | d0403d53e0ee8c39a94778fc96ec8da45a02a8983bdf1009a22131c900b59a3d |
|---|---|
| Author | olim7t <omichallat+github@gmail.com> · 2016-04-06 17:16 +02:00 |
| Committer | Alexandre Dutra <alexandre.dutra@datastax.com> · 2016-05-02 17:20 +02:00 |
| Parents | 375951765914 |
4 files changed
modified changelog/README.md +1 −0
| @@ -21,6 +21,7 @@ | ||
| 21 | 21 | - [improvement] JAVA-1164: Clarify documentation on Host.listenAddress and broadcastAddress. |
| 22 | 22 | - [improvement] JAVA-1171: Add Host method to determine if DSE Graph is enabled. |
| 23 | 23 | - [improvement]: JAVA-1069: Bootstrap driver-examples module. |
| 24 | +- [documentation] JAVA-1150: Add example and FAQ entry about ByteBuffer/BLOB. | |
| 24 | 25 | |
| 25 | 26 | Merged from 2.1 branch: |
| 26 | 27 |
added driver-examples/src/main/java/com/datastax/driver/examples/datatypes/Blobs.java +253 −0
| @@ -0,0 +1,253 @@ | ||
| 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.datatypes; | |
| 17 | + | |
| 18 | +import com.datastax.driver.core.*; | |
| 19 | +import com.datastax.driver.core.utils.Bytes; | |
| 20 | +import com.google.common.collect.ImmutableMap; | |
| 21 | + | |
| 22 | +import java.io.*; | |
| 23 | +import java.nio.ByteBuffer; | |
| 24 | +import java.nio.channels.FileChannel; | |
| 25 | +import java.util.Map; | |
| 26 | + | |
| 27 | +/** | |
| 28 | + * Inserts and retrieves values in BLOB columns. | |
| 29 | + * <p/> | |
| 30 | + * By default, the Java driver maps this type to {@link java.nio.ByteBuffer}. The ByteBuffer API is a bit tricky to use | |
| 31 | + * at times, so we will show common pitfalls as well. We strongly recommend that you read the {@link java.nio.Buffer} | |
| 32 | + * and {@link ByteBuffer} API docs and become familiar with the capacity, limit and position properties. | |
| 33 | + * <a href="http://tutorials.jenkov.com/java-nio/buffers.html">This tutorial</a> might also help. | |
| 34 | + * <p/> | |
| 35 | + * Preconditions: | |
| 36 | + * - a Cassandra cluster is running and accessible through the contacts points identified by CONTACT_POINTS and PORT; | |
| 37 | + * - FILE references an existing file. | |
| 38 | + * <p/> | |
| 39 | + * Side effects: | |
| 40 | + * - creates a new keyspace "examples" in the cluster. It a keyspace with this name already exists, it will be reused; | |
| 41 | + * - creates a table "examples.blobs". If it already exists, it will be reused; | |
| 42 | + * - inserts data in the table. | |
| 43 | + */ | |
| 44 | +public class Blobs { | |
| 45 | + | |
| 46 | + static String[] CONTACT_POINTS = {"127.0.0.1"}; | |
| 47 | + static int PORT = 9042; | |
| 48 | + | |
| 49 | + static File FILE = new File(Blobs.class.getResource("/cassandra_logo.png").getFile()); | |
| 50 | + | |
| 51 | + public static void main(String[] args) throws IOException { | |
| 52 | + Cluster cluster = null; | |
| 53 | + try { | |
| 54 | + cluster = Cluster.builder() | |
| 55 | + .addContactPoints(CONTACT_POINTS).withPort(PORT) | |
| 56 | + .build(); | |
| 57 | + Session session = cluster.connect(); | |
| 58 | + | |
| 59 | + createSchema(session); | |
| 60 | + allocateAndInsert(session); | |
| 61 | + retrieveSimpleColumn(session); | |
| 62 | + retrieveMapColumn(session); | |
| 63 | + insertConcurrent(session); | |
| 64 | + insertFromAndRetrieveToFile(session); | |
| 65 | + } finally { | |
| 66 | + if (cluster != null) cluster.close(); | |
| 67 | + } | |
| 68 | + } | |
| 69 | + | |
| 70 | + private static void createSchema(Session session) { | |
| 71 | + session.execute("CREATE KEYSPACE IF NOT EXISTS examples " + | |
| 72 | + "WITH replication = {'class': 'SimpleStrategy', 'replication_factor': 1}"); | |
| 73 | + session.execute("CREATE TABLE IF NOT EXISTS examples.blobs(k int PRIMARY KEY, b blob, m map<text, blob>)"); | |
| 74 | + } | |
| 75 | + | |
| 76 | + private static void allocateAndInsert(Session session) { | |
| 77 | + // One way to get a byte buffer is to allocate it and fill it yourself: | |
| 78 | + ByteBuffer buffer = ByteBuffer.allocate(16); | |
| 79 | + while (buffer.hasRemaining()) | |
| 80 | + buffer.put((byte) 0xFF); | |
| 81 | + | |
| 82 | + // Don't forget to flip! The driver expects a buffer that is ready for reading. That is, it will consider all | |
| 83 | + // the data between buffer.position() and buffer.limit(). | |
| 84 | + // Right now we are positioned at the end because we just finished writing, so if we passed the buffer as-is it | |
| 85 | + // would appear to be empty: | |
| 86 | + assert buffer.limit() - buffer.position() == 0; | |
| 87 | + | |
| 88 | + buffer.flip(); | |
| 89 | + // Now position is back to the beginning, so the driver will see all 16 bytes. | |
| 90 | + assert buffer.limit() - buffer.position() == 16; | |
| 91 | + | |
| 92 | + session.execute("INSERT INTO examples.blobs (k, b, m) VALUES (1, ?, ?)", | |
| 93 | + buffer, ImmutableMap.of("test", buffer)); | |
| 94 | + } | |
| 95 | + | |
| 96 | + private static void retrieveSimpleColumn(Session session) { | |
| 97 | + Row row = session.execute("SELECT b, m FROM examples.blobs WHERE k = 1").one(); | |
| 98 | + | |
| 99 | + ByteBuffer buffer = row.getBytes("b"); | |
| 100 | + | |
| 101 | + // The driver always returns buffers that are ready for reading. | |
| 102 | + assert buffer.limit() - buffer.position() == 16; | |
| 103 | + | |
| 104 | + // One way to read from the buffer is to use absolute getters. Do NOT start reading at index 0, as the buffer | |
| 105 | + // might start at a different position (we'll see an example of that later). | |
| 106 | + for (int i = buffer.position(); i < buffer.limit(); i++) { | |
| 107 | + byte b = buffer.get(i); | |
| 108 | + assert b == (byte) 0xFF; | |
| 109 | + } | |
| 110 | + | |
| 111 | + // Another way is to use relative getters. | |
| 112 | + while (buffer.hasRemaining()) { | |
| 113 | + byte b = buffer.get(); | |
| 114 | + assert b == (byte) 0xFF; | |
| 115 | + } | |
| 116 | + // Note that relative getters change the position, so when we're done reading we're at the end again. | |
| 117 | + assert buffer.position() == buffer.limit(); | |
| 118 | + | |
| 119 | + // Reset the position for the next operation. | |
| 120 | + buffer.flip(); | |
| 121 | + | |
| 122 | + // Yet another way is to convert the buffer to a byte array. Do NOT use buffer.array(), because it returns the | |
| 123 | + // buffer's *backing array*, which is not the same thing as its contents: | |
| 124 | + // - not all byte buffers have backing arrays | |
| 125 | + // - even then, the backing array might be larger than the buffer's contents | |
| 126 | + // | |
| 127 | + // The driver provides a utility method that handles those details for you: | |
| 128 | + byte[] array = Bytes.getArray(buffer); | |
| 129 | + assert array.length == 16; | |
| 130 | + for (byte b : array) { | |
| 131 | + assert b == (byte) 0xFF; | |
| 132 | + } | |
| 133 | + } | |
| 134 | + | |
| 135 | + private static void retrieveMapColumn(Session session) { | |
| 136 | + Row row = session.execute("SELECT b, m FROM examples.blobs WHERE k = 1").one(); | |
| 137 | + | |
| 138 | + // The map columns illustrates the pitfalls with position() and array(). | |
| 139 | + Map<String, ByteBuffer> m = row.getMap("m", String.class, ByteBuffer.class); | |
| 140 | + ByteBuffer buffer = m.get("test"); | |
| 141 | + | |
| 142 | + // We did get back a buffer that contains 16 bytes as expected. | |
| 143 | + assert buffer.limit() - buffer.position() == 16; | |
| 144 | + // However, it is not positioned at 0. And you can also see that its backing array contains more than 16 bytes. | |
| 145 | + // What happens is that the buffer is a "view" of the last 16 of a 32-byte array. | |
| 146 | + // This is an implementation detail and you shouldn't have to worry about it if you process the buffer correctly | |
| 147 | + // (don't iterate from 0, use Bytes.getArray()). | |
| 148 | + assert buffer.position() == 16; | |
| 149 | + assert buffer.array().length == 32; | |
| 150 | + } | |
| 151 | + | |
| 152 | + private static void insertConcurrent(Session session) { | |
| 153 | + PreparedStatement preparedStatement = session.prepare("INSERT INTO examples.blobs (k, b) VALUES (1, :b)"); | |
| 154 | + | |
| 155 | + // This is another convenient utility provided by the driver. It's useful for tests. | |
| 156 | + ByteBuffer buffer = Bytes.fromHexString("0xffffff"); | |
| 157 | + | |
| 158 | + // When you pass a byte buffer to a bound statement, it creates a shallow copy internally with the | |
| 159 | + // buffer.duplicate() method. | |
| 160 | + BoundStatement boundStatement = preparedStatement.bind(); | |
| 161 | + boundStatement.setBytes("b", buffer); | |
| 162 | + | |
| 163 | + // This means you can now move in the original buffer, without affecting the insertion if it happens later. | |
| 164 | + buffer.position(buffer.limit()); | |
| 165 | + | |
| 166 | + session.execute(boundStatement); | |
| 167 | + Row row = session.execute("SELECT b FROM examples.blobs WHERE k = 1").one(); | |
| 168 | + assert Bytes.toHexString(row.getBytes("b")).equals("0xffffff"); | |
| 169 | + | |
| 170 | + buffer.flip(); | |
| 171 | + | |
| 172 | + // HOWEVER duplicate() only performs a shallow copy. The two buffers still share the same contents. So if you | |
| 173 | + // modify the contents of the original buffer, this will affect another execution of the bound statement. | |
| 174 | + buffer.put(0, (byte) 0xaa); | |
| 175 | + session.execute(boundStatement); | |
| 176 | + row = session.execute("SELECT b FROM examples.blobs WHERE k = 1").one(); | |
| 177 | + assert Bytes.toHexString(row.getBytes("b")).equals("0xaaffff"); | |
| 178 | + | |
| 179 | + // This will also happen if you use the async API, e.g. create the bound statement, call executeAsync() on it | |
| 180 | + // and reuse the buffer immediately. | |
| 181 | + | |
| 182 | + // If you reuse buffers concurrently and want to avoid those issues, perform a deep copy of the buffer before | |
| 183 | + // passing it to the bound statement. | |
| 184 | + int startPosition = buffer.position(); | |
| 185 | + ByteBuffer buffer2 = ByteBuffer.allocate(buffer.limit() - startPosition); | |
| 186 | + buffer2.put(buffer); | |
| 187 | + buffer.position(startPosition); | |
| 188 | + buffer2.flip(); | |
| 189 | + boundStatement.setBytes("b", buffer2); | |
| 190 | + session.execute(boundStatement); | |
| 191 | + | |
| 192 | + // Note: unlike BoundStatement, SimpleStatement does not duplicate its arguments, so even the position will be | |
| 193 | + // affected if you change it before executing the statement. Again, resort to deep copies if required. | |
| 194 | + } | |
| 195 | + | |
| 196 | + private static void insertFromAndRetrieveToFile(Session session) throws IOException { | |
| 197 | + ByteBuffer buffer = readAll(FILE); | |
| 198 | + session.execute("INSERT INTO examples.blobs (k, b) VALUES (1, ?)", buffer); | |
| 199 | + | |
| 200 | + File tmpFile = File.createTempFile("blob", ".png"); | |
| 201 | + System.out.printf("Writing retrieved buffer to %s%n", tmpFile.getAbsoluteFile()); | |
| 202 | + | |
| 203 | + Row row = session.execute("SELECT b FROM examples.blobs WHERE k = 1").one(); | |
| 204 | + writeAll(row.getBytes("b"), tmpFile); | |
| 205 | + } | |
| 206 | + | |
| 207 | + // Note: | |
| 208 | + // - this is written with Java 6 APIs; if you're on a more recent version this can be improved (try-with-resources, | |
| 209 | + // new-new io...) | |
| 210 | + // - this reads the whole file in memory in one go. If your file does not fit in memory you should probably not | |
| 211 | + // insert it into Cassandra either ;) | |
| 212 | + private static ByteBuffer readAll(File file) throws IOException { | |
| 213 | + FileInputStream inputStream = null; | |
| 214 | + boolean threw = false; | |
| 215 | + try { | |
| 216 | + inputStream = new FileInputStream(file); | |
| 217 | + FileChannel channel = inputStream.getChannel(); | |
| 218 | + ByteBuffer buffer = ByteBuffer.allocate((int) channel.size()); | |
| 219 | + channel.read(buffer); | |
| 220 | + buffer.flip(); | |
| 221 | + return buffer; | |
| 222 | + } catch (IOException e) { | |
| 223 | + threw = true; | |
| 224 | + throw e; | |
| 225 | + } finally { | |
| 226 | + close(inputStream, threw); | |
| 227 | + } | |
| 228 | + } | |
| 229 | + | |
| 230 | + private static void writeAll(ByteBuffer buffer, File file) throws IOException { | |
| 231 | + FileOutputStream outputStream = null; | |
| 232 | + boolean threw = false; | |
| 233 | + try { | |
| 234 | + outputStream = new FileOutputStream(file); | |
| 235 | + FileChannel channel = outputStream.getChannel(); | |
| 236 | + channel.write(buffer); | |
| 237 | + } catch (IOException e) { | |
| 238 | + threw = true; | |
| 239 | + throw e; | |
| 240 | + } finally { | |
| 241 | + close(outputStream, threw); | |
| 242 | + } | |
| 243 | + } | |
| 244 | + | |
| 245 | + private static void close(Closeable inputStream, boolean threw) throws IOException { | |
| 246 | + if (inputStream != null) | |
| 247 | + try { | |
| 248 | + inputStream.close(); | |
| 249 | + } catch (IOException e) { | |
| 250 | + if (!threw) throw e; // else preserve original exception | |
| 251 | + } | |
| 252 | + } | |
| 253 | +} |
added driver-examples/src/main/resources/cassandra_logo.png +0 −0
Binary content is not shown. View the file.
modified faq/README.md +19 −0
| @@ -11,6 +11,7 @@ | ||
| 11 | 11 | CQL with `LIMIT` and the `token()` function. See |
| 12 | 12 | [this conversation](https://groups.google.com/a/lists.datastax.com/d/msg/java-driver-user/U2KzAHruWO4/6vDmUVDDkOwJ) on the mailing list. |
| 13 | 13 | |
| 14 | + | |
| 14 | 15 | ### Can I check if a conditional statement (lightweight transaction) was successful? |
| 15 | 16 | |
| 16 | 17 | When executing a conditional statement, the `ResultSet` will contain a single `Row` with a |
| @@ -36,6 +37,7 @@ | ||
| 36 | 37 | |
| 37 | 38 | [wasApplied]: http://docs.datastax.com/en/drivers/java/2.1/com/datastax/driver/core/ResultSet.html#wasApplied-- |
| 38 | 39 | |
| 40 | + | |
| 39 | 41 | ### What is a parameterized statement and how can I use it? |
| 40 | 42 | |
| 41 | 43 | Starting with Cassandra 2.0, normal statements (that is non-prepared statements) do |
| @@ -49,12 +51,14 @@ | ||
| 49 | 51 | |
| 50 | 52 | See [Simple statements](../manual/statements/simple/) for more information. |
| 51 | 53 | |
| 54 | + | |
| 52 | 55 | ### Does a parameterized statement escape parameters? |
| 53 | 56 | |
| 54 | 57 | A parameterized statement sends the values of parameters separate from the query |
| 55 | 58 | (similar to the way a prepared statement does) as bytes so there is no need to escape |
| 56 | 59 | parameters. |
| 57 | 60 | |
| 61 | + | |
| 58 | 62 | ### What's the difference between a parameterized statement and a Prepared statement? |
| 59 | 63 | |
| 60 | 64 | The only similarity between a parameterized statement and a prepared statement is in |
| @@ -67,6 +71,7 @@ | ||
| 67 | 71 | |
| 68 | 72 | See [Prepared statements](../manual/statements/prepared/) for more information. |
| 69 | 73 | |
| 74 | + | |
| 70 | 75 | ### Can I combine `PreparedStatements` and normal statements in a batch? |
| 71 | 76 | |
| 72 | 77 | Yes. A batch can include both bound statements and simple statements: |
| @@ -82,6 +87,7 @@ | ||
| 82 | 87 | session.execute(batch); |
| 83 | 88 | ``` |
| 84 | 89 | |
| 90 | + | |
| 85 | 91 | ### Can I get the raw bytes of a text column? |
| 86 | 92 | |
| 87 | 93 | If you need to access the raw bytes of a text column, call the |
| @@ -90,6 +96,7 @@ | ||
| 90 | 96 | Trying to use `Row.getBytes("columnName")` for the same purpose results in an |
| 91 | 97 | exception, as the `getBytes` method can only be used if the column has the CQL type `BLOB`. |
| 92 | 98 | |
| 99 | + | |
| 93 | 100 | ### How do I increment counters with `QueryBuilder`? |
| 94 | 101 | |
| 95 | 102 | Considering the following query: |
| @@ -106,6 +113,7 @@ | ||
| 106 | 113 | .where(eq("userid", id)); |
| 107 | 114 | ``` |
| 108 | 115 | |
| 116 | + | |
| 109 | 117 | ### Is there a way to control the batch size of the results returned from a query? |
| 110 | 118 | |
| 111 | 119 | Use the `setFetchSize()` method on your `Statement` object. The fetch size controls |
| @@ -118,6 +126,7 @@ | ||
| 118 | 126 | |
| 119 | 127 | See [Paging](../manual/paging/) for more information. |
| 120 | 128 | |
| 129 | + | |
| 121 | 130 | ### What's the difference between using `setFetchSize()` and `LIMIT`? |
| 122 | 131 | |
| 123 | 132 | Basically, `LIMIT` controls the maximum number of results returned by the query, |
| @@ -128,3 +137,13 @@ | ||
| 128 | 137 | rows each. |
| 129 | 138 | |
| 130 | 139 | See [Paging](../manual/paging/) for more information. |
| 140 | + | |
| 141 | + | |
| 142 | +### I'm reading a BLOB column and the driver returns incorrect data. | |
| 143 | + | |
| 144 | +Check your code to ensure that you read the returned `ByteBuffer` correctly. `ByteBuffer` is a very error-prone API, | |
| 145 | +and we've had many reports where the problem turned out to be in user code. | |
| 146 | + | |
| 147 | +See [Blobs.java] in the `driver-examples` module for some examples and explanations. | |
| 148 | + | |
| 149 | +[Blobs.java]: https://github.com/datastax/java-driver/tree/3.0.x/driver-examples/src/main/java/com/datastax/driver/examples/datatypes/Blobs.java | |
| No newline at the end of the file |