akka.http.javadsl.model.HttpRequest Java Examples

The following examples show how to use akka.http.javadsl.model.HttpRequest. 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: 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 #2
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 #3
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 #4
Source File: MessagesRoute.java    From ditto with Eclipse Public License 2.0 6 votes vote down vote up
private static Function<ByteBuffer, MessageCommand<?, ?>> buildSendThingMessage(final MessageDirection direction,
        final RequestContext ctx,
        final DittoHeaders dittoHeaders,
        final ThingId thingId,
        final String msgSubject,
        final Duration timeout) {

    return payload -> {
        final HttpRequest httpRequest = ctx.getRequest();
        final ContentType contentType = httpRequest.entity().getContentType();

        final MessageHeaders headers = MessageHeaders.newBuilder(direction, thingId, normalizeSubject(msgSubject))
                .correlationId(dittoHeaders.getCorrelationId().orElse(null))
                .contentType(contentType.toString())
                .timestamp(OffsetDateTime.now())
                .putHeaders(dittoHeaders)
                .build();

        final MessageBuilder<Object> messageBuilder = initMessageBuilder(payload, contentType, headers);
        return SendThingMessage.of(thingId, messageBuilder.build(), enhanceHeaders(dittoHeaders, timeout));
    };
}
 
Example #5
Source File: ContentTypeValidationDirectiveTest.java    From ditto with Eclipse Public License 2.0 6 votes vote down vote up
@Test
public void testNonValidContentType() {
    // Arrange
    final DittoHeaders dittoHeaders = DittoHeaders.empty();
    final String type = MediaTypes.APPLICATION_JSON.toString();
    final ContentType differentType = ContentTypes.APPLICATION_X_WWW_FORM_URLENCODED;

    final RequestContext mockedCtx = mock(RequestContext.class);
    when(mockedCtx.getRequest())
            .thenReturn(HttpRequest.PUT("someUrl").withEntity(differentType,"something".getBytes()));
    // Act
    final UnsupportedMediaTypeException result =
            catchThrowableOfType(() -> ensureValidContentType(Set.of(type), mockedCtx, dittoHeaders, COMPLETE_OK),
                    UnsupportedMediaTypeException.class);

    // Assert
    assertThat(result).hasMessageContaining(differentType.toString());
    assertThat(result.getStatusCode()).isEqualTo(HttpStatusCode.UNSUPPORTED_MEDIA_TYPE);
}
 
Example #6
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 #7
Source File: UriForLocationHeaderSupplierTest.java    From ditto with Eclipse Public License 2.0 6 votes vote down vote up
@Test
public void getUriForNonIdempotentRequestWithEntityIdInUri() {
    final String host = "https://example.com/things/";
    final Uri uri = Uri.create(host + KNOWN_ENTITY_ID + "will-be-discarded/");
    final HttpRequest httpRequest = HttpRequest.create()
            .withUri(uri)
            .withMethod(HttpMethods.POST);
    final CommandResponse<?> commandResponse = mock(CommandResponse.class);
    when(commandResponse.getEntityId()).thenReturn(KNOWN_ENTITY_ID);
    when(commandResponse.getResourcePath()).thenReturn(JsonPointer.of(KNOWN_RESOURCE_PATH));
    final Uri expectedUri = Uri.create(host + commandResponse.getEntityId() + commandResponse.getResourcePath());

    final UriForLocationHeaderSupplier underTest = new UriForLocationHeaderSupplier(httpRequest, commandResponse);

    assertThat(underTest.get()).isEqualTo(expectedUri);
}
 
Example #8
Source File: RootRouteTest.java    From ditto with Eclipse Public License 2.0 6 votes vote down vote up
@Test
public void getThingWithVeryLongId() {
    final int numberOfUUIDs = 100;
    final StringBuilder pathBuilder = new StringBuilder(THINGS_2_PATH).append("/");
    final StringBuilder idBuilder = new StringBuilder("namespace");
    for (int i = 0; i < numberOfUUIDs; ++i) {
        idBuilder.append(':').append(UUID.randomUUID());
    }
    pathBuilder.append(idBuilder);
    final ThingIdInvalidException expectedEx = ThingIdInvalidException.newBuilder(idBuilder.toString())
            .dittoHeaders(DittoHeaders.empty())
            .build();

    final TestRouteResult result =
            rootTestRoute.run(
                    withHttps(withPreAuthenticatedAuthentication(HttpRequest.GET(pathBuilder.toString()))));

    result.assertEntity(expectedEx.toJsonString());
    result.assertStatusCode(StatusCodes.BAD_REQUEST);
}
 
