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

The following examples show how to use com.linecorp.armeria.server.ServerBuilder#serviceUnder() . 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: ArmeriaGrpcServerInteropTest.java    From armeria with Apache License 2.0 6 votes vote down vote up
@Override
protected void configure(ServerBuilder sb) throws Exception {
    sb.https(new InetSocketAddress("127.0.0.1", 0));
    sb.tls(ssc.certificateFile(), ssc.privateKeyFile());
    sb.tlsCustomizer(ssl -> {
        try {
            ssl.trustManager(TestUtils.loadCert("ca.pem"));
        } catch (IOException e) {
            Exceptions.throwUnsafely(e);
        }
    });
    sb.maxRequestLength(16 * 1024 * 1024);
    sb.serviceUnder("/", grpcService.decorate((delegate, ctx, req) -> {
        ctxCapture.set(ctx);
        return delegate.serve(ctx, req);
    }));
}
 
Example 2
Source File: GrpcServiceServerTest.java    From armeria with Apache License 2.0 6 votes vote down vote up
@Override
protected void configure(ServerBuilder sb) throws Exception {
    sb.workerGroup(EventLoopGroups.newEventLoopGroup(1), true);
    sb.maxRequestLength(0);

    sb.serviceUnder("/",
                    GrpcService.builder()
                               .setMaxInboundMessageSizeBytes(MAX_MESSAGE_SIZE)
                               .addService(ServerInterceptors.intercept(
                                       new UnitTestServiceImpl(),
                                       REPLACE_EXCEPTION, ADD_TO_CONTEXT))
                               .enableUnframedRequests(true)
                               .supportedSerializationFormats(
                                       GrpcSerializationFormats.values())
                               .useBlockingTaskExecutor(true)
                               .build()
                               .decorate(LoggingService.newDecorator())
                               .decorate((delegate, ctx, req) -> {
                                   ctx.log().whenComplete().thenAccept(requestLogQueue::add);
                                   return delegate.serve(ctx, req);
                               }));
}
 
Example 3
Source File: GrpcServiceServerTest.java    From armeria with Apache License 2.0 5 votes vote down vote up
@Override
protected void configure(ServerBuilder sb) throws Exception {
    sb.workerGroup(EventLoopGroups.newEventLoopGroup(1), true);
    sb.maxRequestLength(0);

    sb.serviceUnder("/",
                    GrpcService.builder()
                               .addService(new UnitTestServiceImpl())
                               .build()
                               .decorate(LoggingService.newDecorator())
                               .decorate((delegate, ctx, req) -> {
                                   ctx.log().whenComplete().thenAccept(requestLogQueue::add);
                                   return delegate.serve(ctx, req);
                               }));
}
 
Example 4
Source File: UnmanagedJettyServiceTest.java    From armeria with Apache License 2.0 5 votes vote down vote up
@Override
protected void configure(ServerBuilder sb) throws Exception {
    sb.http(0);
    sb.https(0);
    sb.tlsSelfSigned();

    jetty = new Server(0);
    jetty.setHandler(JettyServiceTest.newWebAppContext());
    jetty.start();
    sb.serviceUnder(
            "/jsp/",
            JettyService.of(jetty).decorate(LoggingService.newDecorator()));
}
 
Example 5
Source File: JettyServiceStartupTest.java    From armeria with Apache License 2.0 5 votes vote down vote up
@Override
protected void configure(ServerBuilder sb) throws Exception {
    sb.http(0);
    sb.https(0);
    sb.tlsSelfSigned();

    sb.serviceUnder(
            "/jsp/",
            JettyService.builder()
                        .handler(newWebAppContext())
                        .configurator(s -> jettyBeans.addAll(s.getBeans()))
                        .build()
                        .decorate(LoggingService.newDecorator()));

    sb.serviceUnder(
            "/default/",
            JettyService.builder()
                        .handler(new DefaultHandler())
                        .build());

    final ResourceHandler resourceHandler = new ResourceHandler();
    resourceHandler.setResourceBase(WebAppContainerTest.webAppRoot().getPath());
    sb.serviceUnder(
            "/resources/",
            JettyService.builder()
                        .handler(resourceHandler)
                        .build());
}
 
