├── .gitpod.Dockerfile
├── img
├── end.gif
├── badge.png
├── cl_read.png
├── splash.png
├── cl_write.png
├── sensor-01.png
├── sensor-02.png
├── sensor-03.png
├── sensor-04.png
├── petclinic_00.png
├── petclinic_01.png
├── petclinic_02.png
├── petclinic_03.png
├── petclinic_04.png
├── petclinic_05.png
├── petclinic_06.png
├── petclinic_07.png
├── petclinic_08.png
├── petclinic_09.png
├── petclinic_10.png
├── query-async.png
├── query-sync.png
├── certifications.png
├── cluster-astra.png
├── cluster-docker.png
├── query-connect.png
├── query-reactive.png
├── secure_bundle.png
├── spring_layers.png
├── astra-create-db.gif
├── micronaut_test_01.png
├── micronaut_test_02.png
├── micronaut_test_03.png
├── micronaut_test_04.png
├── quarkus-dashboard.png
├── quarkus-swagger.png
├── spring_api_gitpod.png
├── spring_api_local.png
├── astra-create-token.gif
├── modelisation-workflow.png
├── gitpod-terminal-astra-01.png
├── gitpod-terminal-astra-02.png
└── gitpod-terminal-astra-03.png
├── labs
├── slides.pdf
├── lab4_cassandra_drivers
│ ├── src
│ │ └── main
│ │ │ ├── resources
│ │ │ ├── cassandra_logo.png
│ │ │ ├── logback.xml
│ │ │ ├── custom_astra.conf
│ │ │ └── custom_application.conf
│ │ │ └── java
│ │ │ └── com
│ │ │ └── datastax
│ │ │ └── samples
│ │ │ ├── E00_TestConnectivity.java
│ │ │ ├── objectmapping
│ │ │ ├── CommentDaoMapper.java
│ │ │ ├── CommentByVideo.java
│ │ │ ├── CommentByUser.java
│ │ │ ├── CommentDao.java
│ │ │ ├── Comment.java
│ │ │ └── CommentDaoQueryProvider.java
│ │ │ ├── dto
│ │ │ ├── VideoFormatDto.java
│ │ │ ├── UserDto.java
│ │ │ ├── FileDto.java
│ │ │ └── VideoDto.java
│ │ │ ├── E01_CreateSchema.java
│ │ │ ├── codec
│ │ │ ├── BytesArrayTypeCodec.java
│ │ │ ├── UdtVideoFormatCodec.java
│ │ │ └── JsonJacksonTypeCodec.java
│ │ │ ├── CqlSessionProvider.java
│ │ │ ├── schema
│ │ │ └── SchemaConstants.java
│ │ │ ├── E05_Paging.java
│ │ │ ├── E11_LightweightTransactions.java
│ │ │ ├── E12_ObjectMapping.java
│ │ │ ├── E10_Counters.java
│ │ │ ├── E02_Statements.java
│ │ │ └── E09_Reactive.java
│ ├── init
│ └── pom.xml
├── lab5_spring_data
│ ├── src
│ │ ├── main
│ │ │ ├── resources
│ │ │ │ ├── application-local.yml
│ │ │ │ ├── META-INF
│ │ │ │ │ └── additional-spring-configuration-metadata.json
│ │ │ │ ├── application.yml
│ │ │ │ ├── application-astra.yml
│ │ │ │ ├── application.conf
│ │ │ │ ├── banner.txt
│ │ │ │ └── logback.xml
│ │ │ └── java
│ │ │ │ └── com
│ │ │ │ └── datastax
│ │ │ │ └── workshop
│ │ │ │ ├── hello
│ │ │ │ └── IndexController.java
│ │ │ │ ├── TodobackendSpringdataApplication.java
│ │ │ │ ├── todo
│ │ │ │ ├── TodoRepositoryCassandra.java
│ │ │ │ ├── TodoRepositorySimpleCassandra.java
│ │ │ │ ├── Todo.java
│ │ │ │ ├── TodoEntity.java
│ │ │ │ └── TodoRestController.java
│ │ │ │ └── conf
│ │ │ │ └── SpringDataConfig.java
│ │ └── test
│ │ │ └── java
│ │ │ └── com
│ │ │ └── datastax
│ │ │ └── workshop
│ │ │ ├── E01_SpringDataInit.java
│ │ │ ├── E02_SpringDataRepository.java
│ │ │ ├── E04_SpringControllerTest.java
│ │ │ └── E03_SpringDataCassandraOperations.java
│ ├── init
│ └── pom.xml
├── lab6_quarkus
│ ├── src
│ │ ├── main
│ │ │ ├── resources
│ │ │ │ ├── META-INF
│ │ │ │ │ └── resources
│ │ │ │ │ │ └── index.html
│ │ │ │ ├── application-local.properties
│ │ │ │ ├── application.properties
│ │ │ │ └── application-astra.properties
│ │ │ ├── java
│ │ │ │ └── com
│ │ │ │ │ └── datastaxdev
│ │ │ │ │ ├── utils
│ │ │ │ │ └── ValidationUtils.java
│ │ │ │ │ └── todo
│ │ │ │ │ ├── cassandra
│ │ │ │ │ ├── TodoItemMapper.java
│ │ │ │ │ ├── TodoItemDao.java
│ │ │ │ │ ├── TodoServicesCassandraOM.java
│ │ │ │ │ └── TodoItem.java
│ │ │ │ │ ├── TodoService.java
│ │ │ │ │ ├── TodoDto.java
│ │ │ │ │ ├── web
│ │ │ │ │ └── Todo.java
│ │ │ │ │ └── TodoRestController.java
│ │ │ └── docker
│ │ │ │ ├── Dockerfile.native
│ │ │ │ └── Dockerfile.jvm
│ │ └── test
│ │ │ └── java
│ │ │ └── com
│ │ │ └── datastax
│ │ │ └── workshop
│ │ │ ├── E04_QuarkusController.java
│ │ │ ├── E03_QuarkusObjectMapping.java
│ │ │ ├── E02_QuarkusCql.java
│ │ │ └── E01_QuarkusInit.java
│ ├── init
│ └── pom.xml
├── lab7_micronaut
│ ├── src
│ │ ├── main
│ │ │ ├── java
│ │ │ │ └── com
│ │ │ │ │ └── datastaxdev
│ │ │ │ │ ├── TodoApplication.java
│ │ │ │ │ ├── utils
│ │ │ │ │ └── ValidationUtils.java
│ │ │ │ │ ├── todo
│ │ │ │ │ ├── cassandra
│ │ │ │ │ │ ├── TodoItemMapper.java
│ │ │ │ │ │ ├── TodoItemDao.java
│ │ │ │ │ │ ├── TodoServicesCassandraOM.java
│ │ │ │ │ │ └── TodoItem.java
│ │ │ │ │ ├── web
│ │ │ │ │ │ └── Todo.java
│ │ │ │ │ └── TodoRestController.java
│ │ │ │ │ ├── TodoApplicationStartup.java
│ │ │ │ │ ├── TodoService.java
│ │ │ │ │ └── TodoDto.java
│ │ │ └── resources
│ │ │ │ ├── application.yml
│ │ │ │ ├── application-local.yml
│ │ │ │ ├── application-astra.yml
│ │ │ │ └── logback.xml
│ │ └── test
│ │ │ └── java
│ │ │ └── com
│ │ │ └── datastaxdev
│ │ │ ├── E03_MicronautObjectMapping.java
│ │ │ ├── E02_MicronautCql.java
│ │ │ ├── E04_MicronautController.java
│ │ │ └── E01_MicronautInit.java
│ ├── init
│ └── pom.xml
├── lab1_initialisation_environnements
│ ├── cassandra-cqlsh
│ ├── astra-cqlsh
│ ├── astra-cqlsh-install
│ └── cassandra-start
└── docker-compose.yml
├── .gitignore
├── .vscode
└── settings.json
└── .gitpod.yml
/.gitpod.Dockerfile:
--------------------------------------------------------------------------------
1 | FROM gitpod/workspace-full
2 |
--------------------------------------------------------------------------------
/img/end.gif:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/datastaxdevs/conference-2022-devoxx-france/main/img/end.gif
--------------------------------------------------------------------------------
/img/badge.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/datastaxdevs/conference-2022-devoxx-france/main/img/badge.png
--------------------------------------------------------------------------------
/img/cl_read.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/datastaxdevs/conference-2022-devoxx-france/main/img/cl_read.png
--------------------------------------------------------------------------------
/img/splash.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/datastaxdevs/conference-2022-devoxx-france/main/img/splash.png
--------------------------------------------------------------------------------
/labs/slides.pdf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/datastaxdevs/conference-2022-devoxx-france/main/labs/slides.pdf
--------------------------------------------------------------------------------
/img/cl_write.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/datastaxdevs/conference-2022-devoxx-france/main/img/cl_write.png
--------------------------------------------------------------------------------
/img/sensor-01.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/datastaxdevs/conference-2022-devoxx-france/main/img/sensor-01.png
--------------------------------------------------------------------------------
/img/sensor-02.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/datastaxdevs/conference-2022-devoxx-france/main/img/sensor-02.png
--------------------------------------------------------------------------------
/img/sensor-03.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/datastaxdevs/conference-2022-devoxx-france/main/img/sensor-03.png
--------------------------------------------------------------------------------
/img/sensor-04.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/datastaxdevs/conference-2022-devoxx-france/main/img/sensor-04.png
--------------------------------------------------------------------------------
/img/petclinic_00.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/datastaxdevs/conference-2022-devoxx-france/main/img/petclinic_00.png
--------------------------------------------------------------------------------
/img/petclinic_01.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/datastaxdevs/conference-2022-devoxx-france/main/img/petclinic_01.png
--------------------------------------------------------------------------------
/img/petclinic_02.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/datastaxdevs/conference-2022-devoxx-france/main/img/petclinic_02.png
--------------------------------------------------------------------------------
/img/petclinic_03.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/datastaxdevs/conference-2022-devoxx-france/main/img/petclinic_03.png
--------------------------------------------------------------------------------
/img/petclinic_04.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/datastaxdevs/conference-2022-devoxx-france/main/img/petclinic_04.png
--------------------------------------------------------------------------------
/img/petclinic_05.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/datastaxdevs/conference-2022-devoxx-france/main/img/petclinic_05.png
--------------------------------------------------------------------------------
/img/petclinic_06.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/datastaxdevs/conference-2022-devoxx-france/main/img/petclinic_06.png
--------------------------------------------------------------------------------
/img/petclinic_07.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/datastaxdevs/conference-2022-devoxx-france/main/img/petclinic_07.png
--------------------------------------------------------------------------------
/img/petclinic_08.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/datastaxdevs/conference-2022-devoxx-france/main/img/petclinic_08.png
--------------------------------------------------------------------------------
/img/petclinic_09.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/datastaxdevs/conference-2022-devoxx-france/main/img/petclinic_09.png
--------------------------------------------------------------------------------
/img/petclinic_10.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/datastaxdevs/conference-2022-devoxx-france/main/img/petclinic_10.png
--------------------------------------------------------------------------------
/img/query-async.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/datastaxdevs/conference-2022-devoxx-france/main/img/query-async.png
--------------------------------------------------------------------------------
/img/query-sync.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/datastaxdevs/conference-2022-devoxx-france/main/img/query-sync.png
--------------------------------------------------------------------------------
/img/certifications.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/datastaxdevs/conference-2022-devoxx-france/main/img/certifications.png
--------------------------------------------------------------------------------
/img/cluster-astra.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/datastaxdevs/conference-2022-devoxx-france/main/img/cluster-astra.png
--------------------------------------------------------------------------------
/img/cluster-docker.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/datastaxdevs/conference-2022-devoxx-france/main/img/cluster-docker.png
--------------------------------------------------------------------------------
/img/query-connect.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/datastaxdevs/conference-2022-devoxx-france/main/img/query-connect.png
--------------------------------------------------------------------------------
/img/query-reactive.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/datastaxdevs/conference-2022-devoxx-france/main/img/query-reactive.png
--------------------------------------------------------------------------------
/img/secure_bundle.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/datastaxdevs/conference-2022-devoxx-france/main/img/secure_bundle.png
--------------------------------------------------------------------------------
/img/spring_layers.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/datastaxdevs/conference-2022-devoxx-france/main/img/spring_layers.png
--------------------------------------------------------------------------------
/img/astra-create-db.gif:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/datastaxdevs/conference-2022-devoxx-france/main/img/astra-create-db.gif
--------------------------------------------------------------------------------
/img/micronaut_test_01.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/datastaxdevs/conference-2022-devoxx-france/main/img/micronaut_test_01.png
--------------------------------------------------------------------------------
/img/micronaut_test_02.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/datastaxdevs/conference-2022-devoxx-france/main/img/micronaut_test_02.png
--------------------------------------------------------------------------------
/img/micronaut_test_03.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/datastaxdevs/conference-2022-devoxx-france/main/img/micronaut_test_03.png
--------------------------------------------------------------------------------
/img/micronaut_test_04.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/datastaxdevs/conference-2022-devoxx-france/main/img/micronaut_test_04.png
--------------------------------------------------------------------------------
/img/quarkus-dashboard.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/datastaxdevs/conference-2022-devoxx-france/main/img/quarkus-dashboard.png
--------------------------------------------------------------------------------
/img/quarkus-swagger.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/datastaxdevs/conference-2022-devoxx-france/main/img/quarkus-swagger.png
--------------------------------------------------------------------------------
/img/spring_api_gitpod.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/datastaxdevs/conference-2022-devoxx-france/main/img/spring_api_gitpod.png
--------------------------------------------------------------------------------
/img/spring_api_local.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/datastaxdevs/conference-2022-devoxx-france/main/img/spring_api_local.png
--------------------------------------------------------------------------------
/img/astra-create-token.gif:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/datastaxdevs/conference-2022-devoxx-france/main/img/astra-create-token.gif
--------------------------------------------------------------------------------
/img/modelisation-workflow.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/datastaxdevs/conference-2022-devoxx-france/main/img/modelisation-workflow.png
--------------------------------------------------------------------------------
/img/gitpod-terminal-astra-01.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/datastaxdevs/conference-2022-devoxx-france/main/img/gitpod-terminal-astra-01.png
--------------------------------------------------------------------------------
/img/gitpod-terminal-astra-02.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/datastaxdevs/conference-2022-devoxx-france/main/img/gitpod-terminal-astra-02.png
--------------------------------------------------------------------------------
/img/gitpod-terminal-astra-03.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/datastaxdevs/conference-2022-devoxx-france/main/img/gitpod-terminal-astra-03.png
--------------------------------------------------------------------------------
/labs/lab4_cassandra_drivers/src/main/resources/cassandra_logo.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/datastaxdevs/conference-2022-devoxx-france/main/labs/lab4_cassandra_drivers/src/main/resources/cassandra_logo.png
--------------------------------------------------------------------------------
/labs/lab5_spring_data/src/main/resources/application-local.yml:
--------------------------------------------------------------------------------
1 | spring:
2 | data:
3 | cassandra:
4 | schema-action: CREATE_IF_NOT_EXISTS
5 | keyspace-name: devoxx_spring
6 | contact-points: localhost:9042
7 | local-datacenter: dc1
8 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | # eclipse conf file
2 | .settings
3 | .classpath
4 | .project
5 | .cache
6 |
7 | # idea conf files
8 | .idea
9 | *.ipr
10 | *.iws
11 | *.iml
12 |
13 | # building
14 | target
15 | build
16 | tmp
17 | dist
18 |
19 | # misc
20 | .DS_Store
21 |
22 | .factorypath
23 |
--------------------------------------------------------------------------------
/labs/lab6_quarkus/src/main/resources/META-INF/resources/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 | Please follow this link.
8 |
9 |
10 |
--------------------------------------------------------------------------------
/.vscode/settings.json:
--------------------------------------------------------------------------------
1 | {
2 | "workbench.editor.enablePreviewFromCodeNavigation": true,
3 | "workbench.editor.enablePreviewFromQuickOpen": true,
4 | "workbench.editor.enablePreview": true,
5 | "workbench.editorAssociations": {
6 | "*.md": "vscode.markdown.preview.editor"
7 | }
8 | }
9 |
10 |
--------------------------------------------------------------------------------
/labs/lab7_micronaut/src/main/java/com/datastaxdev/TodoApplication.java:
--------------------------------------------------------------------------------
1 | package com.datastaxdev;
2 |
3 | import io.micronaut.runtime.Micronaut;
4 |
5 | public class TodoApplication {
6 |
7 | public static void main(String[] args) {
8 | Micronaut.run(TodoApplication.class, args);
9 | }
10 | }
11 |
--------------------------------------------------------------------------------
/labs/lab5_spring_data/src/main/resources/META-INF/additional-spring-configuration-metadata.json:
--------------------------------------------------------------------------------
1 | {
2 | "properties": [
3 | {
4 | "name": "datastax.astra.secure-connect-bundle",
5 | "type": "java.lang.String",
6 | "description": "An absolute path to the Astra secure connect bundle to use."
7 | }
8 | ]
9 | }
--------------------------------------------------------------------------------
/labs/lab5_spring_data/src/main/resources/application.yml:
--------------------------------------------------------------------------------
1 | spring:
2 | data:
3 | cassandra:
4 | schema-action: CREATE_IF_NOT_EXISTS
5 | keyspace-name: devoxx_spring
6 | username: token
7 | password:
8 | datastax:
9 | astra:
10 | secure-connect-bundle: /home/gitpod/.cassandra/bootstrap.zip
11 |
12 |
13 |
--------------------------------------------------------------------------------
/labs/lab5_spring_data/src/main/resources/application-astra.yml:
--------------------------------------------------------------------------------
1 | spring:
2 | data:
3 | cassandra:
4 | schema-action: CREATE_IF_NOT_EXISTS
5 | keyspace-name: devoxx_spring
6 | username: token
7 | password:
8 | datastax:
9 | astra:
10 | secure-connect-bundle: /home/gitpod/.cassandra/bootstrap.zip
11 |
12 |
13 |
--------------------------------------------------------------------------------
/labs/lab7_micronaut/src/main/resources/application.yml:
--------------------------------------------------------------------------------
1 | micronaut:
2 | application:
3 | name: lab7-micronaut
4 | server:
5 | port: 8082
6 | cors:
7 | enabled: true
8 |
9 | cassandra:
10 | default:
11 | basic:
12 | session-keyspace: devoxx_micronaut
13 | contact-points:
14 | - "localhost:9042"
15 | load-balancing-policy:
16 | local-datacenter: dc1
17 |
--------------------------------------------------------------------------------
/labs/lab7_micronaut/src/main/resources/application-local.yml:
--------------------------------------------------------------------------------
1 | micronaut:
2 | application:
3 | name: lab7-micronaut
4 | server:
5 | port: 8082
6 | cors:
7 | enabled: true
8 |
9 | cassandra:
10 | default:
11 | basic:
12 | session-keyspace: devoxx_micronaut
13 | contact-points:
14 | - "localhost:9042"
15 | load-balancing-policy:
16 | local-datacenter: dc1
17 |
--------------------------------------------------------------------------------
/labs/lab5_spring_data/src/main/resources/application.conf:
--------------------------------------------------------------------------------
1 | datastax-java-driver {
2 | basic {
3 | request {
4 | timeout = 8 seconds
5 | consistency = LOCAL_QUORUM
6 | page-size = 5000
7 | }
8 | }
9 | advanced {
10 | connection {
11 | init-query-timeout = 10 seconds
12 | set-keyspace-timeout = 10 seconds
13 | }
14 | control-connection.timeout = 10 seconds
15 | }
16 | }
--------------------------------------------------------------------------------
/labs/lab5_spring_data/src/main/java/com/datastax/workshop/hello/IndexController.java:
--------------------------------------------------------------------------------
1 | package com.datastax.workshop.hello;
2 |
3 | import org.springframework.web.bind.annotation.RequestMapping;
4 | import org.springframework.web.bind.annotation.RestController;
5 |
6 | @RestController
7 | public class IndexController {
8 |
9 | @RequestMapping("/")
10 | public String hello() {
11 | return "Todo endpoint is /api/v1/todos/";
12 | }
13 |
14 | }
--------------------------------------------------------------------------------
/labs/lab5_spring_data/src/main/java/com/datastax/workshop/TodobackendSpringdataApplication.java:
--------------------------------------------------------------------------------
1 | package com.datastax.workshop;
2 |
3 | import org.springframework.boot.SpringApplication;
4 | import org.springframework.boot.autoconfigure.SpringBootApplication;
5 |
6 | @SpringBootApplication
7 | public class TodobackendSpringdataApplication {
8 |
9 | public static void main(String[] args) {
10 | SpringApplication.run(TodobackendSpringdataApplication.class, args);
11 | }
12 |
13 | }
14 |
--------------------------------------------------------------------------------
/labs/lab1_initialisation_environnements/cassandra-cqlsh:
--------------------------------------------------------------------------------
1 | #!/bin/bash
2 |
3 | GREEN='\033[0;32m'
4 | BLUE='\033[0;34m'
5 | NC='\033[0m'
6 |
7 | echo -e ""
8 | echo -e "${BLUE}------------------------------------------------------------${NC}"
9 | echo -e "${BLUE}-- CqlSH (LOCAL DOCKER) ---${NC}"
10 | echo -e "${BLUE}------------------------------------------------------------${NC}"
11 | echo -e ""
12 | docker exec -it `docker ps | grep dc1_seed | cut -b 1-12` cqlsh
--------------------------------------------------------------------------------
/labs/lab5_spring_data/src/main/java/com/datastax/workshop/todo/TodoRepositoryCassandra.java:
--------------------------------------------------------------------------------
1 | package com.datastax.workshop.todo;
2 |
3 | import java.util.UUID;
4 |
5 | import org.springframework.data.cassandra.repository.CassandraRepository;
6 | import org.springframework.stereotype.Repository;
7 |
8 | /**
9 | * For Basic operations you can leverage on Interface only repository
10 | */
11 | @Repository
12 | public interface TodoRepositoryCassandra extends CassandraRepository {
13 |
14 | }
15 |
--------------------------------------------------------------------------------
/labs/lab5_spring_data/init:
--------------------------------------------------------------------------------
1 | #!/bin/bash
2 |
3 | GREEN='\033[0;32m'
4 | BLUE='\033[0;34m'
5 | NC='\033[0m'
6 |
7 | cd /workspace/conference-2022-devoxx/labs/lab5_spring_data
8 | mvn clean compile
9 | clear
10 | echo -e "${BLUE}------------------------------------------------------------${NC}"
11 | echo -e "${BLUE}- SPRING DATA [OK] -${NC}"
12 | echo -e "${BLUE}------------------------------------------------------------${NC}"
13 | cd /workspace/conference-2022-devoxx/labs/lab5_spring_data
--------------------------------------------------------------------------------
/labs/lab6_quarkus/init:
--------------------------------------------------------------------------------
1 | #!/bin/bash
2 |
3 | GREEN='\033[0;32m'
4 | BLUE='\033[0;34m'
5 | NC='\033[0m'
6 |
7 | cd /workspace/conference-2022-devoxx/labs/lab6_quarkus
8 | mvn clean compile
9 | clear
10 | echo -e "${BLUE}------------------------------------------------------------${NC}"
11 | echo -e "${BLUE}- QUARKUS [OK] -${NC}"
12 | echo -e "${BLUE}------------------------------------------------------------${NC}"
13 |
14 |
15 | cd /workspace/conference-2022-devoxx/labs/lab6_quarkus
--------------------------------------------------------------------------------
/labs/lab7_micronaut/init:
--------------------------------------------------------------------------------
1 | #!/bin/bash
2 |
3 | GREEN='\033[0;32m'
4 | BLUE='\033[0;34m'
5 | NC='\033[0m'
6 |
7 | cd /workspace/conference-2022-devoxx/labs/lab7_micronaut
8 | mvn clean compile
9 | clear
10 | echo -e "${BLUE}------------------------------------------------------------${NC}"
11 | echo -e "${BLUE}- MICRONAUT [OK] -${NC}"
12 | echo -e "${BLUE}------------------------------------------------------------${NC}"
13 |
14 | cd /workspace/conference-2022-devoxx/labs/lab7_micronaut
--------------------------------------------------------------------------------
/labs/lab6_quarkus/src/test/java/com/datastax/workshop/E04_QuarkusController.java:
--------------------------------------------------------------------------------
1 | package com.datastax.workshop;
2 |
3 | import static io.restassured.RestAssured.given;
4 |
5 | import org.junit.jupiter.api.Test;
6 |
7 | import io.quarkus.test.junit.QuarkusTest;
8 |
9 | @QuarkusTest
10 | public class E04_QuarkusController {
11 |
12 | @Test
13 | public void testApi() {
14 | given().when().get("/api/v1/clun/todos/")
15 | .then()
16 | .statusCode(200);
17 | }
18 |
19 | }
20 |
--------------------------------------------------------------------------------
/labs/lab4_cassandra_drivers/init:
--------------------------------------------------------------------------------
1 | #!/bin/bash
2 |
3 | GREEN='\033[0;32m'
4 | BLUE='\033[0;34m'
5 | NC='\033[0m'
6 |
7 | cd /workspace/conference-2022-devoxx/labs/lab4_cassandra_drivers
8 | mvn clean compile
9 | clear
10 | echo -e "${BLUE}------------------------------------------------------------${NC}"
11 | echo -e "${BLUE}- DRIVERS [OK] -${NC}"
12 | echo -e "${BLUE}------------------------------------------------------------${NC}"
13 |
14 | cd /workspace/conference-2022-devoxx/labs/lab4_cassandra_drivers
15 |
16 |
--------------------------------------------------------------------------------
/labs/lab4_cassandra_drivers/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 |
14 |
--------------------------------------------------------------------------------
/labs/lab6_quarkus/src/main/java/com/datastaxdev/utils/ValidationUtils.java:
--------------------------------------------------------------------------------
1 | package com.datastaxdev.utils;
2 |
3 | public class ValidationUtils {
4 |
5 | public static void assertNotEmpty(String str) {
6 | if (str == null || "".equals(str)) {
7 | throw new IllegalArgumentException("This string parameter cannot be null nor empty");
8 | }
9 | }
10 |
11 | public static void assertNotNull(Object str) {
12 | if (str == null) {
13 | throw new IllegalArgumentException("This parameter cannot be null ");
14 | }
15 | }
16 |
17 | }
18 |
--------------------------------------------------------------------------------
/labs/lab7_micronaut/src/main/java/com/datastaxdev/utils/ValidationUtils.java:
--------------------------------------------------------------------------------
1 | package com.datastaxdev.utils;
2 |
3 | public class ValidationUtils {
4 |
5 | public static void assertNotEmpty(String str) {
6 | if (str == null || "".equals(str)) {
7 | throw new IllegalArgumentException("This string parameter cannot be null nor empty");
8 | }
9 | }
10 |
11 | public static void assertNotNull(Object str) {
12 | if (str == null) {
13 | throw new IllegalArgumentException("This parameter cannot be null ");
14 | }
15 | }
16 |
17 | }
18 |
--------------------------------------------------------------------------------
/labs/lab4_cassandra_drivers/src/main/java/com/datastax/samples/E00_TestConnectivity.java:
--------------------------------------------------------------------------------
1 | package com.datastax.samples;
2 |
3 | import org.slf4j.Logger;
4 | import org.slf4j.LoggerFactory;
5 |
6 | import com.datastax.oss.driver.api.core.CqlSession;
7 |
8 | public class E00_TestConnectivity {
9 |
10 | private static Logger LOGGER = LoggerFactory.getLogger(E00_TestConnectivity.class);
11 |
12 | public static void main(String[] args) {
13 | try(CqlSession cqlSession = CqlSessionProvider.getInstance().getSession()) {
14 | LOGGER.info("[SUCCESS]");
15 | }
16 | }
17 |
18 |
19 | }
20 |
--------------------------------------------------------------------------------
/labs/lab4_cassandra_drivers/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 |
--------------------------------------------------------------------------------
/labs/lab5_spring_data/src/main/resources/banner.txt:
--------------------------------------------------------------------------------
1 | ${AnsiColor.BLUE} ________ _______________ ________ ________
2 | ${AnsiColor.BLUE} \______ \ _______ _________ ______ __\_____ \ _ \ \_____ \\_____ \
3 | ${AnsiColor.BLUE} | | \_/ __ \ \/ / _ \ \/ /\ \/ // ____/ /_\ \ / ____/ / ____/
4 | ${AnsiColor.BLUE} | ` \ ___/\ ( <_> > < > \ \_/ \/ \/ \
5 | ${AnsiColor.BLUE} /_______ /\___ >\_/ \____/__/\_ \/__/\_ \_______ \_____ /\_______ \_______ \
6 | ${AnsiColor.BLUE} \/ \/ \/ \/ \/ \/ \/ \/
7 |
8 | ${AnsiColor.GREEN} The application will start at ${AnsiColor.RED}http://localhost:8080${AnsiColor.BLACK}
9 |
--------------------------------------------------------------------------------
/labs/lab7_micronaut/src/main/resources/application-astra.yml:
--------------------------------------------------------------------------------
1 | micronaut:
2 | application:
3 | name: lab7-micronaut
4 | server:
5 | port: 8082
6 | cors:
7 | enabled: true
8 | cassandra:
9 | default:
10 | basic:
11 | request:
12 | timeout: 5 seconds
13 | session-keyspace: devoxx_micronaut
14 | cloud:
15 | secure-connect-bundle: /home/gitpod/.cassandra/bootstrap.zip
16 | advanced:
17 | auth-provider:
18 | class: PlainTextAuthProvider
19 | username: token
20 | password:
21 | connection:
22 | init-query-timeout: 5 seconds
23 | set-keyspace-timeout: 5 seconds
24 | control-connection.timeout: 5 seconds
25 |
26 |
27 |
28 |
--------------------------------------------------------------------------------
/labs/lab5_spring_data/src/main/resources/logback.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | %d{HH:mm:ss.SSS} %magenta(%-5level) %cyan(%-45logger) : %msg%n
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
--------------------------------------------------------------------------------
/labs/lab6_quarkus/src/main/docker/Dockerfile.native:
--------------------------------------------------------------------------------
1 | ####
2 | # This Dockerfile is used in order to build a container that runs the Quarkus application in native (no JVM) mode
3 | #
4 | # Before building the docker image run:
5 | #
6 | # mvn package -Pnative -Dquarkus.native.container-build=true
7 | #
8 | # Then, build the image with:
9 | #
10 | # docker build -f src/main/docker/Dockerfile.native -t quarkus/my-artifactId .
11 | #
12 | # Then run the container using:
13 | #
14 | # docker run -i --rm -p 8080:8080 quarkus/my-artifactId
15 | #
16 | ###
17 | FROM registry.access.redhat.com/ubi8/ubi-minimal:8.1
18 | WORKDIR /work/
19 | COPY --chown=1001:root target/*-runner /work/application
20 |
21 | EXPOSE 8080
22 | USER 1001
23 |
24 | CMD ["./application", "-Dquarkus.http.host=0.0.0.0"]
--------------------------------------------------------------------------------
/labs/lab6_quarkus/src/main/java/com/datastaxdev/todo/cassandra/TodoItemMapper.java:
--------------------------------------------------------------------------------
1 | package com.datastaxdev.todo.cassandra;
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 | @Mapper
9 | public interface TodoItemMapper {
10 |
11 | @DaoFactory
12 | TodoItemDao todoItemDao();
13 |
14 | /**
15 | * Utility to initialize.
16 | *
17 | * @param session
18 | * target session
19 | * @return
20 | * target builder
21 | */
22 | static MapperBuilder builder(CqlSession session) {
23 | return new TodoItemMapperBuilder(session);
24 | }
25 |
26 | }
--------------------------------------------------------------------------------
/labs/lab7_micronaut/src/main/java/com/datastaxdev/todo/cassandra/TodoItemMapper.java:
--------------------------------------------------------------------------------
1 | package com.datastaxdev.todo.cassandra;
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 | @Mapper
9 | public interface TodoItemMapper {
10 |
11 | @DaoFactory
12 | TodoItemDao todoItemDao();
13 |
14 | /**
15 | * Utility to initialize.
16 | *
17 | * @param session
18 | * target session
19 | * @return
20 | * target builder
21 | */
22 | static MapperBuilder builder(CqlSession session) {
23 | return new TodoItemMapperBuilder(session);
24 | }
25 |
26 | }
--------------------------------------------------------------------------------
/labs/lab4_cassandra_drivers/src/main/resources/custom_astra.conf:
--------------------------------------------------------------------------------
1 | datastax-java-driver {
2 |
3 | basic {
4 | session-keyspace = javazone
5 | request {
6 | timeout = 8 seconds
7 | consistency = LOCAL_QUORUM
8 | page-size = 5000
9 | }
10 | cloud {
11 | secure-connect-bundle = /Users/cedricklunven/Downloads/secure-connect-javazone.zip
12 | }
13 | }
14 |
15 | advanced {
16 | connection {
17 | init-query-timeout = 10 seconds
18 | set-keyspace-timeout = 10 seconds
19 | }
20 | control-connection.timeout = 10 seconds
21 | auth-provider {
22 | class = PlainTextAuthProvider
23 | username = "change_me"
24 | password = "change_me+KTipmev1nPiYQuXbpMpW1wuN.ywz1.UtKRnnJQzgLRZu4cExSGc2xHIQHREzpeB,pugXl,vlSXStTpNxjhPBnl0yZjXJRyFIg2ZJ-K8SZZWHIcdH0SzS"
25 | }
26 | }
27 | }
--------------------------------------------------------------------------------
/labs/lab4_cassandra_drivers/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 |
10 | request {
11 | timeout = 3 seconds
12 | consistency = LOCAL_QUORUM
13 | page-size = 5000
14 | }
15 | load-balancing-policy {
16 | class = DefaultLoadBalancingPolicy
17 | local-datacenter = dc1
18 | }
19 | }
20 |
21 | # Dedicated Profiles
22 | profiles {
23 | oltp {
24 | basic.request.timeout = 100 milliseconds
25 | basic.request.consistency = ONE
26 | }
27 | olap {
28 | basic.request.timeout = 5 seconds
29 | basic.request.consistency = QUORUM
30 | }
31 | }
32 |
33 |
34 | }
--------------------------------------------------------------------------------
/labs/lab1_initialisation_environnements/astra-cqlsh:
--------------------------------------------------------------------------------
1 | #!/bin/bash
2 | GREEN='\033[0;32m'
3 | BLUE='\033[0;34m'
4 | NC='\033[0m'
5 |
6 | echo -e "${BLUE}------------------------------------------------------------${NC}"
7 | echo -e "${BLUE}-- Astra CQLSH [Launch] ---${NC}"
8 | echo -e "${BLUE}------------------------------------------------------------${NC}"
9 | set -a
10 | source /workspace/conference-2022-devoxx/.env
11 | set +a
12 | echo -e "${GREEN}[OK]${NC} - Database ID is ${BLUE}${ASTRA_DB_ID}${NC}"
13 | echo -e "${GREEN}[OK]${NC} - Database REGION is ${BLUE}${ASTRA_DB_REGION}${NC}"
14 | echo -e "${GREEN}[OK]${NC} - Database TOKEN is ${BLUE}${ASTRA_DB_ADMIN_TOKEN}${NC}"
15 | echo -e "${GREEN}[OK]${NC} - Secure Connect Bundle downloaded"
16 | echo -e "${GREEN}[OK]${NC} - Launching Astra CQLSH...."
17 | /workspace/conference-2022-devoxx/tools/cqlsh-astra/bin/cqlsh -u token -p ${ASTRA_DB_ADMIN_TOKEN} -b /home/gitpod/.cassandra/bootstrap.zip
18 |
--------------------------------------------------------------------------------
/labs/lab5_spring_data/src/test/java/com/datastax/workshop/E01_SpringDataInit.java:
--------------------------------------------------------------------------------
1 | package com.datastax.workshop;
2 |
3 | import org.junit.jupiter.api.Assertions;
4 | import org.junit.jupiter.api.Test;
5 | import org.slf4j.Logger;
6 | import org.slf4j.LoggerFactory;
7 | import org.springframework.beans.factory.annotation.Autowired;
8 | import org.springframework.boot.test.context.SpringBootTest;
9 |
10 | import com.datastax.oss.driver.api.core.CqlSession;
11 |
12 | @SpringBootTest
13 | public class E01_SpringDataInit {
14 |
15 | /** Logger for the class. */
16 | static Logger LOGGER = LoggerFactory.getLogger(E01_SpringDataInit.class);
17 |
18 | @Autowired
19 | CqlSession cqlSession;
20 |
21 | @Test
22 | public void testCqlSession() {
23 | LOGGER.info("Creating your CqlSession to Cassandra...");
24 | Assertions.assertTrue(cqlSession.getKeyspace().isPresent());
25 | LOGGER.info("+ [OK] Your are connected to keyspace {}", cqlSession.getKeyspace().get());
26 | }
27 | }
28 |
--------------------------------------------------------------------------------
/labs/lab4_cassandra_drivers/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 |
--------------------------------------------------------------------------------
/labs/lab7_micronaut/src/main/resources/logback.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | true
5 |
7 |
8 | %cyan(%d{HH:mm:ss.SSS}) %gray([%thread]) %highlight(%-5level) %magenta(%logger{36}) - %msg%n
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
--------------------------------------------------------------------------------
/labs/lab5_spring_data/src/main/java/com/datastax/workshop/conf/SpringDataConfig.java:
--------------------------------------------------------------------------------
1 | package com.datastax.workshop.conf;
2 |
3 | import java.io.File;
4 |
5 | import org.springframework.beans.factory.annotation.Value;
6 | import org.springframework.boot.autoconfigure.cassandra.CqlSessionBuilderCustomizer;
7 | import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
8 | import org.springframework.context.annotation.Bean;
9 | import org.springframework.context.annotation.Configuration;
10 |
11 | @Configuration
12 | public class SpringDataConfig {
13 |
14 | @Value("${datastax.astra.secure-connect-bundle:#{null}}")
15 | private File cloudSecureBundle;
16 |
17 | @Bean
18 | @ConditionalOnProperty(
19 | prefix = "datastax.astra",
20 | value = "secure-connect-bundle",
21 | matchIfMissing = false)
22 | public CqlSessionBuilderCustomizer sessionBuilderCustomizer() {
23 | return builder -> builder.withCloudSecureConnectBundle(cloudSecureBundle.toPath());
24 | }
25 |
26 | }
27 |
--------------------------------------------------------------------------------
/labs/lab1_initialisation_environnements/astra-cqlsh-install:
--------------------------------------------------------------------------------
1 | #!/bin/bash
2 |
3 | GREEN='\033[0;32m'
4 | BLUE='\033[0;34m'
5 | NC='\033[0m'
6 |
7 | clear
8 | echo -e "${BLUE}------------------------------------------------------------${NC}"
9 | echo -e "${BLUE}-- Astra CQLSH [Installation] ---${NC}"
10 | echo -e "${BLUE}------------------------------------------------------------${NC}"
11 | mkdir /workspace/conference-2022-devoxx/tools 2>/dev/null
12 | echo -e "${GREEN}[OK]${NC} - Folder 'tool' has been created"
13 | cd /workspace/conference-2022-devoxx/tools
14 | echo -e "${GREEN}[OK]${NC} - Downloading Package....."
15 | wget -q https://downloads.datastax.com/enterprise/cqlsh-astra.tar.gz >> install-cqlsh.log
16 | tar xvzf cqlsh-astra.tar.gz >> install-cqlsh.log
17 | rm -f cqlsh-astra.tar.gz >> install-cqlsh.log
18 | echo -e "${GREEN}[OK]${NC} - Package has been downloaded"
19 | cd /workspace/conference-2022-devoxx
20 | echo -e "${GREEN}[OK]${NC} - Installing Astra Setup...."
21 | npm install --silent astra-setup 2>/dev/null
22 | echo -e "${GREEN}[OK]${NC} - Astra Setup is ready"
23 |
24 |
25 |
26 |
--------------------------------------------------------------------------------
/labs/lab1_initialisation_environnements/cassandra-start:
--------------------------------------------------------------------------------
1 | #!/bin/bash
2 | GREEN='\033[0;32m'
3 | BLUE='\033[0;34m'
4 | NC='\033[0m'
5 |
6 | clear
7 | echo -e "${BLUE}------------------------------------------------------------${NC}"
8 | echo -e "${BLUE}--- Bienvenue à Devoxx France 2022 ---${NC}"
9 | echo -e "${BLUE}-- Local Cassandra (Docker) ---${NC}"
10 | echo -e "${BLUE}------------------------------------------------------------${NC}"
11 | echo -e ""
12 | cd /workspace/conference-2022-devoxx/labs/
13 |
14 | #echo -e "${GREEN}[OK]${NC} - Demarrage avec docker-compose...."
15 | #cd /workspace/conference-2022-devoxx/labs/
16 | #docker-compose up -d
17 | #sleep 1
18 | #export NOEUD1_CONTAINER_ID=`docker ps | grep dc1_seed | cut -b 1-12`
19 | #echo -e "${GREEN}[OK]${NC} - Container id=$NOEUD1_CONTAINER_ID"
20 | #echo -e "${GREEN}[OK]${NC} - Cassandra démarre...."
21 | #while [ `docker container logs $NOEUD1_CONTAINER_ID | grep "Starting listening for CQL clients" | wc -l` -lt 1 ]; do
22 | # sleep 5
23 | # printf "\033[0;32m■\033[0m"
24 | #done
25 | #echo -e "${GREEN}[OK]${NC} - Premier noeud OK."
--------------------------------------------------------------------------------
/labs/lab7_micronaut/src/test/java/com/datastaxdev/E03_MicronautObjectMapping.java:
--------------------------------------------------------------------------------
1 | package com.datastaxdev;
2 |
3 | import org.junit.jupiter.api.Test;
4 | import org.slf4j.Logger;
5 | import org.slf4j.LoggerFactory;
6 |
7 | import com.datastax.oss.driver.api.core.CqlSession;
8 | import com.datastaxdev.todo.cassandra.TodoServicesCassandraOM;
9 |
10 | import io.micronaut.test.extensions.junit5.annotation.MicronautTest;
11 | import jakarta.inject.Inject;
12 |
13 | @MicronautTest
14 | public class E03_MicronautObjectMapping {
15 |
16 | /** Logger for the class. */
17 | static Logger LOGGER = LoggerFactory.getLogger(E03_MicronautObjectMapping.class);
18 |
19 | @Inject
20 | CqlSession quarkusCqlSession;
21 |
22 | @Inject
23 | TodoServicesCassandraOM todoService;
24 |
25 | @Test
26 | public void testExecuteCql() {
27 | LOGGER.info("Inserting Data");
28 | TodoDto dto = new TodoDto();
29 | dto.setUserId("clun");
30 | dto.setCompleted(false);
31 | dto.setTitle("Apprendre Mapping Objet Micronaut");
32 | todoService.save(dto);
33 | LOGGER.info("+ [OK]");
34 | }
35 |
36 | }
37 |
--------------------------------------------------------------------------------
/labs/lab6_quarkus/src/test/java/com/datastax/workshop/E03_QuarkusObjectMapping.java:
--------------------------------------------------------------------------------
1 | package com.datastax.workshop;
2 |
3 | import javax.inject.Inject;
4 |
5 | import org.junit.jupiter.api.Test;
6 | import org.slf4j.Logger;
7 | import org.slf4j.LoggerFactory;
8 |
9 | import com.datastax.oss.quarkus.runtime.api.session.QuarkusCqlSession;
10 | import com.datastaxdev.todo.TodoDto;
11 | import com.datastaxdev.todo.cassandra.TodoServicesCassandraOM;
12 |
13 | import io.quarkus.test.junit.QuarkusTest;
14 |
15 | @QuarkusTest
16 | public class E03_QuarkusObjectMapping {
17 |
18 | /** Logger for the class. */
19 | static Logger LOGGER = LoggerFactory.getLogger(E02_QuarkusCql.class);
20 |
21 | @Inject
22 | QuarkusCqlSession quarkusCqlSession;
23 |
24 | @Inject
25 | TodoServicesCassandraOM todoService;
26 |
27 | @Test
28 | public void testExecuteCql() {
29 | LOGGER.info("Inserting Data");
30 | TodoDto dto = new TodoDto();
31 | dto.setUserId("clun");
32 | dto.setCompleted(false);
33 | dto.setTitle("Apprendre Mapping Objet Quarkus");
34 | todoService.save(dto);
35 | LOGGER.info("+ [OK]");
36 | }
37 |
38 | }
39 |
--------------------------------------------------------------------------------
/labs/lab6_quarkus/src/main/java/com/datastaxdev/todo/cassandra/TodoItemDao.java:
--------------------------------------------------------------------------------
1 | package com.datastaxdev.todo.cassandra;
2 |
3 | import java.util.Optional;
4 | import java.util.UUID;
5 |
6 | import com.datastax.oss.driver.api.core.PagingIterable;
7 | import com.datastax.oss.driver.api.mapper.annotations.Dao;
8 | import com.datastax.oss.driver.api.mapper.annotations.DefaultNullSavingStrategy;
9 | import com.datastax.oss.driver.api.mapper.annotations.Delete;
10 | import com.datastax.oss.driver.api.mapper.annotations.Insert;
11 | import com.datastax.oss.driver.api.mapper.annotations.Select;
12 | import com.datastax.oss.driver.api.mapper.entity.saving.NullSavingStrategy;
13 |
14 | @Dao
15 | @DefaultNullSavingStrategy(NullSavingStrategy.SET_TO_NULL)
16 | public interface TodoItemDao {
17 |
18 | @Delete(entityClass = TodoItem.class)
19 | void deleteByUser(String userId);
20 |
21 | @Delete(entityClass = TodoItem.class)
22 | void deleteById(String userId, UUID itemId);
23 |
24 | @Select
25 | PagingIterable findByUser(String userId);
26 |
27 | @Select
28 | Optional findById(String userId, UUID itemId);
29 |
30 | @Insert
31 | void save(TodoItem product);
32 | }
33 |
--------------------------------------------------------------------------------
/labs/lab7_micronaut/src/main/java/com/datastaxdev/todo/cassandra/TodoItemDao.java:
--------------------------------------------------------------------------------
1 | package com.datastaxdev.todo.cassandra;
2 |
3 | import java.util.Optional;
4 | import java.util.UUID;
5 |
6 | import com.datastax.oss.driver.api.core.PagingIterable;
7 | import com.datastax.oss.driver.api.mapper.annotations.Dao;
8 | import com.datastax.oss.driver.api.mapper.annotations.DefaultNullSavingStrategy;
9 | import com.datastax.oss.driver.api.mapper.annotations.Delete;
10 | import com.datastax.oss.driver.api.mapper.annotations.Insert;
11 | import com.datastax.oss.driver.api.mapper.annotations.Select;
12 | import com.datastax.oss.driver.api.mapper.entity.saving.NullSavingStrategy;
13 |
14 | @Dao
15 | @DefaultNullSavingStrategy(NullSavingStrategy.SET_TO_NULL)
16 | public interface TodoItemDao {
17 |
18 | @Delete(entityClass = TodoItem.class)
19 | void deleteByUser(String userId);
20 |
21 | @Delete(entityClass = TodoItem.class)
22 | void deleteById(String userId, UUID itemId);
23 |
24 | @Select
25 | PagingIterable findByUser(String userId);
26 |
27 | @Select
28 | Optional findById(String userId, UUID itemId);
29 |
30 | @Insert
31 | void save(TodoItem product);
32 | }
33 |
--------------------------------------------------------------------------------
/labs/lab7_micronaut/src/test/java/com/datastaxdev/E02_MicronautCql.java:
--------------------------------------------------------------------------------
1 | package com.datastaxdev;
2 |
3 | import org.junit.jupiter.api.Test;
4 | import org.slf4j.Logger;
5 | import org.slf4j.LoggerFactory;
6 |
7 | import com.datastax.oss.driver.api.core.CqlSession;
8 | import com.datastaxdev.todo.cassandra.TodoServiceCassandraCql;
9 |
10 | import io.micronaut.test.extensions.junit5.annotation.MicronautTest;
11 | import jakarta.inject.Inject;
12 |
13 | @MicronautTest
14 | public class E02_MicronautCql {
15 |
16 | /** Logger for the class. */
17 | static Logger LOGGER = LoggerFactory.getLogger(E02_MicronautCql.class);
18 |
19 | @Inject
20 | CqlSession cqlSession;
21 |
22 | @Inject
23 | TodoServiceCassandraCql todoService;
24 |
25 | @Test
26 | public void testExecuteCql() {
27 | LOGGER.info("Creating the schema...");
28 | TodoServiceCassandraCql.createTableTodo(cqlSession);
29 | LOGGER.info("+ [OK]");
30 |
31 | LOGGER.info("Inserting Data");
32 | TodoDto dto = new TodoDto();
33 | dto.setUserId("clun");
34 | dto.setCompleted(false);
35 | dto.setTitle("Apprendre Micronaut");
36 | todoService.save(dto);
37 | LOGGER.info("+ [OK]");
38 | }
39 | }
40 |
--------------------------------------------------------------------------------
/labs/lab6_quarkus/src/test/java/com/datastax/workshop/E02_QuarkusCql.java:
--------------------------------------------------------------------------------
1 | package com.datastax.workshop;
2 |
3 | import javax.inject.Inject;
4 |
5 | import org.junit.jupiter.api.Test;
6 | import org.slf4j.Logger;
7 | import org.slf4j.LoggerFactory;
8 |
9 | import com.datastax.oss.quarkus.runtime.api.session.QuarkusCqlSession;
10 | import com.datastaxdev.todo.TodoDto;
11 | import com.datastaxdev.todo.cassandra.TodoServiceCassandraCql;
12 |
13 | import io.quarkus.test.junit.QuarkusTest;
14 |
15 | @QuarkusTest
16 | public class E02_QuarkusCql {
17 |
18 | /** Logger for the class. */
19 | static Logger LOGGER = LoggerFactory.getLogger(E02_QuarkusCql.class);
20 |
21 | @Inject
22 | QuarkusCqlSession quarkusCqlSession;
23 |
24 | @Inject
25 | TodoServiceCassandraCql todoService;
26 |
27 | @Test
28 | public void testExecuteCql() {
29 | LOGGER.info("Creating the schema...");
30 | TodoServiceCassandraCql.createTableTodo(quarkusCqlSession);
31 | LOGGER.info("+ [OK]");
32 |
33 | LOGGER.info("Inserting Data");
34 | TodoDto dto = new TodoDto();
35 | dto.setUserId("clun");
36 | dto.setCompleted(false);
37 | dto.setTitle("Apprendre Quarkus");
38 | todoService.save(dto);
39 | LOGGER.info("+ [OK]");
40 | }
41 | }
42 |
--------------------------------------------------------------------------------
/labs/lab7_micronaut/src/main/java/com/datastaxdev/TodoApplicationStartup.java:
--------------------------------------------------------------------------------
1 | package com.datastaxdev;
2 |
3 | import org.slf4j.Logger;
4 | import org.slf4j.LoggerFactory;
5 |
6 | import com.datastax.oss.driver.api.core.CqlSession;
7 | import com.datastaxdev.todo.cassandra.TodoServiceCassandraCql;
8 |
9 | import io.micronaut.context.event.ApplicationEventListener;
10 | import io.micronaut.discovery.event.ServiceReadyEvent;
11 | import jakarta.inject.Inject;
12 | import jakarta.inject.Singleton;
13 |
14 | /**
15 | * Execute some Action and application startup.
16 | *
17 | * @author Cedrick LUNVEN (@clunven)
18 | */
19 | @Singleton
20 | public class TodoApplicationStartup implements ApplicationEventListener {
21 |
22 | /** Logger for the class. */
23 | private static final Logger LOGGER = LoggerFactory.getLogger(TodoApplicationStartup.class);
24 |
25 | @Inject
26 | private CqlSession cqlSession;
27 |
28 | /** {@inheritDoc} */
29 | @Override
30 | public void onApplicationEvent(final ServiceReadyEvent event) {
31 | LOGGER.info("Startup Initialization");
32 | TodoServiceCassandraCql.createTableTodo(cqlSession);
33 | LOGGER.info("+ Table TodoItems created if needed.");
34 | LOGGER.info("[OK]");
35 | }
36 |
37 |
38 | }
39 |
40 |
41 |
42 |
43 |
--------------------------------------------------------------------------------
/labs/lab6_quarkus/src/test/java/com/datastax/workshop/E01_QuarkusInit.java:
--------------------------------------------------------------------------------
1 | package com.datastax.workshop;
2 |
3 | import javax.inject.Inject;
4 |
5 | import org.eclipse.microprofile.config.inject.ConfigProperty;
6 | import org.junit.jupiter.api.Assertions;
7 | import org.junit.jupiter.api.Test;
8 | import org.slf4j.Logger;
9 | import org.slf4j.LoggerFactory;
10 |
11 | import com.datastax.oss.quarkus.runtime.api.session.QuarkusCqlSession;
12 |
13 | import io.quarkus.test.junit.QuarkusTest;
14 |
15 | @QuarkusTest
16 | public class E01_QuarkusInit {
17 |
18 | /** Logger for the class. */
19 | static Logger LOGGER = LoggerFactory.getLogger(E01_QuarkusInit.class);
20 |
21 | @Inject
22 | QuarkusCqlSession quarkusCqlSession;
23 |
24 | @Inject
25 | @ConfigProperty(name = "quarkus.cassandra.keyspace")
26 | String keyspace;
27 |
28 | @Test
29 | public void testCqlSession() {
30 | LOGGER.info("Creating your CqlSession to Cassandra...");
31 | Assertions.assertNotNull(keyspace);
32 | Assertions.assertTrue(quarkusCqlSession.getKeyspace().isPresent());
33 | LOGGER.info("+ [OK] Your are connected to keyspace {}", quarkusCqlSession.getKeyspace().get());
34 | Assertions.assertEquals(keyspace, quarkusCqlSession.getKeyspace().get().toString());
35 | }
36 |
37 | }
38 |
--------------------------------------------------------------------------------
/labs/docker-compose.yml:
--------------------------------------------------------------------------------
1 | version: "2"
2 | services:
3 |
4 | # Pour construire un DC l'un des noeud est un seed
5 | dc1_seed:
6 | image: cassandra:4.0.3
7 | ports:
8 | - 9042:9042
9 | networks:
10 | - cassandra
11 | mem_limit: 2G
12 | volumes:
13 | - ./lab3_data_modelling:/tmp/data_modelling
14 | #- ~/docker-volumes/dc1_seed/:/var/lib/cassandra/data
15 | environment:
16 | - CASSANDRA_DC=dc1
17 | - CASSANDRA_SEEDS=dc1_seed
18 | - CASSANDRA_CLUSTER_NAME=handson
19 | - CASSANDRA_ENDPOINT_SNITCH=GossipingPropertyFileSnitch
20 | - HEAP_NEWSIZE=128M
21 | - MAX_HEAP_SIZE=1024M
22 |
23 | dc1_noeud:
24 | image: cassandra:4.0.3
25 | command: /bin/bash -c "echo 'On attend que dc1_seed bootstrap pendant 30s' && sleep 30 && /usr/local/bin/docker-entrypoint.sh cassandra -f"
26 | mem_limit: 2G
27 | #volumes:
28 | # - ~/docker-volumes/dc1_noeud/:/var/lib/cassandra/data
29 | networks:
30 | - cassandra
31 | depends_on:
32 | - dc1_seed
33 | environment:
34 | - CASSANDRA_DC=dc1
35 | - CASSANDRA_SEEDS=dc1_seed
36 | - CASSANDRA_CLUSTER_NAME=handson
37 | - CASSANDRA_ENDPOINT_SNITCH=GossipingPropertyFileSnitch
38 | - HEAP_NEWSIZE=128M
39 | - MAX_HEAP_SIZE=1024M
40 |
41 | networks:
42 | cassandra:
43 |
44 |
--------------------------------------------------------------------------------
/labs/lab4_cassandra_drivers/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.schema.SchemaConstants;
9 |
10 | /**
11 | * Specialization for VIDEO.
12 | *
13 | * @author DataStax Developer Advocates team.
14 | */
15 | @Entity
16 | @CqlName(SchemaConstants.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 |
--------------------------------------------------------------------------------
/labs/lab5_spring_data/src/test/java/com/datastax/workshop/E02_SpringDataRepository.java:
--------------------------------------------------------------------------------
1 | package com.datastax.workshop;
2 |
3 | import org.junit.jupiter.api.Assertions;
4 | import org.junit.jupiter.api.Test;
5 | import org.slf4j.Logger;
6 | import org.slf4j.LoggerFactory;
7 | import org.springframework.beans.factory.annotation.Autowired;
8 | import org.springframework.boot.test.context.SpringBootTest;
9 |
10 | import com.datastax.workshop.todo.TodoEntity;
11 | import com.datastax.workshop.todo.TodoRepositoryCassandra;
12 |
13 | @SpringBootTest
14 | public class E02_SpringDataRepository {
15 |
16 | /** Logger for the class. */
17 | static Logger LOGGER = LoggerFactory.getLogger(E02_SpringDataRepository.class);
18 |
19 | @Autowired
20 | TodoRepositoryCassandra todoRepo;
21 |
22 | @Test
23 | public void testCassandraRepository() {
24 | // Given
25 | TodoEntity te = new TodoEntity("Apprendre Cassandra", 0);
26 | // When
27 | TodoEntity e = todoRepo.save(te);
28 | LOGGER.info("Tache enregistree avec id {}", e.getUid());
29 | // Then
30 | Assertions.assertTrue(todoRepo.existsById(te.getUid()));
31 | // Listing
32 | LOGGER.info("Liste des Taches");
33 | todoRepo.findAll().stream().map(Object::toString).forEach(LOGGER::info);
34 | }
35 |
36 |
37 |
38 | }
39 |
--------------------------------------------------------------------------------
/labs/lab5_spring_data/src/main/java/com/datastax/workshop/todo/TodoRepositorySimpleCassandra.java:
--------------------------------------------------------------------------------
1 | package com.datastax.workshop.todo;
2 |
3 | import java.util.UUID;
4 |
5 | import org.springframework.data.cassandra.core.CassandraOperations;
6 | import org.springframework.data.cassandra.core.mapping.CassandraPersistentEntity;
7 | import org.springframework.data.cassandra.repository.support.MappingCassandraEntityInformation;
8 | import org.springframework.data.cassandra.repository.support.SimpleCassandraRepository;
9 | import org.springframework.stereotype.Repository;
10 |
11 | import com.datastax.oss.driver.api.core.CqlSession;
12 |
13 | @Repository
14 | public class TodoRepositorySimpleCassandra extends SimpleCassandraRepository {
15 |
16 | protected final CqlSession cqlSession;
17 |
18 | protected final CassandraOperations cassandraTemplate;
19 |
20 | @SuppressWarnings("unchecked")
21 | public TodoRepositorySimpleCassandra(CqlSession cqlSession, CassandraOperations ops) {
22 | super(new MappingCassandraEntityInformation(
23 | (CassandraPersistentEntity) ops.getConverter().getMappingContext()
24 | .getRequiredPersistentEntity(TodoEntity.class), ops.getConverter()), ops);
25 | this.cqlSession = cqlSession;
26 | this.cassandraTemplate = ops;
27 | }
28 |
29 |
30 | }
31 |
--------------------------------------------------------------------------------
/labs/lab4_cassandra_drivers/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.schema.SchemaConstants;
9 |
10 | /**
11 | * Specialization for USER.
12 | *
13 | * @author DataStax Developer Advocates team.
14 | */
15 | @Entity
16 | @CqlName(SchemaConstants.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 |
--------------------------------------------------------------------------------
/labs/lab7_micronaut/src/test/java/com/datastaxdev/E04_MicronautController.java:
--------------------------------------------------------------------------------
1 | package com.datastaxdev;
2 |
3 |
4 | import static org.junit.jupiter.api.Assertions.assertFalse;
5 |
6 | import java.util.List;
7 |
8 | import org.junit.jupiter.api.Assertions;
9 | import org.junit.jupiter.api.Test;
10 | import org.slf4j.Logger;
11 | import org.slf4j.LoggerFactory;
12 |
13 | import io.micronaut.core.type.Argument;
14 | import io.micronaut.http.HttpRequest;
15 | import io.micronaut.http.client.HttpClient;
16 | import io.micronaut.http.client.annotation.Client;
17 | import io.micronaut.runtime.EmbeddedApplication;
18 | import io.micronaut.test.extensions.junit5.annotation.MicronautTest;
19 | import jakarta.inject.Inject;
20 |
21 | @MicronautTest
22 | public class E04_MicronautController {
23 |
24 | /** Logger for the class. */
25 | static Logger LOGGER = LoggerFactory.getLogger(E04_MicronautController.class);
26 |
27 | @Inject
28 | EmbeddedApplication> application;
29 |
30 | @Inject
31 | @Client("/api/v1/")
32 | HttpClient client;
33 |
34 | @Test
35 | public void testRunApplication() {
36 | Assertions.assertTrue(application.isRunning());
37 | HttpRequest request = HttpRequest.GET("/clun/todos");
38 | List todos = client.toBlocking().retrieve(request, Argument.listOf(TodoDto.class));
39 | assertFalse(todos.isEmpty());
40 | LOGGER.info("{} task retrieved", todos.size());
41 | }
42 |
43 | }
44 |
--------------------------------------------------------------------------------
/labs/lab7_micronaut/src/test/java/com/datastaxdev/E01_MicronautInit.java:
--------------------------------------------------------------------------------
1 | package com.datastaxdev;
2 |
3 | import org.junit.jupiter.api.Assertions;
4 | import org.junit.jupiter.api.Test;
5 | import org.slf4j.Logger;
6 | import org.slf4j.LoggerFactory;
7 |
8 | import com.datastax.oss.driver.api.core.CqlSession;
9 |
10 | import io.micronaut.context.BeanContext;
11 | import io.micronaut.context.annotation.Property;
12 | import io.micronaut.test.extensions.junit5.annotation.MicronautTest;
13 | import jakarta.inject.Inject;
14 |
15 | @MicronautTest
16 | public class E01_MicronautInit {
17 |
18 | /** Logger for the class. */
19 | static Logger LOGGER = LoggerFactory.getLogger(E01_MicronautInit.class);
20 |
21 | @Inject
22 | BeanContext beanContext;
23 |
24 | @Inject
25 | CqlSession cqlSession;
26 |
27 | @Inject
28 | @Property(name = "cassandra.default.basic.session-keyspace")
29 | String keyspace;
30 |
31 | @Test
32 | public void testCqlSession() {
33 | //final CqlSession cqlSession = (CqlSession) beanContext.getBean(CqlSession.class);
34 |
35 | LOGGER.info("Creating your CqlSession to Cassandra...");
36 | Assertions.assertNotNull(keyspace);
37 | Assertions.assertTrue(cqlSession.getKeyspace().isPresent());
38 | LOGGER.info("+ [OK] Your are connected to keyspace {}", cqlSession.getKeyspace().get());
39 | Assertions.assertEquals(keyspace, cqlSession.getKeyspace().get().toString());
40 | }
41 |
42 |
43 | }
44 |
--------------------------------------------------------------------------------
/labs/lab4_cassandra_drivers/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.schema.SchemaConstants;
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 SchemaConstants {
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 |
--------------------------------------------------------------------------------
/labs/lab5_spring_data/src/test/java/com/datastax/workshop/E04_SpringControllerTest.java:
--------------------------------------------------------------------------------
1 | package com.datastax.workshop;
2 |
3 | import org.junit.jupiter.api.Assertions;
4 | import org.junit.jupiter.api.Test;
5 | import org.springframework.boot.test.context.SpringBootTest;
6 | import org.springframework.boot.test.web.client.TestRestTemplate;
7 | import org.springframework.boot.web.server.LocalServerPort;
8 | import org.springframework.http.HttpEntity;
9 | import org.springframework.http.HttpHeaders;
10 | import org.springframework.http.HttpMethod;
11 | import org.springframework.http.HttpStatus;
12 | import org.springframework.http.ResponseEntity;
13 |
14 | import com.datastax.workshop.todo.Todo;
15 |
16 | @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
17 | public class E04_SpringControllerTest {
18 |
19 | @LocalServerPort
20 | private int port;
21 |
22 | TestRestTemplate restTemplate = new TestRestTemplate();
23 |
24 | @Test
25 | public void should_retrieve_todolist_v0() {
26 | HttpHeaders headers = new HttpHeaders();
27 | HttpEntity entity = new HttpEntity(null, headers);
28 | ResponseEntity response = restTemplate.exchange(
29 | createURLWithPort("/api/v1/todos/"), HttpMethod.GET, entity, Todo[].class);
30 | Assertions.assertEquals(HttpStatus.OK, response.getStatusCode());
31 | }
32 |
33 | private String createURLWithPort(String uri) {
34 | return "http://localhost:" + port + uri;
35 | }
36 |
37 |
38 |
39 | }
40 |
41 |
--------------------------------------------------------------------------------
/labs/lab5_spring_data/src/test/java/com/datastax/workshop/E03_SpringDataCassandraOperations.java:
--------------------------------------------------------------------------------
1 | package com.datastax.workshop;
2 |
3 | import org.junit.jupiter.api.Test;
4 | import org.slf4j.Logger;
5 | import org.slf4j.LoggerFactory;
6 | import org.springframework.beans.factory.annotation.Autowired;
7 | import org.springframework.boot.test.context.SpringBootTest;
8 | import org.springframework.data.cassandra.core.CassandraOperations;
9 |
10 | import com.datastax.workshop.todo.TodoEntity;
11 | import com.datastax.workshop.todo.TodoRepositorySimpleCassandra;
12 |
13 | @SpringBootTest
14 | public class E03_SpringDataCassandraOperations {
15 |
16 | /** Logger for the class. */
17 | static Logger LOGGER = LoggerFactory.getLogger(E02_SpringDataRepository.class);
18 |
19 | @Autowired
20 | CassandraOperations cassandraOps;
21 |
22 | @Autowired
23 | TodoRepositorySimpleCassandra todoRepoSimple;
24 |
25 | @Test
26 | public void testCassandraOperations() {
27 | LOGGER.info("Utilisation de CassandraOperations");
28 | cassandraOps.select("select * from todos", TodoEntity.class)
29 | .stream()
30 | .map(Object::toString)
31 | .forEach(LOGGER::info);
32 | }
33 |
34 | @Test
35 | public void testSimpleCassandraRepository() {
36 | TodoEntity e = todoRepoSimple.save(new TodoEntity("Apprendre Cassandra", 0));
37 | LOGGER.info("Tache enregistree avec id {}", e.getUid());
38 |
39 | LOGGER.info("Liste des Taches");
40 | todoRepoSimple.findAll().stream().map(Object::toString).forEach(LOGGER::info);
41 | }
42 |
43 | }
44 |
--------------------------------------------------------------------------------
/labs/lab7_micronaut/src/main/java/com/datastaxdev/TodoService.java:
--------------------------------------------------------------------------------
1 | package com.datastaxdev;
2 |
3 | import java.util.List;
4 | import java.util.Optional;
5 | import java.util.UUID;
6 |
7 | /**
8 | * Definition of services to work with the Todo Application.
9 | *
10 | * @author Cedrick Lunven (@clunven)
11 | */
12 | public interface TodoService {
13 |
14 | /**
15 | * Save Todoitems.
16 | *
17 | * @param todo
18 | * list of todos
19 | * @return
20 | * updated todo with if if relevant
21 | */
22 | TodoDto save(TodoDto todo);
23 |
24 | /**
25 | * Retrieve an task by its itentifier.
26 | *
27 | * @param userId
28 | * userId
29 | * @param itemId
30 | * itemId
31 | * @return
32 | * if the Task exists
33 | */
34 | Optional findById(String userId, UUID itemId);
35 |
36 | /**
37 | * Retrieve the list of Tasks for a user (if exist).
38 | *
39 | * @param userId
40 | * user identifier
41 | * @return
42 | * list of Tasks for the user
43 | */
44 | List findByUser(String userId);
45 |
46 | /**
47 | * Delete a task from its identifier
48 | *
49 | * @param userId
50 | * user identifer
51 | * @param itemId
52 | * item identifier
53 | */
54 | void deleteById(String userId, UUID itemId);
55 |
56 | /**
57 | * Delete all tasks for a user.
58 | *
59 | * @param userId
60 | * user identifier
61 | */
62 | void deleteByUser(String userId);
63 |
64 | /**
65 | * Clean DB.
66 | */
67 | void deleteAll();
68 |
69 | }
70 |
--------------------------------------------------------------------------------
/labs/lab6_quarkus/src/main/java/com/datastaxdev/todo/TodoService.java:
--------------------------------------------------------------------------------
1 | package com.datastaxdev.todo;
2 |
3 | import java.util.List;
4 | import java.util.Optional;
5 | import java.util.UUID;
6 |
7 | /**
8 | * Definition of services to work with the Todo Application.
9 | *
10 | * @author Cedrick Lunven (@clunven)
11 | */
12 | public interface TodoService {
13 |
14 | /**
15 | * Save Todoitems.
16 | *
17 | * @param todo
18 | * list of todos
19 | * @return
20 | * updated todo with if if relevant
21 | */
22 | TodoDto save(TodoDto todo);
23 |
24 | /**
25 | * Retrieve an task by its itentifier.
26 | *
27 | * @param userId
28 | * userId
29 | * @param itemId
30 | * itemId
31 | * @return
32 | * if the Task exists
33 | */
34 | Optional findById(String userId, UUID itemId);
35 |
36 | /**
37 | * Retrieve the list of Tasks for a user (if exist).
38 | *
39 | * @param userId
40 | * user identifier
41 | * @return
42 | * list of Tasks for the user
43 | */
44 | List findByUser(String userId);
45 |
46 | /**
47 | * Delete a task from its identifier
48 | *
49 | * @param userId
50 | * user identifer
51 | * @param itemId
52 | * item identifier
53 | */
54 | void deleteById(String userId, UUID itemId);
55 |
56 | /**
57 | * Delete all tasks for a user.
58 | *
59 | * @param userId
60 | * user identifier
61 | */
62 | void deleteByUser(String userId);
63 |
64 | /**
65 | * Clean DB.
66 | */
67 | void deleteAll();
68 |
69 | }
70 |
--------------------------------------------------------------------------------
/labs/lab4_cassandra_drivers/src/main/java/com/datastax/samples/E01_CreateSchema.java:
--------------------------------------------------------------------------------
1 | package com.datastax.samples;
2 |
3 | import static com.datastax.samples.schema.SchemaUtils.createTableCommentByUser;
4 | import static com.datastax.samples.schema.SchemaUtils.createTableCommentByVideo;
5 | import static com.datastax.samples.schema.SchemaUtils.createTableUser;
6 | import static com.datastax.samples.schema.SchemaUtils.createTableVideo;
7 | import static com.datastax.samples.schema.SchemaUtils.createTableVideoViews;
8 | import static com.datastax.samples.schema.SchemaUtils.createUdtVideoFormat;
9 |
10 | import org.slf4j.Logger;
11 | import org.slf4j.LoggerFactory;
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 | import com.datastax.oss.driver.api.core.CqlSession;
21 | import com.datastax.samples.schema.SchemaConstants;
22 |
23 | public class E01_CreateSchema implements SchemaConstants {
24 |
25 | private static Logger LOGGER = LoggerFactory.getLogger(E01_CreateSchema.class);
26 |
27 | public static void main(String[] args) {
28 | try(CqlSession cqlSession = CqlSessionProvider.getInstance().getSession()) {
29 | createUdtVideoFormat(cqlSession);
30 | createTableUser(cqlSession);
31 | createTableVideo(cqlSession);
32 | createTableVideoViews(cqlSession);
33 | createTableCommentByVideo(cqlSession);
34 | createTableCommentByUser(cqlSession);
35 | }
36 | LOGGER.info("[OK] Success");
37 | System.exit(0);
38 | }
39 |
40 | }
41 |
--------------------------------------------------------------------------------
/labs/lab6_quarkus/src/main/docker/Dockerfile.jvm:
--------------------------------------------------------------------------------
1 | ####
2 | # This Dockerfile is used in order to build a container that runs the Quarkus application in JVM mode
3 | #
4 | # Before building the docker image run:
5 | #
6 | # mvn package
7 | #
8 | # Then, build the image with:
9 | #
10 | # docker build -f src/main/docker/Dockerfile.jvm -t quarkus/my-artifactId-jvm .
11 | #
12 | # Then run the container using:
13 | #
14 | # docker run -i --rm -p 8080:8080 quarkus/my-artifactId-jvm
15 | #
16 | # If you want to include the debug port into your docker image
17 | # you will have to expose the debug port (default 5005) like this : EXPOSE 8080 5050
18 | #
19 | # Then run the container using :
20 | #
21 | # docker run -i --rm -p 8080:8080 -p 5005:5005 -e JAVA_ENABLE_DEBUG="true" quarkus/my-artifactId-jvm
22 | #
23 | ###
24 | FROM registry.access.redhat.com/ubi8/ubi-minimal:8.1
25 |
26 | ARG JAVA_PACKAGE=java-11-openjdk-headless
27 | ARG RUN_JAVA_VERSION=1.3.8
28 |
29 | ENV LANG='en_US.UTF-8' LANGUAGE='en_US:en'
30 |
31 | # Install java and the run-java script
32 | # Also set up permissions for user `1001`
33 | RUN microdnf install curl ca-certificates ${JAVA_PACKAGE} \
34 | && microdnf update \
35 | && microdnf clean all \
36 | && mkdir /deployments \
37 | && chown 1001 /deployments \
38 | && chmod "g+rwX" /deployments \
39 | && chown 1001:root /deployments \
40 | && curl https://repo1.maven.org/maven2/io/fabric8/run-java-sh/${RUN_JAVA_VERSION}/run-java-sh-${RUN_JAVA_VERSION}-sh.sh -o /deployments/run-java.sh \
41 | && chown 1001 /deployments/run-java.sh \
42 | && chmod 540 /deployments/run-java.sh \
43 | && echo "securerandom.source=file:/dev/urandom" >> /etc/alternatives/jre/lib/security/java.security
44 |
45 | # Configure the JAVA_OPTIONS, you can add -XshowSettings:vm to also display the heap size.
46 | ENV JAVA_OPTIONS="-Dquarkus.http.host=0.0.0.0 -Djava.util.logging.manager=org.jboss.logmanager.LogManager"
47 |
48 | COPY target/lib/* /deployments/lib/
49 | COPY target/*-runner.jar /deployments/app.jar
50 |
51 | EXPOSE 8080
52 | USER 1001
53 |
54 | ENTRYPOINT [ "/deployments/run-java.sh" ]
--------------------------------------------------------------------------------
/labs/lab7_micronaut/src/main/java/com/datastaxdev/TodoDto.java:
--------------------------------------------------------------------------------
1 | package com.datastaxdev;
2 |
3 | import java.util.UUID;
4 |
5 | public class TodoDto {
6 |
7 | private String userId;
8 | private UUID itemId;
9 | private String title;
10 | private Boolean completed;
11 |
12 | /**
13 | * Getter accessor for attribute 'userId'.
14 | *
15 | * @return
16 | * current value of 'userId'
17 | */
18 | public String getUserId() {
19 | return userId;
20 | }
21 | /**
22 | * Setter accessor for attribute 'userId'.
23 | * @param userId
24 | * new value for 'userId '
25 | */
26 | public void setUserId(String userId) {
27 | this.userId = userId;
28 | }
29 | /**
30 | * Getter accessor for attribute 'itemId'.
31 | *
32 | * @return
33 | * current value of 'itemId'
34 | */
35 | public UUID getItemId() {
36 | return itemId;
37 | }
38 | /**
39 | * Setter accessor for attribute 'itemId'.
40 | * @param itemId
41 | * new value for 'itemId '
42 | */
43 | public void setItemId(UUID itemId) {
44 | this.itemId = itemId;
45 | }
46 | /**
47 | * Getter accessor for attribute 'title'.
48 | *
49 | * @return
50 | * current value of 'title'
51 | */
52 | public String getTitle() {
53 | return title;
54 | }
55 | /**
56 | * Setter accessor for attribute 'title'.
57 | * @param title
58 | * new value for 'title '
59 | */
60 | public void setTitle(String title) {
61 | this.title = title;
62 | }
63 | /**
64 | * Getter accessor for attribute 'completed'.
65 | *
66 | * @return
67 | * current value of 'completed'
68 | */
69 | public Boolean getCompleted() {
70 | return completed;
71 | }
72 | /**
73 | * Setter accessor for attribute 'completed'.
74 | * @param completed
75 | * new value for 'completed '
76 | */
77 | public void setCompleted(Boolean completed) {
78 | this.completed = completed;
79 | }
80 |
81 | }
82 |
--------------------------------------------------------------------------------
/labs/lab6_quarkus/src/main/java/com/datastaxdev/todo/TodoDto.java:
--------------------------------------------------------------------------------
1 | package com.datastaxdev.todo;
2 |
3 | import java.util.UUID;
4 |
5 | public class TodoDto {
6 |
7 | private String userId;
8 | private UUID itemId;
9 | private String title;
10 | private Boolean completed;
11 |
12 | /**
13 | * Getter accessor for attribute 'userId'.
14 | *
15 | * @return
16 | * current value of 'userId'
17 | */
18 | public String getUserId() {
19 | return userId;
20 | }
21 | /**
22 | * Setter accessor for attribute 'userId'.
23 | * @param userId
24 | * new value for 'userId '
25 | */
26 | public void setUserId(String userId) {
27 | this.userId = userId;
28 | }
29 | /**
30 | * Getter accessor for attribute 'itemId'.
31 | *
32 | * @return
33 | * current value of 'itemId'
34 | */
35 | public UUID getItemId() {
36 | return itemId;
37 | }
38 | /**
39 | * Setter accessor for attribute 'itemId'.
40 | * @param itemId
41 | * new value for 'itemId '
42 | */
43 | public void setItemId(UUID itemId) {
44 | this.itemId = itemId;
45 | }
46 | /**
47 | * Getter accessor for attribute 'title'.
48 | *
49 | * @return
50 | * current value of 'title'
51 | */
52 | public String getTitle() {
53 | return title;
54 | }
55 | /**
56 | * Setter accessor for attribute 'title'.
57 | * @param title
58 | * new value for 'title '
59 | */
60 | public void setTitle(String title) {
61 | this.title = title;
62 | }
63 | /**
64 | * Getter accessor for attribute 'completed'.
65 | *
66 | * @return
67 | * current value of 'completed'
68 | */
69 | public Boolean getCompleted() {
70 | return completed;
71 | }
72 | /**
73 | * Setter accessor for attribute 'completed'.
74 | * @param completed
75 | * new value for 'completed '
76 | */
77 | public void setCompleted(Boolean completed) {
78 | this.completed = completed;
79 | }
80 |
81 | }
82 |
--------------------------------------------------------------------------------
/labs/lab4_cassandra_drivers/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 |
--------------------------------------------------------------------------------
/labs/lab6_quarkus/src/main/resources/application-local.properties:
--------------------------------------------------------------------------------
1 | quarkus.http.port=8081
2 | quarkus.container-image.registry=docker.io
3 | quarkus.profile=dev
4 | quarkus.container-image.name=quarkus-cassandra
5 | quarkus.kubernetes.service-type=load-balancer
6 | quarkus.cassandra.init.eager-init=true
7 |
8 | # Authentication
9 | quarkus.cassandra.contact-points=localhost:9042
10 | quarkus.cassandra.local-datacenter=dc1
11 | quarkus.cassandra.keyspace=devoxx_quarkus
12 |
13 | # Health Checks
14 | quarkus.cassandra.health.enabled=true
15 |
16 | # Metrics
17 | # See https://docs.datastax.com/en/developer/java-driver/latest/manual/core/metrics/
18 | quarkus.cassandra.metrics.enabled=true
19 | quarkus.cassandra.metrics.session.enabled=\
20 | bytes-sent,\
21 | bytes-received,\
22 | connected-nodes,\
23 | cql-requests,\
24 | cql-client-timeouts
25 | quarkus.cassandra.metrics.node.enabled=\
26 | pool.open-connections,\
27 | pool.in-flight,\
28 | bytes-sent,\
29 | bytes-received,\
30 | cql-messages,\
31 | errors.request.unsent,\
32 | errors.request.aborted,\
33 | errors.request.write-timeouts,\
34 | errors.request.read-timeouts,\
35 | errors.request.unavailables,\
36 | errors.request.others,\
37 | retries.total,\
38 | retries.aborted,\
39 | retries.read-timeout,\
40 | retries.write-timeout,\
41 | retries.unavailable,\
42 | retries.other,\
43 | ignores.total,\
44 | ignores.aborted,\
45 | ignores.read-timeout,\
46 | ignores.write-timeout,\
47 | ignores.unavailable,\
48 | ignores.other,\
49 | errors.connection.init,\
50 | errors.connection.auth
51 |
52 | # Request properties
53 | #quarkus.cassandra.request.timeout=PT10S
54 | #quarkus.cassandra.request.consistency-level=LOCAL_QUORUM
55 | #quarkus.cassandra.request.serial-consistency-level=LOCAL_SERIAL
56 | #quarkus.cassandra.request.page-size=5000
57 | #quarkus.cassandra.request.default-idempotence=true
58 |
59 | # Protocol settings
60 | #quarkus.cassandra.protocol.compression=none
61 |
62 | # Startup and Initialization settings
63 | #quarkus.cassandra.init.eager-init=false
64 | #quarkus.cassandra.init.eager-init-timeout=PT10S
65 | #quarkus.cassandra.init.print-eager-init-info=true
66 | #quarkus.cassandra.init.reconnect-on-init=true
67 | #quarkus.cassandra.init.resolve-contact-points=false
68 | #quarkus.cassandra.init.use-quarkus-event-loop=true
69 |
70 | # Logging
71 | #quarkus.log.level=INFO
72 | #quarkus.log.min-level=DEBUG
73 | #quarkus.log.category."com.datastax.oss.quarkus".level=INFO
74 | #quarkus.log.category."com.datastax.oss.driver".level=INFO
75 | #quarkus.log.category."com.datastax.dse.driver".level=INFO
76 |
77 |
--------------------------------------------------------------------------------
/labs/lab4_cassandra_drivers/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.schema.SchemaConstants;
7 |
8 | /**
9 | * Sample bean for row.
10 | */
11 | public class UserDto implements Serializable, SchemaConstants {
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 |
--------------------------------------------------------------------------------
/labs/lab6_quarkus/src/main/resources/application.properties:
--------------------------------------------------------------------------------
1 | quarkus.http.port=8081
2 | quarkus.container-image.registry=docker.io
3 | quarkus.profile=dev
4 | quarkus.container-image.name=quarkus-cassandra
5 | quarkus.kubernetes.service-type=load-balancer
6 | quarkus.cassandra.init.eager-init=true
7 |
8 | quarkus.cassandra.keyspace=devoxx_quarkus
9 | quarkus.cassandra.cloud.secure-connect-bundle=/home/gitpod/.cassandra/bootstrap.zip
10 | quarkus.cassandra.auth.username=token
11 | quarkus.cassandra.auth.password=
12 |
13 | # Health Checks
14 | quarkus.cassandra.health.enabled=true
15 |
16 | # Metrics
17 | # See https://docs.datastax.com/en/developer/java-driver/latest/manual/core/metrics/
18 | quarkus.cassandra.metrics.enabled=true
19 | quarkus.cassandra.metrics.session.enabled=\
20 | bytes-sent,\
21 | bytes-received,\
22 | connected-nodes,\
23 | cql-requests,\
24 | cql-client-timeouts
25 | quarkus.cassandra.metrics.node.enabled=\
26 | pool.open-connections,\
27 | pool.in-flight,\
28 | bytes-sent,\
29 | bytes-received,\
30 | cql-messages,\
31 | errors.request.unsent,\
32 | errors.request.aborted,\
33 | errors.request.write-timeouts,\
34 | errors.request.read-timeouts,\
35 | errors.request.unavailables,\
36 | errors.request.others,\
37 | retries.total,\
38 | retries.aborted,\
39 | retries.read-timeout,\
40 | retries.write-timeout,\
41 | retries.unavailable,\
42 | retries.other,\
43 | ignores.total,\
44 | ignores.aborted,\
45 | ignores.read-timeout,\
46 | ignores.write-timeout,\
47 | ignores.unavailable,\
48 | ignores.other,\
49 | errors.connection.init,\
50 | errors.connection.auth
51 |
52 | # Request properties
53 | #quarkus.cassandra.request.timeout=PT10S
54 | #quarkus.cassandra.request.consistency-level=LOCAL_QUORUM
55 | #quarkus.cassandra.request.serial-consistency-level=LOCAL_SERIAL
56 | #quarkus.cassandra.request.page-size=5000
57 | #quarkus.cassandra.request.default-idempotence=true
58 |
59 | # Protocol settings
60 | #quarkus.cassandra.protocol.compression=none
61 |
62 | # Startup and Initialization settings
63 | #quarkus.cassandra.init.eager-init=false
64 | #quarkus.cassandra.init.eager-init-timeout=PT10S
65 | #quarkus.cassandra.init.print-eager-init-info=true
66 | #quarkus.cassandra.init.reconnect-on-init=true
67 | #quarkus.cassandra.init.resolve-contact-points=false
68 | #quarkus.cassandra.init.use-quarkus-event-loop=true
69 |
70 | # Logging
71 | #quarkus.log.level=INFO
72 | #quarkus.log.min-level=DEBUG
73 | #quarkus.log.category."com.datastax.oss.quarkus".level=INFO
74 | #quarkus.log.category."com.datastax.oss.driver".level=INFO
75 | #quarkus.log.category."com.datastax.dse.driver".level=INFO
76 |
77 |
--------------------------------------------------------------------------------
/labs/lab6_quarkus/src/main/resources/application-astra.properties:
--------------------------------------------------------------------------------
1 | quarkus.http.port=8081
2 | quarkus.container-image.registry=docker.io
3 | quarkus.profile=dev
4 | quarkus.container-image.name=quarkus-cassandra
5 | quarkus.kubernetes.service-type=load-balancer
6 | quarkus.cassandra.init.eager-init=true
7 |
8 | quarkus.cassandra.keyspace=devoxx_quarkus
9 | quarkus.cassandra.cloud.secure-connect-bundle=/home/gitpod/.cassandra/bootstrap.zip
10 | quarkus.cassandra.auth.username=token
11 | quarkus.cassandra.auth.password=
12 |
13 | # Health Checks
14 | quarkus.cassandra.health.enabled=true
15 |
16 | # Metrics
17 | # See https://docs.datastax.com/en/developer/java-driver/latest/manual/core/metrics/
18 | quarkus.cassandra.metrics.enabled=true
19 | quarkus.cassandra.metrics.session.enabled=\
20 | bytes-sent,\
21 | bytes-received,\
22 | connected-nodes,\
23 | cql-requests,\
24 | cql-client-timeouts
25 | quarkus.cassandra.metrics.node.enabled=\
26 | pool.open-connections,\
27 | pool.in-flight,\
28 | bytes-sent,\
29 | bytes-received,\
30 | cql-messages,\
31 | errors.request.unsent,\
32 | errors.request.aborted,\
33 | errors.request.write-timeouts,\
34 | errors.request.read-timeouts,\
35 | errors.request.unavailables,\
36 | errors.request.others,\
37 | retries.total,\
38 | retries.aborted,\
39 | retries.read-timeout,\
40 | retries.write-timeout,\
41 | retries.unavailable,\
42 | retries.other,\
43 | ignores.total,\
44 | ignores.aborted,\
45 | ignores.read-timeout,\
46 | ignores.write-timeout,\
47 | ignores.unavailable,\
48 | ignores.other,\
49 | errors.connection.init,\
50 | errors.connection.auth
51 |
52 | # Request properties
53 | #quarkus.cassandra.request.timeout=PT10S
54 | #quarkus.cassandra.request.consistency-level=LOCAL_QUORUM
55 | #quarkus.cassandra.request.serial-consistency-level=LOCAL_SERIAL
56 | #quarkus.cassandra.request.page-size=5000
57 | #quarkus.cassandra.request.default-idempotence=true
58 |
59 | # Protocol settings
60 | #quarkus.cassandra.protocol.compression=none
61 |
62 | # Startup and Initialization settings
63 | #quarkus.cassandra.init.eager-init=false
64 | #quarkus.cassandra.init.eager-init-timeout=PT10S
65 | #quarkus.cassandra.init.print-eager-init-info=true
66 | #quarkus.cassandra.init.reconnect-on-init=true
67 | #quarkus.cassandra.init.resolve-contact-points=false
68 | #quarkus.cassandra.init.use-quarkus-event-loop=true
69 |
70 | # Logging
71 | #quarkus.log.level=INFO
72 | #quarkus.log.min-level=DEBUG
73 | #quarkus.log.category."com.datastax.oss.quarkus".level=INFO
74 | #quarkus.log.category."com.datastax.oss.driver".level=INFO
75 | #quarkus.log.category."com.datastax.dse.driver".level=INFO
76 |
77 |
--------------------------------------------------------------------------------
/labs/lab4_cassandra_drivers/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 |
--------------------------------------------------------------------------------
/labs/lab5_spring_data/pom.xml:
--------------------------------------------------------------------------------
1 |
2 |
4 | 4.0.0
5 |
6 | org.springframework.boot
7 | spring-boot-starter-parent
8 | 2.6.1
9 |
10 |
11 | com.datastax.workshop
12 | lab5-spring-data
13 | 0.0.1-SNAPSHOT
14 | lab5-spring-data
15 | TodoBackend Spring Boot Microservices with Spring Data for Apache Cassandra
16 |
17 |
18 | 11
19 |
20 |
21 |
22 |
23 |
24 | org.springframework.boot
25 | spring-boot-starter-web
26 |
27 |
28 |
29 | org.springframework.boot
30 | spring-boot-starter-data-cassandra
31 |
32 |
33 |
34 | org.springframework.boot
35 | spring-boot-devtools
36 | runtime
37 | true
38 |
39 |
40 |
41 |
42 | org.springframework.boot
43 | spring-boot-starter-test
44 | test
45 |
46 |
47 | org.junit.vintage
48 | junit-vintage-engine
49 |
50 |
51 | com.vaadin.external.google
52 | android-json
53 |
54 |
55 |
56 |
57 | org.junit.jupiter
58 | junit-jupiter-api
59 | test
60 |
61 |
62 | org.junit.jupiter
63 | junit-jupiter-engine
64 | test
65 |
66 |
67 | org.junit.platform
68 | junit-platform-runner
69 | test
70 |
71 |
72 |
73 |
74 |
75 |
76 | org.springframework.boot
77 | spring-boot-maven-plugin
78 |
79 |
80 |
81 |
82 |
83 |
--------------------------------------------------------------------------------
/.gitpod.yml:
--------------------------------------------------------------------------------
1 | image:
2 | file: .gitpod.Dockerfile
3 |
4 | tasks:
5 | - name: lab4_cassandra_drivers
6 | before: |
7 | chmod 700 /workspace/conference-2022-devoxx/labs/lab4_cassandra_drivers/init
8 | command: |
9 | ./labs/lab4_cassandra_drivers/init
10 | - name: lab5_spring_data
11 | before: |
12 | chmod 700 /workspace/conference-2022-devoxx/labs/lab5_spring_data/init
13 | command: |
14 | ./labs/lab5_spring_data/init
15 | - name: lab6_quarkus
16 | before: |
17 | chmod 700 /workspace/conference-2022-devoxx/labs/lab6_quarkus/init
18 | command: |
19 | ./labs/lab6_quarkus/init
20 | - name: lab7_micronaut
21 | before: |
22 | chmod 700 /workspace/conference-2022-devoxx/labs/lab7_micronaut/init
23 | command: |
24 | ./labs/lab7_micronaut/init
25 | - name: gp
26 | command: |
27 | clear
28 | gp url 8080
29 |
30 |
31 | # -------------------------------------------------
32 | # Install Cqlsh for Astra and setup for a DB
33 | # -------------------------------------------------
34 | - name: cassandra-astra
35 | env:
36 | CQLENG_ALLOW_SCHEMA_MANAGEMENT: 1
37 | before: |
38 | chmod 700 /workspace/conference-2022-devoxx/labs/lab1_initialisation_environnements/astra-cqlsh
39 | chmod 700 /workspace/conference-2022-devoxx/labs/lab1_initialisation_environnements/astra-cqlsh-install
40 | chmod 700 /workspace/conference-2022-devoxx/labs/lab1_initialisation_environnements/cassandra-start
41 | chmod 700 /workspace/conference-2022-devoxx/labs/lab1_initialisation_environnements/cassandra-cqlsh
42 | command: |
43 | ./labs/lab1_initialisation_environnements/astra-cqlsh-install
44 | - name: cassandra-docker
45 | before: |
46 | docker pull cassandra:4.0.3
47 | command: |
48 | ./labs/lab1_initialisation_environnements/cassandra-start 2>/dev/null
49 |
50 | ports:
51 | # Cassandra Node in Docker
52 | - port: 9042
53 | onOpen: ignore
54 | visibility: public
55 | # Spring Application
56 | - port: 8080
57 | onOpen: open-browser
58 | visibility: public
59 | # Quarkus Application
60 | - port: 8081
61 | onOpen: open-browser
62 | visibility: public
63 | # Micronaut Application
64 | - port: 5005
65 | onOpen: ignore
66 | visibility: public
67 | # Micronaut Application
68 | - port: 8082
69 | onOpen: open-browser
70 | visibility: public
71 |
72 | github:
73 | prebuilds:
74 | master: true
75 | branches: true
76 | pullRequests: true
77 | pullRequestsFromForks: false
78 | addCheck: true
79 | addComment: false
80 | addBadge: true
81 | addLabel: false
82 |
83 | vscode:
84 | extensions:
85 | # Lombok
86 | - GabrielBB.vscode-lombok
87 | # Java
88 | - vscjava.vscode-java-pack
89 | # Spring Boot
90 | - Pivotal.vscode-boot-dev-pack
91 | # Docker Containers
92 | - ms-azuretools.vscode-docker
93 |
94 |
--------------------------------------------------------------------------------
/labs/lab4_cassandra_drivers/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.dto.VideoFormatDto;
12 | import com.datastax.samples.schema.SchemaConstants;
13 |
14 | /**
15 | * Codec.
16 | */
17 | public class UdtVideoFormatCodec implements TypeCodec, SchemaConstants {
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 |
--------------------------------------------------------------------------------
/labs/lab7_micronaut/src/main/java/com/datastaxdev/todo/cassandra/TodoServicesCassandraOM.java:
--------------------------------------------------------------------------------
1 | package com.datastaxdev.todo.cassandra;
2 |
3 | import java.util.List;
4 | import java.util.Optional;
5 | import java.util.UUID;
6 | import java.util.stream.Collectors;
7 |
8 | import com.datastax.oss.driver.api.core.CqlSession;
9 | import com.datastax.oss.driver.api.core.uuid.Uuids;
10 | import com.datastax.oss.driver.api.mapper.annotations.Query;
11 | import com.datastaxdev.TodoDto;
12 | import com.datastaxdev.TodoService;
13 |
14 | import jakarta.inject.Singleton;
15 |
16 | /**
17 | * Implementation of the service with ObjectMapping.
18 | *
19 | * @author Cedrick LUNVEN (@clunven)
20 | */
21 | @Singleton
22 | public class TodoServicesCassandraOM implements TodoService {
23 |
24 | /** Driver Dao. */
25 | private TodoItemDao todoDao;
26 |
27 | /**
28 | * Constructor with parameters.
29 | *
30 | * @param cqlSession
31 | * current cqlSession
32 | */
33 | public TodoServicesCassandraOM(CqlSession cqlSession) {
34 | todoDao = TodoItemMapper
35 | .builder(cqlSession)
36 | .withDefaultKeyspace(cqlSession.getKeyspace().get())
37 | .build()
38 | .todoItemDao();
39 | }
40 |
41 | @Override
42 | public TodoDto save(TodoDto todo) {
43 | if(null == todo.getItemId()) todo.setItemId(Uuids.timeBased());
44 | todoDao.save(fromDtoToEntity(todo));
45 | return todo;
46 | }
47 |
48 | @Override
49 | public Optional findById(String userId, UUID itemId) {
50 | return todoDao.findById(userId, itemId).map(this::fromEntityToDto);
51 | }
52 |
53 | @Override
54 | public List findByUser(String userId) {
55 | return todoDao.findByUser(userId)
56 | .all().stream()
57 | .map(this::fromEntityToDto)
58 | .collect(Collectors.toList());
59 | }
60 |
61 | @Override
62 | public void deleteById(String userId, UUID itemId) {
63 | todoDao.deleteById(userId, itemId);
64 | }
65 |
66 | @Override
67 | public void deleteByUser(String userId) {
68 | todoDao.deleteByUser(userId);
69 | }
70 |
71 | @Override
72 | @Query("truncate todoitems")
73 | public void deleteAll() {}
74 |
75 | private TodoItem fromDtoToEntity(TodoDto todo) {
76 | TodoItem ti = new TodoItem();
77 | ti.setCompleted(todo.getCompleted());
78 | ti.setItemId(todo.getItemId());
79 | ti.setTitle(todo.getTitle());
80 | ti.setUserId(todo.getUserId());
81 | return ti;
82 | }
83 |
84 | private TodoDto fromEntityToDto(TodoItem ti) {
85 | TodoDto dto = new TodoDto();
86 | dto.setCompleted(ti.getCompleted());
87 | dto.setItemId(ti.getItemId());
88 | dto.setTitle(ti.getTitle());
89 | dto.setUserId(ti.getUserId());
90 | return dto;
91 | }
92 | }
93 |
--------------------------------------------------------------------------------
/labs/lab6_quarkus/src/main/java/com/datastaxdev/todo/cassandra/TodoServicesCassandraOM.java:
--------------------------------------------------------------------------------
1 | package com.datastaxdev.todo.cassandra;
2 |
3 | import java.util.List;
4 | import java.util.Optional;
5 | import java.util.UUID;
6 | import java.util.stream.Collectors;
7 |
8 | import javax.enterprise.context.ApplicationScoped;
9 |
10 | import com.datastax.oss.driver.api.core.CqlSession;
11 | import com.datastax.oss.driver.api.core.uuid.Uuids;
12 | import com.datastax.oss.driver.api.mapper.annotations.Query;
13 | import com.datastaxdev.todo.TodoDto;
14 | import com.datastaxdev.todo.TodoService;
15 |
16 | /**
17 | * Implementation of the service with ObjectMapping.
18 | *
19 | * @author Cedrick LUNVEN (@clunven)
20 | */
21 | @ApplicationScoped
22 | public class TodoServicesCassandraOM implements TodoService {
23 |
24 | /** Driver Dao. */
25 | private TodoItemDao todoDao;
26 |
27 | /**
28 | * Constructor with parameters.
29 | *
30 | * @param cqlSession
31 | * current cqlSession
32 | */
33 | public TodoServicesCassandraOM(CqlSession cqlSession) {
34 | todoDao = TodoItemMapper
35 | .builder(cqlSession)
36 | .withDefaultKeyspace(cqlSession.getKeyspace().get())
37 | .build()
38 | .todoItemDao();
39 | }
40 |
41 | @Override
42 | public TodoDto save(TodoDto todo) {
43 | if(null == todo.getItemId()) todo.setItemId(Uuids.timeBased());
44 | todoDao.save(fromDtoToEntity(todo));
45 | return todo;
46 | }
47 |
48 | @Override
49 | public Optional findById(String userId, UUID itemId) {
50 | return todoDao.findById(userId, itemId).map(this::fromEntityToDto);
51 | }
52 |
53 | @Override
54 | public List findByUser(String userId) {
55 | return todoDao.findByUser(userId)
56 | .all().stream()
57 | .map(this::fromEntityToDto)
58 | .collect(Collectors.toList());
59 | }
60 |
61 | @Override
62 | public void deleteById(String userId, UUID itemId) {
63 | todoDao.deleteById(userId, itemId);
64 | }
65 |
66 | @Override
67 | public void deleteByUser(String userId) {
68 | todoDao.deleteByUser(userId);
69 | }
70 |
71 | @Override
72 | @Query("truncate todoitems")
73 | public void deleteAll() {}
74 |
75 | private TodoItem fromDtoToEntity(TodoDto todo) {
76 | TodoItem ti = new TodoItem();
77 | ti.setCompleted(todo.getCompleted());
78 | ti.setItemId(todo.getItemId());
79 | ti.setTitle(todo.getTitle());
80 | ti.setUserId(todo.getUserId());
81 | return ti;
82 | }
83 |
84 | private TodoDto fromEntityToDto(TodoItem ti) {
85 | TodoDto dto = new TodoDto();
86 | dto.setCompleted(ti.getCompleted());
87 | dto.setItemId(ti.getItemId());
88 | dto.setTitle(ti.getTitle());
89 | dto.setUserId(ti.getUserId());
90 | return dto;
91 | }
92 | }
93 |
--------------------------------------------------------------------------------
/labs/lab4_cassandra_drivers/src/main/java/com/datastax/samples/CqlSessionProvider.java:
--------------------------------------------------------------------------------
1 | package com.datastax.samples;
2 |
3 | import java.net.InetSocketAddress;
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.samples.schema.SchemaConstants;
11 |
12 | /**
13 | * This me
14 | * You can run the LABS locally, in gitpod with Docker or with Astra.
15 | *
16 | */
17 | public class CqlSessionProvider implements SchemaConstants{
18 |
19 | /** Logger for the class. */
20 | static Logger LOGGER = LoggerFactory.getLogger(CqlSessionProvider.class);
21 |
22 | public static final String LOCAL_DATACENTER = "dc1";
23 | public static final String CONTACT_POINT = "localhost";
24 | public static final int CONTACT_POINT_PORT = 9042;
25 | public static final String ASTRA_USERNAME = "token";
26 | public static final String ASTRA_PASSWORD = "";
27 | public static final String ASTRA_BUNDLE = "/home/gitpod/.cassandra/bootstrap.zip";
28 |
29 | private static CqlSessionProvider _instance;
30 |
31 | /** Singleton we would like to use everywhere. */
32 | private CqlSession cqlSession;
33 |
34 | /* Utile pour creer un keysa
35 | private CqlSession cqlSessionAdmin;
36 |
37 | /**
38 | * Initialization of CqlSession
39 | */
40 | private CqlSessionProvider() {
41 | LOGGER.info("Creating your CqlSession to Cassandra...");
42 | cqlSession = connectToLocalCassandra();
43 | //cqlSession = connectoToAstra();
44 | LOGGER.info("+ [OK] Your are connected.");
45 | }
46 |
47 | /**
48 | * Getter for cqlSession.
49 | *
50 | * @return cqlSession
51 | */
52 | public CqlSession getSession() {
53 | return cqlSession;
54 | }
55 |
56 | /**
57 | * Create a CqlSession.
58 | *
59 | * @return
60 | */
61 | protected static synchronized CqlSessionProvider getInstance() {
62 | if (_instance == null) {
63 | _instance = new CqlSessionProvider();
64 | }
65 | return _instance;
66 | }
67 |
68 | protected static CqlSession connectToLocalCassandra() {
69 | LOGGER.info("+ Connecting to [LOCAL CASSANDRA]");
70 | return CqlSession.builder()
71 | .addContactPoint(new InetSocketAddress(CONTACT_POINT, CONTACT_POINT_PORT))
72 | .withLocalDatacenter(LOCAL_DATACENTER)
73 | .withKeyspace(KEYSPACE_NAME)
74 | .build();
75 | }
76 |
77 | protected static CqlSession connectoToAstra() {
78 | LOGGER.info("+ Connecting to [ASTRA]");
79 | return CqlSession.builder()
80 | .withCloudSecureConnectBundle(Paths.get(ASTRA_BUNDLE))
81 | .withAuthCredentials(ASTRA_USERNAME, ASTRA_PASSWORD)
82 | .withKeyspace(KEYSPACE_NAME)
83 | .build();
84 | }
85 |
86 |
87 | }
88 |
--------------------------------------------------------------------------------
/labs/lab6_quarkus/src/main/java/com/datastaxdev/todo/cassandra/TodoItem.java:
--------------------------------------------------------------------------------
1 | package com.datastaxdev.todo.cassandra;
2 |
3 | import static com.datastaxdev.todo.cassandra.TodoServiceCassandraCql.TABLE_TODOITEMS;
4 | import static com.datastaxdev.todo.cassandra.TodoServiceCassandraCql.TODO_COMPLETED;
5 | import static com.datastaxdev.todo.cassandra.TodoServiceCassandraCql.TODO_ITEM_ID;
6 | import static com.datastaxdev.todo.cassandra.TodoServiceCassandraCql.TODO_TITLE;
7 | import static com.datastaxdev.todo.cassandra.TodoServiceCassandraCql.TODO_USER_ID;
8 |
9 | import java.util.UUID;
10 |
11 | import com.datastax.oss.driver.api.mapper.annotations.ClusteringColumn;
12 | import com.datastax.oss.driver.api.mapper.annotations.CqlName;
13 | import com.datastax.oss.driver.api.mapper.annotations.Entity;
14 | import com.datastax.oss.driver.api.mapper.annotations.PartitionKey;
15 |
16 | @Entity
17 | @CqlName(TABLE_TODOITEMS)
18 | public class TodoItem {
19 |
20 | @PartitionKey
21 | @CqlName(TODO_USER_ID)
22 | private String userId;
23 |
24 | @ClusteringColumn
25 | @CqlName(TODO_ITEM_ID)
26 | private UUID itemId;
27 |
28 | @CqlName(TODO_TITLE)
29 | private String title;
30 |
31 | @CqlName(TODO_COMPLETED)
32 | private Boolean completed;
33 |
34 | /**
35 | * Getter accessor for attribute 'userId'.
36 | *
37 | * @return
38 | * current value of 'userId'
39 | */
40 | public String getUserId() {
41 | return userId;
42 | }
43 |
44 | /**
45 | * Setter accessor for attribute 'userId'.
46 | * @param userId
47 | * new value for 'userId '
48 | */
49 | public void setUserId(String userId) {
50 | this.userId = userId;
51 | }
52 |
53 | /**
54 | * Getter accessor for attribute 'itemId'.
55 | *
56 | * @return
57 | * current value of 'itemId'
58 | */
59 | public UUID getItemId() {
60 | return itemId;
61 | }
62 |
63 | /**
64 | * Setter accessor for attribute 'itemId'.
65 | * @param itemId
66 | * new value for 'itemId '
67 | */
68 | public void setItemId(UUID itemId) {
69 | this.itemId = itemId;
70 | }
71 |
72 | /**
73 | * Getter accessor for attribute 'title'.
74 | *
75 | * @return
76 | * current value of 'title'
77 | */
78 | public String getTitle() {
79 | return title;
80 | }
81 |
82 | /**
83 | * Setter accessor for attribute 'title'.
84 | * @param title
85 | * new value for 'title '
86 | */
87 | public void setTitle(String title) {
88 | this.title = title;
89 | }
90 |
91 | /**
92 | * Getter accessor for attribute 'completed'.
93 | *
94 | * @return
95 | * current value of 'completed'
96 | */
97 | public Boolean getCompleted() {
98 | return completed;
99 | }
100 |
101 | /**
102 | * Setter accessor for attribute 'completed'.
103 | * @param completed
104 | * new value for 'completed '
105 | */
106 | public void setCompleted(Boolean completed) {
107 | this.completed = completed;
108 | }
109 | }
110 |
--------------------------------------------------------------------------------
/labs/lab7_micronaut/src/main/java/com/datastaxdev/todo/cassandra/TodoItem.java:
--------------------------------------------------------------------------------
1 | package com.datastaxdev.todo.cassandra;
2 |
3 | import static com.datastaxdev.todo.cassandra.TodoServiceCassandraCql.TABLE_TODOITEMS;
4 | import static com.datastaxdev.todo.cassandra.TodoServiceCassandraCql.TODO_COMPLETED;
5 | import static com.datastaxdev.todo.cassandra.TodoServiceCassandraCql.TODO_ITEM_ID;
6 | import static com.datastaxdev.todo.cassandra.TodoServiceCassandraCql.TODO_TITLE;
7 | import static com.datastaxdev.todo.cassandra.TodoServiceCassandraCql.TODO_USER_ID;
8 |
9 | import java.util.UUID;
10 |
11 | import com.datastax.oss.driver.api.mapper.annotations.ClusteringColumn;
12 | import com.datastax.oss.driver.api.mapper.annotations.CqlName;
13 | import com.datastax.oss.driver.api.mapper.annotations.Entity;
14 | import com.datastax.oss.driver.api.mapper.annotations.PartitionKey;
15 |
16 | @Entity
17 | @CqlName(TABLE_TODOITEMS)
18 | public class TodoItem {
19 |
20 | @PartitionKey
21 | @CqlName(TODO_USER_ID)
22 | private String userId;
23 |
24 | @ClusteringColumn
25 | @CqlName(TODO_ITEM_ID)
26 | private UUID itemId;
27 |
28 | @CqlName(TODO_TITLE)
29 | private String title;
30 |
31 | @CqlName(TODO_COMPLETED)
32 | private Boolean completed;
33 |
34 | /**
35 | * Getter accessor for attribute 'userId'.
36 | *
37 | * @return
38 | * current value of 'userId'
39 | */
40 | public String getUserId() {
41 | return userId;
42 | }
43 |
44 | /**
45 | * Setter accessor for attribute 'userId'.
46 | * @param userId
47 | * new value for 'userId '
48 | */
49 | public void setUserId(String userId) {
50 | this.userId = userId;
51 | }
52 |
53 | /**
54 | * Getter accessor for attribute 'itemId'.
55 | *
56 | * @return
57 | * current value of 'itemId'
58 | */
59 | public UUID getItemId() {
60 | return itemId;
61 | }
62 |
63 | /**
64 | * Setter accessor for attribute 'itemId'.
65 | * @param itemId
66 | * new value for 'itemId '
67 | */
68 | public void setItemId(UUID itemId) {
69 | this.itemId = itemId;
70 | }
71 |
72 | /**
73 | * Getter accessor for attribute 'title'.
74 | *
75 | * @return
76 | * current value of 'title'
77 | */
78 | public String getTitle() {
79 | return title;
80 | }
81 |
82 | /**
83 | * Setter accessor for attribute 'title'.
84 | * @param title
85 | * new value for 'title '
86 | */
87 | public void setTitle(String title) {
88 | this.title = title;
89 | }
90 |
91 | /**
92 | * Getter accessor for attribute 'completed'.
93 | *
94 | * @return
95 | * current value of 'completed'
96 | */
97 | public Boolean getCompleted() {
98 | return completed;
99 | }
100 |
101 | /**
102 | * Setter accessor for attribute 'completed'.
103 | * @param completed
104 | * new value for 'completed '
105 | */
106 | public void setCompleted(Boolean completed) {
107 | this.completed = completed;
108 | }
109 | }
110 |
--------------------------------------------------------------------------------
/labs/lab6_quarkus/src/main/java/com/datastaxdev/todo/web/Todo.java:
--------------------------------------------------------------------------------
1 | package com.datastaxdev.todo.web;
2 |
3 | import java.util.UUID;
4 |
5 | /**
6 | * Implementa
7 | *
8 | * @author Cedrick LUNVEN (@clunven)
9 | */
10 | public class Todo {
11 |
12 | private String url;
13 | private UUID uuid;
14 | private String title;
15 | private boolean completed = false;
16 | private Integer order = 0;
17 |
18 | public Todo() {}
19 |
20 | public Todo(String title, Integer order) {
21 | this.uuid = UUID.randomUUID();
22 | this.title = title;
23 | this.order = order;
24 | }
25 |
26 | public Todo(String title, int order, boolean completed) {
27 | this(title, order);
28 | this.completed = completed;
29 | }
30 |
31 | public void setUrl(String myUrl) {
32 | this.url = myUrl;
33 | }
34 |
35 | /**
36 | * Getter accessor for attribute 'uuid'.
37 | *
38 | * @return
39 | * current value of 'uuid'
40 | */
41 | public UUID getUuid() {
42 | return uuid;
43 | }
44 |
45 | /**
46 | * Setter accessor for attribute 'uuid'.
47 | * @param uuid
48 | * new value for 'uuid '
49 | */
50 | public void setUuid(UUID uuid) {
51 | this.uuid = uuid;
52 | }
53 |
54 | /**
55 | * Getter accessor for attribute 'title'.
56 | *
57 | * @return
58 | * current value of 'title'
59 | */
60 | public String getTitle() {
61 | return title;
62 | }
63 |
64 | /**
65 | * Setter accessor for attribute 'title'.
66 | * @param title
67 | * new value for 'title '
68 | */
69 | public void setTitle(String title) {
70 | this.title = title;
71 | }
72 |
73 | /**
74 | * Getter accessor for attribute 'completed'.
75 | *
76 | * @return
77 | * current value of 'completed'
78 | */
79 | public boolean isCompleted() {
80 | return completed;
81 | }
82 |
83 | /**
84 | * Setter accessor for attribute 'completed'.
85 | * @param completed
86 | * new value for 'completed '
87 | */
88 | public void setCompleted(boolean completed) {
89 | this.completed = completed;
90 | }
91 |
92 | /**
93 | * Getter accessor for attribute 'order'.
94 | *
95 | * @return
96 | * current value of 'order'
97 | */
98 | public Integer getOrder() {
99 | return order;
100 | }
101 |
102 | /**
103 | * Setter accessor for attribute 'order'.
104 | * @param order
105 | * new value for 'order '
106 | */
107 | public void setOrder(Integer order) {
108 | this.order = order;
109 | }
110 |
111 | /**
112 | * Getter accessor for attribute 'url'.
113 | *
114 | * @return
115 | * current value of 'url'
116 | */
117 | public String getUrl() {
118 | return url;
119 | }
120 |
121 | /** {@inheritDoc} */
122 | @Override
123 | public String toString() {
124 | return "Todo [url=" + url + ", uuid=" + uuid + ", title=" + title + ", completed=" + completed + ", order=" + order + "]";
125 | }
126 | }
127 |
--------------------------------------------------------------------------------
/labs/lab7_micronaut/src/main/java/com/datastaxdev/todo/web/Todo.java:
--------------------------------------------------------------------------------
1 | package com.datastaxdev.todo.web;
2 |
3 | import java.util.UUID;
4 |
5 | /**
6 | * Implementa
7 | *
8 | * @author Cedrick LUNVEN (@clunven)
9 | */
10 | public class Todo {
11 |
12 | private String url;
13 | private UUID uuid;
14 | private String title;
15 | private boolean completed = false;
16 | private Integer order = 0;
17 |
18 | public Todo() {}
19 |
20 | public Todo(String title, Integer order) {
21 | this.uuid = UUID.randomUUID();
22 | this.title = title;
23 | this.order = order;
24 | }
25 |
26 | public Todo(String title, int order, boolean completed) {
27 | this(title, order);
28 | this.completed = completed;
29 | }
30 |
31 | public void setUrl(String myUrl) {
32 | this.url = myUrl;
33 | }
34 |
35 | /**
36 | * Getter accessor for attribute 'uuid'.
37 | *
38 | * @return
39 | * current value of 'uuid'
40 | */
41 | public UUID getUuid() {
42 | return uuid;
43 | }
44 |
45 | /**
46 | * Setter accessor for attribute 'uuid'.
47 | * @param uuid
48 | * new value for 'uuid '
49 | */
50 | public void setUuid(UUID uuid) {
51 | this.uuid = uuid;
52 | }
53 |
54 | /**
55 | * Getter accessor for attribute 'title'.
56 | *
57 | * @return
58 | * current value of 'title'
59 | */
60 | public String getTitle() {
61 | return title;
62 | }
63 |
64 | /**
65 | * Setter accessor for attribute 'title'.
66 | * @param title
67 | * new value for 'title '
68 | */
69 | public void setTitle(String title) {
70 | this.title = title;
71 | }
72 |
73 | /**
74 | * Getter accessor for attribute 'completed'.
75 | *
76 | * @return
77 | * current value of 'completed'
78 | */
79 | public boolean isCompleted() {
80 | return completed;
81 | }
82 |
83 | /**
84 | * Setter accessor for attribute 'completed'.
85 | * @param completed
86 | * new value for 'completed '
87 | */
88 | public void setCompleted(boolean completed) {
89 | this.completed = completed;
90 | }
91 |
92 | /**
93 | * Getter accessor for attribute 'order'.
94 | *
95 | * @return
96 | * current value of 'order'
97 | */
98 | public Integer getOrder() {
99 | return order;
100 | }
101 |
102 | /**
103 | * Setter accessor for attribute 'order'.
104 | * @param order
105 | * new value for 'order '
106 | */
107 | public void setOrder(Integer order) {
108 | this.order = order;
109 | }
110 |
111 | /**
112 | * Getter accessor for attribute 'url'.
113 | *
114 | * @return
115 | * current value of 'url'
116 | */
117 | public String getUrl() {
118 | return url;
119 | }
120 |
121 | /** {@inheritDoc} */
122 | @Override
123 | public String toString() {
124 | return "Todo [url=" + url + ", uuid=" + uuid + ", title=" + title + ", completed=" + completed + ", order=" + order + "]";
125 | }
126 | }
127 |
--------------------------------------------------------------------------------
/labs/lab5_spring_data/src/main/java/com/datastax/workshop/todo/Todo.java:
--------------------------------------------------------------------------------
1 | package com.datastax.workshop.todo;
2 |
3 | import java.util.UUID;
4 |
5 | import javax.servlet.http.HttpServletRequest;
6 |
7 | public class Todo {
8 |
9 | private String url;
10 | private UUID uuid;
11 | private String title;
12 | private boolean completed = false;
13 | private int order = 0;
14 |
15 | public Todo() {}
16 |
17 | public Todo(String title, int order) {
18 | this.uuid = UUID.randomUUID();
19 | this.title = title;
20 | this.order = order;
21 | }
22 |
23 | public Todo(String title, int order, boolean completed) {
24 | this(title, order);
25 | this.completed = completed;
26 | }
27 |
28 | public Todo setUrl(HttpServletRequest req) {
29 | if (url == null) {
30 | String reqUrl = req.getRequestURL().toString();
31 | url = reqUrl.contains("gitpod") ? reqUrl.replaceAll("http", "https") : reqUrl;
32 | url += uuid;
33 | }
34 | return this;
35 | }
36 |
37 | public Todo setUrl(String myUrl) {
38 | if (url == null) {
39 | url = myUrl.contains("gitpod") ? myUrl.replaceAll("http", "https") : myUrl;
40 | }
41 | return this;
42 | }
43 |
44 | /**
45 | * Getter accessor for attribute 'uuid'.
46 | *
47 | * @return
48 | * current value of 'uuid'
49 | */
50 | public UUID getUuid() {
51 | return uuid;
52 | }
53 |
54 | /**
55 | * Setter accessor for attribute 'uuid'.
56 | * @param uuid
57 | * new value for 'uuid '
58 | */
59 | public void setUuid(UUID uuid) {
60 | this.uuid = uuid;
61 | }
62 |
63 | /**
64 | * Getter accessor for attribute 'title'.
65 | *
66 | * @return
67 | * current value of 'title'
68 | */
69 | public String getTitle() {
70 | return title;
71 | }
72 |
73 | /**
74 | * Setter accessor for attribute 'title'.
75 | * @param title
76 | * new value for 'title '
77 | */
78 | public void setTitle(String title) {
79 | this.title = title;
80 | }
81 |
82 | /**
83 | * Getter accessor for attribute 'completed'.
84 | *
85 | * @return
86 | * current value of 'completed'
87 | */
88 | public boolean isCompleted() {
89 | return completed;
90 | }
91 |
92 | /**
93 | * Setter accessor for attribute 'completed'.
94 | * @param completed
95 | * new value for 'completed '
96 | */
97 | public void setCompleted(boolean completed) {
98 | this.completed = completed;
99 | }
100 |
101 | /**
102 | * Getter accessor for attribute 'order'.
103 | *
104 | * @return
105 | * current value of 'order'
106 | */
107 | public int getOrder() {
108 | return order;
109 | }
110 |
111 | /**
112 | * Setter accessor for attribute 'order'.
113 | * @param order
114 | * new value for 'order '
115 | */
116 | public void setOrder(int order) {
117 | this.order = order;
118 | }
119 |
120 | /**
121 | * Getter accessor for attribute 'url'.
122 | *
123 | * @return
124 | * current value of 'url'
125 | */
126 | public String getUrl() {
127 | return url;
128 | }
129 |
130 |
131 | }
132 |
--------------------------------------------------------------------------------
/labs/lab4_cassandra_drivers/pom.xml:
--------------------------------------------------------------------------------
1 |
2 |
5 | 4.0.0
6 | com.datastax
7 | lab4-cassandra-drivers
8 | 1.0-SNAPSHOT
9 | jar
10 | lab4-cassandra-drivers
11 |
12 |
13 | 4.13.0
14 | 1.2.3
15 | 5.8.2
16 | 1.8.2
17 | 11
18 | UTF-8
19 |
20 |
21 |
22 |
23 |
24 |
25 | com.datastax.oss
26 | java-driver-core
27 | ${cassandra.driver.oss.version}
28 |
29 |
30 | ch.qos.logback
31 | logback-classic
32 | ${logback.version}
33 |
34 |
35 |
36 |
37 | com.datastax.oss
38 | java-driver-query-builder
39 | ${cassandra.driver.oss.version}
40 |
41 |
42 | com.datastax.oss
43 | java-driver-mapper-runtime
44 | ${cassandra.driver.oss.version}
45 |
46 |
47 |
48 |
49 | io.projectreactor
50 | reactor-core
51 | 3.3.3.RELEASE
52 |
53 |
54 |
55 |
56 | org.junit.jupiter
57 | junit-jupiter-api
58 | ${junit.version}
59 | test
60 |
61 |
62 | org.junit.jupiter
63 | junit-jupiter-engine
64 | ${junit.version}
65 | test
66 |
67 |
68 | org.junit.platform
69 | junit-platform-runner
70 | ${junit-platform.version}
71 | test
72 |
73 |
74 |
75 |
76 |
77 |
78 |
79 |
80 |
81 |
82 | org.apache.maven.plugins
83 | maven-compiler-plugin
84 | 3.8.1
85 |
86 | ${java.version}
87 | ${java.version}
88 | ${java.version}
89 |
90 |
91 | com.datastax.oss
92 | java-driver-mapper-processor
93 | ${cassandra.driver.oss.version}
94 |
95 |
96 |
97 |
98 |
99 |
100 |
101 |
102 |
103 |
--------------------------------------------------------------------------------
/labs/lab4_cassandra_drivers/src/main/java/com/datastax/samples/schema/SchemaConstants.java:
--------------------------------------------------------------------------------
1 | package com.datastax.samples.schema;
2 |
3 | /**
4 | * Externalization of schema constant.
5 | */
6 | public interface SchemaConstants {
7 |
8 | String KEYSPACE_NAME = "devoxx_drivers";
9 |
10 | /**
11 | * Will be used for this table:
12 | *
13 | * CREATE TABLE IF NOT EXISTS users (
14 | * email text,
15 | * firstname text,
16 | * lastname text,
17 | * PRIMARY KEY (email)
18 | * );
19 | */
20 | String USER_TABLENAME = "users";
21 | String USER_EMAIL = "email";
22 | String USER_FIRSTNAME = "firstname";
23 | String USER_LASTNAME = "lastname";
24 |
25 | /**
26 | * CREATE TYPE IF NOT EXISTS video_format (
27 | * width int,
28 | * height int
29 | *);
30 | */
31 | String UDT_VIDEO_FORMAT_NAME = "video_format";
32 | String UDT_VIDEO_FORMAT_WIDTH = "width";
33 | String UDT_VIDEO_FORMAT_HEIGHT = "height";
34 |
35 | /**
36 | * CREATE TABLE IF NOT EXISTS videos (
37 | * videoid uuid,
38 | * title text,
39 | * upload timestamp,
40 | * email text,
41 | * url text,
42 | * tags set ,
43 | * frames list,
44 | * formats map >,
45 | * PRIMARY KEY (videoid)
46 | * );
47 | **/
48 | String VIDEO_TABLENAME = "videos";
49 | String VIDEO_VIDEOID = "videoid";
50 | String VIDEO_TITLE = "title";
51 | String VIDEO_UPLOAD = "upload";
52 | String VIDEO_USER_EMAIL = "email";
53 | String VIDEO_FRAMES = "frames";
54 | String VIDEO_URL = "url";
55 | String VIDEO_TAGS = "tags";
56 | String VIDEO_FORMAT = "formats";
57 |
58 | /**
59 | * CREATE TABLE IF NOT EXISTS videos_views (
60 | * videoid uuid,
61 | * views counter,
62 | * PRIMARY KEY (videoid)
63 | * );
64 | */
65 | String VIDEO_VIEWS_TABLENAME = "videos_views";
66 | String VIDEO_VIEWS_VIDEOID = "videoid";
67 | String VIDEO_VIEWS_VIEWS = "views";
68 |
69 | /**
70 | * CREATE TABLE IF NOT EXISTS comments_by_video (
71 | * videoid uuid,
72 | * commentid timeuuid,
73 | * userid uuid,
74 | * comment text,
75 | * PRIMARY KEY (videoid, commentid)
76 | * ) WITH CLUSTERING ORDER BY (commentid DESC);
77 | *
78 | *
79 | * CREATE TABLE IF NOT EXISTS comments_by_user (
80 | * userid uuid,
81 | * commentid timeuuid,
82 | * videoid uuid,
83 | * comment text,
84 | * PRIMARY KEY (userid, commentid)
85 | * ) WITH CLUSTERING ORDER BY (commentid DESC);
86 | */
87 | String COMMENT_BY_VIDEO_TABLENAME = "comments_by_video";
88 | String COMMENT_BY_VIDEO_VIDEOID = "videoid";
89 | String COMMENT_BY_VIDEO_COMMENTID = "commentid";
90 | String COMMENT_BY_VIDEO_USERID = "userid";
91 | String COMMENT_BY_VIDEO_COMMENT = "comment";
92 | String COMMENT_BY_USER_TABLENAME = "comments_by_user";
93 | String COMMENT_BY_USER_VIDEOID = COMMENT_BY_VIDEO_VIDEOID;
94 | String COMMENT_BY_USER_COMMENTID = COMMENT_BY_VIDEO_COMMENTID;
95 | String COMMENT_BY_USER_USERID = COMMENT_BY_VIDEO_USERID;
96 | String COMMENT_BY_USER_COMMENT = COMMENT_BY_VIDEO_COMMENT;
97 |
98 | String FILES_TABLENAME = "files";
99 | String FILES_FILENAME = "filename";
100 | String FILES_EXTENSION = "extension";
101 | String FILES_UPLOAD = "upload";
102 | String FILES_BINARY = "binary";
103 |
104 | }
105 |
--------------------------------------------------------------------------------
/labs/lab4_cassandra_drivers/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 |
--------------------------------------------------------------------------------
/labs/lab4_cassandra_drivers/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.schema.SchemaConstants;
10 |
11 | /**
12 | * Bean standing for comment on video.
13 | *
14 | * @author DataStax Developer Advocates team.
15 | */
16 | public class Comment implements Serializable, SchemaConstants {
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 |
--------------------------------------------------------------------------------
/labs/lab5_spring_data/src/main/java/com/datastax/workshop/todo/TodoEntity.java:
--------------------------------------------------------------------------------
1 | package com.datastax.workshop.todo;
2 |
3 | import java.util.UUID;
4 |
5 | import org.springframework.data.cassandra.core.mapping.CassandraType;
6 | import org.springframework.data.cassandra.core.mapping.CassandraType.Name;
7 | import org.springframework.data.cassandra.core.mapping.Column;
8 | import org.springframework.data.cassandra.core.mapping.PrimaryKey;
9 | import org.springframework.data.cassandra.core.mapping.Table;
10 |
11 |
12 | @Table(value = TodoEntity.TABLENAME)
13 | public class TodoEntity {
14 |
15 | public static final String TABLENAME = "todos";
16 | public static final String COLUMN_UID = "uid";
17 | public static final String COLUMN_TITLE = "title";
18 | public static final String COLUMN_COMPLETED = "completed";
19 | public static final String COLUMN_ORDER = "offset";
20 |
21 | @PrimaryKey
22 | @Column(COLUMN_UID)
23 | @CassandraType(type = Name.UUID)
24 | private UUID uid;
25 |
26 | @Column(COLUMN_TITLE)
27 | @CassandraType(type = Name.TEXT)
28 | private String title;
29 |
30 | @Column(COLUMN_COMPLETED)
31 | @CassandraType(type = Name.BOOLEAN)
32 | private boolean completed = false;
33 |
34 | @Column(COLUMN_ORDER)
35 | @CassandraType(type = Name.INT)
36 | private int order = 0;
37 |
38 |
39 | public TodoEntity() {}
40 |
41 | public TodoEntity(UUID uid, String title, boolean completed, int order) {
42 | super();
43 | this.uid = uid;
44 | this.title = title;
45 | this.completed = completed;
46 | this.order = order;
47 | }
48 |
49 | public TodoEntity(String title, int offset) {
50 | this(UUID.randomUUID(), title, false, offset);
51 | }
52 |
53 |
54 |
55 | /**
56 | * Getter accessor for attribute 'uid'.
57 | *
58 | * @return
59 | * current value of 'uid'
60 | */
61 | public UUID getUid() {
62 | return uid;
63 | }
64 |
65 | /**
66 | * Setter accessor for attribute 'uid'.
67 | * @param uid
68 | * new value for 'uid '
69 | */
70 | public void setUid(UUID uid) {
71 | this.uid = uid;
72 | }
73 |
74 | /**
75 | * Getter accessor for attribute 'title'.
76 | *
77 | * @return
78 | * current value of 'title'
79 | */
80 | public String getTitle() {
81 | return title;
82 | }
83 |
84 | /**
85 | * Setter accessor for attribute 'title'.
86 | * @param title
87 | * new value for 'title '
88 | */
89 | public void setTitle(String title) {
90 | this.title = title;
91 | }
92 |
93 | /**
94 | * Getter accessor for attribute 'completed'.
95 | *
96 | * @return
97 | * current value of 'completed'
98 | */
99 | public boolean isCompleted() {
100 | return completed;
101 | }
102 |
103 | /**
104 | * Setter accessor for attribute 'completed'.
105 | * @param completed
106 | * new value for 'completed '
107 | */
108 | public void setCompleted(boolean completed) {
109 | this.completed = completed;
110 | }
111 |
112 | /**
113 | * Getter accessor for attribute 'order'.
114 | *
115 | * @return
116 | * current value of 'order'
117 | */
118 | public int getOrder() {
119 | return order;
120 | }
121 |
122 | /**
123 | * Setter accessor for attribute 'order'.
124 | * @param order
125 | * new value for 'order '
126 | */
127 | public void setOrder(int order) {
128 | this.order = order;
129 | }
130 |
131 | /** {@inheritDoc} */
132 | @Override
133 | public String toString() {
134 | return "+ TodoEntity [uid=" + uid + ", title=" + title + ", completed=" + completed + ", order=" + order + "]";
135 | }
136 |
137 | }
138 |
--------------------------------------------------------------------------------
/labs/lab4_cassandra_drivers/src/main/java/com/datastax/samples/E05_Paging.java:
--------------------------------------------------------------------------------
1 | package com.datastax.samples;
2 |
3 | import static com.datastax.samples.schema.SchemaUtils.createTableUser;
4 | import static com.datastax.samples.schema.SchemaUtils.truncateTable;
5 |
6 | import java.nio.ByteBuffer;
7 | import java.time.Duration;
8 | import java.util.Iterator;
9 |
10 | import org.slf4j.Logger;
11 | import org.slf4j.LoggerFactory;
12 |
13 | import com.datastax.oss.driver.api.core.ConsistencyLevel;
14 | import com.datastax.oss.driver.api.core.CqlSession;
15 | import com.datastax.oss.driver.api.core.cql.BatchStatement;
16 | import com.datastax.oss.driver.api.core.cql.BatchStatementBuilder;
17 | import com.datastax.oss.driver.api.core.cql.DefaultBatchType;
18 | import com.datastax.oss.driver.api.core.cql.PreparedStatement;
19 | import com.datastax.oss.driver.api.core.cql.ResultSet;
20 | import com.datastax.oss.driver.api.core.cql.Row;
21 | import com.datastax.oss.driver.api.core.cql.SimpleStatement;
22 | import com.datastax.oss.driver.api.querybuilder.QueryBuilder;
23 | import com.datastax.oss.protocol.internal.util.Bytes;
24 | import com.datastax.samples.schema.SchemaConstants;
25 |
26 | public class E05_Paging implements SchemaConstants {
27 |
28 | private static Logger LOGGER = LoggerFactory.getLogger(E05_Paging.class);
29 |
30 | public static void main(String[] args) {
31 | try(CqlSession cqlSession = CqlSessionProvider.getInstance().getSession()) {
32 |
33 | createTableUser(cqlSession);
34 |
35 | truncateTable(cqlSession, USER_TABLENAME);
36 |
37 | PreparedStatement stmtCreateUser =
38 | cqlSession.prepare(QueryBuilder.insertInto(USER_TABLENAME)
39 | .value(USER_EMAIL, QueryBuilder.bindMarker())
40 | .value(USER_FIRSTNAME, QueryBuilder.bindMarker())
41 | .value(USER_LASTNAME, QueryBuilder.bindMarker())
42 | .build());
43 |
44 | // Adding 50 records in the table
45 | BatchStatementBuilder bb = BatchStatement.builder(DefaultBatchType.LOGGED);
46 | for (int i = 0; i < 50; i++) {
47 | bb.addStatement(stmtCreateUser.bind("user_" + i + "@sample.com", "user_" + i, "lastname"));
48 | }
49 | cqlSession.execute(bb.build());
50 | LOGGER.info("+ {} users have been created", 50);
51 |
52 | // Paged query
53 | SimpleStatement statement = QueryBuilder.selectFrom(USER_TABLENAME).all().build()
54 | .setPageSize(10) // 10 per pages
55 | .setTimeout(Duration.ofSeconds(1)) // 1s timeout
56 | .setConsistencyLevel(ConsistencyLevel.ONE);
57 | ResultSet page1 = cqlSession.execute(statement);
58 |
59 | // Checking
60 | LOGGER.info("+ Page 1 has {} items", page1.getAvailableWithoutFetching());
61 | Iterator page1Iter = page1.iterator();
62 | while (0 < page1.getAvailableWithoutFetching()) {
63 | LOGGER.info("Page1: " + page1Iter.next().getString(USER_EMAIL));
64 | }
65 |
66 | // Notice that items are NOT ordered (it uses the hashed token)
67 | // From this point if you invoke .next() driver will look for page2.
68 | // But we can invoke page2 directly: (useful for delay between calls)
69 | ByteBuffer pagingStateAsBytes = page1.getExecutionInfo().getPagingState();
70 |
71 | // If you need to to externalize this as a STRING
72 | Bytes.toHexString(pagingStateAsBytes);
73 | // If you need to go back to byteBuffer
74 | // ByteBuffer pagingStateAsBytesBack = Bytes.fromHexString(pageStateAsString);
75 |
76 | statement.setPagingState(pagingStateAsBytes);
77 | ResultSet page2 = cqlSession.execute(statement);
78 | LOGGER.info("+ Page 2 has {} items", page2.getAvailableWithoutFetching());
79 | }
80 | }
81 |
82 | }
83 |
--------------------------------------------------------------------------------
/labs/lab4_cassandra_drivers/src/main/java/com/datastax/samples/E11_LightweightTransactions.java:
--------------------------------------------------------------------------------
1 | package com.datastax.samples;
2 |
3 | import static com.datastax.samples.schema.SchemaUtils.createTableUser;
4 | import static com.datastax.samples.schema.SchemaUtils.truncateTable;
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.cql.PreparedStatement;
11 | import com.datastax.oss.driver.api.querybuilder.QueryBuilder;
12 | import com.datastax.samples.schema.SchemaConstants;
13 |
14 | public class E11_LightweightTransactions implements SchemaConstants {
15 |
16 | private static Logger LOGGER = LoggerFactory.getLogger(E11_LightweightTransactions.class);
17 |
18 | private static PreparedStatement stmtCreateUser;
19 | private static PreparedStatement stmtUpdateUserLwt;
20 |
21 | public static void main(String[] args) {
22 | try(CqlSession cqlSession = CqlSessionProvider.getInstance().getSession()) {
23 |
24 | // Use PreparedStatement for queries that are executed multiple times in your application
25 | prepareStatements(cqlSession);
26 |
27 | // Create working table User (if needed)
28 | createTableUser(cqlSession);
29 |
30 | // Empty tables for tests
31 | truncateTable(cqlSession, USER_TABLENAME);
32 |
33 | // Insert if not exist
34 | boolean first = createUserIfNotExist(cqlSession, "clun@sample.com", "Cedric", "Lunven");
35 | boolean second = createUserIfNotExist(cqlSession, "clun@sample.com", "Cedric", "Lunven");
36 | LOGGER.info("+ Created first time ? {} and second time {}", first, second);
37 |
38 | // Update if condition
39 | boolean applied1 = updateIf(cqlSession, "clun@sample.com", "Cedric", "BEST");
40 | boolean applied2 = updateIf(cqlSession, "clun@sample.com", "Cedrick", "Lunven");
41 | LOGGER.info("+ Applied when correct value ? {} and invalid value {}", applied1, applied2);
42 |
43 | }
44 | }
45 |
46 | /**
47 | * The resultset is applied only if the record is created. If not the resultSet is populated
48 | * with existing data in DB (read)
49 | */
50 | private static boolean createUserIfNotExist(CqlSession cqlSession, String email, String firstname, String lastname) {
51 | return cqlSession.execute(stmtCreateUser.bind(email, firstname, lastname)).wasApplied();
52 | }
53 |
54 | /**
55 | * Note: we named the parameters as they are not in the same order in the query.
56 | */
57 | private static boolean updateIf(CqlSession cqlSession, String email, String expectedFirstName, String newLastName) {
58 | return cqlSession.execute(stmtUpdateUserLwt.bind()
59 | .setString(USER_EMAIL, email)
60 | .setString(USER_FIRSTNAME, expectedFirstName)
61 | .setString(USER_LASTNAME, newLastName)).wasApplied();
62 | }
63 |
64 | /**
65 | * Documentation
66 | * https://docs.datastax.com/en/developer/java-driver/3.8/manual/statements/prepared/#prepared-statements
67 | */
68 | private static void prepareStatements(CqlSession cqlSession) {
69 |
70 | /*
71 | * INSERT INTO users (email, firstname, lastname)
72 | * VALUES(?,?,?)
73 | * IF NOT EXISTS
74 | */
75 | stmtCreateUser = cqlSession.prepare(QueryBuilder.insertInto(USER_TABLENAME)
76 | .value(USER_EMAIL, QueryBuilder.bindMarker())
77 | .value(USER_FIRSTNAME, QueryBuilder.bindMarker())
78 | .value(USER_LASTNAME, QueryBuilder.bindMarker())
79 | .ifNotExists()
80 | .build());
81 |
82 | /*
83 | * UPDATE users SET lastname=:lastname
84 | * WHERE email=:email
85 | * IF firstname=:firstname
86 | *
87 | * Operators available for LWT Condition:
88 | * =, <, <=, >, >=, != and IN
89 | */
90 | stmtUpdateUserLwt = cqlSession.prepare(QueryBuilder.update(USER_TABLENAME)
91 | .setColumn(USER_LASTNAME, QueryBuilder.bindMarker(USER_LASTNAME))
92 | .whereColumn(USER_EMAIL).isEqualTo(QueryBuilder.bindMarker(USER_EMAIL))
93 | .ifColumn(USER_FIRSTNAME).isEqualTo(QueryBuilder.bindMarker(USER_FIRSTNAME))
94 | .build());
95 | }
96 |
97 | }
98 |
--------------------------------------------------------------------------------
/labs/lab4_cassandra_drivers/src/main/java/com/datastax/samples/E12_ObjectMapping.java:
--------------------------------------------------------------------------------
1 | package com.datastax.samples;
2 |
3 | import static com.datastax.samples.schema.SchemaUtils.createTableCommentByUser;
4 | import static com.datastax.samples.schema.SchemaUtils.createTableCommentByVideo;
5 | import static com.datastax.samples.schema.SchemaUtils.truncateTable;
6 |
7 | import java.util.UUID;
8 |
9 | import org.slf4j.Logger;
10 | import org.slf4j.LoggerFactory;
11 |
12 | import com.datastax.oss.driver.api.core.CqlSession;
13 | import com.datastax.samples.objectmapping.Comment;
14 | import com.datastax.samples.objectmapping.CommentByUser;
15 | import com.datastax.samples.objectmapping.CommentByVideo;
16 | import com.datastax.samples.objectmapping.CommentDao;
17 | import com.datastax.samples.objectmapping.CommentDaoMapper;
18 | import com.datastax.samples.schema.SchemaConstants;
19 |
20 | public class E12_ObjectMapping implements SchemaConstants {
21 |
22 | private static Logger LOGGER = LoggerFactory.getLogger(E12_ObjectMapping.class);
23 |
24 | public static void main(String[] args) {
25 | try(CqlSession cqlSession = CqlSessionProvider.getInstance().getSession()) {
26 |
27 | // Create working table User (if needed)
28 | createTableCommentByUser(cqlSession);
29 | createTableCommentByVideo(cqlSession);
30 |
31 | // Comments are used in 2 queries, we need 2 tables to store it
32 | truncateTable(cqlSession, COMMENT_BY_USER_TABLENAME);
33 | truncateTable(cqlSession, COMMENT_BY_VIDEO_TABLENAME);
34 |
35 | // All logic is defined in Mapper/Dao/Entities in objectmapping package
36 | // Mapper required the table to exist
37 | CommentDao dao = CommentDaoMapper.builder(cqlSession)
38 | .withDefaultKeyspace(KEYSPACE_NAME)
39 | .build().commentDao();
40 |
41 | // DataSet
42 | UUID user_1 = UUID.randomUUID();UUID user_2 = UUID.randomUUID();
43 | UUID videoid_1 = UUID.randomUUID();UUID videoid_2 = UUID.randomUUID();
44 | Comment c1 = new Comment(user_1, videoid_1, "I am user1 and video1 is good");
45 | Comment c2 = new Comment(user_2, videoid_1, "I am user2 and video1 is bad");
46 | Comment c3 = new Comment(user_1, videoid_2, "Video2 is cool");
47 | Comment c4 = new Comment(user_2, videoid_2, "Video2");
48 |
49 | /* ==================== CREATE =====================
50 | * Create comment (in 2 tables with BATCH)
51 | * ================================================= */
52 | dao.upsert(c1);dao.upsert(c2);
53 | dao.upsert(c3);dao.upsert(c4);
54 | dao.retrieveVideoComments(videoid_2).all()
55 | .stream().map(CommentByVideo::getComment)
56 | .forEach(LOGGER::info);
57 |
58 | /* =============== UPDATE ==========================
59 | * == Update one comment (in 2 tables with BATCH) ==
60 | * ================================================= */
61 | c1.setComment("This is my new comment");
62 | dao.upsert(c1);
63 | dao.retrieveVideoComments(videoid_1).all()
64 | .stream().map(CommentByVideo::getComment)
65 | .forEach(LOGGER::info);
66 |
67 | /* =============== DELETE ===========================
68 | * Delete one comment (in 2 tables with BATCH) ==
69 | * Note that commentId is NOT ENOUGH as userid and ==
70 | * videoid are part of the the primary keys. ==
71 | * ==================================================*/
72 | dao.delete(c1);
73 | dao.retrieveVideoComments(videoid_1).all()
74 | .stream().map(CommentByVideo::getComment)
75 | .forEach(LOGGER::info);
76 |
77 | /*
78 | * ============================ READ ================================
79 | * == Query1: List comments for user_1 with table comment_by_user =
80 | * == Query2: List comments for video_2 with table comment_by_video =
81 | * ==================================================================
82 | */
83 |
84 | dao.retrieveUserComments(videoid_2).all()
85 | .stream().map(CommentByUser::getComment)
86 | .forEach(LOGGER::info);
87 |
88 | dao.retrieveVideoComments(videoid_2).all()
89 | .stream().map(CommentByVideo::getComment)
90 | .forEach(LOGGER::info);
91 |
92 | }
93 | }
94 |
95 | }
96 |
--------------------------------------------------------------------------------
/labs/lab4_cassandra_drivers/src/main/java/com/datastax/samples/E10_Counters.java:
--------------------------------------------------------------------------------
1 | package com.datastax.samples;
2 |
3 | import static com.datastax.samples.schema.SchemaUtils.createTableVideoViews;
4 | import static com.datastax.samples.schema.SchemaUtils.truncateTable;
5 |
6 | import java.util.Optional;
7 | import java.util.UUID;
8 |
9 | import org.slf4j.Logger;
10 | import org.slf4j.LoggerFactory;
11 |
12 | import com.datastax.oss.driver.api.core.CqlSession;
13 | import com.datastax.oss.driver.api.core.cql.PreparedStatement;
14 | import com.datastax.oss.driver.api.core.cql.Row;
15 | import com.datastax.oss.driver.api.querybuilder.QueryBuilder;
16 | import com.datastax.samples.schema.SchemaConstants;
17 |
18 | public class E10_Counters implements SchemaConstants {
19 |
20 | private static Logger LOGGER = LoggerFactory.getLogger(E10_Counters.class);
21 |
22 | private static PreparedStatement stmtIncrement;
23 | private static PreparedStatement stmtDecrement;
24 | private static PreparedStatement stmtFindById;
25 | private static PreparedStatement stmtDelete;
26 |
27 | public static void main(String[] args) {
28 | try(CqlSession cqlSession = CqlSessionProvider.getInstance().getSession()) {
29 |
30 | // Create tables for tests
31 | createTableVideoViews(cqlSession);
32 |
33 | // Empty tables for tests
34 | truncateTable(cqlSession, VIDEO_VIEWS_TABLENAME);
35 |
36 | // Prepare your statements once and execute multiple times
37 | prepareStatements(cqlSession);
38 |
39 | // ========= CREATE ============
40 |
41 | // We cannot insert in a table with a counter
42 | UUID videoId = UUID.randomUUID();
43 | LOGGER.info("+ Video views {}", findById(cqlSession, videoId));
44 |
45 | // ========= UPDATE ============
46 |
47 | incrementBy(cqlSession, videoId, 10);
48 | LOGGER.info("+ Video views : {}", findById(cqlSession, videoId).get());
49 |
50 | decrementBy(cqlSession, videoId, 8);
51 | LOGGER.info("+ Video views : {}", findById(cqlSession, videoId).get());
52 |
53 | // ========= DELETE ============
54 |
55 | delete(cqlSession, videoId);
56 | LOGGER.info("+ Video views {}", findById(cqlSession, videoId));
57 |
58 | }
59 | }
60 |
61 | private static Optional findById(CqlSession cqlSession, UUID videoid) {
62 | Row record = cqlSession.execute(stmtFindById.bind(videoid)).one();
63 | if (null != record) {
64 | return Optional.of(record.getLong(VIDEO_VIEWS_VIEWS));
65 | }
66 | return Optional.empty();
67 | }
68 |
69 | private static void incrementBy(CqlSession cqlSession, UUID videoid, long val) {
70 | cqlSession.execute(stmtIncrement.bind(val, videoid));
71 | }
72 |
73 | private static void decrementBy(CqlSession cqlSession, UUID videoid, long val) {
74 | cqlSession.execute(stmtDecrement.bind(val, videoid));
75 | }
76 |
77 | private static void delete(CqlSession cqlSession, UUID videoid) {
78 | cqlSession.execute(stmtDelete.bind(videoid));
79 | }
80 |
81 | private static void prepareStatements(CqlSession cqlSession) {
82 |
83 | // update videos_views SET views = views + X WHERE videoid=...
84 | stmtIncrement = cqlSession.prepare(QueryBuilder
85 | .update(VIDEO_VIEWS_TABLENAME)
86 | .increment(VIDEO_VIEWS_VIEWS, QueryBuilder.bindMarker())
87 | .whereColumn(VIDEO_VIEWS_VIDEOID).isEqualTo(QueryBuilder.bindMarker())
88 | .build());
89 |
90 | // update videos_views SET views = views + X WHERE videoid=..
91 | stmtDecrement = cqlSession.prepare(QueryBuilder
92 | .update(VIDEO_VIEWS_TABLENAME)
93 | .decrement(VIDEO_VIEWS_VIEWS, QueryBuilder.bindMarker())
94 | .whereColumn(VIDEO_VIEWS_VIDEOID).isEqualTo(QueryBuilder.bindMarker())
95 | .build());
96 |
97 | // SELECT views FROM videos_views WHERE videoid=...
98 | stmtFindById = cqlSession.prepare(QueryBuilder
99 | .selectFrom(VIDEO_VIEWS_TABLENAME).column(VIDEO_VIEWS_VIEWS)
100 | .whereColumn(VIDEO_VIEWS_VIDEOID).isEqualTo(QueryBuilder.bindMarker())
101 | .build());
102 |
103 | // DELETE FROM videos_views WHERE videoid=...
104 | stmtDelete = cqlSession.prepare(QueryBuilder
105 | .deleteFrom(VIDEO_VIEWS_TABLENAME)
106 | .whereColumn(VIDEO_VIEWS_VIDEOID).isEqualTo(QueryBuilder.bindMarker())
107 | .build());
108 |
109 | }
110 |
111 | }
112 |
--------------------------------------------------------------------------------
/labs/lab5_spring_data/src/main/java/com/datastax/workshop/todo/TodoRestController.java:
--------------------------------------------------------------------------------
1 | package com.datastax.workshop.todo;
2 |
3 | import static org.springframework.web.bind.annotation.RequestMethod.DELETE;
4 | import static org.springframework.web.bind.annotation.RequestMethod.GET;
5 | import static org.springframework.web.bind.annotation.RequestMethod.OPTIONS;
6 | import static org.springframework.web.bind.annotation.RequestMethod.PATCH;
7 | import static org.springframework.web.bind.annotation.RequestMethod.POST;
8 | import static org.springframework.web.bind.annotation.RequestMethod.PUT;
9 |
10 | import java.net.URI;
11 | import java.net.URISyntaxException;
12 | import java.util.Optional;
13 | import java.util.UUID;
14 | import java.util.stream.Stream;
15 |
16 | import javax.servlet.http.HttpServletRequest;
17 |
18 | import org.springframework.http.HttpStatus;
19 | import org.springframework.http.ResponseEntity;
20 | import org.springframework.web.bind.annotation.CrossOrigin;
21 | import org.springframework.web.bind.annotation.DeleteMapping;
22 | import org.springframework.web.bind.annotation.GetMapping;
23 | import org.springframework.web.bind.annotation.PatchMapping;
24 | import org.springframework.web.bind.annotation.PathVariable;
25 | import org.springframework.web.bind.annotation.PostMapping;
26 | import org.springframework.web.bind.annotation.RequestBody;
27 | import org.springframework.web.bind.annotation.RequestMapping;
28 | import org.springframework.web.bind.annotation.RestController;
29 |
30 | @RestController
31 | @CrossOrigin(
32 | methods = {POST, GET, OPTIONS, PUT, DELETE, PATCH},
33 | maxAge = 3600,
34 | allowedHeaders = {"x-requested-with", "origin", "content-type", "accept"},
35 | origins = "*"
36 | )
37 | @RequestMapping("/api/v1/todos/")
38 | public class TodoRestController {
39 |
40 | private TodoRepositoryCassandra repo;
41 |
42 | public TodoRestController(TodoRepositoryCassandra todoRepo) {
43 | this.repo = todoRepo;
44 | }
45 |
46 | @GetMapping
47 | public Stream findAll(HttpServletRequest req) {
48 | return repo.findAll().stream()
49 | .map(TodoRestController::mapAsTodo)
50 | .map(t -> t.setUrl(req));
51 | }
52 |
53 | @GetMapping("/{uid}")
54 | public ResponseEntity findById(HttpServletRequest req, @PathVariable(value = "uid") String uid) {
55 | Optional e = repo.findById(UUID.fromString(uid));
56 | if (!e.isPresent()) {
57 | return ResponseEntity.notFound().build();
58 | }
59 | return ResponseEntity.ok(mapAsTodo(e.get()).setUrl(req.getRequestURL().toString()));
60 | }
61 |
62 | @PostMapping
63 | public ResponseEntity create(HttpServletRequest req, @RequestBody Todo todoReq)
64 | throws URISyntaxException {
65 | TodoEntity te = mapAsTodoEntity(todoReq);
66 | repo.save(te);
67 | todoReq.setUuid(te.getUid());
68 | todoReq.setUrl(req);
69 | return ResponseEntity.created(new URI(todoReq.getUrl())).body(todoReq);
70 | }
71 |
72 | @PatchMapping("{uid}")
73 | public ResponseEntity update(HttpServletRequest req, @PathVariable(value = "uid") String uid, @RequestBody Todo todoReq)
74 | throws URISyntaxException {
75 | todoReq.setUuid(UUID.fromString(uid));
76 | todoReq.setUrl(req.getRequestURL().toString());
77 | repo.save(mapAsTodoEntity(todoReq));
78 | return ResponseEntity.accepted().body(todoReq);
79 | }
80 |
81 | @DeleteMapping("{uid}")
82 | public ResponseEntity deleteById(@PathVariable(value = "uid") String uid) {
83 | if (!repo.existsById(UUID.fromString(uid))) {
84 | return ResponseEntity.notFound().build();
85 | }
86 | repo.deleteById(UUID.fromString(uid));
87 | return new ResponseEntity<>(HttpStatus.NO_CONTENT);
88 | }
89 |
90 | @DeleteMapping
91 | public ResponseEntity deleteAll(HttpServletRequest request) {
92 | repo.deleteAll();
93 | return new ResponseEntity<>(HttpStatus.NO_CONTENT);
94 | }
95 |
96 | private static Todo mapAsTodo(TodoEntity te) {
97 | Todo todo = new Todo();
98 | todo.setTitle(te.getTitle());
99 | todo.setOrder(te.getOrder());
100 | todo.setUuid(te.getUid());
101 | todo.setCompleted(te.isCompleted());
102 | return todo;
103 | }
104 |
105 | private static TodoEntity mapAsTodoEntity(Todo te) {
106 | TodoEntity todo = new TodoEntity();
107 | if (null != te.getUuid()) {
108 | todo.setUid(te.getUuid());
109 | } else {
110 | todo.setUid(UUID.randomUUID());
111 | }
112 | todo.setTitle(te.getTitle());
113 | todo.setOrder(te.getOrder());
114 | todo.setCompleted(te.isCompleted());
115 | return todo;
116 | }
117 | }
--------------------------------------------------------------------------------
/labs/lab4_cassandra_drivers/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.schema.SchemaConstants;
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, SchemaConstants {
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 |
--------------------------------------------------------------------------------
/labs/lab4_cassandra_drivers/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 |
--------------------------------------------------------------------------------
/labs/lab4_cassandra_drivers/src/main/java/com/datastax/samples/E02_Statements.java:
--------------------------------------------------------------------------------
1 | package com.datastax.samples;
2 |
3 | import java.time.Duration;
4 |
5 | import org.slf4j.Logger;
6 | import org.slf4j.LoggerFactory;
7 |
8 | import com.datastax.oss.driver.api.core.ConsistencyLevel;
9 | import com.datastax.oss.driver.api.core.CqlSession;
10 | import com.datastax.oss.driver.api.core.cql.BoundStatement;
11 | import com.datastax.oss.driver.api.core.cql.PreparedStatement;
12 | import com.datastax.oss.driver.api.core.cql.SimpleStatement;
13 | import com.datastax.oss.driver.api.querybuilder.QueryBuilder;
14 | import com.datastax.oss.driver.shaded.guava.common.collect.ImmutableMap;
15 | import com.datastax.samples.schema.SchemaConstants;
16 |
17 | public class E02_Statements implements SchemaConstants {
18 |
19 | private static Logger LOGGER = LoggerFactory.getLogger(E01_CreateSchema.class);
20 |
21 | public static void main(String[] args) {
22 | try(CqlSession cqlSession = CqlSessionProvider.getInstance().getSession()) {
23 |
24 | // #1.a Execution de requete en chaine de caracteres
25 |
26 | cqlSession.execute(""
27 | + "INSERT INTO users (email, firstname, lastname) "
28 | + "VALUES ('clun@sample.com', 'Cedrick', 'Lunven')");
29 | LOGGER.info("+ Insert as a String");
30 |
31 | // #1.b Tout est statement
32 |
33 | cqlSession.execute(SimpleStatement.newInstance(
34 | "INSERT INTO users (email, firstname, lastname) "
35 | + "VALUES ('clun2@sample.com', 'Cedrick', 'Lunven')"));
36 | LOGGER.info("+ Insert as a Statement");
37 |
38 | // #2.a Externalisation des variables en utilisant la position et '?'
39 |
40 | // -- option1: un parametre a la fois
41 | cqlSession.execute(SimpleStatement
42 | .builder("INSERT INTO users (email, firstname, lastname) VALUES (?,?,?)")
43 | .addPositionalValue("clun3@gmail.com")
44 | .addPositionalValue("Cedrick")
45 | .addPositionalValue("Lunven").build());
46 | LOGGER.info("+ Insert and externalize var with ?, option1");
47 |
48 | // -- option2: tous les parametres en une fois
49 | cqlSession.execute(SimpleStatement
50 | .builder("INSERT INTO users (email, firstname, lastname) VALUES (?,?,?)")
51 | .addPositionalValues("clun4@gmail.com", "Cedrick", "Lunven").build());
52 | LOGGER.info("+ Insert and externalize var with ?, option2");
53 |
54 | // #2.b Externalisation en utilisant des labels:name
55 |
56 | // -- option1: un parametre a la fois
57 | cqlSession.execute(SimpleStatement
58 | .builder("INSERT INTO users (email, firstname, lastname) VALUES (:e,:f,:l)")
59 | .addNamedValue("e", "clun5@gmail.com")
60 | .addNamedValue("f", "Cedrick")
61 | .addNamedValue("l", "Lunven").build());
62 | LOGGER.info("+ Insert and externalize var with :labels, option1");
63 |
64 | // -- option2: tous les parametres en une fois
65 | cqlSession.execute(SimpleStatement
66 | .builder("INSERT INTO users (email, firstname, lastname) VALUES (:e,:f,:l)")
67 | .setConsistencyLevel(ConsistencyLevel.LOCAL_QUORUM)
68 | .setTimeout(Duration.ofSeconds(2))
69 | .build()
70 | .setNamedValues(ImmutableMap.of(
71 | "e", "clun6@gmail.com",
72 | "f", "Cedrick",
73 | "l", "Lunven")));
74 | LOGGER.info("+ Insert and externalize var with :labels, option2");
75 |
76 |
77 | // #4. Utilisation du QueryBuilder pour construire les requetes
78 | cqlSession.execute(QueryBuilder
79 | .insertInto(USER_TABLENAME)
80 | .value(USER_EMAIL, QueryBuilder.literal("clun5@gmail.com"))
81 | .value(USER_FIRSTNAME, QueryBuilder.literal("Cedrick"))
82 | .value(USER_LASTNAME, QueryBuilder.literal("Lunven"))
83 | .build());
84 | LOGGER.info("+ Insert with QueryBuilder");
85 |
86 | // #5. il faut preparer ses statements
87 |
88 | // 5.a Parameteres avec `?`
89 | PreparedStatement ps1 = cqlSession.prepare("INSERT INTO users (email, firstname, lastname) "
90 | + "VALUES (?,?,?)");
91 | BoundStatement bs1 = ps1.bind("clun6@gmail.com", "Cedrick", "Lunven");
92 | cqlSession.execute(bs1);
93 | LOGGER.info("+ Insert with PrepareStatements");
94 |
95 |
96 | // 5.b Pour utiliser un prepare statement par la suite on bind les valeurs avec 'bindMarker'
97 | PreparedStatement ps2 = cqlSession.prepare(QueryBuilder
98 | .insertInto(USER_TABLENAME)
99 | .value(USER_EMAIL, QueryBuilder.bindMarker())
100 | .value(USER_FIRSTNAME, QueryBuilder.bindMarker())
101 | .value(USER_LASTNAME, QueryBuilder.bindMarker())
102 | .build());
103 | cqlSession.execute(ps2.bind("clun7@gmail.com", "Cedrick", "Lunven"));
104 | LOGGER.info("+ Insert with PrepareStatements + QueryBuilder");
105 | }
106 | }
107 |
108 |
109 |
110 | }
111 |
--------------------------------------------------------------------------------
/labs/lab7_micronaut/pom.xml:
--------------------------------------------------------------------------------
1 |
2 |
5 | 4.0.0
6 | com.datastax.workshop
7 | lab7-micronaut
8 | lab7-micronaut
9 | jar
10 | 0.0.1-SNAPSHOT
11 |
12 |
13 | 3.2.6
14 | 4.13.0
15 | 1.2.9
16 | 2.13.1
17 | 1.8.2
18 | 5.8.2
19 | 3.1.0
20 | com.datastaxdev.TodoApplication
21 | netty
22 |
23 |
24 |
25 |
26 |
27 |
28 | io.micronaut
29 | micronaut-bom
30 | ${micronaut.version}
31 | pom
32 | import
33 |
34 |
35 |
36 |
37 |
38 |
39 |
40 |
41 | com.datastax.oss
42 | java-driver-core
43 | ${java-driver.version}
44 |
45 |
46 | com.datastax.oss
47 | java-driver-query-builder
48 | ${java-driver.version}
49 |
50 |
51 | com.datastax.oss
52 | java-driver-mapper-runtime
53 | ${java-driver.version}
54 |
55 |
56 | com.datastax.oss
57 | java-driver-mapper-processor
58 | ${java-driver.version}
59 |
60 |
61 | com.datastax.oss
62 | java-driver-metrics-micrometer
63 | ${java-driver.version}
64 |
65 |
66 |
67 |
68 | ch.qos.logback
69 | logback-classic
70 |
71 |
72 |
73 | jakarta.annotation
74 | jakarta.annotation-api
75 | compile
76 |
77 |
78 |
79 |
80 | io.micronaut
81 | micronaut-http-server-netty
82 | compile
83 |
84 |
85 | io.micronaut
86 | micronaut-inject
87 | compile
88 |
89 |
90 | io.micronaut
91 | micronaut-inject-java
92 | compile
93 |
94 |
95 | org.slf4j
96 | slf4j-simple
97 |
98 |
99 |
100 |
101 | io.micronaut
102 | micronaut-validation
103 | compile
104 |
105 |
106 | io.micronaut
107 | micronaut-runtime
108 | compile
109 |
110 |
111 |
112 | io.micronaut.cassandra
113 | micronaut-cassandra
114 | compile
115 |
116 |
117 |
118 | io.micronaut.test
119 | micronaut-test-junit5
120 | test
121 |
122 |
123 | io.micronaut
124 | micronaut-http-client
125 | compile
126 |
127 |
128 | org.junit.jupiter
129 | junit-jupiter-api
130 | test
131 |
132 |
133 | org.junit.jupiter
134 | junit-jupiter-engine
135 | test
136 |
137 |
138 |
139 |
140 |
141 |
142 | io.micronaut.build
143 | micronaut-maven-plugin
144 | ${maven.plugin.micronaut.version}
145 |
146 |
147 |
148 | org.apache.maven.plugins
149 | maven-compiler-plugin
150 | 3.8.1
151 |
152 | 11
153 | 11
154 | false
155 |
156 |
157 | com.datastax.oss
158 | java-driver-mapper-processor
159 | ${java-driver.version}
160 |
161 |
162 | io.micronaut
163 | micronaut-inject-java
164 | ${micronaut.version}
165 |
166 |
167 | io.micronaut
168 | micronaut-validation
169 | ${micronaut.version}
170 |
171 |
172 | io.micronaut
173 | micronaut-http-validation
174 | ${micronaut.version}
175 |
176 |
177 |
178 | -Amicronaut.processing.group=com.datastaxdev
179 | -Amicronaut.processing.module=lab7-micronaut
180 |
181 |
182 |
183 |
184 |
185 |
186 |
187 |
--------------------------------------------------------------------------------
/labs/lab6_quarkus/pom.xml:
--------------------------------------------------------------------------------
1 |
2 |
4 | 4.0.0
5 | com.datastax.samples
6 | lab6-quarkus
7 | 0.0.1-SNAPSHOT
8 |
9 | 3.8.1
10 | true
11 | 11
12 | 11
13 | UTF-8
14 | UTF-8
15 | quarkus-bom
16 | io.quarkus.platform
17 | 2.3.1.Final
18 | 3.0.0-M5
19 |
20 |
21 |
22 |
23 | ${quarkus.platform.group-id}
24 | ${quarkus.platform.artifact-id}
25 | ${quarkus.platform.version}
26 | pom
27 | import
28 |
29 |
30 |
31 |
32 |
33 | io.quarkus
34 | quarkus-resteasy-reactive
35 |
36 |
37 | io.quarkus
38 | quarkus-resteasy-reactive-jackson
39 |
40 |
41 | com.datastax.oss.quarkus
42 | cassandra-quarkus-client
43 | 1.1.1
44 |
45 |
46 | com.datastax.oss
47 | java-driver-mapper-runtime
48 | 4.13.0
49 |
50 |
51 | io.quarkus
52 | quarkus-micrometer
53 |
54 |
55 | io.quarkus
56 | quarkus-micrometer-registry-prometheus
57 |
58 |
59 | io.quarkus
60 | quarkus-smallrye-openapi
61 |
62 |
63 | io.quarkus
64 | quarkus-smallrye-health
65 |
66 |
67 | io.quarkus
68 | quarkus-junit5
69 | test
70 |
71 |
72 | io.rest-assured
73 | rest-assured
74 | test
75 |
76 |
77 | io.quarkus
78 | quarkus-kubernetes
79 |
80 |
81 | io.quarkus
82 | quarkus-container-image-jib
83 |
84 |
85 |
86 |
87 |
88 | ${quarkus.platform.group-id}
89 | quarkus-maven-plugin
90 | ${quarkus.platform.version}
91 | true
92 |
93 |
94 |
95 | build
96 | generate-code
97 | generate-code-tests
98 |
99 |
100 |
101 |
102 |
103 | maven-compiler-plugin
104 | ${compiler-plugin.version}
105 |
106 |
107 |
108 | com.datastax.oss
109 | java-driver-mapper-processor
110 | 4.13.0
111 |
112 |
113 |
114 |
115 |
116 | maven-surefire-plugin
117 | ${surefire-plugin.version}
118 |
119 |
120 | org.jboss.logmanager.LogManager
121 | ${maven.home}
122 |
123 |
124 |
125 |
126 |
127 |
128 |
129 | native
130 |
131 |
132 | native
133 |
134 |
135 |
136 |
137 |
138 | maven-failsafe-plugin
139 | ${surefire-plugin.version}
140 |
141 |
142 |
143 | integration-test
144 | verify
145 |
146 |
147 |
148 | ${project.build.directory}/${project.build.finalName}-runner
149 | org.jboss.logmanager.LogManager
150 | ${maven.home}
151 |
152 |
153 |
154 |
155 |
156 |
157 |
158 |
159 | native
160 |
161 |
162 |
163 |
164 |
--------------------------------------------------------------------------------
/labs/lab7_micronaut/src/main/java/com/datastaxdev/todo/TodoRestController.java:
--------------------------------------------------------------------------------
1 | package com.datastaxdev.todo;
2 |
3 | import java.net.URI;
4 | import java.net.URISyntaxException;
5 | import java.util.List;
6 | import java.util.Optional;
7 | import java.util.UUID;
8 | import java.util.stream.Collectors;
9 |
10 | import javax.validation.constraints.NotEmpty;
11 | import javax.validation.constraints.NotNull;
12 |
13 | import com.datastax.oss.driver.api.core.CqlSession;
14 | import com.datastaxdev.TodoDto;
15 | import com.datastaxdev.TodoService;
16 | import com.datastaxdev.todo.cassandra.TodoServiceCassandraCql;
17 | import com.datastaxdev.todo.web.Todo;
18 |
19 | import io.micronaut.http.HttpRequest;
20 | import io.micronaut.http.HttpResponse;
21 | import io.micronaut.http.annotation.Body;
22 | import io.micronaut.http.annotation.Controller;
23 | import io.micronaut.http.annotation.Delete;
24 | import io.micronaut.http.annotation.Get;
25 | import io.micronaut.http.annotation.Patch;
26 | import io.micronaut.http.annotation.PathVariable;
27 | import io.micronaut.http.annotation.Post;
28 | import io.micronaut.http.context.ServerRequestContext;
29 | import io.micronaut.http.uri.UriBuilder;
30 | import io.micronaut.validation.Validated;
31 | import jakarta.inject.Inject;
32 |
33 | @Validated
34 | @Controller("/api/v1")
35 | public class TodoRestController {
36 |
37 | /** CqlSession initialized from application.yaml */
38 | @Inject
39 | private CqlSession cqlSession;
40 |
41 | /** Todo service reference. */
42 | private TodoService repo;
43 |
44 | @Get(value = "/{user}/todos/")
45 | public List findAllByUser(
46 | @PathVariable(value = "user") @NotEmpty String user) {
47 | return getTodoService().findByUser(user)
48 | .stream()
49 | .map(this::fromDto)
50 | .map(t -> populateUrlWithId(t, ServerRequestContext.currentRequest().get()))
51 | .collect(Collectors.toList());
52 | }
53 |
54 | @Get("/{user}/todos/{uid}")
55 | public HttpResponse findById(
56 | @PathVariable(value = "user") @NotEmpty String user,
57 | @PathVariable(value = "uid") @NotEmpty String itemId) {
58 | Optional e = getTodoService().findById(user, UUID.fromString(itemId));
59 | if (e.isEmpty()) return HttpResponse.notFound();
60 | Todo todo = fromDto(e.get());
61 | populateUrl(todo, ServerRequestContext.currentRequest().get());
62 | //LOGGER.info("Find user={}, TODO={}", user, todo);
63 | return HttpResponse.ok(todo);
64 | }
65 |
66 | @Post("/{user}/todos/")
67 | public HttpResponse create(
68 | @PathVariable(value = "user") String user,
69 | @Body @NotNull Todo todoReq) throws URISyntaxException {
70 | TodoDto te = toDto(todoReq, user);
71 | te = getTodoService().save(te);
72 | todoReq.setUuid(te.getItemId());
73 | populateUrlWithId(todoReq, ServerRequestContext.currentRequest().get());
74 | //LOGGER.info("Created user={}, TODO={}", user, todoReq);
75 | return HttpResponse.created(new URI(todoReq.getUrl())).body(todoReq);
76 | }
77 |
78 | @Patch("/{user}/todos/{uid}")
79 | public HttpResponse update(
80 | @PathVariable(value = "user") @NotEmpty String user,
81 | @PathVariable(value = "uid") @NotEmpty String itemId,
82 | @Body @NotNull Todo todo)
83 | throws URISyntaxException {
84 | //LOGGER.info("Updating user={} id={} with TODO {}", user, itemId, todo);
85 | Optional e = getTodoService().findById(user, UUID.fromString(itemId));
86 | if (e.isEmpty()) return HttpResponse.notFound();
87 | todo.setUuid(UUID.fromString(itemId));
88 | TodoDto todoDto = toDto(todo, user);
89 | todoDto = getTodoService().save(todoDto);
90 | populateUrl(todo, ServerRequestContext.currentRequest().get());
91 | return HttpResponse.ok(todo);
92 | }
93 |
94 | @Delete("/{user}/todos/{uid}")
95 | public HttpResponse deleteById(
96 | @PathVariable(value = "user") String user,
97 | @PathVariable(value = "uid") String uid) {
98 | //LOGGER.info("Delete TODO id={} for user={}", uid, user);
99 | if (getTodoService().findById(user, UUID.fromString(uid)).isEmpty()) {
100 | return HttpResponse.notFound();
101 | }
102 | getTodoService().deleteById(user, UUID.fromString(uid));
103 | return HttpResponse.noContent();
104 | }
105 |
106 | @Delete("/{user}/todos/")
107 | public HttpResponse deleteAllByUser(@PathVariable(value = "user") String user) {
108 | getTodoService().deleteByUser(user);
109 | return HttpResponse.noContent();
110 | }
111 |
112 | /**
113 | * Access todo service.
114 | *
115 | * @return
116 | * todo services
117 | */
118 | public TodoService getTodoService() {
119 | if (repo == null) {
120 | repo = new TodoServiceCassandraCql(cqlSession);
121 | }
122 | return repo;
123 | }
124 |
125 | private Todo fromDto(TodoDto te) {
126 | Todo todo = new Todo();
127 | todo.setTitle(te.getTitle());
128 | todo.setUuid(te.getItemId());
129 | todo.setCompleted(te.getCompleted());
130 | return todo;
131 | }
132 |
133 | private TodoDto toDto(Todo te, String user) {
134 | TodoDto dto = new TodoDto();
135 | dto.setUserId(user);
136 | dto.setItemId(te.getUuid());
137 | dto.setTitle(te.getTitle());
138 | dto.setCompleted(te.isCompleted());
139 | return dto;
140 | }
141 |
142 | private Todo populateUrlWithId(Todo t, HttpRequest