Example #9
Source File: ContentTypeValidationDirectiveTest.java    From ditto with Eclipse Public License 2.0 6 votes vote down vote up
@Test
public void testExceptionContainsDittoHeaders() {
    // Arrange
    final DittoHeaders dittoHeaders = DittoHeaders.of(Map.of("someHeaderKey", "someHeaderVal"));
    final String type = ContentTypes.APPLICATION_JSON.mediaType().toString();

    final RequestContext mockedCtx = mock(RequestContext.class);
    when(mockedCtx.getRequest()).thenReturn(HttpRequest.PUT("someUrl"));

    // Act
    final UnsupportedMediaTypeException result =
            catchThrowableOfType(() -> ensureValidContentType(Set.of(type), mockedCtx, dittoHeaders, COMPLETE_OK),
                    UnsupportedMediaTypeException.class);

    // Assert
    assertThat(result.getDittoHeaders()).isEqualTo(dittoHeaders);
}
 
Example #10
Source File: ContentTypeValidationDirectiveTest.java    From ditto with Eclipse Public License 2.0 6 votes vote down vote up
@Test
public void testWithUpperCaseContentTypeHeaderName() {
    // Arrange
    final DittoHeaders dittoHeaders = DittoHeaders.empty();
    final String type = MediaTypes.APPLICATION_JSON.toString();

    // Act
    final TestRouteResult result =
            testRoute(extractRequestContext(
                    ctx -> ensureValidContentType(Set.of(type), ctx, dittoHeaders, COMPLETE_OK)))
                    .run(HttpRequest.PUT("someUrl")
                            .addHeader(HttpHeader.parse("CONTENT-TYPE", type))
                            .withEntity(ContentTypes.APPLICATION_OCTET_STREAM, "something".getBytes()));

    // Assert
    result.assertStatusCode(StatusCodes.OK);
}
 
Example #11
Source File: ContentTypeValidationDirectiveTest.java    From ditto with Eclipse Public License 2.0 6 votes vote down vote up
@Test
public void testWithoutEntityNoNPEExpected() {
    // Arrange
    final DittoHeaders dittoHeaders = DittoHeaders.empty();
    final String type = ContentTypes.APPLICATION_JSON.mediaType().toString();

    final RequestContext mockedCtx = mock(RequestContext.class);
    when(mockedCtx.getRequest()).thenReturn(HttpRequest.PUT("someUrl"));

    // Act
    final UnsupportedMediaTypeException result =
            catchThrowableOfType(() -> ensureValidContentType(Set.of(type), mockedCtx, dittoHeaders, COMPLETE_OK),
                    UnsupportedMediaTypeException.class);

    // Assert
    assertThat(result.getStatusCode()).isEqualTo(HttpStatusCode.UNSUPPORTED_MEDIA_TYPE);
}
 
Example #12
Source File: ThingsRouteTest.java    From ditto with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void putAttributeWithEmptyPointer() {
    final String body = "\"bumlux\"";
    final HttpRequest request = HttpRequest.PUT("/things/org.eclipse.ditto%3Adummy/attributes//bar")
            .withEntity(HttpEntities.create(ContentTypes.APPLICATION_JSON, body));
    final TestRouteResult result = underTest.run(request);
    result.assertStatusCode(StatusCodes.BAD_REQUEST);
}
 
Example #13
Source File: RootRouteTest.java    From ditto with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void getExceptionForDuplicateHeaderFields() {
    final HttpRequest httpRequest = HttpRequest.GET(THINGS_1_PATH_WITH_IDS)
            .addHeader(RawHeader.create("x-correlation-id", UUID.randomUUID().toString()))
            .addHeader(RawHeader.create("x-correlation-id", UUID.randomUUID().toString()));

    final TestRouteResult result = rootTestRoute.run(withHttps(withPreAuthenticatedAuthentication(httpRequest)));

    result.assertStatusCode(StatusCodes.BAD_REQUEST);
}
 
Example #14
Source File: DirectivesInterceptor.java    From pinpoint with Apache License 2.0 5 votes vote down vote up
private boolean samplingEnable(HttpRequest request) {
    // optional value
    final String samplingFlag = requestAdaptor.getHeader(request, Header.HTTP_SAMPLED.toString());
    if (isDebug) {
        logger.debug("SamplingFlag={}", samplingFlag);
    }
    return SamplingFlagUtils.isSamplingFlag(samplingFlag);
}
 
