Search in sources :

Example 6 with Registry

use of ratpack.registry.Registry in project ratpack by ratpack.

the class SiteMain method main.

public static void main(String... args) throws Exception {
    RxRatpack.initialize();
    RatpackServer.start(b -> b.serverConfig(s -> s.baseDir(BaseDir.find()).env().require("/github", SiteModule.GitHubConfig.class)).registry(Guice.registry(s -> s.module(NewRelicModule.class).module(new AssetPipelineModule()).module(new DropwizardMetricsModule(), c -> c.csv(csv -> csv.enable(false))).module(SiteModule.class).module(MarkupTemplateModule.class, conf -> {
        conf.setAutoNewLine(true);
        conf.setUseDoubleQuotes(true);
        conf.setAutoIndent(true);
    }).module(TextTemplateModule.class, conf -> conf.setStaticallyCompile(true)))).handlers(c -> {
        int longCache = 60 * 60 * 24 * 365;
        int shortCache = 60 * 10;
        c.all(ctx -> {
            String host = ctx.getRequest().getHeaders().get("host");
            if (host != null && (host.endsWith("ratpack-framework.org") || host.equals("www.ratpack.io"))) {
                ctx.redirect(301, "http://ratpack.io" + ctx.getRequest().getRawUri());
                return;
            }
            if (ctx.getRequest().getPath().isEmpty() || ctx.getRequest().getPath().equals("index.html")) {
                ctx.getResponse().getHeaders().set("X-UA-Compatible", "IE=edge,chrome=1");
            }
            ctx.next();
        }).get("index.html", ctx -> {
            ctx.redirect(301, "/");
        }).get(ctx -> ctx.render(groovyMarkupTemplate("index.gtpl"))).get("resources", ctx -> ctx.render(groovyMarkupTemplate("resources.gtpl"))).path("reset", ctx -> ctx.byMethod(methods -> {
            Block impl = () -> {
                ctx.get(GitHubData.class).forceRefresh();
                ctx.render("ok");
            };
            if (ctx.getServerConfig().isDevelopment()) {
                methods.get(impl);
            }
            methods.post(impl);
        })).prefix("versions", v -> v.get(ctx -> ctx.render(ctx.get(RatpackVersions.class).getAll().map(all -> groovyMarkupTemplate("versions.gtpl", m -> m.put("versions", all))))).get(":version", ctx -> ctx.render(ctx.get(RatpackVersions.class).getAll().map(all -> all.version(ctx.getAllPathTokens().get("version"))).onNull(() -> ctx.clientError(404)).flatMap(version -> ctx.get(GitHubData.class).closed(version).map(i -> Pair.of(version, i))).map(p -> groovyMarkupTemplate("version.gtpl", m -> m.put("version", p.left).put("issues", p.right)))))).prefix("manual", c1 -> c1.fileSystem("manual", c2 -> c2.get(ctx -> ctx.redirect(301, "/manual/current")).prefix(":label", c3 -> c3.all(ctx -> {
            String label = ctx.getPathTokens().get("label");
            ctx.get(RatpackVersions.class).getAll().then(all -> {
                if (label.equals("current") || all.isReleased(label)) {
                    ctx.getResponse().getHeaders().add("Cache-Control", "max-age=" + longCache + ", public");
                } else if (label.equals("snapshot") || all.isUnreleased(label)) {
                    ctx.getResponse().getHeaders().add("Cache-Control", "max-age=" + shortCache + ", public");
                }
                RatpackVersion version;
                switch(label) {
                    case "current":
                        version = all.getCurrent();
                        break;
                    case "snapshot":
                        version = all.getSnapshot();
                        break;
                    default:
                        version = all.version(label);
                        if (version == null) {
                            ctx.clientError(404);
                            return;
                        }
                        break;
                }
                ctx.next(Registry.single(ctx.getFileSystemBinding().binding(version.getVersion())));
            });
        }).files(f -> f.indexFiles("index.html"))))).get("robots.txt", ctx -> ctx.get(RatpackVersions.class).getAll().map(RatpackVersions.All::getAll).map(v -> FluentIterable.from(v).transform(i -> "Disallow: /manual/" + i.getVersion()).join(Joiner.on("\n"))).map(s -> "User-agent: *\nDisallow: /manual/snapshot\n" + s).then(ctx::render)).get("favicon.ico", ctx -> {
            ctx.getResponse().getHeaders().add("Cache-Control", "max-age=" + longCache + ", public");
            ctx.next();
        }).files(f -> f.dir("public").indexFiles("index.html"));
    }));
}
Also used : TextTemplateModule(ratpack.groovy.template.TextTemplateModule) RxRatpack(ratpack.rx.RxRatpack) RatpackServer(ratpack.server.RatpackServer) BaseDir(ratpack.server.BaseDir) NewRelicModule(ratpack.newrelic.NewRelicModule) Guice(ratpack.guice.Guice) RatpackVersions(ratpack.site.github.RatpackVersions) Block(ratpack.func.Block) Pair(ratpack.func.Pair) DropwizardMetricsModule(ratpack.dropwizard.metrics.DropwizardMetricsModule) AssetPipelineModule(asset.pipeline.ratpack.AssetPipelineModule) FluentIterable(com.google.common.collect.FluentIterable) Registry(ratpack.registry.Registry) GitHubData(ratpack.site.github.GitHubData) Groovy.groovyMarkupTemplate(ratpack.groovy.Groovy.groovyMarkupTemplate) MarkupTemplateModule(ratpack.groovy.template.MarkupTemplateModule) RatpackVersion(ratpack.site.github.RatpackVersion) Joiner(com.google.common.base.Joiner) MarkupTemplateModule(ratpack.groovy.template.MarkupTemplateModule) RatpackVersions(ratpack.site.github.RatpackVersions) NewRelicModule(ratpack.newrelic.NewRelicModule) AssetPipelineModule(asset.pipeline.ratpack.AssetPipelineModule) GitHubData(ratpack.site.github.GitHubData) Block(ratpack.func.Block) RatpackVersion(ratpack.site.github.RatpackVersion) DropwizardMetricsModule(ratpack.dropwizard.metrics.DropwizardMetricsModule)

