Java Code Examples for com.linecorp.armeria.server.ServerBuilder#decorator()

The following examples show how to use com.linecorp.armeria.server.ServerBuilder#decorator() . 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: CentralDogma.java    From centraldogma with Apache License 2.0 7 votes vote down vote up
private void configureMetrics(ServerBuilder sb, PrometheusMeterRegistry registry) {
    sb.meterRegistry(registry);
    sb.service(METRICS_PATH, new PrometheusExpositionService(registry.getPrometheusRegistry()));
    sb.decorator(MetricCollectingService.newDecorator(MeterIdPrefixFunction.ofDefault("api")));

    // Bind system metrics.
    new FileDescriptorMetrics().bindTo(registry);
    new ProcessorMetrics().bindTo(registry);
    new ClassLoaderMetrics().bindTo(registry);
    new UptimeMetrics().bindTo(registry);
    new DiskSpaceMetrics(cfg.dataDir()).bindTo(registry);
    new JvmGcMetrics().bindTo(registry);
    new JvmMemoryMetrics().bindTo(registry);
    new JvmThreadMetrics().bindTo(registry);

    // Bind global thread pool metrics.
    ExecutorServiceMetrics.monitor(registry, ForkJoinPool.commonPool(), "commonPool");
}
 
Example 2
Source File: HttpServiceLogNameTest.java    From armeria with Apache License 2.0 6 votes vote down vote up
@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 3
Source File: AnnotatedServiceRequestLogNameTest.java    From armeria with Apache License 2.0 6 votes vote down vote up
@Override
protected void configure(ServerBuilder sb) throws Exception {
    sb.annotatedService(new FooService());
    sb.annotatedService("/serviceName", new BarService());
    sb.annotatedService("/decorated", new BarService(), service -> {
        return service.decorate((delegate, ctx, req) -> {
            ctx.logBuilder().name("DecoratedService", ctx.method().name());
            return delegate.serve(ctx, req);
        });
    });

    sb.decorator((delegate, ctx, req) -> {
        logs.add(ctx.log());
        return delegate.serve(ctx, req);
    });

    // The annotated service will not be invoked at all for '/fail_early'.
    sb.routeDecorator().path("/fail_early")
      .build((delegate, ctx, req) -> {
          throw HttpStatusException.of(500);
      });
}
 
Example 4
Source File: ArmeriaConfigurationUtil.java    From armeria with Apache License 2.0 5 votes vote down vote up
private static void configureCompression(ServerBuilder serverBuilder, Compression compression) {
    if (compression.isEnabled()) {
        final int minBytesToForceChunkedAndEncoding;
        final String minResponseSize = compression.getMinResponseSize();
        if (minResponseSize == null) {
            minBytesToForceChunkedAndEncoding = DEFAULT_MIN_BYTES_TO_FORCE_CHUNKED_AND_ENCODING;
        } else {
            minBytesToForceChunkedAndEncoding = Ints.saturatedCast(parseDataSize(minResponseSize));
        }
        serverBuilder.decorator(contentEncodingDecorator(compression.getMimeTypes(),
                                                         compression.getExcludedUserAgents(),
                                                         minBytesToForceChunkedAndEncoding));
    }
}
 
Example 5
Source File: GrpcServiceLogNameTest.java    From armeria with Apache License 2.0 5 votes vote down vote up
@Override
protected void configure(ServerBuilder sb) throws Exception {
    sb.accessLogWriter(AccessLogWriter.combined(), true);
    sb.service(GrpcService.builder()
                          .addService(new TestServiceImpl(Executors.newSingleThreadScheduledExecutor()))
                          .build());
    sb.decorator((delegate, ctx, req) -> {
        capturedCtx = ctx;
        return delegate.serve(ctx, req);
    });
}
 
Example 6
Source File: ClientAuthIntegrationTest.java    From armeria with Apache License 2.0 5 votes vote down vote up
@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 7
Source File: ContentPreviewingClientTest.java    From armeria with Apache License 2.0 5 votes vote down vote up
@Override
protected void configure(ServerBuilder sb) throws Exception {
    sb.service("/", (ctx, req) -> HttpResponse.from(
            req.aggregate()
               .thenApply(aggregated -> {
                   final ResponseHeaders responseHeaders =
                           ResponseHeaders.of(HttpStatus.OK,
                                              HttpHeaderNames.CONTENT_TYPE, MediaType.PLAIN_TEXT_UTF_8);
                   return HttpResponse.of(responseHeaders,
                                          HttpData.ofUtf8("Hello " + aggregated.contentUtf8() + '!'));
               })));
    sb.decorator(EncodingService.builder()
                                .minBytesToForceChunkedEncoding(1)
                                .newDecorator());
}
 