Example 6
Source File: JettyServiceTest.java    From armeria with Apache License 2.0 5 votes vote down vote up
@Override
protected void configure(ServerBuilder sb) throws Exception {
    sb.http(0);
    sb.https(0);
    sb.tlsSelfSigned();

    sb.serviceUnder(
            "/jsp/",
            JettyService.builder()
                        .handler(newWebAppContext())
                        .configurator(s -> jettyBeans.addAll(s.getBeans()))
                        .build()
                        .decorate(LoggingService.newDecorator()));

    sb.serviceUnder(
            "/default/",
            JettyService.builder()
                        .handler(new DefaultHandler())
                        .build());

    final ResourceHandler resourceHandler = new ResourceHandler();
    resourceHandler.setResourceBase(webAppRoot().getPath());
    sb.serviceUnder(
            "/resources/",
            JettyService.builder()
                        .handler(resourceHandler)
                        .build());
}
 
Example 7
Source File: GrpcFlowControlTest.java    From armeria with Apache License 2.0 5 votes vote down vote up
@Override
protected void configure(ServerBuilder sb) throws Exception {
    sb.maxRequestLength(0);
    sb.requestTimeoutMillis(0);

    sb.serviceUnder("/",
                    GrpcService.builder()
                               .addService(new FlowControlService())
                               .setMaxInboundMessageSizeBytes(Integer.MAX_VALUE)
                               .build());
}
 
Example 8
Source File: GrpcStatusCauseTest.java    From armeria with Apache License 2.0 5 votes vote down vote up
@Override
protected void configure(ServerBuilder sb) throws Exception {
    sb.serviceUnder("/",
                    GrpcService.builder()
                               .addService(new TestServiceImpl())
                               .build());
}
 
Example 9
Source File: GrpcDocServiceTest.java    From armeria with Apache License 2.0 5 votes vote down vote up
@Override
protected void configure(ServerBuilder sb) throws Exception {
    if (TestUtil.isDocServiceDemoMode()) {
        sb.http(8080);
    }
    sb.serviceUnder("/test",
                    GrpcService.builder()
                               .addService(new TestService())
                               .supportedSerializationFormats(GrpcSerializationFormats.values())
                               .enableUnframedRequests(true)
                               .build());
    sb.serviceUnder("/docs/",
                    DocService.builder()
                              .exampleRequestForMethod(
                                    TestServiceGrpc.SERVICE_NAME,
                                    "UnaryCall",
                                    SimpleRequest.newBuilder()
                                                 .setPayload(
                                                     Payload.newBuilder()
                                                            .setBody(ByteString.copyFromUtf8("world")))
                                                 .build())
                              .injectedScript(INJECTED_HEADER_PROVIDER1, INJECTED_HEADER_PROVIDER2)
                              .injectedScriptSupplier((ctx, req) -> INJECTED_HEADER_PROVIDER3)
                              .exclude(DocServiceFilter.ofMethodName(
                                                TestServiceGrpc.SERVICE_NAME,
                                                "EmptyCall"))
                              .build()
                              .decorate(LoggingService.newDecorator()));
    sb.serviceUnder("/excludeAll/",
                    DocService.builder()
                              .exclude(DocServiceFilter.ofGrpc())
                              .build());
    sb.serviceUnder("/",
                    GrpcService.builder()
                               .addService(mock(ReconnectServiceImplBase.class))
                               .build());
}
 
Example 10
Source File: CompositeServiceTest.java    From armeria with Apache License 2.0 5 votes vote down vote up
@Override
protected void configure(ServerBuilder sb) throws Exception {
    sb.meterRegistry(PrometheusMeterRegistries.newRegistry());
    sb.serviceUnder("/qux/", composite);

    // Should not hit the following services
    sb.serviceUnder("/foo/", otherService);
    sb.serviceUnder("/bar/", otherService);
    sb.service(Route.builder().glob("/*").build(), otherService);
}
 
Example 11
Source File: ManagedTomcatServiceTest.java    From armeria with Apache License 2.0 5 votes vote down vote up
@Override
protected void configure(ServerBuilder sb) throws Exception {
    sb.http(0);
    sb.https(0);
    sb.tlsSelfSigned();

    sb.serviceUnder(
            "/jsp/",
            TomcatService.builder(webAppRoot())
                         .serviceName(SERVICE_NAME)
                         .configurator(s -> Collections.addAll(tomcatServices, s.findServices()))
                         .build()
                         .decorate(LoggingService.newDecorator()));

    sb.serviceUnder(
            "/jar/",
            TomcatService.builder(AppRootFinder.find(Future.class))
                         .serviceName("TomcatServiceTest-JAR")
                         .build()
                         .decorate(LoggingService.newDecorator()));

    sb.serviceUnder(
            "/jar_altroot/",
            TomcatService.builder(AppRootFinder.find(Future.class), "/io/netty/util/concurrent")
                         .serviceName("TomcatServiceTest-JAR-AltRoot")
                         .build()
                         .decorate(LoggingService.newDecorator()));
}
 
