com.linecorp.armeria.common.AggregatedHttpRequest Java Examples

The following examples show how to use com.linecorp.armeria.common.AggregatedHttpRequest. 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: WatchRequestConverter.java    From centraldogma with Apache License 2.0 6 votes vote down vote up
/**
 * Converts the specified {@code request} to a {@link WatchRequest} when the request has
 * {@link HttpHeaderNames#IF_NONE_MATCH}. {@code null} otherwise.
 */
@Override
@Nullable
public WatchRequest convertRequest(
        ServiceRequestContext ctx, AggregatedHttpRequest request, Class<?> expectedResultType,
        @Nullable ParameterizedType expectedParameterizedResultType) throws Exception {

    final String ifNoneMatch = request.headers().get(HttpHeaderNames.IF_NONE_MATCH);
    if (isNullOrEmpty(ifNoneMatch)) {
        return null;
    }

    final Revision lastKnownRevision = new Revision(ifNoneMatch);
    final String prefer = request.headers().get(HttpHeaderNames.PREFER);
    final long timeoutMillis;
    if (!isNullOrEmpty(prefer)) {
        timeoutMillis = getTimeoutMillis(prefer);
    } else {
        timeoutMillis = DEFAULT_TIMEOUT_MILLIS;
    }

    return new WatchRequest(lastKnownRevision, timeoutMillis);
}
 
Example #2
Source File: JettyService.java    From armeria with Apache License 2.0 6 votes vote down vote up
private static MetaData.Request toRequestMetadata(ServiceRequestContext ctx, AggregatedHttpRequest aReq) {
    // Construct the HttpURI
    final StringBuilder uriBuf = new StringBuilder();
    final RequestHeaders aHeaders = aReq.headers();

    uriBuf.append(ctx.sessionProtocol().isTls() ? "https" : "http");
    uriBuf.append("://");
    uriBuf.append(aHeaders.authority());
    uriBuf.append(aHeaders.path());

    final HttpURI uri = new HttpURI(uriBuf.toString());
    uri.setPath(ctx.mappedPath());

    // Convert HttpHeaders to HttpFields
    final HttpFields jHeaders = new HttpFields(aHeaders.size());
    aHeaders.forEach(e -> {
        final AsciiString key = e.getKey();
        if (!key.isEmpty() && key.byteAt(0) != ':') {
            jHeaders.add(key.toString(), e.getValue());
        }
    });

    return new MetaData.Request(aHeaders.get(HttpHeaderNames.METHOD), uri,
                                HttpVersion.HTTP_1_1, jHeaders, aReq.content().length());
}
 
Example #3
Source File: StringRequestConverterFunction.java    From armeria with Apache License 2.0 6 votes vote down vote up
/**
 * Converts the specified {@link AggregatedHttpRequest} to a {@link String}.
 */
@Override
public Object convertRequest(
        ServiceRequestContext ctx, AggregatedHttpRequest request, Class<?> expectedResultType,
        @Nullable ParameterizedType expectedParameterizedResultType) throws Exception {

    if (expectedResultType == String.class ||
        expectedResultType == CharSequence.class) {
        final Charset charset;
        final MediaType contentType = request.contentType();
        if (contentType != null) {
            charset = contentType.charset(ArmeriaHttpUtil.HTTP_DEFAULT_CONTENT_CHARSET);
        } else {
            charset = ArmeriaHttpUtil.HTTP_DEFAULT_CONTENT_CHARSET;
        }
        return request.content(charset);
    }
    return RequestConverterFunction.fallthrough();
}
 
Example #4
Source File: DefaultHealthCheckUpdateHandler.java    From armeria with Apache License 2.0 6 votes vote down vote up
private static HealthCheckUpdateResult handlePatch(AggregatedHttpRequest req) {
    final JsonNode json = toJsonNode(req);
    if (json.getNodeType() != JsonNodeType.ARRAY ||
        json.size() != 1) {
        throw HttpStatusException.of(HttpStatus.BAD_REQUEST);
    }

    final JsonNode patchCommand = json.get(0);
    final JsonNode op = patchCommand.get("op");
    final JsonNode path = patchCommand.get("path");
    final JsonNode value = patchCommand.get("value");
    if (op == null || path == null || value == null ||
        !"replace".equals(op.textValue()) ||
        !"/healthy".equals(path.textValue()) ||
        !value.isBoolean()) {
        throw HttpStatusException.of(HttpStatus.BAD_REQUEST);
    }

    return value.booleanValue() ? HealthCheckUpdateResult.HEALTHY
                                : HealthCheckUpdateResult.UNHEALTHY;
}
 