Example 8
Source File: RetryingClientAuthorityHeaderTest.java    From armeria with Apache License 2.0 5 votes vote down vote up
@Override
protected void configure(ServerBuilder sb) throws Exception {
    sb.service("/", new AbstractHttpService() {

        @Override
        protected HttpResponse doGet(ServiceRequestContext ctx, HttpRequest req) throws Exception {
            return HttpResponse.of(SERVICE_UNAVAILABLE);
        }
    });
    sb.decorator(LoggingService.newDecorator());
}
 
Example 9
Source File: RetryingClientAuthorityHeaderTest.java    From armeria with Apache License 2.0 5 votes vote down vote up
@Override
protected void configure(ServerBuilder sb) throws Exception {
    sb.service("/", new AbstractHttpService() {

        @Override
        protected HttpResponse doGet(ServiceRequestContext ctx, HttpRequest req) throws Exception {
            return HttpResponse.of(req.headers().authority());
        }
    });
    sb.decorator(LoggingService.newDecorator());
}
 
Example 10
Source File: ContentPreviewingServiceTest.java    From armeria with Apache License 2.0 5 votes vote down vote up
@Override
protected void configure(ServerBuilder sb) throws Exception {
    final HttpService httpService = (ctx, req) -> HttpResponse.from(
            req.aggregate()
               .thenApply(aggregated -> {
                   final ResponseHeaders responseHeaders =
                           ResponseHeaders.of(HttpStatus.OK,
                                              HttpHeaderNames.CONTENT_TYPE, MediaType.PLAIN_TEXT_UTF_8);
                   return HttpResponse.of(responseHeaders,
                                          HttpData.ofUtf8("Hello " + aggregated.contentUtf8() + '!'));
               }));
    sb.decorator("/beforeEncoding", EncodingService.builder()
                                                   .minBytesToForceChunkedEncoding(1)
                                                   .newDecorator());
    sb.decorator("/beforeEncoding", ContentPreviewingService.newDecorator(100));
    sb.service("/beforeEncoding", httpService);

    sb.decorator("/encoded", decodingContentPreviewDecorator());
    sb.decorator("/encoded", EncodingService.builder()
                                            .minBytesToForceChunkedEncoding(1)
                                            .newDecorator());
    sb.service("/encoded", httpService);

    sb.decoratorUnder("/", (delegate, ctx, req) -> {
        contextCaptor.set(ctx);
        return delegate.serve(ctx, req);
    });
}
 
Example 11
Source File: ContentPreviewerTest.java    From armeria with Apache License 2.0 5 votes vote down vote up
void build(ServerBuilder sb) {
    sb.decorator(ContentPreviewingService.newDecorator(contentPreviewerFactory(10)));
    sb.decorator(delegate -> (ctx, req) -> {
        if (waitingFuture != null) {
            ctx.log().whenComplete().thenAccept(waitingFuture::complete);
        }
        return delegate.serve(ctx, req);
    });
    sb.annotatedService("/example", new Object() {
        @Get("/get")
        public String get() {
            return "test";
        }

        @Get("/get-unicode")
        public HttpResponse getUnicode() {
            return HttpResponse.of(MediaType.ANY_TEXT_TYPE, "안녕");
        }

        @Get("/get-audio")
        public HttpResponse getBinary() {
            return HttpResponse.of(HttpStatus.OK, MediaType.BASIC_AUDIO, new byte[] { 1, 2, 3, 4 });
        }

        @Get("/get-json")
        public HttpResponse getJson() {
            return HttpResponse.of(MediaType.JSON, "{\"value\":1}");
        }

        @Get("/get-longstring")
        public String getLongString() {
            return Strings.repeat("a", 10000);
        }

        @Post("/post")
        public String post(String requestContent) {
            return "abcdefghijkmnopqrstu";
        }
    });
}
 
