ListPeopleServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { FetchOptions fetchOptions = FetchOptions.Builder.withLimit(PAGE_SIZE); String startCursor = req.getParameter("cursor"); if (startCursor != null) { fetchOptions.startCursor(Cursor.fromWebSafeString(startCursor)); } Query q = new Query("Person").addSort("name", SortDirection.ASCENDING); PreparedQuery pq = datastore.prepare(q); QueryResultList<Entity> results; try { results = pq.asQueryResultList(fetchOptions); } catch (IllegalArgumentException e) { resp.sendRedirect("/people"); return; } resp.setContentType("text/html"); resp.setCharacterEncoding("UTF-8"); PrintWriter w = resp.getWriter(); w.println("<!DOCTYPE html>"); w.println("<meta charset=\"utf-8\">"); w.println("<title>Cloud Datastore Cursor Sample</title>"); w.println("<ul>"); for (Entity entity : results) { w.println("<li>" + entity.getProperty("name") + "</li>"); } w.println("</ul>"); String cursorString = results.getCursor().toWebSafeString(); w.println("<a href='/people?cursor=" + cursorString + "'>Next page</a>"); } ListPeopleServlet();   }
@Test public void doGet_noCursor_writesNames() throws Exception { servletUnderTest.doGet(mockRequest, mockResponse); String response = responseWriter.toString(); for (int i = 0; i < ListPeopleServlet.PAGE_SIZE; i++) { assertWithMessage("ListPeopleServlet response").that(response).contains(TEST_NAMES.get(i)); } }
@Test public void doGet_withValidCursor_writesNames() throws Exception { when(mockRequest.getParameter("cursor")).thenReturn(getFirstCursor()); servletUnderTest.doGet(mockRequest, mockResponse); String response = responseWriter.toString(); int i = 0; while (i + ListPeopleServlet.PAGE_SIZE < TEST_NAMES.size() && i < ListPeopleServlet.PAGE_SIZE) { assertWithMessage("ListPeopleServlet response") .that(response) .contains(TEST_NAMES.get(i + ListPeopleServlet.PAGE_SIZE)); i++; } }
@Test public void doGet_withInvalidCursor_writesRedirect() throws Exception { when(mockRequest.getParameter("cursor")).thenReturn("ThisCursorIsTotallyInvalid"); servletUnderTest.doGet(mockRequest, mockResponse); verify(mockResponse).sendRedirect("/people"); }