akka.http.javadsl.model.HttpResponse Java Examples

The following examples show how to use akka.http.javadsl.model.HttpResponse. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: AkkaHttpClientITest.java    From java-specialagent with Apache License 2.0 6 votes vote down vote up
public static void main(final String[] args) throws Exception {
  final ActorSystem system = ActorSystem.create();
  final Materializer materializer = ActorMaterializer.create(system);

  final Http http = getHttp(system);
  final CompletionStage<HttpResponse> stage = http.singleRequest(HttpRequest.GET("http://www.google.com"));
  stage.whenComplete(new BiConsumer<HttpResponse,Throwable>() {
    @Override
    public void accept(final HttpResponse httpResponse, final Throwable throwable) {
      TestUtil.checkActiveSpan();
      System.out.println(httpResponse.status());
    }
  }).toCompletableFuture().get().entity().getDataBytes().runForeach(param -> {}, materializer);

  stage.thenRun(system::terminate).toCompletableFuture().get();
  TestUtil.checkSpan(new ComponentSpanCount("akka-http-client", 1));
}
 
Example #2
Source File: AkkaHttpSyncHandler.java    From java-specialagent with Apache License 2.0 6 votes vote down vote up
@Override
public HttpResponse apply(final HttpRequest request) throws Exception {
  final Span span = buildSpan(request);
  try (final Scope scope = GlobalTracer.get().activateSpan(span)) {
    final HttpResponse response = handler.apply(request);
    span.setTag(Tags.HTTP_STATUS, response.status().intValue());
    return response;
  }
  catch (final Exception e) {
    OpenTracingApiUtil.setErrorTag(span, e);
    throw e;
  }
  finally {
    span.finish();
  }
}
 
Example #3
Source File: DittoRuntimeExceptionToHttpResponseTest.java    From ditto with Eclipse Public License 2.0 6 votes vote down vote up
@Test
public void conversionReturnsExpected() {
    final byte invalidApiVersion = -1;
    final DittoHeaders dittoHeaders = DittoHeaders.newBuilder()
            .correlationId(testName.getMethodName())
            .build();
    final CommandNotSupportedException exception = CommandNotSupportedException.newBuilder(invalidApiVersion)
            .dittoHeaders(dittoHeaders)
            .build();
    final Map<String, String> externalHeaders = headerTranslator.toExternalHeaders(dittoHeaders);
    final List<HttpHeader> httpHeaders = new ArrayList<>(externalHeaders.size());
    externalHeaders.forEach((key, value) -> httpHeaders.add(HttpHeader.parse(key, value)));
    final HttpResponse expected = HttpResponse.create()
            .withStatus(exception.getStatusCode().toInt())
            .withHeaders(httpHeaders)
            .withEntity(ContentTypes.APPLICATION_JSON, ByteString.fromString(exception.toJsonString()));

    final DittoRuntimeExceptionToHttpResponse underTest =
            DittoRuntimeExceptionToHttpResponse.getInstance(headerTranslator);

    final HttpResponse actual = underTest.apply(exception);

    assertThat(actual).isEqualTo(expected);
}
 
Example #4
Source File: HttpPushClientActorTest.java    From ditto with Eclipse Public License 2.0 6 votes vote down vote up
@Test
public void placeholderReplacement() throws Exception {
    final Target target = TestConstants.Targets.TARGET_WITH_PLACEHOLDER
            .withAddress("PATCH:" + TestConstants.Targets.TARGET_WITH_PLACEHOLDER.getAddress());
    connection = connection.toBuilder().setTargets(singletonList(target)).build();

    new TestKit(actorSystem) {{
        // GIVEN: local HTTP connection is connected
        final ActorRef underTest = actorSystem.actorOf(createClientActor(getRef(), getConnection(false)));
        underTest.tell(OpenConnection.of(connection.getId(), DittoHeaders.empty()), getRef());
        expectMsg(new Status.Success(BaseClientState.CONNECTED));

        // WHEN: a thing event is sent to a target with header mapping content-type=application/json
        final ThingModifiedEvent thingModifiedEvent = TestConstants.thingModified(Collections.emptyList());
        final OutboundSignal outboundSignal =
                OutboundSignalFactory.newOutboundSignal(thingModifiedEvent, singletonList(target));
        underTest.tell(outboundSignal, getRef());

        // THEN: a POST-request is forwarded to the path defined in the target
        final HttpRequest thingModifiedRequest = requestQueue.take();
        responseQueue.offer(HttpResponse.create().withStatus(StatusCodes.OK));
        assertThat(thingModifiedRequest.getUri().getPathString()).isEqualTo("/target:ditto/thing@twin");
    }};
}
 