Example 12
Source File: MockWebServerExtension.java    From armeria with Apache License 2.0 5 votes vote down vote up
@Override
protected final void configure(ServerBuilder sb) throws Exception {
    sb.http(0);
    sb.https(0);
    sb.tlsSelfSigned();

    sb.serviceUnder("/", new MockWebService());

    configureServer(sb);
}
 
Example 13
Source File: AWSSignatureVersion4Test.java    From zipkin-aws with Apache License 2.0 5 votes vote down vote up
@Override protected void configure(ServerBuilder sb) {
  sb.serviceUnder("/", (ctx, req) -> HttpResponse.from(
      req.aggregate().thenApply(agg -> {
        CAPTURED_REQUEST.set(agg);
        return MOCK_RESPONSE.get().toHttpResponse();
      })));
}
 
Example 14
Source File: ElasticsearchDomainEndpointTest.java    From zipkin-aws with Apache License 2.0 5 votes vote down vote up
@Override protected void configure(ServerBuilder sb) {
  sb.serviceUnder("/", (ctx, req) -> HttpResponse.from(
      req.aggregate().thenApply(agg -> {
        CAPTURED_REQUEST.set(agg);
        return MOCK_RESPONSE.get().toHttpResponse();
      })));
}
 
Example 15
Source File: CentralDogma.java    From centraldogma with Apache License 2.0 4 votes vote down vote up
private Server startServer(ProjectManager pm, CommandExecutor executor,
                           PrometheusMeterRegistry meterRegistry, @Nullable SessionManager sessionManager) {
    final ServerBuilder sb = Server.builder();
    sb.verboseResponses(true);
    cfg.ports().forEach(sb::port);

    if (cfg.ports().stream().anyMatch(ServerPort::hasTls)) {
        try {
            final TlsConfig tlsConfig = cfg.tls();
            if (tlsConfig != null) {
                sb.tls(tlsConfig.keyCertChainFile(), tlsConfig.keyFile(), tlsConfig.keyPassword());
            } else {
                logger.warn(
                        "Missing TLS configuration. Generating a self-signed certificate for TLS support.");
                sb.tlsSelfSigned();
            }
        } catch (Exception e) {
            Exceptions.throwUnsafely(e);
        }
    }

    sb.clientAddressSources(cfg.clientAddressSourceList());
    sb.clientAddressTrustedProxyFilter(cfg.trustedProxyAddressPredicate());

    cfg.numWorkers().ifPresent(
            numWorkers -> sb.workerGroup(EventLoopGroups.newEventLoopGroup(numWorkers), true));
    cfg.maxNumConnections().ifPresent(sb::maxNumConnections);
    cfg.idleTimeoutMillis().ifPresent(sb::idleTimeoutMillis);
    cfg.requestTimeoutMillis().ifPresent(sb::requestTimeoutMillis);
    cfg.maxFrameLength().ifPresent(sb::maxRequestLength);
    cfg.gracefulShutdownTimeout().ifPresent(
            t -> sb.gracefulShutdownTimeoutMillis(t.quietPeriodMillis(), t.timeoutMillis()));

    final MetadataService mds = new MetadataService(pm, executor);
    final WatchService watchService = new WatchService(meterRegistry);
    final AuthProvider authProvider = createAuthProvider(executor, sessionManager, mds);

    configureThriftService(sb, pm, executor, watchService, mds);

    sb.service("/title", webAppTitleFile(cfg.webAppTitle(), SystemInfo.hostname()).asService());

    sb.service(HEALTH_CHECK_PATH, HealthCheckService.of());

    // TODO(hyangtack): This service is temporarily added to support redirection from '/docs' to '/docs/'.
    //                  It would be removed if this kind of redirection is handled by Armeria.
    sb.service("/docs", new AbstractHttpService() {
        @Override
        protected HttpResponse doGet(ServiceRequestContext ctx, HttpRequest req)
                throws Exception {
            return HttpResponse.of(
                    ResponseHeaders.of(HttpStatus.TEMPORARY_REDIRECT, HttpHeaderNames.LOCATION, "/docs/"));
        }
    });
    sb.serviceUnder("/docs/",
                    DocService.builder()
                              .exampleHttpHeaders(CentralDogmaService.class,
                                                  HttpHeaders.of(HttpHeaderNames.AUTHORIZATION,
                                                                 "Bearer " + CsrfToken.ANONYMOUS))
                              .build());

    configureHttpApi(sb, pm, executor, watchService, mds, authProvider, sessionManager);

    configureMetrics(sb, meterRegistry);

    // Configure access log format.
    final String accessLogFormat = cfg.accessLogFormat();
    if (isNullOrEmpty(accessLogFormat)) {
        sb.accessLogWriter(AccessLogWriter.disabled(), true);
    } else if ("common".equals(accessLogFormat)) {
        sb.accessLogWriter(AccessLogWriter.common(), true);
    } else if ("combined".equals(accessLogFormat)) {
        sb.accessLogWriter(AccessLogWriter.combined(), true);
    } else {
        sb.accessLogFormat(accessLogFormat);
    }

    final Server s = sb.build();
    s.start().join();
    return s;
}
 
