Search in sources :

Example 1 with Response

use of com.spotify.apollo.Response in project apollo by spotify.

the class StubClient method send.

@Override
public CompletionStage<Response<ByteString>> send(Request request) {
    final ResponseSource responseSource = responseSource(request);
    if (responseSource == null) {
        final NoMatchingResponseFoundException notFound = new NoMatchingResponseFoundException(formatRequestNotMatchedExceptionMessage(request));
        final CompletableFuture<Response<ByteString>> notFoundFuture = new CompletableFuture<>();
        notFoundFuture.completeExceptionally(notFound);
        return notFoundFuture;
    }
    // Create response task
    final ResponseWithDelay responseWithDelay = responseSource.create(request);
    // Schedule a response in the future
    final CompletableFuture<Response<ByteString>> future = new CompletableFuture<>();
    final Runnable replyTask = () -> {
        Response<ByteString> response = responseWithDelay.getResponse();
        requestsAndResponses.add(RequestResponsePair.create(request, response));
        future.complete(response);
    };
    if (responseWithDelay.getDelayMillis() <= 0) {
        replyTask.run();
    } else {
        executor.schedule(replyTask, responseWithDelay.getDelayMillis(), TimeUnit.MILLISECONDS);
    }
    return future;
}
Also used : Response(com.spotify.apollo.Response) CompletableFuture(java.util.concurrent.CompletableFuture) ResponseWithDelay(com.spotify.apollo.test.response.ResponseWithDelay) ResponseSource(com.spotify.apollo.test.response.ResponseSource)

Example 2 with Response

use of com.spotify.apollo.Response in project apollo by spotify.

the class MinimalApp method beer.

static CompletionStage<Response<String>> beer(RequestContext context) {
    Request breweryRequest = Request.forUri("http://brewery/order");
    CompletionStage<Response<ByteString>> orderRequest = context.requestScopedClient().send(breweryRequest);
    return orderRequest.thenApply(orderResponse -> {
        if (orderResponse.status() != Status.OK) {
            return Response.forStatus(Status.INTERNAL_SERVER_ERROR);
        }
        // assume we get an order id as a plaintext payload
        final String orderId = orderResponse.payload().get().utf8();
        return Response.forPayload("your order is " + orderId);
    });
}
Also used : Response(com.spotify.apollo.Response) Request(com.spotify.apollo.Request) ByteString(okio.ByteString)

Example 3 with Response

use of com.spotify.apollo.Response in project apollo by spotify.

the class AlbumResource method getAlbums.

CompletionStage<Response<ArrayList<Album>>> getAlbums(RequestContext requestContext, String tag) {
    // We need to first query the search API, parse the result, then query the album API.
    Request searchRequest = Request.forUri(SEARCH_API + "?type=album&q=tag%3A" + tag);
    Client client = requestContext.requestScopedClient();
    return client.send(searchRequest).thenComposeAsync(response -> {
        String ids = parseResponseAlbumIds(response.payload().get().utf8());
        return client.send(Request.forUri(ALBUM_API + "?ids=" + ids));
    }).thenApplyAsync(response -> Response.ok().withPayload(parseAlbumData(response.payload().get().utf8())));
}
Also used : Response(com.spotify.apollo.Response) AsyncHandler(com.spotify.apollo.route.AsyncHandler) Request(com.spotify.apollo.Request) ObjectWriter(com.fasterxml.jackson.databind.ObjectWriter) RequestContext(com.spotify.apollo.RequestContext) Album(com.spotify.apollo.example.data.Album) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) JsonSerializerMiddlewares(com.spotify.apollo.route.JsonSerializerMiddlewares) IOException(java.io.IOException) Route(com.spotify.apollo.route.Route) ArrayList(java.util.ArrayList) CompletionStage(java.util.concurrent.CompletionStage) Stream(java.util.stream.Stream) StringJoiner(java.util.StringJoiner) ByteString(okio.ByteString) Artist(com.spotify.apollo.example.data.Artist) JsonNode(com.fasterxml.jackson.databind.JsonNode) Client(com.spotify.apollo.Client) Request(com.spotify.apollo.Request) ByteString(okio.ByteString) Client(com.spotify.apollo.Client)

Example 4 with Response

use of com.spotify.apollo.Response in project apollo by spotify.

the class ArtistResource method getArtistTopTracks.

CompletionStage<Response<ArrayList<Track>>> getArtistTopTracks(RequestContext requestContext) {
    // Validate request
    Optional<String> query = requestContext.request().parameter("q");
    if (!query.isPresent()) {
        return CompletableFuture.completedFuture(Response.forStatus(Status.BAD_REQUEST.withReasonPhrase("No search query")));
    }
    String country = requestContext.pathArgs().get("country");
    // We need to first query the search API, parse the result, then query top-tracks.
    Request searchRequest = Request.forUri(SEARCH_API + "?type=artist&q=" + query.get());
    Client client = requestContext.requestScopedClient();
    return client.send(searchRequest).thenComposeAsync(response -> {
        String topArtistId = parseFirstArtistId(response.payload().get().utf8());
        Request topTracksRequest = Request.forUri(String.format("%s/%s/top-tracks?country=%s", ARTIST_API, topArtistId, country));
        return client.send(topTracksRequest);
    }).thenApplyAsync(response -> Response.ok().withPayload(parseTopTracks(response.payload().get().utf8()))).exceptionally(throwable -> Response.forStatus(Status.INTERNAL_SERVER_ERROR.withReasonPhrase("Something failed")));
}
Also used : Response(com.spotify.apollo.Response) AsyncHandler(com.spotify.apollo.route.AsyncHandler) Request(com.spotify.apollo.Request) ObjectWriter(com.fasterxml.jackson.databind.ObjectWriter) RequestContext(com.spotify.apollo.RequestContext) Album(com.spotify.apollo.example.data.Album) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) JsonSerializerMiddlewares(com.spotify.apollo.route.JsonSerializerMiddlewares) IOException(java.io.IOException) CompletableFuture(java.util.concurrent.CompletableFuture) Route(com.spotify.apollo.route.Route) ArrayList(java.util.ArrayList) Track(com.spotify.apollo.example.data.Track) CompletionStage(java.util.concurrent.CompletionStage) Stream(java.util.stream.Stream) ByteString(okio.ByteString) Artist(com.spotify.apollo.example.data.Artist) Optional(java.util.Optional) JsonNode(com.fasterxml.jackson.databind.JsonNode) Client(com.spotify.apollo.Client) Status(com.spotify.apollo.Status) Request(com.spotify.apollo.Request) ByteString(okio.ByteString) Client(com.spotify.apollo.Client)