Example #5
Source File: AkkaAgentIntercept.java    From java-specialagent with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
public static Object requestEnd(final Object returned, final Throwable thrown) {
  final LocalSpanContext context = LocalSpanContext.get(COMPONENT_NAME_CLIENT);
  if (context == null || context.decrementAndGet() != 0)
    return returned;

  final Span span = context.getSpan();
  context.closeScope();

  if (thrown != null) {
    OpenTracingApiUtil.setErrorTag(span, thrown);
    span.finish();
    return returned;
  }

  return ((CompletionStage<HttpResponse>)returned).thenApply(httpResponse -> {
    span.setTag(Tags.HTTP_STATUS, httpResponse.status().intValue());
    span.finish();
    return httpResponse;
  }).exceptionally(throwable -> {
    OpenTracingApiUtil.setErrorTag(span, throwable);
    span.finish();
    return null;
  });
}
 
Example #6
Source File: AkkaHttpClientServiceShould.java    From mutual-tls-ssl with Apache License 2.0 6 votes vote down vote up
@Test
public void executeRequest() {
    HttpResponse httpResponse = HttpResponse.create()
            .withEntity(ContentTypes.TEXT_PLAIN_UTF8, "Hello")
            .withStatus(StatusCodes.OK);

    when(akkaHttpClient.singleRequest(any(HttpRequest.class))).thenReturn(CompletableFuture.completedFuture(httpResponse));

    ArgumentCaptor<HttpRequest> httpRequestArgumentCaptor = ArgumentCaptor.forClass(HttpRequest.class);

    ClientResponse clientResponse = victim.executeRequest(HTTP_URL);

    assertThat(clientResponse.getStatusCode()).isEqualTo(200);
    assertThat(clientResponse.getResponseBody()).isEqualTo("Hello");

    verify(akkaHttpClient, times(1)).singleRequest(httpRequestArgumentCaptor.capture());
    assertThat(httpRequestArgumentCaptor.getValue().method().value()).isEqualTo("GET");
    assertThat(httpRequestArgumentCaptor.getValue().getHeaders()).containsExactly(HttpHeader.parse(TestConstants.HEADER_KEY_CLIENT_TYPE, AKKA_HTTP_CLIENT.getValue()));
    assertThat(httpRequestArgumentCaptor.getValue().getUri().toString()).isEqualTo(HTTP_URL);
}
 
Example #7
Source File: HealthService.java    From ari-proxy with GNU Affero General Public License v3.0 6 votes vote down vote up
private CompletionStage<ServerBinding> startHttpServer() {
	final ActorSystem system = getContext().getSystem();
	final Http http = Http.get(system);
	final ActorMaterializer materializer = ActorMaterializer.create(system);

	final Flow<HttpRequest, HttpResponse, NotUsed> routeFlow = createRoute().flow(system, materializer);

	final String address = "0.0.0.0";
	final CompletionStage<ServerBinding> binding = http.bindAndHandle(
			routeFlow,
			ConnectHttp.toHost(address, httpPort),
			materializer
	);

	log().info("HTTP server online at http://{}:{}/...", address, httpPort);

	return binding;
}
 
Example #8
Source File: AbstractHttpRequestActor.java    From ditto with Eclipse Public License 2.0 6 votes vote down vote up
private HttpResponse enhanceResponseWithExternalDittoHeaders(final HttpResponse response,
        final DittoHeaders allDittoHeaders) {

    logger.setCorrelationId(allDittoHeaders);
    final Map<String, String> externalHeaders = getExternalHeaders(allDittoHeaders);

    if (externalHeaders.isEmpty()) {
        logger.debug("No external headers for enhancing the response, returning it as-is.");
        return response;
    }

    logger.debug("Enhancing response with external headers <{}>.", externalHeaders);
    final List<HttpHeader> externalHttpHeaders = new ArrayList<>(externalHeaders.size());
    externalHeaders.forEach((k, v) -> externalHttpHeaders.add(RawHeader.create(k, v)));
    logger.discardCorrelationId();

    return response.withHeaders(externalHttpHeaders);
}
 
