com.linecorp.armeria.server.docs.DocService Java Examples
The following examples show how to use
com.linecorp.armeria.server.docs.DocService.
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 |
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: HelloConfiguration.java From armeria with Apache License 2.0 | 6 votes |
/** * A user can configure a {@link Server} by providing an {@link ArmeriaServerConfigurator} bean. */ @Bean public ArmeriaServerConfigurator armeriaServerConfigurator() { // Customize the server using the given ServerBuilder. For example: return builder -> { // Add DocService that enables you to send Thrift and gRPC requests from web browser. builder.serviceUnder("/docs", new DocService()); // Log every message which the server receives and responds. builder.decorator(LoggingService.newDecorator()); // Write access log after completing a request. builder.accessLogWriter(AccessLogWriter.combined(), false); // You can also bind annotated HTTP services and asynchronous RPC services such as Thrift and gRPC: // builder.annotatedService("/rest", service); // builder.service("/thrift", THttpService.of(...)); // builder.service(GrpcService.builder()...build()); }; }
Example #3
Source File: HelloConfiguration.java From armeria with Apache License 2.0 | 6 votes |
/** * A user can configure a {@link Server} by providing an {@link ArmeriaServerConfigurator} bean. */ @Bean public ArmeriaServerConfigurator armeriaServerConfigurator(HelloAnnotatedService service) { // Customize the server using the given ServerBuilder. For example: return builder -> { // Add DocService that enables you to send Thrift and gRPC requests from web browser. builder.serviceUnder("/docs", new DocService()); // Log every message which the server receives and responds. builder.decorator(LoggingService.newDecorator()); // Write access log after completing a request. builder.accessLogWriter(AccessLogWriter.combined(), false); // Add an Armeria annotated HTTP service. builder.annotatedService(service); // You can also bind asynchronous RPC services such as Thrift and gRPC: // builder.service(THttpService.of(...)); // builder.service(GrpcService.builder()...build()); }; }
Example #4
Source File: ArmeriaGrpcServer.java From grpc-by-example-java with Apache License 2.0 | 5 votes |
static Server newServer(int httpPort, int httpsPort) throws Exception { final HelloRequest exampleRequest = HelloRequest.newBuilder().setName("Armeria").build(); final HttpServiceWithRoutes grpcService = GrpcService.builder() .addService(new HelloServiceImpl()) // See https://github.com/grpc/grpc-java/blob/master/documentation/server-reflection-tutorial.md .addService(ProtoReflectionService.newInstance()) .supportedSerializationFormats(GrpcSerializationFormats.values()) .enableUnframedRequests(true) // You can set useBlockingTaskExecutor(true) in order to execute all gRPC // methods in the blockingTaskExecutor thread pool. // .useBlockingTaskExecutor(true) .build(); return Server.builder() .http(httpPort) .https(httpsPort) .tlsSelfSigned() .service(grpcService) // You can access the documentation service at http://127.0.0.1:8080/docs. // See https://line.github.io/armeria/server-docservice.html for more information. .serviceUnder("/docs", DocService.builder() .exampleRequestForMethod(HelloServiceGrpc.SERVICE_NAME, "Hello", exampleRequest) .exampleRequestForMethod(HelloServiceGrpc.SERVICE_NAME, "LazyHello", exampleRequest) .exampleRequestForMethod(HelloServiceGrpc.SERVICE_NAME, "BlockingHello", exampleRequest) .exclude(DocServiceFilter.ofServiceName( ServerReflectionGrpc.SERVICE_NAME)) .build()) .build(); }
Example #5
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 #6
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 #7
Source File: Main.java From armeria with Apache License 2.0 | 5 votes |
static Server newServer(int httpPort, int httpsPort) throws Exception { final HelloRequest exampleRequest = HelloRequest.newBuilder().setName("Armeria").build(); final HttpServiceWithRoutes grpcService = GrpcService.builder() .addService(new HelloServiceImpl()) // See https://github.com/grpc/grpc-java/blob/master/documentation/server-reflection-tutorial.md .addService(ProtoReflectionService.newInstance()) .supportedSerializationFormats(GrpcSerializationFormats.values()) .enableUnframedRequests(true) // You can set useBlockingTaskExecutor(true) in order to execute all gRPC // methods in the blockingTaskExecutor thread pool. // .useBlockingTaskExecutor(true) .build(); return Server.builder() .http(httpPort) .https(httpsPort) .tlsSelfSigned() .service(grpcService) // You can access the documentation service at http://127.0.0.1:8080/docs. // See https://armeria.dev/docs/server-docservice for more information. .serviceUnder("/docs", DocService.builder() .exampleRequestForMethod( HelloServiceGrpc.SERVICE_NAME, "Hello", exampleRequest) .exampleRequestForMethod( HelloServiceGrpc.SERVICE_NAME, "LazyHello", exampleRequest) .exampleRequestForMethod( HelloServiceGrpc.SERVICE_NAME, "BlockingHello", exampleRequest) .exclude(DocServiceFilter.ofServiceName( ServerReflectionGrpc.SERVICE_NAME)) .build()) .build(); }
Example #8
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 #9
Source File: Main.java From armeria with Apache License 2.0 | 5 votes |
static Server newServer(int httpPort, int httpsPort) throws Exception { final HelloRequest exampleRequest = HelloRequest.newBuilder().setName("Armeria").build(); final HttpServiceWithRoutes grpcService = GrpcService.builder() .addService(new HelloServiceImpl()) // See https://github.com/grpc/grpc-java/blob/master/documentation/server-reflection-tutorial.md .addService(ProtoReflectionService.newInstance()) .supportedSerializationFormats(GrpcSerializationFormats.values()) .enableUnframedRequests(true) // You can set useBlockingTaskExecutor(true) in order to execute all gRPC // methods in the blockingTaskExecutor thread pool. // .useBlockingTaskExecutor(true) .build(); return Server.builder() .http(httpPort) .https(httpsPort) .tlsSelfSigned() .service(grpcService) // You can access the documentation service at http://127.0.0.1:8080/docs. // See https://armeria.dev/docs/server-docservice for more information. .serviceUnder("/docs", DocService.builder() .exampleRequestForMethod(HelloServiceGrpc.SERVICE_NAME, "Hello", exampleRequest) .exampleRequestForMethod(HelloServiceGrpc.SERVICE_NAME, "LazyHello", exampleRequest) .exampleRequestForMethod(HelloServiceGrpc.SERVICE_NAME, "BlockingHello", exampleRequest) .exclude(DocServiceFilter.ofServiceName( ServerReflectionGrpc.SERVICE_NAME)) .build()) .build(); }
Example #10
Source File: GrpcDocServiceTest.java From armeria with Apache License 2.0 | 5 votes |
@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 #11
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 #12
Source File: ArmeriaReactiveWebServerFactory.java From armeria with Apache License 2.0 | 4 votes |
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 #13
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 #14
Source File: ThriftDocServiceTest.java From armeria with Apache License 2.0 | 4 votes |
@Override protected void configure(ServerBuilder sb) throws Exception { if (TestUtil.isDocServiceDemoMode()) { sb.http(8080); } final THttpService helloAndSleepService = THttpService.builder() .addService("hello", HELLO_SERVICE_HANDLER) .addService("sleep", SLEEP_SERVICE_HANDLER) .build(); final THttpService fooService = THttpService.ofFormats(mock(FooService.AsyncIface.class), COMPACT); final THttpService cassandraService = THttpService.ofFormats(mock(Cassandra.AsyncIface.class), BINARY); final THttpService cassandraServiceDebug = THttpService.ofFormats(mock(Cassandra.AsyncIface.class), TEXT); final THttpService hbaseService = THttpService.of(mock(Hbase.AsyncIface.class)); final THttpService onewayHelloService = THttpService.of(mock(OnewayHelloService.AsyncIface.class)); sb.service("/", helloAndSleepService); sb.service("/foo", fooService); // Add a service with serviceUnder() to test whether prefix mapping is detected. sb.serviceUnder("/foo", fooService); sb.service("/cassandra", cassandraService); sb.service("/cassandra/debug", cassandraServiceDebug); sb.service("/hbase", hbaseService); sb.service("/oneway", onewayHelloService); sb.serviceUnder("/docs/", DocService.builder() .exampleHttpHeaders(EXAMPLE_HEADERS_ALL) .exampleHttpHeaders(HelloService.class, EXAMPLE_HEADERS_HELLO) .exampleHttpHeaders(FooService.class, EXAMPLE_HEADERS_FOO) .exampleHttpHeaders(FooService.class, "bar1", EXAMPLE_HEADERS_FOO_BAR1) .exampleRequest(EXAMPLE_HELLO) .build()); sb.serviceUnder("/excludeAll/", DocService.builder() .exclude(DocServiceFilter.ofThrift()) .build()); }