Java Code Examples for akka.util.ByteString

The following examples show how to use akka.util.ByteString. These examples are extracted from open source projects. 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 Project: glowroot   Source File: StreamController.java    License: Apache License 2.0 6 votes vote down vote up
public Result stream() {
    Source<ByteString, ?> source = Source.<ByteString>actorRef(256, OverflowStrategy.dropNew())
            .mapMaterializedValue(sourceActor -> {
                sourceActor.tell(ByteString.fromString("kiki"), null);
                try {
                    MILLISECONDS.sleep(100);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
                sourceActor.tell(ByteString.fromString("foo"), null);
                sourceActor.tell(ByteString.fromString("bar"), null);
                sourceActor.tell(new Status.Success(NotUsed.getInstance()), null);
                new CreateTraceEntry().traceEntryMarker();
                return null;
            });
    return ok().chunked(source);
}
 
Example 2
@Test(timeout = SolutionSettingsControllerTest.TIMEOUT)
@Category({UnitTest.class})
public void getLogoShouldReturnExpectedNameAndType() throws BaseException, ExecutionException, InterruptedException {
    // Arrange
    String image = rand.NextString();
    String type = rand.NextString();
    String name = rand.NextString();
    Logo model = new Logo(image, type, name, false);
    getLogoMockSetup(model);
    controller = new SolutionSettingsController(mockStorage, mockActions);
    Http.Response mockResponse = TestUtils.setRequest(SolutionSettingsControllerTest.LOGO_BODY);

    // Act
    Result result = controller.getLogoAsync().toCompletableFuture().get();
    byte[] bytes = TestUtils.getBytes(result);
    byte[] bytesold = Base64.getDecoder().decode(model.getImage().getBytes());

    // Assert
    assertEquals(ByteString.fromArray(bytes), ByteString.fromArray(bytesold));
    Mockito.verify(mockResponse).setHeader(Logo.NAME_HEADER, name);
    Mockito.verify(mockResponse).setHeader(Logo.IS_DEFAULT_HEADER, Boolean.toString(false));
}
 
Example 3
@Test(timeout = SolutionSettingsControllerTest.TIMEOUT)
@Category({UnitTest.class})
public void getLogoShouldReturnDefaultLogo() throws BaseException, ExecutionException, InterruptedException {
    // Arrange
    Logo model = Logo.Default;
    getLogoMockSetup(model);
    controller = new SolutionSettingsController(mockStorage, mockActions);
    Http.Response mockResponse = TestUtils.setRequest(SolutionSettingsControllerTest.LOGO_BODY);

    // Act
    Result result = controller.getLogoAsync().toCompletableFuture().get();
    byte[] bytes = TestUtils.getBytes(result);
    byte[] bytesold = Base64.getDecoder().decode(model.getImage().getBytes());

    // Assert
    assertEquals(ByteString.fromArray(bytes), ByteString.fromArray(bytesold));
    Mockito.verify(mockResponse).setHeader(Logo.NAME_HEADER, Logo.Default.getName());
    Mockito.verify(mockResponse).setHeader(Logo.IS_DEFAULT_HEADER, Boolean.toString(true));
}
 
Example 4
@Test(timeout = SolutionSettingsControllerTest.TIMEOUT)
@Category({UnitTest.class})
public void setLogoShouldReturnGivenLogoAndName() throws BaseException, ExecutionException, InterruptedException, UnsupportedEncodingException, URISyntaxException {
    // Arrange
    String image = rand.NextString();
    String type = rand.NextString();
    String name = rand.NextString();
    Logo model = new Logo(image, type, name, false);
    setLogoMockSetup(model);
    controller = new SolutionSettingsController(mockStorage, mockActions);
    Http.Response mockResponse = TestUtils.setRequest(SolutionSettingsControllerTest.LOGO_BODY);

    // Act
    byte[] bytes = TestUtils.getBytes(controller.setLogoAsync().toCompletableFuture().get());
    byte[] bytesold = Base64.getDecoder().decode(model.getImage().getBytes());

    // Assert
    assertEquals(ByteString.fromArray(bytes), ByteString.fromArray(bytesold));
    Mockito.verify(mockResponse).setHeader(Logo.NAME_HEADER, name);
    Mockito.verify(mockResponse).setHeader(Logo.IS_DEFAULT_HEADER, Boolean.toString(false));
}
 
Example 5
@Test(timeout = SolutionSettingsControllerTest.TIMEOUT)
@Category({UnitTest.class})
public void setLogoShouldReturnGivenLogo() throws BaseException, ExecutionException, InterruptedException, UnsupportedEncodingException, URISyntaxException {
    // Arrange
    String image = rand.NextString();
    String type = rand.NextString();
    Logo model = new Logo(image, type, null, false);
    setLogoMockSetup(model);
    controller = new SolutionSettingsController(mockStorage, mockActions);
    Http.Response mockResponse = TestUtils.setRequest(SolutionSettingsControllerTest.LOGO_BODY);

    // Act
    byte[] bytes = TestUtils.getBytes(controller.setLogoAsync().toCompletableFuture().get());
    byte[] bytesold = Base64.getDecoder().decode(model.getImage().getBytes());

    // Assert
    assertEquals(ByteString.fromArray(bytes), ByteString.fromArray(bytesold));
    Mockito.verify(mockResponse).setHeader(Logo.IS_DEFAULT_HEADER, Boolean.toString(false));
}
 
Example 6
@Test(timeout = SolutionSettingsControllerTest.TIMEOUT)
@Category({UnitTest.class})
public void setLogoShouldReturnGivenName() throws BaseException, ExecutionException, InterruptedException, UnsupportedEncodingException, URISyntaxException {
    // Arrange
    String name = rand.NextString();
    Logo model = new Logo(null, null, name, false);
    setLogoMockSetup(model);
    controller = new SolutionSettingsController(mockStorage, mockActions);
    Http.Response mockResponse = TestUtils.setRequest(SolutionSettingsControllerTest.LOGO_BODY);

    // Act
    byte[] bytes = TestUtils.getBytes(controller.setLogoAsync().toCompletableFuture().get());
    byte[] emptyBytes = new byte[0];

    // Assert
    assertEquals(ByteString.fromArray(bytes), ByteString.fromArray(emptyBytes));
    Mockito.verify(mockResponse).setHeader(Logo.NAME_HEADER, name);
    Mockito.verify(mockResponse).setHeader(Logo.IS_DEFAULT_HEADER, Boolean.toString(false));
}
 
Example 7
Source Project: ditto   Source File: CompressedDDataHandler.java    License: Eclipse Public License 2.0 6 votes vote down vote up
@Override
public CompletionStage<Collection<ActorRef>> getSubscribers(final Collection<ByteString> topic) {

    return get(Replicator.readLocal()).thenApply(optional -> {
        if (optional.isPresent()) {
            final ORMultiMap<ActorRef, ByteString> mmap = optional.get();
            ddataMetrics.set((long) mmap.size());
            return JavaConverters.mapAsJavaMap(mmap.entries())
                    .entrySet()
                    .stream()
                    .filter(entry -> topic.stream().anyMatch(entry.getValue()::contains))
                    .map(Map.Entry::getKey)
                    .collect(Collectors.toList());
        } else {
            ddataMetrics.set(0L);
            return Collections.emptyList();
        }
    });
}
 
Example 8
Source Project: ditto   Source File: StatsRoute.java    License: Eclipse Public License 2.0 6 votes vote down vote up
private Route handleSudoCountThingsPerRequest(final RequestContext ctx, final SudoCountThings command) {
    final CompletableFuture<HttpResponse> httpResponseFuture = new CompletableFuture<>();

    Source.single(command)
            .to(Sink.actorRef(createHttpPerRequestActor(ctx, httpResponseFuture),
                    AbstractHttpRequestActor.COMPLETE_MESSAGE))
            .run(materializer);

    final CompletionStage<HttpResponse> allThingsCountHttpResponse = Source.fromCompletionStage(httpResponseFuture)
            .flatMapConcat(httpResponse -> httpResponse.entity().getDataBytes())
            .fold(ByteString.empty(), ByteString::concat)
            .map(ByteString::utf8String)
            .map(Integer::valueOf)
            .map(count -> JsonObject.newBuilder().set("allThingsCount", count).build())
            .map(jsonObject -> HttpResponse.create()
                    .withEntity(ContentTypes.APPLICATION_JSON, ByteString.fromString(jsonObject.toString()))
                    .withStatus(HttpStatusCode.OK.toInt()))
            .runWith(Sink.head(), materializer);

    return completeWithFuture(allThingsCountHttpResponse);
}
 
Example 9
Source Project: ditto   Source File: AbstractRoute.java    License: Eclipse Public License 2.0 6 votes vote down vote up
protected Route handlePerRequest(final RequestContext ctx,
        final DittoHeaders dittoHeaders,
        final Source<ByteString, ?> payloadSource,
        final Function<String, Command> requestJsonToCommandFunction,
        @Nullable final Function<JsonValue, JsonValue> responseTransformFunction) {

    // check if Akka HTTP timeout was overwritten by our code (e.g. for claim messages)
    final boolean increasedAkkaHttpTimeout = ctx.getRequest().getHeader(TimeoutAccess.class)
            .map(TimeoutAccess::timeoutAccess)
            .map(akka.http.javadsl.TimeoutAccess::getTimeout)
            .map(scalaDuration -> Duration.ofNanos(scalaDuration.toNanos()))
            .filter(akkaHttpTimeout -> akkaHttpTimeout.compareTo(commandConfig.getMaxTimeout()) > 0)
            .isPresent();

    if (increasedAkkaHttpTimeout) {
        return doHandlePerRequest(ctx, dittoHeaders, payloadSource, requestJsonToCommandFunction,
                responseTransformFunction);
    } else {
        return withCustomRequestTimeout(dittoHeaders.getTimeout().orElse(null),
                this::validateCommandTimeout,
                null, // don't set default timeout in order to use the configured akka-http default
                timeout -> doHandlePerRequest(ctx, dittoHeaders.toBuilder().timeout(timeout).build(), payloadSource,
                        requestJsonToCommandFunction, responseTransformFunction));
    }
}
 
Example 10
@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 11
Source Project: ts-reaktive   Source File: WebSocketDataCenterServer.java    License: MIT License 6 votes vote down vote up
private Flow<Message,Message,?> flow(ActorRef shardRegion) {
    return Flow.<Message>create()
        .map(msg -> {
            if (msg.isText()) {
                log.warn("Ignoring unexpected text-kind web socket message {}", msg);
                return Option.<Query.EventEnvelope>none();
            } else {
                return Option.<Query.EventEnvelope>some(Query.EventEnvelope.parseFrom(msg.asBinaryMessage().getStrictData().toArray()));
            }
        })
        .filter(o -> o.isDefined())
        .map(o -> o.get())
        .mapAsync(maxInFlight, e -> ask(shardRegion, e, timeout))
        .map(resp -> (Long) resp)
        .map(l -> BinaryMessage.create(ByteString.fromArray(EventsPersisted.newBuilder().setOffset(l).build().toByteArray())));
}
 
Example 12
Source Project: mutual-tls-ssl   Source File: AkkaHttpClientService.java    License: 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 13
Source Project: ts-reaktive   Source File: S3.java    License: MIT License 5 votes vote down vote up
/**
   * Reads the stream of events written to S3 using {@link #store(String, Seq)} before.
   */
  public Source<com.tradeshift.reaktive.protobuf.Query.EventEnvelope, NotUsed> loadEvents(String key) {
      return download(key)
.recoverWith(new PFBuilder<Throwable, Source<ByteString,NotUsed>>()
	.matchAny(x -> Source.empty()) // not found -> no data
	.build()
)
      .via(DelimitedProtobufFraming.instance)
      .map(bs -> com.tradeshift.reaktive.protobuf.Query.EventEnvelope.parseFrom(bs.iterator().asInputStream()));
  }
 
Example 14
Source Project: sunbird-lms-service   Source File: AccessLogFilter.java    License: MIT License 5 votes vote down vote up
@Override
public EssentialAction apply(EssentialAction next) {
  return EssentialAction.of(
      request -> {
        long startTime = System.currentTimeMillis();
        Accumulator<ByteString, Result> accumulator = next.apply(request);
        return accumulator.map(
            result -> {
              long endTime = System.currentTimeMillis();
              long requestTime = endTime - startTime;
              try {
                org.sunbird.common.request.Request req = new org.sunbird.common.request.Request();
                Map<String, Object> params = new WeakHashMap<>();
                params.put(JsonKey.URL, request.uri());
                params.put(JsonKey.METHOD, request.method());
                params.put(JsonKey.LOG_TYPE, JsonKey.API_ACCESS);
                params.put(JsonKey.MESSAGE, "");
                params.put(JsonKey.METHOD, request.method());
                params.put(JsonKey.DURATION, requestTime);
                params.put(JsonKey.STATUS, result.status());
                params.put(JsonKey.LOG_LEVEL, JsonKey.INFO);
                String contextDetails = request.flash().get(JsonKey.CONTEXT);
                Map<String, Object> context =
                    objectMapper.readValue(
                        contextDetails, new TypeReference<Map<String, Object>>() {});
                req.setRequest(
                    generateTelemetryRequestForController(
                        TelemetryEvents.LOG.getName(),
                        params,
                        (Map<String, Object>) context.get(JsonKey.CONTEXT)));
                TelemetryWriter.write(req);
              } catch (Exception ex) {
                ProjectLogger.log("AccessLogFilter:apply Exception in writing telemetry", ex);
              }
              return result;
            },
            executor);
      });
}
 
Example 15
Source Project: tutorials   Source File: HomeControllerTest.java    License: MIT License 5 votes vote down vote up
@Test
public void givenMultigigabyteResponseConsumeWithStreams() throws Exception {
    CountDownLatch latch = new CountDownLatch(1);
    final ActorSystem system = ActorSystem.create();
    final ActorMaterializer materializer = ActorMaterializer.create(system);
    final Path path = Files.createTempFile("tmp_", ".out");

    WSClient ws = play.test.WSTestClient.newClient(port);
    log.info("Starting test server on url: " + url);
    ws.url(url)
      .stream()
      .thenAccept(
        response -> {
            try {
                OutputStream outputStream = java.nio.file.Files.newOutputStream(path);
                Sink<ByteString, CompletionStage<Done>> outputWriter =
                  Sink.foreach(bytes -> {
                      log.info("Reponse: " + bytes.utf8String());
                      outputStream.write(bytes.toArray());
                  });

                response.getBodyAsSource()
                        .runWith(outputWriter, materializer);

            } catch (IOException e) {
                log.error("An error happened while opening the output stream", e);
            }
        })
      .whenComplete((value, error) -> latch.countDown());

    log.debug(
      "Waiting for requests to be completed. Current Time: " + System.currentTimeMillis());
    latch.await(5, TimeUnit.SECONDS );
    assertEquals(0, latch.getCount());
    log.debug("All requests have been completed. Exiting test.");
}
 
Example 16
Source Project: ditto   Source File: CompressedDDataHandler.java    License: Eclipse Public License 2.0 5 votes vote down vote up
@Override
public CompletionStage<Void> removeAddress(final Address address,
        final Replicator.WriteConsistency writeConsistency) {
    return update(writeConsistency, mmap -> {
        ORMultiMap<ActorRef, ByteString> result = mmap;
        for (final ActorRef subscriber : mmap.getEntries().keySet()) {
            if (subscriber.path().address().equals(address)) {
                result = result.remove(selfUniqueAddress, subscriber);
            }
        }
        return result;
    });
}
 
Example 17
Source Project: ts-reaktive   Source File: StaxWriter.java    License: MIT License 5 votes vote down vote up
/**
 * Returns a flow that buffers up to [maximumBatchSize] XML events and writing them together.
 * 
 * Buffering is only done if upstream is faster than downstream. If there is demand from downstream,
 * also slower batches will be written.
 */
public static Flow<XMLEvent,ByteString,NotUsed> flow(int maximumBatchSize) {
    return Flow.of(XMLEvent.class)
        .batch(maximumBatchSize, event -> {
            List<XMLEvent> l = new ArrayList<>();
            l.add(event);
            return l;
        }, (list, event) -> {
            list.add(event);
            return list;
        }).via(new StaxWriter());
}
 
Example 18
Source Project: ditto   Source File: CompressedSubscriptions.java    License: Eclipse Public License 2.0 5 votes vote down vote up
private CompressedSubscriptions(
        final Collection<Integer> seeds,
        final Map<ActorRef, Set<String>> subscriberToTopic,
        final Map<ActorRef, Predicate<Collection<String>>> subscriberToFilter,
        final Map<String, TopicData<ByteString>> topicToData,
        final Map<ByteString, Integer> hashCodeToTopicCount,
        final CompressedUpdate updates) {
    super(subscriberToTopic, subscriberToFilter, topicToData);
    this.seeds = seeds;
    this.hashCodeToTopicCount = hashCodeToTopicCount;
    this.updates = updates;
}
 
Example 19
Source Project: ts-reaktive   Source File: Base64Flows.java    License: MIT License 5 votes vote down vote up
/**
 * Removes whitespace (or any other ignored characters) from an incoming ByteString buffer
 * and returns the result.
 */
private static ByteString removeWhitespace(ByteString in) {
    ByteStringBuilder b = new ByteStringBuilder();
    b.sizeHint(in.size());
    for (int i = 0; i < in.size(); i++) {
        byte ch = in.apply(i);
        if (NOT_WHITESPACE[ch]) {
            b.putByte(ch);
        }
    }
    return b.result();
}
 
Example 20
Source Project: ditto   Source File: CompressedSubscriptions.java    License: Eclipse Public License 2.0 5 votes vote down vote up
@Override
protected void onRemovedTopic(final TopicData<ByteString> removedTopic) {
    hashCodeToTopicCount.computeIfPresent(removedTopic.getHashes(), (hashes, count) -> {
        if (count > 1) {
            return count - 1;
        } else {
            updates.delete(hashes);
            return null;
        }
    });
}
 
Example 21
Source Project: ditto   Source File: CompressedSubscriptionsTest.java    License: Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void exportAllSubscriptions() {
    final CompressedSubscriptions underTest = getVennDiagram();
    final CompressedUpdate update = underTest.export(true);
    assertThat(update.shouldReplaceAll()).isTrue();
    assertThat(update.getDeletes()).isEmpty();
    assertThat(update.getInserts()).containsExactlyInAnyOrder(
            IntStream.rangeClosed(1, 7)
                    .mapToObj(i -> underTest.hashTopic(String.valueOf(i)))
                    .toArray(ByteString[]::new)
    );
}
 
Example 22
Source Project: ditto   Source File: PrometheusReporterRoute.java    License: Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Builds a Route for a HTTP Prometheus endpoint where Prometheus can scrape metrics from.
 *
 * @param prometheusReporter the PrometheusReporter to retrieve the {@code scrapeData} from
 * @return the Prometheus Route
 */
public static Route buildPrometheusReporterRoute(final PrometheusReporter prometheusReporter) {
    return get(() ->
            complete(HttpResponse.create()
                    .withStatus(StatusCodes.OK)
                    .withEntity(CONTENT_TYPE, ByteString.fromString(prometheusReporter.scrapeData()))
            )
    );
}
 
Example 23
@Override
public HttpResponse apply(final DittoRuntimeException exception) {
    checkNotNull(exception, "exception");
    return HttpResponse.create()
            .withStatus(exception.getStatusCode().toInt())
            .withHeaders(getExternalHeadersFor(exception.getDittoHeaders()))
            .withEntity(ContentTypes.APPLICATION_JSON, ByteString.fromString(exception.toJsonString()));
}
 
Example 24
Source Project: ditto   Source File: StatsRoute.java    License: 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 25
Source Project: ditto   Source File: MessagesRoute.java    License: 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 26
Source Project: ditto   Source File: AbstractRoute.java    License: Eclipse Public License 2.0 5 votes vote down vote up
protected Route handlePerRequest(final RequestContext ctx,
        final DittoHeaders dittoHeaders,
        final Source<ByteString, ?> payloadSource,
        final Function<String, Command> requestJsonToCommandFunction) {

    return handlePerRequest(ctx, dittoHeaders, payloadSource, requestJsonToCommandFunction, null);
}
 
Example 27
Source Project: ditto   Source File: AbstractHttpRequestActor.java    License: Eclipse Public License 2.0 5 votes vote down vote up
private static HttpResponse buildResponseWithoutHeadersFromDittoRuntimeException(
        final DittoRuntimeException exception) {

    final HttpResponse responseWithoutHeaders = HttpResponse.create().withStatus(exception.getStatusCode().toInt());
    if (HttpStatusCode.NOT_MODIFIED.equals(exception.getStatusCode())) {
        return responseWithoutHeaders;
    }
    return responseWithoutHeaders.withEntity(CONTENT_TYPE_JSON, ByteString.fromString(exception.toJsonString()));
}
 
Example 28
Source Project: ditto   Source File: AbstractHttpRequestActor.java    License: 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 29
Source Project: ditto   Source File: HttpRequestActorTest.java    License: Eclipse Public License 2.0 5 votes vote down vote up
private HttpResponse createExpectedWhoamiResponse(final Whoami whoami) {
    final UserInformation userInformation = DefaultUserInformation.fromAuthorizationContext(
            whoami.getDittoHeaders().getAuthorizationContext());
    final List<HttpHeader> expectedHeaders = whoami.getDittoHeaders().entrySet()
            .stream()
            .map(e -> RawHeader.create(e.getKey(), e.getValue()))
            .collect(Collectors.toList());
    return HttpResponse.create().withStatus(StatusCodes.OK)
            .withEntity(ContentTypes.APPLICATION_JSON, ByteString.fromString(userInformation.toJsonString()))
            .withHeaders(expectedHeaders);
}
 
Example 30
Source Project: ditto   Source File: HttpPublisherActor.java    License: 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);
}