Example 7 with Registry

use of ratpack.registry.Registry in project ratpack by ratpack.

the class DefaultRequestFixture method invoke.

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 long getContentLength() {
            return requestBody.readableBytes();
        }

        @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();
    }
}
Also used : RatpackServer(ratpack.server.RatpackServer) HttpVersion(io.netty.handler.codec.http.HttpVersion) ClientErrorHandler(ratpack.error.ClientErrorHandler) RequestFixture(ratpack.test.handling.RequestFixture) RootPathBinding(ratpack.path.internal.RootPathBinding) HandlerTimeoutException(ratpack.test.handling.HandlerTimeoutException) Unpooled.unreleasableBuffer(io.netty.buffer.Unpooled.unreleasableBuffer) ServerRegistry(ratpack.server.internal.ServerRegistry) ByteBuf(io.netty.buffer.ByteBuf) MutableHeaders(ratpack.http.MutableHeaders) PathBindingStorage(ratpack.path.internal.PathBindingStorage) RequestBodyReader(ratpack.server.internal.RequestBodyReader) ServerConfig(ratpack.server.ServerConfig) ServerConfigBuilder(ratpack.server.ServerConfigBuilder) Registry(ratpack.registry.Registry) Map(java.util.Map) CharsetUtil(io.netty.util.CharsetUtil) DefaultPathBinding(ratpack.path.internal.DefaultPathBinding) DefaultRequest(ratpack.http.internal.DefaultRequest) Unpooled.buffer(io.netty.buffer.Unpooled.buffer) DefaultExecController(ratpack.exec.internal.DefaultExecController) Streams(ratpack.stream.Streams) RegistryBuilder(ratpack.registry.RegistryBuilder) ServerErrorHandler(ratpack.error.ServerErrorHandler) ImmutableMap(com.google.common.collect.ImmutableMap) HttpMethod(io.netty.handler.codec.http.HttpMethod) Promise(ratpack.exec.Promise) Block(ratpack.func.Block) Instant(java.time.Instant) HostAndPort(com.google.common.net.HostAndPort) InetSocketAddress(java.net.InetSocketAddress) Chain(ratpack.handling.Chain) RegistrySpec(ratpack.registry.RegistrySpec) Impositions(ratpack.impose.Impositions) DefaultHttpHeaders(io.netty.handler.codec.http.DefaultHttpHeaders) HandlingResult(ratpack.test.handling.HandlingResult) Action(ratpack.func.Action) Handler(ratpack.handling.Handler) Exceptions(ratpack.util.Exceptions) TransformablePublisher(ratpack.stream.TransformablePublisher) HttpHeaderNames(io.netty.handler.codec.http.HttpHeaderNames) Handlers(ratpack.handling.Handlers) NettyHeadersBackedMutableHeaders(ratpack.http.internal.NettyHeadersBackedMutableHeaders) ExecController(ratpack.exec.ExecController) TransformablePublisher(ratpack.stream.TransformablePublisher) DefaultRequest(ratpack.http.internal.DefaultRequest) InetSocketAddress(java.net.InetSocketAddress) DefaultExecController(ratpack.exec.internal.DefaultExecController) ExecController(ratpack.exec.ExecController) ByteBuf(io.netty.buffer.ByteBuf) RequestBodyReader(ratpack.server.internal.RequestBodyReader) HandlerTimeoutException(ratpack.test.handling.HandlerTimeoutException) ServerConfig(ratpack.server.ServerConfig) Promise(ratpack.exec.Promise) Block(ratpack.func.Block)

