Search in sources :

Example 6 with Response

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

the class StubClientTest method shouldReturnIterativeRepliesWithVaryingStatusCodes.

@Test
public void shouldReturnIterativeRepliesWithVaryingStatusCodes() throws Exception {
    ResponseWithDelay response1 = ResponseWithDelay.forResponse(Response.of(Status.ACCEPTED, encodeUtf8("first response")));
    ResponseWithDelay response2 = ResponseWithDelay.forResponse(Response.of(Status.FORBIDDEN, encodeUtf8("second response")));
    List<ResponseWithDelay> responses = Arrays.asList(response1, response2);
    ResponseSource responseSequence = Responses.sequence(responses);
    stubClient.respond(responseSequence).to("http://ping");
    CompletionStage<Response<ByteString>> reply1 = getResponseFromPing();
    CompletionStage<Response<ByteString>> reply2 = getResponseFromPing();
    Response<ByteString> message1 = reply1.toCompletableFuture().get();
    Response<ByteString> message2 = reply2.toCompletableFuture().get();
    assertThat(message1.status(), is(Status.ACCEPTED));
    assertThat(message2.status(), is(Status.FORBIDDEN));
    assertThat(message1.payload().get().utf8(), is("first response"));
    assertThat(message2.payload().get().utf8(), is("second response"));
}
Also used : Response(com.spotify.apollo.Response) ResponseWithDelay(com.spotify.apollo.test.response.ResponseWithDelay) ResponseSource(com.spotify.apollo.test.response.ResponseSource) ByteString(okio.ByteString) Test(org.junit.Test)

Example 7 with Response

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

the class RouteTransformMetricsExampleTest method responsePayloadSizeHistogram.

/**
 * Middleware to track response payload size in a Histogram,
 * tagged with an endpoint tag set to the given endpoint name.
 */
public Middleware<AsyncHandler<Response<ByteString>>, AsyncHandler<Response<ByteString>>> responsePayloadSizeHistogram(String endpointName) {
    final MetricId histogramId = MetricId.build().tagged("service", serviceName).tagged("endpoint", endpointName).tagged("what", "endpoint-response-size");
    final Histogram histogram = registry.histogram(histogramId);
    return (inner) -> (requestContext) -> inner.invoke(requestContext).whenComplete((response, t) -> {
        if (response != null) {
            histogram.update(response.payload().map(ByteString::size).orElse(0));
        }
    });
}
Also used : Matchers.hasEntry(org.hamcrest.Matchers.hasEntry) Histogram(com.codahale.metrics.Histogram) Response(com.spotify.apollo.Response) AsyncHandler(com.spotify.apollo.route.AsyncHandler) RequestContext(com.spotify.apollo.RequestContext) Matchers.allOf(org.hamcrest.Matchers.allOf) MetricId(com.spotify.metrics.core.MetricId) SemanticMetricRegistry(com.spotify.metrics.core.SemanticMetricRegistry) Test(org.junit.Test) Mockito.when(org.mockito.Mockito.when) Middleware(com.spotify.apollo.route.Middleware) Route(com.spotify.apollo.route.Route) Matchers.hasProperty(org.hamcrest.Matchers.hasProperty) Matchers.containsInAnyOrder(org.hamcrest.Matchers.containsInAnyOrder) ByteString(okio.ByteString) MatcherAssert.assertThat(org.hamcrest.MatcherAssert.assertThat) Collections(java.util.Collections) Mockito.mock(org.mockito.Mockito.mock) MetricId(com.spotify.metrics.core.MetricId) Histogram(com.codahale.metrics.Histogram) ByteString(okio.ByteString)

Example 8 with Response

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

the class FallbackClient method send.

@Override
public CompletionStage<Response<ByteString>> send(Request request, Optional<Request> incoming) {
    final CompletionStage<Response<ByteString>> send = mainClient.send(request, incoming);
    return fallbackCompose(send, t -> {
        if (NoMatchingResponseFoundException.class.isAssignableFrom(t.getClass())) {
            NoMatchingResponseFoundException e = (NoMatchingResponseFoundException) t;
            LOG.debug("Falling back to real client: {}", e.getMessage());
            return fallbackClient.send(request, incoming);
        } else {
            return send;
        }
    });
}
Also used : Response(com.spotify.apollo.Response) NoMatchingResponseFoundException(com.spotify.apollo.test.StubClient.NoMatchingResponseFoundException)