Example 16
Source File: GrpcServiceServerTest.java    From armeria with Apache License 2.0 4 votes vote down vote up
@Override
protected void configure(ServerBuilder sb) throws Exception {
    sb.workerGroup(EventLoopGroups.newEventLoopGroup(1), true);
    sb.maxRequestLength(0);

    sb.service(
            GrpcService.builder()
                       .setMaxInboundMessageSizeBytes(MAX_MESSAGE_SIZE)
                       .addService(ServerInterceptors.intercept(
                               new UnitTestServiceImpl(),
                               REPLACE_EXCEPTION, ADD_TO_CONTEXT))
                       .enableUnframedRequests(true)
                       .supportedSerializationFormats(GrpcSerializationFormats.values())
                       .build(),
            service -> service
                    .decorate(LoggingService.newDecorator())
                    .decorate((delegate, ctx, req) -> {
                        ctx.log().whenComplete().thenAccept(requestLogQueue::add);
                        return delegate.serve(ctx, req);
                    }));

    // For simplicity, mount onto subpaths with custom options
    sb.serviceUnder(
            "/json-preserving/",
            GrpcService.builder()
                       .addService(new UnitTestServiceImpl())
                       .supportedSerializationFormats(GrpcSerializationFormats.values())
                       .jsonMarshallerFactory(serviceDescriptor -> {
                           return GrpcJsonMarshaller.builder()
                                                    .jsonMarshallerCustomizer(marshaller -> {
                                                        marshaller.preservingProtoFieldNames(true);
                                                    })
                                                    .build(serviceDescriptor);
                       })
                       .build());
    sb.serviceUnder(
            "/no-client-timeout/",
            GrpcService.builder()
                       .addService(new UnitTestServiceImpl())
                       .useClientTimeoutHeader(false)
                       .build());

    sb.service(
            GrpcService.builder()
                       .addService(ProtoReflectionService.newInstance())
                       .build(),
            service -> service.decorate(LoggingService.newDecorator()));
}
 
Example 17
Source File: GrpcClientTest.java    From armeria with Apache License 2.0 4 votes vote down vote up
@Override
protected void configure(ServerBuilder sb) {
    sb.workerGroup(EventLoopGroups.newEventLoopGroup(1), true);
    sb.maxRequestLength(MAX_MESSAGE_SIZE);
    sb.idleTimeoutMillis(0);
    sb.http(0);
    sb.https(0);
    sb.tlsSelfSigned();

    final ServerServiceDefinition interceptService =
            ServerInterceptors.intercept(
                    new TestServiceImpl(Executors.newSingleThreadScheduledExecutor()),
                    new ServerInterceptor() {
                        @Override
                        public <REQ, RESP> Listener<REQ> interceptCall(
                                ServerCall<REQ, RESP> call,
                                Metadata requestHeaders,
                                ServerCallHandler<REQ, RESP> next) {
                            final HttpHeadersBuilder fromClient = HttpHeaders.builder();
                            MetadataUtil.fillHeaders(requestHeaders, fromClient);
                            CLIENT_HEADERS_CAPTURE.set(fromClient.build());
                            return next.startCall(
                                    new SimpleForwardingServerCall<REQ, RESP>(call) {
                                        @Override
                                        public void close(Status status, Metadata trailers) {
                                            trailers.merge(requestHeaders);
                                            super.close(status, trailers);
                                        }
                                    }, requestHeaders);
                        }
                    });

    sb.serviceUnder("/",
                    GrpcService.builder()
                               .addService(interceptService)
                               .setMaxInboundMessageSizeBytes(MAX_MESSAGE_SIZE)
                               .setMaxOutboundMessageSizeBytes(MAX_MESSAGE_SIZE)
                               .useClientTimeoutHeader(false)
                               .build()
                               .decorate((client, ctx, req) -> {
                                   final HttpResponse res = client.serve(ctx, req);
                                   return new FilteredHttpResponse(res) {
                                       private boolean headersReceived;

                                       @Override
                                       protected HttpObject filter(HttpObject obj) {
                                           if (obj instanceof HttpHeaders) {
                                               if (!headersReceived) {
                                                   headersReceived = true;
                                               } else {
                                                   SERVER_TRAILERS_CAPTURE.set((HttpHeaders) obj);
                                               }
                                           }
                                           return obj;
                                       }
                                   };
                               }));
}
 