Example #9
Source File: StatusRoute.java    From ditto with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Builds the {@code /status} route.
 *
 * @return the {@code /status} route.
 */
public Route buildStatusRoute() {
    return pathPrefix(PATH_STATUS, () -> // /status/*
            get(() -> // GET
                    route(
                            pathEndOrSingleSlash(() -> // /status
                                    complete(
                                            HttpResponse.create().withStatus(StatusCodes.OK)
                                                    .withEntity(ContentTypes.APPLICATION_JSON,
                                                            Status.provideStaticStatus().toString())
                                    )
                            ),
                            path(PATH_HEALTH, healthRouteSupplier), // /status/health
                            path(PATH_CLUSTER, () -> complete( // /status/cluster
                                    HttpResponse.create().withStatus(StatusCodes.OK)
                                            .withEntity(ContentTypes.APPLICATION_JSON,
                                                    clusterStateSupplier.get().toJson().toString()))
                            )
                    )
            ).orElse(complete(StatusCodes.METHOD_NOT_ALLOWED)));
}
 
Example #10
Source File: AbstractHttpRequestActor.java    From ditto with Eclipse Public License 2.0 6 votes vote down vote up
protected AbstractHttpRequestActor(final ActorRef proxyActor,
        final HeaderTranslator headerTranslator,
        final HttpRequest request,
        final CompletableFuture<HttpResponse> httpResponseFuture,
        final HttpConfig httpConfig,
        final CommandConfig commandConfig) {

    this.proxyActor = proxyActor;
    this.headerTranslator = headerTranslator;
    this.httpResponseFuture = httpResponseFuture;
    this.httpRequest = request;
    this.commandConfig = commandConfig;
    responseLocationUri = null;

    getContext().setReceiveTimeout(httpConfig.getRequestTimeout());
}
 
Example #11
Source File: DittoPublicKeyProvider.java    From ditto with Eclipse Public License 2.0 6 votes vote down vote up
private CompletableFuture<PublicKey> loadPublicKey(final PublicKeyIdWithIssuer publicKeyIdWithIssuer,
        final Executor executor) {

    final String issuer = publicKeyIdWithIssuer.getIssuer();
    final String keyId = publicKeyIdWithIssuer.getKeyId();
    LOGGER.debug("Loading public key with id <{}> from issuer <{}>.", keyId, issuer);

    final JwtSubjectIssuerConfig subjectIssuerConfig =
            jwtSubjectIssuersConfig.getConfigItem(issuer)
                    .orElseThrow(() -> GatewayJwtIssuerNotSupportedException.newBuilder(issuer).build());

    final String discoveryEndpoint = getDiscoveryEndpoint(subjectIssuerConfig.getIssuer());
    final CompletableFuture<HttpResponse> responseFuture =
            CompletableFuture.supplyAsync(() -> getPublicKeysFromDiscoveryEndpoint(discoveryEndpoint));
    final CompletableFuture<JsonArray> publicKeysFuture =
            responseFuture.thenCompose(this::mapResponseToJsonArray);
    return publicKeysFuture.thenApply(publicKeysArray -> mapToPublicKey(publicKeysArray, keyId, discoveryEndpoint))
            .toCompletableFuture();
}
 
Example #12
Source File: HttpPushFactoryTest.java    From ditto with Eclipse Public License 2.0 6 votes vote down vote up
private void newBinding() {
    requestQueue = new LinkedBlockingQueue<>();
    responseQueue = new LinkedBlockingQueue<>();

    final Flow<HttpRequest, HttpResponse, NotUsed> handler =
            Flow.fromGraph(KillSwitches.<HttpRequest>single())
                    .mapAsync(1, request -> {
                        requestQueue.offer(request);
                        return responseQueue.take();
                    })
                    .mapMaterializedValue(killSwitch -> {
                        Objects.requireNonNull(killSwitchTrigger.peek())
                                .thenAccept(_void -> killSwitch.shutdown());
                        return NotUsed.getInstance();
                    });
    binding = Http.get(actorSystem).bindAndHandle(handler, ConnectHttp.toHost("127.0.0.1", 0), mat)
            .toCompletableFuture()
            .join();
}
 