Example #15
Source File: MessagesRoute.java    From ditto with Eclipse Public License 2.0 5 votes vote down vote up
private static Function<ByteBuffer, MessageCommand<?, ?>> buildSendFeatureMessage(final MessageDirection direction,
        final RequestContext ctx,
        final DittoHeaders dittoHeaders,
        final ThingId thingId,
        final String featureId,
        final String msgSubject,
        final Duration timeout) {

    final HttpRequest httpRequest = ctx.getRequest();

    return payload -> {
        final ContentType contentType = httpRequest.entity()
                .getContentType();

        final MessageHeaders headers = MessageHeaders.newBuilder(direction, thingId, normalizeSubject(msgSubject))
                .featureId(featureId)
                .correlationId(dittoHeaders.getCorrelationId().orElse(null))
                .contentType(contentType.toString())
                .timestamp(OffsetDateTime.now())
                .putHeaders(dittoHeaders)
                .build();

        final MessageBuilder<Object> messageBuilder = initMessageBuilder(payload, contentType, headers);
        return SendFeatureMessage.of(thingId, featureId, messageBuilder.build(),
                enhanceHeaders(dittoHeaders, timeout));
    };
}
 
Example #16
Source File: RootRouteTest.java    From ditto with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void getNonExistingSearchUrl() {
    final HttpRequest request = withHttps(withPreAuthenticatedAuthentication(HttpRequest.GET(UNKNOWN_SEARCH_PATH)));

    final TestRouteResult result = rootTestRoute.run(request);

    result.assertStatusCode(StatusCodes.NOT_FOUND);
}
 
Example #17
Source File: RootRouteTest.java    From ditto with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void getThingsUrlWithIds() {
    final TestRouteResult result =
            rootTestRoute.run(
                    withHttps(withPreAuthenticatedAuthentication(HttpRequest.GET(THINGS_1_PATH_WITH_IDS))));

    result.assertStatusCode(EndpointTestConstants.DUMMY_COMMAND_SUCCESS);
}
 
Example #18
Source File: WebSocketRoute.java    From ditto with Eclipse Public License 2.0 5 votes vote down vote up
private CompletionStage<HttpResponse> createWebSocket(final UpgradeToWebSocket upgradeToWebSocket,
        final JsonSchemaVersion version,
        final String requestCorrelationId,
        final DittoHeaders dittoHeaders,
        final ProtocolAdapter adapter,
        final HttpRequest request) {

    @Nullable final SignalEnrichmentFacade signalEnrichmentFacade =
            signalEnrichmentProvider == null ? null : signalEnrichmentProvider.getFacade(request);

    final StreamingSessionIdentifier connectionCorrelationId =
            StreamingSessionIdentifier.of(requestCorrelationId, UUID.randomUUID().toString());

    final AuthorizationContext authContext = dittoHeaders.getAuthorizationContext();
    LOGGER.withCorrelationId(connectionCorrelationId)
            .info("Creating WebSocket for connection authContext: <{}>", authContext);

    return retrieveWebsocketConfig().thenApply(websocketConfig -> {
        final Flow<Message, DittoRuntimeException, NotUsed> incoming =
                createIncoming(version, connectionCorrelationId, authContext, dittoHeaders, adapter, request,
                        websocketConfig);
        final Flow<DittoRuntimeException, Message, NotUsed> outgoing =
                createOutgoing(version, connectionCorrelationId, dittoHeaders, adapter, request,
                        websocketConfig, signalEnrichmentFacade);

        return upgradeToWebSocket.handleMessagesWith(incoming.via(outgoing));
    });
}
 
Example #19
Source File: RootRouteTest.java    From ditto with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void getExceptionForDuplicationHeaderAndQueryParameter() {
    final String headerKey = DittoHeaderDefinition.TIMEOUT.getKey();
    HttpRequest httpRequest = HttpRequest.GET(THINGS_1_PATH_WITH_IDS + "&" + headerKey + "=32s");
    httpRequest = httpRequest.addHeader(akka.http.javadsl.model.HttpHeader.parse(headerKey, "23s"));
    final GatewayDuplicateHeaderException expectedException = GatewayDuplicateHeaderException.newBuilder()
            .message(() -> MessageFormat.format(
                    "<{0}> was provided as header as well as query parameter with divergent values!", headerKey))
            .build();

    final TestRouteResult result = rootTestRoute.run(withHttps(withPreAuthenticatedAuthentication(httpRequest)));

    result.assertStatusCode(StatusCodes.BAD_REQUEST);
    result.assertEntity(expectedException.toJsonString());
}
 
