com.linecorp.armeria.common.HttpResponse Java Examples
The following examples show how to use
com.linecorp.armeria.common.HttpResponse.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: AuthService.java From armeria with Apache License 2.0 | 6 votes |
@Override public HttpResponse serve(ServiceRequestContext ctx, HttpRequest req) throws Exception { return HttpResponse.from(AuthorizerUtil.authorize(authorizer, ctx, req).handleAsync((result, cause) -> { try { final HttpService delegate = (HttpService) unwrap(); if (cause == null) { if (result != null) { return result ? successHandler.authSucceeded(delegate, ctx, req) : failureHandler.authFailed(delegate, ctx, req, null); } cause = AuthorizerUtil.newNullResultException(authorizer); } return failureHandler.authFailed(delegate, ctx, req, cause); } catch (Exception e) { return Exceptions.throwUnsafely(e); } }, ctx.contextAwareEventLoop())); }
Example #2
Source File: HttpsOnlyService.java From curiostack with MIT License | 6 votes |
@Override public HttpResponse serve(ServiceRequestContext ctx, HttpRequest req) throws Exception { String xForwardedProto = Ascii.toLowerCase(Strings.nullToEmpty(req.headers().get(X_FORWARDED_PROTO))); if (xForwardedProto.isEmpty() || xForwardedProto.equals("https")) { ctx.addAdditionalResponseHeader(STRICT_TRANSPORT_SECURITY, "max-age=31536000; preload"); ctx.addAdditionalResponseHeader(HttpHeaderNames.X_FRAME_OPTIONS, "DENY"); config .getAdditionalResponseHeaders() .forEach( (key, value) -> ctx.addAdditionalResponseHeader(HttpHeaderNames.of(key), (String) value)); return delegate().serve(ctx, req); } StringBuilder redirectUrl = new StringBuilder("https://" + req.headers().authority() + ctx.path()); if (ctx.query() != null) { redirectUrl.append('?').append(ctx.query()); } return HttpResponse.of( HttpResponse.of( ResponseHeaders.of( HttpStatus.MOVED_PERMANENTLY, HttpHeaderNames.LOCATION, redirectUrl.toString()))); }
Example #3
Source File: HttpClientRequestPathTest.java From armeria with Apache License 2.0 | 6 votes |
@Override protected void configure(ServerBuilder sb) throws Exception { sb.http(0) .https(0) .tlsSelfSigned() .service("/simple-client", (ctx, req) -> HttpResponse.of(OK)) .service("/retry", (ctx, req) -> { if (++counter < 3) { return HttpResponse.of(INTERNAL_SERVER_ERROR); } else { return HttpResponse.of(OK); } }) .service("/redirect", (ctx, req) -> { final HttpHeaders headers = ResponseHeaders.of(HttpStatus.TEMPORARY_REDIRECT, LOCATION, server1.httpUri() + "/new-location"); return HttpResponse.of(headers); }); }
Example #4
Source File: HttpServiceLogNameTest.java From armeria with Apache License 2.0 | 6 votes |
@Override protected void configure(ServerBuilder sb) throws Exception { sb.accessLogWriter(AccessLogWriter.combined(), true); sb.service("/no-default", new MyHttpService()); sb.service("/no-default/:id", new MyHttpService().decorate(LoggingService.newDecorator())); sb.route() .get("/users/:id") .defaultServiceName("userService") .defaultLogName("profile") .build((ctx, req) -> HttpResponse.of(HttpStatus.OK)); sb.annotatedService("/annotated", new MyAnnotatedService()); sb.decorator((delegate, ctx, req) -> { capturedCtx = ctx; return delegate.serve(ctx, req); }); }
Example #5
Source File: HttpClientTimeoutTest.java From armeria with Apache License 2.0 | 6 votes |
@Test public void responseTimeoutH1C() throws Exception { try (ServerSocket ss = new ServerSocket(0)) { final WebClient client = WebClient.builder("h1c://127.0.0.1:" + ss.getLocalPort()) .factory(factory) .responseTimeout(Duration.ofSeconds(1)) .build(); final HttpResponse res = client.get("/"); try (Socket s = ss.accept()) { s.setSoTimeout(1000); // Let the response timeout occur. assertThatThrownBy(() -> res.aggregate().join()) .isInstanceOf(CompletionException.class) .hasCauseInstanceOf(ResponseTimeoutException.class); // Make sure that the connection is closed. final InputStream in = s.getInputStream(); while (in.read() >= 0) { continue; } } } }
Example #6
Source File: ZooKeeperRegistrationTest.java From armeria with Apache License 2.0 | 6 votes |
private static List<Server> startServers(boolean endpointRegistrationSpec) { final List<Server> servers = new ArrayList<>(); for (int i = 0; i < sampleEndpoints.size(); i++) { final Server server = Server.builder() .http(sampleEndpoints.get(i).port()) .service("/", (ctx, req) -> HttpResponse.of(200)) .build(); final ZooKeeperRegistrationSpec registrationSpec; if (endpointRegistrationSpec) { registrationSpec = ZooKeeperRegistrationSpec.legacy(sampleEndpoints.get(i)); } else { registrationSpec = ZooKeeperRegistrationSpec.builderForCurator(CURATOR_X_SERVICE_NAME) .serviceId(String.valueOf(i)) .serviceAddress(CURATOR_X_ADDRESS) .build(); } final ServerListener listener = ZooKeeperUpdatingListener.builder(zkInstance.connectString(), Z_NODE, registrationSpec) .sessionTimeoutMillis(SESSION_TIMEOUT_MILLIS) .build(); server.addListener(listener); server.start().join(); servers.add(server); } return servers; }
Example #7
Source File: RouteDecoratingTest.java From armeria with Apache License 2.0 | 6 votes |
@Override protected void configure(ServerBuilder sb) throws Exception { sb.decorator(Route.builder().path("/") .matchesHeaders("dest=headers-decorator").build(), (delegate, ctx, req) -> HttpResponse.of("headers-decorator")) .service(Route.builder().methods(HttpMethod.GET).path("/") .matchesHeaders("dest=headers-service").build(), (ctx, req) -> HttpResponse.of("headers-service")) .decorator(Route.builder().path("/") .matchesParams("dest=params-decorator").build(), (delegate, ctx, req) -> HttpResponse.of("params-decorator")) .service(Route.builder().methods(HttpMethod.GET).path("/") .matchesParams("dest=params-service").build(), (ctx, req) -> HttpResponse.of("params-service")) .service(Route.builder().methods(HttpMethod.GET).path("/").build(), (ctx, req) -> HttpResponse.of(HttpStatus.INTERNAL_SERVER_ERROR)); }
Example #8
Source File: AbstractHttpFile.java From armeria with Apache License 2.0 | 6 votes |
@Nullable private HttpResponse read(Executor fileReadExecutor, ByteBufAllocator alloc, @Nullable HttpFileAttributes attrs) { final ResponseHeaders headers = readHeaders(attrs); if (headers == null) { return null; } final long length = attrs.length(); if (length == 0) { // No need to stream an empty file. return HttpResponse.of(headers); } try { return doRead(headers, length, fileReadExecutor, alloc); } catch (IOException e) { return Exceptions.throwUnsafely(e); } }
Example #9
Source File: RouteDecoratingTest.java From armeria with Apache License 2.0 | 6 votes |
@Override protected void configure(final ServerBuilder sb) throws Exception { sb.virtualHost("foo.com") .routeDecorator() .pathPrefix("/foo") .build((delegate, ctx, req) -> { if (!ACCESS_TOKEN.equals(req.headers().get(HttpHeaderNames.AUTHORIZATION))) { return HttpResponse.of(HttpStatus.UNAUTHORIZED); } return delegate.serve(ctx, req); }) .serviceUnder("/foo", (ctx, req) -> HttpResponse.of(HttpStatus.OK)) .and() .virtualHost("bar.com") .serviceUnder("/bar", (ctx, req) -> HttpResponse.of(HttpStatus.OK)); }
Example #10
Source File: RetryingClientTest.java From armeria with Apache License 2.0 | 6 votes |
private WebClient client(RetryRuleWithContent<HttpResponse> retryRuleWithContent, long responseTimeoutMillis, long responseTimeoutForEach, int maxTotalAttempts) { final Function<? super HttpClient, RetryingClient> retryingDecorator = RetryingClient.builder(retryRuleWithContent) .responseTimeoutMillisForEachAttempt(responseTimeoutForEach) .useRetryAfter(true) .maxTotalAttempts(maxTotalAttempts) .newDecorator(); return WebClient.builder(server.httpUri()) .factory(clientFactory) .responseTimeoutMillis(responseTimeoutMillis) .decorator(LoggingClient.newDecorator()) .decorator(retryingDecorator) .build(); }
Example #11
Source File: ExceptionHandlerService.java From armeria with Apache License 2.0 | 5 votes |
@Override public HttpResponse handleException(ServiceRequestContext ctx, HttpRequest req, Throwable cause) { if (cause instanceof GloballyGeneralException) { return HttpResponse.of(HttpStatus.FORBIDDEN); } // To the next exception handler. return ExceptionHandlerFunction.fallthrough(); }
Example #12
Source File: AnnotatedService.java From armeria with Apache License 2.0 | 5 votes |
private static void warnIfHttpResponseArgumentExists(Type returnType, ParameterizedType type) { for (final Type arg : type.getActualTypeArguments()) { if (arg instanceof ParameterizedType) { warnIfHttpResponseArgumentExists(returnType, (ParameterizedType) arg); } else if (arg instanceof Class) { final Class<?> clazz = (Class<?>) arg; if (HttpResponse.class.isAssignableFrom(clazz) || AggregatedHttpResponse.class.isAssignableFrom(clazz)) { logger.warn("{} in the return type '{}' may take precedence over {}.", clazz.getSimpleName(), returnType, HttpResult.class.getSimpleName()); } } } }
Example #13
Source File: DeferredHttpFile.java From armeria with Apache License 2.0 | 5 votes |
@Override public CompletableFuture<HttpResponse> read(Executor fileReadExecutor, ByteBufAllocator alloc) { requireNonNull(fileReadExecutor, "fileReadExecutor"); requireNonNull(alloc, "alloc"); final HttpFile delegate = this.delegate; if (delegate != null) { return delegate.read(fileReadExecutor, alloc); } return stage.thenCompose(file -> { setDelegate(file); return file.read(fileReadExecutor, alloc); }); }
Example #14
Source File: TruncatingHttpResponseTest.java From armeria with Apache License 2.0 | 5 votes |
@Test void smallContent() throws InterruptedException { final HttpResponseWriter writer = HttpResponse.streaming(); writer.write(() -> ResponseHeaders.of(HttpStatus.OK)); writer.write(() -> HttpData.ofUtf8("1234567890")); writer.close(); final TruncatingHttpResponse response = new TruncatingHttpResponse(writer, 20); final AggregatedHttpResponse agg = response.aggregate().join(); assertThat(agg.contentUtf8()).isEqualTo("1234567890"); }
Example #15
Source File: PortUnificationServerTest.java From armeria with Apache License 2.0 | 5 votes |
@Override protected void configure(ServerBuilder sb) throws Exception { sb.port(0, PROXY, HTTP, HTTPS); sb.tlsSelfSigned(); sb.service("/", new AbstractHttpService() { @Override protected HttpResponse doGet(ServiceRequestContext ctx, HttpRequest req) { return HttpResponse.of(HttpStatus.OK, MediaType.PLAIN_TEXT_UTF_8, ctx.sessionProtocol().name()); } }); }
Example #16
Source File: Http1ConnectionReuseTest.java From armeria with Apache License 2.0 | 5 votes |
@Override protected void configure(ServerBuilder sb) throws Exception { sb.service("/", (ctx, req) -> { remoteAddresses.add(ctx.remoteAddress()); return HttpResponse.of(200); }); }
Example #17
Source File: PooledResponseBufferBenchmark.java From armeria with Apache License 2.0 | 5 votes |
@Override public HttpResponse serve(ServiceRequestContext ctx, HttpRequest req) throws Exception { final HttpResponse res = unwrap().serve(ctx, req); final HttpResponseWriter decorated = HttpResponse.streaming(); res.subscribe(new Subscriber<HttpObject>() { @Override public void onSubscribe(Subscription s) { s.request(Long.MAX_VALUE); } @Override public void onNext(HttpObject httpObject) { decorated.write(httpObject); } @Override public void onError(Throwable t) { decorated.close(t); } @Override public void onComplete() { decorated.close(); } }); return decorated; }
Example #18
Source File: TestConverters.java From armeria with Apache License 2.0 | 5 votes |
@Override public HttpResponse convertResponse(ServiceRequestContext ctx, ResponseHeaders headers, @Nullable Object result, HttpHeaders trailers) throws Exception { return httpResponse(HttpData.ofUtf8(result != null ? result.toString() : "(null)")); }
Example #19
Source File: RetryingClientWithLoggingTest.java From armeria with Apache License 2.0 | 5 votes |
private Function<? super HttpClient, ? extends HttpClient> loggingDecorator() { return delegate -> new SimpleDecoratingHttpClient(delegate) { @Override public HttpResponse execute(ClientRequestContext ctx, HttpRequest req) throws Exception { ctx.log().whenRequestComplete().thenAccept(log -> listener.accept(log.partial())); ctx.log().whenComplete().thenAccept(listener); return unwrap().execute(ctx, req); } }; }
Example #20
Source File: ArmeriaAutoConfigurationTest.java From armeria with Apache License 2.0 | 5 votes |
@Test public void testAnnotatedServiceRegistrationBean() throws Exception { final WebClient client = WebClient.of(newUrl("h1c")); HttpResponse response = client.get("/annotated/get"); AggregatedHttpResponse res = response.aggregate().get(); assertThat(res.status()).isEqualTo(HttpStatus.OK); assertThat(res.contentUtf8()).isEqualTo("annotated"); response = client.get("/annotated/get/2"); res = response.aggregate().get(); assertThat(res.status()).isEqualTo(HttpStatus.OK); assertThat(res.contentUtf8()).isEqualTo("exception"); final RequestHeaders postJson = RequestHeaders.of(HttpMethod.POST, "/annotated/post", HttpHeaderNames.CONTENT_TYPE, "application/json"); response = client.execute(postJson, "{\"foo\":\"bar\"}"); res = response.aggregate().join(); assertThat(res.status()).isEqualTo(HttpStatus.OK); assertThatJson(res.contentUtf8()).node("foo").isEqualTo("bar"); final WebClient webClient = WebClient.of(newUrl("h1c")); response = webClient.get("/internal/docs/specification.json"); res = response.aggregate().get(); assertThat(res.status()).isEqualTo(HttpStatus.OK); assertThatJson(res.contentUtf8()).node("services[0].name").isStringEqualTo( "com.linecorp.armeria.spring.ArmeriaAutoConfigurationTest$AnnotatedService"); assertThatJson(res.contentUtf8()) .node("services[0].methods[2].exampleRequests[0]").isStringEqualTo("{\"foo\":\"bar\"}"); assertThatJson(res.contentUtf8()) .node("services[0].exampleHttpHeaders[0].x-additional-header").isStringEqualTo("headerVal"); assertThatJson(res.contentUtf8()) .node("services[0].methods[0].exampleHttpHeaders[0].x-additional-header") .isStringEqualTo("headerVal"); }
Example #21
Source File: AnnotatedServiceHandlersOrderTest.java From armeria with Apache License 2.0 | 5 votes |
@Override public HttpResponse convertResponse(ServiceRequestContext ctx, ResponseHeaders headers, @Nullable Object result, HttpHeaders trailers) throws Exception { if (result instanceof String && "hello foo".equals(result)) { assertThat(responseCounter.getAndIncrement()).isZero(); } return ResponseConverterFunction.fallthrough(); }
Example #22
Source File: AnnotatedServiceBindingBuilderTest.java From armeria with Apache License 2.0 | 5 votes |
@Test void testAllConfigurationsAreRespected() { final boolean verboseResponse = true; final boolean shutdownOnStop = true; final long maxRequestLength = 2 * 1024; final AccessLogWriter accessLogWriter = AccessLogWriter.common(); final Duration requestTimeoutDuration = Duration.ofMillis(1000); final Server server = Server.builder() .annotatedService() .requestTimeout(requestTimeoutDuration) .maxRequestLength(maxRequestLength) .exceptionHandlers((ctx, request, cause) -> HttpResponse.of(400)) .pathPrefix("/home") .accessLogWriter(accessLogWriter, shutdownOnStop) .verboseResponses(verboseResponse) .build(new TestService()) .build(); assertThat(server.config().serviceConfigs()).hasSize(2); final ServiceConfig homeFoo = server.config().serviceConfigs().get(0); assertThat(homeFoo.requestTimeoutMillis()).isEqualTo(requestTimeoutDuration.toMillis()); assertThat(homeFoo.maxRequestLength()).isEqualTo(maxRequestLength); assertThat(homeFoo.accessLogWriter()).isEqualTo(accessLogWriter); assertThat(homeFoo.shutdownAccessLogWriterOnStop()).isTrue(); assertThat(homeFoo.verboseResponses()).isTrue(); final ServiceConfig homeBar = server.config().serviceConfigs().get(1); assertThat(homeBar.requestTimeoutMillis()).isEqualTo(requestTimeoutDuration.toMillis()); assertThat(homeBar.maxRequestLength()).isEqualTo(maxRequestLength); assertThat(homeBar.accessLogWriter()).isEqualTo(accessLogWriter); assertThat(homeBar.shutdownAccessLogWriterOnStop()).isTrue(); assertThat(homeBar.verboseResponses()).isTrue(); }
Example #23
Source File: AggregatedHttpFile.java From armeria with Apache License 2.0 | 5 votes |
@Override default CompletableFuture<HttpResponse> read(Executor fileReadExecutor, ByteBufAllocator alloc) { final AggregatedHttpResponse res = read(); if (res == null) { return UnmodifiableFuture.completedFuture(null); } else { return UnmodifiableFuture.completedFuture(res.toHttpResponse()); } }
Example #24
Source File: ArmeriaConfigurationUtilTest.java From armeria with Apache License 2.0 | 5 votes |
@Test void configureServer() throws Exception { final File yml = new File(resourceFilePath("armeria-settings.yaml")); final ArmeriaSettings armeriaSettings = configFactory.build(yml); armeriaSettings.setSsl(null); final ServerBuilder serverBuilder = Server.builder() .service("/foo", (ctx, req) -> HttpResponse.of(200)); serverBuilder.tlsSelfSigned(); ArmeriaConfigurationUtil.configureServer(serverBuilder, armeriaSettings); final Server server = serverBuilder.build(); assertThat(server.defaultHostname()).isEqualTo("host.name.com"); assertThat(server.config().maxNumConnections()).isEqualTo(5000); assertThat(server.config().isDateHeaderEnabled()).isFalse(); assertThat(server.config().isServerHeaderEnabled()).isTrue(); assertThat(server.config().defaultVirtualHost().maxRequestLength()).isEqualTo(10485761); assertThat(server.config().ports()).hasSize(3); assertThat(server.config().ports()).containsExactly( new ServerPort(8080, SessionProtocol.HTTP), new ServerPort(new InetSocketAddress("127.0.0.1", 8081), SessionProtocol.HTTPS), new ServerPort(8443, SessionProtocol.HTTPS, SessionProtocol.PROXY) ); assertThat(server.config().http1MaxChunkSize()).isEqualTo(4000); assertThat(server.config().http1MaxInitialLineLength()).isEqualTo(4096); assertThat(server.config().http1MaxInitialLineLength()).isEqualTo(4096); assertThat(server.config().http2InitialConnectionWindowSize()).isEqualTo(1024 * 1024 * 2); assertThat(server.config().http2InitialStreamWindowSize()).isEqualTo(1024 * 1024 * 2); assertThat(server.config().http2MaxFrameSize()).isEqualTo(16385); assertThat(server.config().http2MaxHeaderListSize()).isEqualTo(8193); assertThat(server.config().proxyProtocolMaxTlvSize()).isEqualTo(65320); }
Example #25
Source File: VirtualHostServiceBindingBuilderTest.java From armeria with Apache License 2.0 | 5 votes |
@Test void withRoute() { final ServerBuilder sb = Server.builder(); sb.virtualHost("example.com").withRoute(builder -> { builder.pathPrefix("/foo/bar") .methods(HttpMethod.GET) .consumes(JSON, PLAIN_TEXT_UTF_8) .produces(JSON_UTF_8, PLAIN_TEXT_UTF_8) .requestTimeoutMillis(10) .maxRequestLength(8192) .verboseResponses(true) .build((ctx, req) -> HttpResponse.of(OK)); }); final List<ServiceConfig> serviceConfigs = sb.build().serviceConfigs(); assertThat(serviceConfigs.size()).isOne(); final ServiceConfig serviceConfig = serviceConfigs.get(0); final Route route = serviceConfig.route(); assertThat(route.pathType()).isSameAs(RoutePathType.PREFIX); assertThat(route.paths()).containsExactly("/foo/bar/", "/foo/bar/*"); assertThat(route.consumes()).containsExactly(JSON, PLAIN_TEXT_UTF_8); assertThat(route.produces()).containsExactly(JSON_UTF_8, PLAIN_TEXT_UTF_8); assertThat(serviceConfig.requestTimeoutMillis()).isEqualTo(10); assertThat(serviceConfig.maxRequestLength()).isEqualTo(8192); assertThat(serviceConfig.verboseResponses()).isEqualTo(true); }
Example #26
Source File: ClientAuthIntegrationTest.java From armeria with Apache License 2.0 | 5 votes |
@Override protected void configure(ServerBuilder sb) throws Exception { sb.tls(serverCert.certificateFile(), serverCert.privateKeyFile()); sb.tlsCustomizer(sslCtxBuilder -> { sslCtxBuilder.trustManager(InsecureTrustManagerFactory.INSTANCE) .clientAuth(ClientAuth.REQUIRE); }); sb.service("/", (ctx, req) -> HttpResponse.of("success")); sb.decorator(LoggingService.builder().newDecorator()); }
Example #27
Source File: HttpServerKeepAliveHandlerTest.java From armeria with Apache License 2.0 | 5 votes |
@Override protected void configure(ServerBuilder sb) throws Exception { sb.idleTimeoutMillis(0); sb.pingIntervalMillis(0); sb.requestTimeoutMillis(1000); sb.service("/", (ctx, req) -> HttpResponse.of("OK")); sb.service("/streaming", (ctx, req) -> HttpResponse.streaming()); }
Example #28
Source File: MyAuthHandler.java From armeria with Apache License 2.0 | 5 votes |
/** * Invoked when a single sign-on request is rejected from the identity provider. */ @Override public HttpResponse loginFailed(ServiceRequestContext ctx, AggregatedHttpRequest req, @Nullable MessageContext<Response> message, Throwable cause) { return HttpResponse.of(HttpStatus.UNAUTHORIZED, MediaType.HTML_UTF_8, "<html><body>Login failed.</body></html>"); }
Example #29
Source File: SimplePooledDecoratingHttpServiceTest.java From armeria with Apache License 2.0 | 5 votes |
@Override protected HttpResponse serve(PooledHttpService delegate, ServiceRequestContext ctx, PooledHttpRequest req) throws Exception { // Whether the decorator is applied to an unpooled or pooled delegate, it doesn't matter, we have // easy access to the unsafe API. return HttpResponse.from( delegate.serve(ctx, req).aggregateWithPooledObjects(ctx.eventLoop(), ctx.alloc()) .thenApply(agg -> { try (SafeCloseable unused = agg) { return HttpResponse.of(agg.contentUtf8() + " and goodbye!"); } })); }
Example #30
Source File: HttpServerDefaultHeadersTest.java From armeria with Apache License 2.0 | 5 votes |
@Override protected void configure(ServerBuilder sb) throws Exception { sb.disableServerHeader(); sb.service("/", (ctx, req) -> { return HttpResponse.of(HttpStatus.OK); }); }