Example #13
Source File: CachingHealthRoute.java    From ditto with Eclipse Public License 2.0 6 votes vote down vote up
private CompletionStage<HttpResponse> createOverallHealthResponse() {
    if (cachedHealth == null || isCacheTimedOut()) {
        cachedHealth = statusHealthHelper.retrieveHealth()
                .exceptionally(t -> StatusInfo.fromDetail(StatusDetailMessage.of(StatusDetailMessage.Level.ERROR,
                        "Exception: " + t.getMessage())));
        lastCheckInstant = Instant.now();
    }

    return cachedHealth.thenApply(overallHealth -> {
        final JsonObject statusObject = JsonFactory.newObject()
                .set(StatusInfo.JSON_KEY_STATUS, overallHealth.getStatus().toString());
        if (overallHealth.isHealthy()) {
            return HttpResponse.create()
                    .withStatus(StatusCodes.OK)
                    .withEntity(ContentTypes.APPLICATION_JSON, statusObject.toString());
        } else {
            return HttpResponse.create()
                    .withStatus(StatusCodes.SERVICE_UNAVAILABLE)
                    .withEntity(ContentTypes.APPLICATION_JSON, statusObject.toString());
        }
    });
}
 
Example #14
Source File: DittoPublicKeyProviderTest.java    From ditto with Eclipse Public License 2.0 6 votes vote down vote up
private void mockSuccessfulPublicKeysRequest() {

        final JsonObject jsonWebKey = JsonObject.newBuilder()
                .set(JsonWebKey.JsonFields.KEY_TYPE, "RSA")
                .set(JsonWebKey.JsonFields.KEY_ALGORITHM, "HS256")
                .set(JsonWebKey.JsonFields.KEY_USAGE, "sig")
                .set(JsonWebKey.JsonFields.KEY_ID, KEY_ID)
                .set(JsonWebKey.JsonFields.KEY_MODULUS,
                        "pjdss8ZaDfEH6K6U7GeW2nxDqR4IP049fk1fK0lndimbMMVBdPv_hSpm8T8EtBDxrUdi1OHZfMhUixGaut-3nQ4GG9nM249oxhCtxqqNvEXrmQRGqczyLxuh-fKn9Fg--hS9UpazHpfVAFnB5aCfXoNhPuI8oByyFKMKaOVgHNqP5NBEqabiLftZD3W_lsFCPGuzr4Vp0YS7zS2hDYScC2oOMu4rGU1LcMZf39p3153Cq7bS2Xh6Y-vw5pwzFYZdjQxDn8x8BG3fJ6j8TGLXQsbKH1218_HcUJRvMwdpbUQG5nvA2GXVqLqdwp054Lzk9_B_f1lVrmOKuHjTNHq48w")
                .set(JsonWebKey.JsonFields.KEY_EXPONENT, "AQAB")
                .build();
        final JsonArray keysArray = JsonArray.newBuilder().add(jsonWebKey).build();
        final JsonObject keysJson = JsonObject.newBuilder().set("keys", keysArray).build();
        final HttpResponse publicKeysResponse = HttpResponse.create()
                .withStatus(StatusCodes.OK)
                .withEntity(keysJson.toString());
        when(httpClientMock.createSingleHttpRequest(PUBLIC_KEYS_REQUEST))
                .thenReturn(CompletableFuture.completedFuture(publicKeysResponse));
    }
 
