Elffuss BraidHub

kikocis/java-driver public

Add REST paging examples (#717)

Changesetd49a67f537ce977034cdaed3e5937946ed3a856dbf5e009b8fef52c21af9348c
AuthorOlivier Michallat <olim7t@users.noreply.github.com> · 2016-10-03 09:25 -07:00
CommitterGitHub <noreply@github.com> · 2016-10-03 09:25 -07:00
Parents7d5b7df67525

Browse the files at this changeset

4 files changed

modified driver-examples/pom.xml +71 −3
@@ -31,10 +31,16 @@
3131
3232 <properties>
3333 <main.basedir>${project.parent.basedir}</main.basedir>
34+ <jax-rs.version>2.0.1</jax-rs.version>
35+ <jersey.version>2.23.1</jersey.version>
36+ <hk2.version>2.4.0-b34</hk2.version>
37+ <logback.version>1.1.3</logback.version>
3438 </properties>
3539
3640 <dependencies>
3741
42+ <!-- driver dependencies -->
43+
3844 <dependency>
3945 <groupId>com.datastax.cassandra</groupId>
4046 <artifactId>cassandra-driver-core</artifactId>
@@ -48,6 +54,15 @@
4854 <optional>true</optional>
4955 </dependency>
5056
57+ <!--Jackson-->
58+
59+ <dependency>
60+ <groupId>com.fasterxml.jackson.core</groupId>
61+ <artifactId>jackson-annotations</artifactId>
62+ <version>${jackson.version}</version>
63+ <optional>true</optional>
64+ </dependency>
65+
5166 <dependency>
5267 <groupId>com.fasterxml.jackson.core</groupId>
5368 <artifactId>jackson-databind</artifactId>
@@ -55,6 +70,8 @@
5570 <optional>true</optional>
5671 </dependency>
5772
73+ <!--JSR-353 (Java JSON API)-->
74+
5875 <dependency>
5976 <groupId>javax.json</groupId>
6077 <artifactId>javax.json-api</artifactId>
@@ -70,12 +87,54 @@
7087 <scope>runtime</scope>
7188 </dependency>
7289
73- <!-- driver logs -->
90+ <!--JAX-RS-->
91+
92+ <dependency>
93+ <groupId>javax.ws.rs</groupId>
94+ <artifactId>javax.ws.rs-api</artifactId>
95+ <version>${jax-rs.version}</version>
96+ <optional>true</optional>
97+ </dependency>
98+
99+ <!--Jersey-->
100+
101+ <dependency>
102+ <groupId>org.glassfish.jersey.core</groupId>
103+ <artifactId>jersey-server</artifactId>
104+ <version>${jersey.version}</version>
105+ <optional>true</optional>
106+ </dependency>
107+
108+ <dependency>
109+ <groupId>org.glassfish.jersey.media</groupId>
110+ <artifactId>jersey-media-json-jackson</artifactId>
111+ <version>${jersey.version}</version>
112+ <optional>true</optional>
113+ </dependency>
114+
115+ <dependency>
116+ <groupId>org.glassfish.jersey.containers</groupId>
117+ <artifactId>jersey-container-jdk-http</artifactId>
118+ <version>${jersey.version}</version>
119+ <optional>true</optional>
120+ </dependency>
121+
122+
123+ <!--CDI frameworks (HK2)-->
124+
125+ <dependency>
126+ <groupId>org.glassfish.hk2</groupId>
127+ <artifactId>hk2-api</artifactId>
128+ <version>${hk2.version}</version>
129+ <optional>true</optional>
130+ </dependency>
131+
132+ <!--logging -->
133+
74134 <dependency>
75135 <groupId>ch.qos.logback</groupId>
76136 <artifactId>logback-classic</artifactId>
77- <version>1.1.3</version>
78- <scope>runtime</scope>
137+ <version>${logback.version}</version>
79138 </dependency>
80139
81140 </dependencies>
@@ -84,6 +143,15 @@
84143
85144 <plugins>
86145
146+ <plugin>
147+ <groupId>org.codehaus.mojo</groupId>
148+ <artifactId>animal-sniffer-maven-plugin</artifactId>
149+ <version>1.15</version>
150+ <configuration>
151+ <skip>true</skip>
152+ </configuration>
153+ </plugin>
154+
87155 <plugin>
88156 <groupId>org.apache.maven.plugins</groupId>
89157 <artifactId>maven-install-plugin</artifactId>
modified driver-examples/src/main/java/com/datastax/driver/examples/datatypes/Blobs.java +4 −2
@@ -17,11 +17,11 @@
1717
1818 import com.datastax.driver.core.*;
1919 import com.datastax.driver.core.utils.Bytes;
20-import com.google.common.collect.ImmutableMap;
2120
2221 import java.io.*;
2322 import java.nio.ByteBuffer;
2423 import java.nio.channels.FileChannel;
24+import java.util.HashMap;
2525 import java.util.Map;
2626
2727 /**
@@ -89,8 +89,10 @@
8989 // Now position is back to the beginning, so the driver will see all 16 bytes.
9090 assert buffer.limit() - buffer.position() == 16;
9191
92+ Map<String, ByteBuffer> map = new HashMap<String, ByteBuffer>();
93+ map.put("test", buffer);
9294 session.execute("INSERT INTO examples.blobs (k, b, m) VALUES (1, ?, ?)",
93- buffer, ImmutableMap.of("test", buffer));
95+ buffer, map);
9496 }
9597
9698 private static void retrieveSimpleColumn(Session session) {
added driver-examples/src/main/java/com/datastax/driver/examples/paging/ForwardPagingRestUi.java +294 −0
@@ -0,0 +1,294 @@
1+/*
2+ * Copyright (C) 2012-2015 DataStax Inc.
3+ *
4+ * Licensed under the Apache License, Version 2.0 (the "License");
5+ * you may not use this file except in compliance with the License.
6+ * You may obtain a copy of the License at
7+ *
8+ * http://www.apache.org/licenses/LICENSE-2.0
9+ *
10+ * Unless required by applicable law or agreed to in writing, software
11+ * distributed under the License is distributed on an "AS IS" BASIS,
12+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+ * See the License for the specific language governing permissions and
14+ * limitations under the License.
15+ */
16+package com.datastax.driver.examples.paging;
17+
18+import com.datastax.driver.core.*;
19+import com.sun.net.httpserver.HttpServer;
20+import org.glassfish.hk2.utilities.binding.AbstractBinder;
21+import org.glassfish.jersey.jdkhttp.JdkHttpServerFactory;
22+import org.glassfish.jersey.server.ResourceConfig;
23+
24+import javax.annotation.PostConstruct;
25+import javax.inject.Inject;
26+import javax.inject.Singleton;
27+import javax.ws.rs.*;
28+import javax.ws.rs.core.Context;
29+import javax.ws.rs.core.UriBuilder;
30+import javax.ws.rs.core.UriInfo;
31+import java.io.IOException;
32+import java.net.URI;
33+import java.util.ArrayList;
34+import java.util.Date;
35+import java.util.List;
36+import java.util.concurrent.ExecutorService;
37+import java.util.concurrent.Executors;
38+
39+/**
40+ * A stateless REST service (backed by
41+ * <a href="https://jersey.java.net/">Jersey</a>,
42+ * <a href="https://hk2.java.net/">HK2</a> and
43+ * the JDK HttpServer) that displays paginated results for a CQL query.
44+ * <p/>
45+ * Conversion to and from JSON is made through
46+ * <a href="https://jersey.java.net/documentation/latest/media.html#json.jackson">Jersey Jackson providers</a>.
47+ * <p/>
48+ * Navigation is forward-only.
49+ * The implementation relies on the paging state returned by Cassandra, and encodes it in HTTP URLs.
50+ * <p/>
51+ * Preconditions:
52+ * - a Cassandra cluster is running and accessible through the contacts points identified by CONTACT_POINTS and
53+ * CASSANDRA_PORT;
54+ * - port HTTP_PORT is available.
55+ * <p/>
56+ * Side effects:
57+ * - creates a new keyspace "examples" in the cluster. If a keyspace with this name already exists, it will be reused;
58+ * - creates a table "examples.forward_paging_rest_ui". If it already exists, it will be reused;
59+ * - inserts data in the table;
60+ * - launches a REST server listening on HTTP_PORT.
61+ */
62+public class ForwardPagingRestUi {
63+
64+ static final String[] CONTACT_POINTS = {"127.0.0.1"};
65+
66+ static final int CASSANDRA_PORT = 9042;
67+
68+ static final int HTTP_PORT = 8080;
69+
70+ static final int ITEMS_PER_PAGE = 10;
71+
72+ static final URI BASE_URI = UriBuilder.fromUri("http://localhost/").path("").port(HTTP_PORT).build();
73+
74+ public static void main(String[] args) throws Exception {
75+
76+ Cluster cluster = null;
77+ try {
78+
79+ cluster = Cluster.builder()
80+ .addContactPoints(CONTACT_POINTS).withPort(CASSANDRA_PORT)
81+ .build();
82+ Session session = cluster.connect();
83+
84+ createSchema(session);
85+ populateSchema(session);
86+ startRestService(session);
87+
88+ } finally {
89+ if (cluster != null) cluster.close();
90+ }
91+
92+ }
93+
94+ // Creates a table storing videos by users, in a typically denormalized way
95+ private static void createSchema(Session session) {
96+ session.execute("CREATE KEYSPACE IF NOT EXISTS examples " +
97+ "WITH replication = {'class': 'SimpleStrategy', 'replication_factor': 1}");
98+ session.execute("CREATE TABLE IF NOT EXISTS examples.forward_paging_rest_ui(" +
99+ "userid int, username text, " +
100+ "added timestamp, " +
101+ "videoid int, title text, " +
102+ "PRIMARY KEY (userid, added, videoid)" +
103+ ") WITH CLUSTERING ORDER BY (added DESC, videoid ASC)");
104+ }
105+
106+ private static void populateSchema(Session session) {
107+ // 3 users
108+ for (int i = 0; i < 3; i++) {
109+ // 49 videos each
110+ for (int j = 0; j < 49; j++) {
111+ int videoid = i * 100 + j;
112+ session.execute("INSERT INTO examples.forward_paging_rest_ui (userid, username, added, videoid, title) VALUES (?, ?, ?, ?, ?)",
113+ i, "user " + i, new Date(j * 100000), videoid, "video " + videoid);
114+ }
115+ }
116+ }
117+
118+ // starts the REST server using JDK HttpServer (com.sun.net.httpserver.HttpServer)
119+ private static void startRestService(Session session) throws IOException, InterruptedException {
120+
121+ final HttpServer server = JdkHttpServerFactory.createHttpServer(BASE_URI, new VideoApplication(session), false);
122+ final ExecutorService executor = Executors.newSingleThreadExecutor();
123+ server.setExecutor(executor);
124+ Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() {
125+ @Override
126+ public void run() {
127+ System.out.println();
128+ System.out.println("Stopping REST Service");
129+ server.stop(0);
130+ executor.shutdownNow();
131+ System.out.println("REST Service stopped");
132+ }
133+ }));
134+ server.start();
135+
136+ System.out.println();
137+ System.out.printf("REST Service started on http://localhost:%d/users, press CTRL+C to stop%n", HTTP_PORT);
138+ System.out.println("To explore this example, start with the following request and walk from there:");
139+ System.out.printf("curl -i http://localhost:%d/users/1/videos%n", HTTP_PORT);
140+ System.out.println();
141+
142+ Thread.currentThread().join();
143+
144+ }
145+
146+ /**
147+ * Configures the REST application and handles injection of custom objects, such
148+ * as the driver session.
149+ * <p>
150+ * This is also the place where you would normally configure JSON serialization, etc.
151+ * <p>
152+ * Note that in this example, we rely on the automatic discovery and configuration of
153+ * Jackson through {@link org.glassfish.jersey.jackson.JacksonFeature}.
154+ */
155+ public static class VideoApplication extends ResourceConfig {
156+
157+ public VideoApplication(final Session session) {
158+ super(UserService.class);
159+ // AbstractBinder is provided by HK2
160+ register(new AbstractBinder() {
161+
162+ @Override
163+ protected void configure() {
164+ bind(session).to(Session.class);
165+ }
166+
167+ });
168+ }
169+
170+ }
171+
172+ /**
173+ * A typical REST service, handling requests involving users.
174+ * <p/>
175+ * Typically, this service would contain methods for listing and searching for users,
176+ * and methods to retrieve user details. Here, for brevity,
177+ * only one method, listing videos by user, is implemented.
178+ */
179+ @Singleton
180+ @Path("/users")
181+ @Produces("application/json")
182+ public static class UserService {
183+
184+ @Inject
185+ private Session session;
186+
187+ @Context
188+ private UriInfo uri;
189+
190+ private PreparedStatement videosByUser;
191+
192+ @PostConstruct
193+ @SuppressWarnings("unused")
194+ public void init() {
195+ this.videosByUser = session.prepare("SELECT videoid, title, added FROM examples.forward_paging_rest_ui WHERE userid = ?");
196+ }
197+
198+ /**
199+ * Returns a paginated list of all the videos created by the given user.
200+ *
201+ * @param userid the user ID.
202+ * @param page the page to request, or {@code null} to get the first page.
203+ */
204+ @GET
205+ @Path("/{userid}/videos")
206+ public UserVideosResponse getUserVideos(@PathParam("userid") int userid, @QueryParam("page") String page) {
207+
208+ Statement statement = videosByUser.bind(userid).setFetchSize(ITEMS_PER_PAGE);
209+ if (page != null)
210+ statement.setPagingState(PagingState.fromString(page));
211+
212+ ResultSet rs = session.execute(statement);
213+ PagingState nextPage = rs.getExecutionInfo().getPagingState();
214+
215+ int remaining = rs.getAvailableWithoutFetching();
216+ List<UserVideo> videos = new ArrayList<UserVideo>(remaining);
217+
218+ if (remaining > 0) {
219+ for (Row row : rs) {
220+
221+ UserVideo video = new UserVideo(
222+ row.getInt("videoid"),
223+ row.getString("title"),
224+ row.getTimestamp("added"));
225+ videos.add(video);
226+
227+ // Make sure we don't go past the current page (we don't want the driver to fetch the next one)
228+ if (--remaining == 0)
229+ break;
230+ }
231+ }
232+
233+ URI next = null;
234+ if (nextPage != null)
235+ next = uri.getAbsolutePathBuilder().queryParam("page", nextPage).build();
236+
237+ return new UserVideosResponse(videos, next);
238+ }
239+
240+ }
241+
242+ public static class UserVideosResponse {
243+
244+ private final List<UserVideo> videos;
245+
246+ private final URI nextPage;
247+
248+ public UserVideosResponse(List<UserVideo> videos, URI nextPage) {
249+ this.videos = videos;
250+ this.nextPage = nextPage;
251+ }
252+
253+ @SuppressWarnings("unused")
254+ public List<UserVideo> getVideos() {
255+ return videos;
256+ }
257+
258+ @SuppressWarnings("unused")
259+ public URI getNextPage() {
260+ return nextPage;
261+ }
262+
263+ }
264+
265+ public static class UserVideo {
266+
267+ private final int videoid;
268+
269+ private final String title;
270+
271+ private final Date added;
272+
273+ public UserVideo(int videoid, String title, Date added) {
274+ this.videoid = videoid;
275+ this.title = title;
276+ this.added = added;
277+ }
278+
279+ @SuppressWarnings("unused")
280+ public int getVideoid() {
281+ return videoid;
282+ }
283+
284+ public String getTitle() {
285+ return title;
286+ }
287+
288+ @SuppressWarnings("unused")
289+ public Date getAdded() {
290+ return added;
291+ }
292+ }
293+
294+}
added driver-examples/src/main/java/com/datastax/driver/examples/paging/RandomPagingRestUi.java +363 −0
@@ -0,0 +1,363 @@
1+/*
2+ * Copyright (C) 2012-2015 DataStax Inc.
3+ *
4+ * Licensed under the Apache License, Version 2.0 (the "License");
5+ * you may not use this file except in compliance with the License.
6+ * You may obtain a copy of the License at
7+ *
8+ * http://www.apache.org/licenses/LICENSE-2.0
9+ *
10+ * Unless required by applicable law or agreed to in writing, software
11+ * distributed under the License is distributed on an "AS IS" BASIS,
12+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+ * See the License for the specific language governing permissions and
14+ * limitations under the License.
15+ */
16+package com.datastax.driver.examples.paging;
17+
18+import com.datastax.driver.core.*;
19+import com.google.common.collect.Lists;
20+import com.sun.net.httpserver.HttpServer;
21+import org.glassfish.hk2.utilities.binding.AbstractBinder;
22+import org.glassfish.jersey.jdkhttp.JdkHttpServerFactory;
23+import org.glassfish.jersey.server.ResourceConfig;
24+
25+import javax.annotation.PostConstruct;
26+import javax.inject.Inject;
27+import javax.inject.Singleton;
28+import javax.ws.rs.*;
29+import javax.ws.rs.core.Context;
30+import javax.ws.rs.core.UriBuilder;
31+import javax.ws.rs.core.UriInfo;
32+import java.io.IOException;
33+import java.net.URI;
34+import java.util.Collections;
35+import java.util.Date;
36+import java.util.List;
37+import java.util.concurrent.ExecutorService;
38+import java.util.concurrent.Executors;
39+
40+/**
41+ * A stateless REST service (backed by
42+ * <a href="https://jersey.java.net/">Jersey</a>,
43+ * <a href="https://hk2.java.net/">HK2</a> and
44+ * the JDK HttpServer) that displays paginated results for a CQL query.
45+ * <p/>
46+ * Conversion to and from JSON is made through
47+ * <a href="https://jersey.java.net/documentation/latest/media.html#json.jackson">Jersey Jackson providers</a>.
48+ * <p/>
49+ * Navigation is bidirectional, and you can jump to a random page (by modifying the URL).
50+ * Cassandra does not support offset queries (see https://issues.apache.org/jira/browse/CASSANDRA-6511), so we emulate
51+ * it by restarting from the beginning each time, and iterating through the results until we reach the requested page.
52+ * This is fundamentally inefficient (O(n) in the number of rows skipped), but the tradeoff might be acceptable for some
53+ * use cases; for example, if you show 10 results per page and you think users are unlikely to browse past page 10,
54+ * you only need to retrieve at most 100 rows.
55+ * <p/>
56+ * Preconditions:
57+ * - a Cassandra cluster is running and accessible through the contacts points identified by CONTACT_POINTS and
58+ * CASSANDRA_PORT;
59+ * - port HTTP_PORT is available.
60+ * <p/>
61+ * Side effects:
62+ * - creates a new keyspace "examples" in the cluster. If a keyspace with this name already exists, it will be reused;
63+ * - creates a table "examples.random_paging_rest_ui". If it already exists, it will be reused;
64+ * - inserts data in the table;
65+ * - launches a REST server listening on HTTP_PORT.
66+ */
67+public class RandomPagingRestUi {
68+
69+ static final String[] CONTACT_POINTS = {"127.0.0.1"};
70+
71+ static final int CASSANDRA_PORT = 9042;
72+
73+ static final int HTTP_PORT = 8080;
74+
75+ static final int ITEMS_PER_PAGE = 10;
76+ // How many rows the driver will retrieve at a time.
77+ // This is set artificially low for the sake of this example. Unless your rows are very large, you can probably use
78+ // a much higher value (the driver's default is 5000).
79+ static final int FETCH_SIZE = 60;
80+
81+ static final URI BASE_URI = UriBuilder.fromUri("http://localhost/").path("").port(HTTP_PORT).build();
82+
83+ public static void main(String[] args) throws Exception {
84+
85+ Cluster cluster = null;
86+ try {
87+
88+ cluster = Cluster.builder()
89+ .addContactPoints(CONTACT_POINTS).withPort(CASSANDRA_PORT)
90+ .build();
91+ Session session = cluster.connect();
92+
93+ createSchema(session);
94+ populateSchema(session);
95+ startRestService(session);
96+
97+ } finally {
98+ if (cluster != null) cluster.close();
99+ }
100+
101+ }
102+
103+ // Creates a table storing videos by users, in a typically denormalized way
104+ private static void createSchema(Session session) {
105+ session.execute("CREATE KEYSPACE IF NOT EXISTS examples " +
106+ "WITH replication = {'class': 'SimpleStrategy', 'replication_factor': 1}");
107+ session.execute("CREATE TABLE IF NOT EXISTS examples.random_paging_rest_ui(" +
108+ "userid int, username text, " +
109+ "added timestamp, " +
110+ "videoid int, title text, " +
111+ "PRIMARY KEY (userid, added, videoid)" +
112+ ") WITH CLUSTERING ORDER BY (added DESC, videoid ASC)");
113+ }
114+
115+ private static void populateSchema(Session session) {
116+ // 3 users
117+ for (int i = 0; i < 3; i++) {
118+ // 49 videos each
119+ for (int j = 0; j < 49; j++) {
120+ int videoid = i * 100 + j;
121+ session.execute("INSERT INTO examples.random_paging_rest_ui (userid, username, added, videoid, title) VALUES (?, ?, ?, ?, ?)",
122+ i, "user " + i, new Date(j * 100000), videoid, "video " + videoid);
123+ }
124+ }
125+ }
126+
127+ // starts the REST server using JDK HttpServer (com.sun.net.httpserver.HttpServer)
128+ private static void startRestService(Session session) throws IOException, InterruptedException {
129+
130+ final HttpServer server = JdkHttpServerFactory.createHttpServer(BASE_URI, new VideoApplication(session), false);
131+ final ExecutorService executor = Executors.newSingleThreadExecutor();
132+ server.setExecutor(executor);
133+ Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() {
134+ @Override
135+ public void run() {
136+ System.out.println();
137+ System.out.println("Stopping REST Service");
138+ server.stop(0);
139+ executor.shutdownNow();
140+ System.out.println("REST Service stopped");
141+ }
142+ }));
143+ server.start();
144+
145+ System.out.println();
146+ System.out.printf("REST Service started on http://localhost:%d/users, press CTRL+C to stop%n", HTTP_PORT);
147+ System.out.println("To explore this example, start with the following request and walk from there:");
148+ System.out.printf("curl -i http://localhost:%d/users/1/videos%n", HTTP_PORT);
149+ System.out.println();
150+
151+ Thread.currentThread().join();
152+
153+ }
154+
155+ /**
156+ * Configures the REST application and handles injection of custom objects, such
157+ * as the driver session.
158+ * <p/>
159+ * This is also the place where you would normally configure JSON serialization, etc.
160+ * <p/>
161+ * Note that in this example, we rely on the automatic discovery and configuration of
162+ * Jackson through {@link org.glassfish.jersey.jackson.JacksonFeature}.
163+ */
164+ public static class VideoApplication extends ResourceConfig {
165+
166+ public VideoApplication(final Session session) {
167+ super(UserService.class);
168+ // AbstractBinder is provided by HK2
169+ register(new AbstractBinder() {
170+
171+ @Override
172+ protected void configure() {
173+ bind(session).to(Session.class);
174+ }
175+
176+ });
177+ }
178+
179+ }
180+
181+ /**
182+ * A typical REST service, handling requests involving users.
183+ * <p/>
184+ * Typically, this service would contain methods for listing and searching for users,
185+ * and methods to retrieve user details. Here, for brevity,
186+ * only one method, listing videos by user, is implemented.
187+ */
188+ @Singleton
189+ @Path("/users")
190+ @Produces("application/json")
191+ public static class UserService {
192+
193+ @Inject
194+ private Session session;
195+
196+ @Context
197+ private UriInfo uri;
198+
199+ private PreparedStatement videosByUser;
200+ private Pager pager;
201+
202+ @PostConstruct
203+ @SuppressWarnings("unused")
204+ public void init() {
205+ this.pager = new Pager(session, ITEMS_PER_PAGE);
206+ this.videosByUser = session.prepare("SELECT videoid, title, added FROM examples.random_paging_rest_ui WHERE userid = ?");
207+ }
208+
209+ /**
210+ * Returns a paginated list of all the videos created by the given user.
211+ *
212+ * @param userid the user ID.
213+ * @param page the page to request, or {@code null} to get the first page.
214+ */
215+ @GET
216+ @Path("/{userid}/videos")
217+ public UserVideosResponse getUserVideos(@PathParam("userid") int userid, @QueryParam("page") Integer page) {
218+
219+ Statement statement = videosByUser.bind(userid).setFetchSize(FETCH_SIZE);
220+
221+ if (page == null) page = 1;
222+ ResultSet rs = pager.skipTo(statement, page);
223+
224+ List<UserVideo> videos;
225+ boolean empty = rs.isExhausted();
226+ if (empty) {
227+ videos = Collections.emptyList();
228+ } else {
229+ int remaining = ITEMS_PER_PAGE;
230+ videos = Lists.newArrayListWithExpectedSize(remaining);
231+ for (Row row : rs) {
232+ UserVideo video = new UserVideo(
233+ row.getInt("videoid"),
234+ row.getString("title"),
235+ row.getTimestamp("added"));
236+ videos.add(video);
237+
238+ if (--remaining == 0)
239+ break;
240+ }
241+ }
242+
243+ URI previous = (page == 1) ? null
244+ : uri.getAbsolutePathBuilder().queryParam("page", page - 1).build();
245+ URI next = (empty) ? null
246+ : uri.getAbsolutePathBuilder().queryParam("page", page + 1).build();
247+ return new UserVideosResponse(videos, previous, next);
248+ }
249+
250+ }
251+
252+ public static class UserVideosResponse {
253+
254+ private final List<UserVideo> videos;
255+
256+ private final URI previousPage;
257+
258+ private final URI nextPage;
259+
260+ public UserVideosResponse(List<UserVideo> videos, URI previousPage, URI nextPage) {
261+ this.videos = videos;
262+ this.previousPage = previousPage;
263+ this.nextPage = nextPage;
264+ }
265+
266+ @SuppressWarnings("unused")
267+ public List<UserVideo> getVideos() {
268+ return videos;
269+ }
270+
271+ @SuppressWarnings("unused")
272+ public URI getPreviousPage() {
273+ return previousPage;
274+ }
275+
276+ @SuppressWarnings("unused")
277+ public URI getNextPage() {
278+ return nextPage;
279+ }
280+
281+ }
282+
283+ public static class UserVideo {
284+
285+ private final int videoid;
286+
287+ private final String title;
288+
289+ private final Date added;
290+
291+ public UserVideo(int videoid, String title, Date added) {
292+ this.videoid = videoid;
293+ this.title = title;
294+ this.added = added;
295+ }
296+
297+ @SuppressWarnings("unused")
298+ public int getVideoid() {
299+ return videoid;
300+ }
301+
302+ public String getTitle() {
303+ return title;
304+ }
305+
306+ @SuppressWarnings("unused")
307+ public Date getAdded() {
308+ return added;
309+ }
310+ }
311+
312+ /**
313+ * Helper class to emulate random paging.
314+ * <p/>
315+ * Note that it MUST be stateless, because it is cached as a field in our HTTP handler.
316+ */
317+ static class Pager {
318+ private final Session session;
319+ private final int pageSize;
320+
321+ Pager(Session session, int pageSize) {
322+ this.session = session;
323+ this.pageSize = pageSize;
324+ }
325+
326+ ResultSet skipTo(Statement statement, int displayPage) {
327+ // Absolute index of the first row we want to display on the web page. Our goal is that rs.next() returns
328+ // that row.
329+ int targetRow = (displayPage - 1) * pageSize;
330+
331+ ResultSet rs = session.execute(statement);
332+ // Absolute index of the next row returned by rs (if it is not exhausted)
333+ int currentRow = 0;
334+ int fetchedSize = rs.getAvailableWithoutFetching();
335+ byte[] nextState = rs.getExecutionInfo().getPagingStateUnsafe();
336+
337+ // Skip protocol pages until we reach the one that contains our target row.
338+ // For example, if the first query returned 60 rows and our target is row number 90, we know we can skip
339+ // those 60 rows directly without even iterating through them.
340+ // This part is optional, we could simply iterate through the rows with the for loop below, but that's
341+ // slightly less efficient because iterating each row involves a bit of internal decoding.
342+ while (fetchedSize > 0 && nextState != null && currentRow + fetchedSize < targetRow) {
343+ statement.setPagingStateUnsafe(nextState);
344+ rs = session.execute(statement);
345+ currentRow += fetchedSize;
346+ fetchedSize = rs.getAvailableWithoutFetching();
347+ nextState = rs.getExecutionInfo().getPagingStateUnsafe();
348+ }
349+
350+ if (currentRow < targetRow) {
351+ for (@SuppressWarnings("unused") Row row : rs) {
352+ if (++currentRow == targetRow) break;
353+ }
354+ }
355+ // If targetRow is past the end, rs will be exhausted.
356+ // This means you can request a page past the end in the web UI (e.g. request page 12 while there are only
357+ // 10 pages), and it will show up as empty.
358+ // One improvement would be to detect that and take a different action, for example redirect to page 10 or
359+ // show an error message, this is left as an exercise for the reader.
360+ return rs;
361+ }
362+ }
363+}