generated from DataStax-Examples/datastax-examples-template
-
Notifications
You must be signed in to change notification settings - Fork 3
/
ForwardPagingRestUi.java
302 lines (257 loc) · 10.6 KB
/
ForwardPagingRestUi.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
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
/*
* 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.oss.driver.api.core.CqlSession;
import com.datastax.oss.driver.api.core.cql.BoundStatementBuilder;
import com.datastax.oss.driver.api.core.cql.PreparedStatement;
import com.datastax.oss.driver.api.core.cql.ResultSet;
import com.datastax.oss.driver.api.core.cql.Row;
import com.datastax.oss.driver.internal.core.type.codec.DateCodec;
import com.datastax.oss.protocol.internal.util.Bytes;
import com.sun.net.httpserver.HttpServer;
import java.io.IOException;
import java.net.URI;
import java.time.Instant;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import javax.annotation.PostConstruct;
import javax.inject.Inject;
import javax.inject.Singleton;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.UriBuilder;
import javax.ws.rs.core.UriInfo;
import org.glassfish.jersey.server.ResourceConfig;
import org.glassfish.hk2.utilities.binding.AbstractBinder;
import org.glassfish.jersey.jdkhttp.JdkHttpServerFactory;
/**
* A stateless REST service (backed by <a href="https://jersey.java.net/">Jersey</a>, <a
* href="https://hk2.java.net/">HK2</a> and the JDK HttpServer) that displays paginated results for
* a CQL query.
*
* <p>Conversion to and from JSON is made through <a
* href="https://jersey.java.net/documentation/latest/media.html#json.jackson">Jersey Jackson
* providers</a>.
*
* <p>Navigation is forward-only. The implementation relies on the paging state returned by
* Cassandra, and encodes it in HTTP URLs.
*
* <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 "examples" in the cluster. If a keyspace with this name already
* exists, it will be reused;
* <li>creates a table "examples.forward_paging_rest_ui". If it already exists, it will be reused;
* <li>inserts data in the table;
* <li>launches a REST server listening on HTTP_PORT.
* </ul>
*/
public class ForwardPagingRestUi {
private static final int HTTP_PORT = 8080;
private static final int ITEMS_PER_PAGE = 10;
private static final URI BASE_URI =
UriBuilder.fromUri("http://localhost/").path("").port(HTTP_PORT).build();
public static void main(String[] args) throws Exception {
try (CqlSession session = CqlSession.builder().addTypeCodecs(new DateCodec()).build()) {
createSchema(session);
populateSchema(session);
startRestService(session);
}
}
// Creates a table storing videos by users, in a typically denormalized way
private static void createSchema(CqlSession session) {
session.execute(
"CREATE KEYSPACE IF NOT EXISTS examples "
+ "WITH replication = {'class': 'SimpleStrategy', 'replication_factor': 1}");
session.execute(
"CREATE TABLE IF NOT EXISTS examples.forward_paging_rest_ui("
+ "userid int, username text, "
+ "added timestamp, "
+ "videoid int, title text, "
+ "PRIMARY KEY (userid, added, videoid)"
+ ") WITH CLUSTERING ORDER BY (added DESC, videoid ASC)");
}
private static void populateSchema(CqlSession session) {
PreparedStatement prepare =
session.prepare(
"INSERT INTO examples.forward_paging_rest_ui (userid, username, added, videoid, title) VALUES (?, ?, ?, ?, ?)");
// 3 users
for (int i = 0; i < 3; i++) {
// 49 videos each
for (int j = 0; j < 49; j++) {
int videoid = i * 100 + j;
session.execute(
prepare.bind(
i, "user " + i, Instant.ofEpochMilli(j * 100000), videoid, "video " + videoid));
}
}
}
// starts the REST server using JDK HttpServer (com.sun.net.httpserver.HttpServer)
private static void startRestService(CqlSession session)
throws IOException, InterruptedException {
final HttpServer server =
JdkHttpServerFactory.createHttpServer(BASE_URI, new VideoApplication(session), false);
final ExecutorService executor = Executors.newSingleThreadExecutor();
server.setExecutor(executor);
Runtime.getRuntime()
.addShutdownHook(
new Thread(
() -> {
System.out.println();
System.out.println("Stopping REST Service");
server.stop(0);
executor.shutdownNow();
System.out.println("REST Service stopped");
}));
server.start();
System.out.println();
System.out.printf(
"REST Service started on http://localhost:%d/users, press CTRL+C to stop%n", HTTP_PORT);
System.out.println(
"To explore this example, start with the following request and walk from there:");
System.out.printf("curl -i http://localhost:%d/users/1/videos%n", HTTP_PORT);
System.out.println();
Thread.currentThread().join();
}
/**
* Configures the REST application and handles injection of custom objects, such as the driver
* session.
*
* <p>This is also the place where you would normally configure JSON serialization, etc.
*
* <p>Note that in this example, we rely on the automatic discovery and configuration of Jackson
* through {@code org.glassfish.jersey.jackson.JacksonFeature}.
*/
public static class VideoApplication extends ResourceConfig {
public VideoApplication(final CqlSession session) {
super(UserService.class);
// AbstractBinder is provided by HK2
register(
new AbstractBinder() {
@Override
protected void configure() {
bind(session).to(CqlSession.class);
}
});
}
}
/**
* A typical REST service, handling requests involving users.
*
* <p>Typically, this service would contain methods for listing and searching for users, and
* methods to retrieve user details. Here, for brevity, only one method, listing videos by user,
* is implemented.
*/
@Singleton
@Path("/users")
@Produces("application/json")
public static class UserService {
@Inject private CqlSession session;
@Context private UriInfo uri;
private PreparedStatement videosByUser;
@PostConstruct
@SuppressWarnings("unused")
public void init() {
this.videosByUser =
session.prepare(
"SELECT videoid, title, added FROM examples.forward_paging_rest_ui WHERE userid = ?");
}
/**
* Returns a paginated list of all the videos created by the given user.
*
* @param userid the user ID.
* @param page the page to request, or {@code null} to get the first page.
*/
@GET
@Path("/{userid}/videos")
public UserVideosResponse getUserVideos(
@PathParam("userid") int userid, @QueryParam("page") String page) {
BoundStatementBuilder statementBuilder =
videosByUser.boundStatementBuilder(userid).setPageSize(ITEMS_PER_PAGE);
if (page != null) {
statementBuilder.setPagingState(Bytes.fromHexString(page));
}
ResultSet rs = session.execute(statementBuilder.build());
String nextPage = Bytes.toHexString(rs.getExecutionInfo().getPagingState());
int remaining = rs.getAvailableWithoutFetching();
List<UserVideo> videos = new ArrayList<>(remaining);
if (remaining > 0) {
for (Row row : rs) {
UserVideo video =
new UserVideo(row.getInt("videoid"), row.getString("title"), row.getInstant("added"));
videos.add(video);
// Make sure we don't go past the current page (we don't want the driver to fetch the next
// one)
if (--remaining == 0) {
break;
}
}
}
URI next = null;
if (nextPage != null)
next = uri.getAbsolutePathBuilder().queryParam("page", nextPage).build();
return new UserVideosResponse(videos, next);
}
}
@SuppressWarnings("unused")
public static class UserVideosResponse {
private final List<UserVideo> videos;
private final URI nextPage;
public UserVideosResponse(List<UserVideo> videos, URI nextPage) {
this.videos = videos;
this.nextPage = nextPage;
}
public List<UserVideo> getVideos() {
return videos;
}
public URI getNextPage() {
return nextPage;
}
}
@SuppressWarnings("unused")
public static class UserVideo {
private final int videoid;
private final String title;
private final Instant added;
public UserVideo(int videoid, String title, Instant added) {
this.videoid = videoid;
this.title = title;
this.added = added;
}
public int getVideoid() {
return videoid;
}
public String getTitle() {
return title;
}
public Instant getAdded() {
return added;
}
}
}