Example #20
Source File: DirectivesInterceptor.java    From pinpoint with Apache License 2.0 5 votes vote down vote up
private TraceId populateTraceIdFromRequest(final HttpRequest request) {
    final String transactionId = requestAdaptor.getHeader(request, Header.HTTP_TRACE_ID.toString());
    if (transactionId != null) {
        final long parentSpanID = NumberUtils.parseLong(requestAdaptor.getHeader(request, Header.HTTP_PARENT_SPAN_ID.toString()), SpanId.NULL);
        final long spanID = NumberUtils.parseLong(requestAdaptor.getHeader(request, Header.HTTP_SPAN_ID.toString()), SpanId.NULL);
        final short flags = NumberUtils.parseShort(requestAdaptor.getHeader(request, Header.HTTP_FLAGS.toString()), (short) 0);
        final TraceId id = traceContext.createTraceId(transactionId, parentSpanID, spanID, flags);
        if (isDebug) {
            logger.debug("TraceID exist. continue trace. {}", id);
        }
        return id;
    } else {
        return null;
    }
}
 
Example #21
Source File: RootRoute.java    From ditto with Eclipse Public License 2.0 5 votes vote down vote up
@Nullable
private static String getUserAgentOrNull(final RequestContext requestContext) {
    final HttpRequest request = requestContext.getRequest();
    for (final HttpHeader header : request.getHeaders()) {

        // find user-agent: HTTP header names are case-insensitive
        if ("user-agent".equalsIgnoreCase(header.name())) {
            return header.value();
        }
    }
    return null;
}
 
Example #22
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()
    ));
}
 
Example #23
Source File: FeaturesRouteTest.java    From ditto with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void getFeaturesWithFieldSelector() {
    final String someField = "featureId";
    final TestRouteResult result = underTest.run(HttpRequest.GET(FEATURES_PATH + "?" + ThingsParameter.FIELDS
            .toString() + "=" + someField));
    result.assertStatusCode(EndpointTestConstants.DUMMY_COMMAND_SUCCESS);
}
 
Example #24
Source File: ContentTypeValidationDirective.java    From ditto with Eclipse Public License 2.0 5 votes vote down vote up
private static String requestToLogString(final HttpRequest request) {
    final String msgPatten = "{0} {1} {2}";
    return MessageFormat.format(msgPatten,
            request.getUri().getHost().address(),
            request.method().value(),
            request.getUri().getPathString());
}
 
Example #25
Source File: ThingsSseRouteBuilderTest.java    From ditto with Eclipse Public License 2.0 5 votes vote down vote up
private void executeThingsRouteTest(final HttpRequest httpRequest, final StartStreaming expectedStartStreaming) {
    new TestKit(actorSystem) {{
        final TestRouteResult routeResult = underTest.run(httpRequest);

        final CompletableFuture<Void> routeTestAssertions = CompletableFuture.runAsync(() -> {
            routeResult.assertMediaType(MediaTypes.TEXT_EVENT_STREAM);
            routeResult.assertStatusCode(StatusCodes.OK);
        });

        final Connect receivedConnect = streamingActor.expectMsgClass(Connect.class);

        final ActorRef publisherActor = publisherActorReference.get();
        publisherActor.tell(receivedConnect, ActorRef.noSender());

        final StartStreaming receivedStartStreaming = streamingActor.expectMsgClass(StartStreaming.class);

        // exclude connectionCorrelationId from being equal as the backend adds a random UUID to it:
        assertThat(receivedStartStreaming.getAuthorizationContext())
                .isEqualTo(expectedStartStreaming.getAuthorizationContext());
        assertThat(receivedStartStreaming.getExtraFields())
                .isEqualTo(expectedStartStreaming.getExtraFields());
        assertThat(receivedStartStreaming.getFilter())
                .isEqualTo(expectedStartStreaming.getFilter());
        assertThat(receivedStartStreaming.getNamespaces())
                .isEqualTo(expectedStartStreaming.getNamespaces());
        assertThat(receivedStartStreaming.getStreamingType())
                .isEqualTo(expectedStartStreaming.getStreamingType());

        publisherActor.tell(
                CloseStreamExceptionally.getInstance(GatewayServiceUnavailableException.newBuilder().build(),
                        connectionCorrelationId), ActorRef.noSender());

        try {
            routeTestAssertions.join();
        } catch (final CompletionException e) {
            // Ignore as the Future is expected to fail because of exceptionally closing the SSE stream.
        }
    }};
}
 
