| 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 | } |