Example 18
Source File: ArmeriaAutoConfiguration.java    From armeria with Apache License 2.0 4 votes vote down vote up
/**
 * Create a started {@link Server} bean.
 */
@Bean
@Nullable
public Server armeriaServer(
        ArmeriaSettings armeriaSettings,
        Optional<MeterRegistry> meterRegistry,
        Optional<MeterIdPrefixFunctionFactory> meterIdPrefixFunctionFactory,
        Optional<List<HealthChecker>> healthCheckers,
        Optional<List<ArmeriaServerConfigurator>> armeriaServerConfigurators,
        Optional<List<Consumer<ServerBuilder>>> armeriaServerBuilderConsumers,
        Optional<List<ThriftServiceRegistrationBean>> thriftServiceRegistrationBeans,
        Optional<List<GrpcServiceRegistrationBean>> grpcServiceRegistrationBeans,
        Optional<List<HttpServiceRegistrationBean>> httpServiceRegistrationBeans,
        Optional<List<AnnotatedServiceRegistrationBean>> annotatedServiceRegistrationBeans,
        Optional<List<DocServiceConfigurator>> docServiceConfigurators)
        throws InterruptedException {

    if (!armeriaServerConfigurators.isPresent() &&
        !armeriaServerBuilderConsumers.isPresent() &&
        !thriftServiceRegistrationBeans.isPresent() &&
        !grpcServiceRegistrationBeans.isPresent() &&
        !httpServiceRegistrationBeans.isPresent() &&
        !annotatedServiceRegistrationBeans.isPresent()) {
        // No services to register, no need to start up armeria server.
        return null;
    }

    final MeterIdPrefixFunctionFactory meterIdPrefixFuncFactory;
    if (armeriaSettings.isEnableMetrics()) {
        meterIdPrefixFuncFactory = meterIdPrefixFunctionFactory.orElse(
                MeterIdPrefixFunctionFactory.ofDefault());
    } else {
        meterIdPrefixFuncFactory = null;
    }

    final ServerBuilder serverBuilder = Server.builder();

    final List<Port> ports = armeriaSettings.getPorts();
    if (ports.isEmpty()) {
        serverBuilder.port(new ServerPort(DEFAULT_PORT.getPort(), DEFAULT_PORT.getProtocols()));
    } else {
        configurePorts(serverBuilder, ports);
    }

    final DocServiceBuilder docServiceBuilder = DocService.builder();
    docServiceConfigurators.ifPresent(
            configurators -> configurators.forEach(
                    configurator -> configurator.configure(docServiceBuilder)));

    final String docsPath = armeriaSettings.getDocsPath();
    configureThriftServices(serverBuilder,
                            docServiceBuilder,
                            thriftServiceRegistrationBeans.orElseGet(Collections::emptyList),
                            meterIdPrefixFuncFactory,
                            docsPath);
    configureGrpcServices(serverBuilder,
                          docServiceBuilder,
                          grpcServiceRegistrationBeans.orElseGet(Collections::emptyList),
                          meterIdPrefixFuncFactory,
                          docsPath);
    configureHttpServices(serverBuilder,
                          httpServiceRegistrationBeans.orElseGet(Collections::emptyList),
                          meterIdPrefixFuncFactory);
    configureAnnotatedServices(serverBuilder,
                               docServiceBuilder,
                               annotatedServiceRegistrationBeans.orElseGet(Collections::emptyList),
                               meterIdPrefixFuncFactory,
                               docsPath);
    configureServerWithArmeriaSettings(serverBuilder, armeriaSettings,
                                       meterRegistry.orElse(Metrics.globalRegistry),
                                       healthCheckers.orElseGet(Collections::emptyList));

    armeriaServerConfigurators.ifPresent(
            configurators -> configurators.forEach(
                    configurator -> configurator.configure(serverBuilder)));

    armeriaServerBuilderConsumers.ifPresent(
            consumers -> consumers.forEach(
                    consumer -> consumer.accept(serverBuilder)));

    if (!Strings.isNullOrEmpty(docsPath)) {
        serverBuilder.serviceUnder(docsPath, docServiceBuilder.build());
    }

    final Server server = serverBuilder.build();

    server.start().handle((result, t) -> {
        if (t != null) {
            throw new IllegalStateException("Armeria server failed to start", t);
        }
        return result;
    }).join();
    logger.info("Armeria server started at ports: {}", server.activePorts());
    return server;
}
 
Example 19
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 20
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());
}