Example 8 with Registry

use of ratpack.registry.Registry in project ratpack by ratpack.

the class Pac4jAuthenticator method handle.

@Override
public void handle(Context ctx) throws Exception {
    PathBinding pathBinding = ctx.getPathBinding();
    String pastBinding = pathBinding.getPastBinding();
    if (pastBinding.equals(path)) {
        RatpackWebContext.from(ctx, true).flatMap(webContext -> {
            SessionData sessionData = webContext.getSession();
            return createClients(ctx, pathBinding).map(clients -> clients.findClient(webContext)).map(Types::<Client<Credentials, UserProfile>>cast).flatMap(client -> getProfile(webContext, client)).map(profile -> {
                if (profile != null) {
                    sessionData.set(Pac4jSessionKeys.USER_PROFILE, profile);
                }
                Optional<String> originalUrl = sessionData.get(Pac4jSessionKeys.REQUESTED_URL);
                sessionData.remove(Pac4jSessionKeys.REQUESTED_URL);
                return originalUrl;
            }).onError(t -> {
                if (t instanceof RequiresHttpAction) {
                    webContext.sendResponse((RequiresHttpAction) t);
                } else {
                    ctx.error(new TechnicalException("Failed to get user profile", t));
                }
            });
        }).then(originalUrlOption -> {
            ctx.redirect(originalUrlOption.orElse("/"));
        });
    } else {
        createClients(ctx, pathBinding).then(clients -> {
            Registry registry = Registry.singleLazy(Clients.class, () -> uncheck(() -> clients));
            ctx.next(registry);
        });
    }
}
Also used : Types(ratpack.util.Types) Context(ratpack.handling.Context) RatpackPac4j(ratpack.pac4j.RatpackPac4j) Exceptions.uncheck(ratpack.util.Exceptions.uncheck) Promise(ratpack.exec.Promise) PublicAddress(ratpack.server.PublicAddress) Blocking(ratpack.exec.Blocking) RequiresHttpAction(org.pac4j.core.exception.RequiresHttpAction) WebContext(org.pac4j.core.context.WebContext) List(java.util.List) ImmutableList(com.google.common.collect.ImmutableList) Clients(org.pac4j.core.client.Clients) Client(org.pac4j.core.client.Client) Handler(ratpack.handling.Handler) Registry(ratpack.registry.Registry) Optional(java.util.Optional) PathBinding(ratpack.path.PathBinding) TechnicalException(org.pac4j.core.exception.TechnicalException) UserProfile(org.pac4j.core.profile.UserProfile) SessionData(ratpack.session.SessionData) Credentials(org.pac4j.core.credentials.Credentials) Types(ratpack.util.Types) RequiresHttpAction(org.pac4j.core.exception.RequiresHttpAction) TechnicalException(org.pac4j.core.exception.TechnicalException) UserProfile(org.pac4j.core.profile.UserProfile) SessionData(ratpack.session.SessionData) Registry(ratpack.registry.Registry) PathBinding(ratpack.path.PathBinding) Credentials(org.pac4j.core.credentials.Credentials)

Aggregations

Registry (ratpack.registry.Registry)8 Handler (ratpack.handling.Handler)5 ServerConfig (ratpack.server.ServerConfig)5 ClientErrorHandler (ratpack.error.ClientErrorHandler)4 ServerErrorHandler (ratpack.error.ServerErrorHandler)4 Promise (ratpack.exec.Promise)4 Action (ratpack.func.Action)4 Block (ratpack.func.Block)4 Instant (java.time.Instant)3 ExecController (ratpack.exec.ExecController)3 ImmutableMap (com.google.common.collect.ImmutableMap)2 Lists (com.google.common.collect.Lists)2 HostAndPort (com.google.common.net.HostAndPort)2 ByteBuf (io.netty.buffer.ByteBuf)2 Unpooled.buffer (io.netty.buffer.Unpooled.buffer)2 Unpooled.unreleasableBuffer (io.netty.buffer.Unpooled.unreleasableBuffer)2 DefaultHttpHeaders (io.netty.handler.codec.http.DefaultHttpHeaders)2 HttpHeaderNames (io.netty.handler.codec.http.HttpHeaderNames)2 HttpMethod (io.netty.handler.codec.http.HttpMethod)2 HttpVersion (io.netty.handler.codec.http.HttpVersion)2