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

The following examples show how to use com.linecorp.armeria.server.ServerBuilder#service() . 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: ServerSentEventsTest.java    From armeria with Apache License 2.0 6 votes vote down vote up
@Override
protected void configure(ServerBuilder sb) throws Exception {
    sb.service("/sse/publisher", (ctx, req) -> ServerSentEvents.fromPublisher(
            Flux.just(ServerSentEvent.ofData("foo"), ServerSentEvent.ofData("bar"))));
    sb.service("/sse/stream", (ctx, req) -> ServerSentEvents.fromStream(
            Stream.of(ServerSentEvent.ofData("foo"), ServerSentEvent.ofData("bar")),
            MoreExecutors.directExecutor()));

    sb.service("/converter/publisher", (ctx, req) -> ServerSentEvents.fromPublisher(
            Flux.just("foo", "bar"), ServerSentEvent::ofComment));
    sb.service("/converter/stream", (ctx, req) -> ServerSentEvents.fromStream(
            Stream.of("foo", "bar"), MoreExecutors.directExecutor(), ServerSentEvent::ofComment));

    sb.service("/single/sse", (ctx, req) -> ServerSentEvents.fromEvent(
            ServerSentEvent.ofEvent("add")));
}
 
Example 2
Source File: ThrottlingServiceTest.java    From armeria with Apache License 2.0 6 votes vote down vote up
@Override
protected void configure(ServerBuilder sb) throws Exception {
    sb.service("/http-always", SERVICE.decorate(ThrottlingService.newDecorator(always())));
    sb.service("/http-never", SERVICE.decorate(ThrottlingService.newDecorator(never())));
    sb.service("/http-never-custom", SERVICE.decorate(
            ThrottlingService.newDecorator(ThrottlingStrategy.of((ctx, req) -> completedFuture(false)),
                (delegate, ctx, req, cause) -> HttpResponse.of(HttpStatus.SERVICE_UNAVAILABLE))

    ));
    sb.service("/http-always-custom", SERVICE.decorate(
            ThrottlingService.builder(ThrottlingStrategy.of((ctx, req) -> completedFuture(true)))
                             .onAcceptedRequest((delegate, ctx, req) -> {
                                 ctx.addAdditionalResponseHeader(
                                         "X-RateLimit-Limit",
                                         "10, 10;window=1;burst=1000, 1000;window=3600");
                                 return delegate.serve(ctx, req);
                             })
                             .newDecorator()
    ));
}
 
Example 3
Source File: DropwizardArmeriaApplication.java    From armeria with Apache License 2.0 6 votes vote down vote up
@Override
public void initialize(Bootstrap<DropwizardArmeriaConfiguration> bootstrap) {
    final ArmeriaBundle<DropwizardArmeriaConfiguration> bundle =
            new ArmeriaBundle<DropwizardArmeriaConfiguration>() {
        @Override
        public void configure(ServerBuilder builder) {
            builder.service("/", (ctx, res) -> HttpResponse.of(MediaType.HTML_UTF_8, "<h2>It works!</h2>"));
            builder.service("/armeria", (ctx, res) -> HttpResponse.of("Hello, Armeria!"));

            builder.annotatedService(new HelloService());

            // You can also bind asynchronous RPC services such as Thrift and gRPC:
            // builder.service(THttpService.of(...));
            // builder.service(GrpcService.builder()...build());
        }
    };
    bootstrap.addBundle(bundle);
}
 
Example 4
Source File: ThriftDynamicTimeoutTest.java    From armeria with Apache License 2.0 5 votes vote down vote up
@Override
protected void configure(ServerBuilder sb) throws Exception {
    // Used for testing if changing the timeout dynamically works.
    sb.service("/sleep", ThriftCallService.of(sleepService)
                                          .decorate(DynamicTimeoutService::new)
                                          .decorate(THttpService.newDecorator()));
    // Used for testing if disabling the timeout dynamically works.
    sb.service("/fakeSleep", ThriftCallService.of(fakeSleepService)
                                              .decorate(TimeoutDisablingService::new)
                                              .decorate(THttpService.newDecorator()));
    sb.requestTimeout(Duration.ofSeconds(1));
}
 