Example 12
Source File: ArmeriaReactiveWebServerFactory.java    From armeria with Apache License 2.0 4 votes vote down vote up
private void configureArmeriaService(ServerBuilder sb, ArmeriaSettings settings) {
    final MeterIdPrefixFunctionFactory meterIdPrefixFunctionFactory =
            settings.isEnableMetrics() ? firstNonNull(findBean(MeterIdPrefixFunctionFactory.class),
                                                      MeterIdPrefixFunctionFactory.ofDefault())
                                       : null;

    configurePorts(sb, settings.getPorts());
    final DocServiceBuilder docServiceBuilder = DocService.builder();
    configureThriftServices(sb,
                            docServiceBuilder,
                            findBeans(ThriftServiceRegistrationBean.class),
                            meterIdPrefixFunctionFactory,
                            settings.getDocsPath());
    configureGrpcServices(sb,
                          docServiceBuilder,
                          findBeans(GrpcServiceRegistrationBean.class),
                          meterIdPrefixFunctionFactory,
                          settings.getDocsPath());
    configureHttpServices(sb,
                          findBeans(HttpServiceRegistrationBean.class),
                          meterIdPrefixFunctionFactory);
    configureAnnotatedServices(sb,
                               docServiceBuilder,
                               findBeans(AnnotatedServiceRegistrationBean.class),
                               meterIdPrefixFunctionFactory,
                               settings.getDocsPath());
    configureServerWithArmeriaSettings(sb, settings,
                                       firstNonNull(findBean(MeterRegistry.class), Metrics.globalRegistry),
                                       findBeans(HealthChecker.class));
    if (settings.getSsl() != null) {
        configureTls(sb, settings.getSsl());
    }

    final ArmeriaSettings.Compression compression = settings.getCompression();
    if (compression != null && compression.isEnabled()) {
        final long parsed = parseDataSize(compression.getMinResponseSize());
        sb.decorator(contentEncodingDecorator(compression.getMimeTypes(),
                                              compression.getExcludedUserAgents(),
                                              Ints.saturatedCast(parsed)));
    }

    if (!Strings.isNullOrEmpty(settings.getDocsPath())) {
        sb.serviceUnder(settings.getDocsPath(), docServiceBuilder.build());
    }
}
 
Example 13
Source File: ArmeriaConfigurationUtil.java    From armeria with Apache License 2.0 4 votes vote down vote up
/**
 * Sets graceful shutdown timeout, health check services and {@link MeterRegistry} for the specified
 * {@link ServerBuilder}.
 */
public static void configureServerWithArmeriaSettings(ServerBuilder server, ArmeriaSettings settings,
                                                      MeterRegistry meterRegistry,
                                                      List<HealthChecker> healthCheckers) {
    requireNonNull(server, "server");
    requireNonNull(settings, "settings");
    requireNonNull(meterRegistry, "meterRegistry");
    requireNonNull(healthCheckers, "healthCheckers");

    if (settings.getGracefulShutdownQuietPeriodMillis() >= 0 &&
        settings.getGracefulShutdownTimeoutMillis() >= 0) {
        server.gracefulShutdownTimeoutMillis(settings.getGracefulShutdownQuietPeriodMillis(),
                                             settings.getGracefulShutdownTimeoutMillis());
        logger.debug("Set graceful shutdown timeout: quiet period {} ms, timeout {} ms",
                     settings.getGracefulShutdownQuietPeriodMillis(),
                     settings.getGracefulShutdownTimeoutMillis());
    }

    final String healthCheckPath = settings.getHealthCheckPath();
    if (!Strings.isNullOrEmpty(healthCheckPath)) {
        server.service(healthCheckPath, HealthCheckService.of(healthCheckers));
    }

    server.meterRegistry(meterRegistry);

    if (settings.isEnableMetrics() && !Strings.isNullOrEmpty(settings.getMetricsPath())) {
        final boolean hasPrometheus = hasAllClasses(
                "io.micrometer.prometheus.PrometheusMeterRegistry",
                "io.prometheus.client.CollectorRegistry");

        final boolean addedPrometheusExposition;
        if (hasPrometheus) {
            addedPrometheusExposition = PrometheusSupport.addExposition(settings, server, meterRegistry);
        } else {
            addedPrometheusExposition = false;
        }

        if (!addedPrometheusExposition) {
            final boolean hasDropwizard = hasAllClasses(
                    "io.micrometer.core.instrument.dropwizard.DropwizardMeterRegistry",
                    "com.codahale.metrics.MetricRegistry",
                    "com.codahale.metrics.json.MetricsModule");
            if (hasDropwizard) {
                DropwizardSupport.addExposition(settings, server, meterRegistry);
            }
        }
    }

    if (settings.getSsl() != null) {
        configureTls(server, settings.getSsl());
    }

    final ArmeriaSettings.Compression compression = settings.getCompression();
    if (compression != null && compression.isEnabled()) {
        final int minBytesToForceChunkedAndEncoding =
                Ints.saturatedCast(parseDataSize(compression.getMinResponseSize()));
        server.decorator(contentEncodingDecorator(compression.getMimeTypes(),
                                                  compression.getExcludedUserAgents(),
                                                  minBytesToForceChunkedAndEncoding));
    }
}
 