Example #5
Source File: MergeQueryRequestConverterTest.java    From centraldogma with Apache License 2.0 6 votes vote down vote up
@Test
void convert() throws Exception {
    final ServiceRequestContext ctx = mock(ServiceRequestContext.class);
    final String queryString = "path=/foo.json" + '&' +
                               "pa%22th=/foo1.json" + '&' +
                               "optional_path=/foo2.json" + '&' +
                               "path=/foo3.json" + '&' +
                               "jsonpath=$.a" + '&' +
                               "revision=9999";
    when(ctx.query()).thenReturn(queryString);
    @SuppressWarnings("unchecked")
    final MergeQuery<JsonNode> mergeQuery =
            (MergeQuery<JsonNode>) converter.convertRequest(
                    ctx, mock(AggregatedHttpRequest.class), null, null);
    assertThat(mergeQuery).isEqualTo(
            MergeQuery.ofJsonPath(
                    ImmutableList.of(MergeSource.ofRequired("/foo.json"),
                                     MergeSource.ofOptional("/foo2.json"),
                                     MergeSource.ofRequired("/foo3.json")),
                    ImmutableList.of("$.a")));
}
 
Example #6
Source File: MainGraph.java    From armeria with Apache License 2.0 6 votes vote down vote up
@Produces
static ListenableFuture<List<AggregatedHttpResponse>> fetchFromBackend(
        AggregatedHttpRequest request, List<Long> dbNums, WebClient backendClient,
        ServiceRequestContext context) {
    // The context is mounted in a thread-local, meaning it is available to all logic such as tracing.
    checkState(ServiceRequestContext.current() == context);
    checkState(context.eventLoop().inEventLoop());

    final Stream.Builder<Long> nums = Stream.builder();
    for (String token : Iterables.concat(
            NUM_SPLITTER.split(request.path().substring(1)),
            NUM_SPLITTER.split(request.contentUtf8()))) {
        nums.add(Long.parseLong(token));
    }
    dbNums.forEach(nums::add);

    return Futures.allAsList(
            nums.build()
                .map(num -> toListenableFuture(backendClient.get("/square/" + num).aggregate()))
            .collect(toImmutableList()));
}
 
Example #7
Source File: DefaultHealthCheckUpdateHandler.java    From armeria with Apache License 2.0 6 votes vote down vote up
private static HealthCheckUpdateResult handlePut(AggregatedHttpRequest req) {
    final JsonNode json = toJsonNode(req);
    if (json.getNodeType() != JsonNodeType.OBJECT) {
        throw HttpStatusException.of(HttpStatus.BAD_REQUEST);
    }

    final JsonNode healthy = json.get("healthy");
    if (healthy == null) {
        throw HttpStatusException.of(HttpStatus.BAD_REQUEST);
    }
    if (healthy.getNodeType() != JsonNodeType.BOOLEAN) {
        throw HttpStatusException.of(HttpStatus.BAD_REQUEST);
    }

    return healthy.booleanValue() ? HealthCheckUpdateResult.HEALTHY
                                  : HealthCheckUpdateResult.UNHEALTHY;
}
 
Example #8
Source File: SamlMetadataServiceFunction.java    From armeria with Apache License 2.0 6 votes vote down vote up
@Override
public HttpResponse serve(ServiceRequestContext ctx, AggregatedHttpRequest req,
                          String defaultHostname, SamlPortConfig portConfig) {
    final HttpData metadata = metadataMap.computeIfAbsent(defaultHostname, h -> {
        try {
            final Element element =
                    SamlMessageUtil.serialize(buildMetadataEntityDescriptorElement(h, portConfig));
            final HttpData newMetadata = HttpData.ofUtf8(nodeToString(element));
            logger.debug("SAML service provider metadata has been prepared for: {}.", h);
            return newMetadata;
        } catch (Throwable cause) {
            logger.warn("{} Unexpected metadata request.", ctx, cause);
            return HttpData.empty();
        }
    });

    if (metadata != HttpData.empty()) {
        return HttpResponse.of(HTTP_HEADERS, metadata);
    } else {
        return HttpResponse.of(HttpStatus.NOT_FOUND);
    }
}
 