Example 5
Source File: HealthCheckedEndpointGroupLongPollingTest.java    From armeria with Apache License 2.0 5 votes vote down vote up
@Override
protected void configure(ServerBuilder sb) throws Exception {
    sb.service(HEALTH_CHECK_PATH, HealthCheckService.builder()
                                                    .longPolling(LONG_POLLING_TIMEOUT)
                                                    .checkers(health)
                                                    .build());

    // Enable graceful shutdown so that the server is given a chance
    // to send a health check response when the server is shutting down.
    // Without graceful shutdown, the health check request will be aborted
    // with GOAWAY or disconnection.
    sb.gracefulShutdownTimeoutMillis(3000, 10000);
}
 
Example 6
Source File: HttpClientPipeliningTest.java    From armeria with Apache License 2.0 5 votes vote down vote up
@Override
protected void configure(ServerBuilder sb) throws Exception {
    // Bind a service that returns the remote address of the connection to determine
    // if the same connection was used to handle more than one request.
    sb.service("/", new AbstractHttpService() {
        @Override
        protected HttpResponse doGet(ServiceRequestContext ctx, HttpRequest req) throws Exception {
            // Consume the request completely so that the connection can be returned to the pool.
            return HttpResponse.from(req.aggregate().handle((unused1, unused2) -> {
                // Signal the main thread that the connection has been returned to the pool.
                // Note that this is true only when pipelining is enabled. The connection is returned
                // after response is fully sent if pipelining is disabled.
                lock.lock();
                try {
                    connectionReturnedToPool = true;
                    condition.signal();
                } finally {
                    lock.unlock();
                }

                semaphore.acquireUninterruptibly();
                try {
                    return HttpResponse.of(HttpStatus.OK, MediaType.PLAIN_TEXT_UTF_8,
                                           String.valueOf(ctx.remoteAddress()));
                } finally {
                    semaphore.release();
                }
            }));
        }
    });
}
 
Example 7
Source File: EurekaUpdatingListenerTest.java    From armeria with Apache License 2.0 5 votes vote down vote up
@Override
protected void configure(ServerBuilder sb) throws Exception {
    sb.service("/apps/" + APP_NAME, (ctx, req) -> {
        if (req.method() != HttpMethod.POST) {
            registerContentCaptor.set(null);
            return HttpResponse.of(HttpStatus.METHOD_NOT_ALLOWED);
        }
        final CompletableFuture<HttpResponse> future = new CompletableFuture<>();
        req.aggregate().handle((aggregatedRes, cause) -> {
            registerContentCaptor.set(aggregatedRes.content());
            future.complete(HttpResponse.of(HttpStatus.NO_CONTENT));
            return null;
        });
        return HttpResponse.from(future);
    });
    final AtomicInteger heartBeatRequestCounter = new AtomicInteger();
    sb.service("/apps/" + APP_NAME + '/' + INSTANCE_ID, (ctx, req) -> {
        req.aggregate();
        if (req.method() == HttpMethod.PUT) {
            final int count = heartBeatRequestCounter.getAndIncrement();
            if (count == 0) {
                // This is for the test that EurekaUpdatingListener automatically retries when
                // RetryingClient is not used.
                return HttpResponse.of(HttpStatus.INTERNAL_SERVER_ERROR);
            }
            heartBeatHeadersCaptor.complete(req.headers());
        } else if (req.method() == HttpMethod.DELETE) {
            deregisterHeadersCaptor.complete(req.headers());
        }
        return HttpResponse.of(HttpStatus.OK);
    });
}
 
