├── .gitignore
├── CODE_OF_CONDUCT.md
├── CONTRIBUTING.md
├── LICENSE.md
├── README.md
├── docker-compose.yaml
├── example-3x
├── pom.xml
└── src
│ └── main
│ ├── java
│ └── com
│ │ └── datastax
│ │ └── samples
│ │ ├── ExampleSchema.java
│ │ ├── ExampleUtils.java
│ │ ├── SampleCode3x_CONNECT_AuthenticationAndSsl.java
│ │ ├── SampleCode3x_CONNECT_ClusterShowMetaData.java
│ │ ├── SampleCode3x_CONNECT_CreateKeyspace.java
│ │ ├── SampleCode3x_CONNECT_CreateSchema.java
│ │ ├── SampleCode3x_CONNECT_DropKeyspace.java
│ │ ├── SampleCode3x_CONNECT_DropSchema.java
│ │ ├── SampleCode3x_CONNECT_Metrics.java
│ │ ├── SampleCode3x_CONNECT_Policies.java
│ │ ├── SampleCode3x_CONNECT_ServiceCloudAstra.java
│ │ ├── SampleCode3x_CRUD_00_GettingStarted.java
│ │ ├── SampleCode3x_CRUD_01_Simple.java
│ │ ├── SampleCode3x_CRUD_02_Paging.java
│ │ ├── SampleCode3x_CRUD_03_Batches.java
│ │ ├── SampleCode3x_CRUD_04_ListSetMapAndUdt.java
│ │ ├── SampleCode3x_CRUD_05_Json.java
│ │ ├── SampleCode3x_CRUD_06_Async.java
│ │ ├── SampleCode3x_CRUD_07_ObjectMapping.java
│ │ ├── SampleCode3x_CRUD_08_Counters.java
│ │ ├── SampleCode3x_CRUD_09_LightweightTransactions.java
│ │ ├── SampleCode3x_CRUD_10_BlobAndCodec.java
│ │ ├── codec
│ │ ├── BytesArrayCodec.java
│ │ └── VideoFormatDtoCodec.java
│ │ ├── dto
│ │ ├── FileDto.java
│ │ ├── UserDto.java
│ │ ├── VideoDto.java
│ │ └── VideoFormatDto.java
│ │ └── objectmapping
│ │ ├── Comment.java
│ │ ├── CommentByUser.java
│ │ └── CommentByVideo.java
│ └── resources
│ ├── cassandra_logo.png
│ └── logback.xml
└── example-4x
├── pom.xml
└── src
└── main
├── java
└── com
│ └── datastax
│ └── samples
│ ├── ExampleSchema.java
│ ├── ExampleUtils.java
│ ├── SampleCode4x_CONNECT_ClusterShowMetaData.java
│ ├── SampleCode4x_CONNECT_CreateKeyspace.java
│ ├── SampleCode4x_CONNECT_CreateSchema.java
│ ├── SampleCode4x_CONNECT_DriverConfigLoader.java
│ ├── SampleCode4x_CONNECT_DropKeyspace.java
│ ├── SampleCode4x_CONNECT_DropSchema.java
│ ├── SampleCode4x_CONNECT_ProgrammaticConfiguration.java
│ ├── SampleCode4x_CONNECT_ServiceCloudAstra.java
│ ├── SampleCode4x_CRUD_00_GettingStarted.java
│ ├── SampleCode4x_CRUD_01_Simple.java
│ ├── SampleCode4x_CRUD_02_Paging.java
│ ├── SampleCode4x_CRUD_03_Batches.java
│ ├── SampleCode4x_CRUD_04_ListSetMapAndUdt.java
│ ├── SampleCode4x_CRUD_05_Json.java
│ ├── SampleCode4x_CRUD_06_Async.java
│ ├── SampleCode4x_CRUD_07_ObjectMapping.java
│ ├── SampleCode4x_CRUD_08_Counters.java
│ ├── SampleCode4x_CRUD_09_LightweightTransactions.java
│ ├── SampleCode4x_CRUD_10_BlobAndCodec.java
│ ├── SampleCode4x_CRUD_11_Reactive.java
│ ├── SampleCode4x_Vector.java
│ ├── codec
│ ├── BytesArrayTypeCodec.java
│ ├── JsonJacksonTypeCodec.java
│ └── UdtVideoFormatCodec.java
│ ├── dto
│ ├── FileDto.java
│ ├── UserDto.java
│ ├── VideoDto.java
│ └── VideoFormatDto.java
│ └── objectmapping
│ ├── Comment.java
│ ├── CommentByUser.java
│ ├── CommentByVideo.java
│ ├── CommentDao.java
│ ├── CommentDaoMapper.java
│ └── CommentDaoQueryProvider.java
└── resources
├── cassandra_logo.png
├── custom_application.conf
├── custom_astra.conf
└── logback.xml
/.gitignore:
--------------------------------------------------------------------------------
1 | astra-sdk-java.wiki/
2 | .env
3 | .astrarc
4 | sec
5 |
6 | # eclipse conf file
7 | .settings
8 | .classpath
9 | .project
10 | .cache
11 |
12 | # idea conf files
13 | .idea
14 | *.ipr
15 | *.iws
16 | *.iml
17 |
18 | # building
19 | target
20 | build
21 | tmp
22 | dist
23 |
24 | # misc
25 | .DS_Store
26 |
27 | .factorypath
28 | .sts4-cache
29 | *.log
30 |
31 | release.properties
32 | pom.xml.releaseBackup
--------------------------------------------------------------------------------
/CODE_OF_CONDUCT.md:
--------------------------------------------------------------------------------
1 | # Contributor Covenant Code of Conduct
2 |
3 | ## Our Pledge
4 |
5 | In the interest of fostering an open and welcoming environment, we as
6 | contributors and maintainers pledge to making participation in our project and
7 | our community a harassment-free experience for everyone, regardless of age, body
8 | size, disability, ethnicity, sex characteristics, gender identity and expression,
9 | level of experience, education, socio-economic status, nationality, personal
10 | appearance, race, religion, or sexual identity and orientation.
11 |
12 | ## Our Standards
13 |
14 | Examples of behavior that contributes to creating a positive environment
15 | include:
16 |
17 | * Using welcoming and inclusive language
18 | * Being respectful of differing viewpoints and experiences
19 | * Gracefully accepting constructive criticism
20 | * Focusing on what is best for the community
21 | * Showing empathy towards other community members
22 |
23 | Examples of unacceptable behavior by participants include:
24 |
25 | * The use of sexualized language or imagery and unwelcome sexual attention or
26 | advances
27 | * Trolling, insulting/derogatory comments, and personal or political attacks
28 | * Public or private harassment
29 | * Publishing others' private information, such as a physical or electronic
30 | address, without explicit permission
31 | * Other conduct which could reasonably be considered inappropriate in a
32 | professional setting
33 |
34 | ## Our Responsibilities
35 |
36 | Project maintainers are responsible for clarifying the standards of acceptable
37 | behavior and are expected to take appropriate and fair corrective action in
38 | response to any instances of unacceptable behavior.
39 |
40 | Project maintainers have the right and responsibility to remove, edit, or
41 | reject comments, commits, code, wiki edits, issues, and other contributions
42 | that are not aligned to this Code of Conduct, or to ban temporarily or
43 | permanently any contributor for other behaviors that they deem inappropriate,
44 | threatening, offensive, or harmful.
45 |
46 | ## Scope
47 |
48 | This Code of Conduct applies both within project spaces and in public spaces
49 | when an individual is representing the project or its community. Examples of
50 | representing a project or community include using an official project e-mail
51 | address, posting via an official social media account, or acting as an appointed
52 | representative at an online or offline event. Representation of a project may be
53 | further defined and clarified by project maintainers.
54 |
55 | ## Enforcement
56 |
57 | Instances of abusive, harassing, or otherwise unacceptable behavior may be
58 | reported by contacting the project team at . All
59 | complaints will be reviewed and investigated and will result in a response that
60 | is deemed necessary and appropriate to the circumstances. The project team is
61 | obligated to maintain confidentiality with regard to the reporter of an incident.
62 | Further details of specific enforcement policies may be posted separately.
63 |
64 | Project maintainers who do not follow or enforce the Code of Conduct in good
65 | faith may face temporary or permanent repercussions as determined by other
66 | members of the project's leadership.
67 |
68 | ## Attribution
69 |
70 | This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4,
71 | available at https://www.contributor-covenant.org/version/1/4/code-of-conduct.html
72 |
73 | [homepage]: https://www.contributor-covenant.org
74 |
75 | For answers to common questions about this code of conduct, see
76 | https://www.contributor-covenant.org/faq
77 |
--------------------------------------------------------------------------------
/CONTRIBUTING.md:
--------------------------------------------------------------------------------
1 | # Contributing
2 |
3 | When contributing to this repository, please first discuss the change you wish to make via issue,
4 | email, or any other method with the owners of this repository before making a change.
5 |
6 | Please note we have a [Code of Conduct](CODE_OF_CONDUCT.md), please follow it in all your interactions with the project.
7 |
8 | ## Found an Issue?
9 | If you find a bug in the source code or a mistake in the documentation, you can help us by
10 | [submitting an issue](#submit-issue) to the GitHub Repository. Even better, you can
11 | [submit a Pull Request](#submit-pr) with a fix.
12 |
13 | ## Want a Feature?
14 | You can *request* a new feature by [submitting an issue](#submit-issue) to the GitHub
15 | Repository. If you would like to *implement* a new feature, please submit an issue with
16 | a proposal for your work first, to be sure that we can use it.
17 |
18 | * **Small Features** can be crafted and directly [submitted as a Pull Request](#submit-pr).
19 |
20 | ## Contribution Guidelines
21 |
22 | ### Submitting an Issue
23 | Before you submit an issue, search the archive, maybe your question was already answered.
24 |
25 | If your issue appears to be a bug, and hasn't been reported, open a new issue.
26 | Help us to maximize the effort we can spend fixing issues and adding new
27 | features, by not reporting duplicate issues. Providing the following information will increase the
28 | chances of your issue being dealt with quickly:
29 |
30 | * **Overview of the Issue** - if an error is being thrown a non-minified stack trace helps
31 | * **Motivation for or Use Case** - explain what are you trying to do and why the current behavior is a bug for you
32 | * **Reproduce the Error** - provide a live example or a unambiguous set of steps
33 | * **Suggest a Fix** - if you can't fix the bug yourself, perhaps you can point to what might be
34 | causing the problem (line of code or commit)
35 |
36 | ### Submitting a Pull Request (PR)
37 | Before you submit your Pull Request (PR) consider the following guidelines:
38 |
39 | * Search the repository (https://github.com/bechbd/[repository-name]/pulls) for an open or closed PR that relates to your submission. You don't want to duplicate effort.
40 |
41 | * Create a fork of the repo
42 | * Navigate to the repo you want to fork
43 | * In the top right corner of the page click **Fork**:
44 | 
45 |
46 | * Make your changes in the forked repo
47 | * Commit your changes using a descriptive commit message
48 | * In GitHub, create a pull request: https://help.github.com/en/articles/creating-a-pull-request-from-a-fork
49 | * If we suggest changes then:
50 | * Make the required updates.
51 | * Rebase your fork and force push to your GitHub repository (this will update your Pull Request):
52 |
53 | ```shell
54 | git rebase master -i
55 | git push -f
56 | ```
57 |
58 | That's it! Thank you for your contribution!
--------------------------------------------------------------------------------
/docker-compose.yaml:
--------------------------------------------------------------------------------
1 | version: '2'
2 | services:
3 | cassandra:
4 | image: cassandra:5.0-beta1
5 | ports:
6 | - 9042:9042
7 | ulimits:
8 | memlock: -1
9 |
10 |
11 | # If you want to have cqlsh
12 | # docker exec -it `docker ps | grep assandra:5.0-beta1 | cut -b 1-12` cqlsh
13 |
14 |
15 |
--------------------------------------------------------------------------------
/example-3x/pom.xml:
--------------------------------------------------------------------------------
1 |
2 |
5 | 4.0.0
6 | com.datastax.samples
7 | example-3x
8 | 1.0-SNAPSHOT
9 | jar
10 |
11 |
12 |
13 |
14 | 3.11.5
15 | 1.2.3
16 |
17 |
18 | 1.8
19 | UTF-8
20 |
21 |
22 |
23 |
24 |
25 |
26 |
27 | com.datastax.cassandra
28 | cassandra-driver-core
29 | ${cassandra.driver.oss.version}
30 |
31 |
32 |
33 |
34 | ch.qos.logback
35 | logback-classic
36 | ${logback.version}
37 |
38 |
39 |
40 |
41 | com.datastax.cassandra
42 | cassandra-driver-mapping
43 | ${cassandra.driver.oss.version}
44 |
45 |
46 |
47 |
48 | com.datastax.cassandra
49 | cassandra-driver-extras
50 | ${cassandra.driver.oss.version}
51 |
52 |
53 |
54 |
55 |
56 |
57 |
58 |
59 |
60 | org.apache.maven.plugins
61 | maven-compiler-plugin
62 | 3.8.1
63 |
64 |
65 |
66 |
67 |
68 |
69 | 1.8
70 | 1.8
71 |
72 |
73 |
74 |
75 |
76 |
77 |
78 |
79 |
--------------------------------------------------------------------------------
/example-3x/src/main/java/com/datastax/samples/ExampleSchema.java:
--------------------------------------------------------------------------------
1 | package com.datastax.samples;
2 |
3 | /**
4 | * Externalization of schema constant.
5 | */
6 | public interface ExampleSchema {
7 |
8 | String KEYSPACE_NAME = "killrvideo";
9 | int KEYSPACE_REPLICATION_FACTOR = 1;
10 |
11 | /**
12 | * Will be used for this table:
13 | *
14 | * CREATE TABLE IF NOT EXISTS users (
15 | * email text,
16 | * firstname text,
17 | * lastname text,
18 | * PRIMARY KEY (email)
19 | * );
20 | */
21 | String USER_TABLENAME = "users";
22 | String USER_EMAIL = "email";
23 | String USER_FIRSTNAME = "firstname";
24 | String USER_LASTNAME = "lastname";
25 |
26 | /**
27 | * CREATE TYPE IF NOT EXISTS video_format (
28 | * width int,
29 | * height int
30 | *);
31 | */
32 | String UDT_VIDEO_FORMAT_NAME = "video_format";
33 | String UDT_VIDEO_FORMAT_WIDTH = "width";
34 | String UDT_VIDEO_FORMAT_HEIGHT = "height";
35 |
36 | /**
37 | * CREATE TABLE IF NOT EXISTS videos (
38 | * videoid uuid,
39 | * title text,
40 | * upload timestamp,
41 | * email text,
42 | * url text,
43 | * tags set ,
44 | * frames list,
45 | * formats map >,
46 | * PRIMARY KEY (videoid)
47 | * );
48 | **/
49 | String VIDEO_TABLENAME = "videos";
50 | String VIDEO_VIDEOID = "videoid";
51 | String VIDEO_TITLE = "title";
52 | String VIDEO_UPLOAD = "upload";
53 | String VIDEO_USER_EMAIL = "email";
54 | String VIDEO_FRAMES = "frames";
55 | String VIDEO_URL = "url";
56 | String VIDEO_TAGS = "tags";
57 | String VIDEO_FORMAT = "formats";
58 |
59 | /**
60 | * CREATE TABLE IF NOT EXISTS videos_views (
61 | * videoid uuid,
62 | * views counter,
63 | * PRIMARY KEY (videoid)
64 | * );
65 | */
66 | String VIDEO_VIEWS_TABLENAME = "videos_views";
67 | String VIDEO_VIEWS_VIDEOID = "videoid";
68 | String VIDEO_VIEWS_VIEWS = "views";
69 |
70 | /**
71 | * CREATE TABLE IF NOT EXISTS comments_by_video (
72 | * videoid uuid,
73 | * commentid timeuuid,
74 | * userid uuid,
75 | * comment text,
76 | * PRIMARY KEY (videoid, commentid)
77 | * ) WITH CLUSTERING ORDER BY (commentid DESC);
78 | *
79 | *
80 | * CREATE TABLE IF NOT EXISTS comments_by_user (
81 | * userid uuid,
82 | * commentid timeuuid,
83 | * videoid uuid,
84 | * comment text,
85 | * PRIMARY KEY (userid, commentid)
86 | * ) WITH CLUSTERING ORDER BY (commentid DESC);
87 | */
88 | String COMMENT_BY_VIDEO_TABLENAME = "comments_by_video";
89 | String COMMENT_BY_VIDEO_VIDEOID = "videoid";
90 | String COMMENT_BY_VIDEO_COMMENTID = "commentid";
91 | String COMMENT_BY_VIDEO_USERID = "userid";
92 | String COMMENT_BY_VIDEO_COMMENT = "comment";
93 | String COMMENT_BY_USER_TABLENAME = "comments_by_user";
94 | String COMMENT_BY_USER_VIDEOID = COMMENT_BY_VIDEO_VIDEOID;
95 | String COMMENT_BY_USER_COMMENTID = COMMENT_BY_VIDEO_COMMENTID;
96 | String COMMENT_BY_USER_USERID = COMMENT_BY_VIDEO_USERID;
97 | String COMMENT_BY_USER_COMMENT = COMMENT_BY_VIDEO_COMMENT;
98 |
99 | String FILES_TABLENAME = "files";
100 | String FILES_FILENAME = "filename";
101 | String FILES_EXTENSION = "extension";
102 | String FILES_UPLOAD = "upload";
103 | String FILES_BINARY = "binary";
104 |
105 |
106 | }
107 |
--------------------------------------------------------------------------------
/example-3x/src/main/java/com/datastax/samples/SampleCode3x_CONNECT_AuthenticationAndSsl.java:
--------------------------------------------------------------------------------
1 | package com.datastax.samples;
2 |
3 | import java.io.File;
4 | import java.io.FileInputStream;
5 | import java.io.IOException;
6 | import java.io.InputStream;
7 | import java.security.KeyStore;
8 | import java.security.KeyStoreException;
9 | import java.security.NoSuchAlgorithmException;
10 | import java.security.cert.CertificateException;
11 |
12 | import javax.net.ssl.SSLException;
13 | import javax.net.ssl.TrustManagerFactory;
14 |
15 | import org.slf4j.Logger;
16 | import org.slf4j.LoggerFactory;
17 |
18 | import com.datastax.driver.core.Cluster;
19 | import com.datastax.driver.core.PlainTextAuthProvider;
20 | import com.datastax.driver.core.RemoteEndpointAwareNettySSLOptions;
21 | import com.datastax.driver.core.SSLOptions;
22 |
23 | import io.netty.handler.ssl.SslContext;
24 | import io.netty.handler.ssl.SslContextBuilder;
25 | import io.netty.handler.ssl.SslProvider;
26 |
27 | /**
28 | * Create a keyspace with Simple Strategy and replication factor 1 (for local environment)
29 | *
30 | * Pre-requisites:
31 | * - Cassandra running locally (127.0.0.1, port 9042)
32 | *
33 | * @author DataStax Developer Advocate Team
34 | *
35 | * Need Help ? Join us on community.datastax.com to ask your questions for free.
36 | *
37 | * https://docs.datastax.com/en/developer/java-driver/4.5/manual/core/load_balancing/
38 | */
39 | public class SampleCode3x_CONNECT_AuthenticationAndSsl implements ExampleSchema {
40 |
41 | /** Logger for the class. */
42 | private static Logger LOGGER = LoggerFactory.getLogger(SampleCode3x_CONNECT_AuthenticationAndSsl.class);
43 |
44 | private static final boolean enableSSL = false;
45 |
46 | /**
47 | * StandAlone program relying on main method to easy copy/paste.
48 | */
49 | public static void main(String[] args) {
50 | LOGGER.info("Starting 'AuthenticationAndSsl' sample...");
51 |
52 | // --- Authentication ---
53 |
54 | // Shortcut for PlainTextAuthProvider
55 | try(Cluster cluster = Cluster.builder()
56 | .addContactPoint("127.0.0.1")
57 | .withCredentials("cassandra", "cassandra")
58 | .build()) {
59 | LOGGER.info("Connected to Cluster with Default AuthProvider");
60 | }
61 |
62 | try(Cluster cluster = Cluster.builder()
63 | .addContactPoint("127.0.0.1")
64 | .withAuthProvider(new PlainTextAuthProvider("cassandra", "cassandra"))
65 | .build()) {
66 | LOGGER.info("Connected to Cluster with Explicit AuthProvider");
67 | }
68 |
69 | /*
70 | * --- SSL ---
71 | *
72 | * - client-to-node encryption, where the traffic is encrypted, and the client verifies the
73 | * identity of the Cassandra nodes it connects to
74 | * - optionally, client certificate authentication, where Cassandra nodes also verify the
75 | * identity of the client.
76 | */
77 |
78 | if (enableSSL) {
79 |
80 | try(Cluster cluster = Cluster.builder()
81 | .addContactPoint("127.0.0.1")
82 | .withSSL()
83 | .build()) {
84 | LOGGER.info("Connected to Cluster with Default SSL");
85 | }
86 |
87 | // You can create SSL Options, SSL Context
88 |
89 | // Init a TrustManager from a Keystore
90 | try {
91 | TrustManagerFactory trustManager =
92 | TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
93 |
94 | KeyStore ks = KeyStore.getInstance("JKS");
95 | InputStream trustStore = new FileInputStream("client.truststore");
96 | ks.load(trustStore, "password123".toCharArray());
97 | trustManager.init(ks);
98 |
99 | // Netty SslContext
100 | SslContext sslContextNetty = SslContextBuilder.forClient()
101 | // Pick a SSL Provider
102 | .sslProvider(SslProvider.OPENSSL)
103 | // Client authentication
104 | .keyManager(new File("client.crt"), new File("client.key"))
105 | // And the Trust Manager
106 | .trustManager(trustManager)
107 | .build();
108 |
109 | SSLOptions sslOptionsNetty =
110 | new RemoteEndpointAwareNettySSLOptions(sslContextNetty);
111 |
112 | try(Cluster cluster = Cluster.builder()
113 | .addContactPoint("127.0.0.1")
114 | .withSSL(sslOptionsNetty)
115 | .build()) {
116 | LOGGER.info("Connected to Cluster with explicit SSL");
117 | }
118 |
119 | } catch (NoSuchAlgorithmException e) {
120 | LOGGER.error("Error in SSL", e);
121 | } catch (KeyStoreException e) {
122 | LOGGER.error("Error in SSL", e);
123 | } catch (SSLException e) {
124 | LOGGER.error("Error in SSL", e);
125 | } catch (CertificateException e) {
126 | LOGGER.error("Error in SSL", e);
127 | } catch (IOException e) {
128 | LOGGER.error("Error in SSL", e);
129 | }
130 | }
131 | LOGGER.info("[OK] Success");
132 | System.exit(0);
133 | }
134 |
135 | }
136 |
--------------------------------------------------------------------------------
/example-3x/src/main/java/com/datastax/samples/SampleCode3x_CONNECT_ClusterShowMetaData.java:
--------------------------------------------------------------------------------
1 | package com.datastax.samples;
2 |
3 | import org.slf4j.Logger;
4 | import org.slf4j.LoggerFactory;
5 |
6 | import com.datastax.driver.core.Cluster;
7 | import com.datastax.driver.core.Host;
8 | import com.datastax.driver.core.KeyspaceMetadata;
9 | import com.datastax.driver.core.Metadata;
10 |
11 | /**
12 | * Standalone class to log metadata of a running cluster.
13 | *
14 | *
15 | * Pre-requisites:
16 | * - Cassandra running locally (127.0.0.1, port 9042)
17 | *
18 | * @author DataStax Developer Advocate Team
19 | *
20 | * Need Help ? Join us on community.datastax.com to ask your questions for free.
21 | */
22 | public class SampleCode3x_CONNECT_ClusterShowMetaData implements ExampleSchema {
23 |
24 | /** Logger for the class. */
25 | private static Logger LOGGER = LoggerFactory.getLogger(SampleCode3x_CONNECT_ClusterShowMetaData.class);
26 |
27 | /** StandAlone (vs JUNIT) to help you running. */
28 | public static void main(String[] args) {
29 | LOGGER.info("Starting 'ClusterShowMetaData' sample...");
30 |
31 | /**
32 | * Connecting to the cluster using a single endpoint:
33 | * - Note that we don't provide any keyspace informations
34 | */
35 | try(Cluster cluster = Cluster.builder()
36 | .addContactPoint("127.0.0.1") // Single EndPoint is required, 2 is better
37 | .withPort(9042) // Default port, optional here
38 | .build()) {
39 |
40 | // Enforcing meta datas to be retrieved
41 | cluster.init();
42 | Metadata metadata = cluster.getMetadata();
43 | LOGGER.info("Connected to cluster '{}'", metadata.getClusterName());
44 |
45 | LOGGER.info("Protocol Version: {}",
46 | cluster.getConfiguration()
47 | .getProtocolOptions()
48 | .getProtocolVersion());
49 |
50 | LOGGER.info("Listing available Nodes:");
51 | for (Host host : metadata.getAllHosts()) {
52 | LOGGER.info("+ [{}]: datacenter='{}' and rack='{}'",
53 | host.getListenAddress(),
54 | host.getDatacenter(),
55 | host.getRack());
56 | }
57 |
58 | LOGGER.info("Listing available keyspaces:");
59 | for (KeyspaceMetadata meta : metadata.getKeyspaces()) {
60 | LOGGER.info("+ [{}] \t with replication={}", meta.getName(), meta.getReplication());
61 | }
62 | LOGGER.info("[OK] Success");
63 | }
64 | System.exit(0);
65 | }
66 | }
67 |
--------------------------------------------------------------------------------
/example-3x/src/main/java/com/datastax/samples/SampleCode3x_CONNECT_CreateKeyspace.java:
--------------------------------------------------------------------------------
1 | package com.datastax.samples;
2 |
3 | import org.slf4j.Logger;
4 | import org.slf4j.LoggerFactory;
5 |
6 | /**
7 | * Create a keyspace with Simple Strategy and replication factor 1 (for local environment)
8 | *
9 | * Pre-requisites:
10 | * - Cassandra running locally (127.0.0.1, port 9042)
11 | *
12 | * This code below will execute the following CQL statement:
13 | * --------------------------------------------------------------------
14 | * CREATE KEYSPACE killrvideo
15 | * WITH replication =
16 | * {'class': 'SimpleStrategy',
17 | * 'replication_factor': '1'}
18 | * AND durable_writes = true;
19 | * ---------------------------------------------------------------------
20 | *
21 | * @author DataStax Developer Advocate Team
22 | *
23 | * Need Help ? Join us on community.datastax.com to ask your questions for free.
24 | */
25 | public class SampleCode3x_CONNECT_CreateKeyspace implements ExampleSchema {
26 |
27 | /** Logger for the class. */
28 | private static Logger LOGGER = LoggerFactory.getLogger(SampleCode3x_CONNECT_CreateKeyspace.class);
29 |
30 | /**
31 | * StandAlone program relying on main method to easy copy/paste.
32 | */
33 | public static void main(String[] args) {
34 | LOGGER.info("Starting 'CreateKeyspace' sample...");
35 |
36 | ExampleUtils.createKeyspace();
37 | System.exit(0);
38 | }
39 |
40 | }
41 |
--------------------------------------------------------------------------------
/example-3x/src/main/java/com/datastax/samples/SampleCode3x_CONNECT_CreateSchema.java:
--------------------------------------------------------------------------------
1 | package com.datastax.samples;
2 |
3 | import static com.datastax.samples.ExampleUtils.createTableCommentByUser;
4 | import static com.datastax.samples.ExampleUtils.createTableCommentByVideo;
5 | import static com.datastax.samples.ExampleUtils.createTableUser;
6 | import static com.datastax.samples.ExampleUtils.createTableVideo;
7 | import static com.datastax.samples.ExampleUtils.createTableVideoViews;
8 | import static com.datastax.samples.ExampleUtils.createUdtVideoFormat;
9 | import static com.datastax.samples.ExampleUtils.createKeyspace;
10 | import static com.datastax.samples.ExampleUtils.createTableFiles;
11 |
12 | import org.slf4j.Logger;
13 | import org.slf4j.LoggerFactory;
14 |
15 | import com.datastax.driver.core.Cluster;
16 | import com.datastax.driver.core.Session;
17 |
18 | /**
19 | * Create keyspace killrvideo if needed and all tables, user defined types.
20 | *
21 | * Pre-requisites:
22 | * - Cassandra running locally (127.0.0.1, port 9042)
23 | *
24 | * @author DataStax Developer Advocate Team
25 | *
26 | * Need Help ? Join us on community.datastax.com to ask your questions for free.
27 | */
28 | public class SampleCode3x_CONNECT_CreateSchema implements ExampleSchema {
29 |
30 | /** Logger for the class. */
31 | private static Logger LOGGER = LoggerFactory.getLogger(SampleCode3x_CONNECT_CreateSchema.class);
32 |
33 | /** StandAlone (vs JUNIT) to help you running. */
34 | public static void main(String[] args) {
35 | LOGGER.info("Starting 'CreateSchema' sample...");
36 |
37 | try(Cluster cluster = Cluster.builder()
38 | .addContactPoint("127.0.0.1")
39 | .build()) {
40 |
41 | LOGGER.info("Connected to Cluster");
42 | createKeyspace(cluster);
43 |
44 | try(Session session = cluster.connect(KEYSPACE_NAME)) {
45 | LOGGER.info("[OK] Connected to Keyspace {}", KEYSPACE_NAME);
46 | createUdtVideoFormat(session);
47 | createTableUser(session);
48 | createTableVideo(session);
49 | createTableVideoViews(session);
50 | createTableCommentByVideo(session);
51 | createTableCommentByUser(session);
52 | createTableFiles(session);
53 | }
54 | }
55 | LOGGER.info("[OK] Success");
56 | System.exit(0);
57 | }
58 |
59 | }
60 |
--------------------------------------------------------------------------------
/example-3x/src/main/java/com/datastax/samples/SampleCode3x_CONNECT_DropKeyspace.java:
--------------------------------------------------------------------------------
1 | package com.datastax.samples;
2 |
3 | import org.slf4j.Logger;
4 | import org.slf4j.LoggerFactory;
5 |
6 | import com.datastax.driver.core.Cluster;
7 |
8 | /**
9 | * Sample code to create tables, types and objects in a keyspace.
10 | *
11 | * Pre-requisites:
12 | * - Cassandra running locally (127.0.0.1, port 9042)
13 | * - Keyspace killrvideo created {@link SampleCode3x_CONNECT_CreateKeyspace}
14 | *
15 | * @author DataStax Developer Advocate Team
16 | *
17 | * Need Help ? Join us on community.datastax.com to ask your questions for free.
18 | */
19 | public class SampleCode3x_CONNECT_DropKeyspace implements ExampleSchema {
20 |
21 | /** Logger for the class. */
22 | private static Logger LOGGER = LoggerFactory.getLogger(SampleCode3x_CONNECT_DropKeyspace.class);
23 |
24 | /** StandAlone (vs JUNIT) to help you running. */
25 | public static void main(String[] args) {
26 | LOGGER.info("Starting 'DropKeyspace' sample...");
27 |
28 | try(Cluster cluster = Cluster.builder().addContactPoint("127.0.0.1").build()) {
29 | LOGGER.info("Connected to Cluster");
30 | ExampleUtils.dropKeyspace(cluster);
31 | }
32 | LOGGER.info("[OK] Success");
33 | System.exit(0);
34 | }
35 | }
36 |
--------------------------------------------------------------------------------
/example-3x/src/main/java/com/datastax/samples/SampleCode3x_CONNECT_DropSchema.java:
--------------------------------------------------------------------------------
1 | package com.datastax.samples;
2 |
3 | import static com.datastax.samples.ExampleUtils.dropTableIfExists;
4 | import static com.datastax.samples.ExampleUtils.dropTypeIffExists;
5 |
6 | import org.slf4j.Logger;
7 | import org.slf4j.LoggerFactory;
8 |
9 | import com.datastax.driver.core.Cluster;
10 | import com.datastax.driver.core.Session;
11 |
12 | /**
13 | * Sample code to create tables, types and objects in a keyspace.
14 | *
15 | * Pre-requisites:
16 | * - Cassandra running locally (127.0.0.1, port 9042)
17 | * - Keyspace killrvideo created {@link SampleCode3x_CONNECT_CreateKeyspace}
18 | *
19 | * @author DataStax Developer Advocate Team
20 | *
21 | * Need Help ? Join us on community.datastax.com to ask your questions for free.
22 | */
23 | public class SampleCode3x_CONNECT_DropSchema implements ExampleSchema {
24 |
25 | /** Logger for the class. */
26 | private static Logger LOGGER = LoggerFactory.getLogger(SampleCode3x_CONNECT_DropSchema.class);
27 |
28 | /** StandAlone (vs JUNIT) to help you running. */
29 | public static void main(String[] args) {
30 | LOGGER.info("Starting 'DropSchema' sample...");
31 |
32 | try(Cluster cluster = Cluster.builder().addContactPoint("127.0.0.1").build()) {
33 | LOGGER.info("Connected to Cluster");
34 | try(Session session = cluster.connect(KEYSPACE_NAME)) {
35 | LOGGER.info("[OK] Connected to Keyspace {}", KEYSPACE_NAME);
36 | dropTableIfExists(session, COMMENT_BY_VIDEO_TABLENAME);
37 | dropTableIfExists(session, COMMENT_BY_USER_TABLENAME);
38 | dropTableIfExists(session, VIDEO_VIEWS_TABLENAME);
39 | dropTableIfExists(session, VIDEO_TABLENAME);
40 | dropTableIfExists(session, USER_TABLENAME);
41 | dropTypeIffExists(session, UDT_VIDEO_FORMAT_NAME);
42 | }
43 | }
44 | LOGGER.info("[OK] Success");
45 | System.exit(0);
46 | }
47 |
48 | }
49 |
--------------------------------------------------------------------------------
/example-3x/src/main/java/com/datastax/samples/SampleCode3x_CONNECT_Metrics.java:
--------------------------------------------------------------------------------
1 | package com.datastax.samples;
2 |
3 | import static com.datastax.samples.ExampleUtils.createTableUser;
4 |
5 | import java.io.File;
6 | import java.util.concurrent.TimeUnit;
7 |
8 | import org.slf4j.Logger;
9 | import org.slf4j.LoggerFactory;
10 |
11 | import com.codahale.metrics.CsvReporter;
12 | import com.codahale.metrics.MetricRegistry;
13 | import com.datastax.driver.core.Cluster;
14 | import com.datastax.driver.core.Session;
15 | import static com.datastax.samples.ExampleUtils.createKeyspace;
16 |
17 | /**
18 | * Create keyspace killrvideo if needed and all tables, user defined types.
19 | *
20 | * Pre-requisites:
21 | * - Cassandra running locally (127.0.0.1, port 9042)
22 | *
23 | * @author DataStax Developer Advocate Team
24 | *
25 | * Need Help ? Join us on community.datastax.com to ask your questions for free.
26 | */
27 | public class SampleCode3x_CONNECT_Metrics implements ExampleSchema {
28 |
29 | /** Logger for the class. */
30 | private static Logger LOGGER = LoggerFactory.getLogger(SampleCode3x_CONNECT_Metrics.class);
31 |
32 | /** StandAlone (vs JUNIT) to help you running. */
33 | public static void main(String[] args) throws Exception {
34 | LOGGER.info("Starting 'Metrics' sample...");
35 |
36 | // https://docs.datastax.com/en/developer/java-driver/3.8/manual/metrics/
37 |
38 | createKeyspace();
39 |
40 | // Metrics is enabled by default but you can disable
41 | try(Session session = Cluster.builder().addContactPoint("127.0.0.1")
42 | //.withoutMetrics() // Disable Metrics
43 | //.withoutJMXReporting() // Disable JMX
44 | .build()
45 | .connect(KEYSPACE_NAME)) {
46 | createTableUser(session);
47 | LOGGER.info("Items in tables 'users' : {}" ,
48 | session.execute("select * from users")
49 | .getAvailableWithoutFetching());
50 | }
51 | MetricRegistry myRegistry = new MetricRegistry();
52 |
53 | // Reading metrics values
54 | try(Cluster cluster = Cluster.builder().addContactPoint("127.0.0.1").build()) {
55 | cluster.init();
56 | myRegistry.registerAll(cluster.getMetrics().getRegistry());
57 |
58 | // Exporter as CSV
59 | File csvDestination = File.createTempFile("metrics-", "");
60 | CsvReporter csvReporter = CsvReporter.forRegistry(cluster.getMetrics().getRegistry())
61 | .convertDurationsTo(TimeUnit.MILLISECONDS)
62 | .convertRatesTo(TimeUnit.SECONDS)
63 | .build(csvDestination.getParentFile());
64 | csvReporter.start(1, TimeUnit.SECONDS);
65 |
66 | // Work with Session
67 | try(Session session = cluster.connect(KEYSPACE_NAME)) {
68 | createTableUser(session);
69 | LOGGER.info("Items in tables 'users' : {}" ,
70 | session.execute("select * from users")
71 | .getAvailableWithoutFetching());
72 | }
73 |
74 | // Wait to help generation of all CSV
75 | Thread.sleep(1000);
76 | LOGGER.info("Metrics files have been generated here {}", csvDestination.getParentFile().getAbsolutePath());
77 | }
78 | LOGGER.info("[OK] Success");
79 | System.exit(0);
80 | }
81 |
82 | }
83 |
--------------------------------------------------------------------------------
/example-3x/src/main/java/com/datastax/samples/SampleCode3x_CONNECT_Policies.java:
--------------------------------------------------------------------------------
1 | package com.datastax.samples;
2 |
3 | import java.util.concurrent.TimeUnit;
4 |
5 | import org.slf4j.Logger;
6 | import org.slf4j.LoggerFactory;
7 |
8 | import com.datastax.driver.core.Cluster;
9 | import com.datastax.driver.core.ClusterWidePercentileTracker;
10 | import com.datastax.driver.core.PercentileTracker;
11 | import com.datastax.driver.core.policies.ConstantReconnectionPolicy;
12 | import com.datastax.driver.core.policies.ConstantSpeculativeExecutionPolicy;
13 | import com.datastax.driver.core.policies.DCAwareRoundRobinPolicy;
14 | import com.datastax.driver.core.policies.DefaultRetryPolicy;
15 | import com.datastax.driver.core.policies.ExponentialReconnectionPolicy;
16 | import com.datastax.driver.core.policies.FallthroughRetryPolicy;
17 | import com.datastax.driver.core.policies.LatencyAwarePolicy;
18 | import com.datastax.driver.core.policies.LoadBalancingPolicy;
19 | import com.datastax.driver.core.policies.LoggingRetryPolicy;
20 | import com.datastax.driver.core.policies.PercentileSpeculativeExecutionPolicy;
21 | import com.datastax.driver.core.policies.ReconnectionPolicy;
22 | import com.datastax.driver.core.policies.RetryPolicy;
23 | import com.datastax.driver.core.policies.RoundRobinPolicy;
24 | import com.datastax.driver.core.policies.SpeculativeExecutionPolicy;
25 | import com.datastax.driver.core.policies.TokenAwarePolicy;
26 |
27 | /**
28 | * Create a keyspace with Simple Strategy and replication factor 1 (for local environment)
29 | *
30 | * Pre-requisites:
31 | * - Cassandra running locally (127.0.0.1, port 9042)
32 | *
33 | * @author DataStax Developer Advocate Team
34 | *
35 | * Need Help ? Join us on community.datastax.com to ask your questions for free.
36 | *
37 | * https://docs.datastax.com/en/developer/java-driver/4.5/manual/core/load_balancing/
38 | */
39 | public class SampleCode3x_CONNECT_Policies implements ExampleSchema {
40 |
41 | /** Logger for the class. */
42 | private static Logger LOGGER = LoggerFactory.getLogger(SampleCode3x_CONNECT_Policies.class);
43 |
44 | /**
45 | * StandAlone program relying on main method to easy copy/paste.
46 | */
47 | public static void main(String[] args) {
48 | LOGGER.info("Starting 'Policies' sample...");
49 |
50 | /**
51 | * Load-Balancing Policies
52 | * https://docs.datastax.com/en/developer/java-driver/3.8/manual/load_balancing/
53 | */
54 | // Default
55 | // https://docs.datastax.com/en/developer/java-driver/3.8/manual/load_balancing/#token-aware-policy
56 | LoadBalancingPolicy lbDefault = new TokenAwarePolicy(DCAwareRoundRobinPolicy.builder().build());
57 | LOGGER.info("[LoadBalancing] - {}", lbDefault.toString());
58 | // RoundRobin
59 | // https://docs.datastax.com/en/developer/java-driver/3.8/manual/load_balancing/#round-robin-policy
60 | LoadBalancingPolicy lbRoundRobin = new RoundRobinPolicy();
61 | LOGGER.info("[LoadBalancing] - {}", lbRoundRobin.toString());
62 | // DataCenter aware
63 | // https://docs.datastax.com/en/developer/java-driver/3.8/manual/load_balancing/#dc-aware-round-robin-policy
64 | LoadBalancingPolicy lbLocalDc = DCAwareRoundRobinPolicy.builder().withLocalDc("datacenter1").build();
65 | LOGGER.info("[LoadBalancing] - {}", lbLocalDc.toString());
66 | // Latency aware
67 | // https://docs.datastax.com/en/developer/java-driver/3.8/manual/load_balancing/#latency-aware-policy
68 | LoadBalancingPolicy lbLatency = LatencyAwarePolicy.builder(lbLocalDc)
69 | .withExclusionThreshold(2.0)
70 | .withScale(100, TimeUnit.MILLISECONDS)
71 | .withRetryPeriod(10, TimeUnit.SECONDS)
72 | .withUpdateRate(100, TimeUnit.MILLISECONDS)
73 | .withMininumMeasurements(50)
74 | .build();
75 | LOGGER.info("[LoadBalancing] - {}", lbLatency.toString());
76 |
77 | /**
78 | * Retry Policies
79 | * https://docs.datastax.com/en/developer/java-driver/3.8/manual/retries/#retry-policy
80 | * https://docs.datastax.com/en/drivers/java/3.8/com/datastax/driver/core/policies/RetryPolicy.html
81 | */
82 | RetryPolicy retryDefault = DefaultRetryPolicy.INSTANCE;
83 | LOGGER.info("[Retry] - {}", retryDefault.toString());
84 | // https://docs.datastax.com/en/drivers/java/3.8/com/datastax/driver/core/policies/FallthroughRetryPolicy.html
85 | RetryPolicy retryFall = FallthroughRetryPolicy.INSTANCE;
86 | LOGGER.info("[Retry] - {}", retryFall.toString());
87 | RetryPolicy retryLogged = new LoggingRetryPolicy(retryFall);
88 | LOGGER.info("[Retry] - {}", retryLogged.toString());
89 |
90 | /**
91 | * Reconnection Policies
92 | * https://docs.datastax.com/en/developer/java-driver/3.8/manual/reconnection/
93 | */
94 | ReconnectionPolicy reconnExpo = new ExponentialReconnectionPolicy(1000, 10 * 60 * 1000);
95 | LOGGER.info("[Reconnection] - {}", reconnExpo.toString());
96 | ReconnectionPolicy reconnConst = new ConstantReconnectionPolicy(20);
97 | LOGGER.info("[Reconnection] - {}", reconnConst.toString());
98 |
99 |
100 | /**
101 | * Speculative
102 | * https://docs.datastax.com/en/developer/java-driver/3.8/manual/speculative_execution/
103 | */
104 |
105 | /*
106 | * Constant
107 | * - delay before a new execution is launched
108 | * - maximum number of executions
109 | */
110 | SpeculativeExecutionPolicy seConstantPolicy = new ConstantSpeculativeExecutionPolicy(500, 2);
111 | LOGGER.info("[SpeculativeExecution] - {}", seConstantPolicy.toString());
112 |
113 | /*
114 | * Percentile based
115 | * - percentile
116 | * - maximum number of executions
117 | */
118 | PercentileTracker trackerCluster = ClusterWidePercentileTracker.builder(15000).build();
119 | // PercentileTracker trackerHost = PerHostPercentileTracker.builder(1500).build();
120 | SpeculativeExecutionPolicy sePercentilePolicy = new PercentileSpeculativeExecutionPolicy(trackerCluster, 99.0,2);
121 | LOGGER.info("[SpeculativeExecution] - {}", sePercentilePolicy.toString());
122 |
123 | try(Cluster cluster = Cluster.builder()
124 | .addContactPoint("127.0.0.1")
125 | .withLoadBalancingPolicy(lbDefault)
126 | .withRetryPolicy(retryDefault)
127 | .withReconnectionPolicy(reconnExpo)
128 | .withSpeculativeExecutionPolicy(sePercentilePolicy)
129 | .build()) {
130 | LOGGER.info("Connected to Cluster");
131 | }
132 | LOGGER.info("[OK] Success");
133 | System.exit(0);
134 | }
135 |
136 | }
137 |
--------------------------------------------------------------------------------
/example-3x/src/main/java/com/datastax/samples/SampleCode3x_CONNECT_ServiceCloudAstra.java:
--------------------------------------------------------------------------------
1 | package com.datastax.samples;
2 |
3 | import java.io.File;
4 |
5 | import org.slf4j.Logger;
6 | import org.slf4j.LoggerFactory;
7 |
8 | import com.datastax.driver.core.Cluster;
9 | import com.datastax.driver.core.Session;
10 |
11 | /**
12 | * This class shows how to connect to the DataStax Cloud Cassandra As a Service: ASTRA
13 | *
14 | * Pre-requisites:
15 | * ===================
16 | *
17 | * 1. You need an ASTRA intance : go to astra.datastax.com and create an instance there. There is a free tier
18 | * for you to have a 3-node clusters availables forever. You can find more info on:
19 | *
20 | * 2. You need to provide you ASTRA credentials username, password, keyspace
21 | * but also the secure bundle ZIP. To download it please follow the instruction on :
22 | * https://docs.datastax.com/en/developer/java-driver/3.8/manual/cloud/
23 | *
24 | * 3. You need a java driver version 3.8
25 | *
26 | * @author DataStax Developer Advocate Team
27 | *
28 | * Need Help ? Join us on community.datastax.com to ask your questions for free.
29 | */
30 | public class SampleCode3x_CONNECT_ServiceCloudAstra implements ExampleSchema {
31 |
32 | /** Logger for the class. */
33 | private static Logger LOGGER = LoggerFactory.getLogger(SampleCode3x_CONNECT_ServiceCloudAstra.class);
34 |
35 | /** StandAlone (vs JUNIT) to help you running. */
36 | public static void main(String[] args) {
37 | LOGGER.info("Starting 'ServiceCloudAstra' sample...");
38 |
39 | // Those are mandatory to connect to ASTRA
40 | final String ASTRA_ZIP_FILE = "/Users/cedricklunven/Downloads/secure-connect-killrvideo.zip";
41 | final String ASTRA_USERNAME = "killrvideo";
42 | final String ASTRA_PASSWORD = "killrvideo";
43 | final String ASTRA_KEYSPACE = "killrvideo";
44 |
45 | // Check the cloud zip file
46 | File cloudSecureConnectBundleFile = new File(ASTRA_ZIP_FILE);
47 | if (!cloudSecureConnectBundleFile.exists()) {
48 | throw new IllegalStateException("File '" + ASTRA_ZIP_FILE + "' has not been found\n"
49 | + "To run this sample you need to download the secure bundle file from ASTRA WebPage\n"
50 | + "More info here:");
51 | }
52 |
53 | // Connect
54 | try(Cluster cluster = Cluster.builder()
55 | .withCloudSecureConnectBundle(cloudSecureConnectBundleFile)
56 | .withCredentials(ASTRA_USERNAME, ASTRA_PASSWORD)
57 | .build() ) {
58 | Session session = cluster.connect(ASTRA_KEYSPACE);
59 | LOGGER.info("[OK] Welcome to ASTRA. Connected to Keyspace {}", session.getLoggedKeyspace());
60 | }
61 |
62 | LOGGER.info("[OK] Success");
63 | System.exit(0);
64 | }
65 |
66 | }
67 |
--------------------------------------------------------------------------------
/example-3x/src/main/java/com/datastax/samples/SampleCode3x_CRUD_00_GettingStarted.java:
--------------------------------------------------------------------------------
1 | package com.datastax.samples;
2 |
3 | import static com.datastax.samples.ExampleUtils.closeSessionAndCluster;
4 | import static com.datastax.samples.ExampleUtils.connect;
5 | import static com.datastax.samples.ExampleUtils.createKeyspace;
6 | import static com.datastax.samples.ExampleUtils.createTableUser;
7 | import static com.datastax.samples.ExampleUtils.truncateTable;
8 |
9 | import org.slf4j.Logger;
10 | import org.slf4j.LoggerFactory;
11 |
12 | import com.datastax.driver.core.BoundStatement;
13 | import com.datastax.driver.core.Cluster;
14 | import com.datastax.driver.core.ConsistencyLevel;
15 | import com.datastax.driver.core.PreparedStatement;
16 | import com.datastax.driver.core.Session;
17 | import com.datastax.driver.core.SimpleStatement;
18 | import com.datastax.driver.core.querybuilder.QueryBuilder;
19 | import com.google.common.collect.ImmutableMap;
20 |
21 | /**
22 | * Sample codes using Cassandra OSS Driver 3.x
23 | *
24 | * Disclaimers:
25 | * - Tests for arguments nullity has been removed for code clarity
26 | * - Packaged as a main class for usability
27 | *
28 | * Pre-requisites:
29 | * - Cassandra running locally (127.0.0.1, port 9042)
30 | *
31 | * @author Cedrick LUNVEN (@clunven)
32 | * @author Erick RAMIREZ (@@flightc)
33 | *
34 | * Need Help ? Join us on community.datastax.com to ask your questions for free.
35 | */
36 | public class SampleCode3x_CRUD_00_GettingStarted implements ExampleSchema {
37 |
38 | /** Logger for the class. */
39 | private static Logger LOGGER = LoggerFactory.getLogger(SampleCode3x_CRUD_00_GettingStarted.class);
40 |
41 | /** StandAlone (vs JUNIT) to help you running. */
42 | public static void main(String[] args) {
43 | LOGGER.info("Starting 'GettingStarted' sample...");
44 |
45 | Cluster cluster = null;
46 | Session session = null;
47 | try {
48 |
49 | // === INITIALIZING ===
50 |
51 | // Create killrvideo keyspace (if needed)
52 | createKeyspace();
53 |
54 | // Initialize Cluster and Session Objects (connected to keyspace killrvideo)
55 | session = connect(cluster);
56 |
57 | // Create working table User (if needed)
58 | createTableUser(session);
59 |
60 | // Empty tables for tests
61 | truncateTable(session, USER_TABLENAME);
62 |
63 | /**
64 | * In this class we will focus only on INSERTING records in order
65 | * to detailled all the ways to interact with Cassandra.
66 | **/
67 |
68 | // #1. You can execute CQL queries as a String
69 | session.execute(""
70 | + "INSERT INTO users (email, firstname, lastname) "
71 | + "VALUES ('clun@sample.com', 'Cedrick', 'Lunven')");
72 | LOGGER.info("+ Insert as a String");
73 |
74 | // #2.a You should externalize variables using character '?'
75 | session.execute(""
76 | + "INSERT INTO users (email, firstname, lastname) "
77 | + "VALUES (?,?,?)", "clun2@gmail.com", "Cedrick", "Lunven");
78 | LOGGER.info("+ Insert and externalize var with ?");
79 |
80 | // #2.b You can also externalize variables setting a label like :name
81 | session.execute(""
82 | + "INSERT INTO users (email, firstname, lastname) "
83 | + "VALUES (:e,:f,:l)", ImmutableMap.of(
84 | "e", "clun3@gmail.com",
85 | "f", "Cedrick",
86 | "l", "Lunven"));
87 | LOGGER.info("+ Insert and externalize var with :labels");
88 |
89 | // #3. You query is marshalled as 'Statement'
90 | // You can create it explicitely in order to override some parameters
91 | // doc: https://docs.datastax.com/en/developer/java-driver/3.0/manual/statements/simple/
92 | SimpleStatement statement = new SimpleStatement(""
93 | + "INSERT INTO users (email, firstname, lastname) "
94 | + "VALUES ('clun4@sample.com', 'Cedrick', 'Lunven')");
95 | statement.setConsistencyLevel(ConsistencyLevel.ONE);
96 | session.execute(statement);
97 | LOGGER.info("+ Insert with explicit statements");
98 |
99 | // #4. You can use QueryBuilder to help you building your statements
100 | // doc: https://docs.datastax.com/en/drivers/java/3.8/com/datastax/driver/core/querybuilder/QueryBuilder.html
101 | session.execute(QueryBuilder.insertInto("users")
102 | .value("email", "clun5@gmail.com")
103 | .value("firstname", "Cedrick")
104 | .value("lastname", "Lunven"));
105 | LOGGER.info("+ Insert with QueryBuilder");
106 |
107 | // #5.It is recommended to prepare your statements
108 | // Prepare once, execute multiple times is much faster
109 | // Use session.prepare()
110 | // doc: https://docs.datastax.com/en/developer/java-driver/3.8/manual/statements/built/
111 |
112 | // 5.a Use '?' for parameters
113 | // doc: https://docs.datastax.com/en/developer/java-driver/3.8/manual/statements/prepared/
114 | PreparedStatement ps1 = session.prepare(""
115 | + "INSERT INTO users (email, firstname, lastname) "
116 | + "VALUES (?,?,?)");
117 | BoundStatement bs1 = ps1.bind("clun6@gmail.com", "Cedrick", "Lunven");
118 | session.execute(bs1);
119 | LOGGER.info("+ Insert with preparing the statement");
120 |
121 | // 5.b To prepare statements with QueryBuilder, use 'bindMarker'
122 | PreparedStatement ps2 = session.prepare(QueryBuilder.insertInto("users")
123 | .value("email", QueryBuilder.bindMarker())
124 | .value("firstname", QueryBuilder.bindMarker())
125 | .value("lastname", QueryBuilder.bindMarker()));
126 | session.execute(ps2.bind("clun7@gmail.com", "Cedrick", "Lunven"));
127 | LOGGER.info("+ Insert with PrepareStatements + QueryBuilder");
128 |
129 |
130 | // In next SAMPLES you will find everything with QueryBuidler and PreparedStatement
131 | // Enjoy !!!
132 |
133 | } finally {
134 | closeSessionAndCluster(session, cluster);
135 | }
136 | System.exit(0);
137 | }
138 |
139 |
140 |
141 | }
142 |
--------------------------------------------------------------------------------
/example-3x/src/main/java/com/datastax/samples/SampleCode3x_CRUD_02_Paging.java:
--------------------------------------------------------------------------------
1 | package com.datastax.samples;
2 |
3 | import static com.datastax.samples.ExampleUtils.closeSessionAndCluster;
4 | import static com.datastax.samples.ExampleUtils.connect;
5 | import static com.datastax.samples.ExampleUtils.createKeyspace;
6 | import static com.datastax.samples.ExampleUtils.createTableUser;
7 | import static com.datastax.samples.ExampleUtils.truncateTable;
8 |
9 | import java.util.Iterator;
10 |
11 | import org.slf4j.Logger;
12 | import org.slf4j.LoggerFactory;
13 |
14 | import com.datastax.driver.core.BatchStatement;
15 | import com.datastax.driver.core.Cluster;
16 | import com.datastax.driver.core.ConsistencyLevel;
17 | import com.datastax.driver.core.PagingState;
18 | import com.datastax.driver.core.PreparedStatement;
19 | import com.datastax.driver.core.ResultSet;
20 | import com.datastax.driver.core.Row;
21 | import com.datastax.driver.core.Session;
22 | import com.datastax.driver.core.Statement;
23 | import com.datastax.driver.core.querybuilder.QueryBuilder;
24 |
25 | /**
26 | * Sample codes using Cassandra OSS Driver 3.x
27 | *
28 | * Disclaimers:
29 | * - Tests for arguments nullity has been removed for code clarity
30 | * - Packaged as a main class for usability
31 | *
32 | * Pre-requisites:
33 | * - Cassandra running locally (127.0.0.1, port 9042)
34 | *
35 | * @author Cedrick LUNVEN (@clunven)
36 | * @author Erick RAMIREZ (@@flightc)
37 | *
38 | * Need Help ? Join us on community.datastax.com to ask your questions for free.
39 | */
40 | public class SampleCode3x_CRUD_02_Paging implements ExampleSchema {
41 |
42 | /** Logger for the class. */
43 | private static Logger LOGGER = LoggerFactory.getLogger(SampleCode3x_CRUD_02_Paging.class);
44 |
45 | /** StandAlone (vs JUNIT) to help you running. */
46 | public static void main(String[] args) {
47 |
48 | Cluster cluster = null;
49 | Session session = null;
50 | try {
51 |
52 | // === INITIALIZING ===
53 |
54 | // Create killrvideo keyspace (if needed)
55 | createKeyspace();
56 |
57 | // Initialize Cluster and Session Objects
58 | session = connect(cluster);
59 |
60 | // Create working table User (if needed)
61 | createTableUser(session);
62 |
63 | // Empty tables for tests
64 | truncateTable(session, USER_TABLENAME);
65 |
66 | PreparedStatement stmtCreateUser =
67 | session.prepare(QueryBuilder.insertInto(USER_TABLENAME)
68 | .value(USER_EMAIL, QueryBuilder.bindMarker())
69 | .value(USER_FIRSTNAME, QueryBuilder.bindMarker())
70 | .value(USER_LASTNAME, QueryBuilder.bindMarker()));
71 |
72 | // Adding 50 records in the table
73 | BatchStatement batch = new BatchStatement();
74 | for (int i = 0; i < 50; i++) {
75 | batch.add(stmtCreateUser.bind("user_" + i + "@sample.com", "user_" + i, "lastname"));
76 | }
77 | session.execute(batch);
78 | LOGGER.info("+ {} users have been created", 50);
79 |
80 | // Paged query
81 | Statement statement = QueryBuilder.select()
82 | .from(USER_TABLENAME)
83 | .setFetchSize(10) // 10 per pages
84 | .setReadTimeoutMillis(1000) // 1s timeout
85 | .setConsistencyLevel(ConsistencyLevel.ONE);
86 | ResultSet page1 = session.execute(statement);
87 |
88 | // Checking
89 | LOGGER.info("+ Page 1 has {} items", page1.getAvailableWithoutFetching());
90 | Iterator page1Iter = page1.iterator();
91 | while (0 < page1.getAvailableWithoutFetching()) {
92 | LOGGER.info("Page1: " + page1Iter.next().getString(USER_EMAIL));
93 | }
94 |
95 | // Notice that items are NOT ordered (it uses the hashed token)
96 | // From this point if you invoke .next() driver will look for page2.
97 | // But we can invoke page2 directly: (useful for delay between calls)
98 | String page1PagingState = page1.getExecutionInfo().getPagingState().toString();
99 | statement.setPagingState(PagingState.fromString(page1PagingState));
100 | ResultSet page2 = session.execute(statement);
101 | LOGGER.info("+ Page 2 has {} items", page2.getAvailableWithoutFetching());
102 |
103 | } finally {
104 | closeSessionAndCluster(session, cluster);
105 | }
106 | System.exit(0);
107 | }
108 |
109 | }
110 |
--------------------------------------------------------------------------------
/example-3x/src/main/java/com/datastax/samples/SampleCode3x_CRUD_05_Json.java:
--------------------------------------------------------------------------------
1 | package com.datastax.samples;
2 |
3 | import static com.datastax.samples.ExampleUtils.closeSessionAndCluster;
4 | import static com.datastax.samples.ExampleUtils.createKeyspace;
5 | import static com.datastax.samples.ExampleUtils.createTableVideo;
6 | import static com.datastax.samples.ExampleUtils.createUdtVideoFormat;
7 | import static com.datastax.samples.ExampleUtils.truncateTable;
8 |
9 | import java.util.Arrays;
10 | import java.util.Date;
11 | import java.util.HashSet;
12 | import java.util.UUID;
13 |
14 | import org.slf4j.Logger;
15 | import org.slf4j.LoggerFactory;
16 |
17 | import com.datastax.driver.core.Cluster;
18 | import com.datastax.driver.core.CodecRegistry;
19 | import com.datastax.driver.core.ResultSet;
20 | import com.datastax.driver.core.Row;
21 | import com.datastax.driver.core.Session;
22 | import com.datastax.driver.core.querybuilder.Insert;
23 | import com.datastax.driver.core.querybuilder.QueryBuilder;
24 | import com.datastax.driver.core.utils.UUIDs;
25 | import com.datastax.driver.extras.codecs.json.JacksonJsonCodec;
26 | import com.datastax.samples.dto.VideoDto;
27 |
28 | /**
29 | * Show how to work with JSON Statements for rows and columns.
30 | *
31 | * Pre-requisites:
32 | * - Cassandra running locally (127.0.0.1, port 9042)
33 | *
34 | * @author Cedrick LUNVEN (@clunven)
35 | * @author Erick RAMIREZ (@@flightc)
36 | *
37 | * Need Help ? Join us on community.datastax.com to ask your questions for free.
38 | */
39 | public class SampleCode3x_CRUD_05_Json implements ExampleSchema {
40 |
41 | /** Logger for the class. */
42 | private static Logger LOGGER = LoggerFactory.getLogger(SampleCode3x_CRUD_04_ListSetMapAndUdt.class);
43 |
44 | // This will be used as singletons for the sample
45 | private static Cluster cluster;
46 | private static Session session;
47 |
48 | /** StandAlone (vs JUNIT) to help you running. */
49 | public static void main(String[] args) {
50 | try {
51 |
52 | // Create killrvideo keyspace (if needed)
53 | createKeyspace();
54 |
55 | // Initialize Cluster and Session Objects
56 | session = connect(cluster);
57 |
58 | // Create required tables
59 | createUdtVideoFormat(session);
60 | createTableVideo(session);
61 |
62 | // Empty tables for tests
63 | truncateTable(session, VIDEO_TABLENAME);
64 |
65 | // Insert as a String - with regular Core CQL
66 | UUID videoid1 = UUIDs.random();
67 | session.execute(""
68 | + "INSERT INTO " + VIDEO_TABLENAME + "(videoid, email, title, upload, url, tags, frames, formats) "
69 | + "VALUES("+ videoid1.toString() +", "
70 | + " 'clu@sample.com', 'sample video',"
71 | + " toTimeStamp(now()), 'http://google.fr', "
72 | + " { 'cassandra','accelerate','2020'}, "
73 | + " [ 1, 2, 3, 4], "
74 | + " { 'mp4':{width:1,height:1}, "
75 | + " 'ogg':{width:1,height:1} "
76 | + " });");
77 | LOGGER.info("+ Video 'e7ae5cf3-d358-4d99-b900-85902fda9bb0' has been inserted");
78 |
79 | // Insert as a String - with a Column as JSON
80 | UUID videoid2 = UUIDs.random();
81 | session.execute("INSERT INTO " + VIDEO_TABLENAME + "(videoid, email, title, upload, url, tags, frames, formats) "
82 | + "VALUES(?,?,?,?,?,?,?,fromJson(?))",
83 | videoid2, "clu@sample.com", "sample video", new Date(),
84 | "http://google.fr", new HashSet<>(), Arrays.asList(1,2,3,4),
85 | "{ \"mp4\":{\"width\":1,\"height\":1}, \"ogg\":{\"width\":1,\"height\":1} }");
86 | LOGGER.info("+ Video '{}' has been inserted", videoid2);
87 |
88 | // Insert as a JSON String
89 | UUID videoid3 = UUIDs.random();
90 | session.execute(""
91 | + "INSERT INTO " + VIDEO_TABLENAME + " JSON '{"
92 | + "\"videoid\":\""+videoid3.toString()+"\","
93 | + "\"email\":\"clu@sample.com\","
94 | + "\"title\":\"sample video\","
95 | + "\"upload\":\"2020-02-26 15:09:22 +00:00\","
96 | + "\"url\":\"http://google.fr\","
97 | + "\"frames\": [1,2,3,4],"
98 | + "\"tags\": [\"cassandra\",\"accelerate\", \"2020\"],"
99 | + "\"formats\": {"
100 | + " \"mp4\":{\"width\":1,\"height\":1},"
101 | + " \"ogg\":{\"width\":1,\"height\":1}"
102 | + "}}'");
103 | LOGGER.info("+ Video '{}' has been inserted", videoid3);
104 |
105 | // Insert as a JSON Param
106 | UUID videoid4 = UUIDs.random();
107 | session.execute(""
108 | + "INSERT INTO " + VIDEO_TABLENAME + " JSON ? ", "{"
109 | + "\"videoid\":\""+ videoid4.toString() + "\","
110 | + "\"email\":\"clu@sample.com\","
111 | + "\"title\":\"sample video\","
112 | + "\"upload\":\"2020-02-26 15:09:22 +00:00\","
113 | + "\"url\":\"http://google.fr\","
114 | + "\"frames\": [1,2,3,4],"
115 | + "\"tags\": [\"cassandra\",\"accelerate\", \"2020\"],"
116 | + "\"formats\": {"
117 | + " \"mp4\":{\"width\":1,\"height\":1},"
118 | + " \"ogg\":{\"width\":1,\"height\":1}"
119 | + "}}");
120 | LOGGER.info("+ Video '{}' has been inserted", videoid4);
121 |
122 | // Insert with QueryBuilder - as a JSON String
123 | UUID videoid5 = UUIDs.random();
124 | Insert stmt = QueryBuilder.insertInto(VIDEO_TABLENAME).json("{"
125 | + "\"videoid\":\""+ videoid5.toString() + "\","
126 | + "\"email\":\"clu@sample.com\","
127 | + "\"title\":\"sample video\","
128 | + "\"upload\":\"2020-02-26 15:09:22 +00:00\","
129 | + "\"url\":\"http://google.fr\","
130 | + "\"frames\": [1,2,3,4],"
131 | + "\"tags\": [\"cassandra\",\"accelerate\", \"2020\"],"
132 | + "\"formats\": {"
133 | + " \"mp4\":{\"width\":1,\"height\":1},"
134 | + " \"ogg\":{\"width\":1,\"height\":1}"
135 | + "}}");
136 | session.execute(stmt);
137 | LOGGER.info("+ Video '{}' has been inserted", videoid5);
138 | LOGGER.info("[OK] - All video Inserted");
139 |
140 | // Insert with QueryBuilder - As an object + Jackson Codec
141 | UUID videoid6 = UUIDs.random();
142 | VideoDto dto = new VideoDto(videoid6, "sample video", "clu@sample.com", "http://google.fr");
143 | session.execute(QueryBuilder.insertInto(VIDEO_TABLENAME).json(dto));
144 | LOGGER.info("+ Video '{}' has been inserted", videoid5);
145 |
146 | // Read with QueryBuilder - As an object + Jackson Codec
147 | ResultSet rows = session.execute(QueryBuilder.select().json().from(VIDEO_TABLENAME));
148 | for (Row row : rows) {
149 | VideoDto myVideo = row.get(0, VideoDto.class);
150 | LOGGER.info("+ Video '{}' has been read ", myVideo.getVideoid());
151 | }
152 | LOGGER.info("[OK] - All video read");
153 |
154 | } finally {
155 | closeSessionAndCluster(session, cluster);
156 | }
157 | System.exit(0);
158 |
159 | }
160 |
161 | public static Session connect(Cluster cluster) {
162 | cluster = Cluster.builder()
163 | .addContactPoint("127.0.0.1")
164 | .withCodecRegistry(
165 | new CodecRegistry().register(new JacksonJsonCodec(VideoDto.class)))
166 | .build();
167 | LOGGER.info("Connected to Cluster, Looking for keyspace '{}'...", KEYSPACE_NAME);
168 | session = cluster.connect(KEYSPACE_NAME);
169 | LOGGER.info("[OK] Connected to Keyspace");
170 | return session;
171 | }
172 | }
173 |
--------------------------------------------------------------------------------
/example-3x/src/main/java/com/datastax/samples/SampleCode3x_CRUD_07_ObjectMapping.java:
--------------------------------------------------------------------------------
1 | package com.datastax.samples;
2 |
3 | import static com.datastax.samples.ExampleUtils.closeSessionAndCluster;
4 | import static com.datastax.samples.ExampleUtils.connect;
5 | import static com.datastax.samples.ExampleUtils.createKeyspace;
6 | import static com.datastax.samples.ExampleUtils.createTableCommentByUser;
7 | import static com.datastax.samples.ExampleUtils.createTableCommentByVideo;
8 | import static com.datastax.samples.ExampleUtils.truncateTable;
9 |
10 | import java.util.UUID;
11 |
12 | import org.slf4j.Logger;
13 | import org.slf4j.LoggerFactory;
14 |
15 | import com.datastax.driver.core.BatchStatement;
16 | import com.datastax.driver.core.Cluster;
17 | import com.datastax.driver.core.PreparedStatement;
18 | import com.datastax.driver.core.Session;
19 | import com.datastax.driver.core.querybuilder.QueryBuilder;
20 | import com.datastax.driver.core.utils.UUIDs;
21 | import com.datastax.driver.mapping.Mapper;
22 | import com.datastax.driver.mapping.MappingManager;
23 | import com.datastax.driver.mapping.Result;
24 | import com.datastax.samples.objectmapping.Comment;
25 | import com.datastax.samples.objectmapping.CommentByUser;
26 | import com.datastax.samples.objectmapping.CommentByVideo;
27 |
28 | /**
29 | * Show how to map Objects to Cassandra tables relying on Annotations.
30 | *
31 | * Pre-requisites:
32 | * - Cassandra running locally (127.0.0.1, port 9042)
33 | *
34 | * @author Cedrick LUNVEN (@clunven)
35 | * @author Erick RAMIREZ (@@flightc)
36 | *
37 | * Need Help ? Join us on community.datastax.com to ask your questions for free.
38 | */
39 | public class SampleCode3x_CRUD_07_ObjectMapping implements ExampleSchema {
40 |
41 | /** Logger for the class. */
42 | private static Logger LOGGER = LoggerFactory.getLogger(SampleCode3x_CRUD_07_ObjectMapping.class);
43 |
44 | // This will be used as singletons for the sample
45 | private static Cluster cluster;
46 | private static Session session;
47 |
48 | // Prepare your statements once and execute multiple times
49 | private static PreparedStatement selectCommentByVideo;
50 | private static PreparedStatement selectCommentByUser;
51 |
52 | // Using Object Mapping.
53 | private static Mapper < CommentByUser > mapperCommentByUser;
54 | private static Mapper < CommentByVideo > mapperCommentByVideo;
55 |
56 | /** StandAlone (vs JUNIT) to help you running. */
57 | public static void main(String[] args) {
58 |
59 | try {
60 |
61 | // Create killrvideo keyspace (if needed)
62 | createKeyspace();
63 |
64 | // Initialize Cluster and Session Objects
65 | session = connect(cluster);
66 |
67 | // Create working table User (if needed)
68 | createTableCommentByUser(session);
69 | createTableCommentByVideo(session);
70 |
71 | // Comments are used in 2 queries, we need 2 tables to store it
72 | truncateTable(session, COMMENT_BY_USER_TABLENAME);
73 | truncateTable(session, COMMENT_BY_VIDEO_TABLENAME);
74 |
75 | // Mapping Management Object <-> TABLE
76 | MappingManager mm = new MappingManager(session);
77 | mapperCommentByUser = mm.mapper(CommentByUser.class);
78 | mapperCommentByVideo = mm.mapper(CommentByVideo.class);
79 |
80 | // Prepare your statements once and execute multiple times
81 | prepareStatements();
82 |
83 | // DataSet
84 | UUID user_1 = UUIDs.random();UUID user_2 = UUIDs.random();
85 | UUID videoid_1 = UUIDs.random();UUID videoid_2 = UUIDs.random();
86 | Comment c1 = new Comment(user_1, videoid_1, "I am user1 and video1 is good");
87 | Comment c2 = new Comment(user_2, videoid_1, "I am user2 and video1 is bad");
88 | Comment c3 = new Comment(user_1, videoid_2, "Video2 is cool");
89 | Comment c4 = new Comment(user_2, videoid_2, "Video2");
90 |
91 | /* ==================== CREATE =====================
92 | * Create comment (in 2 tables with BATCH)
93 | * ================================================= */
94 | createComment(c1);createComment(c2);
95 | createComment(c3);createComment(c4);
96 |
97 | retrieveCommentsVideo(videoid_2).all()
98 | .stream().map(CommentByVideo::getComment)
99 | .forEach(LOGGER::info);
100 |
101 | /* =============== UPDATE ==========================
102 | * == Update one comment (in 2 tables with BATCH) ==
103 | * ================================================= */
104 | c1.setComment("This is my new comment");
105 | updateComment(c1);
106 | retrieveCommentsVideo(videoid_1).all()
107 | .stream().map(CommentByVideo::getComment)
108 | .forEach(LOGGER::info);
109 |
110 | /* =============== DELETE ===========================
111 | * Delete one comment (in 2 tables with BATCH) ==
112 | * Note that commentId is NOT ENOUGH as userid and ==
113 | * videoid are part of the the primary keys. ==
114 | * ==================================================*/
115 | deleteComment(c1);
116 | retrieveCommentsVideo(videoid_1).all()
117 | .stream().map(CommentByVideo::getComment)
118 | .forEach(LOGGER::info);
119 |
120 | /*
121 | * ============================ READ ================================
122 | * == Query1: List comments for user_1 with table comment_by_user =
123 | * == Query2: List comments for video_2 with table comment_by_video =
124 | * ==================================================================
125 | */
126 |
127 | retrieveCommentsUser(user_1).all()
128 | .stream().map(CommentByUser::getComment)
129 | .forEach(LOGGER::info);
130 |
131 | retrieveCommentsVideo(videoid_2).all()
132 | .stream().map(CommentByVideo::getComment)
133 | .forEach(LOGGER::info);
134 |
135 | } finally {
136 | // Close Cluster and Session
137 | closeSessionAndCluster(session, cluster);
138 | }
139 | System.exit(0);
140 | }
141 |
142 | private static void prepareStatements() {
143 | selectCommentByVideo = session.prepare(
144 | QueryBuilder.select().from(COMMENT_BY_VIDEO_TABLENAME)
145 | .where(QueryBuilder.eq(COMMENT_BY_USER_VIDEOID, QueryBuilder.bindMarker())));
146 | selectCommentByUser = session.prepare(
147 | QueryBuilder.select().from(COMMENT_BY_USER_TABLENAME)
148 | .where(QueryBuilder.eq(COMMENT_BY_USER_USERID, QueryBuilder.bindMarker())));
149 | }
150 |
151 |
152 | private static void createComment(Comment comment) {
153 | updateComment(comment);
154 | }
155 |
156 | private static void updateComment(Comment comment) {
157 | final BatchStatement batch = new BatchStatement(BatchStatement.Type.UNLOGGED);
158 | batch.add(mapperCommentByVideo.saveQuery(new CommentByVideo(comment)));
159 | batch.add(mapperCommentByUser.saveQuery(new CommentByUser(comment)));
160 | session.execute(batch);
161 | }
162 |
163 | private static void deleteComment(Comment comment) {
164 | session.execute(new BatchStatement()
165 | .add(mapperCommentByVideo.deleteQuery(new CommentByVideo(comment)))
166 | .add(mapperCommentByVideo.deleteQuery(new CommentByVideo(comment))));
167 | }
168 |
169 | private static Result retrieveCommentsVideo(UUID videoid) {
170 | return mapperCommentByVideo.map(
171 | session.execute(selectCommentByVideo.bind(videoid)));
172 | }
173 |
174 | private static Result retrieveCommentsUser(UUID userId) {
175 | return mapperCommentByUser.map(
176 | session.execute(selectCommentByUser.bind(userId)));
177 | }
178 | }
179 |
--------------------------------------------------------------------------------
/example-3x/src/main/java/com/datastax/samples/SampleCode3x_CRUD_08_Counters.java:
--------------------------------------------------------------------------------
1 | package com.datastax.samples;
2 |
3 | import static com.datastax.samples.ExampleUtils.closeSessionAndCluster;
4 | import static com.datastax.samples.ExampleUtils.connect;
5 | import static com.datastax.samples.ExampleUtils.createKeyspace;
6 | import static com.datastax.samples.ExampleUtils.createTableVideoViews;
7 | import static com.datastax.samples.ExampleUtils.truncateTable;
8 |
9 | import java.util.Optional;
10 | import java.util.UUID;
11 |
12 | import org.slf4j.Logger;
13 | import org.slf4j.LoggerFactory;
14 |
15 | import com.datastax.driver.core.Cluster;
16 | import com.datastax.driver.core.PreparedStatement;
17 | import com.datastax.driver.core.Row;
18 | import com.datastax.driver.core.Session;
19 | import com.datastax.driver.core.querybuilder.QueryBuilder;
20 | import com.datastax.driver.core.utils.UUIDs;
21 |
22 | /**
23 | * Working with Counters :
24 | *
25 | * CREATE TABLE IF NOT EXISTS videos_views (
26 | * videoid uuid,
27 | * views counter,
28 | * PRIMARY KEY (videoid)
29 | * );
30 | *
31 | * Definition:
32 | * - 64-bit signed integer
33 | * -First op assumes the value is zero
34 | *
35 | * Use-case:
36 | * - Imprecise values such as likes, views, etc.
37 | *
38 | * Two operations:
39 | * - Increment
40 | * - Decrement
41 | *
42 | * Limitations:
43 | * - Cannot be part of primary key
44 | * - Counters not mixed with other types in table
45 | * - Value cannot be set
46 | * - Rows with counters cannot be inserted
47 | * - Updates are not idempotent
48 | * - Counters should not be used for precise values
49 | *
50 | * Need Help ? Join us on community.datastax.com to ask your questions for free.
51 | */
52 | public class SampleCode3x_CRUD_08_Counters implements ExampleSchema {
53 |
54 | /** Logger for the class. */
55 | private static Logger LOGGER = LoggerFactory.getLogger(SampleCode3x_CRUD_08_Counters.class);
56 |
57 | // This will be used as singletons for the sample
58 | private static Cluster cluster;
59 | private static Session session;
60 |
61 | // Prepare your statements once and execute multiple times
62 | private static PreparedStatement stmtIncrement;
63 | private static PreparedStatement stmtDecrement;
64 | private static PreparedStatement stmtFindById;
65 | private static PreparedStatement stmtDelete;
66 |
67 | /** StandAlone (vs JUNIT) to help you running. */
68 | public static void main(String[] args) {
69 | try {
70 |
71 | // Create killrvideo keyspace (if needed)
72 | createKeyspace();
73 |
74 | // Initialize Cluster and Session Objects
75 | session = connect(cluster);
76 |
77 | // Create tables for tests
78 | createTableVideoViews(session);
79 |
80 | // Empty tables for tests
81 | truncateTable(session, VIDEO_VIEWS_TABLENAME);
82 |
83 | // Prepare your statements once and execute multiple times
84 | prepareStatements();
85 |
86 | // ========= CREATE ============
87 |
88 | // We cannot insert in a table with a counter
89 | UUID videoId = UUIDs.random();
90 | LOGGER.info("+ Video views {}", findById(videoId));
91 |
92 | // ========= UPDATE ============
93 |
94 | incrementBy(videoId, 10);
95 | LOGGER.info("+ Video views : {}", findById(videoId).get());
96 |
97 | decrementBy(videoId, 8);
98 | LOGGER.info("+ Video views : {}", findById(videoId).get());
99 |
100 | // ========= DELETE ============
101 |
102 | delete(videoId);
103 | LOGGER.info("+ Video views {}", findById(videoId));
104 |
105 |
106 | } finally {
107 | // Close Cluster and Session
108 | closeSessionAndCluster(session, cluster);
109 | }
110 | System.exit(0);
111 | }
112 |
113 | private static Optional findById(UUID videoid) {
114 | Row record = session.execute(stmtFindById.bind(videoid)).one();
115 | if (null != record) {
116 | return Optional.of(record.getLong(VIDEO_VIEWS_VIEWS));
117 | }
118 | return Optional.empty();
119 | }
120 |
121 | private static void incrementBy(UUID videoid, long val) {
122 | session.execute(stmtIncrement.bind(val, videoid));
123 | }
124 |
125 | private static void decrementBy(UUID videoid, long val) {
126 | session.execute(stmtDecrement.bind(val, videoid));
127 | }
128 |
129 | private static void delete(UUID videoid) {
130 | session.execute(stmtDelete.bind(videoid));
131 | }
132 |
133 | private static void prepareStatements() {
134 |
135 | // update videos_views SET views = views + X WHERE videoid=...
136 | stmtIncrement = session.prepare(QueryBuilder
137 | .update(VIDEO_VIEWS_TABLENAME)
138 | .with(QueryBuilder.incr(VIDEO_VIEWS_VIEWS, QueryBuilder.bindMarker()))
139 | .where(QueryBuilder.eq(VIDEO_VIEWS_VIDEOID, QueryBuilder.bindMarker())));
140 |
141 | // update videos_views SET views = views + X WHERE videoid=..
142 | stmtDecrement = session.prepare(QueryBuilder
143 | .update(VIDEO_VIEWS_TABLENAME)
144 | .with(QueryBuilder.decr(VIDEO_VIEWS_VIEWS, QueryBuilder.bindMarker()))
145 | .where(QueryBuilder.eq(VIDEO_VIEWS_VIDEOID, QueryBuilder.bindMarker())));
146 |
147 | // SELECT views FROM videos_views WHERE videoid=...
148 | stmtFindById = session.prepare(QueryBuilder
149 | .select().column(VIDEO_VIEWS_VIEWS)
150 | .from(VIDEO_VIEWS_TABLENAME)
151 | .where(QueryBuilder.eq(VIDEO_VIEWS_VIDEOID, QueryBuilder.bindMarker())));
152 |
153 | // DELETE FROM videos_views WHERE videoid=...
154 | stmtDelete = session.prepare(QueryBuilder
155 | .delete().from(VIDEO_VIEWS_TABLENAME)
156 | .where(QueryBuilder.eq(VIDEO_VIEWS_VIDEOID, QueryBuilder.bindMarker())));
157 | }
158 |
159 | }
160 |
--------------------------------------------------------------------------------
/example-3x/src/main/java/com/datastax/samples/SampleCode3x_CRUD_09_LightweightTransactions.java:
--------------------------------------------------------------------------------
1 | package com.datastax.samples;
2 |
3 | import static com.datastax.samples.ExampleUtils.closeSessionAndCluster;
4 | import static com.datastax.samples.ExampleUtils.connect;
5 | import static com.datastax.samples.ExampleUtils.createTableUser;
6 | import static com.datastax.samples.ExampleUtils.truncateTable;
7 |
8 | import org.slf4j.Logger;
9 | import org.slf4j.LoggerFactory;
10 |
11 | import com.datastax.driver.core.Cluster;
12 | import com.datastax.driver.core.PreparedStatement;
13 | import com.datastax.driver.core.Session;
14 | import com.datastax.driver.core.querybuilder.QueryBuilder;
15 |
16 | /**
17 | * Show how to execute LWT (IF NOT EXISTS, nother IF) and parse wasApplied.
18 | *
19 | * Pre-requisites:
20 | * - Cassandra running locally (127.0.0.1, port 9042)
21 | *
22 | * @author Cedrick LUNVEN (@clunven)
23 | * @author Erick RAMIREZ (@@flightc)
24 | *
25 | * Need Help ? Join us on community.datastax.com to ask your questions for free.
26 | */
27 | public class SampleCode3x_CRUD_09_LightweightTransactions implements ExampleSchema {
28 |
29 | /** Logger for the class. */
30 | private static Logger LOGGER = LoggerFactory.getLogger(SampleCode3x_CRUD_09_LightweightTransactions.class);
31 |
32 | // This will be used as singletons for the sample
33 | private static Cluster cluster;
34 | private static Session session;
35 |
36 | // Prepare your statements once and execute multiple times
37 | private static PreparedStatement stmtCreateUser;
38 | private static PreparedStatement stmtUpdateUserLwt;
39 |
40 | /** StandAlone (vs JUNIT) to help you running. */
41 | public static void main(String[] args) {
42 | try {
43 |
44 | // Initialize Cluster and Session Objects
45 | session = connect(cluster);
46 |
47 | // Use PreparedStatement for queries that are executed multiple times in your application
48 | prepareStatements();
49 |
50 | // Create working table User (if needed)
51 | createTableUser(session);
52 |
53 | // Empty tables for tests
54 | truncateTable(session, USER_TABLENAME);
55 |
56 | // Insert if not exist
57 | boolean first = createUserIfNotExist("clun@sample.com", "Cedric", "Lunven");
58 | boolean second = createUserIfNotExist("clun@sample.com", "Cedric", "Lunven");
59 | LOGGER.info("+ Created first time ? {} and second time {}", first, second);
60 |
61 | // Update if condition
62 | boolean applied1 = updateIf("clun@sample.com", "Cedric", "BEST");
63 | boolean applied2 = updateIf("clun@sample.com", "Cedrick", "Lunven");
64 | LOGGER.info("+ Applied when correct value ? {} and invalid value {}", applied1, applied2);
65 |
66 |
67 | } finally {
68 | closeSessionAndCluster(session, cluster);
69 | }
70 | System.exit(0);
71 | }
72 |
73 | /**
74 | * The resultset is applied only if the record is created. If not the resultSet is populated
75 | * with existing data in DB (read)
76 | */
77 | private static boolean createUserIfNotExist(String email, String firstname, String lastname) {
78 | return session.execute(stmtCreateUser.bind(email, firstname, lastname)).wasApplied();
79 | }
80 |
81 | /**
82 | * Note: we named the parameters as they are not in the same order in the query.
83 | */
84 | private static boolean updateIf(String email, String expectedFirstName, String newLastName) {
85 | return session.execute(stmtUpdateUserLwt.bind()
86 | .setString(USER_EMAIL, email)
87 | .setString(USER_FIRSTNAME, expectedFirstName)
88 | .setString(USER_LASTNAME, newLastName)).wasApplied();
89 | }
90 |
91 | /**
92 | * Documentation
93 | * https://docs.datastax.com/en/developer/java-driver/3.8/manual/statements/prepared/#prepared-statements
94 | */
95 | private static void prepareStatements() {
96 |
97 | /*
98 | * INSERT INTO users (email, firstname, lastname)
99 | * VALUES(?,?,?)
100 | * IF NOT EXISTS
101 | */
102 | stmtCreateUser = session.prepare(QueryBuilder.insertInto(USER_TABLENAME)
103 | .value(USER_EMAIL, QueryBuilder.bindMarker())
104 | .value(USER_FIRSTNAME, QueryBuilder.bindMarker())
105 | .value(USER_LASTNAME, QueryBuilder.bindMarker())
106 | .ifNotExists());
107 |
108 | /*
109 | * UPDATE users SET lastname=:lastname
110 | * WHERE email=:email
111 | * IF firstname=:firstname
112 | *
113 | * Operators available for LWT Condition:
114 | * =, <, <=, >, >=, != and IN
115 | */
116 | stmtUpdateUserLwt = session.prepare(QueryBuilder.update(USER_TABLENAME)
117 | .with(QueryBuilder.set(USER_LASTNAME, QueryBuilder.bindMarker(USER_LASTNAME)))
118 | .where(QueryBuilder.eq(USER_EMAIL, QueryBuilder.bindMarker(USER_EMAIL)))
119 | .onlyIf(QueryBuilder.eq(USER_FIRSTNAME, QueryBuilder.bindMarker(USER_FIRSTNAME))));
120 | }
121 |
122 | }
123 |
--------------------------------------------------------------------------------
/example-3x/src/main/java/com/datastax/samples/codec/BytesArrayCodec.java:
--------------------------------------------------------------------------------
1 | package com.datastax.samples.codec;
2 |
3 | import java.nio.ByteBuffer;
4 | import java.nio.charset.Charset;
5 | import java.nio.charset.StandardCharsets;
6 |
7 | import com.datastax.driver.core.DataType;
8 | import com.datastax.driver.core.ProtocolVersion;
9 | import com.datastax.driver.core.TypeCodec;
10 | import com.datastax.driver.core.exceptions.InvalidTypeException;
11 | import com.datastax.samples.ExampleSchema;
12 |
13 | /**
14 | * Convert from BLOB <-> byte[]
15 | */
16 | public class BytesArrayCodec extends TypeCodec implements ExampleSchema {
17 |
18 | private Charset charSet = StandardCharsets.UTF_8;
19 |
20 | public BytesArrayCodec(Charset charSet) {
21 | super(DataType.blob(), byte[].class);
22 | this.charSet = charSet;
23 | }
24 |
25 | /** Default constructor. */
26 | public BytesArrayCodec() {
27 | this(StandardCharsets.UTF_8);
28 | }
29 |
30 | /** {@inheritDoc} */
31 | @Override
32 | public byte[] parse(String value) throws InvalidTypeException {
33 | return (value == null || value.isEmpty() || value.equalsIgnoreCase("NULL"))
34 | ? null
35 | : value.getBytes(charSet);
36 | }
37 |
38 | /** {@inheritDoc} */
39 | @Override
40 | public String format(byte[] value) throws InvalidTypeException {
41 | if (value == null) return "NULL";
42 | return new String(value, charSet);
43 | }
44 |
45 | /** {@inheritDoc} */
46 | @Override
47 | public ByteBuffer serialize(byte[] value, ProtocolVersion protocolVersion) throws InvalidTypeException {
48 | if (value == null) return null;
49 | ByteBuffer byteBuffer = ByteBuffer.allocate(value.length);
50 | byteBuffer.put(value);
51 | return byteBuffer;
52 | }
53 |
54 | /** {@inheritDoc} */
55 | @Override
56 | public byte[] deserialize(ByteBuffer byteBuffer, ProtocolVersion protocolVersion) throws InvalidTypeException {
57 | if (byteBuffer == null) return null;
58 | byte[] bytesArray = new byte[byteBuffer.remaining()];
59 | byteBuffer.get(bytesArray, 0, bytesArray.length);
60 | return bytesArray;
61 | }
62 |
63 | }
64 |
--------------------------------------------------------------------------------
/example-3x/src/main/java/com/datastax/samples/codec/VideoFormatDtoCodec.java:
--------------------------------------------------------------------------------
1 | package com.datastax.samples.codec;
2 |
3 | import java.nio.ByteBuffer;
4 |
5 | import com.datastax.driver.core.ProtocolVersion;
6 | import com.datastax.driver.core.TypeCodec;
7 | import com.datastax.driver.core.UDTValue;
8 | import com.datastax.driver.core.UserType;
9 | import com.datastax.driver.core.exceptions.InvalidTypeException;
10 | import com.datastax.samples.ExampleSchema;
11 | import com.datastax.samples.dto.VideoFormatDto;
12 |
13 | /**
14 | * Codec to help with UDT and do not use only UDTValue.
15 | */
16 | public class VideoFormatDtoCodec extends TypeCodec implements ExampleSchema {
17 |
18 | private final TypeCodec innerCodec;
19 |
20 | private final UserType videoFormatUdt;
21 |
22 | public VideoFormatDtoCodec(TypeCodec innerCodec, Class javaType) {
23 | super(innerCodec.getCqlType(), javaType);
24 | this.innerCodec = innerCodec;
25 | this.videoFormatUdt = (UserType) innerCodec.getCqlType();
26 | }
27 |
28 | /** {@inheritDoc} */
29 | @Override
30 | public ByteBuffer serialize(VideoFormatDto value, ProtocolVersion protocolVersion) throws InvalidTypeException {
31 | return innerCodec.serialize(toUDTValue(value), protocolVersion);
32 | }
33 |
34 | @Override
35 | public VideoFormatDto deserialize(ByteBuffer bytes, ProtocolVersion protocolVersion) throws InvalidTypeException {
36 | return toVideoFormatDto(innerCodec.deserialize(bytes, protocolVersion));
37 | }
38 |
39 | protected VideoFormatDto toVideoFormatDto(UDTValue value) {
40 | return value == null ? null : new VideoFormatDto(
41 | value.getInt(UDT_VIDEO_FORMAT_WIDTH),
42 | value.getInt(UDT_VIDEO_FORMAT_HEIGHT)
43 | );
44 | }
45 |
46 | /** {@inheritDoc} */
47 | @Override
48 | public VideoFormatDto parse(String value) throws InvalidTypeException {
49 | return value == null || value.isEmpty() || value.equalsIgnoreCase("NULL") ?
50 | null : toVideoFormatDto(innerCodec.parse(value));
51 | }
52 |
53 | /** {@inheritDoc} */
54 | @Override
55 | public String format(VideoFormatDto value) throws InvalidTypeException {
56 | return value == null ? "NULL" : innerCodec.format(toUDTValue(value));
57 | }
58 |
59 | protected UDTValue toUDTValue(VideoFormatDto value) {
60 | return value == null ? null : videoFormatUdt.newValue()
61 | .setInt(UDT_VIDEO_FORMAT_WIDTH, value.getWidth())
62 | .setInt(UDT_VIDEO_FORMAT_HEIGHT, value.getHeight());
63 | }
64 |
65 |
66 | }
67 |
--------------------------------------------------------------------------------
/example-3x/src/main/java/com/datastax/samples/dto/FileDto.java:
--------------------------------------------------------------------------------
1 | package com.datastax.samples.dto;
2 |
3 | import java.io.Serializable;
4 | import java.nio.ByteBuffer;
5 | import java.util.Date;
6 |
7 | /**
8 | * Sample POJO.
9 | */
10 | public class FileDto implements Serializable {
11 |
12 | /** Serial. */
13 | private static final long serialVersionUID = 7325306650146053028L;
14 |
15 | private String filename;
16 |
17 | private String extension;
18 |
19 | private Date updload;
20 |
21 | private ByteBuffer content;
22 |
23 | public FileDto() {
24 | }
25 |
26 | /**
27 | * Getter accessor for attribute 'filename'.
28 | *
29 | * @return
30 | * current value of 'filename'
31 | */
32 | public String getFilename() {
33 | return filename;
34 | }
35 |
36 | /**
37 | * Setter accessor for attribute 'filename'.
38 | * @param filename
39 | * new value for 'filename '
40 | */
41 | public void setFilename(String filename) {
42 | this.filename = filename;
43 | }
44 |
45 | /**
46 | * Getter accessor for attribute 'extension'.
47 | *
48 | * @return
49 | * current value of 'extension'
50 | */
51 | public String getExtension() {
52 | return extension;
53 | }
54 |
55 | /**
56 | * Setter accessor for attribute 'extension'.
57 | * @param extension
58 | * new value for 'extension '
59 | */
60 | public void setExtension(String extension) {
61 | this.extension = extension;
62 | }
63 |
64 | /**
65 | * Getter accessor for attribute 'updload'.
66 | *
67 | * @return
68 | * current value of 'updload'
69 | */
70 | public Date getUpload() {
71 | return updload;
72 | }
73 |
74 | /**
75 | * Setter accessor for attribute 'updload'.
76 | * @param updload
77 | * new value for 'updload '
78 | */
79 | public void setUpload(Date updload) {
80 | this.updload = updload;
81 | }
82 |
83 | /**
84 | * Getter accessor for attribute 'content'.
85 | *
86 | * @return
87 | * current value of 'content'
88 | */
89 | public ByteBuffer getContent() {
90 | return content;
91 | }
92 |
93 | /**
94 | * Setter accessor for attribute 'content'.
95 | * @param content
96 | * new value for 'content '
97 | */
98 | public void setContent(ByteBuffer content) {
99 | this.content = content;
100 | }
101 |
102 |
103 |
104 | }
105 |
--------------------------------------------------------------------------------
/example-3x/src/main/java/com/datastax/samples/dto/UserDto.java:
--------------------------------------------------------------------------------
1 | package com.datastax.samples.dto;
2 |
3 | import java.io.Serializable;
4 |
5 | import com.datastax.driver.core.Row;
6 | import com.datastax.samples.ExampleSchema;
7 |
8 | /**
9 | * Sample bean for row.
10 | *
11 | * @author Cedrick LUNVEN (@clunven)
12 | */
13 | public class UserDto implements Serializable, ExampleSchema {
14 |
15 | /** Serial. */
16 | private static final long serialVersionUID = -6767335554891314036L;
17 |
18 | private String email;
19 |
20 | private String firstName;
21 |
22 | private String lastName;
23 |
24 | public UserDto() {
25 | }
26 |
27 | public UserDto(Row tableUsersRow) {
28 | super();
29 | this.email = tableUsersRow.getString(USER_EMAIL);
30 | this.firstName = tableUsersRow.getString(USER_FIRSTNAME);
31 | this.lastName = tableUsersRow.getString(USER_LASTNAME);
32 | }
33 |
34 | public UserDto(String email, String firstName, String lastName) {
35 | super();
36 | this.email = email;
37 | this.firstName = firstName;
38 | this.lastName = lastName;
39 | }
40 |
41 | /**
42 | * Getter accessor for attribute 'email'.
43 | *
44 | * @return
45 | * current value of 'email'
46 | */
47 | public String getEmail() {
48 | return email;
49 | }
50 |
51 | /**
52 | * Setter accessor for attribute 'email'.
53 | * @param email
54 | * new value for 'email '
55 | */
56 | public void setEmail(String email) {
57 | this.email = email;
58 | }
59 |
60 | /**
61 | * Getter accessor for attribute 'firstName'.
62 | *
63 | * @return
64 | * current value of 'firstName'
65 | */
66 | public String getFirstName() {
67 | return firstName;
68 | }
69 |
70 | /**
71 | * Setter accessor for attribute 'firstName'.
72 | * @param firstName
73 | * new value for 'firstName '
74 | */
75 | public void setFirstName(String firstName) {
76 | this.firstName = firstName;
77 | }
78 |
79 | /**
80 | * Getter accessor for attribute 'lastName'.
81 | *
82 | * @return
83 | * current value of 'lastName'
84 | */
85 | public String getLastName() {
86 | return lastName;
87 | }
88 |
89 | /**
90 | * Setter accessor for attribute 'lastName'.
91 | * @param lastName
92 | * new value for 'lastName '
93 | */
94 | public void setLastName(String lastName) {
95 | this.lastName = lastName;
96 | }
97 |
98 | }
99 |
--------------------------------------------------------------------------------
/example-3x/src/main/java/com/datastax/samples/dto/VideoDto.java:
--------------------------------------------------------------------------------
1 | package com.datastax.samples.dto;
2 |
3 | import java.io.Serializable;
4 | import java.time.Instant;
5 | import java.util.ArrayList;
6 | import java.util.HashMap;
7 | import java.util.HashSet;
8 | import java.util.List;
9 | import java.util.Map;
10 | import java.util.Set;
11 | import java.util.UUID;
12 |
13 | import com.fasterxml.jackson.annotation.JsonIgnore;
14 |
15 | /**
16 | * CREATE TABLE IF NOT EXISTS videos ( videoid uuid, title text, upload timestamp, email text, url text, tags set , formats
17 | * map >, PRIMARY KEY (videoid) );
18 | */
19 | public class VideoDto implements Serializable {
20 |
21 | /** Serial. */
22 | private static final long serialVersionUID = -5086632646056781255L;
23 |
24 | private UUID videoid;
25 |
26 | private String title;
27 |
28 | private String email;
29 |
30 | private String url;
31 |
32 | @JsonIgnore
33 | private long upload = Instant.now().toEpochMilli();
34 |
35 | private Set tags = new HashSet<>();
36 |
37 | private List frames = new ArrayList<>();
38 |
39 | private Map formats = new HashMap<>();
40 |
41 | public VideoDto() {}
42 |
43 | public VideoDto(UUID videoId, String title, String email, String url) {
44 | super();
45 | this.videoid = videoId;
46 | this.title = title;
47 | this.email = email;
48 | }
49 |
50 | /**
51 | * Getter accessor for attribute 'videoId'.
52 | *
53 | * @return current value of 'videoId'
54 | */
55 | public UUID getVideoid() {
56 | return videoid;
57 | }
58 |
59 | /**
60 | * Setter accessor for attribute 'videoId'.
61 | *
62 | * @param videoId
63 | * new value for 'videoId '
64 | */
65 | public void setVideoid(UUID videoId) {
66 | this.videoid = videoId;
67 | }
68 |
69 | /**
70 | * Getter accessor for attribute 'title'.
71 | *
72 | * @return current value of 'title'
73 | */
74 | public String getTitle() {
75 | return title;
76 | }
77 |
78 | /**
79 | * Setter accessor for attribute 'title'.
80 | *
81 | * @param title
82 | * new value for 'title '
83 | */
84 | public void setTitle(String title) {
85 | this.title = title;
86 | }
87 |
88 | /**
89 | * Getter accessor for attribute 'upload'.
90 | *
91 | * @return current value of 'upload'
92 | */
93 | public Long getUpload() {
94 | return upload;
95 | }
96 |
97 | /**
98 | * Setter accessor for attribute 'upload'.
99 | *
100 | * @param upload
101 | * new value for 'upload '
102 | */
103 | public void setUpload(Long upload) {
104 | this.upload = upload;
105 | }
106 |
107 | /**
108 | * Getter accessor for attribute 'email'.
109 | *
110 | * @return current value of 'email'
111 | */
112 | public String getEmail() {
113 | return email;
114 | }
115 |
116 | /**
117 | * Setter accessor for attribute 'email'.
118 | *
119 | * @param email
120 | * new value for 'email '
121 | */
122 | public void setEmail(String email) {
123 | this.email = email;
124 | }
125 |
126 | /**
127 | * Getter accessor for attribute 'tags'.
128 | *
129 | * @return current value of 'tags'
130 | */
131 | public Set getTags() {
132 | return tags;
133 | }
134 |
135 | /**
136 | * Setter accessor for attribute 'tags'.
137 | *
138 | * @param tags
139 | * new value for 'tags '
140 | */
141 | public void setTags(Set tags) {
142 | this.tags = tags;
143 | }
144 |
145 | /**
146 | * Getter accessor for attribute 'formatsd'.
147 | *
148 | * @return current value of 'formatsd'
149 | */
150 | public Map getFormats() {
151 | return formats;
152 | }
153 |
154 | /**
155 | * Setter accessor for attribute 'formatsd'.
156 | *
157 | * @param formatsd
158 | * new value for 'formatsd '
159 | */
160 | public void setFormats(Map formatsd) {
161 | this.formats = formatsd;
162 | }
163 |
164 | public String getUrl() {
165 | return url;
166 | }
167 |
168 | public void setUrl(String url) {
169 | this.url = url;
170 | }
171 |
172 | /**
173 | * Getter accessor for attribute 'frames'.
174 | *
175 | * @return current value of 'frames'
176 | */
177 | public List getFrames() {
178 | return frames;
179 | }
180 |
181 | /**
182 | * Setter accessor for attribute 'frames'.
183 | *
184 | * @param frames
185 | * new value for 'frames '
186 | */
187 | public void setFrames(List frames) {
188 | this.frames = frames;
189 | }
190 |
191 | }
192 |
--------------------------------------------------------------------------------
/example-3x/src/main/java/com/datastax/samples/dto/VideoFormatDto.java:
--------------------------------------------------------------------------------
1 | package com.datastax.samples.dto;
2 |
3 | /**
4 | * CREATE TYPE IF NOT EXISTS video_format (
5 | * width int,
6 | * height int,
7 | * frames list
8 | * );
9 | */
10 | public class VideoFormatDto {
11 |
12 | private int width = 0;
13 |
14 | private int height = 0;
15 |
16 | public VideoFormatDto() {}
17 |
18 | public VideoFormatDto(int w, int h) {
19 | this.width = w;
20 | this.height = h;
21 | }
22 |
23 | public int getWidth() {
24 | return width;
25 | }
26 |
27 | public void setWidth(int width) {
28 | this.width = width;
29 | }
30 |
31 | public int getHeight() {
32 | return height;
33 | }
34 |
35 | public void setHeight(int height) {
36 | this.height = height;
37 | }
38 |
39 | @Override
40 | public String toString() {
41 | return "VideoFormatDto [width=" + width + ", height=" + height;
42 | }
43 | }
44 |
--------------------------------------------------------------------------------
/example-3x/src/main/java/com/datastax/samples/objectmapping/Comment.java:
--------------------------------------------------------------------------------
1 | package com.datastax.samples.objectmapping;
2 |
3 | import java.util.Date;
4 | import java.util.UUID;
5 |
6 | import com.datastax.driver.core.utils.UUIDs;
7 | import com.datastax.driver.mapping.annotations.ClusteringColumn;
8 | import com.datastax.driver.mapping.annotations.Column;
9 | import com.datastax.driver.mapping.annotations.Computed;
10 | import com.datastax.samples.ExampleSchema;
11 |
12 | /**
13 | * Bean standing for comment on video.
14 | *
15 | * @author DataStax Developer Advocates team.
16 | */
17 | public class Comment implements ExampleSchema {
18 |
19 | @Column(name = COMMENT_BY_USER_USERID)
20 | protected UUID userid;
21 |
22 | @Column(name = COMMENT_BY_USER_VIDEOID)
23 | protected UUID videoid;
24 |
25 | @Column(name = COMMENT_BY_USER_COMMENTID)
26 | @ClusteringColumn
27 | protected UUID commentid;
28 |
29 | @Column(name = COMMENT_BY_USER_COMMENT)
30 | protected String comment;
31 |
32 | @Computed("toTimestamp(commentid)")
33 | private Date dateOfComment;
34 |
35 | /**
36 | * Default constructor.
37 | */
38 | public Comment() {
39 | }
40 |
41 | public Comment(UUID userid, UUID videoId, String comment) {
42 | this.userid = userid;
43 | this.videoid = videoId;
44 | this.comment = comment;
45 | this.commentid = UUIDs.timeBased();
46 | }
47 |
48 | /**
49 | * Default constructor.
50 | */
51 | public Comment(String comment) {
52 | this.comment = comment;
53 | }
54 |
55 | /**
56 | * Setter for attribute 'userid'.
57 | * @param userid
58 | * new value for 'userid '
59 | */
60 | public void setUserid(UUID userid) {
61 | this.userid = userid;
62 | }
63 |
64 | /**
65 | * Setter for attribute 'videoid'.
66 | * @param videoid
67 | * new value for 'videoid '
68 | */
69 | public void setVideoid(UUID videoid) {
70 | this.videoid = videoid;
71 | }
72 |
73 | /**
74 | * Getter for attribute 'commentid'.
75 | *
76 | * @return
77 | * current value of 'commentid'
78 | */
79 | public UUID getCommentid() {
80 | return commentid;
81 | }
82 |
83 | /**
84 | * Setter for attribute 'commentid'.
85 | * @param commentid
86 | * new value for 'commentid '
87 | */
88 | public void setCommentid(UUID commentid) {
89 | this.commentid = commentid;
90 | }
91 |
92 | /**
93 | * Getter for attribute 'comment'.
94 | *
95 | * @return
96 | * current value of 'comment'
97 | */
98 | public String getComment() {
99 | return comment;
100 | }
101 |
102 | /**
103 | * Setter for attribute 'comment'.
104 | * @param comment
105 | * new value for 'comment '
106 | */
107 | public void setComment(String comment) {
108 | this.comment = comment;
109 | }
110 |
111 | /**
112 | * Getter for attribute 'dateOfComment'.
113 | *
114 | * @return
115 | * current value of 'dateOfComment'
116 | */
117 | public Date getDateOfComment() {
118 | return dateOfComment;
119 | }
120 |
121 | /**
122 | * Setter for attribute 'dateOfComment'.
123 | * @param dateOfComment
124 | * new value for 'dateOfComment '
125 | */
126 | public void setDateOfComment(Date dateOfComment) {
127 | this.dateOfComment = dateOfComment;
128 | }
129 |
130 | /**
131 | * Getter for attribute 'userid'.
132 | *
133 | * @return
134 | * current value of 'userid'
135 | */
136 | public UUID getUserid() {
137 | return userid;
138 | }
139 |
140 | /**
141 | * Getter for attribute 'videoid'.
142 | *
143 | * @return
144 | * current value of 'videoid'
145 | */
146 | public UUID getVideoid() {
147 | return videoid;
148 | }
149 | }
150 |
--------------------------------------------------------------------------------
/example-3x/src/main/java/com/datastax/samples/objectmapping/CommentByUser.java:
--------------------------------------------------------------------------------
1 | package com.datastax.samples.objectmapping;
2 |
3 | import java.util.UUID;
4 |
5 | import com.datastax.driver.mapping.annotations.PartitionKey;
6 | import com.datastax.driver.mapping.annotations.Table;
7 | import com.datastax.samples.ExampleSchema;
8 |
9 | /**
10 | * Specialization for USER.
11 | */
12 | @Table(
13 | keyspace = ExampleSchema.KEYSPACE_NAME,
14 | name = ExampleSchema.COMMENT_BY_USER_TABLENAME)
15 | public class CommentByUser extends Comment {
16 |
17 | /** Default constructor. */
18 | public CommentByUser() {}
19 |
20 | /**
21 | * Copy constructor.
22 | *
23 | * @param c
24 | */
25 | public CommentByUser(Comment c) {
26 | this.commentid = c.getCommentid();
27 | this.userid = c.getUserid();
28 | this.videoid = c.getVideoid();
29 | this.comment = c.getComment();
30 | }
31 |
32 | /**
33 | * Getter for attribute 'userid'.
34 | *
35 | * @return
36 | * current value of 'userid'
37 | */
38 | @PartitionKey
39 | public UUID getUserid() {
40 | return userid;
41 | }
42 |
43 | }
44 |
--------------------------------------------------------------------------------
/example-3x/src/main/java/com/datastax/samples/objectmapping/CommentByVideo.java:
--------------------------------------------------------------------------------
1 | package com.datastax.samples.objectmapping;
2 |
3 | import java.util.UUID;
4 |
5 | import com.datastax.driver.mapping.annotations.PartitionKey;
6 | import com.datastax.driver.mapping.annotations.Table;
7 | import com.datastax.samples.ExampleSchema;
8 |
9 | /**
10 | * Specialization for USER.
11 | */
12 | @Table(
13 | keyspace = ExampleSchema.KEYSPACE_NAME,
14 | name = ExampleSchema.COMMENT_BY_VIDEO_TABLENAME)
15 | public class CommentByVideo extends Comment {
16 |
17 | /** Default constructor. */
18 | public CommentByVideo() {}
19 |
20 | /**
21 | * Copy constructor.
22 | *
23 | * @param c
24 | */
25 | public CommentByVideo(Comment c) {
26 | this.commentid = c.getCommentid();
27 | this.userid = c.getUserid();
28 | this.videoid = c.getVideoid();
29 | this.comment = c.getComment();
30 | }
31 |
32 | /**
33 | * Getter for attribute 'videoid'.
34 | *
35 | * @return
36 | * current value of 'videoid'
37 | */
38 | @PartitionKey
39 | public UUID getVideoid() {
40 | return videoid;
41 | }
42 |
43 | }
44 |
--------------------------------------------------------------------------------
/example-3x/src/main/resources/cassandra_logo.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/DataStax-Examples/java-cassandra-driver-from3x-to4x/d613cfcf69d8d24fd51cfb034c99fdc9315defd3/example-3x/src/main/resources/cassandra_logo.png
--------------------------------------------------------------------------------
/example-3x/src/main/resources/logback.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | %d{HH:mm:ss.SSS} %magenta(%-5level) %cyan(%-45logger) : %msg%n
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
--------------------------------------------------------------------------------
/example-4x/pom.xml:
--------------------------------------------------------------------------------
1 |
2 |
5 | 4.0.0
6 | com.datastax.samples
7 | example-4x
8 | 1.0-SNAPSHOT
9 | jar
10 |
11 |
12 | 17
13 | UTF-8
14 |
15 |
16 | org.apache.cassandra
17 | 4.18.0
18 |
19 |
20 | 1.5.0
21 | 2.0.12
22 | 3.3.3.RELEASE
23 |
24 |
25 |
26 |
27 |
28 |
29 | ${cassandra.driver.groupId}
30 | java-driver-core
31 | ${cassandra.driver.oss.version}
32 |
33 |
34 |
35 |
36 | ${cassandra.driver.groupId}
37 | java-driver-query-builder
38 | ${cassandra.driver.oss.version}
39 |
40 |
41 | ${cassandra.driver.groupId}
42 | java-driver-mapper-runtime
43 | ${cassandra.driver.oss.version}
44 |
45 |
46 |
47 |
48 | org.slf4j
49 | slf4j-api
50 | ${slf4j.version}
51 |
52 |
53 | ch.qos.logback
54 | logback-classic
55 | ${logback.version}
56 |
57 |
58 |
59 |
60 | io.projectreactor
61 | reactor-core
62 | ${reactor-core.version}
63 |
64 |
65 |
66 |
67 |
68 |
69 |
70 |
71 | org.apache.maven.plugins
72 | maven-compiler-plugin
73 | 3.8.1
74 |
75 | ${java.version}
76 | ${java.version}
77 | ${java.version}
78 |
79 |
80 | ${cassandra.driver.groupId}
81 | java-driver-mapper-processor
82 | ${cassandra.driver.oss.version}
83 |
84 |
85 |
86 |
87 |
88 |
89 |
90 |
91 |
92 |
--------------------------------------------------------------------------------
/example-4x/src/main/java/com/datastax/samples/ExampleSchema.java:
--------------------------------------------------------------------------------
1 | package com.datastax.samples;
2 |
3 | /**
4 | * Externalization of schema constant.
5 | */
6 | public interface ExampleSchema {
7 |
8 | String KEYSPACE_NAME = "killrvideo";
9 | int KEYSPACE_REPLICATION_FACTOR = 1;
10 |
11 | /**
12 | * Will be used for this table:
13 | *
14 | * CREATE TABLE IF NOT EXISTS users (
15 | * email text,
16 | * firstname text,
17 | * lastname text,
18 | * PRIMARY KEY (email)
19 | * );
20 | */
21 | String USER_TABLENAME = "users";
22 | String USER_EMAIL = "email";
23 | String USER_FIRSTNAME = "firstname";
24 | String USER_LASTNAME = "lastname";
25 |
26 | /**
27 | * CREATE TYPE IF NOT EXISTS video_format (
28 | * width int,
29 | * height int
30 | *);
31 | */
32 | String UDT_VIDEO_FORMAT_NAME = "video_format";
33 | String UDT_VIDEO_FORMAT_WIDTH = "width";
34 | String UDT_VIDEO_FORMAT_HEIGHT = "height";
35 |
36 | /**
37 | * CREATE TABLE IF NOT EXISTS videos (
38 | * videoid uuid,
39 | * title text,
40 | * upload timestamp,
41 | * email text,
42 | * url text,
43 | * tags set ,
44 | * frames list,
45 | * formats map >,
46 | * PRIMARY KEY (videoid)
47 | * );
48 | **/
49 | String VIDEO_TABLENAME = "videos";
50 | String VIDEO_VIDEOID = "videoid";
51 | String VIDEO_TITLE = "title";
52 | String VIDEO_UPLOAD = "upload";
53 | String VIDEO_USER_EMAIL = "email";
54 | String VIDEO_FRAMES = "frames";
55 | String VIDEO_URL = "url";
56 | String VIDEO_TAGS = "tags";
57 | String VIDEO_FORMAT = "formats";
58 |
59 | /**
60 | * CREATE TABLE IF NOT EXISTS videos_views (
61 | * videoid uuid,
62 | * views counter,
63 | * PRIMARY KEY (videoid)
64 | * );
65 | */
66 | String VIDEO_VIEWS_TABLENAME = "videos_views";
67 | String VIDEO_VIEWS_VIDEOID = "videoid";
68 | String VIDEO_VIEWS_VIEWS = "views";
69 |
70 | /**
71 | * CREATE TABLE IF NOT EXISTS comments_by_video (
72 | * videoid uuid,
73 | * commentid timeuuid,
74 | * userid uuid,
75 | * comment text,
76 | * PRIMARY KEY (videoid, commentid)
77 | * ) WITH CLUSTERING ORDER BY (commentid DESC);
78 | *
79 | *
80 | * CREATE TABLE IF NOT EXISTS comments_by_user (
81 | * userid uuid,
82 | * commentid timeuuid,
83 | * videoid uuid,
84 | * comment text,
85 | * PRIMARY KEY (userid, commentid)
86 | * ) WITH CLUSTERING ORDER BY (commentid DESC);
87 | */
88 | String COMMENT_BY_VIDEO_TABLENAME = "comments_by_video";
89 | String COMMENT_BY_VIDEO_VIDEOID = "videoid";
90 | String COMMENT_BY_VIDEO_COMMENTID = "commentid";
91 | String COMMENT_BY_VIDEO_USERID = "userid";
92 | String COMMENT_BY_VIDEO_COMMENT = "comment";
93 | String COMMENT_BY_USER_TABLENAME = "comments_by_user";
94 | String COMMENT_BY_USER_VIDEOID = COMMENT_BY_VIDEO_VIDEOID;
95 | String COMMENT_BY_USER_COMMENTID = COMMENT_BY_VIDEO_COMMENTID;
96 | String COMMENT_BY_USER_USERID = COMMENT_BY_VIDEO_USERID;
97 | String COMMENT_BY_USER_COMMENT = COMMENT_BY_VIDEO_COMMENT;
98 |
99 | String FILES_TABLENAME = "files";
100 | String FILES_FILENAME = "filename";
101 | String FILES_EXTENSION = "extension";
102 | String FILES_UPLOAD = "upload";
103 | String FILES_BINARY = "binary";
104 |
105 | }
106 |
--------------------------------------------------------------------------------
/example-4x/src/main/java/com/datastax/samples/SampleCode4x_CONNECT_ClusterShowMetaData.java:
--------------------------------------------------------------------------------
1 | package com.datastax.samples;
2 |
3 | import java.net.InetSocketAddress;
4 |
5 | import org.slf4j.Logger;
6 | import org.slf4j.LoggerFactory;
7 |
8 | import com.datastax.oss.driver.api.core.CqlSession;
9 | import com.datastax.oss.driver.api.core.metadata.Metadata;
10 | import com.datastax.oss.driver.api.core.metadata.Node;
11 | import com.datastax.oss.driver.api.core.metadata.schema.KeyspaceMetadata;
12 |
13 | /**
14 | * Standalone class to log metadata of a running cluster.
15 | *
16 | * We expect you to have a running Cassandra on 127.0.0.1 with default port 9042
17 | */
18 | public class SampleCode4x_CONNECT_ClusterShowMetaData {
19 |
20 | /** Logger for the class. */
21 | private static Logger LOGGER = LoggerFactory.getLogger(SampleCode4x_CONNECT_ClusterShowMetaData.class);
22 |
23 | /** StandAlone (vs JUNIT) to help you running. */
24 | public static void main(String[] args) {
25 | LOGGER.info("Starting 'ClusterShowMetaData' sample...");
26 |
27 | try (CqlSession cqlSession = CqlSession.builder()
28 | .addContactPoint(new InetSocketAddress("127.0.0.1", 9042))
29 | .withLocalDatacenter("datacenter1")
30 | .build()) {
31 |
32 | LOGGER.info("Connected to cluster with Session '{}'",
33 | cqlSession.getName());
34 |
35 | LOGGER.info("Protocol Version: {}",
36 | cqlSession.getContext().getProtocolVersion());
37 |
38 | Metadata metaData = cqlSession.getMetadata();
39 |
40 | LOGGER.info("Listing available Nodes:");
41 | for (Node host : metaData.getNodes().values()) {
42 | LOGGER.info("+ [{}]: datacenter='{}' and rack='{}'",
43 | host.getListenAddress().orElse(null),
44 | host.getDatacenter(),
45 | host.getRack());
46 | }
47 |
48 | LOGGER.info("Listing available keyspaces:");
49 | for (KeyspaceMetadata meta : metaData.getKeyspaces().values()) {
50 | LOGGER.info("+ [{}] \t with replication={}", meta.getName(), meta.getReplication());
51 | }
52 |
53 | LOGGER.info("[OK] Success");
54 | }
55 | System.exit(0);
56 | }
57 | }
58 |
--------------------------------------------------------------------------------
/example-4x/src/main/java/com/datastax/samples/SampleCode4x_CONNECT_CreateKeyspace.java:
--------------------------------------------------------------------------------
1 | package com.datastax.samples;
2 |
3 | import org.slf4j.Logger;
4 | import org.slf4j.LoggerFactory;
5 |
6 | /**
7 | * Create a keyspace with Simple Strategy and replication factor 1 (for local environment)
8 | *
9 | * Pre-requisites:
10 | * - Cassandra running at (ip=127.0.0.1, port=9042, datacenter=datacenter1)
11 | *
12 | * This code below will execute the following CQL statement:
13 | * --------------------------------------------------------------------
14 | * CREATE KEYSPACE killrvideo
15 | * WITH replication =
16 | * {'class': 'SimpleStrategy',
17 | * 'replication_factor': '1'}
18 | * AND durable_writes = true;
19 | * ---------------------------------------------------------------------
20 | *
21 | * @author DataStax Developer Advocate Team
22 | *
23 | * Need Help ? Join us on community.datastax.com to ask your questions for free.
24 | */
25 | public class SampleCode4x_CONNECT_CreateKeyspace implements ExampleSchema {
26 |
27 | /** Logger for the class. */
28 | private static Logger LOGGER = LoggerFactory.getLogger(SampleCode4x_CONNECT_CreateKeyspace.class);
29 |
30 | /**
31 | * StandAlone program relying on main method to easy copy/paste.
32 | */
33 | public static void main(String[] args) {
34 | LOGGER.info("Starting 'CreateKeyspace' sample...");
35 | ExampleUtils.createKeyspace();
36 | System.exit(0);
37 | }
38 |
39 | }
40 |
--------------------------------------------------------------------------------
/example-4x/src/main/java/com/datastax/samples/SampleCode4x_CONNECT_CreateSchema.java:
--------------------------------------------------------------------------------
1 | package com.datastax.samples;
2 |
3 | import static com.datastax.samples.ExampleUtils.createTableCommentByUser;
4 | import static com.datastax.samples.ExampleUtils.createTableCommentByVideo;
5 | import static com.datastax.samples.ExampleUtils.createTableUser;
6 | import static com.datastax.samples.ExampleUtils.createTableVideo;
7 | import static com.datastax.samples.ExampleUtils.createTableVideoViews;
8 | import static com.datastax.samples.ExampleUtils.createUdtVideoFormat;
9 |
10 | import java.net.InetSocketAddress;
11 |
12 | import org.slf4j.Logger;
13 | import org.slf4j.LoggerFactory;
14 |
15 | /**
16 | * Sample code to create tables, types and objects in a keyspace.
17 | *
18 | * Pre-requisites:
19 | * - Cassandra running locally (127.0.0.1, port 9042)
20 | * - Keyspace killrvideo created {@link SampleCode4x_CONNECT_CreateKeyspace}
21 | */
22 | import com.datastax.oss.driver.api.core.CqlSession;
23 |
24 |
25 | /**
26 | * Sample code to create tables, types and objects in a keyspace.
27 | *
28 | * Pre-requisites:
29 | * - Cassandra running locally (127.0.0.1, port 9042)
30 | */
31 | public class SampleCode4x_CONNECT_CreateSchema implements ExampleSchema {
32 |
33 | /** Logger for the class. */
34 | private static Logger LOGGER = LoggerFactory.getLogger(SampleCode4x_CONNECT_CreateSchema.class);
35 |
36 | /** StandAlone (vs JUNIT) to help you running. */
37 | public static void main(String[] args) {
38 | LOGGER.info("Starting 'CreateSchema' sample...");
39 |
40 | try (CqlSession cqlSession = CqlSession.builder()
41 | .addContactPoint(new InetSocketAddress("127.0.0.1", 9042))
42 | .withLocalDatacenter("datacenter1")
43 | .withKeyspace(KEYSPACE_NAME)
44 | .build()) {
45 | createUdtVideoFormat(cqlSession);
46 | createTableUser(cqlSession);
47 | createTableVideo(cqlSession);
48 | createTableVideoViews(cqlSession);
49 | createTableCommentByVideo(cqlSession);
50 | createTableCommentByUser(cqlSession);
51 | }
52 | LOGGER.info("[OK] Success");
53 | System.exit(0);
54 | }
55 |
56 | }
57 |
--------------------------------------------------------------------------------
/example-4x/src/main/java/com/datastax/samples/SampleCode4x_CONNECT_DriverConfigLoader.java:
--------------------------------------------------------------------------------
1 | package com.datastax.samples;
2 |
3 | import java.io.File;
4 |
5 | import org.slf4j.Logger;
6 | import org.slf4j.LoggerFactory;
7 |
8 | import com.datastax.oss.driver.api.core.CqlSession;
9 | import com.datastax.oss.driver.api.core.config.DriverConfigLoader;
10 |
11 | /**
12 | * Sample code to create tables, types and objects in a keyspace.
13 | *
14 | * Pre-requisites:
15 | * - Cassandra running locally (127.0.0.1, port 9042)
16 | * - Keyspace killrvideo created {@link SampleCode4x_CONNECT_CreateKeyspace}
17 | *
18 | * @author Cedrick LUNVEN (@clunven)
19 | */
20 | public class SampleCode4x_CONNECT_DriverConfigLoader implements ExampleSchema {
21 |
22 | /** Logger for the class. */
23 | private static Logger LOGGER = LoggerFactory.getLogger(SampleCode4x_CONNECT_DriverConfigLoader.class);
24 |
25 | /** StandAlone (vs JUNIT) to help you running. */
26 | public static void main(String[] args) {
27 |
28 | // Load Configuration from file
29 | String confFilePath = SampleCode4x_CONNECT_DriverConfigLoader
30 | .class.getResource("/custom_application.conf").getFile();
31 |
32 | // Create a Load with this file
33 | DriverConfigLoader loader =
34 | DriverConfigLoader.fromFile(new File(confFilePath));
35 |
36 | // Use it to create the session
37 | try (CqlSession cqlSession = CqlSession.builder().withConfigLoader(loader).build()) {
38 |
39 | // Use session
40 | LOGGER.info("[OK] Connected to Keyspace {}", cqlSession.getKeyspace().get());
41 | }
42 | LOGGER.info("[OK] Success");
43 | System.exit(0);
44 | }
45 |
46 | }
47 |
--------------------------------------------------------------------------------
/example-4x/src/main/java/com/datastax/samples/SampleCode4x_CONNECT_DropKeyspace.java:
--------------------------------------------------------------------------------
1 | package com.datastax.samples;
2 |
3 | import java.net.InetSocketAddress;
4 |
5 | import org.slf4j.Logger;
6 | import org.slf4j.LoggerFactory;
7 |
8 | import com.datastax.oss.driver.api.core.CqlSession;
9 | import com.datastax.oss.driver.api.querybuilder.SchemaBuilder;
10 |
11 | /**
12 | * Sample code to create tables, types and objects in a keyspace.
13 | *
14 | * Pre-requisites:
15 | * - Cassandra running locally (127.0.0.1, port 9042)
16 | * - Keyspace killrvideo created {@link SampleCode4x_CONNECT_CreateKeyspace}
17 | *
18 | * @author Cedrick LUNVEN (@clunven)
19 | */
20 | public class SampleCode4x_CONNECT_DropKeyspace implements ExampleSchema {
21 |
22 | /** Logger for the class. */
23 | private static Logger LOGGER = LoggerFactory.getLogger(SampleCode4x_CONNECT_DropKeyspace.class);
24 |
25 | /** StandAlone (vs JUNIT) to help you running. */
26 | public static void main(String[] args) {
27 | try (CqlSession cqlSession = CqlSession.builder()
28 | .addContactPoint(new InetSocketAddress("127.0.0.1", 9042))
29 | .withLocalDatacenter("datacenter1")
30 | .build()) {
31 | cqlSession.execute(SchemaBuilder.dropKeyspace(KEYSPACE_NAME).ifExists().build());
32 | LOGGER.info("+ Keyspace '{}' has been dropped (if needed).", KEYSPACE_NAME);
33 | }
34 | LOGGER.info("[OK] Success");
35 | System.exit(0);
36 | }
37 | }
38 |
--------------------------------------------------------------------------------
/example-4x/src/main/java/com/datastax/samples/SampleCode4x_CONNECT_DropSchema.java:
--------------------------------------------------------------------------------
1 | package com.datastax.samples;
2 |
3 | import static com.datastax.samples.ExampleUtils.dropTableIfExists;
4 | import static com.datastax.samples.ExampleUtils.dropTypeIffExists;
5 |
6 | import java.net.InetSocketAddress;
7 |
8 | import org.slf4j.Logger;
9 | import org.slf4j.LoggerFactory;
10 |
11 | import com.datastax.oss.driver.api.core.CqlSession;
12 |
13 | /**
14 | * Sample code to create tables, types and objects in a keyspace.
15 | *
16 | * Pre-requisites:
17 | * - Cassandra running locally (127.0.0.1, port 9042)
18 | * - Keyspace killrvideo created {@link SampleCode4x_CONNECT_CreateKeyspace}
19 | *
20 | * @author Cedrick LUNVEN (@clunven)
21 | */
22 | public class SampleCode4x_CONNECT_DropSchema implements ExampleSchema {
23 |
24 | /** Logger for the class. */
25 | private static Logger LOGGER = LoggerFactory.getLogger(SampleCode4x_CONNECT_DropSchema.class);
26 |
27 | /** StandAlone (vs JUNIT) to help you running. */
28 | public static void main(String[] args) {
29 |
30 | try (CqlSession cqlSession = CqlSession.builder()
31 | .addContactPoint(new InetSocketAddress("127.0.0.1", 9042))
32 | .withLocalDatacenter("datacenter1")
33 | .withKeyspace(KEYSPACE_NAME)
34 | .build()) {
35 | LOGGER.info("[OK] Connected to Keyspace");
36 | dropTableIfExists(cqlSession, COMMENT_BY_VIDEO_TABLENAME);
37 | dropTableIfExists(cqlSession, COMMENT_BY_USER_TABLENAME);
38 | dropTableIfExists(cqlSession, VIDEO_VIEWS_TABLENAME);
39 | dropTableIfExists(cqlSession, VIDEO_TABLENAME);
40 | dropTableIfExists(cqlSession, USER_TABLENAME);
41 | dropTypeIffExists(cqlSession, UDT_VIDEO_FORMAT_NAME);
42 | }
43 | LOGGER.info("[OK] Success");
44 | System.exit(0);
45 | }
46 |
47 | }
48 |
--------------------------------------------------------------------------------
/example-4x/src/main/java/com/datastax/samples/SampleCode4x_CONNECT_ProgrammaticConfiguration.java:
--------------------------------------------------------------------------------
1 | package com.datastax.samples;
2 |
3 | import java.time.Duration;
4 | import java.util.Arrays;
5 |
6 | import org.slf4j.Logger;
7 | import org.slf4j.LoggerFactory;
8 |
9 | import com.datastax.oss.driver.api.core.CqlSession;
10 | import com.datastax.oss.driver.api.core.config.DefaultDriverOption;
11 | import com.datastax.oss.driver.api.core.config.DriverConfigLoader;
12 |
13 | /**
14 | * Sample code to create tables, types and objects in a keyspace.
15 | *
16 | * Pre-requisites:
17 | * - Cassandra running locally (127.0.0.1, port 9042)
18 | * - Keyspace killrvideo created {@link SampleCode4x_CONNECT_CreateKeyspace}
19 | *
20 | * Doc : https://docs.datastax.com/en/developer/java-driver/4.5/manual/core/configuration/
21 | */
22 | public class SampleCode4x_CONNECT_ProgrammaticConfiguration implements ExampleSchema {
23 |
24 | /** Logger for the class. */
25 | private static Logger LOGGER = LoggerFactory.getLogger(SampleCode4x_CONNECT_ProgrammaticConfiguration.class);
26 |
27 | /** StandAlone (vs JUNIT) to help you running. */
28 | public static void main(String[] args) {
29 |
30 | DriverConfigLoader loader = DriverConfigLoader.programmaticBuilder()
31 | .withStringList(DefaultDriverOption.CONTACT_POINTS, Arrays.asList("127.0.0.1:9042"))
32 | .withString(DefaultDriverOption.LOAD_BALANCING_LOCAL_DATACENTER, "datacenter1")
33 | .withString(DefaultDriverOption.SESSION_KEYSPACE, KEYSPACE_NAME)
34 | .withDuration(DefaultDriverOption.REQUEST_TIMEOUT, Duration.ofSeconds(5))
35 |
36 | // If you want to override with an execution profile
37 | .startProfile("slow")
38 | .withDuration(DefaultDriverOption.REQUEST_TIMEOUT, Duration.ofSeconds(30))
39 | .endProfile()
40 | .build();
41 |
42 |
43 | // Use it to create the session
44 | try (CqlSession cqlSession = CqlSession.builder().withConfigLoader(loader).build()) {
45 |
46 | // Use session
47 | LOGGER.info("[OK] Connected to Keyspace {}", cqlSession.getKeyspace().get());
48 | }
49 | LOGGER.info("[OK] Success");
50 | System.exit(0);
51 | }
52 |
53 | }
54 |
--------------------------------------------------------------------------------
/example-4x/src/main/java/com/datastax/samples/SampleCode4x_CONNECT_ServiceCloudAstra.java:
--------------------------------------------------------------------------------
1 | package com.datastax.samples;
2 |
3 | import java.io.File;
4 | import java.nio.file.Paths;
5 |
6 | import org.slf4j.Logger;
7 | import org.slf4j.LoggerFactory;
8 |
9 | import com.datastax.oss.driver.api.core.CqlSession;
10 | import com.datastax.oss.driver.api.core.config.DriverConfigLoader;
11 |
12 | /**
13 | * This class shows how to connect to the DataStax Cloud Cassandra As a Service: ASTRA
14 | *
15 | * Pre-requisites:
16 | * ===================
17 | *
18 | * 1. You need an ASTRA intance : go to astra.datastax.com and create an instance there. There is a free tier
19 | * for you to have a 3-node clusters availables forever. You can find more info on:
20 | *
21 | * 2. You need to provide you ASTRA credentials username, password, keyspace
22 | * but also the secure bundle ZIP. To download it please follow the instruction on :
23 | * https://docs.datastax.com/en/developer/java-driver/4.5/manual/cloud/
24 | *
25 | * 3. You need a java driver version 3.8
26 | */
27 | public class SampleCode4x_CONNECT_ServiceCloudAstra implements ExampleSchema {
28 |
29 | /** Logger for the class. */
30 | private static Logger LOGGER = LoggerFactory.getLogger(SampleCode4x_CONNECT_ServiceCloudAstra.class);
31 |
32 | /** StandAlone (vs JUNIT) to help you running. */
33 | public static void main(String[] args) {
34 |
35 | // ----
36 | // #1. Connecting explicitely using the CqlSessionBuilder
37 | // ----
38 |
39 | // Those are mandatory to connect to ASTRA
40 | final String ASTRA_ZIP_FILE = "/path/to/secure-connect-bundkle.zip";
41 | final String ASTRA_USERNAME = "token";
42 | final String ASTRA_PASSWORD = "AstraCS:...your token";
43 | final String ASTRA_KEYSPACE = "default_keyspace";
44 |
45 | // Check the cloud zip file
46 | File cloudSecureConnectBundleFile = new File(ASTRA_ZIP_FILE);
47 | if (!cloudSecureConnectBundleFile.exists()) {
48 | throw new IllegalStateException("File '" + ASTRA_ZIP_FILE + "' has not been found\n"
49 | + "To run this sample you need to download the secure bundle file from ASTRA WebPage\n"
50 | + "More info here:");
51 | }
52 |
53 | // Connect
54 | try (CqlSession cqlSession = CqlSession.builder()
55 | .withCloudSecureConnectBundle(Paths.get(ASTRA_ZIP_FILE))
56 | .withAuthCredentials(ASTRA_USERNAME, ASTRA_PASSWORD)
57 | .withKeyspace(ASTRA_KEYSPACE)
58 | .build()) {
59 | LOGGER.info("[OK] Welcome to ASTRA. Connected to Keyspace {}", cqlSession.getKeyspace().get());
60 | }
61 |
62 | // ----
63 | // #2. Delegating configuration parameters to dedicated file
64 | // ----
65 |
66 | /*
67 | * In this sample target conf is located in src/main/resources,
68 | * this is what it looks like
69 | *
70 | * datastax-java-driver {
71 | * basic {
72 | * session-keyspace = killrvideo
73 | * cloud {
74 | * secure-connect-bundle = /Users/cedricklunven/Downloads/secure-connect-killrvideo.zip
75 | * }
76 | * }
77 | * advanced {
78 | * auth-provider {
79 | * class = PlainTextAuthProvider
80 | * username = killrvideo
81 | * password = killrvideo
82 | * }
83 | * }
84 | * }
85 | */
86 | String confFilePath = SampleCode4x_CONNECT_DriverConfigLoader
87 | .class.getResource("/custom_astra.conf").getFile();
88 |
89 | try (CqlSession cqlSession = CqlSession.builder()
90 | .withConfigLoader(DriverConfigLoader.fromFile(new File(confFilePath))).build()) {
91 | // Use session
92 | LOGGER.info("[OK] Welcome to ASTRA (conf file). Connected to Keyspace {}",
93 | cqlSession.getKeyspace().get());
94 | }
95 |
96 | LOGGER.info("[OK] Success");
97 | System.exit(0);
98 | }
99 |
100 | }
101 |
--------------------------------------------------------------------------------
/example-4x/src/main/java/com/datastax/samples/SampleCode4x_CRUD_00_GettingStarted.java:
--------------------------------------------------------------------------------
1 | package com.datastax.samples;
2 |
3 | import static com.datastax.samples.ExampleUtils.closeSession;
4 | import static com.datastax.samples.ExampleUtils.connect;
5 | import static com.datastax.samples.ExampleUtils.createKeyspace;
6 | import static com.datastax.samples.ExampleUtils.createTableUser;
7 | import static com.datastax.samples.ExampleUtils.truncateTable;
8 |
9 | import java.time.Duration;
10 |
11 | import org.slf4j.Logger;
12 | import org.slf4j.LoggerFactory;
13 |
14 | import com.datastax.oss.driver.api.core.ConsistencyLevel;
15 | import com.datastax.oss.driver.api.core.CqlSession;
16 | import com.datastax.oss.driver.api.core.cql.BoundStatement;
17 | import com.datastax.oss.driver.api.core.cql.PreparedStatement;
18 | import com.datastax.oss.driver.api.core.cql.SimpleStatement;
19 | import com.datastax.oss.driver.api.querybuilder.QueryBuilder;
20 | import com.datastax.oss.driver.shaded.guava.common.collect.ImmutableMap;
21 |
22 | /**
23 | * Sample codes using Cassandra OSS Driver 4.x
24 | *
25 | * Disclaimers:
26 | * - Tests for arguments nullity has been removed for code clarity
27 | * - Packaged as a main class for usability
28 | *
29 | * Pre-requisites:
30 | * - Cassandra running locally (127.0.0.1, port 9042)
31 | *
32 | * @author Cedrick LUNVEN (@clunven)
33 | * @author Erick RAMIREZ (@@flightc)
34 | */
35 | public class SampleCode4x_CRUD_00_GettingStarted implements ExampleSchema {
36 |
37 | /** Logger for the class. */
38 | private static Logger LOGGER = LoggerFactory.getLogger(SampleCode4x_CRUD_00_GettingStarted.class);
39 |
40 | /** StandAlone (vs JUNIT) to help you running. */
41 | public static void main(String[] args) {
42 |
43 | CqlSession session = null;
44 | try {
45 |
46 | // === INITIALIZING ===
47 |
48 | // Create killrvideo keyspace (if needed)
49 | createKeyspace();
50 |
51 | // Initialize Cluster and Session Objects (connected to keyspace killrvideo)
52 | session = connect();
53 |
54 | // Create working table User (if needed)
55 | createTableUser(session);
56 |
57 | // Empty tables for tests
58 | truncateTable(session, USER_TABLENAME);
59 |
60 | /**
61 | * In this class we will focus only on INSERTING records in order
62 | * to detailled all the ways to interact with Cassandra.
63 | **/
64 |
65 | // #1.a You can execute CQL queries as a String
66 | session.execute(""
67 | + "INSERT INTO users (email, firstname, lastname) "
68 | + "VALUES ('clun@sample.com', 'Cedrick', 'Lunven')");
69 | LOGGER.info("+ Insert as a String");
70 |
71 | // #1.b But everything is a statement
72 | session.execute(SimpleStatement.newInstance(
73 | "INSERT INTO users (email, firstname, lastname) "
74 | + "VALUES ('clun2@sample.com', 'Cedrick', 'Lunven')"));
75 | LOGGER.info("+ Insert as a Statement");
76 |
77 | // #2.a You should externalize variables using character '?'
78 |
79 | // -- option1: add one parameter at a time
80 | session.execute(SimpleStatement
81 | .builder("INSERT INTO users (email, firstname, lastname) VALUES (?,?,?)")
82 | .addPositionalValue("clun3@gmail.com")
83 | .addPositionalValue("Cedrick")
84 | .addPositionalValue("Lunven").build());
85 | LOGGER.info("+ Insert and externalize var with ?, option1");
86 |
87 | // -- option2: add all parameters in one go
88 | session.execute(SimpleStatement
89 | .builder("INSERT INTO users (email, firstname, lastname) VALUES (?,?,?)")
90 | .addPositionalValues("clun4@gmail.com", "Cedrick", "Lunven").build());
91 | LOGGER.info("+ Insert and externalize var with ?, option2");
92 |
93 | // #2.b You can also externalize variables setting a label like :name
94 |
95 | // -- option1: add one parameter at a time
96 | session.execute(SimpleStatement
97 | .builder("INSERT INTO users (email, firstname, lastname) VALUES (:e,:f,:l)")
98 | .addNamedValue("e", "clun5@gmail.com")
99 | .addNamedValue("f", "Cedrick")
100 | .addNamedValue("l", "Lunven").build());
101 | LOGGER.info("+ Insert and externalize var with :labels, option1");
102 |
103 | // -- option2: add all parameters in one go
104 | session.execute(SimpleStatement
105 | .builder("INSERT INTO users (email, firstname, lastname) VALUES (:e,:f,:l)")
106 | // You can override attributes in the statements
107 | .setConsistencyLevel(ConsistencyLevel.ONE)
108 | .setTimeout(Duration.ofSeconds(2))
109 | .build()
110 | .setNamedValues(ImmutableMap.of(
111 | "e", "clun6@gmail.com",
112 | "f", "Cedrick",
113 | "l", "Lunven")));
114 | LOGGER.info("+ Insert and externalize var with :labels, option2");
115 |
116 |
117 | // #4. You can use QueryBuilder to help you building your statements
118 | session.execute(QueryBuilder
119 | .insertInto(USER_TABLENAME)
120 | .value(USER_EMAIL, QueryBuilder.literal("clun5@gmail.com"))
121 | .value(USER_FIRSTNAME, QueryBuilder.literal("Cedrick"))
122 | .value(USER_LASTNAME, QueryBuilder.literal("Lunven"))
123 | .build());
124 | LOGGER.info("+ Insert with QueryBuilder");
125 |
126 | // #5.It is recommended to prepare your statements
127 | // Prepare once, execute multiple times is much faster
128 | // Use session.prepare()
129 |
130 | // 5.a Use '?' for parameters
131 | // doc: https://docs.datastax.com/en/developer/java-driver/4.5/manual/core/statements/prepared/
132 | PreparedStatement ps1 = session.prepare("INSERT INTO users (email, firstname, lastname) "
133 | + "VALUES (?,?,?)");
134 | BoundStatement bs1 = ps1.bind("clun6@gmail.com", "Cedrick", "Lunven");
135 | session.execute(bs1);
136 | LOGGER.info("+ Insert with PrepareStatements");
137 |
138 |
139 | // 5.b To prepare statements with QueryBuilder, use 'bindMarker'
140 | PreparedStatement ps2 = session.prepare(QueryBuilder
141 | .insertInto(USER_TABLENAME)
142 | .value(USER_EMAIL, QueryBuilder.bindMarker())
143 | .value(USER_FIRSTNAME, QueryBuilder.bindMarker())
144 | .value(USER_LASTNAME, QueryBuilder.bindMarker())
145 | .build());
146 | session.execute(ps2.bind("clun7@gmail.com", "Cedrick", "Lunven"));
147 | LOGGER.info("+ Insert with PrepareStatements + QueryBuilder");
148 |
149 |
150 | // In next SAMPLES you will find everything with QueryBuidler and PreparedStatement
151 | // Enjoy !!!
152 |
153 | } finally {
154 | closeSession(session);
155 | }
156 | System.exit(0);
157 | }
158 |
159 |
160 |
161 | }
162 |
--------------------------------------------------------------------------------
/example-4x/src/main/java/com/datastax/samples/SampleCode4x_CRUD_01_Simple.java:
--------------------------------------------------------------------------------
1 | package com.datastax.samples;
2 |
3 | import static com.datastax.samples.ExampleUtils.closeSession;
4 | import static com.datastax.samples.ExampleUtils.connect;
5 | import static com.datastax.samples.ExampleUtils.createKeyspace;
6 | import static com.datastax.samples.ExampleUtils.createTableUser;
7 | import static com.datastax.samples.ExampleUtils.truncateTable;
8 |
9 | import java.util.List;
10 | import java.util.Optional;
11 | import java.util.stream.Collectors;
12 |
13 | import org.slf4j.Logger;
14 | import org.slf4j.LoggerFactory;
15 |
16 | import com.datastax.oss.driver.api.core.CqlSession;
17 | import com.datastax.oss.driver.api.core.cql.PreparedStatement;
18 | import com.datastax.oss.driver.api.core.cql.ResultSet;
19 | import com.datastax.oss.driver.api.core.cql.Row;
20 | import com.datastax.oss.driver.api.querybuilder.QueryBuilder;
21 | import com.datastax.samples.dto.UserDto;
22 |
23 | /**
24 | * Sample codes using Cassandra OSS Driver 4.x
25 | *
26 | * Disclaimers:
27 | * - Tests for arguments nullity has been removed for code clarity
28 | * - Packaged as a main class for usability
29 | *
30 | * Pre-requisites:
31 | * - Cassandra running locally (127.0.0.1, port 9042)
32 | *
33 | * @author Cedrick LUNVEN (@clunven)
34 | * @author Erick RAMIREZ (@@flightc)
35 | */
36 | public class SampleCode4x_CRUD_01_Simple implements ExampleSchema {
37 |
38 | /** Logger for the class. */
39 | private static Logger LOGGER = LoggerFactory.getLogger(SampleCode4x_CRUD_01_Simple.class);
40 |
41 | // This will be used as singletons for the sample
42 | private static CqlSession session;
43 |
44 | // Prepare your statements once and execute multiple times
45 | private static PreparedStatement stmtCreateUser;
46 | private static PreparedStatement stmtUpsertUser;
47 | private static PreparedStatement stmtExistUser;
48 | private static PreparedStatement stmtDeleteUser;
49 | private static PreparedStatement stmtFindUser;
50 |
51 | /** StandAlone (vs JUNIT) to help you running. */
52 | public static void main(String[] args) {
53 | try {
54 |
55 | // === INITIALIZING ===
56 |
57 | // Create killrvideo keyspace (if needed)
58 | createKeyspace();
59 |
60 | // Initialize Cluster and Session Objects (connected to keyspace killrvideo)
61 | session = connect();
62 |
63 | // Create working table User (if needed)
64 | createTableUser(session);
65 |
66 | // Empty tables for tests
67 | truncateTable(session, USER_TABLENAME);
68 |
69 | // Prepare your statements once and execute multiple times
70 | prepareStatements();
71 |
72 | // ========== CREATE ===========
73 |
74 | String userEmail = "clun@sample.com";
75 |
76 | if (!existUser(userEmail)) {
77 | LOGGER.info("+ {} does not exists in table 'user'", userEmail);
78 | }
79 |
80 | createUser(userEmail, "Cedric", "Lunven");
81 |
82 | if (existUser(userEmail)) {
83 | LOGGER.info("+ {} now exists in table 'user'", userEmail);
84 | }
85 |
86 | // ========= UPDATE ============
87 |
88 | String userEmail2 = "eram@sample.com";
89 |
90 | if (!existUser(userEmail2)) {
91 | LOGGER.info("+ {} does not exists in table 'user'", userEmail2);
92 | }
93 |
94 | updateUser(userEmail2, "Eric", "Ramirez");
95 |
96 | if (existUser(userEmail2)) {
97 | LOGGER.info("+ {} now exists in table 'user'", userEmail2);
98 | }
99 |
100 | // ========= DELETE ============
101 |
102 | // Delete an existing user by its email (if email does not exist, no error)
103 | deleteUser(userEmail2);
104 | if (!existUser(userEmail2)) {
105 | LOGGER.info("+ {} does not exists in table 'user'", userEmail2);
106 | }
107 |
108 | // ========= READ ==============
109 |
110 | // Will be empty as we have deleted it
111 | Optional erick = findUserById(userEmail2);
112 | LOGGER.info("+ Retrieved {}: {}", userEmail2,erick); // Expected Optiona.empty()
113 |
114 | // Not null
115 | Optional cedrick = findUserById(userEmail);
116 | LOGGER.info("+ Retrieved {}: {}", userEmail, cedrick.get().getEmail());
117 |
118 | // Read all (first upserts)
119 | updateUser(userEmail2, "Eric", "Ramirez");
120 | updateUser(userEmail, "Cedrick", "Lunven");
121 | List allUsers = session
122 | .execute(QueryBuilder.selectFrom(USER_TABLENAME).all().build())
123 | .all().stream().map(UserDto::new)
124 | .collect(Collectors.toList());
125 | LOGGER.info("+ Retrieved users count {}", allUsers.size());
126 |
127 | } finally {
128 | closeSession(session);
129 | }
130 | System.exit(0);
131 | }
132 |
133 | private static boolean existUser(String email) {
134 | return session.execute(stmtExistUser.bind(email)).getAvailableWithoutFetching() > 0;
135 | }
136 |
137 | private static void createUser(String email, String firstname, String lastname) {
138 | ResultSet rs = session.execute(stmtCreateUser.bind(email, firstname, lastname));
139 | if (!rs.wasApplied()) {
140 | throw new IllegalArgumentException("Email '" + email + "' already exist in Database. Cannot create new user");
141 | }
142 | LOGGER.info("+ User {} has been created", email);
143 | }
144 |
145 | private static void updateUser(String email, String firstname, String lastname) {
146 | session.execute(stmtUpsertUser.bind(email, firstname, lastname));
147 | LOGGER.info("+ User {} has been updated", email);
148 | }
149 |
150 | private static void deleteUser(String email) {
151 | session.execute(stmtDeleteUser.bind(email));
152 | LOGGER.info("+ User {} has been deleted", email);
153 | }
154 |
155 | private static Optional < UserDto > findUserById(String email) {
156 | ResultSet rs = session.execute(stmtFindUser.bind(email));
157 | // We query by the primary key ensuring unicity
158 | Row record = rs.one();
159 | return (null != record) ? Optional.of(new UserDto(record)) :Optional.empty();
160 | }
161 |
162 | private static void prepareStatements() {
163 | stmtCreateUser = session.prepare(QueryBuilder.insertInto(USER_TABLENAME)
164 | .value(USER_EMAIL, QueryBuilder.bindMarker())
165 | .value(USER_FIRSTNAME, QueryBuilder.bindMarker())
166 | .value(USER_LASTNAME, QueryBuilder.bindMarker())
167 | .ifNotExists().build());
168 | stmtUpsertUser = session.prepare(QueryBuilder.insertInto(USER_TABLENAME)
169 | .value(USER_EMAIL, QueryBuilder.bindMarker())
170 | .value(USER_FIRSTNAME, QueryBuilder.bindMarker())
171 | .value(USER_LASTNAME, QueryBuilder.bindMarker())
172 | .build());
173 | stmtExistUser = session.prepare(QueryBuilder
174 | .selectFrom(USER_TABLENAME).column(USER_EMAIL)
175 | .whereColumn(USER_EMAIL)
176 | .isEqualTo(QueryBuilder.bindMarker())
177 | .build());
178 | stmtDeleteUser = session.prepare(QueryBuilder
179 | .deleteFrom(USER_TABLENAME)
180 | .whereColumn(USER_EMAIL)
181 | .isEqualTo(QueryBuilder.bindMarker())
182 | .build());
183 | stmtFindUser = session.prepare(QueryBuilder
184 | .selectFrom(USER_TABLENAME).all()
185 | .whereColumn(USER_EMAIL)
186 | .isEqualTo(QueryBuilder.bindMarker())
187 | .build());
188 |
189 | }
190 |
191 | }
192 |
--------------------------------------------------------------------------------
/example-4x/src/main/java/com/datastax/samples/SampleCode4x_CRUD_02_Paging.java:
--------------------------------------------------------------------------------
1 | package com.datastax.samples;
2 |
3 | import static com.datastax.samples.ExampleUtils.closeSession;
4 | import static com.datastax.samples.ExampleUtils.connect;
5 | import static com.datastax.samples.ExampleUtils.createKeyspace;
6 | import static com.datastax.samples.ExampleUtils.createTableUser;
7 | import static com.datastax.samples.ExampleUtils.truncateTable;
8 |
9 | import java.nio.ByteBuffer;
10 | import java.time.Duration;
11 | import java.util.Iterator;
12 |
13 | import org.slf4j.Logger;
14 | import org.slf4j.LoggerFactory;
15 |
16 | import com.datastax.oss.driver.api.core.ConsistencyLevel;
17 | import com.datastax.oss.driver.api.core.CqlSession;
18 | import com.datastax.oss.driver.api.core.cql.BatchStatement;
19 | import com.datastax.oss.driver.api.core.cql.BatchStatementBuilder;
20 | import com.datastax.oss.driver.api.core.cql.DefaultBatchType;
21 | import com.datastax.oss.driver.api.core.cql.PreparedStatement;
22 | import com.datastax.oss.driver.api.core.cql.ResultSet;
23 | import com.datastax.oss.driver.api.core.cql.Row;
24 | import com.datastax.oss.driver.api.core.cql.SimpleStatement;
25 | import com.datastax.oss.driver.api.querybuilder.QueryBuilder;
26 |
27 | import com.datastax.oss.protocol.internal.util.Bytes;
28 |
29 | /**
30 | * Sample codes using Cassandra OSS Driver 4.x
31 | *
32 | * Disclaimers:
33 | * - Tests for arguments nullity has been removed for code clarity
34 | * - Packaged as a main class for usability
35 | *
36 | * Pre-requisites:
37 | * - Cassandra running locally (127.0.0.1, port 9042)
38 | *
39 | * @author Cedrick LUNVEN (@clunven)
40 | * @author Erick RAMIREZ (@@flightc)
41 | */
42 | public class SampleCode4x_CRUD_02_Paging implements ExampleSchema {
43 |
44 | /** Logger for the class. */
45 | private static Logger LOGGER = LoggerFactory.getLogger(SampleCode4x_CRUD_02_Paging.class);
46 |
47 | /** StandAlone (vs JUNIT) to help you running. */
48 | public static void main(String[] args) {
49 |
50 | CqlSession session = null;
51 | try {
52 |
53 | // === INITIALIZING ===
54 |
55 | // Create killrvideo keyspace (if needed)
56 | createKeyspace();
57 |
58 | // Initialize Cluster and Session Objects
59 | session = connect();
60 |
61 | // Create working table User (if needed)
62 | createTableUser(session);
63 |
64 | // Empty tables for tests
65 | truncateTable(session, USER_TABLENAME);
66 |
67 | PreparedStatement stmtCreateUser =
68 | session.prepare(QueryBuilder.insertInto(USER_TABLENAME)
69 | .value(USER_EMAIL, QueryBuilder.bindMarker())
70 | .value(USER_FIRSTNAME, QueryBuilder.bindMarker())
71 | .value(USER_LASTNAME, QueryBuilder.bindMarker())
72 | .build());
73 |
74 | // Adding 50 records in the table
75 | BatchStatementBuilder bb = BatchStatement.builder(DefaultBatchType.LOGGED);
76 | for (int i = 0; i < 50; i++) {
77 | bb.addStatement(stmtCreateUser.bind("user_" + i + "@sample.com", "user_" + i, "lastname"));
78 | }
79 | session.execute(bb.build());
80 | LOGGER.info("+ {} users have been created", 50);
81 |
82 | // Paged query
83 | SimpleStatement statement = QueryBuilder.selectFrom(USER_TABLENAME).all().build()
84 | .setPageSize(10) // 10 per pages
85 | .setTimeout(Duration.ofSeconds(1)) // 1s timeout
86 | .setConsistencyLevel(ConsistencyLevel.ONE);
87 | ResultSet page1 = session.execute(statement);
88 |
89 | // Checking
90 | LOGGER.info("+ Page 1 has {} items", page1.getAvailableWithoutFetching());
91 | Iterator page1Iter = page1.iterator();
92 | while (0 < page1.getAvailableWithoutFetching()) {
93 | LOGGER.info("Page1: " + page1Iter.next().getString(USER_EMAIL));
94 | }
95 |
96 | // Notice that items are NOT ordered (it uses the hashed token)
97 | // From this point if you invoke .next() driver will look for page2.
98 | // But we can invoke page2 directly: (useful for delay between calls)
99 | ByteBuffer pagingStateAsBytes = page1.getExecutionInfo().getPagingState();
100 |
101 | // If you need to to externalize this as a STRING
102 | Bytes.toHexString(pagingStateAsBytes);
103 | // If you need to go back to byteBuffer
104 | // ByteBuffer pagingStateAsBytesBack = Bytes.fromHexString(pageStateAsString);
105 |
106 | statement.setPagingState(pagingStateAsBytes);
107 | ResultSet page2 = session.execute(statement);
108 | LOGGER.info("+ Page 2 has {} items", page2.getAvailableWithoutFetching());
109 |
110 | } finally {
111 | closeSession(session);
112 | }
113 | System.exit(0);
114 | }
115 |
116 | }
117 |
--------------------------------------------------------------------------------
/example-4x/src/main/java/com/datastax/samples/SampleCode4x_CRUD_07_ObjectMapping.java:
--------------------------------------------------------------------------------
1 | package com.datastax.samples;
2 |
3 | import static com.datastax.samples.ExampleUtils.closeSession;
4 | import static com.datastax.samples.ExampleUtils.connect;
5 | import static com.datastax.samples.ExampleUtils.createKeyspace;
6 | import static com.datastax.samples.ExampleUtils.createTableCommentByUser;
7 | import static com.datastax.samples.ExampleUtils.createTableCommentByVideo;
8 | import static com.datastax.samples.ExampleUtils.truncateTable;
9 |
10 | import java.util.UUID;
11 |
12 | import org.slf4j.Logger;
13 | import org.slf4j.LoggerFactory;
14 |
15 | import com.datastax.oss.driver.api.core.CqlSession;
16 | import com.datastax.samples.objectmapping.Comment;
17 | import com.datastax.samples.objectmapping.CommentByUser;
18 | import com.datastax.samples.objectmapping.CommentByVideo;
19 | import com.datastax.samples.objectmapping.CommentDao;
20 | import com.datastax.samples.objectmapping.CommentDaoMapper;
21 |
22 | /**
23 | * Sample codes using Cassandra OSS Driver 4.x
24 | *
25 | * Disclaimers:
26 | * - Tests for arguments nullity has been removed for code clarity
27 | * - Packaged as a main class for usability
28 | *
29 | * Pre-requisites:
30 | * - Cassandra running locally (127.0.0.1, port 9042)
31 | *
32 | * @author Cedrick LUNVEN (@clunven)
33 | * @author Erick RAMIREZ (@@flightc)
34 | */
35 | public class SampleCode4x_CRUD_07_ObjectMapping implements ExampleSchema {
36 |
37 | /** Logger for the class. */
38 | private static Logger LOGGER = LoggerFactory.getLogger(SampleCode4x_CRUD_07_ObjectMapping.class);
39 |
40 | // This will be used as singletons for the sample
41 | private static CqlSession session;
42 |
43 | /** StandAlone (vs JUNIT) to help you running. */
44 | public static void main(String[] args) {
45 |
46 | try {
47 |
48 | // Create killrvideo keyspace (if needed)
49 | createKeyspace();
50 |
51 | // Initialize Cluster and Session Objects
52 | session = connect();
53 |
54 | // Create working table User (if needed)
55 | createTableCommentByUser(session);
56 | createTableCommentByVideo(session);
57 |
58 | // Comments are used in 2 queries, we need 2 tables to store it
59 | truncateTable(session, COMMENT_BY_USER_TABLENAME);
60 | truncateTable(session, COMMENT_BY_VIDEO_TABLENAME);
61 |
62 | // All logic is defined in Mapper/Dao/Entities in objectmapping package
63 | // Mapper required the table to exist
64 | CommentDao dao = CommentDaoMapper.builder(session)
65 | .withDefaultKeyspace(KEYSPACE_NAME)
66 | .build().commentDao();
67 |
68 | // DataSet
69 | UUID user_1 = UUID.randomUUID();UUID user_2 = UUID.randomUUID();
70 | UUID videoid_1 = UUID.randomUUID();UUID videoid_2 = UUID.randomUUID();
71 | Comment c1 = new Comment(user_1, videoid_1, "I am user1 and video1 is good");
72 | Comment c2 = new Comment(user_2, videoid_1, "I am user2 and video1 is bad");
73 | Comment c3 = new Comment(user_1, videoid_2, "Video2 is cool");
74 | Comment c4 = new Comment(user_2, videoid_2, "Video2");
75 |
76 | /* ==================== CREATE =====================
77 | * Create comment (in 2 tables with BATCH)
78 | * ================================================= */
79 | dao.upsert(c1);dao.upsert(c2);
80 | dao.upsert(c3);dao.upsert(c4);
81 | dao.retrieveVideoComments(videoid_2).all()
82 | .stream().map(CommentByVideo::getComment)
83 | .forEach(LOGGER::info);
84 |
85 | /* =============== UPDATE ==========================
86 | * == Update one comment (in 2 tables with BATCH) ==
87 | * ================================================= */
88 | c1.setComment("This is my new comment");
89 | dao.upsert(c1);
90 | dao.retrieveVideoComments(videoid_1).all()
91 | .stream().map(CommentByVideo::getComment)
92 | .forEach(LOGGER::info);
93 |
94 | /* =============== DELETE ===========================
95 | * Delete one comment (in 2 tables with BATCH) ==
96 | * Note that commentId is NOT ENOUGH as userid and ==
97 | * videoid are part of the the primary keys. ==
98 | * ==================================================*/
99 | dao.delete(c1);
100 | dao.retrieveVideoComments(videoid_1).all()
101 | .stream().map(CommentByVideo::getComment)
102 | .forEach(LOGGER::info);
103 |
104 | /*
105 | * ============================ READ ================================
106 | * == Query1: List comments for user_1 with table comment_by_user =
107 | * == Query2: List comments for video_2 with table comment_by_video =
108 | * ==================================================================
109 | */
110 |
111 | dao.retrieveUserComments(videoid_2).all()
112 | .stream().map(CommentByUser::getComment)
113 | .forEach(LOGGER::info);
114 |
115 | dao.retrieveVideoComments(videoid_2).all()
116 | .stream().map(CommentByVideo::getComment)
117 | .forEach(LOGGER::info);
118 |
119 | } finally {
120 | // Close Cluster and Session
121 | closeSession(session);
122 | }
123 | System.exit(0);
124 | }
125 |
126 | }
127 |
--------------------------------------------------------------------------------
/example-4x/src/main/java/com/datastax/samples/SampleCode4x_CRUD_08_Counters.java:
--------------------------------------------------------------------------------
1 | package com.datastax.samples;
2 |
3 | import static com.datastax.samples.ExampleUtils.connect;
4 | import static com.datastax.samples.ExampleUtils.closeSession;
5 | import static com.datastax.samples.ExampleUtils.createKeyspace;
6 | import static com.datastax.samples.ExampleUtils.createTableVideoViews;
7 | import static com.datastax.samples.ExampleUtils.truncateTable;
8 |
9 | import java.util.Optional;
10 | import java.util.UUID;
11 |
12 | import org.slf4j.Logger;
13 | import org.slf4j.LoggerFactory;
14 |
15 | import com.datastax.oss.driver.api.core.CqlSession;
16 | import com.datastax.oss.driver.api.core.cql.PreparedStatement;
17 | import com.datastax.oss.driver.api.core.cql.Row;
18 | import com.datastax.oss.driver.api.querybuilder.QueryBuilder;
19 |
20 | /**
21 | * Working with Counters :
22 | *
23 | * CREATE TABLE IF NOT EXISTS videos_views (
24 | * videoid uuid,
25 | * views counter,
26 | * PRIMARY KEY (videoid)
27 | * );
28 | *
29 | * Definition:
30 | * - 64-bit signed integer
31 | * -First op assumes the value is zero
32 | *
33 | * Use-case:
34 | * - Imprecise values such as likes, views, etc.
35 | *
36 | * Two operations:
37 | * - Increment
38 | * - Decrement
39 | *
40 | * Limitations:
41 | * - Cannot be part of primary key
42 | * - Counters not mixed with other types in table
43 | * - Value cannot be set
44 | * - Rows with counters cannot be inserted
45 | * - Updates are not idempotent
46 | * - Counters should not be used for precise values
47 | */
48 | public class SampleCode4x_CRUD_08_Counters implements ExampleSchema {
49 |
50 | /** Logger for the class. */
51 | private static Logger LOGGER = LoggerFactory.getLogger(SampleCode4x_CRUD_08_Counters.class);
52 |
53 | // This will be used as singletons for the sample
54 | private static CqlSession session;
55 |
56 | // Prepare your statements once and execute multiple times
57 | private static PreparedStatement stmtIncrement;
58 | private static PreparedStatement stmtDecrement;
59 | private static PreparedStatement stmtFindById;
60 | private static PreparedStatement stmtDelete;
61 |
62 | /** StandAlone (vs JUNIT) to help you running. */
63 | public static void main(String[] args) {
64 | try {
65 |
66 | // Create killrvideo keyspace (if needed)
67 | createKeyspace();
68 |
69 | // Initialize Cluster and Session Objects
70 | session = connect();
71 |
72 | // Create tables for tests
73 | createTableVideoViews(session);
74 |
75 | // Empty tables for tests
76 | truncateTable(session, VIDEO_VIEWS_TABLENAME);
77 |
78 | // Prepare your statements once and execute multiple times
79 | prepareStatements();
80 |
81 | // ========= CREATE ============
82 |
83 | // We cannot insert in a table with a counter
84 | UUID videoId = UUID.randomUUID();
85 | LOGGER.info("+ Video views {}", findById(videoId));
86 |
87 | // ========= UPDATE ============
88 |
89 | incrementBy(videoId, 10);
90 | LOGGER.info("+ Video views : {}", findById(videoId).get());
91 |
92 | decrementBy(videoId, 8);
93 | LOGGER.info("+ Video views : {}", findById(videoId).get());
94 |
95 | // ========= DELETE ============
96 |
97 | delete(videoId);
98 | LOGGER.info("+ Video views {}", findById(videoId));
99 |
100 |
101 | } finally {
102 | // Close Cluster and Session
103 | closeSession(session);
104 | }
105 | System.exit(0);
106 | }
107 |
108 | private static Optional findById(UUID videoid) {
109 | Row record = session.execute(stmtFindById.bind(videoid)).one();
110 | if (null != record) {
111 | return Optional.of(record.getLong(VIDEO_VIEWS_VIEWS));
112 | }
113 | return Optional.empty();
114 | }
115 |
116 | private static void incrementBy(UUID videoid, long val) {
117 | session.execute(stmtIncrement.bind(val, videoid));
118 | }
119 |
120 | private static void decrementBy(UUID videoid, long val) {
121 | session.execute(stmtDecrement.bind(val, videoid));
122 | }
123 |
124 | private static void delete(UUID videoid) {
125 | session.execute(stmtDelete.bind(videoid));
126 | }
127 |
128 | private static void prepareStatements() {
129 |
130 | // update videos_views SET views = views + X WHERE videoid=...
131 | stmtIncrement = session.prepare(QueryBuilder
132 | .update(VIDEO_VIEWS_TABLENAME)
133 | .increment(VIDEO_VIEWS_VIEWS, QueryBuilder.bindMarker())
134 | .whereColumn(VIDEO_VIEWS_VIDEOID).isEqualTo(QueryBuilder.bindMarker())
135 | .build());
136 |
137 | // update videos_views SET views = views + X WHERE videoid=..
138 | stmtDecrement = session.prepare(QueryBuilder
139 | .update(VIDEO_VIEWS_TABLENAME)
140 | .decrement(VIDEO_VIEWS_VIEWS, QueryBuilder.bindMarker())
141 | .whereColumn(VIDEO_VIEWS_VIDEOID).isEqualTo(QueryBuilder.bindMarker())
142 | .build());
143 |
144 | // SELECT views FROM videos_views WHERE videoid=...
145 | stmtFindById = session.prepare(QueryBuilder
146 | .selectFrom(VIDEO_VIEWS_TABLENAME).column(VIDEO_VIEWS_VIEWS)
147 | .whereColumn(VIDEO_VIEWS_VIDEOID).isEqualTo(QueryBuilder.bindMarker())
148 | .build());
149 |
150 | // DELETE FROM videos_views WHERE videoid=...
151 | stmtDelete = session.prepare(QueryBuilder
152 | .deleteFrom(VIDEO_VIEWS_TABLENAME)
153 | .whereColumn(VIDEO_VIEWS_VIDEOID).isEqualTo(QueryBuilder.bindMarker())
154 | .build());
155 |
156 | }
157 |
158 | }
159 |
--------------------------------------------------------------------------------
/example-4x/src/main/java/com/datastax/samples/SampleCode4x_CRUD_09_LightweightTransactions.java:
--------------------------------------------------------------------------------
1 | package com.datastax.samples;
2 |
3 | import static com.datastax.samples.ExampleUtils.*;
4 |
5 | import org.slf4j.Logger;
6 | import org.slf4j.LoggerFactory;
7 |
8 | import com.datastax.oss.driver.api.core.CqlSession;
9 | import com.datastax.oss.driver.api.core.cql.PreparedStatement;
10 | import com.datastax.oss.driver.api.querybuilder.QueryBuilder;
11 |
12 |
13 | /**
14 | * CREATE TABLE IF NOT EXISTS users (
15 | * email text,
16 | * firstname text,
17 | * lastname text,
18 | * PRIMARY KEY (email)
19 | * );
20 | */
21 | public class SampleCode4x_CRUD_09_LightweightTransactions implements ExampleSchema {
22 |
23 | /** Logger for the class. */
24 | private static Logger LOGGER = LoggerFactory.getLogger(SampleCode4x_CRUD_09_LightweightTransactions.class);
25 |
26 | // This will be used as singletons for the sample
27 | private static CqlSession session;
28 |
29 | // Prepare your statements once and execute multiple times
30 | private static PreparedStatement stmtCreateUser;
31 | private static PreparedStatement stmtUpdateUserLwt;
32 |
33 | /** StandAlone (vs JUNIT) to help you running. */
34 | public static void main(String[] args) {
35 | try {
36 |
37 | // Initialize Cluster and Session Objects
38 | session = connect();
39 |
40 | // Use PreparedStatement for queries that are executed multiple times in your application
41 | prepareStatements();
42 |
43 | // Create working table User (if needed)
44 | createTableUser(session);
45 |
46 | // Empty tables for tests
47 | truncateTable(session, USER_TABLENAME);
48 |
49 | // Insert if not exist
50 | boolean first = createUserIfNotExist("clun@sample.com", "Cedric", "Lunven");
51 | boolean second = createUserIfNotExist("clun@sample.com", "Cedric", "Lunven");
52 | LOGGER.info("+ Created first time ? {} and second time {}", first, second);
53 |
54 | // Update if condition
55 | boolean applied1 = updateIf("clun@sample.com", "Cedric", "BEST");
56 | boolean applied2 = updateIf("clun@sample.com", "Cedrick", "Lunven");
57 | LOGGER.info("+ Applied when correct value ? {} and invalid value {}", applied1, applied2);
58 |
59 | } finally {
60 | closeSession(session);
61 | }
62 | System.exit(0);
63 | }
64 |
65 | /**
66 | * The resultset is applied only if the record is created. If not the resultSet is populated
67 | * with existing data in DB (read)
68 | */
69 | private static boolean createUserIfNotExist(String email, String firstname, String lastname) {
70 | return session.execute(stmtCreateUser.bind(email, firstname, lastname)).wasApplied();
71 | }
72 |
73 | /**
74 | * Note: we named the parameters as they are not in the same order in the query.
75 | */
76 | private static boolean updateIf(String email, String expectedFirstName, String newLastName) {
77 | return session.execute(stmtUpdateUserLwt.bind()
78 | .setString(USER_EMAIL, email)
79 | .setString(USER_FIRSTNAME, expectedFirstName)
80 | .setString(USER_LASTNAME, newLastName)).wasApplied();
81 | }
82 |
83 | /**
84 | * Documentation
85 | * https://docs.datastax.com/en/developer/java-driver/3.8/manual/statements/prepared/#prepared-statements
86 | */
87 | private static void prepareStatements() {
88 |
89 | /*
90 | * INSERT INTO users (email, firstname, lastname)
91 | * VALUES(?,?,?)
92 | * IF NOT EXISTS
93 | */
94 | stmtCreateUser = session.prepare(QueryBuilder.insertInto(USER_TABLENAME)
95 | .value(USER_EMAIL, QueryBuilder.bindMarker())
96 | .value(USER_FIRSTNAME, QueryBuilder.bindMarker())
97 | .value(USER_LASTNAME, QueryBuilder.bindMarker())
98 | .ifNotExists()
99 | .build());
100 |
101 | /*
102 | * UPDATE users SET lastname=:lastname
103 | * WHERE email=:email
104 | * IF firstname=:firstname
105 | *
106 | * Operators available for LWT Condition:
107 | * =, <, <=, >, >=, != and IN
108 | */
109 | stmtUpdateUserLwt = session.prepare(QueryBuilder.update(USER_TABLENAME)
110 | .setColumn(USER_LASTNAME, QueryBuilder.bindMarker(USER_LASTNAME))
111 | .whereColumn(USER_EMAIL).isEqualTo(QueryBuilder.bindMarker(USER_EMAIL))
112 | .ifColumn(USER_FIRSTNAME).isEqualTo(QueryBuilder.bindMarker(USER_FIRSTNAME))
113 | .build());
114 | }
115 |
116 | }
117 |
--------------------------------------------------------------------------------
/example-4x/src/main/java/com/datastax/samples/SampleCode4x_CRUD_11_Reactive.java:
--------------------------------------------------------------------------------
1 | package com.datastax.samples;
2 |
3 | import static com.datastax.samples.ExampleUtils.closeSession;
4 | import static com.datastax.samples.ExampleUtils.connect;
5 | import static com.datastax.samples.ExampleUtils.createKeyspace;
6 | import static com.datastax.samples.ExampleUtils.createTableUser;
7 | import static com.datastax.samples.ExampleUtils.truncateTable;
8 |
9 | import java.util.Optional;
10 | import java.util.concurrent.ExecutionException;
11 |
12 | import org.slf4j.Logger;
13 | import org.slf4j.LoggerFactory;
14 |
15 | import com.datastax.dse.driver.api.core.cql.reactive.ReactiveResultSet;
16 | import com.datastax.oss.driver.api.core.CqlSession;
17 | import com.datastax.oss.driver.api.core.cql.PreparedStatement;
18 | import com.datastax.oss.driver.api.core.cql.SimpleStatement;
19 | import com.datastax.oss.driver.api.querybuilder.QueryBuilder;
20 | import com.datastax.samples.dto.UserDto;
21 |
22 | import reactor.core.publisher.Flux;
23 | import reactor.core.publisher.Mono;
24 |
25 | /**
26 | * Sample codes using Cassandra OSS Driver 4.x
27 | *
28 | * Disclaimers:
29 | * - Tests for arguments nullity has been removed for code clarity
30 | * - Packaged as a main class for usability
31 | *
32 | * Pre-requisites:
33 | * - Cassandra running locally (127.0.0.1, port 9042)
34 | *
35 | * Doc: https://docs.datastax.com/en/developer/java-driver/4.4/manual/core/reactive/
36 | * @author Cedrick LUNVEN (@clunven)
37 | * @author Erick RAMIREZ (@@flightc)
38 | */
39 | public class SampleCode4x_CRUD_11_Reactive implements ExampleSchema {
40 |
41 | /** Logger for the class. */
42 | private static Logger LOGGER = LoggerFactory.getLogger(SampleCode4x_CRUD_11_Reactive.class);
43 |
44 | // This will be used as singletons for the sample
45 | private static CqlSession session;
46 |
47 | // Prepare your statements once and execute multiple times
48 | private static PreparedStatement stmtUpsertUser;
49 | private static PreparedStatement stmtExistUser;
50 | private static PreparedStatement stmtDeleteUser;
51 | private static PreparedStatement stmtFindUser;
52 |
53 | /** StandAlone (vs JUNIT) to help you running.
54 | * @throws ExecutionException
55 | * @throws InterruptedException */
56 | public static void main(String[] args)
57 | throws InterruptedException, ExecutionException {
58 | try {
59 |
60 | // === INITIALIZING ===
61 |
62 | // Create killrvideo keyspace (if needed)
63 | createKeyspace();
64 |
65 | // Initialize Cluster and Session Objects (connected to keyspace killrvideo)
66 | session = connect();
67 |
68 | // Create working table User (if needed)
69 | createTableUser(session);
70 |
71 | // Empty tables for tests
72 | truncateTable(session, USER_TABLENAME);
73 |
74 | // Prepare your statements once and execute multiple times
75 | prepareStatements();
76 |
77 | // ========== CREATE / UPDATE ===========
78 |
79 | String userEmail = "clun@sample.com";
80 | String userEmail2 = "ram@sample.com";
81 |
82 | // Test existence of user 1 to false and then create user 1
83 | existUserReactive(userEmail)
84 | .doOnNext(exist -> LOGGER.info("+ '{}' exists ? (expecting false): {}", userEmail, exist))
85 | .and(upsertUserReactive(userEmail, "Cedric", "Lunven"))
86 | .block();
87 |
88 | // User 1 now exist and we log (blocking call)
89 | existUserReactive(userEmail)
90 | .doOnNext(exist -> LOGGER.info("+ '{}' exists ? (expecting false): {}", userEmail, exist))
91 | .block();
92 |
93 | // Creating user 2 to be deleted
94 | upsertUserReactive(userEmail2, "Eric", "Ramirez")
95 | .doOnNext(exist -> LOGGER.info("+ '{}' exists ? (expecting false): {}", userEmail2, exist))
96 | .block();
97 |
98 | // ========= DELETE ============
99 |
100 | deleteUserReactive(userEmail2)
101 | .doOnNext(exist -> LOGGER.info("+ '{}' exists ? (expecting false) {}", userEmail2, exist))
102 | .block(); // enforce blocking call to have logs.
103 |
104 | // ========= READ ==============
105 |
106 | // User 2 has been deleted as such will be empty
107 | findUserByIdReactive("eram@sample.com")
108 | .doOnNext(erick -> LOGGER.info("+ Retrieved '{}': (expecting Optional.empty) {}", userEmail2, erick))
109 | .block(); // enforce blocking call to have logs.
110 |
111 | // User 1 is there so we should lie
112 | findUserByIdReactive("clun@sample.com")
113 | .doOnNext(erick -> LOGGER.info("+ Retrieved '{}': (expecting result) {}", userEmail2, erick))
114 | .block(); // enforce blocking call to have logs.
115 |
116 | // creating user 2 again to have 2 records in the tables
117 | upsertUserReactive(userEmail2, "Eric", "Ramirez")
118 | .doOnNext(exist -> LOGGER.info("+ '{}' exists ? (expecting false): {}", userEmail2, exist))
119 | .block();
120 | // Listing users
121 | listAllUserReactive()
122 | .map(UserDto::getEmail)
123 | .doOnNext(email -> LOGGER.info("+ '{}' email found", email))
124 | .blockLast();
125 |
126 | Thread.sleep(500);
127 | } finally {
128 | closeSession(session);
129 | }
130 | System.exit(0);
131 | }
132 |
133 | private static Mono existUserReactive(String email) {
134 | ReactiveResultSet rrs = session.executeReactive(stmtExistUser.bind(email));
135 | return Mono.from(rrs).map(rs -> true).defaultIfEmpty(false);
136 | }
137 |
138 | private static Mono> findUserByIdReactive(String email) {
139 | return Mono.from(session.executeReactive(stmtFindUser.bind(email)))
140 | .doOnNext(row -> LOGGER.info("+ Retrieved '{}': (expecting result) {}", row.getString(USER_EMAIL), email))
141 | .map(UserDto::new).map(Optional::of)
142 | .defaultIfEmpty(Optional.empty());
143 | }
144 |
145 | private static Mono upsertUserReactive(String email, String firstname, String lastname) {
146 | ReactiveResultSet rrs = session.executeReactive(stmtUpsertUser.bind(email, firstname, lastname));
147 | return Mono.from(rrs).then();
148 | }
149 |
150 | private static Mono deleteUserReactive(String email) {
151 | return Mono.from(session.executeReactive(stmtDeleteUser.bind(email))).then();
152 | }
153 |
154 | private static Flux listAllUserReactive() {
155 | SimpleStatement queryAllUser = QueryBuilder.selectFrom(USER_TABLENAME).all().build();
156 | return Flux.from(session.executeReactive(queryAllUser)).map(UserDto::new);
157 | }
158 |
159 | private static void prepareStatements() {
160 | stmtUpsertUser = session.prepare(QueryBuilder.insertInto(USER_TABLENAME)
161 | .value(USER_EMAIL, QueryBuilder.bindMarker())
162 | .value(USER_FIRSTNAME, QueryBuilder.bindMarker())
163 | .value(USER_LASTNAME, QueryBuilder.bindMarker())
164 | .build());
165 | stmtExistUser = session.prepare(QueryBuilder
166 | .selectFrom(USER_TABLENAME).column(USER_EMAIL)
167 | .whereColumn(USER_EMAIL)
168 | .isEqualTo(QueryBuilder.bindMarker())
169 | .build());
170 | stmtDeleteUser = session.prepare(QueryBuilder
171 | .deleteFrom(USER_TABLENAME)
172 | .whereColumn(USER_EMAIL)
173 | .isEqualTo(QueryBuilder.bindMarker())
174 | .build());
175 | stmtFindUser = session.prepare(QueryBuilder
176 | .selectFrom(USER_TABLENAME).all()
177 | .whereColumn(USER_EMAIL)
178 | .isEqualTo(QueryBuilder.bindMarker())
179 | .build());
180 |
181 | }
182 |
183 | }
184 |
--------------------------------------------------------------------------------
/example-4x/src/main/java/com/datastax/samples/SampleCode4x_Vector.java:
--------------------------------------------------------------------------------
1 | package com.datastax.samples;
2 |
3 | import com.datastax.oss.driver.api.core.CqlSession;
4 | import com.datastax.oss.driver.api.core.cql.Row;
5 | import com.datastax.oss.driver.api.core.cql.SimpleStatement;
6 | import org.slf4j.Logger;
7 | import org.slf4j.LoggerFactory;
8 |
9 | import java.util.List;
10 | import java.util.Optional;
11 | import java.util.concurrent.ExecutionException;
12 |
13 | import static com.datastax.samples.ExampleUtils.closeSession;
14 | import static com.datastax.samples.ExampleUtils.connect;
15 | import static com.datastax.samples.ExampleUtils.createKeyspace;
16 |
17 | public class SampleCode4x_Vector {
18 |
19 | private static final Logger LOGGER = LoggerFactory.getLogger(SampleCode4x_CRUD_11_Reactive.class);
20 |
21 | private static CqlSession session;
22 |
23 | public static void main(String[] args)
24 | throws InterruptedException, ExecutionException {
25 |
26 | try {
27 |
28 | // === INITIALIZING ===
29 |
30 | // Create keyspace (if needed)
31 | createKeyspace();
32 |
33 | // Initialize Cluster and Session Objects (connected to keyspace)
34 | session = connect();
35 |
36 | // Create table and index.
37 | createSchema(session);
38 |
39 | // Populate Table
40 | populateTable(session);
41 |
42 | // Semantic Search
43 | findProductById(session, "pf1843").ifPresent(product -> {
44 | LOGGER.info("Product Found ! looking for similar products");
45 | findAllSimilarProducts(session, product).forEach(p -> LOGGER.info("Product {}", p));
46 | });
47 |
48 | } finally {
49 | closeSession(session);
50 |
51 | }
52 | }
53 |
54 | private static record Product(String productId, String productName, Object vector) {}
55 |
56 | private static void createSchema(CqlSession cqlSession) {
57 | // Create a Table with Embeddings
58 | cqlSession.execute(
59 | "CREATE TABLE IF NOT EXISTS pet_supply_vectors (" +
60 | " product_id TEXT PRIMARY KEY," +
61 | " product_name TEXT," +
62 | " product_vector vector)");
63 | LOGGER.info("Table created.");
64 |
65 | // Create a Search Index
66 | cqlSession.execute(
67 | "CREATE CUSTOM INDEX IF NOT EXISTS idx_vector " +
68 | "ON pet_supply_vectors(product_vector) " +
69 | "USING 'StorageAttachedIndex'");
70 | LOGGER.info("Index Created.");
71 | }
72 |
73 | private static void populateTable(CqlSession cqlSession) {
74 | // Insert rows
75 | cqlSession.execute(
76 | "INSERT INTO pet_supply_vectors (product_id, product_name, product_vector) " +
77 | "VALUES ('pf1843','HealthyFresh - Chicken raw dog food',[1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0])");
78 | cqlSession.execute(
79 | "INSERT INTO pet_supply_vectors (product_id, product_name, product_vector) " +
80 | "VALUES ('pf1844','HealthyFresh - Beef raw dog food',[1, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0])");
81 | cqlSession.execute(
82 | "INSERT INTO pet_supply_vectors (product_id, product_name, product_vector) " +
83 | "VALUES ('pt0021','Dog Tennis Ball Toy',[0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0])");
84 | cqlSession.execute(
85 | "INSERT INTO pet_supply_vectors (product_id, product_name, product_vector) " +
86 | "VALUES ('pt0041','Dog Ring Chew Toy',[0, 0, 0, 1, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0])");
87 | cqlSession.execute(
88 | "INSERT INTO pet_supply_vectors (product_id, product_name, product_vector) " +
89 | "VALUES ('pf7043','PupperSausage Bacon dog Treats',[0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 1, 1])");
90 | cqlSession.execute(
91 | "INSERT INTO pet_supply_vectors (product_id, product_name, product_vector) " +
92 | "VALUES ('pf7044','PupperSausage Beef dog Treats',[0, 0, 0, 1, 0, 1, 1, 0, 0, 0, 0, 0, 1, 0])");
93 | LOGGER.info("Rows inserted.");
94 | }
95 |
96 | private static Optional findProductById(CqlSession cqlsession, String productId) {
97 | Row row = cqlsession.execute(SimpleStatement
98 | .builder("SELECT * FROM pet_supply_vectors WHERE product_id = ?")
99 | .addPositionalValue(productId).build()).one();
100 | return (row != null) ? Optional.of(row).map(SampleCode4x_Vector::mapRowAsProduct) : Optional.empty();
101 | }
102 |
103 | private static List findAllSimilarProducts(CqlSession cqlsession, Product orginal) {
104 | return cqlsession.execute(SimpleStatement
105 | .builder("SELECT * FROM pet_supply_vectors " +
106 | "ORDER BY product_vector ANN OF ? LIMIT 2;")
107 | .addPositionalValue(orginal.vector)
108 | .build())
109 | .all()
110 | .stream()
111 | .filter(row -> !row.getString("product_id").equals(orginal.productId))
112 | .map(SampleCode4x_Vector::mapRowAsProduct)
113 | .toList();
114 | }
115 |
116 | private static Product mapRowAsProduct(Row row) {
117 | return new Product(
118 | row.getString("product_id"),
119 | row.getString("product_name"),
120 | row.getObject("product_vector"));
121 | }
122 |
123 |
124 | }
125 |
--------------------------------------------------------------------------------
/example-4x/src/main/java/com/datastax/samples/codec/BytesArrayTypeCodec.java:
--------------------------------------------------------------------------------
1 | package com.datastax.samples.codec;
2 |
3 | import java.nio.ByteBuffer;
4 | import java.nio.charset.Charset;
5 | import java.nio.charset.StandardCharsets;
6 |
7 | import com.datastax.oss.driver.api.core.ProtocolVersion;
8 | import com.datastax.oss.driver.api.core.type.DataType;
9 | import com.datastax.oss.driver.api.core.type.DataTypes;
10 | import com.datastax.oss.driver.api.core.type.codec.TypeCodec;
11 | import com.datastax.oss.driver.api.core.type.reflect.GenericType;
12 |
13 | /**
14 | * Retrieve a blob as a byte array from Cassandra.
15 | */
16 | public class BytesArrayTypeCodec implements TypeCodec {
17 |
18 | private Charset charSet = StandardCharsets.UTF_8;
19 |
20 | public BytesArrayTypeCodec(Charset charSet) {
21 | this.charSet = charSet;
22 | }
23 |
24 | /** Default constructor. */
25 | public BytesArrayTypeCodec() {
26 | this(StandardCharsets.UTF_8);
27 | }
28 |
29 | /** {@inheritDoc} */
30 | @Override
31 | public GenericType getJavaType() {
32 | return GenericType.of(byte[].class);
33 | }
34 |
35 | /** {@inheritDoc} */
36 | @Override
37 | public DataType getCqlType() {
38 | return DataTypes.BLOB;
39 | }
40 |
41 | /** {@inheritDoc} */
42 | @Override
43 | public ByteBuffer encode(byte[] value, ProtocolVersion protocolVersion) {
44 | if (value == null) return null;
45 | ByteBuffer byteBuffer = ByteBuffer.allocate(value.length);
46 | byteBuffer.put(value);
47 | return byteBuffer;
48 | }
49 |
50 | /** {@inheritDoc} */
51 | @Override
52 | public byte[] decode(ByteBuffer byteBuffer, ProtocolVersion protocolVersion) {
53 | if (byteBuffer == null) return null;
54 | byte[] bytesArray = new byte[byteBuffer.remaining()];
55 | byteBuffer.get(bytesArray, 0, bytesArray.length);
56 | return bytesArray;
57 | }
58 |
59 | /** {@inheritDoc} */
60 | @Override
61 | public String format(byte[] value) {
62 | if (value == null) return "NULL";
63 | return new String(value, charSet);
64 | }
65 |
66 | /** {@inheritDoc} */
67 | @Override
68 | public byte[] parse(String value) {
69 | return (value == null || value.isEmpty() || value.equalsIgnoreCase("NULL"))
70 | ? null
71 | : value.getBytes(charSet);
72 | }
73 |
74 | }
75 |
--------------------------------------------------------------------------------
/example-4x/src/main/java/com/datastax/samples/codec/JsonJacksonTypeCodec.java:
--------------------------------------------------------------------------------
1 | package com.datastax.samples.codec;
2 |
3 | import java.io.IOException;
4 | import java.io.Serializable;
5 | import java.nio.ByteBuffer;
6 |
7 | import com.datastax.oss.driver.api.core.ProtocolVersion;
8 | import com.datastax.oss.driver.api.core.type.DataType;
9 | import com.datastax.oss.driver.api.core.type.DataTypes;
10 | import com.datastax.oss.driver.api.core.type.codec.TypeCodec;
11 | import com.datastax.oss.driver.api.core.type.reflect.GenericType;
12 | import com.fasterxml.jackson.core.JsonProcessingException;
13 | import com.fasterxml.jackson.databind.ObjectMapper;
14 | import com.fasterxml.jackson.databind.type.TypeFactory;
15 |
16 | /**
17 | * Convert some PJP into JSON.
18 | *
19 | * @param
20 | */
21 | public class JsonJacksonTypeCodec implements TypeCodec {
22 |
23 | /**
24 | * Jackson will help us here json <-> POJO
25 | */
26 | private final ObjectMapper objectMapper = new ObjectMapper();
27 |
28 | private Class javaType;
29 |
30 | public JsonJacksonTypeCodec(Class classType) {
31 | this.javaType = classType;
32 | }
33 |
34 | /** {@inheritDoc} */
35 | @Override
36 | public GenericType getJavaType() {
37 | return GenericType.of(javaType);
38 | }
39 |
40 | /** {@inheritDoc} */
41 | @Override
42 | public DataType getCqlType() {
43 | return DataTypes.TEXT;
44 | }
45 |
46 | /** {@inheritDoc} */
47 | @Override
48 | public ByteBuffer encode(T value, ProtocolVersion protocolVersion) {
49 | if (value == null)
50 | return null;
51 | try {
52 | return ByteBuffer.wrap(objectMapper.writeValueAsBytes(value));
53 | } catch (JsonProcessingException e) {
54 | throw new IllegalArgumentException(e.getMessage(), e);
55 | }
56 | }
57 |
58 | /** {@inheritDoc} */
59 | @Override
60 | @SuppressWarnings("unchecked")
61 | public T decode(ByteBuffer bytes, ProtocolVersion protocolVersion) {
62 | if (bytes == null)
63 | return null;
64 | try {
65 | byte[] b = new byte[bytes.remaining()];
66 | bytes.duplicate().get(b);
67 | return (T) objectMapper.readValue(b, TypeFactory.defaultInstance().constructType(getJavaType().getType()));
68 | } catch (IOException e) {
69 | throw new IllegalArgumentException(e.getMessage(), e);
70 | }
71 | }
72 |
73 | /** {@inheritDoc} */
74 | @Override
75 | public String format(T value) {
76 | if (value == null)
77 | return "NULL";
78 | String json;
79 | try {
80 | json = objectMapper.writeValueAsString(value);
81 | } catch (IOException e) {
82 | throw new IllegalArgumentException(e.getMessage(), e);
83 | }
84 | return '\'' + json.replace("\'", "''") + '\'';
85 | }
86 |
87 | /** {@inheritDoc} */
88 | @Override
89 | @SuppressWarnings("unchecked")
90 | public T parse(String value) {
91 | if (value == null || value.isEmpty() || value.equalsIgnoreCase("NULL"))
92 | return null;
93 | if (value.charAt(0) != '\'' || value.charAt(value.length() - 1) != '\'')
94 | throw new IllegalArgumentException("JSON strings must be enclosed by single quotes");
95 | String json = value.substring(1, value.length() - 1).replace("''", "'");
96 | try {
97 | return (T) objectMapper.readValue(json, TypeFactory.defaultInstance().constructType(getJavaType().getType()));
98 | } catch (IOException e) {
99 | throw new IllegalArgumentException(e.getMessage(), e);
100 | }
101 | }
102 |
103 | }
104 |
--------------------------------------------------------------------------------
/example-4x/src/main/java/com/datastax/samples/codec/UdtVideoFormatCodec.java:
--------------------------------------------------------------------------------
1 | package com.datastax.samples.codec;
2 |
3 | import java.nio.ByteBuffer;
4 |
5 | import com.datastax.oss.driver.api.core.ProtocolVersion;
6 | import com.datastax.oss.driver.api.core.data.UdtValue;
7 | import com.datastax.oss.driver.api.core.type.DataType;
8 | import com.datastax.oss.driver.api.core.type.UserDefinedType;
9 | import com.datastax.oss.driver.api.core.type.codec.TypeCodec;
10 | import com.datastax.oss.driver.api.core.type.reflect.GenericType;
11 | import com.datastax.samples.ExampleSchema;
12 | import com.datastax.samples.dto.VideoFormatDto;
13 |
14 | /**
15 | * Codec.
16 | */
17 | public class UdtVideoFormatCodec implements TypeCodec, ExampleSchema {
18 |
19 | final TypeCodec innerCodec;
20 |
21 | final UserDefinedType videoFormatUdt;
22 |
23 | public UdtVideoFormatCodec(TypeCodec innerCodec, Class javaType) {
24 | this.innerCodec = innerCodec;
25 | this.videoFormatUdt = (UserDefinedType) innerCodec.getCqlType();
26 | }
27 |
28 | /** {@inheritDoc} */
29 | @Override
30 | public GenericType getJavaType() {
31 | return GenericType.of(VideoFormatDto.class);
32 | }
33 |
34 | /** {@inheritDoc} */
35 | @Override
36 | public DataType getCqlType() {
37 | return videoFormatUdt;
38 | }
39 |
40 | /** {@inheritDoc} */
41 | @Override
42 | public ByteBuffer encode(VideoFormatDto value, ProtocolVersion protocolVersion) {
43 | return innerCodec.encode(toUDTValue(value), protocolVersion);
44 | }
45 |
46 | /** {@inheritDoc} */
47 | @Override
48 | public VideoFormatDto decode(ByteBuffer bytes, ProtocolVersion protocolVersion) {
49 | return toVideoFormatDto(innerCodec.decode(bytes, protocolVersion));
50 | }
51 |
52 | /** {@inheritDoc} */
53 | @Override
54 | public String format(VideoFormatDto value) {
55 | return value == null ? "NULL" : innerCodec.format(toUDTValue(value));
56 | }
57 |
58 | /** {@inheritDoc} */
59 | @Override
60 | public VideoFormatDto parse(String value) {
61 | return value == null || value.isEmpty() || value.equalsIgnoreCase("NULL") ?
62 | null : toVideoFormatDto(innerCodec.parse(value));
63 | }
64 |
65 | protected VideoFormatDto toVideoFormatDto(UdtValue value) {
66 | return value == null ? null : new VideoFormatDto(
67 | value.getInt(UDT_VIDEO_FORMAT_WIDTH),
68 | value.getInt(UDT_VIDEO_FORMAT_HEIGHT)
69 | );
70 | }
71 |
72 | protected UdtValue toUDTValue(VideoFormatDto value) {
73 | return value == null ? null : videoFormatUdt.newValue()
74 | .setInt(UDT_VIDEO_FORMAT_WIDTH, value.getWidth())
75 | .setInt(UDT_VIDEO_FORMAT_HEIGHT, value.getHeight());
76 | }
77 |
78 | }
79 |
--------------------------------------------------------------------------------
/example-4x/src/main/java/com/datastax/samples/dto/FileDto.java:
--------------------------------------------------------------------------------
1 | package com.datastax.samples.dto;
2 |
3 | import java.io.Serializable;
4 | import java.nio.ByteBuffer;
5 | import java.time.Instant;
6 |
7 | /**
8 | * Sample POJO.
9 | */
10 | public class FileDto implements Serializable {
11 |
12 | /** Serial. */
13 | private static final long serialVersionUID = 7325306650146053028L;
14 |
15 | private String filename;
16 |
17 | private String extension;
18 |
19 | private Instant updload;
20 |
21 | private ByteBuffer content;
22 |
23 | public FileDto() {
24 | }
25 |
26 | /**
27 | * Getter accessor for attribute 'filename'.
28 | *
29 | * @return
30 | * current value of 'filename'
31 | */
32 | public String getFilename() {
33 | return filename;
34 | }
35 |
36 | /**
37 | * Setter accessor for attribute 'filename'.
38 | * @param filename
39 | * new value for 'filename '
40 | */
41 | public void setFilename(String filename) {
42 | this.filename = filename;
43 | }
44 |
45 | /**
46 | * Getter accessor for attribute 'extension'.
47 | *
48 | * @return
49 | * current value of 'extension'
50 | */
51 | public String getExtension() {
52 | return extension;
53 | }
54 |
55 | /**
56 | * Setter accessor for attribute 'extension'.
57 | * @param extension
58 | * new value for 'extension '
59 | */
60 | public void setExtension(String extension) {
61 | this.extension = extension;
62 | }
63 |
64 | /**
65 | * Getter accessor for attribute 'updload'.
66 | *
67 | * @return
68 | * current value of 'updload'
69 | */
70 | public Instant getUpload() {
71 | return updload;
72 | }
73 |
74 | /**
75 | * Setter accessor for attribute 'updload'.
76 | * @param updload
77 | * new value for 'updload '
78 | */
79 | public void setUpload(Instant updload) {
80 | this.updload = updload;
81 | }
82 |
83 | /**
84 | * Getter accessor for attribute 'content'.
85 | *
86 | * @return
87 | * current value of 'content'
88 | */
89 | public ByteBuffer getContent() {
90 | return content;
91 | }
92 |
93 | /**
94 | * Setter accessor for attribute 'content'.
95 | * @param content
96 | * new value for 'content '
97 | */
98 | public void setContent(ByteBuffer content) {
99 | this.content = content;
100 | }
101 |
102 |
103 |
104 | }
105 |
--------------------------------------------------------------------------------
/example-4x/src/main/java/com/datastax/samples/dto/UserDto.java:
--------------------------------------------------------------------------------
1 | package com.datastax.samples.dto;
2 |
3 | import java.io.Serializable;
4 |
5 | import com.datastax.oss.driver.api.core.cql.Row;
6 | import com.datastax.samples.ExampleSchema;
7 |
8 | /**
9 | * Sample bean for row.
10 | */
11 | public class UserDto implements Serializable, ExampleSchema {
12 |
13 | /** Serial. */
14 | private static final long serialVersionUID = -6767335554891314036L;
15 |
16 | private String email;
17 |
18 | private String firstName;
19 |
20 | private String lastName;
21 |
22 | public UserDto() {
23 | }
24 |
25 | public UserDto(Row tableUsersRow) {
26 | super();
27 | this.email = tableUsersRow.getString(USER_EMAIL);
28 | this.firstName = tableUsersRow.getString(USER_FIRSTNAME);
29 | this.lastName = tableUsersRow.getString(USER_LASTNAME);
30 | }
31 |
32 | public UserDto(String email, String firstName, String lastName) {
33 | super();
34 | this.email = email;
35 | this.firstName = firstName;
36 | this.lastName = lastName;
37 | }
38 |
39 | /**
40 | * Getter accessor for attribute 'email'.
41 | *
42 | * @return
43 | * current value of 'email'
44 | */
45 | public String getEmail() {
46 | return email;
47 | }
48 |
49 | /**
50 | * Setter accessor for attribute 'email'.
51 | * @param email
52 | * new value for 'email '
53 | */
54 | public void setEmail(String email) {
55 | this.email = email;
56 | }
57 |
58 | /**
59 | * Getter accessor for attribute 'firstName'.
60 | *
61 | * @return
62 | * current value of 'firstName'
63 | */
64 | public String getFirstName() {
65 | return firstName;
66 | }
67 |
68 | /**
69 | * Setter accessor for attribute 'firstName'.
70 | * @param firstName
71 | * new value for 'firstName '
72 | */
73 | public void setFirstName(String firstName) {
74 | this.firstName = firstName;
75 | }
76 |
77 | /**
78 | * Getter accessor for attribute 'lastName'.
79 | *
80 | * @return
81 | * current value of 'lastName'
82 | */
83 | public String getLastName() {
84 | return lastName;
85 | }
86 |
87 | /**
88 | * Setter accessor for attribute 'lastName'.
89 | * @param lastName
90 | * new value for 'lastName '
91 | */
92 | public void setLastName(String lastName) {
93 | this.lastName = lastName;
94 | }
95 |
96 | }
97 |
--------------------------------------------------------------------------------
/example-4x/src/main/java/com/datastax/samples/dto/VideoDto.java:
--------------------------------------------------------------------------------
1 | package com.datastax.samples.dto;
2 |
3 | import java.io.Serializable;
4 | import java.time.Instant;
5 | import java.util.ArrayList;
6 | import java.util.HashMap;
7 | import java.util.HashSet;
8 | import java.util.List;
9 | import java.util.Map;
10 | import java.util.Set;
11 | import java.util.UUID;
12 |
13 | import com.fasterxml.jackson.annotation.JsonIgnore;
14 |
15 | /**
16 | * CREATE TABLE IF NOT EXISTS videos ( videoid uuid, title text, upload timestamp, email text, url text, tags set , formats
17 | * map >, PRIMARY KEY (videoid) );
18 | */
19 | public class VideoDto implements Serializable {
20 |
21 | /** Serial. */
22 | private static final long serialVersionUID = -5086632646056781255L;
23 |
24 | private UUID videoid;
25 |
26 | private String title;
27 |
28 | private String email;
29 |
30 | private String url;
31 |
32 | @JsonIgnore
33 | private long upload = Instant.now().toEpochMilli();
34 |
35 | private Set tags = new HashSet<>();
36 |
37 | private List frames = new ArrayList<>();
38 |
39 | private Map formats = new HashMap<>();
40 |
41 | public VideoDto() {}
42 |
43 | public VideoDto(UUID videoId, String title, String email, String url) {
44 | super();
45 | this.videoid = videoId;
46 | this.title = title;
47 | this.email = email;
48 | }
49 |
50 | /**
51 | * Getter accessor for attribute 'videoId'.
52 | *
53 | * @return current value of 'videoId'
54 | */
55 | public UUID getVideoid() {
56 | return videoid;
57 | }
58 |
59 | /**
60 | * Setter accessor for attribute 'videoId'.
61 | *
62 | * @param videoId
63 | * new value for 'videoId '
64 | */
65 | public void setVideoid(UUID videoId) {
66 | this.videoid = videoId;
67 | }
68 |
69 | /**
70 | * Getter accessor for attribute 'title'.
71 | *
72 | * @return current value of 'title'
73 | */
74 | public String getTitle() {
75 | return title;
76 | }
77 |
78 | /**
79 | * Setter accessor for attribute 'title'.
80 | *
81 | * @param title
82 | * new value for 'title '
83 | */
84 | public void setTitle(String title) {
85 | this.title = title;
86 | }
87 |
88 | /**
89 | * Getter accessor for attribute 'upload'.
90 | *
91 | * @return current value of 'upload'
92 | */
93 | public Long getUpload() {
94 | return upload;
95 | }
96 |
97 | /**
98 | * Setter accessor for attribute 'upload'.
99 | *
100 | * @param upload
101 | * new value for 'upload '
102 | */
103 | public void setUpload(Long upload) {
104 | this.upload = upload;
105 | }
106 |
107 | /**
108 | * Getter accessor for attribute 'email'.
109 | *
110 | * @return current value of 'email'
111 | */
112 | public String getEmail() {
113 | return email;
114 | }
115 |
116 | /**
117 | * Setter accessor for attribute 'email'.
118 | *
119 | * @param email
120 | * new value for 'email '
121 | */
122 | public void setEmail(String email) {
123 | this.email = email;
124 | }
125 |
126 | /**
127 | * Getter accessor for attribute 'tags'.
128 | *
129 | * @return current value of 'tags'
130 | */
131 | public Set getTags() {
132 | return tags;
133 | }
134 |
135 | /**
136 | * Setter accessor for attribute 'tags'.
137 | *
138 | * @param tags
139 | * new value for 'tags '
140 | */
141 | public void setTags(Set tags) {
142 | this.tags = tags;
143 | }
144 |
145 | /**
146 | * Getter accessor for attribute 'formatsd'.
147 | *
148 | * @return current value of 'formatsd'
149 | */
150 | public Map getFormats() {
151 | return formats;
152 | }
153 |
154 | /**
155 | * Setter accessor for attribute 'formatsd'.
156 | *
157 | * @param formatsd
158 | * new value for 'formatsd '
159 | */
160 | public void setFormats(Map formatsd) {
161 | this.formats = formatsd;
162 | }
163 |
164 | public String getUrl() {
165 | return url;
166 | }
167 |
168 | public void setUrl(String url) {
169 | this.url = url;
170 | }
171 |
172 | /**
173 | * Getter accessor for attribute 'frames'.
174 | *
175 | * @return current value of 'frames'
176 | */
177 | public List getFrames() {
178 | return frames;
179 | }
180 |
181 | /**
182 | * Setter accessor for attribute 'frames'.
183 | *
184 | * @param frames
185 | * new value for 'frames '
186 | */
187 | public void setFrames(List frames) {
188 | this.frames = frames;
189 | }
190 |
191 | }
192 |
--------------------------------------------------------------------------------
/example-4x/src/main/java/com/datastax/samples/dto/VideoFormatDto.java:
--------------------------------------------------------------------------------
1 | package com.datastax.samples.dto;
2 |
3 | /**
4 | * CREATE TYPE IF NOT EXISTS video_format (
5 | * width int,
6 | * height int,
7 | * frames list
8 | * );
9 | */
10 | public class VideoFormatDto {
11 |
12 | private int width = 0;
13 |
14 | private int height = 0;
15 |
16 | public VideoFormatDto() {}
17 |
18 | public VideoFormatDto(int w, int h) {
19 | this.width = w;
20 | this.height = h;
21 | }
22 |
23 | public int getWidth() {
24 | return width;
25 | }
26 |
27 | public void setWidth(int width) {
28 | this.width = width;
29 | }
30 |
31 | public int getHeight() {
32 | return height;
33 | }
34 |
35 | public void setHeight(int height) {
36 | this.height = height;
37 | }
38 |
39 | @Override
40 | public String toString() {
41 | return "VideoFormatDto [width=" + width + ", height=" + height;
42 | }
43 | }
44 |
--------------------------------------------------------------------------------
/example-4x/src/main/java/com/datastax/samples/objectmapping/Comment.java:
--------------------------------------------------------------------------------
1 | package com.datastax.samples.objectmapping;
2 |
3 | import java.io.Serializable;
4 | import java.util.UUID;
5 |
6 | import com.datastax.oss.driver.api.core.uuid.Uuids;
7 | import com.datastax.oss.driver.api.mapper.annotations.ClusteringColumn;
8 | import com.datastax.oss.driver.api.mapper.annotations.CqlName;
9 | import com.datastax.samples.ExampleSchema;
10 |
11 | /**
12 | * Bean standing for comment on video.
13 | *
14 | * @author DataStax Developer Advocates team.
15 | */
16 | public class Comment implements Serializable, ExampleSchema {
17 |
18 | /** Serial. */
19 | private static final long serialVersionUID = 7675521710612951368L;
20 |
21 | @CqlName(COMMENT_BY_USER_USERID)
22 | protected UUID userid;
23 |
24 | @CqlName(COMMENT_BY_USER_VIDEOID)
25 | protected UUID videoid;
26 |
27 | @ClusteringColumn
28 | @CqlName(COMMENT_BY_USER_COMMENTID)
29 | protected UUID commentid;
30 |
31 | @CqlName(COMMENT_BY_USER_COMMENT)
32 | protected String comment;
33 |
34 | /**
35 | * Default constructor.
36 | */
37 | public Comment() {
38 | }
39 |
40 | /**
41 | * Constructor with parameters.
42 | *
43 | * @param userid
44 | * user unique identifier
45 | * @param videoId
46 | * video unique identifier
47 | * @param comment
48 | * text value for the comment
49 | */
50 | public Comment(UUID userid, UUID videoId, String comment) {
51 | this.userid = userid;
52 | this.videoid = videoId;
53 | this.comment = comment;
54 | this.commentid = Uuids.timeBased();
55 | }
56 |
57 | /**
58 | * Default constructor.
59 | */
60 | public Comment(String comment) {
61 | this.comment = comment;
62 | }
63 |
64 | /**
65 | * Setter for attribute 'userid'.
66 | * @param userid
67 | * new value for 'userid '
68 | */
69 | public void setUserid(UUID userid) {
70 | this.userid = userid;
71 | }
72 |
73 | /**
74 | * Setter for attribute 'videoid'.
75 | * @param videoid
76 | * new value for 'videoid '
77 | */
78 | public void setVideoid(UUID videoid) {
79 | this.videoid = videoid;
80 | }
81 |
82 | /**
83 | * Getter for attribute 'commentid'.
84 | *
85 | * @return
86 | * current value of 'commentid'
87 | */
88 | public UUID getCommentid() {
89 | return commentid;
90 | }
91 |
92 | /**
93 | * Setter for attribute 'commentid'.
94 | * @param commentid
95 | * new value for 'commentid '
96 | */
97 | public void setCommentid(UUID commentid) {
98 | this.commentid = commentid;
99 | }
100 |
101 | /**
102 | * Getter for attribute 'comment'.
103 | *
104 | * @return
105 | * current value of 'comment'
106 | */
107 | public String getComment() {
108 | return comment;
109 | }
110 |
111 | /**
112 | * Setter for attribute 'comment'.
113 | * @param comment
114 | * new value for 'comment '
115 | */
116 | public void setComment(String comment) {
117 | this.comment = comment;
118 | }
119 |
120 | /**
121 | * Getter for attribute 'userid'.
122 | *
123 | * @return
124 | * current value of 'userid'
125 | */
126 | public UUID getUserid() {
127 | return userid;
128 | }
129 |
130 | /**
131 | * Getter for attribute 'videoid'.
132 | *
133 | * @return
134 | * current value of 'videoid'
135 | */
136 | public UUID getVideoid() {
137 | return videoid;
138 | }
139 |
140 |
141 | }
142 |
--------------------------------------------------------------------------------
/example-4x/src/main/java/com/datastax/samples/objectmapping/CommentByUser.java:
--------------------------------------------------------------------------------
1 | package com.datastax.samples.objectmapping;
2 |
3 | import java.util.UUID;
4 |
5 | import com.datastax.oss.driver.api.mapper.annotations.CqlName;
6 | import com.datastax.oss.driver.api.mapper.annotations.Entity;
7 | import com.datastax.oss.driver.api.mapper.annotations.PartitionKey;
8 | import com.datastax.samples.ExampleSchema;
9 |
10 | /**
11 | * Specialization for USER.
12 | *
13 | * @author DataStax Developer Advocates team.
14 | */
15 | @Entity
16 | @CqlName(ExampleSchema.COMMENT_BY_USER_TABLENAME)
17 | public class CommentByUser extends Comment {
18 |
19 | /** Serial. */
20 | private static final long serialVersionUID = 1453554109222565840L;
21 |
22 | /**
23 | * Default constructor.
24 | */
25 | public CommentByUser() {}
26 |
27 | /**
28 | * Copy constructor.
29 | *
30 | * @param c
31 | */
32 | public CommentByUser(Comment c) {
33 | this.commentid = c.getCommentid();
34 | this.userid = c.getUserid();
35 | this.videoid = c.getVideoid();
36 | this.comment = c.getComment();
37 | }
38 |
39 | /**
40 | * Getter for attribute 'userid'.
41 | *
42 | * @return
43 | * current value of 'userid'
44 | */
45 | @PartitionKey
46 | public UUID getUserid() {
47 | return userid;
48 | }
49 |
50 | }
51 |
--------------------------------------------------------------------------------
/example-4x/src/main/java/com/datastax/samples/objectmapping/CommentByVideo.java:
--------------------------------------------------------------------------------
1 | package com.datastax.samples.objectmapping;
2 |
3 | import java.util.UUID;
4 |
5 | import com.datastax.oss.driver.api.mapper.annotations.CqlName;
6 | import com.datastax.oss.driver.api.mapper.annotations.Entity;
7 | import com.datastax.oss.driver.api.mapper.annotations.PartitionKey;
8 | import com.datastax.samples.ExampleSchema;
9 |
10 | /**
11 | * Specialization for VIDEO.
12 | *
13 | * @author DataStax Developer Advocates team.
14 | */
15 | @Entity
16 | @CqlName(ExampleSchema.COMMENT_BY_VIDEO_TABLENAME)
17 | public class CommentByVideo extends Comment {
18 |
19 | /** Serial. */
20 | private static final long serialVersionUID = -6738790629520080307L;
21 |
22 | public CommentByVideo() {
23 | }
24 |
25 | public CommentByVideo(Comment c) {
26 | this.commentid = c.getCommentid();
27 | this.userid = c.getUserid();
28 | this.videoid = c.getVideoid();
29 | this.comment = c.getComment();
30 | }
31 |
32 | /**
33 | * Getter for attribute 'videoid'.
34 | *
35 | * @return
36 | * current value of 'videoid'
37 | */
38 | @PartitionKey
39 | public UUID getVideoid() {
40 | return videoid;
41 | }
42 |
43 |
44 | }
45 |
--------------------------------------------------------------------------------
/example-4x/src/main/java/com/datastax/samples/objectmapping/CommentDao.java:
--------------------------------------------------------------------------------
1 | package com.datastax.samples.objectmapping;
2 |
3 | import java.util.UUID;
4 |
5 | import com.datastax.oss.driver.api.core.PagingIterable;
6 | import com.datastax.oss.driver.api.mapper.annotations.Dao;
7 | import com.datastax.oss.driver.api.mapper.annotations.Query;
8 | import com.datastax.oss.driver.api.mapper.annotations.QueryProvider;
9 | import com.datastax.samples.ExampleSchema;
10 |
11 | /**
12 | * Implementation of Services to work with Comments in Killrvideo. We work with
13 | * 2 tables 'comments_by_user' and 'comments_by_video'.
14 | */
15 | @Dao
16 | public interface CommentDao extends ExampleSchema {
17 |
18 | @Query("SELECT * FROM ${keyspaceId}.${tableId} "
19 | + "WHERE " + COMMENT_BY_USER_USERID + " = :userid ")
20 | PagingIterable retrieveUserComments(UUID userid);
21 |
22 | @Query("SELECT * FROM ${keyspaceId}.${tableId} "
23 | + "WHERE " + COMMENT_BY_VIDEO_VIDEOID + " = :videoid ")
24 | PagingIterable retrieveVideoComments(UUID videoid);
25 |
26 | @QueryProvider(
27 | providerClass = CommentDaoQueryProvider.class,
28 | entityHelpers = { CommentByUser.class, CommentByVideo.class})
29 | void upsert(Comment comment);
30 |
31 | @QueryProvider(
32 | providerClass = CommentDaoQueryProvider.class,
33 | entityHelpers = { CommentByUser.class, CommentByVideo.class})
34 | void delete(Comment res);
35 | }
36 |
--------------------------------------------------------------------------------
/example-4x/src/main/java/com/datastax/samples/objectmapping/CommentDaoMapper.java:
--------------------------------------------------------------------------------
1 | package com.datastax.samples.objectmapping;
2 |
3 | import com.datastax.oss.driver.api.core.CqlSession;
4 | import com.datastax.oss.driver.api.mapper.MapperBuilder;
5 | import com.datastax.oss.driver.api.mapper.annotations.DaoFactory;
6 | import com.datastax.oss.driver.api.mapper.annotations.Mapper;
7 |
8 | /**
9 | * Definition of operation for mapping.
10 | */
11 | @Mapper
12 | public interface CommentDaoMapper {
13 |
14 | @DaoFactory
15 | CommentDao commentDao();
16 |
17 | static MapperBuilder builder(CqlSession session) {
18 | return new CommentDaoMapperBuilder(session);
19 | }
20 | }
21 |
22 |
--------------------------------------------------------------------------------
/example-4x/src/main/java/com/datastax/samples/objectmapping/CommentDaoQueryProvider.java:
--------------------------------------------------------------------------------
1 | package com.datastax.samples.objectmapping;
2 |
3 | import java.util.UUID;
4 |
5 | import com.datastax.oss.driver.api.core.CqlSession;
6 | import com.datastax.oss.driver.api.core.PagingIterable;
7 | import com.datastax.oss.driver.api.core.cql.BatchStatement;
8 | import com.datastax.oss.driver.api.core.cql.BoundStatement;
9 | import com.datastax.oss.driver.api.core.cql.BoundStatementBuilder;
10 | import com.datastax.oss.driver.api.core.cql.DefaultBatchType;
11 | import com.datastax.oss.driver.api.core.cql.PreparedStatement;
12 | import com.datastax.oss.driver.api.mapper.MapperContext;
13 | import com.datastax.oss.driver.api.mapper.entity.EntityHelper;
14 | import com.datastax.oss.driver.api.mapper.entity.saving.NullSavingStrategy;
15 | import com.datastax.oss.driver.api.querybuilder.QueryBuilder;
16 | import com.datastax.samples.ExampleSchema;
17 |
18 | /**
19 | * Query implementation for Comment Dse and Mapper.
20 | *
21 | * @author DataStax Developer Advocates team.
22 | */
23 | @SuppressWarnings("deprecation")
24 | public class CommentDaoQueryProvider implements CommentDao, ExampleSchema {
25 |
26 | private final CqlSession cqlSession;
27 |
28 | private final EntityHelper helperUser;
29 | private final EntityHelper helperVideo;
30 |
31 | private static PreparedStatement selectCommentByVideo;
32 | private static PreparedStatement selectCommentByUser;
33 |
34 | private PreparedStatement psInsertCommentUser;
35 | private PreparedStatement psDeleteCommentUser;
36 | private PreparedStatement psInsertCommentVideo;
37 | private PreparedStatement psDeleteCommentVideo;
38 |
39 | public CommentDaoQueryProvider(MapperContext context,
40 | EntityHelper helperUser,
41 | EntityHelper helperVideo) {
42 |
43 | this.cqlSession = context.getSession();
44 | this.helperUser = helperUser;
45 | this.helperVideo = helperVideo;
46 | psInsertCommentUser = cqlSession.prepare(helperUser.insert().asCql());
47 | psDeleteCommentUser = cqlSession.prepare(helperUser.deleteByPrimaryKey().asCql());
48 | psInsertCommentVideo = cqlSession.prepare(helperVideo.insert().asCql());
49 | psDeleteCommentVideo = cqlSession.prepare(helperVideo.deleteByPrimaryKey().asCql());
50 |
51 | selectCommentByVideo = cqlSession.prepare(
52 | QueryBuilder.selectFrom(COMMENT_BY_VIDEO_TABLENAME).all()
53 | .whereColumn(COMMENT_BY_VIDEO_VIDEOID).isEqualTo(QueryBuilder.bindMarker())
54 | .build());
55 | selectCommentByUser = cqlSession.prepare(
56 | QueryBuilder.selectFrom(COMMENT_BY_USER_TABLENAME).all()
57 | .whereColumn(COMMENT_BY_USER_USERID).isEqualTo(QueryBuilder.bindMarker())
58 | .build());
59 | }
60 |
61 | /** {@inheritDoc} */
62 |
63 | @Override
64 | public PagingIterable retrieveUserComments(UUID userid) {
65 | return cqlSession.execute(selectCommentByUser.bind(userid)).map(helperUser::get);
66 | }
67 |
68 | /** {@inheritDoc} */
69 | @Override
70 | public PagingIterable retrieveVideoComments(UUID videoid) {
71 | return cqlSession.execute(selectCommentByVideo.bind(videoid)).map(helperVideo::get);
72 | }
73 |
74 | /** {@inheritDoc} */
75 | @Override
76 | public void upsert(Comment comment) {
77 | cqlSession.execute(BatchStatement.builder(DefaultBatchType.LOGGED)
78 | .addStatement(bind(psInsertCommentUser, new CommentByUser(comment), helperUser))
79 | .addStatement(bind(psInsertCommentVideo, new CommentByVideo(comment), helperVideo))
80 | .build());
81 | }
82 |
83 | /** {@inheritDoc} */
84 | @Override
85 | public void delete(Comment comment) {
86 |
87 | CommentByUser cbu = new CommentByUser();
88 | cbu.setCommentid(comment.getCommentid());
89 | cbu.setUserid(comment.getUserid());
90 |
91 | CommentByVideo cbv = new CommentByVideo();
92 | cbv.setCommentid(comment.getCommentid());
93 | cbv.setVideoid(comment.getVideoid());
94 |
95 | cqlSession.execute(
96 | BatchStatement.builder(DefaultBatchType.LOGGED)
97 | .addStatement(bind(psDeleteCommentUser, cbu, helperUser))
98 | .addStatement(bind(psDeleteCommentVideo, cbv, helperVideo))
99 | .build());
100 | }
101 |
102 | public static BoundStatement bind(PreparedStatement preparedStatement, T entity, EntityHelper entityHelper) {
103 | BoundStatementBuilder boundStatement = preparedStatement.boundStatementBuilder();
104 | entityHelper.set(entity, boundStatement, NullSavingStrategy.DO_NOT_SET);
105 | return boundStatement.build();
106 | }
107 |
108 | }
109 |
--------------------------------------------------------------------------------
/example-4x/src/main/resources/cassandra_logo.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/DataStax-Examples/java-cassandra-driver-from3x-to4x/d613cfcf69d8d24fd51cfb034c99fdc9315defd3/example-4x/src/main/resources/cassandra_logo.png
--------------------------------------------------------------------------------
/example-4x/src/main/resources/custom_application.conf:
--------------------------------------------------------------------------------
1 | datastax-java-driver {
2 |
3 | # Core settings
4 | basic {
5 | contact-points = [ "127.0.0.1:9042"]
6 | session-name = my_sample_session
7 | session-keyspace = killrvideo
8 | config-reload-interval = 5 minutes
9 | request {
10 | timeout = 3 seconds
11 | consistency = LOCAL_QUORUM
12 | page-size = 5000
13 | }
14 | load-balancing-policy {
15 | class = DefaultLoadBalancingPolicy
16 | local-datacenter = datacenter1
17 | }
18 | }
19 |
20 | # Dedicated Profiles
21 | profiles {
22 | oltp {
23 | basic.request.timeout = 100 milliseconds
24 | basic.request.consistency = ONE
25 | }
26 | olap {
27 | basic.request.timeout = 5 seconds
28 | basic.request.consistency = QUORUM
29 | }
30 | }
31 |
32 |
33 | }
--------------------------------------------------------------------------------
/example-4x/src/main/resources/custom_astra.conf:
--------------------------------------------------------------------------------
1 | datastax-java-driver {
2 | basic {
3 | session-keyspace = default_keyspace
4 | cloud {
5 | secure-connect-bundle = path_to_your_secure_connect_bundle.zip
6 | }
7 | }
8 | advanced {
9 | auth-provider {
10 | class = PlainTextAuthProvider
11 | username = token
12 | password = "AstraCS:.. your tokemn"
13 | }
14 | }
15 | }
--------------------------------------------------------------------------------
/example-4x/src/main/resources/logback.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | %d{HH:mm:ss.SSS} %magenta(%-5level) %cyan(%-45logger) : %msg%n
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
--------------------------------------------------------------------------------