Example 9 with Response

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

the class MiddlewaresTest method httpShouldNotSetContentLengthOrAppendPayloadForInvalidStatusCodes.

@Test
public void httpShouldNotSetContentLengthOrAppendPayloadForInvalidStatusCodes() throws Exception {
    List<StatusType> invalid = ImmutableList.of(Status.createForCode(100), NO_CONTENT, NOT_MODIFIED);
    for (StatusType status : invalid) {
        CompletableFuture<Response<ByteString>> future = new CompletableFuture<>();
        delegate = requestContext -> future;
        future.complete(Response.of(status, ByteString.of((byte) 14, (byte) 19)));
        Response<ByteString> result = getResult(Middlewares.httpPayloadSemantics(delegate));
        Optional<String> header = result.headers().get("Content-Length");
        assertThat("no content-length for " + status, header, is(Optional.empty()));
        assertThat("no payload for " + status, result.payload(), is(Optional.<ByteString>empty()));
    }
}
Also used : Response(com.spotify.apollo.Response) CompletableFuture(java.util.concurrent.CompletableFuture) StatusType(com.spotify.apollo.StatusType) ByteString(okio.ByteString) ByteString(okio.ByteString) Test(org.junit.Test)

Example 10 with Response

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

the class IrisPrediction method predict.

/**
 * Prediction endpoint. Takes a request in a from of a String containing iris features `-`
 * separated, and returns a response in a form of a predicted iris class.
 */
public static Response<String> predict(final String requestFeatures) {
    if (requestFeatures == null) {
        return Response.forStatus(Status.BAD_REQUEST);
    }
    final String[] features = requestFeatures.split("-");
    if (features.length != 4) {
        return Response.forStatus(Status.BAD_REQUEST);
    }
    final Iris featureData = new Iris(Option.apply(Double.parseDouble(features[0])), Option.apply(Double.parseDouble(features[1])), Option.apply(Double.parseDouble(features[2])), Option.apply(Double.parseDouble(features[3])), Option.empty());
    int[] predictions = new int[0];
    try {
        predictions = predictor.predict(featureData).thenApply(p -> p.stream().mapToInt(prediction -> prediction.value().intValue()).toArray()).toCompletableFuture().get();
    } catch (final Exception e) {
        e.printStackTrace();
    // TODO: what to return in case of failure here?
    }
    final String predictedClass = idToClass.get(predictions[0]);
    return Response.forPayload(predictedClass);
}
Also used : Example(org.tensorflow.example.Example) Response(com.spotify.apollo.Response) FeatranExtractFns(com.spotify.zoltar.featran.FeatranExtractFns) Tensors(org.tensorflow.Tensors) Predictors(com.spotify.zoltar.Predictors) Session(org.tensorflow.Session) CompletableFuture(java.util.concurrent.CompletableFuture) TensorFlowModel(com.spotify.zoltar.tf.TensorFlowModel) TensorFlowPredictFn(com.spotify.zoltar.tf.TensorFlowPredictFn) IrisFeaturesSpec(com.spotify.zoltar.IrisFeaturesSpec) Map(java.util.Map) URI(java.net.URI) Tensor(org.tensorflow.Tensor) Status(com.spotify.apollo.Status) CompletableFutures(com.spotify.futures.CompletableFutures) Prediction(com.spotify.zoltar.Prediction) FeatureSpec(com.spotify.featran.FeatureSpec) TensorFlowExtras(com.spotify.zoltar.tf.TensorFlowExtras) ImmutableMap(com.google.common.collect.ImmutableMap) Files(java.nio.file.Files) JTensor(com.spotify.zoltar.tf.JTensor) IOException(java.io.IOException) Option(scala.Option) Collectors(java.util.stream.Collectors) Iris(com.spotify.zoltar.IrisFeaturesSpec.Iris) List(java.util.List) Paths(java.nio.file.Paths) ModelLoader(com.spotify.zoltar.ModelLoader) Predictor(com.spotify.zoltar.Predictor) ExtractFn(com.spotify.zoltar.FeatureExtractFns.ExtractFn) Models(com.spotify.zoltar.Models) Iris(com.spotify.zoltar.IrisFeaturesSpec.Iris) IOException(java.io.IOException)

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