Example #9
Source File: HttpPostBindingUtil.java    From armeria with Apache License 2.0 6 votes vote down vote up
/**
 * Converts an {@link AggregatedHttpRequest} which is received from the remote entity to
 * a {@link SAMLObject}.
 */
static <T extends SAMLObject> MessageContext<T> toSamlObject(AggregatedHttpRequest req, String name) {
    final SamlParameters parameters = new SamlParameters(req);
    final byte[] decoded;
    try {
        decoded = Base64.getMimeDecoder().decode(parameters.getFirstValue(name));
    } catch (IllegalArgumentException e) {
        throw new InvalidSamlRequestException(
                "failed to decode a base64 string of the parameter: " + name, e);
    }

    @SuppressWarnings("unchecked")
    final T message = (T) deserialize(decoded);

    final MessageContext<T> messageContext = new MessageContext<>();
    messageContext.setMessage(message);

    final String relayState = parameters.getFirstValueOrNull(RELAY_STATE);
    if (relayState != null) {
        final SAMLBindingContext context = messageContext.getSubcontext(SAMLBindingContext.class, true);
        assert context != null;
        context.setRelayState(relayState);
    }

    return messageContext;
}
 
Example #10
Source File: QueryRequestConverter.java    From centraldogma with Apache License 2.0 6 votes vote down vote up
/**
 * Converts the specified {@code request} to a {@link Query} when the request has a valid file path.
 * {@code null} otherwise.
 */
@Override
@Nullable
public Query<?> convertRequest(
        ServiceRequestContext ctx, AggregatedHttpRequest request, Class<?> expectedResultType,
        @Nullable ParameterizedType expectedParameterizedResultType) throws Exception {

    final String path = getPath(ctx);
    final Iterable<String> jsonPaths = getJsonPaths(ctx);
    if (jsonPaths != null) {
        return Query.ofJsonPath(path, jsonPaths);
    }

    if (isValidFilePath(path)) {
        return Query.of(QueryType.IDENTITY, path);
    }

    return null;
}
 
Example #11
Source File: DefaultHttpRequestTest.java    From armeria with Apache License 2.0 6 votes vote down vote up
@Test
void ignoresAfterTrailersIsWritten() {
    final HttpRequestWriter req = HttpRequest.streaming(HttpMethod.GET, "/foo");
    req.write(HttpData.ofUtf8("foo"));
    req.write(HttpHeaders.of(HttpHeaderNames.of("a"), "b"));
    req.write(HttpHeaders.of(HttpHeaderNames.of("c"), "d")); // Ignored.
    req.close();

    final AggregatedHttpRequest aggregated = req.aggregate().join();
    // Request headers
    assertThat(aggregated.headers()).isEqualTo(
            RequestHeaders.of(HttpMethod.GET, "/foo",
                              HttpHeaderNames.CONTENT_LENGTH, "3"));
    // Content
    assertThat(aggregated.contentUtf8()).isEqualTo("foo");
    // Trailers
    assertThat(aggregated.trailers()).isEqualTo(HttpHeaders.of(HttpHeaderNames.of("a"), "b"));
}
 
Example #12
Source File: HttpClientIntegrationTest.java    From armeria with Apache License 2.0 6 votes vote down vote up
@Test
void testUpgradeRequestExecutesLogicOnlyOnce() throws Exception {
    final ClientFactory clientFactory = ClientFactory.builder()
                                                     .useHttp2Preface(false)
                                                     .build();
    final WebClient client = WebClient.builder(server.httpUri())
                                      .factory(clientFactory)
                                      .decorator(DecodingClient.newDecorator())
                                      .build();

    final AggregatedHttpResponse response = client.execute(
            AggregatedHttpRequest.of(HttpMethod.GET, "/only-once/request")).aggregate().get();

    assertThat(response.status()).isEqualTo(HttpStatus.OK);

    clientFactory.close();
}
 
Example #13
Source File: RepositoryService.java    From centraldogma with Apache License 2.0 6 votes vote down vote up
/**
 * POST /projects/{projectName}/repositories/{repoName}/delete/revisions/{revision}{path}
 * Deletes a file.
 */
@Post("regex:/projects/(?<projectName>[^/]+)/repositories/(?<repoName>[^/]+)" +
      "/delete/revisions/(?<revision>[^/]+)(?<path>/.*$)")
@RequiresWritePermission
public HttpResponse deleteFile(@Param String projectName,
                               @Param String repoName,
                               @Param String revision,
                               @Param String path,
                               AggregatedHttpRequest request,
                               ServiceRequestContext ctx) {
    final CommitMessageDto commitMessage;
    try {
        final JsonNode node = Jackson.readTree(request.contentUtf8());
        commitMessage = Jackson.convertValue(node.get("commitMessage"), CommitMessageDto.class);
    } catch (IOException e) {
        throw new IllegalArgumentException("invalid data to be parsed", e);
    }

    final CompletableFuture<?> future =
            push(projectName, repoName, new Revision(revision), AuthUtil.currentAuthor(ctx),
                 commitMessage.getSummary(), commitMessage.getDetail().getContent(),
                 Markup.valueOf(commitMessage.getDetail().getMarkup()), Change.ofRemoval(path));

    return HttpResponse.from(future.thenApply(unused -> HttpResponse.of(HttpStatus.OK)));
}
 
Example #14
Source File: RepositoryService.java    From centraldogma with Apache License 2.0 6 votes vote down vote up
/**
 * POST|PUT /projects/{projectName}/repositories/{repoName}/files/revisions/{revision}
 * Adds a new file or edits the existing file.
 */
@Post
@Put
@Path("/projects/{projectName}/repositories/{repoName}/files/revisions/{revision}")
@RequiresWritePermission
public CompletionStage<Object> addOrEditFile(@Param String projectName,
                                             @Param String repoName,
                                             @Param String revision,
                                             AggregatedHttpRequest request,
                                             ServiceRequestContext ctx) {
    final Entry<CommitMessageDto, Change<?>> p = commitMessageAndChange(request);
    final CommitMessageDto commitMessage = p.getKey();
    final Change<?> change = p.getValue();
    return push(projectName, repoName, new Revision(revision), AuthUtil.currentAuthor(ctx),
                commitMessage.getSummary(), commitMessage.getDetail().getContent(),
                Markup.valueOf(commitMessage.getDetail().getMarkup()), change)
            // This is so weird but there is no way to find a converter for 'null' with the current
            // Armeria's converter implementation. We will figure out a better way to improve it.
            .thenApply(unused -> VOID);
}
 
Example #15
Source File: SamlService.java    From armeria with Apache License 2.0 6 votes vote down vote up
/**
 * Creates a {@link SamlParameters} instance with the specified {@link AggregatedHttpRequest}.
 */
SamlParameters(AggregatedHttpRequest req) {
    requireNonNull(req, "req");
    final MediaType contentType = req.contentType();

    if (contentType != null && contentType.belongsTo(MediaType.FORM_DATA)) {
        final String query = req.content(contentType.charset(StandardCharsets.UTF_8));
        params = QueryParams.fromQueryString(query);
    } else {
        final String path = req.path();
        final int queryStartIdx = path.indexOf('?');
        if (queryStartIdx < 0) {
            params = QueryParams.of();
        } else {
            params = QueryParams.fromQueryString(path.substring(queryStartIdx + 1));
        }
    }
}
 
Example #16
Source File: AnnotatedServiceRequestConverterTest.java    From armeria with Apache License 2.0 6 votes vote down vote up
@Test
void testDefaultRequestConverter_text() throws Exception {
    final WebClient client = WebClient.of(server.httpUri());

    AggregatedHttpResponse response;

    final byte[] utf8 = "¥".getBytes(StandardCharsets.UTF_8);
    response = client.execute(AggregatedHttpRequest.of(HttpMethod.POST, "/2/default/text",
                                                       MediaType.PLAIN_TEXT_UTF_8, utf8))
                     .aggregate().join();
    assertThat(response.status()).isEqualTo(HttpStatus.OK);
    assertThat(response.content().array()).isEqualTo(utf8);

    final MediaType textPlain = MediaType.create("text", "plain");
    response = client.execute(AggregatedHttpRequest.of(HttpMethod.POST, "/2/default/text",
                                                       textPlain, utf8))
                     .aggregate().join();
    assertThat(response.status()).isEqualTo(HttpStatus.OK);
    // Response is encoded as UTF-8.
    assertThat(response.content().array()).isEqualTo(utf8);
}
 
