Skip to content

Instantly share code, notes, and snippets.

@danhyun
Created December 5, 2014 22:32
Show Gist options
  • Save danhyun/d752924cb7faf79428ff to your computer and use it in GitHub Desktop.
Save danhyun/d752924cb7faf79428ff to your computer and use it in GitHub Desktop.
First example blocks subsequent requests - Ratpack 0.9.11
package ratpack.example.java;
import ratpack.guice.Guice;
import ratpack.handling.Handler;
import ratpack.launch.LaunchConfig;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class HandlerFactory implements ratpack.launch.HandlerFactory {
ExecutorService executorService = Executors.newCachedThreadPool();
@Override
public Handler create(LaunchConfig launchConfig) throws Exception {
// A Handler that makes objects bound to Guice by modules available downstream
return Guice.builder(launchConfig)
.bindings(bindingsSpec -> bindingsSpec.add(new MyModule()))
.build(chain -> chain
.handler("foo", context -> context.render("from the foo handler")) // Map to /foo
.handler("bar", context -> context.render("from the bar handler")) // Map to /bar
.handler("long", context ->
// context.promise(f -> {
// new Thread() {
// @Override
// public void run() {
// try {
// Thread.sleep(10000);
// } catch (InterruptedException e) {
// e.printStackTrace();
// }
// f.success("Success");
// }
// }.run();
// })
context.promise(f -> {
executorService.submit(() -> {
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
e.printStackTrace();
}
f.success("SUCCESS");
});
})
// context.blocking(() -> {
// Thread.sleep(10000);
// return "Success";
// })
.then( a -> context.getResponse().send(a + " long done")))
.prefix("nested", nested -> { // Set up a nested routing block, which is delegated to `nestedHandler`
nested.handler(":var1/:var2?", context -> { // The path tokens are the :var1 and :var2 path components above
Map<String, String> pathTokens = context.getPathTokens();
context.render(
"from the nested handler, var1: " + pathTokens.get("var1") +
", var2: " + pathTokens.get("var2")
);
});
})
.handler("injected", chain.getRegistry().get(MyHandler.class)) // Map to a dependency injected handler
.prefix("static", nested -> nested.assets("assets/images")) // Bind the /static app path to the src/ratpack/assets/images dir
.handler(context -> context.render("root handler!")));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment