generated from DataStax-Examples/datastax-examples-template
-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathMapperApp.java
199 lines (173 loc) · 7.62 KB
/
MapperApp.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
/*
* Copyright DataStax, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.datastax.examples;
import com.datastax.examples.mapper.killrvideo.KillrVideoMapper;
import com.datastax.examples.mapper.killrvideo.user.User;
import com.datastax.examples.mapper.killrvideo.user.UserDao;
import com.datastax.examples.mapper.killrvideo.video.LatestVideo;
import com.datastax.examples.mapper.killrvideo.video.UserVideo;
import com.datastax.examples.mapper.killrvideo.video.Video;
import com.datastax.examples.mapper.killrvideo.video.VideoByTag;
import com.datastax.examples.mapper.killrvideo.video.VideoDao;
import com.datastax.oss.driver.api.core.CqlIdentifier;
import com.datastax.oss.driver.api.core.CqlSession;
import com.datastax.oss.driver.api.core.PagingIterable;
import com.datastax.oss.driver.api.core.cql.SimpleStatement;
import java.net.URI;
import java.nio.file.FileSystems;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.Instant;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.UUID;
import java.util.stream.Collectors;
/**
* Uses the driver's object mapper to interact with a schema.
*
* <p>We use the data model of the <a href="https://killrvideo.github.io/">KillrVideo</a> sample
* application. The mapped entities and DAOs are in the {@link
* com.datastax.examples.mapper.killrvideo} package. We only cover a subset of the data
* model (ratings, stats, recommendations and comments are not covered).
*
* <p>Preconditions:
*
* <ul>
* <li>An Apache Cassandra(R) cluster is running and accessible through the contacts points
* identified by basic.contact-points (see application.conf).
* </ul>
*
* <p>Side effects:
*
* <ul>
* <li>creates a new keyspace "killrvideo" in the session. If a keyspace with this name already
* exists, it will be reused;
* <li>creates the tables of the KillrVideo data model, if they don't already exist;
* <li>inserts a new user, or reuse the existing one if the email address is already taken;
* <li>inserts a video for that user.
* </ul>
*
* @see <a href="https://docs.datastax.com/en/developer/java-driver/latest/manual/mapper/">Java
* Driver Mapper manual</a>
*/
@SuppressWarnings("CatchAndPrintStackTrace")
public class MapperApp {
private static final CqlIdentifier KEYSPACE_ID = CqlIdentifier.fromCql("killrvideo");
public static void main(String[] args) {
try (CqlSession session = CqlSession.builder().build()) {
maybeCreateSchema(session);
KillrVideoMapper mapper =
KillrVideoMapper.builder(session).withDefaultKeyspace(KEYSPACE_ID).build();
// Create a new user
UserDao userDao = mapper.userDao();
User user =
new User(UUID.randomUUID(), "test", "user", "[email protected]", Instant.now());
if (userDao.create(user, "password123".toCharArray())) {
System.out.println("Created " + user);
} else {
user = userDao.getByEmail("[email protected]");
System.out.println("Reusing existing " + user);
}
// Creating another user with the same email should fail
assert !userDao.create(
new User(UUID.randomUUID(), "test2", "user", "[email protected]", Instant.now()),
"secret123".toCharArray());
// Simulate login attempts
tryLogin(userDao, "[email protected]", "password123");
tryLogin(userDao, "[email protected]", "secret123");
// Insert a video
VideoDao videoDao = mapper.videoDao();
Video video = new Video();
video.setUserid(user.getUserid());
video.setName("Accelerate: A NoSQL Original Series (TRAILER)");
video.setLocation("https://www.youtube.com/watch?v=LulWy8zmrog");
Set<String> tags = new HashSet<>();
tags.add("apachecassandra");
tags.add("nosql");
tags.add("hybridcloud");
video.setTags(tags);
videoDao.create(video);
System.out.printf("Created video [%s] %s%n", video.getVideoid(), video.getName());
// Check that associated denormalized tables have also been updated:
PagingIterable<UserVideo> userVideos = videoDao.getByUser(user.getUserid());
System.out.printf("Videos for %s %s:%n", user.getFirstname(), user.getLastname());
for (UserVideo userVideo : userVideos) {
System.out.printf(" [%s] %s%n", userVideo.getVideoid(), userVideo.getName());
}
PagingIterable<LatestVideo> latestVideos = videoDao.getLatest(todaysTimestamp());
System.out.println("Latest videos:");
for (LatestVideo latestVideo : latestVideos) {
System.out.printf(" [%s] %s%n", latestVideo.getVideoid(), latestVideo.getName());
}
PagingIterable<VideoByTag> videosByTag = videoDao.getByTag("apachecassandra");
System.out.println("Videos tagged with apachecassandra:");
for (VideoByTag videoByTag : videosByTag) {
System.out.printf(" [%s] %s%n", videoByTag.getVideoid(), videoByTag.getName());
}
// Update the existing video:
Video template = new Video();
template.setVideoid(video.getVideoid());
template.setName(
"Accelerate: A NoSQL Original Series - join us online!");
videoDao.update(template);
// Reload the whole entity and check the fields
video = videoDao.get(video.getVideoid());
System.out.printf("Updated name for video %s: %s%n", video.getVideoid(), video.getName());
} catch (Exception e) {
e.printStackTrace();
}
}
private static void tryLogin(UserDao userDao, String email, String password) {
Optional<User> maybeUser = userDao.login(email, password.toCharArray());
System.out.printf(
"Logging in with %s/%s: %s%n",
email, password, maybeUser.isPresent() ? "Success" : "Failure");
}
private static void maybeCreateSchema(CqlSession session) throws Exception {
session.execute(
SimpleStatement.newInstance(
"CREATE KEYSPACE IF NOT EXISTS killrvideo WITH replication = {'class': 'SimpleStrategy', 'replication_factor': 1}")
.setExecutionProfileName("slow"));
session.execute("USE killrvideo");
for (String statement : getStatements("killrvideo_schema.cql")) {
session.execute(SimpleStatement.newInstance(statement).setExecutionProfileName("slow"));
}
}
private static List<String> getStatements(String fileName) throws Exception {
URI uri = Thread.currentThread().getContextClassLoader().getResource(fileName).toURI();
FileSystems.newFileSystem(uri, Map.of("create", "true"));
Path path = Paths.get(uri);
String contents = Files.readString(path);
return Arrays.stream(contents.split(";"))
.map(String::trim)
.filter(s -> !s.isEmpty())
.collect(Collectors.toList());
}
/**
* KillrVideo uses a textual timestamp to partition recent video. Build the timestamp for today to
* fetch our latest insertions.
*/
private static String todaysTimestamp() {
return DateTimeFormatter.ofPattern("yyyyMMdd").withZone(ZoneOffset.UTC).format(Instant.now());
}
}