Example #17
Source File: WebOperationService.java    From armeria with Apache License 2.0 6 votes vote down vote up
private static Map<String, Object> getArguments(ServiceRequestContext ctx, AggregatedHttpRequest req) {
    final Map<String, Object> arguments = new LinkedHashMap<>(ctx.pathParams());
    if (!req.content().isEmpty()) {
        final Map<String, Object> bodyParams;
        try {
            bodyParams = OBJECT_MAPPER.readValue(req.content().array(), JSON_MAP);
        } catch (IOException e) {
            throw new IllegalArgumentException("Invalid JSON in request.");
        }
        arguments.putAll(bodyParams);
    }

    final QueryParams params = QueryParams.fromQueryString(ctx.query());
    for (String name : params.names()) {
        final List<String> values = params.getAll(name);
        arguments.put(name, values.size() != 1 ? values : values.get(0));
    }

    return ImmutableMap.copyOf(arguments);
}
 
Example #18
Source File: PooledHttpRequest.java    From armeria with Apache License 2.0 5 votes vote down vote up
/**
 * Aggregates this request. The returned {@link CompletableFuture} will be notified when the content and
 * the trailers of the request are received fully.
 */
default CompletableFuture<PooledAggregatedHttpRequest> aggregateWithPooledObjects(
        EventExecutor executor, ByteBufAllocator alloc) {
    requireNonNull(executor, "executor");
    requireNonNull(alloc, "alloc");
    final CompletableFuture<AggregatedHttpRequest> future = new EventLoopCheckingFuture<>();
    final HttpRequestAggregator aggregator = new HttpRequestAggregator(this, future, alloc);
    subscribeWithPooledObjects(aggregator, executor);
    return future.thenApply(DefaultPooledAggregatedHttpRequest::new);
}
 
Example #19
Source File: HttpClientIntegrationTest.java    From armeria with Apache License 2.0 5 votes vote down vote up
@Test
void testDefaultClientFactoryOptions() throws Exception {
    final ClientFactory clientFactory = ClientFactory.builder()
                                                     .options(ClientFactoryOptions.of())
                                                     .build();
    final WebClient client = WebClient.builder(server.httpUri())
                                      .factory(clientFactory)
                                      .build();

    final AggregatedHttpResponse response = client.execute(
            AggregatedHttpRequest.of(HttpMethod.GET, "/hello/world")).aggregate().get();
    assertThat(response.status()).isEqualTo(HttpStatus.OK);

    clientFactory.close();
}
 
Example #20
Source File: AnnotatedServiceRequestConverterTest.java    From armeria with Apache License 2.0 5 votes vote down vote up
@Override
public RequestJsonObj1 convertRequest(
        ServiceRequestContext ctx, AggregatedHttpRequest request, Class<?> expectedResultType,
        @Nullable ParameterizedType expectedParameterizedResultType) throws Exception {

    if (expectedResultType.isAssignableFrom(RequestJsonObj1.class)) {
        final RequestJsonObj1 obj1 = mapper.readValue(request.contentUtf8(),
                                                      RequestJsonObj1.class);
        return new RequestJsonObj1(obj1.intVal() + 1, obj1.strVal() + 'a');
    }

    return RequestConverterFunction.fallthrough();
}
 
Example #21
Source File: AnnotatedServiceRequestConverterTest.java    From armeria with Apache License 2.0 5 votes vote down vote up
@Nullable
@Override
public Object convertRequest(
        ServiceRequestContext ctx, AggregatedHttpRequest request, Class<?> expectedResultType,
        @Nullable ParameterizedType expectedParameterizedResultType) throws Exception {

    if (expectedResultType == Bob.class) {
        final String age = ctx.pathParam("age");
        assert age != null;
        return new Bob(Integer.parseInt(age) * 2);
    }
    return RequestConverterFunction.fallthrough();
}
 
Example #22
Source File: AnnotatedServiceAnnotationAliasTest.java    From armeria with Apache License 2.0 5 votes vote down vote up
@Nullable
@Override
public Object convertRequest(
        ServiceRequestContext ctx, AggregatedHttpRequest request, Class<?> expectedResultType,
        @Nullable ParameterizedType expectedParameterizedResultType) throws Exception {

    if (expectedResultType == MyRequest.class) {
        final String decorated = ctx.attr(decoratedFlag);
        return new MyRequest(request.contentUtf8() + decorated);
    }
    return RequestConverterFunction.fallthrough();
}
 
