HelloSpanner implements HttpFunction { @Override public void service(HttpRequest request, HttpResponse response) throws Exception { var writer = new PrintWriter(response.getWriter()); try { DatabaseClient client = getClient(); try (ResultSet rs = client .singleUse() .executeQuery(Statement.of("SELECT SingerId, AlbumId, AlbumTitle FROM Albums"))) { writer.printf("Albums:%n"); while (rs.next()) { writer.printf( "%d %d %s%n", rs.getLong("SingerId"), rs.getLong("AlbumId"), rs.getString("AlbumTitle")); } } catch (SpannerException e) { writer.printf("Error querying database: %s%n", e.getMessage()); response.setStatusCode(HttpStatusCodes.STATUS_CODE_SERVER_ERROR, e.getMessage()); } } catch (Throwable t) { logger.log(Level.SEVERE, "Spanner example failed", t); writer.printf("Error setting up Spanner: %s%n", t.getMessage()); response.setStatusCode(HttpStatusCodes.STATUS_CODE_SERVER_ERROR, t.getMessage()); } }  @Override void service(HttpRequest request, HttpResponse response);  }
@Test public void functionsHelloSpanner_shouldListAlbums() throws Exception { setupSuccessfulMockQuery(); new HelloSpanner() { @Override DatabaseClient getClient() { return client; } }.service(request, response); writerOut.flush(); assertThat(responseOut.toString()).isEqualTo("Albums:\n1 1 Album 1\n2 1 Album 2\n"); }
@Test public void functionsHelloSpanner_shouldShowQueryError() throws Exception { setupFailedMockQuery(); new HelloSpanner() { @Override DatabaseClient getClient() { return client; } }.service(request, response); writerOut.flush(); assertThat(responseOut.toString()) .isEqualTo("Error querying database: NOT_FOUND: Table `Albums` not found\n"); }
@Test public void functionsHelloSpanner_shouldShowInitializationError() throws Exception { new HelloSpanner() { @Override DatabaseClient getClient() { throw new IllegalArgumentException("Invalid database name"); } }.service(request, response); writerOut.flush(); assertThat(responseOut.toString()) .isEqualTo("Error setting up Spanner: Invalid database name\n"); assertThat(logHandler.getStoredLogRecords().get(0).getMessage()) .startsWith("Spanner example failed"); }