Example 14
Source File: BraveServiceIntegrationTest.java    From armeria with Apache License 2.0 4 votes vote down vote up
@Override
protected void init() {
    final ServerBuilder sb = Server.builder();
    sb.service("/", (ctx, req) -> {
        if (req.method() == HttpMethod.OPTIONS) {
            return HttpResponse.of(OK, MediaType.PLAIN_TEXT_UTF_8, "");
        }
        return HttpResponse.of(HttpStatus.NOT_FOUND);
    });
    sb.service("/foo", (ctx, req) -> HttpResponse.of(OK, MediaType.PLAIN_TEXT_UTF_8, "bar"));
    sb.service("/async", (ctx, req) -> asyncResponse(future -> {
        future.complete(HttpResponse.of(OK, MediaType.PLAIN_TEXT_UTF_8, "bar"));
    }));

    sb.service("/exception", (ctx, req) -> {
        throw new IllegalStateException("not ready");
    });
    sb.service("/exceptionAsync", (ctx, req) -> asyncResponse(future -> {
        future.completeExceptionally(new IllegalStateException("not ready"));
    }));
    sb.service("/badrequest", (ctx, req) -> HttpResponse.of(BAD_REQUEST));

    sb.service("/items/:itemId",
               (ctx, req) -> HttpResponse.of(OK, MediaType.PLAIN_TEXT_UTF_8,
                                             String.valueOf(ctx.pathParam("itemId"))));
    sb.service("/async_items/:itemId", (ctx, req) -> asyncResponse(future -> {
        future.complete(HttpResponse.of(OK, MediaType.PLAIN_TEXT_UTF_8,
                                        String.valueOf(ctx.pathParam("itemId"))));
    }));
    // "/nested" left out as there's no sub-routing feature at the moment.

    sb.service("/child", (ctx, req) -> {
        tracing.tracer().nextSpan().name("child").start().finish();
        return HttpResponse.of(OK, MediaType.PLAIN_TEXT_UTF_8, "happy");
    });
    sb.service("/baggage", (ctx, req) -> {
        final String value = String.valueOf(BAGGAGE_FIELD.getValue());
        return HttpResponse.of(OK, MediaType.PLAIN_TEXT_UTF_8, value);
    });

    sb.service("/badrequest", (ctx, req) -> HttpResponse.of(BAD_REQUEST));

    sb.decorator(BraveService.newDecorator(httpTracing));

    server = sb.build();
    server.start().join();
}
 
Example 15
Source File: AbstractPooledHttpServiceTest.java    From armeria with Apache License 2.0 4 votes vote down vote up
@Override
protected void configure(ServerBuilder sb) {
    sb.service("/implemented", IMPLEMENTED);
    sb.service("/not-implemented", new AbstractHttpService() {});
    sb.decorator(LoggingService.builder().newDecorator());
}
 
Example 16
Source File: FileServiceTest.java    From armeria with Apache License 2.0 4 votes vote down vote up
@Override
protected void configure(ServerBuilder sb) {

    final ClassLoader classLoader = getClass().getClassLoader();

    sb.serviceUnder(
            "/cached/fs/",
            FileService.builder(tmpDir)
                       .autoIndex(true)
                       .build());

    sb.serviceUnder(
            "/uncached/fs/",
            FileService.builder(tmpDir)
                       .maxCacheEntries(0)
                       .autoIndex(true)
                       .build());

    sb.serviceUnder(
            "/cached/compressed/",
            FileService.builder(classLoader, baseResourceDir + "foo")
                       .serveCompressedFiles(true)
                       .build());
    sb.serviceUnder(
            "/uncached/compressed/",
            FileService.builder(classLoader, baseResourceDir + "foo")
                       .serveCompressedFiles(true)
                       .maxCacheEntries(0)
                       .build());

    sb.serviceUnder(
            "/cached/classes/",
            FileService.of(classLoader, "/"));
    sb.serviceUnder(
            "/uncached/classes/",
            FileService.builder(classLoader, "/")
                       .maxCacheEntries(0)
                       .build());

    sb.serviceUnder(
            "/cached/by-entry/classes/",
            FileService.builder(classLoader, "/")
                       .entryCacheSpec("maximumSize=512")
                       .build());
    sb.serviceUnder(
            "/uncached/by-entry/classes/",
            FileService.builder(classLoader, "/")
                       .entryCacheSpec("off")
                       .build());

    sb.serviceUnder(
            "/cached/",
            FileService.of(classLoader, baseResourceDir + "foo")
                       .orElse(FileService.of(classLoader, baseResourceDir + "bar")));
    sb.serviceUnder(
            "/uncached/",
            FileService.builder(classLoader, baseResourceDir + "foo")
                       .maxCacheEntries(0)
                       .build()
                       .orElse(FileService.builder(classLoader, baseResourceDir + "bar")
                                          .maxCacheEntries(0)
                                          .build()));

    sb.decorator(LoggingService.newDecorator());
}