Example #23
Source File: HttpClientIntegrationTest.java    From armeria with Apache License 2.0 5 votes vote down vote up
@Test
void testEmptyClientFactoryOptions() throws Exception {
    final ClientFactory clientFactory = ClientFactory.builder()
                                                     .options(ClientFactoryOptions.of(ImmutableList.of()))
                                                     .build();
    final WebClient client = WebClient.builder(server.httpUri())
                                      .factory(clientFactory)
                                      .build();

    final AggregatedHttpResponse response = client.execute(
            AggregatedHttpRequest.of(HttpMethod.GET, "/hello/world")).aggregate().get();
    assertThat(response.status()).isEqualTo(HttpStatus.OK);

    clientFactory.close();
}
 
Example #24
Source File: AnnotatedServiceRequestConverterTest.java    From armeria with Apache License 2.0 5 votes vote down vote up
@Test
void testDefaultRequestConverter_bean2() throws Exception {
    final WebClient client = WebClient.of(server.httpUri());
    final ObjectMapper mapper = new ObjectMapper();

    AggregatedHttpResponse response;

    // test for RequestBean2
    final RequestBean2 expectedRequestBean = new RequestBean2(98765L, "abcd-efgh");
    expectedRequestBean.userName = "john";
    expectedRequestBean.age = 25;
    expectedRequestBean.gender = MALE;
    expectedRequestBean.permissions = Arrays.asList("perm1", "perm2");
    expectedRequestBean.clientName = "TestClient";

    final String expectedResponseContent = mapper.writeValueAsString(expectedRequestBean);

    // Normal Request: POST + Form Data
    final HttpData formData = HttpData.ofAscii("age=25&gender=male");
    RequestHeaders reqHeaders = RequestHeaders.of(HttpMethod.POST, "/2/default/bean2/john/98765",
                                                  HttpHeaderNames.of("x-user-permission"), "perm1,perm2",
                                                  HttpHeaderNames.of("x-client-name"), "TestClient",
                                                  HttpHeaderNames.of("uid"), "abcd-efgh",
                                                  HttpHeaderNames.CONTENT_TYPE, MediaType.FORM_DATA);

    response = client.execute(AggregatedHttpRequest.of(reqHeaders, formData)).aggregate().join();
    assertThat(response.status()).isEqualTo(HttpStatus.OK);
    assertThat(response.contentUtf8()).isEqualTo(expectedResponseContent);

    // Normal Request: GET + Query String
    reqHeaders = RequestHeaders.of(HttpMethod.GET,
                                   "/2/default/bean2/john?age=25&gender=MALE&serialNo=98765",
                                   HttpHeaderNames.of("x-user-permission"), "perm1,perm2",
                                   HttpHeaderNames.of("x-client-name"), "TestClient",
                                   HttpHeaderNames.of("uid"), "abcd-efgh");

    response = client.execute(AggregatedHttpRequest.of(reqHeaders)).aggregate().join();
    assertThat(response.status()).isEqualTo(HttpStatus.OK);
    assertThat(response.contentUtf8()).isEqualTo(expectedResponseContent);
}
 
Example #25
Source File: AnnotatedServiceHandlersOrderTest.java    From armeria with Apache License 2.0 5 votes vote down vote up
@Override
public Object convertRequest(
        ServiceRequestContext ctx, AggregatedHttpRequest request, Class<?> expectedResultType,
        @Nullable ParameterizedType expectedParameterizedResultType) throws Exception {

    if (expectedResultType == JsonNode.class) {
        assertThat(requestCounter.getAndIncrement()).isZero();
    }
    return RequestConverterFunction.fallthrough();
}
 
Example #26
Source File: JettyService.java    From armeria with Apache License 2.0 5 votes vote down vote up
private static void fillRequest(
        ServiceRequestContext ctx, AggregatedHttpRequest aReq, Request jReq) {

    jReq.setDispatcherType(DispatcherType.REQUEST);
    jReq.setAsyncSupported(false, "armeria");
    jReq.setSecure(ctx.sessionProtocol().isTls());
    jReq.setMetaData(toRequestMetadata(ctx, aReq));

    final HttpData content = aReq.content();
    if (!content.isEmpty()) {
        jReq.getHttpInput().addContent(new Content(ByteBuffer.wrap(content.array())));
    }
    jReq.getHttpInput().eof();
}
 
