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"));
}));
}
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();
}
}
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);
});
}
}
Aggregations