Java Code Examples for com.linecorp.armeria.server.Server#builder()
The following examples show how to use
com.linecorp.armeria.server.Server#builder() .
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: 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 2
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 3
Source File: Main.java From armeria with Apache License 2.0 | 5 votes |
/** * Returns a new {@link Server} instance configured with annotated HTTP services. * * @param port the port that the server is to be bound to */ static Server newServer(int port) { final ServerBuilder sb = Server.builder(); return sb.http(port) .annotatedService("/pathPattern", new PathPatternService()) .annotatedService("/injection", new InjectionService()) .annotatedService("/messageConverter", new MessageConverterService()) .annotatedService("/exception", new ExceptionHandlerService()) .serviceUnder("/docs", new DocService()) .build(); }
Example 4
Source File: GrpcDocServicePluginTest.java From armeria with Apache License 2.0 | 5 votes |
private static Map<String, ServiceInfo> services(DocServiceFilter include, DocServiceFilter exclude) { final ServerBuilder serverBuilder = Server.builder(); // The case where a GrpcService is added to ServerBuilder without a prefix. final HttpServiceWithRoutes prefixlessService = GrpcService.builder() .addService(mock(TestServiceImplBase.class)) .build(); serverBuilder.service(prefixlessService); // The case where a GrpcService is added to ServerBuilder with a prefix. serverBuilder.service( Route.builder().pathPrefix("/test").build(), GrpcService.builder().addService(mock(UnitTestServiceImplBase.class)).build()); // Another GrpcService with a different prefix. serverBuilder.service( Route.builder().pathPrefix("/reconnect").build(), GrpcService.builder().addService(mock(ReconnectServiceImplBase.class)).build()); // Make sure all services and their endpoints exist in the specification. final ServiceSpecification specification = generator.generateSpecification( ImmutableSet.copyOf(serverBuilder.build().serviceConfigs()), unifyFilter(include, exclude)); return specification .services() .stream() .collect(toImmutableMap(ServiceInfo::name, Function.identity())); }
Example 5
Source File: App.java From FrameworkBenchmarks with BSD 3-Clause "New" or "Revised" License | 5 votes |
public static void main(String[] args) { ServerBuilder sb = Server.builder(); sb.http(8080) .annotatedService(new HelloService()) .annotatedService(new PostgresDbService()) .annotatedService(new PostgresFortunesService()); Server server = sb.build(); server.start().join(); }
Example 6
Source File: CentralDogma.java From centraldogma with Apache License 2.0 | 4 votes |
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 7
Source File: ArmeriaAutoConfiguration.java From armeria with Apache License 2.0 | 4 votes |
/** * 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 8
Source File: BraveServiceIntegrationTest.java From armeria with Apache License 2.0 | 4 votes |
@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(); }