Example 5 with Response

use of com.spotify.apollo.Response in project apollo by spotify.

the class AsyncContextOngoingRequestTest method shouldLogWarningOnErrorWritingResponse.

// note: this test may fail when running in IntelliJ, due to
// https://youtrack.jetbrains.com/issue/IDEA-122783
@Test
public void shouldLogWarningOnErrorWritingResponse() throws Exception {
    HttpServletResponse spy = spy(response);
    when(asyncContext.getResponse()).thenReturn(spy);
    doReturn(outputStream).when(spy).getOutputStream();
    doThrow(new IOException("expected")).when(outputStream).write(any(byte[].class));
    ongoingRequest.reply(Response.forPayload(ByteString.encodeUtf8("floop")));
    List<LoggingEvent> events = testLogger.getLoggingEvents().stream().filter(event -> event.getLevel() == Level.WARN).filter(event -> event.getMessage().contains("Failed to write response")).collect(Collectors.toList());
    assertThat(events, hasSize(1));
}
Also used : LoggingEvent(uk.org.lidalia.slf4jtest.LoggingEvent) CoreMatchers.is(org.hamcrest.CoreMatchers.is) Response(com.spotify.apollo.Response) Request(com.spotify.apollo.Request) Mock(org.mockito.Mock) Level(uk.org.lidalia.slf4jext.Level) TestLoggerFactory(uk.org.lidalia.slf4jtest.TestLoggerFactory) INTERNAL_SERVER_ERROR(com.spotify.apollo.Status.INTERNAL_SERVER_ERROR) Mockito.spy(org.mockito.Mockito.spy) MockHttpServletResponse(org.springframework.mock.web.MockHttpServletResponse) OngoingRequest(com.spotify.apollo.request.OngoingRequest) Assert.assertThat(org.junit.Assert.assertThat) MockitoAnnotations(org.mockito.MockitoAnnotations) AsyncContext(javax.servlet.AsyncContext) Mockito.doThrow(org.mockito.Mockito.doThrow) IM_A_TEAPOT(com.spotify.apollo.Status.IM_A_TEAPOT) TestLogger(uk.org.lidalia.slf4jtest.TestLogger) ByteString(okio.ByteString) Matchers.hasSize(org.hamcrest.Matchers.hasSize) LoggingEvent(uk.org.lidalia.slf4jtest.LoggingEvent) Mockito.doReturn(org.mockito.Mockito.doReturn) Status(com.spotify.apollo.Status) Before(org.junit.Before) BAD_REQUEST(com.spotify.apollo.Status.BAD_REQUEST) HttpServletResponse(javax.servlet.http.HttpServletResponse) Test(org.junit.Test) IOException(java.io.IOException) Mockito.when(org.mockito.Mockito.when) TestLoggerFactoryResetRule(uk.org.lidalia.slf4jtest.TestLoggerFactoryResetRule) Instant(java.time.Instant) Collectors(java.util.stream.Collectors) Mockito.verify(org.mockito.Mockito.verify) Matchers.any(org.mockito.Matchers.any) List(java.util.List) Rule(org.junit.Rule) RequestMetadataImpl(com.spotify.apollo.request.RequestMetadataImpl) Optional(java.util.Optional) MockHttpServletResponse(org.springframework.mock.web.MockHttpServletResponse) HttpServletResponse(javax.servlet.http.HttpServletResponse) IOException(java.io.IOException) Test(org.junit.Test)

Aggregations

Response (com.spotify.apollo.Response)10 ByteString (okio.ByteString)7 Request (com.spotify.apollo.Request)4 IOException (java.io.IOException)4 CompletableFuture (java.util.concurrent.CompletableFuture)4 Test (org.junit.Test)4 RequestContext (com.spotify.apollo.RequestContext)3 Status (com.spotify.apollo.Status)3 AsyncHandler (com.spotify.apollo.route.AsyncHandler)3 Route (com.spotify.apollo.route.Route)3 JsonNode (com.fasterxml.jackson.databind.JsonNode)2 ObjectMapper (com.fasterxml.jackson.databind.ObjectMapper)2 ObjectWriter (com.fasterxml.jackson.databind.ObjectWriter)2 Client (com.spotify.apollo.Client)2 Album (com.spotify.apollo.example.data.Album)2 Artist (com.spotify.apollo.example.data.Artist)2 JsonSerializerMiddlewares (com.spotify.apollo.route.JsonSerializerMiddlewares)2 ResponseSource (com.spotify.apollo.test.response.ResponseSource)2 ResponseWithDelay (com.spotify.apollo.test.response.ResponseWithDelay)2 ArrayList (java.util.ArrayList)2