public static void main(String[] args) throws Exception { final SamlServiceProvider ssp = samlServiceProvider(); final Server server = new ServerBuilder() .https(8443) // You can add this certificate to your trust store in order to make your web browser happy. .tls(new File(ClassLoader.getSystemResource("localhost.crt").toURI()), new File(ClassLoader.getSystemResource("localhost.key").toURI())) // Decorate you service with SAML decorator. .annotatedService("/", new MyService(), ssp.newSamlDecorator()) // Add SAML service to your server which handles a SAML response and a metadata request. .service(ssp.newSamlService()) .build(); Runtime.getRuntime().addShutdownHook(new Thread(() -> { server.stop().join(); logger.info("Server has been stopped."); })); server.start().join(); logger.info("Server has been started."); } }
@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.forServer(jetty).decorate(LoggingService.newDecorator())); } };
/** * Sets the amount of time to wait after calling {@link Server#stop()} for * requests to go away before actually shutting down. * * @param quietPeriodMillis the number of milliseconds to wait for active * requests to go end before shutting down. 0 means the server will * stop right away without waiting. * @param timeoutMillis the number of milliseconds to wait before shutting * down the server regardless of active requests. This should be set to * a time greater than {@code quietPeriodMillis} to ensure the server * shuts down even if there is a stuck request. */ public ServerBuilder gracefulShutdownTimeout(long quietPeriodMillis, long timeoutMillis) { return gracefulShutdownTimeout( Duration.ofMillis(quietPeriodMillis), Duration.ofMillis(timeoutMillis)); }
/** * Returns a new {@link Server} instance configured with annotated HTTP services. * * @param port the port that the server is to be bound to */ public static Server of(int port) { final ServerBuilder sb = new ServerBuilder(); return sb.http(port) .annotatedService("/pathPattern", new PathPatternService()) .annotatedService("/injection", new InjectionService()) .annotatedService("/messageConverter", new MessageConverterService()) .annotatedService("/exception", new ExceptionHandlerService()) .build(); }
/** * Starts the {@link Server} configured by {@link #configure(ServerBuilder)}. * If the {@link Server} has been started up already, the existing {@link Server} is returned. * Note that this operation blocks until the {@link Server} finished the start-up. * * @return the started {@link Server} */ public Server start() { final Server oldServer = server.get(); if (!isStopped(oldServer)) { return oldServer; } final ServerBuilder sb = new ServerBuilder(); try { configure(sb); } catch (Exception e) { throw new IllegalStateException("failed to configure a Server", e); } final Server server = sb.build(); server.start().join(); this.server.set(server); return server; }
final ServerBuilder server = new ServerBuilder(); meterRegistry.ifPresent(server::meterRegistry); server.gracefulShutdownTimeout( armeriaSettings.getGracefulShutdownQuietPeriodMillis(), armeriaSettings.getGracefulShutdownTimeoutMillis()); server.service(bean.getPath(), service); docServiceRequests.addAll(bean.getExampleRequests()); bean.getService().as(THttpService.class).ifPresent( server.service(bean.getPathMapping(), service); })); server.annotatedService(bean.getPathPrefix(), bean.getService(), decorator); })); server.service(armeriaSettings.getHealthCheckPath(), new HttpHealthCheckService(healthCheckers.orElseGet(Collections::emptyList) .toArray(EMPTY_HEALTH_CHECKERS))); server.serviceUnder(armeriaSettings.getDocsPath(), docServiceBuilder.build()); .enable(SerializationFeature.INDENT_OUTPUT) .registerModule(new MetricsModule(TimeUnit.SECONDS, TimeUnit.MILLISECONDS, true)); server.service( armeriaSettings.getMetricsPath(), new AbstractHttpService() {
private Server startServer(ProjectManager pm, CommandExecutor executor, @Nullable CentralDogmaSecurityManager securityManager) { final ServerBuilder sb = new ServerBuilder(); cfg.ports().forEach(sb::port); 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(); numWorkers -> sb.workerGroup(EventLoopGroups.newEventLoopGroup(numWorkers), true)); cfg.maxNumConnections().ifPresent(sb::maxNumConnections); cfg.idleTimeoutMillis().ifPresent(sb::idleTimeoutMillis); cfg.maxFrameLength().ifPresent(sb::defaultMaxRequestLength); cfg.gracefulShutdownTimeout().ifPresent( t -> sb.gracefulShutdownTimeout(t.quietPeriodMillis(), t.timeoutMillis())); sb.service("/hostname", HttpFileService.forVfs(new AbstractHttpVfs() { @Override public Entry get(String path, @Nullable String contentEncoding) { sb.service("/cache_stats", new AbstractHttpService() { @Override protected HttpResponse doGet(ServiceRequestContext ctx, HttpRequest req) sb.service(HEALTH_CHECK_PATH, new HttpHealthCheckService());
sb.service("/security_enabled", new AbstractHttpService() { @Override protected HttpResponse doGet(ServiceRequestContext ctx, HttpRequest req) { sb.annotatedService(API_V1_PATH_PREFIX, new AdministrativeService(safePm, executor), decorator, v1RequestConverter, v1ResponseConverter); sb.annotatedService(API_V1_PATH_PREFIX, new ProjectServiceV1(safePm, executor, mds), decorator, v1RequestConverter, v1ResponseConverter); sb.annotatedService(API_V1_PATH_PREFIX, new RepositoryServiceV1(safePm, executor, mds), decorator, v1RequestConverter, v1ResponseConverter); sb.annotatedService(API_V1_PATH_PREFIX, new ContentServiceV1(safePm, executor, watchService), decorator, v1RequestConverter, v1ResponseConverter); final AuthConfig authCfg = cfg.authConfig(); assert authCfg != null : "authCfg"; sb.annotatedService(API_V1_PATH_PREFIX, new MetadataApiService(mds, authCfg.loginNameNormalizer()), decorator, v1RequestConverter, v1ResponseConverter); sb.annotatedService(API_V1_PATH_PREFIX, new TokenService(pm, executor, mds), decorator, v1RequestConverter, v1ResponseConverter); .ifPresent(login -> LOGIN_API_PATH_MAPPINGS.forEach(mapping -> sb.service(mapping, login))); .orElseGet(() -> new DefaultLogoutService(executor)); for (PathMapping mapping : LOGOUT_API_PATH_MAPPINGS) {
/** * Binds the specified {@link Service} at the specified path pattern of the default {@link VirtualHost}. * * @deprecated Use {@link #service(String, Service)} instead. */ @Deprecated public ServerBuilder serviceAt(String pathPattern, Service<HttpRequest, HttpResponse> service) { return service(pathPattern, service); }
final ServerBuilder serverBuilder = new ServerBuilder().meterRegistry(meterRegistry()) .workerGroup(eventLoop(), false) .service(path(), service); serverConfigurators.forEach(configurator -> configurator.accept(serverBuilder)); final Server server = serverBuilder.build(); server.addListener(rejectingListener);
@Before public void startServers() { servers = new ArrayList<>(); for (Endpoint endpoint : sampleEndpoints) { final Server server = new ServerBuilder().http(endpoint.port()) .service("/", new EchoService()) .build(); final ServerListener listener = new ZooKeeperUpdatingListenerBuilder( instance().connectString().get(), zNode) .sessionTimeoutMillis(sessionTimeoutMillis) .endpoint(endpoint) .build(); server.addListener(listener); server.start().join(); servers.add(server); } }
server.service(bean.getPath(), service); docServiceRequests.addAll(bean.getExampleRequests()); ThriftServiceUtils.serviceNames(bean.getService()) docServiceBuilder.exampleHttpHeaders(entry.getKey(), entry.getValue()); server.serviceUnder(docsPath, docServiceBuilder.build());
/** * Binds the specified annotated service object under the specified path prefix. * * @param exceptionHandlersAndConverters an iterable object of {@link ExceptionHandlerFunction}, * {@link RequestConverterFunction} and/or * {@link ResponseConverterFunction} */ public ServerBuilder annotatedService(String pathPrefix, Object service, Iterable<?> exceptionHandlersAndConverters) { return annotatedService(pathPrefix, service, Function.identity(), exceptionHandlersAndConverters); }
server.gracefulShutdownTimeout(settings.getGracefulShutdownQuietPeriodMillis(), settings.getGracefulShutdownTimeoutMillis()); logger.debug("Set graceful shutdown timeout: quiet period {} ms, timeout {} ms", server.service(healthCheckPath, new HttpHealthCheckService(healthCheckers.toArray(EMPTY_HEALTH_CHECKERS))); server.meterRegistry(meterRegistry); .enable(SerializationFeature.INDENT_OUTPUT) .registerModule(new MetricsModule(TimeUnit.SECONDS, TimeUnit.MILLISECONDS, true)); server.service( settings.getMetricsPath(), new AbstractHttpService() {
@Override public WebServer getWebServer(HttpHandler httpHandler) { final ServerBuilder sb = new ServerBuilder(); final int port = ensureValidPort(getPort()); if (address != null) { sb.port(new InetSocketAddress(address, port), protocol); } else { sb.port(port, protocol); sb.decorator(contentEncodingDecorator(compression)); final Server server = configureService(sb, httpHandler, factoryWrapper, getServerHeader()).build(); return new ArmeriaWebServer(server, protocol, address, port);
: null; final ServerBuilder server = new ServerBuilder(); server.port(new ServerPort(DEFAULT_PORT.getPort(), DEFAULT_PORT.getProtocols())); } else { configurePorts(server, ports); configurator -> configurator.configure(server))); final Server s = server.build();
@Override protected void configure(ServerBuilder sb) throws Exception { sb.service("/pojo", new AbstractHttpService() { @Override protected HttpResponse doGet(ServiceRequestContext ctx, HttpRequest req) throws Exception { .serviceUnder("/pathWithName", new AbstractHttpService() { .service("/nest/pojo", new AbstractHttpService() { @Override protected HttpResponse doGet(ServiceRequestContext ctx, HttpRequest req) throws Exception { .service("/pojos", new AbstractHttpService() { @Override protected HttpResponse doGet(ServiceRequestContext ctx, HttpRequest req) throws Exception { .service("/queryString", new AbstractHttpService() { @Override protected HttpResponse doGet(ServiceRequestContext ctx, HttpRequest req) throws Exception { .service("/post", new AbstractHttpService() { @Override protected HttpResponse doPost(ServiceRequestContext ctx, HttpRequest req) throws Exception { .service("/postForm", new AbstractHttpService() { @Override protected HttpResponse doPost(ServiceRequestContext ctx, HttpRequest req) throws Exception { .service("/postCustomContentType", new AbstractHttpService() { @Override
@Override protected void configure(ServerBuilder sb) throws Exception { sb.workerGroup(EventLoopGroups.newEventLoopGroup(1), true); sb.defaultMaxRequestLength(Long.MAX_VALUE); sb.serviceUnder("/", new GrpcServiceBuilder() .addService(new UnitTestServiceImpl()) .build() .decorate(LoggingService.newDecorator()) .decorate((delegate, ctx, req) -> { ctx.log().addListener(requestLogQueue::add, RequestLogAvailability.COMPLETE); return delegate.serve(ctx, req); })); } };
@Override protected void configure(ServerBuilder sb) throws Exception { sb.gracefulShutdownTimeout(1000L, 2000L); sb.defaultRequestTimeoutMillis(0); // Disable RequestTimeoutException. sb.service("/sleep", THttpService.of( (AsyncIface) (milliseconds, resultHandler) -> RequestContext.current().eventLoop().schedule( () -> resultHandler.onComplete(milliseconds), milliseconds, MILLISECONDS))); } };
.build(); sb.service(sp.newSamlService()) .annotatedService("/", new Object() { @Get("/{bindingProtocol}") public String root() {