Example #26
Source File: HttpRequestActorTest.java    From ditto with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void handlesWhoamiCommand() throws ExecutionException, InterruptedException {
    final DittoHeaders dittoHeaders = createAuthorizedHeaders();
    final Whoami whoami = Whoami.of(dittoHeaders);
    final HttpResponse expectedResponse = createExpectedWhoamiResponse(whoami);
    final HttpRequest request = HttpRequest.GET("/whoami");
    final CompletableFuture<HttpResponse> responseFuture = new CompletableFuture<>();

    final ActorRef underTest = createHttpRequestActor(request, responseFuture);
    underTest.tell(Whoami.of(dittoHeaders), ActorRef.noSender());

    assertThat(responseFuture.get()).isEqualTo(expectedResponse);
}
 
Example #27
Source File: ThingsRouteTest.java    From ditto with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void getAttributesWithTrailingSlash() {
    final HttpRequest request = HttpRequest.GET("/things/org.eclipse.ditto%3Adummy/attributes/");
    final TestRouteResult result = underTest.run(request);
    result.assertStatusCode(StatusCodes.OK);
    final String entityString = result.entityString();
    assertThat(entityString).contains(RetrieveAttributes.TYPE);
}
 
Example #28
Source File: FeaturesRouteTest.java    From ditto with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void putFeatureEntryPropertiesEntryWithJsonException() {
    final String tooLongNumber = "89314404000484999942";
    final TestRouteResult result = underTest.run(HttpRequest.PUT(FEATURE_ENTRY_PROPERTIES_ENTRY_PATH).withEntity
            (ContentTypes.APPLICATION_JSON ,tooLongNumber));
    result.assertStatusCode(StatusCodes.BAD_REQUEST);
}
 
Example #29
Source File: HttpFlow.java    From ts-reaktive with MIT License 5 votes vote down vote up
private Flow<ByteString, ByteString, CompletionStage<HttpResponse>> createFlow(HttpMethod method, Uri uri, Option<ContentType> contentType, Predicate<HttpResponse> isSuccess, HttpHeader... headers) {
    Sink<ByteString, Publisher<ByteString>> in = Sink.asPublisher(AsPublisher.WITH_FANOUT); // akka internally recreates this twice, on some errors...
    Source<ByteString, Subscriber<ByteString>> out = Source.asSubscriber();
    
    return Flow.fromSinkAndSourceMat(in, out, Keep.both()).mapMaterializedValue(pair -> {
        RequestEntity entity;
        if (contentType.isDefined()) {
            Source<ByteString, NotUsed> inReader = Source.fromPublisher(pair.first());
            entity = HttpEntities.createChunked(contentType.get(), inReader);
        } else {
            entity = HttpEntities.EMPTY;
        }
        HttpRequest rq = HttpRequest.create().withMethod(method).withUri(uri).addHeaders(Arrays.asList(headers)).withEntity(entity);
        
        return http.singleRequest(rq).thenApply(resp -> {
            if (isSuccess.test(resp)) {
                resp.entity().getDataBytes()
                    .runWith(Sink.fromSubscriber(pair.second()), materializer);
            } else {
                log.info("Http responded error: {} for request {}", resp, rq);
                resp.discardEntityBytes(materializer);
                pair.second().onError(new IllegalStateException("Unsuccessful HTTP response: " + resp + " for " + rq));
            }
            return resp;
        }).exceptionally(x -> {
            Throwable cause = (x instanceof CompletionException) ? x.getCause() : x;
            if (!(cause instanceof IllegalStateException)) {
                log.info("Could not make http request " + rq, cause);
            }
            pair.second().onError(cause);
            throw (cause instanceof RuntimeException) ? (RuntimeException) x : new RuntimeException(cause);
        });
    });
}
 
Example #30
Source File: DevOpsRouteTest.java    From ditto with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void testPiggyback() {
    final RetrieveThing retrieveThing = RetrieveThing.of("thing:id", DittoHeaders.empty());
    final ExecutePiggybackCommand body =
            ExecutePiggybackCommand.of("things", "1", retrieveThing.toJson(), DittoHeaders.empty());
    final RequestEntity requestEntity = HttpEntities.create(ContentTypes.APPLICATION_JSON, body.toJsonString());
    final TestRouteResult result = underTest.run(HttpRequest.POST("/devops/piggyback")
            .withEntity(requestEntity));
    result.assertStatusCode(StatusCodes.OK);
}