Example #27
Source File: ByteArrayRequestConverterFunction.java    From armeria with Apache License 2.0 5 votes vote down vote up
/**
 * Converts the specified {@link AggregatedHttpRequest} to an object of {@code expectedResultType}.
 * This converter allows only {@code byte[]} and {@link HttpData} as its return type, and
 * {@link AggregatedHttpRequest} would be consumed only if it does not have a {@code Content-Type} header
 * or if it has {@code Content-Type: application/octet-stream} or {@code Content-Type: application/binary}.
 */
@Override
public Object convertRequest(
        ServiceRequestContext ctx, AggregatedHttpRequest request, Class<?> expectedResultType,
        @Nullable ParameterizedType expectedParameterizedResultType) throws Exception {

    final HttpData content = request.content();
    if (expectedResultType == byte[].class) {
        return content.array();
    }
    if (expectedResultType == HttpData.class) {
        return content;
    }
    return RequestConverterFunction.fallthrough();
}
 
Example #28
Source File: SamlServiceProviderTest.java    From armeria with Apache License 2.0 5 votes vote down vote up
@Override
public HttpResponse loginSucceeded(ServiceRequestContext ctx, AggregatedHttpRequest req,
                                   MessageContext<Response> message, @Nullable String sessionIndex,
                                   @Nullable String relayState) {
    return HttpResponse.of(headersWithLocation(firstNonNull(relayState, "/"))
                                   .toBuilder()
                                   .add(HttpHeaderNames.SET_COOKIE, setCookie)
                                   .build());
}
 
Example #29
Source File: SamlAuthSsoHandler.java    From centraldogma with Apache License 2.0 5 votes vote down vote up
@Override
public HttpResponse loginSucceeded(ServiceRequestContext ctx, AggregatedHttpRequest req,
                                   MessageContext<Response> message, @Nullable String sessionIndex,
                                   @Nullable String relayState) {
    final Response response = requireNonNull(message, "message").getMessage();
    final String username = Optional.ofNullable(findLoginNameFromSubjects(response))
                                    .orElseGet(() -> findLoginNameFromAttributes(response));
    if (Strings.isNullOrEmpty(username)) {
        return loginFailed(ctx, req, message,
                           new IllegalStateException("Cannot get a username from the response"));
    }

    final String sessionId = sessionIdGenerator.get();
    final Session session =
            new Session(sessionId, loginNameNormalizer.apply(username), sessionValidDuration);

    final String redirectionScript;
    if (!Strings.isNullOrEmpty(relayState)) {
        redirectionScript = "window.location.href='/#" + relayState + '\'';
    } else {
        redirectionScript = "window.location.href='/'";
    }
    return HttpResponse.from(loginSessionPropagator.apply(session).thenApply(
            unused -> HttpResponse.of(HttpStatus.OK, MediaType.HTML_UTF_8, getHtmlWithOnload(
                    "localStorage.setItem('sessionId','" + sessionId + "')",
                    redirectionScript))));
}
 
Example #30
Source File: AnnotatedServiceRequestConverterTest.java    From armeria with Apache License 2.0 5 votes vote down vote up
@Test
void testDefaultRequestConverter_bean4() throws Exception {
    final WebClient client = WebClient.of(server.httpUri() + "/3");
    final ObjectMapper mapper = new ObjectMapper();

    AggregatedHttpResponse response;

    response = client.get("/composite1/10").aggregate().join();
    assertThat(response.contentUtf8())
            .isEqualTo(CompositeRequestBean1.class.getSimpleName() + ":10:20");

    response = client.get("/composite2/10").aggregate().join();
    assertThat(response.contentUtf8())
            .isEqualTo(CompositeRequestBean2.class.getSimpleName() + ":10:20");

    response = client.get("/composite3/10").aggregate().join();
    assertThat(response.contentUtf8())
            .isEqualTo(CompositeRequestBean3.class.getSimpleName() + ":10:20");

    response = client.get("/composite4/10").aggregate().join();
    assertThat(response.contentUtf8())
            .isEqualTo(CompositeRequestBean4.class.getSimpleName() + ":10:20");

    final RequestJsonObj1 obj1 = new RequestJsonObj1(1, "abc");
    final String content1 = mapper.writeValueAsString(obj1);

    response = client.execute(AggregatedHttpRequest.of(
            HttpMethod.POST, "/composite5/10", MediaType.JSON_UTF_8, content1)).aggregate().join();
    assertThat(response.contentUtf8())
            .isEqualTo(CompositeRequestBean5.class.getSimpleName() + ":10:20:" +
                       obj1.strVal() + ':' + obj1.intVal());
}