Example 8
Source File: GrpcMetricsIntegrationTest.java    From armeria with Apache License 2.0 5 votes vote down vote up
@Override
protected void configure(ServerBuilder sb) throws Exception {
    sb.meterRegistry(registry);
    sb.service(GrpcService.builder()
                          .addService(new TestServiceImpl())
                          .enableUnframedRequests(true)
                          .build(),
               MetricCollectingService.newDecorator(MeterIdPrefixFunction.ofDefault("server")),
               LoggingService.newDecorator());
}
 
Example 9
Source File: CircuitBreakerClientRuleTest.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.of("Hello, Armeria!"));
    sb.service("/503", (ctx, req) -> HttpResponse.of(HttpStatus.SERVICE_UNAVAILABLE));
    sb.service("/slow", (ctx, req) -> HttpResponse.streaming());
    sb.service("/trailers", (ctx, req) -> HttpResponse.of(ResponseHeaders.of(200),
                                                          HttpData.ofUtf8("oops"),
                                                          HttpHeaders.of("grpc-status", 3)));
}
 
Example 10
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 11
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 12
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 13
Source File: HttpRequestSubscriberTest.java    From armeria with Apache License 2.0 5 votes vote down vote up
@Override
protected void configure(ServerBuilder sb) throws Exception {
    final ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor();

    // TODO(hyangtack) Remove one of the following services.
    // Returning a response immediately causes a failure of a test with PublisherBasedHttpRequest.
    sb.service("/ok", (ctx, req) -> HttpResponse.of(HttpStatus.OK));
    sb.service("/delayed_ok", (ctx, req) -> {
                   final CompletableFuture<HttpResponse> f = new CompletableFuture<>();
                   executor.schedule(() -> f.complete(HttpResponse.of(HttpStatus.OK)),
                                     100, TimeUnit.MILLISECONDS);
                   return HttpResponse.from(f);
               }
    );
}
 
Example 14
Source File: RetryingRpcClientTest.java    From armeria with Apache License 2.0 5 votes vote down vote up
@Override
protected void configure(ServerBuilder sb) throws Exception {
    final AtomicInteger retryCount = new AtomicInteger();
    sb.service("/thrift", THttpService.of(serviceHandler).decorate(
            (delegate, ctx, req) -> {
                final int count = retryCount.getAndIncrement();
                if (count != 0) {
                    assertThat(count).isEqualTo(req.headers().getInt(ARMERIA_RETRY_COUNT));
                }
                return delegate.serve(ctx, req);
            }));
    sb.service("/thrift-devnull", THttpService.of(devNullServiceHandler));
}
 
Example 15
Source File: ThriftHttpHeaderTest.java    From armeria with Apache License 2.0 4 votes vote down vote up
@Override
protected void configure(ServerBuilder sb) throws Exception {
    sb.service("/hello", THttpService.of(helloService));
}
 
Example 16
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 17
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 18
Source File: HttpClientResponseTimeoutTest.java    From armeria with Apache License 2.0 4 votes vote down vote up
@Override
protected void configure(ServerBuilder sb) throws Exception {
    sb.requestTimeoutMillis(0);
    sb.service("/no-timeout", (ctx, req) -> HttpResponse.streaming());
}
 
Example 19
Source File: HttpClientContextCaptorTest.java    From armeria with Apache License 2.0 4 votes vote down vote up
@Override
protected void configure(ServerBuilder sb) throws Exception {
    sb.service("/foo", (ctx, req) -> HttpResponse.of(200));
}
 
Example 20
Source File: SimplePooledDecoratingHttpServiceTest.java    From armeria with Apache License 2.0 4 votes vote down vote up
@Override
protected void configure(ServerBuilder sb) {
    sb.service("/unpooled-delegate", UNPOOLED_DELEGATE.decorate(PooledDecorator::new));

    sb.service("/pooled-delegate", POOLED_DELEGATE.decorate(PooledDecorator::new));
}