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

The following examples show how to use com.linecorp.armeria.server.ServerBuilder#build() . 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: Main.java    From Jax-RS-Performance-Comparison with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) {
    HelloService.AsyncIface helloHandler = new HelloService.AsyncIface(){
        @Override
        public void hello(AsyncMethodCallback resultHandler) throws TException {
            resultHandler.onComplete("Hello world");
        }
    };

    ServerBuilder sb = new ServerBuilder();
    sb.port(8080, SessionProtocol.HTTP);
    sb.serviceAt("/hello", ThriftService.of(helloHandler, SerializationFormat.THRIFT_BINARY))
            .serviceUnder("/docs/", new DocService());

    Server server= sb.build();
    server.start();
}
 
Example 2
Source File: ManagedArmeriaServer.java    From armeria with Apache License 2.0 6 votes vote down vote up
@Override
public void start() throws Exception {
    logger.trace("Getting Armeria Server Builder");
    final ServerBuilder sb = ((ArmeriaServerFactory) serverFactory).getServerBuilder();
    logger.trace("Calling Server Configurator");
    serverConfigurator.configure(sb);
    server = sb.build();
    if (logger.isDebugEnabled()) {
        logger.debug("Built server {}", server);
    }
    logger.info("Starting Armeria Server");
    try {
        server.start().join();
    } catch (Throwable cause) {
        Exceptions.throwUnsafely(Exceptions.peel(cause));
    }
    logger.info("Started Armeria Server");
}
 
Example 3
Source File: PooledResponseBufferBenchmark.java    From armeria with Apache License 2.0 6 votes vote down vote up
@Setup
public void startServer() throws Exception {
    final ServerBuilder sb =
            Server.builder()
                  .service("/a", THttpService.of((AsyncIface) (name, cb) -> cb.onComplete(RESPONSE))
                                             .decorate(PooledDecoratingService::new))
                  .service("/b", THttpService.of((AsyncIface) (name, cb) -> cb.onComplete(RESPONSE))
                                             .decorate(UnpooledDecoratingService::new));
    server = sb.build();
    server.start().join();

    final int httpPort = server.activeLocalPort(SessionProtocol.HTTP);
    pooledClient = Clients.newClient("tbinary+http://127.0.0.1:" + httpPort + "/a",
                                     HelloService.Iface.class);
    unpooledClient = Clients.newClient("tbinary+http://127.0.0.1:" + httpPort + "/b",
                                       HelloService.Iface.class);
}
 
Example 4
Source File: ArmeriaConfigurationUtilTest.java    From armeria with Apache License 2.0 5 votes vote down vote up
@Test
void configureServer() throws Exception {
    final File yml = new File(resourceFilePath("armeria-settings.yaml"));
    final ArmeriaSettings armeriaSettings = configFactory.build(yml);
    armeriaSettings.setSsl(null);
    final ServerBuilder serverBuilder = Server.builder()
            .service("/foo", (ctx, req) -> HttpResponse.of(200));
    serverBuilder.tlsSelfSigned();
    ArmeriaConfigurationUtil.configureServer(serverBuilder, armeriaSettings);
    final Server server = serverBuilder.build();
    assertThat(server.defaultHostname()).isEqualTo("host.name.com");
    assertThat(server.config().maxNumConnections()).isEqualTo(5000);
    assertThat(server.config().isDateHeaderEnabled()).isFalse();
    assertThat(server.config().isServerHeaderEnabled()).isTrue();
    assertThat(server.config().defaultVirtualHost().maxRequestLength()).isEqualTo(10485761);

    assertThat(server.config().ports()).hasSize(3);
    assertThat(server.config().ports()).containsExactly(
            new ServerPort(8080, SessionProtocol.HTTP),
            new ServerPort(new InetSocketAddress("127.0.0.1", 8081), SessionProtocol.HTTPS),
            new ServerPort(8443, SessionProtocol.HTTPS, SessionProtocol.PROXY)
    );
    assertThat(server.config().http1MaxChunkSize()).isEqualTo(4000);
    assertThat(server.config().http1MaxInitialLineLength()).isEqualTo(4096);
    assertThat(server.config().http1MaxInitialLineLength()).isEqualTo(4096);
    assertThat(server.config().http2InitialConnectionWindowSize()).isEqualTo(1024 * 1024 * 2);
    assertThat(server.config().http2InitialStreamWindowSize()).isEqualTo(1024 * 1024 * 2);
    assertThat(server.config().http2MaxFrameSize()).isEqualTo(16385);
    assertThat(server.config().http2MaxHeaderListSize()).isEqualTo(8193);
    assertThat(server.config().proxyProtocolMaxTlvSize()).isEqualTo(65320);
}
 
Example 5
Source File: ArmeriaConfigurationUtilTest.java    From armeria with Apache License 2.0 5 votes vote down vote up
@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 6
Source File: ArmeriaConfigurationUtilTest.java    From armeria with Apache License 2.0 5 votes vote down vote up
@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 7
Source File: ServerApplication.java    From skywalking with Apache License 2.0 5 votes vote down vote up
@PostConstruct
public void init() {
    ServerBuilder sb = new ServerBuilder().http(8085)
                                          .service("/healthCheck", (ctx, res) -> HttpResponse.of(SUCCESS))
                                          .service("/greet/{name}", (ctx, res) -> HttpResponse.of("Hello %s~", ctx.pathParam("name")));

    Server server = sb.build();
    CompletableFuture<Void> future = server.start();
    future.join();
}
 
Example 8
Source File: ServerApplication.java    From skywalking with Apache License 2.0 5 votes vote down vote up
@PostConstruct
public void init() {
    ServerBuilder sb = new ServerBuilder().http(8085)
                                          .service("/healthCheck", (ctx, res) -> HttpResponse.of(SUCCESS))
                                          .service("/greet/{name}", (ctx, res) -> HttpResponse.of("Hello %s~", ctx.pathParam("name")));

    Server server = sb.build();
    CompletableFuture<Void> future = server.start();
    future.join();
}
 
Example 9
Source File: App.java    From FrameworkBenchmarks with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
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 10
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 11
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 12
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();
}