Example #15
Source File: DittoPublicKeyProviderTest.java    From ditto with Eclipse Public License 2.0 6 votes vote down vote up
private void mockSuccessfulPublicKeysRequestWithoutMatchingKeyId() {

        final JsonObject jsonWebKey = JsonObject.newBuilder()
                .set(JsonWebKey.JsonFields.KEY_TYPE, "RSA")
                .set(JsonWebKey.JsonFields.KEY_ALGORITHM, "HS256")
                .set(JsonWebKey.JsonFields.KEY_USAGE, "sig")
                .set(JsonWebKey.JsonFields.KEY_ID, "anotherId")
                .set(JsonWebKey.JsonFields.KEY_MODULUS,
                        "pjdss8ZaDfEH6K6U7GeW2nxDqR4IP049fk1fK0lndimbMMVBdPv_hSpm8T8EtBDxrUdi1OHZfMhUixGaut-3nQ4GG9nM249oxhCtxqqNvEXrmQRGqczyLxuh-fKn9Fg--hS9UpazHpfVAFnB5aCfXoNhPuI8oByyFKMKaOVgHNqP5NBEqabiLftZD3W_lsFCPGuzr4Vp0YS7zS2hDYScC2oOMu4rGU1LcMZf39p3153Cq7bS2Xh6Y-vw5pwzFYZdjQxDn8x8BG3fJ6j8TGLXQsbKH1218_HcUJRvMwdpbUQG5nvA2GXVqLqdwp054Lzk9_B_f1lVrmOKuHjTNHq48w")
                .set(JsonWebKey.JsonFields.KEY_EXPONENT, "AQAB")
                .build();
        final JsonArray keysArray = JsonArray.newBuilder().add(jsonWebKey).build();
        final JsonObject keysJson = JsonObject.newBuilder().set("keys", keysArray).build();
        final HttpResponse publicKeysResponse = HttpResponse.create()
                .withStatus(StatusCodes.OK)
                .withEntity(keysJson.toString());
        when(httpClientMock.createSingleHttpRequest(PUBLIC_KEYS_REQUEST))
                .thenReturn(CompletableFuture.completedFuture(publicKeysResponse));
    }
 
Example #16
Source File: OverallStatusRoute.java    From ditto with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Builds the {@code /status} route.
 *
 * @return the {@code /status} route.
 */
public Route buildOverallStatusRoute() {
    return rawPathPrefix(PathMatchers.slash().concat(PATH_OVERALL), () -> {// /overall/*
        final DevOpsBasicAuthenticationDirective devOpsBasicAuthenticationDirective =
                DevOpsBasicAuthenticationDirective.getInstance(devOpsConfig);
        return devOpsBasicAuthenticationDirective.authenticateDevOpsBasic(REALM_STATUS, get(() -> // GET
                // /overall/status
                // /overall/status/health
                // /overall/status/cluster
                rawPathPrefix(PathMatchers.slash().concat(PATH_STATUS), () -> concat(
                        // /status
                        pathEndOrSingleSlash(() -> completeWithFuture(createOverallStatusResponse())),
                        // /status/health
                        path(PATH_HEALTH, () -> completeWithFuture(createOverallHealthResponse())),
                        // /status/cluster
                        path(PATH_CLUSTER, () -> complete(
                                HttpResponse.create().withStatus(StatusCodes.OK)
                                        .withEntity(ContentTypes.APPLICATION_JSON,
                                                clusterStateSupplier.get().toJson().toString()))
                        )
                ))
        ));
    });
}
 
Example #17
Source File: AbstractHttpRequestActor.java    From ditto with Eclipse Public License 2.0 5 votes vote down vote up
private static HttpResponse addEntityAccordingToContentType(final HttpResponse response, final JsonValue entity,
        final DittoHeaders dittoHeaders) {

    final ContentType contentType = getContentType(dittoHeaders);
    final String entityString = CONTENT_TYPE_TEXT.equals(contentType) ? entity.asString() : entity.toString();
    return response.withEntity(contentType, ByteString.fromString(entityString));
}
 
Example #18
Source File: AbstractHttpRequestActor.java    From ditto with Eclipse Public License 2.0 5 votes vote down vote up
private static UnaryOperator<HttpResponse> createBodyAddingResponseMapper(final DittoHeaders dittoHeaders,
        final WithOptionalEntity withOptionalEntity) {

    return response -> {
        if (StatusCodes.NO_CONTENT.equals(response.status())) {
            return response;
        }
        final JsonSchemaVersion schemaVersion = dittoHeaders.getSchemaVersion()
                .orElse(dittoHeaders.getImplementedSchemaVersion());
        return withOptionalEntity.getEntity(schemaVersion)
                .map(entity -> addEntityAccordingToContentType(response, entity, dittoHeaders))
                .orElse(response);
    };
}
 
