com.linecorp.armeria.server.HttpService Java Examples
The following examples show how to use
com.linecorp.armeria.server.HttpService.
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: DeferredHttpFile.java From armeria with Apache License 2.0 | 6 votes |
@Override public HttpService asService() { final HttpFile delegate = this.delegate; if (delegate != null) { return delegate.asService(); } return (ctx, req) -> HttpResponse.from(stage.thenApply(file -> { setDelegate(file); try { return file.asService().serve(ctx, req); } catch (Exception e) { return Exceptions.throwUnsafely(e); } })); }
Example #2
Source File: ArmeriaConfigurationUtil.java From armeria with Apache License 2.0 | 6 votes |
/** * Adds HTTP services to the specified {@link ServerBuilder}. */ public static void configureHttpServices( ServerBuilder server, List<HttpServiceRegistrationBean> beans, @Nullable MeterIdPrefixFunctionFactory meterIdPrefixFunctionFactory) { requireNonNull(server, "server"); requireNonNull(beans, "beans"); beans.forEach(bean -> { HttpService service = bean.getService(); for (Function<? super HttpService, ? extends HttpService> decorator : bean.getDecorators()) { service = service.decorate(decorator); } service = setupMetricCollectingService(service, bean, meterIdPrefixFunctionFactory); server.service(bean.getRoute(), service); }); }
Example #3
Source File: ContentPreviewingServiceTest.java From armeria with Apache License 2.0 | 6 votes |
private Function<? super HttpService, ContentPreviewingService> decodingContentPreviewDecorator() { final BiPredicate<? super RequestContext, ? super HttpHeaders> previewerPredicate = (requestContext, headers) -> "gzip".equals(headers.get(HttpHeaderNames.CONTENT_ENCODING)); final BiFunction<HttpHeaders, ByteBuf, String> producer = (headers, data) -> { final byte[] bytes = new byte[data.readableBytes()]; data.getBytes(0, bytes); final byte[] decoded; try (GZIPInputStream unzipper = new GZIPInputStream(new ByteArrayInputStream(bytes))) { decoded = ByteStreams.toByteArray(unzipper); } catch (Exception e) { throw new IllegalArgumentException(e); } return new String(decoded, StandardCharsets.UTF_8); }; final ContentPreviewerFactory factory = ContentPreviewerFactory.builder() .maxLength(100) .binary(producer, previewerPredicate) .build(); return ContentPreviewingService.newDecorator(factory); }
Example #4
Source File: CentralDogma.java From centraldogma with Apache License 2.0 | 6 votes |
private void configureThriftService(ServerBuilder sb, ProjectManager pm, CommandExecutor executor, WatchService watchService, MetadataService mds) { final CentralDogmaServiceImpl service = new CentralDogmaServiceImpl(pm, executor, watchService, mds); HttpService thriftService = ThriftCallService.of(service) .decorate(CentralDogmaTimeoutScheduler::new) .decorate(CentralDogmaExceptionTranslator::new) .decorate(THttpService.newDecorator()); if (cfg.isCsrfTokenRequiredForThrift()) { thriftService = thriftService.decorate(AuthService.newDecorator(new CsrfTokenAuthorizer())); } else { thriftService = thriftService.decorate(TokenlessClientLogger::new); } // Enable content compression for API responses. thriftService = thriftService.decorate(contentEncodingDecorator()); sb.service("/cd/thrift/v1", thriftService); }
Example #5
Source File: FirebaseAuthorizer.java From curiostack with MIT License | 6 votes |
@Override public HttpResponse authFailed( HttpService delegate, ServiceRequestContext ctx, HttpRequest req, @Nullable Throwable cause) throws Exception { if (cause != null) { logger.warn("Unexpected exception during authorization.", cause); return HttpResponse.of(HttpStatus.UNAUTHORIZED); } if (!config.getIncludedPaths().isEmpty()) { if (config.getIncludedPaths().contains(ctx.path())) { return HttpResponse.of(HttpStatus.UNAUTHORIZED); } else { return delegate.serve(ctx, req); } } if (config.getExcludedPaths().contains(ctx.path())) { return delegate.serve(ctx, req); } return HttpResponse.of(HttpStatus.UNAUTHORIZED); }
Example #6
Source File: ThrottlingServiceBuilder.java From armeria with Apache License 2.0 | 5 votes |
/** * Returns a newly-created decorator that decorates an {@link Service} with a new * {@link ThrottlingService} based on the {@link ThrottlingStrategy}s added to this builder. */ public Function<? super HttpService, ThrottlingService> newDecorator() { final ThrottlingStrategy<HttpRequest> strategy = getStrategy(); final ThrottlingAcceptHandler<HttpRequest, HttpResponse> acceptHandler = getAcceptHandler(); final ThrottlingRejectHandler<HttpRequest, HttpResponse> rejectHandler = getRejectHandler(); return service -> new ThrottlingService(service, strategy, acceptHandler, rejectHandler); }
Example #7
Source File: EncodingService.java From armeria with Apache License 2.0 | 5 votes |
/** * Creates a new instance. */ EncodingService(HttpService delegate, Predicate<MediaType> encodableContentTypePredicate, Predicate<? super RequestHeaders> encodableRequestHeadersPredicate, long minBytesToForceChunkedAndEncoding) { super(delegate); this.encodableContentTypePredicate = encodableContentTypePredicate; this.encodableRequestHeadersPredicate = encodableRequestHeadersPredicate; this.minBytesToForceChunkedAndEncoding = minBytesToForceChunkedAndEncoding; }
Example #8
Source File: LoggingServiceBuilder.java From armeria with Apache License 2.0 | 5 votes |
/** * Returns a newly-created {@link LoggingService} decorating {@link HttpService} based on the properties * of this builder. */ public LoggingService build(HttpService delegate) { return new LoggingService(delegate, logger(), requestLogLevelMapper(), responseLogLevelMapper(), requestHeadersSanitizer(), requestContentSanitizer(), requestTrailersSanitizer(), responseHeadersSanitizer(), responseContentSanitizer(), responseTrailersSanitizer(), responseCauseSanitizer(), sampler); }
Example #9
Source File: LoggingService.java From armeria with Apache License 2.0 | 5 votes |
/** * Returns a new {@link HttpService} decorator that logs {@link HttpRequest}s and {@link HttpResponse}s at * {@link LogLevel#INFO} for success, {@link LogLevel#WARN} for failure. * * @see LoggingServiceBuilder for more information on the default settings. */ public static Function<? super HttpService, LoggingService> newDecorator() { return builder().requestLogLevel(LogLevel.INFO) .successfulResponseLogLevel(LogLevel.INFO) .failureResponseLogLevel(LogLevel.WARN) .newDecorator(); }
Example #10
Source File: AuthProvider.java From centraldogma with Apache License 2.0 | 5 votes |
/** * Returns a {@link Service} which handles a logout request from a web browser. By default, * the browser would bring a user to the built-in web logout page served on * {@value BUILTIN_WEB_LOGOUT_PATH}. */ default HttpService webLogoutService() { // Redirect to the default page: /link/auth/logout -> /web/auth/logout return (ctx, req) -> HttpResponse.of( ResponseHeaders.of(HttpStatus.MOVED_PERMANENTLY, HttpHeaderNames.LOCATION, BUILTIN_WEB_LOGOUT_PATH)); }
Example #11
Source File: MetricCollectingService.java From armeria with Apache License 2.0 | 5 votes |
/** * Returns a new {@link HttpService} decorator that tracks request stats using {@link MeterRegistry}. */ public static Function<? super HttpService, MetricCollectingService> newDecorator( MeterIdPrefixFunction meterIdPrefixFunction) { requireNonNull(meterIdPrefixFunction, "meterIdPrefixFunction"); return delegate -> new MetricCollectingService(delegate, meterIdPrefixFunction); }
Example #12
Source File: AnnotatedServiceFactory.java From armeria with Apache License 2.0 | 5 votes |
private DecoratorAndOrder(Annotation annotation, Function<? super HttpService, ? extends HttpService> decorator, int order) { this.annotation = annotation; this.decorator = decorator; this.order = order; }
Example #13
Source File: LoggingModule.java From curiostack with MIT License | 5 votes |
@Provides @Singleton static Function<HttpService, LoggingService> loggingService( LoggingConfig config, @RequestHeaderSanitizer Set<Consumer<HttpHeadersBuilder>> requestHeaderSanitizers, @ResponseHeaderSanitizer Set<Consumer<HttpHeadersBuilder>> responseHeaderSanitizers) { LoggingServiceBuilder builder = LoggingService.builder(); configureLoggingDecorator(builder, config, requestHeaderSanitizers, responseHeaderSanitizers); if (config.getLogAllServerRequests()) { builder.requestLogLevel(LogLevel.INFO); builder.successfulResponseLogLevel(LogLevel.INFO); } return builder::build; }
Example #14
Source File: HttpServerCorsTest.java From armeria with Apache License 2.0 | 5 votes |
@Test public void testCorsBuilderException() { assertThatThrownBy(() -> CorsService.builderForAnyOrigin().maxAge(-1)).isInstanceOf( IllegalStateException.class); assertThatThrownBy(() -> CorsService.builderForAnyOrigin().allowNullOrigin()).isInstanceOf( IllegalStateException.class); assertThatThrownBy(() -> CorsService.builderForAnyOrigin().shortCircuit()).isInstanceOf( IllegalStateException.class); assertThatThrownBy(() -> CorsService.builderForAnyOrigin().allowRequestHeaders("", null, "")) .isInstanceOf(NullPointerException.class); assertThatThrownBy(() -> CorsService.builderForAnyOrigin().allowRequestMethods(HttpMethod.GET, null)) .isInstanceOf(NullPointerException.class); assertThatThrownBy( () -> CorsService.builderForAnyOrigin().preflightResponseHeader("header", null, null)) .isInstanceOf(NullPointerException.class); assertThatThrownBy(() -> CorsService.builderForAnyOrigin().preflightResponseHeader("header", Arrays .asList("11", null))).isInstanceOf(NullPointerException.class); assertThatThrownBy(() -> CorsService.builderForAnyOrigin().preflightResponseHeader("123")).isInstanceOf( IllegalArgumentException.class); assertThatThrownBy(() -> CorsService.builderForAnyOrigin().preflightResponseHeader("123", ImmutableList.of())); assertThatThrownBy(() -> CorsService.builderForAnyOrigin().exposeHeaders()).isInstanceOf( IllegalArgumentException.class); assertThatThrownBy(() -> CorsService.builderForAnyOrigin().allowRequestMethods()).isInstanceOf( IllegalArgumentException.class); assertThatThrownBy(() -> CorsService.builderForAnyOrigin().allowRequestHeaders()).isInstanceOf( IllegalArgumentException.class); // Ensure double decoration is prohibited. assertThatThrownBy(() -> { final Function<? super HttpService, CorsService> decorator = CorsService.builderForAnyOrigin().newDecorator(); final HttpService service = (ctx, req) -> HttpResponse.of("OK"); service.decorate(decorator).decorate(decorator); }).isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("decorated with a CorsService already"); }
Example #15
Source File: NonExistentHttpFile.java From armeria with Apache License 2.0 | 5 votes |
@Override public HttpService asService() { return (ctx, req) -> { switch (req.method()) { case HEAD: case GET: return HttpResponse.of(HttpStatus.NOT_FOUND); default: return HttpResponse.of(HttpStatus.METHOD_NOT_ALLOWED); } }; }
Example #16
Source File: AnnotatedServiceElement.java From armeria with Apache License 2.0 | 5 votes |
AnnotatedServiceElement(Route route, AnnotatedService service, Function<? super HttpService, ? extends HttpService> decorator) { this.route = requireNonNull(route, "route"); this.service = requireNonNull(service, "service"); this.decorator = requireNonNull(decorator, "decorator"); }
Example #17
Source File: ServerModule.java From curiostack with MIT License | 5 votes |
private static HttpService internalService( HttpService service, Optional<Function<HttpService, IpFilteringService>> ipFilter, ServerConfig config) { if (!ipFilter.isPresent() || !config.getIpFilterInternalOnly()) { return service; } return service.decorate(ipFilter.get()); }
Example #18
Source File: CachingHttpFile.java From armeria with Apache License 2.0 | 5 votes |
@Override public HttpService asService() { return (ctx, req) -> { try { return getFile(ctx.blockingTaskExecutor()).asService().serve(ctx, req); } catch (Exception e) { return Exceptions.throwUnsafely(e); } }; }
Example #19
Source File: ArmeriaConfigurationUtilTest.java From armeria with Apache License 2.0 | 5 votes |
@Test void makesSureDecoratedServiceIsAdded() { final Function<? super HttpService, ? extends HttpService> decorator = spy(new DecoratingFunction()); final AnnotatedServiceRegistrationBean bean = new AnnotatedServiceRegistrationBean() .setServiceName("test") .setService(new SimpleService()) .setDecorators(decorator); final ServerBuilder sb = Server.builder(); final DocServiceBuilder dsb = DocService.builder(); configureAnnotatedServices(sb, dsb, ImmutableList.of(bean), null, null); final Server s = sb.build(); verify(decorator, times(2)).apply(any()); assertThat(service(s).as(SimpleDecorator.class)).isNotNull(); }
Example #20
Source File: ArmeriaConfigurationUtilTest.java From armeria with Apache License 2.0 | 5 votes |
@Test void makesSureDecoratorsAreConfigured() { final Function<? super HttpService, ? extends HttpService> decorator = spy(new IdentityFunction()); final AnnotatedServiceRegistrationBean bean = new AnnotatedServiceRegistrationBean() .setServiceName("test") .setService(new SimpleService()) .setDecorators(decorator); final ServerBuilder sb1 = Server.builder(); final DocServiceBuilder dsb1 = DocService.builder(); configureAnnotatedServices(sb1, dsb1, ImmutableList.of(bean), MeterIdPrefixFunctionFactory.ofDefault(), null); final Server s1 = sb1.build(); verify(decorator, times(2)).apply(any()); assertThat(service(s1).as(MetricCollectingService.class)).isNotNull(); reset(decorator); final ServerBuilder sb2 = Server.builder(); final DocServiceBuilder dsb2 = DocService.builder(); configureAnnotatedServices(sb2, dsb2, ImmutableList.of(bean), null, null); final Server s2 = sb2.build(); verify(decorator, times(2)).apply(any()); assertThat(getServiceForHttpMethod(sb2.build(), HttpMethod.OPTIONS)) .isInstanceOf(AnnotatedService.class); }
Example #21
Source File: DefaultRequestLog.java From armeria with Apache License 2.0 | 5 votes |
private static String getInnermostServiceName(HttpService service) { Unwrappable unwrappable = service; while (true) { final Unwrappable delegate = unwrappable.unwrap(); if (delegate != unwrappable) { unwrappable = delegate; continue; } return delegate.getClass().getName(); } }
Example #22
Source File: ThriftServiceUtils.java From armeria with Apache License 2.0 | 5 votes |
/** * Retrieves thrift service names of {@code service} using reflection. */ static Set<String> serviceNames(HttpService service) { if (thriftServiceClass == null || entriesMethod == null || interfacesMethod == null) { return ImmutableSet.of(); } final Object thriftService = service.as(thriftServiceClass); if (thriftService == null) { return ImmutableSet.of(); } @SuppressWarnings("unchecked") final Map<String, ?> entries = (Map<String, ?>) invokeMethod(entriesMethod, thriftService); assert entries != null; return toServiceName(entries.values()); }
Example #23
Source File: ArmeriaConfigurationUtil.java From armeria with Apache License 2.0 | 5 votes |
/** * Adds Thrift services to the specified {@link ServerBuilder}. */ public static void configureThriftServices( ServerBuilder server, DocServiceBuilder docServiceBuilder, List<ThriftServiceRegistrationBean> beans, @Nullable MeterIdPrefixFunctionFactory meterIdPrefixFunctionFactory, @Nullable String docsPath) { requireNonNull(server, "server"); requireNonNull(docServiceBuilder, "docServiceBuilder"); requireNonNull(beans, "beans"); final List<TBase<?, ?>> docServiceRequests = new ArrayList<>(); final Map<String, Collection<? extends ExampleHeaders>> docServiceHeaders = new HashMap<>(); beans.forEach(bean -> { HttpService service = bean.getService(); for (Function<? super HttpService, ? extends HttpService> decorator : bean.getDecorators()) { service = service.decorate(decorator); } service = setupMetricCollectingService(service, bean, meterIdPrefixFunctionFactory); server.service(bean.getPath(), service); docServiceRequests.addAll(bean.getExampleRequests()); ThriftServiceUtils.serviceNames(bean.getService()) .forEach(serviceName -> docServiceHeaders.put(serviceName, bean.getExampleHeaders())); }); if (Strings.isNullOrEmpty(docsPath)) { return; } docServiceBuilder.exampleRequest(docServiceRequests); for (Entry<String, Collection<? extends ExampleHeaders>> entry : docServiceHeaders.entrySet()) { for (ExampleHeaders exampleHeaders : entry.getValue()) { configureExampleHeaders(docServiceBuilder, entry.getKey(), exampleHeaders.getMethodName(), exampleHeaders.getHeaders()); } } }
Example #24
Source File: ArmeriaConfigurationUtil.java From armeria with Apache License 2.0 | 5 votes |
private static HttpService setupMetricCollectingService( HttpService service, AbstractServiceRegistrationBean<?, ?, ?, ?> bean, @Nullable MeterIdPrefixFunctionFactory meterIdPrefixFunctionFactory) { requireNonNull(service, "service"); requireNonNull(bean, "bean"); if (meterIdPrefixFunctionFactory == null) { return service; } return service.decorate(metricCollectingServiceDecorator(bean, meterIdPrefixFunctionFactory)); }
Example #25
Source File: AnnotatedServiceElement.java From armeria with Apache License 2.0 | 5 votes |
/** * Builds a safe decorated {@link HttpService} by wrapping the localDecorator with * exceptionHandlingDecorators. * * @param localDecorator a decorator to decorate the service with. */ public HttpService buildSafeDecoratedService( Function<? super HttpService, ? extends HttpService> localDecorator) { // Apply decorators which are specified in the service class. HttpService decoratedService = decorator.apply(service); // Apply localDecorator passed in through method parameter decoratedService = decoratedService.decorate(localDecorator); // If there is a decorator, we should add one more decorator which handles an exception // raised from decorators. if (decoratedService != service) { decoratedService = service.exceptionHandlingDecorator().apply(decoratedService); } return decoratedService; }
Example #26
Source File: AnnotatedServiceAnnotationAliasTest.java From armeria with Apache License 2.0 | 4 votes |
@Override public HttpResponse serve( HttpService delegate, ServiceRequestContext ctx, HttpRequest req) throws Exception { appendAttribute(ctx, " (decorated-1)"); return delegate.serve(ctx, req); }
Example #27
Source File: SimpleCompositeServiceBuilder.java From armeria with Apache License 2.0 | 4 votes |
@Override public SimpleCompositeServiceBuilder serviceUnder(String pathPrefix, HttpService service) { return (SimpleCompositeServiceBuilder) super.serviceUnder(pathPrefix, service); }
Example #28
Source File: ContentPreviewingService.java From armeria with Apache License 2.0 | 4 votes |
/** * Creates a new {@link ContentPreviewingService} decorator with the specified * {@link ContentPreviewerFactory}. */ public static Function<? super HttpService, ContentPreviewingService> newDecorator( ContentPreviewerFactory contentPreviewerFactory) { requireNonNull(contentPreviewerFactory, "contentPreviewerFactory"); return delegate -> new ContentPreviewingService(delegate, contentPreviewerFactory); }
Example #29
Source File: AuthServiceBuilder.java From armeria with Apache License 2.0 | 4 votes |
/** * Returns a newly-created {@link AuthService} based on the {@link Authorizer}s added to this builder. */ public AuthService build(HttpService delegate) { return new AuthService(requireNonNull(delegate, "delegate"), authorizer(), successHandler, failureHandler); }
Example #30
Source File: AuthServiceBuilder.java From armeria with Apache License 2.0 | 4 votes |
/** * Returns a newly-created decorator that decorates an {@link HttpService} with a new * {@link AuthService} based on the {@link Authorizer}s added to this builder. */ public Function<? super HttpService, AuthService> newDecorator() { final Authorizer<HttpRequest> authorizer = authorizer(); return delegate -> build(delegate, authorizer); }