private Registry getEffectiveRegistry(final DefaultHandlingResult.ResultsHolder results) { ClientErrorHandler clientErrorHandler = (context, statusCode) -> { results.setClientError(statusCode); context.getResponse().status(statusCode); results.getLatch().countDown(); }; ServerErrorHandler serverErrorHandler = (context, throwable1) -> { results.setThrowable(throwable1); results.getLatch().countDown(); }; final Registry userRegistry = Registry.builder() .add(ClientErrorHandler.class, clientErrorHandler) .add(ServerErrorHandler.class, serverErrorHandler) .build(); return Exceptions.uncheck( () -> { ServerConfig serverConfig = serverConfigBuilder.build(); DefaultExecController execController = new DefaultExecController(serverConfig.getThreads()); return ServerRegistry.serverRegistry( new TestServer(), Impositions.none(), execController, serverConfig, r -> userRegistry.join(registryBuilder.build())); }); }
@Override public void execute(RatpackServerSpec server) throws Exception { RatpackDslClosures closures = new RatpackDslClosures(null); RatpackDslBacking backing = new RatpackDslBacking(closures); ClosureUtil.configureDelegateFirst(backing, closure); server.registry(Guice.registry(ClosureUtil.delegatingAction(closures.getBindings()))); server.handlers(Groovy.chainAction(closures.getHandlers())); ServerConfigBuilder builder = ServerConfig.builder().development(true); if (ephemeralPort) { builder.port(0); } ClosureUtil.configureDelegateFirst(builder, closures.getServerConfig()); server.serverConfig(builder); }
@Override public TransformablePublisher<? extends ByteBuf> getBodyStream() { return getBodyStream(serverConfig.getMaxContentLength()); }
@Override public Promise<TypedData> getBody(Block onTooLarge) { return getBody(serverConfig.getMaxContentLength(), onTooLarge); }
@Override public Promise<TypedData> getBody() { return getBody(serverConfig.getMaxContentLength()); }
@Provides HttpClient httpClient(ByteBufAllocator byteBufAllocator, ServerConfig serverConfig) { return HttpClient.httpClient(byteBufAllocator, serverConfig.getMaxContentLength()); }
public static Registry buildBaseRegistry( RatpackServer ratpackServer, ExecController execController, ServerConfig serverConfig) { ErrorHandler errorHandler = serverConfig.isDevelopment() ? new DefaultDevelopmentErrorHandler() : new DefaultProductionErrorHandler(); RegistryBuilder baseRegistryBuilder; try { baseRegistryBuilder = Registry.builder() .add(ServerConfig.class, serverConfig) .add(ByteBufAllocator.class, PooledByteBufAllocator.DEFAULT) .add(ExecController.class, execController) .add(MimeTypes.class, new ActivationBackedMimeTypes()) .add( PublicAddress.class, new DefaultPublicAddress( serverConfig.getPublicAddress(), serverConfig.getSSLContext() == null ? HTTP_SCHEME : HTTPS_SCHEME)) .add(Redirector.class, new DefaultRedirector()) .add(ClientErrorHandler.class, errorHandler) .add(ServerErrorHandler.class, errorHandler) .with(new DefaultFileRenderer().register()) .with(new PromiseRenderer().register()) .with(new PublisherRenderer().register()) .with(new RenderableRenderer().register()) .with(new CharSequenceRenderer().register()) .add(FormParser.class, FormParser.multiPart()) .add(FormParser.class, FormParser.urlEncoded()) .add(FormNoOptParser.class, FormNoOptParser.multiPart()) .add(FormNoOptParser.class, FormNoOptParser.urlEncoded()) .add(RatpackServer.class, ratpackServer) // TODO remove Stopper, and just use RatpackServer instead (will need to update perf // and gradle tests) .add( Stopper.class, () -> uncheck( () -> { ratpackServer.stop(); return null; })) .add( HttpClient.class, HttpClient.httpClient( PooledByteBufAllocator.DEFAULT, serverConfig.getMaxContentLength())) .add( ServerSentEventStreamClient.class, ServerSentEventStreamClient.sseStreamClient(PooledByteBufAllocator.DEFAULT)) .add(HealthCheckResultsRenderer.class, new HealthCheckResultsRenderer()) .add(RequestId.Generator.class, new UuidBasedRequestIdGenerator()); addConfigObjects(serverConfig, baseRegistryBuilder); } catch (Exception e) { // Uncheck because it really shouldn't happen throw uncheck(e); } if (serverConfig.isHasBaseDir()) { baseRegistryBuilder.add(FileSystemBinding.class, serverConfig.getBaseDir()); } return baseRegistryBuilder.build(); }
private static void addConfigObjects( ServerConfig serverConfig, RegistryBuilder baseRegistryBuilder) { for (ConfigObject<?> configObject : serverConfig.getRequiredConfig()) { addConfigObject(baseRegistryBuilder, configObject); } }
/** * @see ratpack.test.handling.RequestFixture#handle(ratpack.handling.Handler, ratpack.func.Action) */ @SuppressWarnings("UnusedDeclaration") public class DefaultRequestFixture implements RequestFixture { private final ByteBuf requestBody = unreleasableBuffer(buffer()); private final MutableHeaders requestHeaders = new NettyHeadersBackedMutableHeaders(new DefaultHttpHeaders()); private final NettyHeadersBackedMutableHeaders responseHeaders = new NettyHeadersBackedMutableHeaders(new DefaultHttpHeaders()); private String method = "GET"; private String protocol = "HTTP/1.1"; private String uri = "/"; private HostAndPort remoteHostAndPort = HostAndPort.fromParts("localhost", 45678); private HostAndPort localHostAndPort = HostAndPort.fromParts("localhost", ServerConfig.DEFAULT_PORT); private int timeout = 5; private RegistryBuilder registryBuilder = Registry.builder(); private ServerConfigBuilder serverConfigBuilder = ServerConfig.builder(); private DefaultPathBinding pathBinding; @Override public RequestFixture body(byte[] bytes, String contentType) { requestHeaders.add(HttpHeaderNames.CONTENT_TYPE, contentType); requestHeaders.add(HttpHeaderNames.CONTENT_LENGTH, bytes.length); requestBody.capacity(bytes.length).writeBytes(bytes); return this; } @Override public RequestFixture body(String text, String contentType) { return body(text.getBytes(CharsetUtil.UTF_8), contentType); } @Override public RegistrySpec getRegistry() { return registryBuilder; } @Override public HandlingResult handle(Handler handler) throws HandlerTimeoutException { final DefaultHandlingResult.ResultsHolder results = new DefaultHandlingResult.ResultsHolder(); return invoke(handler, getEffectiveRegistry(results), results); } @Override public HandlingResult handleChain(Action<? super Chain> chainAction) throws Exception { final DefaultHandlingResult.ResultsHolder results = new DefaultHandlingResult.ResultsHolder(); Registry registry = getEffectiveRegistry(results); ServerConfig serverConfig = registry.get(ServerConfig.class); Handler handler = Handlers.chain(serverConfig, registry, chainAction); return invoke(handler, registry, results); } private HandlingResult invoke( Handler handler, Registry registry, DefaultHandlingResult.ResultsHolder results) throws HandlerTimeoutException { ServerConfig serverConfig = registry.get(ServerConfig.class); DefaultRequest request = new DefaultRequest( Instant.now(), requestHeaders, HttpMethod.valueOf(method.toUpperCase()), HttpVersion.valueOf(protocol), uri, new InetSocketAddress(remoteHostAndPort.getHostText(), remoteHostAndPort.getPort()), new InetSocketAddress(localHostAndPort.getHostText(), localHostAndPort.getPort()), serverConfig, new RequestBodyReader() { @Override public Promise<? extends ByteBuf> read(long maxContentLength, Block onTooLarge) { return Promise.value(requestBody) .route(r -> r.readableBytes() > maxContentLength, onTooLarge.action()); } @Override public TransformablePublisher<? extends ByteBuf> readStream(long maxContentLength) { return Streams.<ByteBuf>yield( r -> { if (r.getRequestNum() > 0) { return null; } else { return requestBody; } }); } }); if (pathBinding != null) { handler = Handlers.chain( ctx -> { ctx.getExecution().get(PathBindingStorage.TYPE).push(pathBinding); ctx.next(); }, handler); } try { return new DefaultHandlingResult( request, results, responseHeaders, registry, timeout, handler); } catch (Exception e) { throw Exceptions.uncheck(e); } finally { registry.get(ExecController.class).close(); } } @Override public RequestFixture header(CharSequence name, String value) { requestHeaders.add(name, value); return this; } @Override public RequestFixture serverConfig(Action<? super ServerConfigBuilder> action) throws Exception { serverConfigBuilder = ServerConfig.builder(); action.execute(serverConfigBuilder); return this; } @Override public RequestFixture method(String method) { if (method == null) { throw new IllegalArgumentException("method must not be null"); } this.method = method.toUpperCase(); return this; } @Override public RequestFixture pathBinding(Map<String, String> pathTokens) { return pathBinding("", "", pathTokens); } @Override public RequestFixture pathBinding( String boundTo, String pastBinding, Map<String, String> pathTokens) { pathBinding = new DefaultPathBinding( pastBinding, ImmutableMap.copyOf(pathTokens), new RootPathBinding(pastBinding)); return this; } @Override public RequestFixture registry(Action<? super RegistrySpec> action) throws Exception { action.execute(registryBuilder); return this; } @Override public RequestFixture responseHeader(CharSequence name, String value) { responseHeaders.add(name, value); return this; } @Override public RequestFixture timeout(int timeoutSeconds) { if (timeoutSeconds < 0) { throw new IllegalArgumentException("timeout must be > 0"); } this.timeout = timeoutSeconds; return this; } @Override public RequestFixture uri(String uri) { if (uri == null) { throw new NullPointerException("uri cannot be null"); } if (!uri.startsWith("/")) { uri = "/" + uri; } this.uri = uri; return this; } @Override public RequestFixture remoteAddress(HostAndPort remote) { remoteHostAndPort = remote; return this; } @Override public RequestFixture localAddress(HostAndPort local) { localHostAndPort = local; return this; } @Override public RequestFixture protocol(String protocol) { this.protocol = protocol; return this; } private Registry getEffectiveRegistry(final DefaultHandlingResult.ResultsHolder results) { ClientErrorHandler clientErrorHandler = (context, statusCode) -> { results.setClientError(statusCode); context.getResponse().status(statusCode); results.getLatch().countDown(); }; ServerErrorHandler serverErrorHandler = (context, throwable1) -> { results.setThrowable(throwable1); results.getLatch().countDown(); }; final Registry userRegistry = Registry.builder() .add(ClientErrorHandler.class, clientErrorHandler) .add(ServerErrorHandler.class, serverErrorHandler) .build(); return Exceptions.uncheck( () -> { ServerConfig serverConfig = serverConfigBuilder.build(); DefaultExecController execController = new DefaultExecController(serverConfig.getThreads()); return ServerRegistry.serverRegistry( new TestServer(), Impositions.none(), execController, serverConfig, r -> userRegistry.join(registryBuilder.build())); }); } // TODO some kind of impl here private static class TestServer implements RatpackServer { @Override public String getScheme() { throw new UnsupportedOperationException(); } @Override public int getBindPort() { throw new UnsupportedOperationException(); } @Override public String getBindHost() { throw new UnsupportedOperationException(); } @Override public boolean isRunning() { throw new UnsupportedOperationException(); } @Override public void start() throws Exception { throw new UnsupportedOperationException(); } @Override public void stop() throws Exception { throw new UnsupportedOperationException(); } @Override public RatpackServer reload() throws Exception { throw new UnsupportedOperationException(); } } }
@Override public RequestFixture serverConfig(Action<? super ServerConfigBuilder> action) throws Exception { serverConfigBuilder = ServerConfig.builder(); action.execute(serverConfigBuilder); return this; }