Example #19
Source File: AbstractHttpRequestActor.java    From ditto with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Modify an HTTP response according to the HTTP response's status code, add the {@code Location} header
 * when the status code was {@link HttpStatusCode#CREATED}.
 *
 * @param response the candidate HTTP response.
 * @return the modified HTTP response.
 */
protected HttpResponse modifyResponse(final HttpResponse response) {
    if (HttpStatusCode.CREATED.toInt() == response.status().intValue() && null != responseLocationUri) {
        return response.addHeader(Location.create(responseLocationUri));
    } else {
        return response;
    }
}
 
Example #20
Source File: AbstractRoute.java    From ditto with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Create HTTP request actor by the dynamically loaded props factory.
 *
 * @param ctx the request context.
 * @param httpResponseFuture the promise of a response to be fulfilled by the HTTP request actor.
 * @return reference of the created actor.
 */
protected ActorRef createHttpPerRequestActor(final RequestContext ctx,
        final CompletableFuture<HttpResponse> httpResponseFuture) {

    final Props props = httpRequestActorPropsFactory.props(
            proxyActor, headerTranslator, ctx.getRequest(), httpResponseFuture, httpConfig, commandConfig);

    return actorSystem.actorOf(props);
}
 
Example #21
Source File: HttpPublisherActor.java    From ditto with Eclipse Public License 2.0 5 votes vote down vote up
private static CompletionStage<String> getResponseBody(final HttpResponse response,
        final ActorMaterializer materializer) {
    return response.entity()
            .toStrict(READ_BODY_TIMEOUT_MS, materializer)
            .thenApply(HttpEntity.Strict::getData)
            .thenApply(ByteString::utf8String);
}
 
Example #22
Source File: HttpPublisherActorTest.java    From ditto with Eclipse Public License 2.0 5 votes vote down vote up
@Override
protected void setupMocks(final TestProbe probe) {
    httpPushFactory = new DummyHttpPushFactory("8.8.4.4", request -> {
        received.offer(request);
        return HttpResponse.create().withStatus(StatusCodes.OK);
    });
}
 
Example #23
Source File: DefaultHttpPushFactory.java    From ditto with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public <T> Flow<Pair<HttpRequest, T>, Pair<Try<HttpResponse>, T>, ?> createFlow(final ActorSystem system,
        final LoggingAdapter log) {

    final Http http = Http.get(system);
    final ConnectionPoolSettings poolSettings = getConnectionPoolSettings(system);
    final Flow<Pair<HttpRequest, T>, Pair<Try<HttpResponse>, T>, ?> flow;
    if (null != httpsConnectionContext) {
        final ConnectHttp connectHttpsWithCustomSSLContext =
                ConnectHttp.toHostHttps(baseUri).withCustomHttpsContext(httpsConnectionContext);
        // explicitly added <T> as in (some?) IntelliJ idea the line would show an error:
        flow = http.<T>cachedHostConnectionPoolHttps(connectHttpsWithCustomSSLContext, poolSettings, log);
    } else {
        // explicitly added <T> as in (some?) IntelliJ idea the line would show an error:
        // no SSL, hence no need for SSLContextCreator
        flow = http.<T>cachedHostConnectionPool(ConnectHttp.toHost(baseUri), poolSettings, log);
    }
    return flow.buffer(parallelism, OverflowStrategy.backpressure());
}
 
Example #24
Source File: MessagesRoute.java    From ditto with Eclipse Public License 2.0 5 votes vote down vote up
private Route handleMessage(final RequestContext ctx, final Source<ByteString, Object> payloadSource,
        final Function<ByteBuffer, MessageCommand<?, ?>> requestPayloadToCommandFunction) {

    final CompletableFuture<HttpResponse> httpResponseFuture = new CompletableFuture<>();
    payloadSource.fold(ByteString.empty(), ByteString::concat)
            .map(ByteString::toArray)
            .map(ByteBuffer::wrap)
            .map(requestPayloadToCommandFunction)
            .to(Sink.actorRef(createHttpPerRequestActor(ctx, httpResponseFuture),
                    AbstractHttpRequestActor.COMPLETE_MESSAGE))
            .run(materializer);

    return completeWithFuture(preprocessResponse(httpResponseFuture));
}
 
Example #25
Source File: StatsRoute.java    From ditto with Eclipse Public License 2.0 5 votes vote down vote up
private Route handleDevOpsPerRequest(final RequestContext ctx,
        final Source<ByteString, ?> payloadSource,
        final Function<String, DevOpsCommand<?>> requestJsonToCommandFunction) {
    final CompletableFuture<HttpResponse> httpResponseFuture = new CompletableFuture<>();

    payloadSource
            .fold(ByteString.empty(), ByteString::concat)
            .map(ByteString::utf8String)
            .map(requestJsonToCommandFunction)
            .to(Sink.actorRef(createHttpPerRequestActor(ctx, httpResponseFuture),
                    AbstractHttpRequestActor.COMPLETE_MESSAGE))
            .run(materializer);

    return completeWithFuture(httpResponseFuture);
}
 
Example #26
Source File: EventMarshallers.java    From ts-reaktive with MIT License 5 votes vote down vote up
/** 
 * Returns a Marshaller that marshals event envelopes using the given function, writing the resulting protobuf messages as delimited protobuf
 * into a chunked HTTP response with the given content type. 
 */
public static Marshaller<Source<EventEnvelope, ?>, HttpResponse> marshallerWith(Function<EventEnvelope, ? extends MessageLite> f, ContentType contentType) {
    return Marshaller.<Source<EventEnvelope, ?>, HttpResponse>opaque(events -> 
        HttpResponse.create().withEntity(
            HttpEntities.create(
                contentType, events.map(e -> serializeDelimited(f.apply(e)))
            )
        )
    );
}
 
Example #27
Source File: OverallStatusRoute.java    From ditto with Eclipse Public License 2.0 5 votes vote down vote up
private CompletionStage<HttpResponse> createOverallHealthResponse() {
    return statusHealthProvider.retrieveHealth()
            .thenApply(overallHealth -> {
                if (overallHealth.isHealthy()) {
                    return HttpResponse.create()
                            .withStatus(StatusCodes.OK)
                            .withEntity(ContentTypes.APPLICATION_JSON, overallHealth.toJsonString());
                } else {
                    return HttpResponse.create()
                            .withStatus(StatusCodes.SERVICE_UNAVAILABLE)
                            .withEntity(ContentTypes.APPLICATION_JSON, overallHealth.toJsonString());
                }
            });
}
 
Example #28
Source File: AkkaHttpClientService.java    From mutual-tls-ssl with Apache License 2.0 5 votes vote down vote up
private String extractBody(HttpResponse httpResponse) {
    return httpResponse.entity()
            .getDataBytes()
            .fold(ByteString.empty(), ByteString::concat)
            .map(ByteString::utf8String)
            .runWith(Sink.head(), actorSystem)
            .toCompletableFuture()
            .join();
}
 
Example #29
Source File: HttpPushFactoryTest.java    From ditto with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void basicAuth() throws Exception {
    // GIVEN: the connection has plain credentials in the URI
    connection = connection.toBuilder()
            .uri("http://username:[email protected]:" + binding.localAddress().getPort() + "/path/prefix/")
            .build();
    final HttpPushFactory underTest = HttpPushFactory.of(connection, connectionConfig.getHttpPushConfig());
    final Pair<SourceQueueWithComplete<HttpRequest>, SinkQueueWithCancel<Try<HttpResponse>>> pair =
            newSourceSinkQueues(underTest);
    final SourceQueueWithComplete<HttpRequest> sourceQueue = pair.first();
    final SinkQueueWithCancel<Try<HttpResponse>> sinkQueue = pair.second();
    final HttpRequest request = underTest.newRequest(HttpPublishTarget.of("PUT:/path/appendage/"));
    final HttpResponse response = HttpResponse.create().withStatus(StatusCodes.OK);

    // WHEN: request-response cycle is carried out
    responseQueue.offer(CompletableFuture.completedFuture(response));
    sourceQueue.offer(request);
    final HttpRequest actualRequest = requestQueue.take();

    // THEN: actual received request has a basic auth header
    assertThat(actualRequest.getHeader(Authorization.class))
            .contains(Authorization.basic("username", "password"));
}
 
Example #30
Source File: HttpRequestActorTest.java    From ditto with Eclipse Public License 2.0 5 votes vote down vote up
private ActorRef createHttpRequestActor(final HttpRequest request, final CompletableFuture<HttpResponse> response) {
    return system.actorOf(HttpRequestActor.props(
            TestProbe.apply(system).ref(),
            HeaderTranslator.empty(),
            request,
            response,
            gatewayConfig.getHttpConfig(),
            gatewayConfig.getCommandConfig()
    ));
}