Java Code Examples for com.linecorp.armeria.common.HttpRequest#of()
The following examples show how to use
com.linecorp.armeria.common.HttpRequest#of() .
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: DefaultServiceRequestContextTest.java From armeria with Apache License 2.0 | 6 votes |
@Test void extendRequestTimeout() { final HttpRequest req = HttpRequest.of(HttpMethod.GET, "/"); final ServiceRequestContext ctx = ServiceRequestContext.of(req); ctx.eventLoop().execute(() -> { ctx.setRequestTimeoutMillis(TimeoutMode.SET_FROM_NOW, 1000); final long oldRequestTimeout1 = ctx.requestTimeoutMillis(); ctx.setRequestTimeoutMillis(TimeoutMode.EXTEND, 1000); assertThat(ctx.requestTimeoutMillis()).isEqualTo(oldRequestTimeout1 + 1000); final long oldRequestTimeout2 = ctx.requestTimeoutMillis(); ctx.setRequestTimeout(TimeoutMode.EXTEND, Duration.ofSeconds(-2)); assertThat(ctx.requestTimeoutMillis()).isEqualTo(oldRequestTimeout2 - 2000); final long oldRequestTimeout3 = ctx.requestTimeoutMillis(); ctx.setRequestTimeoutMillis(TimeoutMode.EXTEND, 0); assertThat(ctx.requestTimeoutMillis()).isEqualTo(oldRequestTimeout3); finished.set(true); }); await().untilTrue(finished); }
Example 2
Source File: DefaultClientRequestContextTest.java From armeria with Apache License 2.0 | 6 votes |
@Test void extendResponseTimeout() { final HttpRequest req = HttpRequest.of(HttpMethod.GET, "/"); final ClientRequestContext ctx = ClientRequestContext.of(req); final long oldResponseTimeout1 = ctx.responseTimeoutMillis(); ctx.setResponseTimeoutMillis(TimeoutMode.EXTEND, 1000); await().untilAsserted(() -> { assertThat(ctx.responseTimeoutMillis()).isEqualTo(oldResponseTimeout1 + 1000); }); final long oldResponseTimeout2 = ctx.responseTimeoutMillis(); ctx.setResponseTimeout(TimeoutMode.EXTEND, Duration.ofSeconds(-2)); await().untilAsserted(() -> { assertThat(ctx.responseTimeoutMillis()).isEqualTo(oldResponseTimeout2 - 2000); }); final long oldResponseTimeout3 = ctx.responseTimeoutMillis(); ctx.setResponseTimeoutMillis(TimeoutMode.EXTEND, 0); await().untilAsserted(() -> { assertThat(ctx.responseTimeoutMillis()).isEqualTo(oldResponseTimeout3); }); }
Example 3
Source File: DefaultServiceRequestContextTest.java From armeria with Apache License 2.0 | 6 votes |
@Test void setRequestTimeoutAt() throws InterruptedException { final HttpRequest req = HttpRequest.of(HttpMethod.GET, "/"); final DefaultServiceRequestContext ctx = (DefaultServiceRequestContext) ServiceRequestContext.of(req); final long tolerance = 100; ctx.eventLoop().execute(() -> { ctx.setRequestTimeoutAt(Instant.now().plusSeconds(1)); final long oldRequestTimeoutMillis = ctx.requestTimeoutMillis(); ctx.setRequestTimeoutAtMillis(Instant.now().plusMillis(1500).toEpochMilli()); assertThat(ctx.requestTimeoutMillis()).isBetween(oldRequestTimeoutMillis + 500 - tolerance, oldRequestTimeoutMillis + 500 + tolerance); finished.set(true); }); await().untilTrue(finished); }
Example 4
Source File: LoggingClientTest.java From armeria with Apache License 2.0 | 6 votes |
@Test void sanitizeRequestHeaders() throws Exception { final HttpRequest req = HttpRequest.of(RequestHeaders.of(HttpMethod.POST, "/hello/trustin", HttpHeaderNames.SCHEME, "http", HttpHeaderNames.AUTHORITY, "test.com")); final ClientRequestContext ctx = ClientRequestContext.of(req); // use default logger final LoggingClient defaultLoggerClient = LoggingClient.builder() .requestLogLevel(LogLevel.INFO) .successfulResponseLogLevel(LogLevel.INFO) .requestHeadersSanitizer(RegexBasedSanitizer.of( Pattern.compile("trustin"), Pattern.compile("com"))) .build(delegate); // Pre sanitize step assertThat(ctx.logBuilder().toString()).contains("trustin"); assertThat(ctx.logBuilder().toString()).contains("test.com"); defaultLoggerClient.execute(ctx, req); // After the sanitize assertThat(ctx.logBuilder().toString()).doesNotContain("trustin"); assertThat(ctx.logBuilder().toString()).doesNotContain("com"); }
Example 5
Source File: DefaultServiceRequestContextTest.java From armeria with Apache License 2.0 | 6 votes |
@Test void extendRequestTimeoutFromZero() { final HttpRequest req = HttpRequest.of(HttpMethod.GET, "/"); final ServiceRequestContext ctx = ServiceRequestContext.of(req); ctx.eventLoop().execute(() -> { // This request now has an infinite timeout ctx.clearRequestTimeout(); ctx.setRequestTimeoutMillis(TimeoutMode.EXTEND, 1000); assertThat(ctx.requestTimeoutMillis()).isEqualTo(0); ctx.setRequestTimeoutMillis(TimeoutMode.EXTEND, -1000); assertThat(ctx.requestTimeoutMillis()).isEqualTo(0); finished.set(true); }); await().untilTrue(finished); }
Example 6
Source File: RequestContextAwareFutureTest.java From armeria with Apache License 2.0 | 6 votes |
@ParameterizedTest @ArgumentsSource(ContextFutureCallbackArgumentsProvider.class) void makeContextAwareCompletableFutureWithDifferentContext( BiConsumer<CompletableFuture<?>, AtomicBoolean> callback) { final HttpRequest req = HttpRequest.of(HttpMethod.GET, "/"); final ServiceRequestContext ctx1 = ServiceRequestContext.builder(req).build(); final ServiceRequestContext ctx2 = ServiceRequestContext.builder(req).build(); try (SafeCloseable ignored = ctx1.push()) { final CompletableFuture<Object> future = new CompletableFuture<>(); final CompletableFuture<Object> contextAwareFuture = ctx2.makeContextAware(future); final AtomicBoolean callbackCalled = new AtomicBoolean(); callback.accept(contextAwareFuture, callbackCalled); future.complete(null); assertThat(callbackCalled.get()).isFalse(); verify(appender, atLeast(0)).doAppend(eventCaptor.capture()); assertThat(eventCaptor.getAllValues()).anySatisfy(event -> { assertThat(event.getLevel()).isEqualTo(Level.WARN); assertThat(event.getMessage()).startsWith("An error occurred while pushing"); }); } }
Example 7
Source File: DefaultClientRequestContextTest.java From armeria with Apache License 2.0 | 5 votes |
@Test void deriveContext() { final DefaultClientRequestContext originalCtx = newContext(); mutateAdditionalHeaders(originalCtx); final AttributeKey<String> foo = AttributeKey.valueOf(DefaultClientRequestContextTest.class, "foo"); originalCtx.setAttr(foo, "foo"); final RequestId newId = RequestId.random(); final HttpRequest newRequest = HttpRequest.of(RequestHeaders.of( HttpMethod.POST, "/foo", HttpHeaderNames.SCHEME, "http", HttpHeaderNames.AUTHORITY, "example.com:8080", "foo", "bar")); final ClientRequestContext derivedCtx = originalCtx.newDerivedContext(newId, newRequest, null); assertThat(derivedCtx.endpoint()).isSameAs(originalCtx.endpoint()); assertThat(derivedCtx.sessionProtocol()).isSameAs(originalCtx.sessionProtocol()); assertThat(derivedCtx.method()).isSameAs(originalCtx.method()); assertThat(derivedCtx.options()).isSameAs(originalCtx.options()); assertThat(derivedCtx.id()).isSameAs(newId); assertThat(derivedCtx.request()).isSameAs(newRequest); assertThat(derivedCtx.path()).isEqualTo(originalCtx.path()); assertThat(derivedCtx.maxResponseLength()).isEqualTo(originalCtx.maxResponseLength()); assertThat(derivedCtx.responseTimeoutMillis()).isEqualTo(originalCtx.responseTimeoutMillis()); assertThat(derivedCtx.writeTimeoutMillis()).isEqualTo(originalCtx.writeTimeoutMillis()); assertThat(derivedCtx.additionalRequestHeaders()).isSameAs(originalCtx.additionalRequestHeaders()); // the attribute is derived as well assertThat(derivedCtx.attr(foo)).isEqualTo("foo"); // log is different assertThat(derivedCtx.log()).isNotSameAs(originalCtx.log()); final AttributeKey<String> bar = AttributeKey.valueOf(DefaultClientRequestContextTest.class, "bar"); originalCtx.setAttr(bar, "bar"); // the Attribute added to the original context after creation is not propagated to the derived context assertThat(derivedCtx.attr(bar)).isEqualTo(null); }
Example 8
Source File: ServerRequestContextAdapterTest.java From armeria with Apache License 2.0 | 5 votes |
@Test void path() { final HttpRequest req = HttpRequest.of(HttpMethod.GET, "/foo"); final HttpServerRequest braveReq = ServiceRequestContextAdapter.asHttpServerRequest( ServiceRequestContext.of(req)); assertThat(braveReq.path()).isEqualTo("/foo"); }
Example 9
Source File: DefaultClientRequestContextTest.java From armeria with Apache License 2.0 | 5 votes |
@Test void setResponseTimeoutZeroFromStart() { final HttpRequest req = HttpRequest.of(HttpMethod.GET, "/"); final DefaultClientRequestContext ctx = (DefaultClientRequestContext) ClientRequestContext.of(req); ctx.setResponseTimeoutMillis(TimeoutMode.SET_FROM_START, 0); await().untilAsserted(() -> assertThat(ctx.responseTimeoutMillis()).isEqualTo(0)); }
Example 10
Source File: ClientRequestContextAdapterTest.java From armeria with Apache License 2.0 | 5 votes |
@Test void path() { final HttpRequest req = HttpRequest.of(HttpMethod.GET, "/foo"); final HttpClientRequest braveReq = ClientRequestContextAdapter.asHttpClientRequest( ClientRequestContext.of(req), req.headers().toBuilder()); assertThat(braveReq.path()).isEqualTo("/foo"); }
Example 11
Source File: DefaultClientRequestContextTest.java From armeria with Apache License 2.0 | 5 votes |
@Test void setResponseTimeoutAfterWithNonPositive() { final HttpRequest req = HttpRequest.of(HttpMethod.GET, "/"); final ClientRequestContext ctx = ClientRequestContext.of(req); assertThatThrownBy(() -> ctx.setResponseTimeoutMillis(TimeoutMode.SET_FROM_NOW, 0)) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("(expected: > 0)"); assertThatThrownBy(() -> ctx.setResponseTimeoutMillis(TimeoutMode.SET_FROM_NOW, -10)) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("(expected: > 0)"); }
Example 12
Source File: DefaultServiceRequestContextTest.java From armeria with Apache License 2.0 | 5 votes |
@Test void setRequestTimeoutAtWithNonPositive() throws InterruptedException { final HttpRequest req = HttpRequest.of(HttpMethod.GET, "/"); final ServiceRequestContext ctx = ServiceRequestContext.of(req); ctx.setRequestTimeoutAt(Instant.now().minusSeconds(1)); await().untilAsserted(() -> assertThat(ctx.isTimedOut()).isTrue()); }
Example 13
Source File: SamlServiceProviderTest.java From armeria with Apache License 2.0 | 5 votes |
private AggregatedHttpResponse sendViaHttpRedirectBindingProtocol( String path, String paramName, SAMLObject samlObject) throws Exception { final QueryParamsBuilder params = QueryParams.builder(); params.add(paramName, toDeflatedBase64(samlObject)); params.add(SIGNATURE_ALGORITHM, signatureAlgorithm); final String input = params.toQueryString(); final String output = generateSignature(idpCredential, signatureAlgorithm, input); params.add(SIGNATURE, output); final HttpRequest req = HttpRequest.of(HttpMethod.POST, path, MediaType.FORM_DATA, params.toQueryString()); return client.execute(req).aggregate().join(); }
Example 14
Source File: FramedGrpcServiceTest.java From armeria with Apache License 2.0 | 5 votes |
@Test void badContentType() throws Exception { final HttpRequest req = HttpRequest.of( RequestHeaders.of(HttpMethod.POST, "/grpc.testing.TestService.UnaryCall", HttpHeaderNames.CONTENT_TYPE, MediaType.JSON_UTF_8)); final ServiceRequestContext ctx = ServiceRequestContext.of(req); final HttpResponse response = grpcService.doPost(ctx, PooledHttpRequest.of(req)); assertThat(response.aggregate().get()).isEqualTo(AggregatedHttpResponse.of( ResponseHeaders.of(HttpStatus.UNSUPPORTED_MEDIA_TYPE, HttpHeaderNames.CONTENT_TYPE, MediaType.PLAIN_TEXT_UTF_8, HttpHeaderNames.CONTENT_LENGTH, 39), HttpData.ofUtf8("Missing or invalid Content-Type header."))); }
Example 15
Source File: UnaryGrpcClient.java From armeria with Apache License 2.0 | 5 votes |
/** * Executes a unary gRPC client request. The given {@code payload} will be framed and sent to the path at * {@code uri}. {@code uri} should be the method's URI, which is always of the format * {@code /:package-name.:service-name/:method}. For example, for the proto package * {@code armeria.protocol}, the service name {@code CoolService} and the method name * {@code RunWithoutStubs}, the {@code uri} would be {@code /armeria.protocol.CoolService/RunWithoutStubs}. * If you aren't sure what the package, service name, and method name are for your method, you should * probably use normal gRPC stubs instead of this class. */ public CompletableFuture<byte[]> execute(String uri, byte[] payload) { final HttpRequest request = HttpRequest.of( RequestHeaders.of(HttpMethod.POST, uri, HttpHeaderNames.CONTENT_TYPE, "application/grpc+proto", HttpHeaderNames.TE, HttpHeaderValues.TRAILERS), HttpData.wrap(payload)); return webClient.execute(request).aggregate() .thenApply(msg -> { if (!HttpStatus.OK.equals(msg.status())) { throw new ArmeriaStatusException( StatusCodes.INTERNAL, "Non-successful HTTP response code: " + msg.status()); } // Status can either be in the headers or trailers depending on error String grpcStatus = msg.headers().get(GrpcHeaderNames.GRPC_STATUS); if (grpcStatus != null) { checkGrpcStatus(grpcStatus, msg.headers()); } else { grpcStatus = msg.trailers().get(GrpcHeaderNames.GRPC_STATUS); checkGrpcStatus(grpcStatus, msg.trailers()); } return msg.content().array(); }); }
Example 16
Source File: ArmeriaServerHttpRequestTest.java From armeria with Apache License 2.0 | 5 votes |
@Test void requestUriContainsBaseUrl() { final HttpRequest httpRequest = HttpRequest.of(RequestHeaders.builder(HttpMethod.POST, "/") .scheme("http") .authority("127.0.0.1") .build()); final ServiceRequestContext ctx = newRequestContext(httpRequest); final ArmeriaServerHttpRequest req = request(ctx); assertThat(req.getURI().toString()).isEqualTo("http://127.0.0.1/"); }
Example 17
Source File: ArmeriaSpringActuatorAutoConfigurationTest.java From armeria with Apache License 2.0 | 5 votes |
@Test void testOptions() { final HttpRequest req = HttpRequest.of(RequestHeaders.of( HttpMethod.OPTIONS, "/internal/actuator/health", HttpHeaderNames.ORIGIN, "https://example.com", HttpHeaderNames.ACCESS_CONTROL_REQUEST_METHOD, "GET")); final AggregatedHttpResponse res = client.execute(req).aggregate().join(); assertThat(res.status()).isEqualTo(HttpStatus.OK); assertThat(res.headers().get(HttpHeaderNames.ACCESS_CONTROL_ALLOW_ORIGIN)) .isEqualTo("https://example.com"); assertThat(res.headers().get(HttpHeaderNames.ACCESS_CONTROL_ALLOW_METHODS)) .isEqualTo("GET,POST"); assertThat(res.headers().contains(HttpHeaderNames.ACCESS_CONTROL_MAX_AGE)).isTrue(); assertThat(res.status()).isNotEqualTo(HttpStatus.METHOD_NOT_ALLOWED); }
Example 18
Source File: ArmeriaRequestHandler.java From curiostack with MIT License | 5 votes |
private <T, R extends ApiResponse<T>> PendingResult<T> handleMethod( HttpMethod method, String hostName, String url, HttpData payload, String userAgent, String experienceIdHeaderValue, Class<R> clazz, FieldNamingPolicy fieldNamingPolicy, long errorTimeout, Integer maxRetries, ExceptionsAllowedToRetry exceptionsAllowedToRetry) { var client = httpClients.computeIfAbsent( hostName, host -> WebClient.builder(host).factory(clientFactory).options(clientOptions).build()); var gson = gsonForPolicy(fieldNamingPolicy); var headers = RequestHeaders.builder(method, url); if (experienceIdHeaderValue != null) { headers.add("X-Goog-Maps-Experience-ID", experienceIdHeaderValue); } var request = HttpRequest.of(headers.build(), payload); return new ArmeriaPendingResult<>(client, request, clazz, gson); }
Example 19
Source File: DefaultServiceRequestContextTest.java From armeria with Apache License 2.0 | 5 votes |
@Test void clearRequestTimeout() { final HttpRequest req = HttpRequest.of(HttpMethod.GET, "/"); final DefaultServiceRequestContext ctx = (DefaultServiceRequestContext) ServiceRequestContext.of(req); ctx.eventLoop().execute(() -> { ctx.setRequestTimeoutMillis(2000); assertThat(ctx.requestTimeoutMillis()).isEqualTo(2000); ctx.clearRequestTimeout(); assertThat(ctx.requestTimeoutMillis()).isEqualTo(0); finished.set(true); }); await().untilTrue(finished); }
Example 20
Source File: ArmeriaCompressionConfigurationTest.java From armeria with Apache License 2.0 | 4 votes |
private static HttpRequest request(int sizeParam) { return HttpRequest.of(RequestHeaders.of(HttpMethod.GET, "/hello?size=" + sizeParam, HttpHeaderNames.ACCEPT_ENCODING, "gzip")); }