This document provides an overview of Ratpack, an open-source web framework for Java and Groovy applications. It summarizes Ratpack's key features including its non-blocking and high performance architecture using Netty, support for Groovy and Java, integration with build tools like Gradle, and handler-based routing model. The document also discusses how Ratpack handles asynchronous operations, blocking operations, and real-time capabilities like server-sent events.
Overview of the Ratpack web framework.
Source for the talk (including demo apps) here:
https://github.com/ratpack/ratpack-talks/tree/master/talks/cdjdn
Overview of the Ratpack web framework.
Source for the talk (including demo apps) here:
https://github.com/ratpack/ratpack-talks/tree/master/talks/cdjdn
Gradle is an open source build automation system that builds upon the concepts of Apache Ant and Apache Maven and introduces a Groovy-based domain-specific language (DSL) instead of the XML form used by Apache Maven for declaring the project configuration.
This presentation was held at the Spring One 2GX 2015 conference in Washington DC.
The presentation explains how to migrate an existing Grails 2 application to the new Spring Boot and Gradle based Grails 3. It covers migrating plugins, applications and features gotchas as well as best praciteces.
The conference presentation also included an extensive live coding section in which I migrated an existing application to Grails 3.
The Making of the Oracle R2DBC Driver and How to Take Your Code from Synchron...VMware Tanzu
SpringOne 2021
Session Title:The Making of the Oracle R2DBC Driver and How to Take Your Code from Synchronous to Reactive
Speakers: Kuassi Mensah, Director of Product Management at Oracle; Michael McMahon, Principal Member of Technical Staff at Oracle
Adoptar o implementar nuevas tecnologías a nuestros sistemas basados en Java tiene muchos ángulos de análisis que van más allá de lo técnico.
En esta sesion veremos 10 formas prácticas y efectivas en las que puedes contribuir activamente en el ecosistema Cloud Native de Java con JakartaEE y Apache TomEE.
Con esta información podrás tomar mejores decisiones en las mejoras continuas de tus arquitecturas y sistemas basados en java.
Spring Boot on Amazon Web Services with Spring Cloud AWSVMware Tanzu
SpringOne 2021
Session Title: Spring Boot on Amazon Web Services with Spring Cloud AWS
Speakers: Maciej Walkowiak, Software Consultant at Independent; Matej Nedic, Software engineer at Ingemark
These slides highlight what’s new in Grails® framework 5, Micronaut Integration, Groovy 3, and the current developments around Grails framework.
It is originally presented at Madrid GUG on 15 December, 2021.
Google App Engine (GAE) is a popular PaaS offering. Where its scalable and reliable environment is hidden behind a custom API. This makes GAE apps hard to port over to other non-GAE environments.
But what if one could implement such similar environment? And you could simply move your GAE application’s .war file to this new environment and it would just work?
After all, at the end it’s all about the API, plus scalable and reliable services.
JBoss CapeDwarf project aims at making this a reality. This presentation will provide a glimpse into what it takes to implement something as GAE, ranging from runtime integration with JBoss Application Server, actual services implementation to last but not least, automated heavy testing.
Gradle is a general-purpose build automation tool. It combines the power and flexibility of Ant with the dependency management and conventions of Maven into a more effective way to build. Its powered by Groovy DSL. Presentation discusses what and why Gradle with demo for java, groovy, web, multi-project and grails projects.
The new GraalVM from Oracle supports multiple language including JavaScript, Python, Ruby, R, C++ as well as Java and other JVM languages. This opens up interesting possibilities for polygot enterprise applications. Now you can use a Node library in a Java application or call an R statistical function from an EJB. Previously, this type of integration was extremely challenging. This session will provide recipes to get up and running along with best practices and some cool demos.
Code: https://github.com/rcuprak/graalvm_jee
7 recomendaciones para migrar tus aplicaciones a Jakarta EE utilizando Apache...César Hernández
Con el impacto en el ecosistema después de la migración del paquete javax a Jakarta en Jakarta EE 9 y el soporte para Java SE 11 en Jakarta EE 9.1, esta sesión cubre recomendaciones y estrategias para ayudarlo a navegar el proceso de migración a Jakarta EE 9.1 usando Apache TomEE .
One of the goals of Grails 3 is to reach out of the servlet container. Grails 3 has a concept of application profiles for choosing a certain set of core plugins to use. In this talk Lari will present how Ratpack fits in Grails 3. He will also talk about how Grails 3 supports micro service architectures.
Gradle is an open source build automation system that builds upon the concepts of Apache Ant and Apache Maven and introduces a Groovy-based domain-specific language (DSL) instead of the XML form used by Apache Maven for declaring the project configuration.
This presentation was held at the Spring One 2GX 2015 conference in Washington DC.
The presentation explains how to migrate an existing Grails 2 application to the new Spring Boot and Gradle based Grails 3. It covers migrating plugins, applications and features gotchas as well as best praciteces.
The conference presentation also included an extensive live coding section in which I migrated an existing application to Grails 3.
The Making of the Oracle R2DBC Driver and How to Take Your Code from Synchron...VMware Tanzu
SpringOne 2021
Session Title:The Making of the Oracle R2DBC Driver and How to Take Your Code from Synchronous to Reactive
Speakers: Kuassi Mensah, Director of Product Management at Oracle; Michael McMahon, Principal Member of Technical Staff at Oracle
Adoptar o implementar nuevas tecnologías a nuestros sistemas basados en Java tiene muchos ángulos de análisis que van más allá de lo técnico.
En esta sesion veremos 10 formas prácticas y efectivas en las que puedes contribuir activamente en el ecosistema Cloud Native de Java con JakartaEE y Apache TomEE.
Con esta información podrás tomar mejores decisiones en las mejoras continuas de tus arquitecturas y sistemas basados en java.
Spring Boot on Amazon Web Services with Spring Cloud AWSVMware Tanzu
SpringOne 2021
Session Title: Spring Boot on Amazon Web Services with Spring Cloud AWS
Speakers: Maciej Walkowiak, Software Consultant at Independent; Matej Nedic, Software engineer at Ingemark
These slides highlight what’s new in Grails® framework 5, Micronaut Integration, Groovy 3, and the current developments around Grails framework.
It is originally presented at Madrid GUG on 15 December, 2021.
Google App Engine (GAE) is a popular PaaS offering. Where its scalable and reliable environment is hidden behind a custom API. This makes GAE apps hard to port over to other non-GAE environments.
But what if one could implement such similar environment? And you could simply move your GAE application’s .war file to this new environment and it would just work?
After all, at the end it’s all about the API, plus scalable and reliable services.
JBoss CapeDwarf project aims at making this a reality. This presentation will provide a glimpse into what it takes to implement something as GAE, ranging from runtime integration with JBoss Application Server, actual services implementation to last but not least, automated heavy testing.
Gradle is a general-purpose build automation tool. It combines the power and flexibility of Ant with the dependency management and conventions of Maven into a more effective way to build. Its powered by Groovy DSL. Presentation discusses what and why Gradle with demo for java, groovy, web, multi-project and grails projects.
The new GraalVM from Oracle supports multiple language including JavaScript, Python, Ruby, R, C++ as well as Java and other JVM languages. This opens up interesting possibilities for polygot enterprise applications. Now you can use a Node library in a Java application or call an R statistical function from an EJB. Previously, this type of integration was extremely challenging. This session will provide recipes to get up and running along with best practices and some cool demos.
Code: https://github.com/rcuprak/graalvm_jee
7 recomendaciones para migrar tus aplicaciones a Jakarta EE utilizando Apache...César Hernández
Con el impacto en el ecosistema después de la migración del paquete javax a Jakarta en Jakarta EE 9 y el soporte para Java SE 11 en Jakarta EE 9.1, esta sesión cubre recomendaciones y estrategias para ayudarlo a navegar el proceso de migración a Jakarta EE 9.1 usando Apache TomEE .
One of the goals of Grails 3 is to reach out of the servlet container. Grails 3 has a concept of application profiles for choosing a certain set of core plugins to use. In this talk Lari will present how Ratpack fits in Grails 3. He will also talk about how Grails 3 supports micro service architectures.
Concurrent Collections — набор коллекций, более эффективно работающие в многопоточной среде нежели стандартные универсальные коллекции из java.util пакета. Вместо базового враппера Collections.synchronizedList с блокированием доступа ко всей коллекции используются блокировки по сегментам данных или же оптимизируется работа для параллельного чтения данных по wait-free алгоритмам.
Queues — неблокирующие и блокирующие очереди с поддержкой многопоточности. Неблокирующие очереди заточены на скорость и работу без блокирования потоков. Блокирующие очереди используются, когда нужно «притормозить» потоки «Producer» или «Consumer», если не выполнены какие-либо условия, например, очередь пуста или перепонена, или же нет свободного «Consumer»'a.
Synchronizers — вспомогательные утилиты для синхронизации потоков. Представляют собой мощное оружие в «параллельных» вычислениях.
Executors — содержит в себе отличные фрейморки для создания пулов потоков, планирования работы асинхронных задач с получением результатов.
Locks — представляет собой альтернативные и более гибкие механизмы синхронизации потоков по сравнению с базовыми synchronized, wait, notify, notifyAll.
Atomics — классы с поддержкой атомарных операций над примитивами и ссылками.
Лекция для сотрудников фирмы Soft-logic, проведенная 25.12.2014. В ходе лекции рассматривались следующие ключевые моменты:
1. Постановка проблемы. Паттерн пул потоков
- Проблема производительности
- Описание паттерна в общем виде
- Основные два подхода к запуску задач
- Три стратегии организации пулов потоков
2. Интерфейсы и классы взаимодействия с пулами потоков
- Интерфейсы ExecutorService, ScheduledExecutorService
- Реализации ThreadPoolExecutor, ScheduledThreadPoolExecutor
- Интерфейсы Runnable, Callable<v>,Future<v>, RunnableFuture<v>
3. Фабрика пулов Executors
- CachedThreadPool
- SingleThreadExecutor
- FixedThreadPool
- ThreadScheduledExecutor
- WorkStealingPool
4. Классы задач
- ForkJoinTask, RecursiveTask, RecursiveAction
- CompletableFuture<v>
5. ForkJoinPool
- Особенности производительности
- Общий пул ява машины
Build Highly scalable systems demand special care in which regards Engineering and Operation. Maintain/support a cluster with hundred/thousand of servers is a quite complex task.
This is a presentation about Apache Mesos and how It helps to manage clusters in an efficient way.
PC = Personal Cloud (or how to use your development machine with Vagrant and ...Codemotion
by Andrey Adamovich - Have you ever wished to run production clone on your laptop to find that annoying bug? With decreasing hardware costs and growing hardware performance characteristics it becomes possible. Virtualization tools like VirtualBox come very handy at simulating real OS with real setup. Tools like Vagrant (VirtualBox wrapper) make it even easier. This presentation gives several hands-on demonstrations of Vagrant capabilities and the simplicity of integrating that into your normal development cycle.
Multithreading in java past and actualYevgen Levik
In this talk I’d like to give you an overview of java.util.concurrent package and represent useful Java concurrency tools. I’ll cover the core functionality and the state-of-the-art API (Executors, Accumulators, StampedLock etc).
Simple examples in github (https://github.com/levik666/OverviewInJavaUtilConcurrent)
Presentation on reactor design pattern should introduce you a pattern that our server’s core is based on. We will try to give away all pros and cons about it. This pattern is used to simplify development of highly concurrent servers by separating business logic from communication. This is very technical presentation, but it is designed for beginners so it should be understandable to anyone with basic software engineering skills.
"WTF is Twisted? (or; owl amongst the ponies)" is a talk that introduces the Twisted asynchronous programming framework, how it works, and what uses it.
This is a presentation for International Lisp Conference 2012 which was held in Kyoto, Japan.
Clack is a web application environment for Common Lisp to make your web applications be portable and reusable by abstracting HTTP into a simple API.
In this paper, I describe what are problems in web development and how Clack solves them.
Intro to node.js - Ran Mizrahi (27/8/2014)Ran Mizrahi
Node.js is a platform built on Chrome V8 javascript runtime engine for building fast and scalable, non-blocking, real-time and network applications. In this session Ran will introduce node.js and how to develop large code bases using it. He'll cover the following aspects:
• What is node.js?
• Apache vs. Nginx performance (One thread per connection vs. event loop) and what it has to do with node.js.
• Why node was written in Javascript?
• Main tools and frameworks (Express, socket.io, mongoose etc.)
• TDD/BDD with node.js using mocha and Chai.
Ran Mizrahi, Founder of CoCycles, Passionate entrepreneur and software engineer who loves to continuously innovate and deliver meaningful products while having true fun with the right team.
Lessons Learned From PayPal: Implementing Back-Pressure With Akka Streams And...Lightbend
Akka Streams and its amazing handling of streaming with back-pressure should be no surprise to anyone. But it takes a couple of use cases to really see it in action - especially in use cases where the amount of work continues to increase as you’re processing it. This is where back-pressure really shines.
In this talk for Architects and Dev Managers by Akara Sucharitakul, Principal MTS for Global Platform Frameworks at PayPal, Inc., we look at how back-pressure based on Akka Streams and Kafka is being used at PayPal to handle very bursty workloads.
In addition, Akara will also share experiences in creating a platform based on Akka and Akka Streams that currently processes over 1 billion transactions per day (on just 8 VMs), with the aim of helping teams adopt these technologies. In this webinar, you will:
*Start with a sample web crawler use case to examine what happens when each processing pass expands to a larger and larger workload to process.
*Review how we use the buffering capabilities in Kafka and the back-pressure with asynchronous processing in Akka Streams to handle such bursts.
*Look at lessons learned, plus some constructive “rants” about the architectural components, the maturity, or immaturity you’ll expect, and tidbits and open source goodies like memory-mapped stream buffers that can be helpful in other Akka Streams and/or Kafka use cases.
Our new product (Clicktale Experience cloud) requires processing up to half a million messages per second, sessionizing each "users" journey throughout a web page. In this talk we'll discuss how we have achieved that using Spark's stateful streaming capabilities with only few servers in production, the challenges we've faced and how we've solved them. We'll also take a look at Spark 2.2 (the brand new version) and its new stateful aggregation and talk about how we've used it in order to improve performance significantly.
Virtual Flink Forward 2020: How Streaming Helps Your Staging Environment and ...Flink Forward
In this session, we will look at how Apache Flink can be used to stream anonymized API request and response data from a production environment to make sure staging environments are up-to-date and reflect the most recent features (and bugs) that comprise a service. The talk will also examine how to deal with issues of data retention, throttling, and persistence, finishing with recommendations for how to use these sandbox environments to rapidly prototype and test new features and fixes.
Modern application development with oracle cloud sangam17Vinay Kumar
How Oracle cloud helps in building modern application development. This explains Oracle Application container cloud with developer cloud service and etc. Spring boot application deployed in Oracle ACCS and CI/CD part done in Oracle Developer cloud service.
Slides from my GGX 2013 talk. http://skillsmatter.com/podcast/home/message-driven-architecture-in-grails
Code here: https://github.com/danveloper/ggx-2013-mda
DevOps and Testing slides at DASA ConnectKari Kakkonen
My and Rik Marselis slides at 30.5.2024 DASA Connect conference. We discuss about what is testing, then what is agile testing and finally what is Testing in DevOps. Finally we had lovely workshop with the participants trying to find out different ways to think about quality and testing in different parts of the DevOps infinity loop.
Securing your Kubernetes cluster_ a step-by-step guide to success !KatiaHIMEUR1
Today, after several years of existence, an extremely active community and an ultra-dynamic ecosystem, Kubernetes has established itself as the de facto standard in container orchestration. Thanks to a wide range of managed services, it has never been so easy to set up a ready-to-use Kubernetes cluster.
However, this ease of use means that the subject of security in Kubernetes is often left for later, or even neglected. This exposes companies to significant risks.
In this talk, I'll show you step-by-step how to secure your Kubernetes cluster for greater peace of mind and reliability.
The Art of the Pitch: WordPress Relationships and SalesLaura Byrne
Clients don’t know what they don’t know. What web solutions are right for them? How does WordPress come into the picture? How do you make sure you understand scope and timeline? What do you do if sometime changes?
All these questions and more will be explored as we talk about matching clients’ needs with what your agency offers without pulling teeth or pulling your hair out. Practical tips, and strategies for successful relationship building that leads to closing the deal.
Epistemic Interaction - tuning interfaces to provide information for AI supportAlan Dix
Paper presented at SYNERGY workshop at AVI 2024, Genoa, Italy. 3rd June 2024
https://alandix.com/academic/papers/synergy2024-epistemic/
As machine learning integrates deeper into human-computer interactions, the concept of epistemic interaction emerges, aiming to refine these interactions to enhance system adaptability. This approach encourages minor, intentional adjustments in user behaviour to enrich the data available for system learning. This paper introduces epistemic interaction within the context of human-system communication, illustrating how deliberate interaction design can improve system understanding and adaptation. Through concrete examples, we demonstrate the potential of epistemic interaction to significantly advance human-computer interaction by leveraging intuitive human communication strategies to inform system design and functionality, offering a novel pathway for enriching user-system engagements.
Key Trends Shaping the Future of Infrastructure.pdfCheryl Hung
Keynote at DIGIT West Expo, Glasgow on 29 May 2024.
Cheryl Hung, ochery.com
Sr Director, Infrastructure Ecosystem, Arm.
The key trends across hardware, cloud and open-source; exploring how these areas are likely to mature and develop over the short and long-term, and then considering how organisations can position themselves to adapt and thrive.
Generative AI Deep Dive: Advancing from Proof of Concept to ProductionAggregage
Join Maher Hanafi, VP of Engineering at Betterworks, in this new session where he'll share a practical framework to transform Gen AI prototypes into impactful products! He'll delve into the complexities of data collection and management, model selection and optimization, and ensuring security, scalability, and responsible use.
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...UiPathCommunity
💥 Speed, accuracy, and scaling – discover the superpowers of GenAI in action with UiPath Document Understanding and Communications Mining™:
See how to accelerate model training and optimize model performance with active learning
Learn about the latest enhancements to out-of-the-box document processing – with little to no training required
Get an exclusive demo of the new family of UiPath LLMs – GenAI models specialized for processing different types of documents and messages
This is a hands-on session specifically designed for automation developers and AI enthusiasts seeking to enhance their knowledge in leveraging the latest intelligent document processing capabilities offered by UiPath.
Speakers:
👨🏫 Andras Palfi, Senior Product Manager, UiPath
👩🏫 Lenka Dulovicova, Product Program Manager, UiPath
2. • Member of the Ratpack core team
• Work at Netflix
• Writing Learning Ratpack for O’Reilly
• Follow me on Twitter: @danveloper
3. • A full-stack, high throughput, non-blocking
web framework
• Built entirely on Java 8
• Specialized support for writing apps in Groovy
4. • Groovy has come a long way over the last few
years…
• Static compilation and (optional) compile time type
checking
• Excellent language for writing concise DSLs
• DSLs can be statically compiled!
Why Groovy?
5. • Groovy’s three compilation modes give
applications a lot of flexibility
• Parallels Java performance using Invoke Dynamic
or Static Compilation
• Pick-and-choose static or dynamic, depending on
the use-case!
Why Groovy?
6. • Requires Groovy 2.3.6+
• Utilize advanced static compilation and type
checking features of Groovy, like @DelegatesTo
• Allows you to define your application structure in a
ratpack.groovy file
Why Groovy?
8. • There are no plugins in Ratpack, instead the
framework provides functionality through modules
• Modules are built in Guice*
• DI is an abstraction in Ratpack, so even though the
framework uses Guice, you don’t have to
*
h$ps://github.com/google/guice
9. • A set of composable libraries for building
unopinionated, rich web applications
• Pick-and-choose what aspects of the
framework you want
• No lock-in to a single way of doing things
10. • Emphasis on Performance and Efficiency in both applications
and development experience
• Hot reloading is available during development time
• Beautiful development-time error pages
• Extreme emphasis on developer testing, especially functional
and integration
• Support for mocking nearly all aspects of the framework
12. • Convention over configuration taken too far
doesn’t let you wire things together
• Ratpack makes wiring modules a “one-liner”, so
there’s not a lot of work to get new features
integrated
• Out of the box support for Guice and Spring
(Spring Boot) DI
13. • Gradle integration makes building robust
projects easy to do
• Simple apps can be run entirely through
the Groovy command-line
14. buildscript {
repositories {
jcenter()
maven { url "http://oss.jfrog.org/oss-snapshot-local" }
maven { url "http://clinker.netty.io/nexus/content/repositories/snapshots" }
}
dependencies {
classpath 'io.ratpack:ratpack-gradle:0.9.13-SNAPSHOT'
}
}
apply plugin: 'io.ratpack.ratpack-java'
Simple Gradle Build Script*
* Ratpack 0.9.13 will be released on Feb 1, 2014
15. • Any non-trivial application needs build and
packaging capabilities
• The Ratpack Gradle plugin provides all the
fixtures to support building web
application projects
16. • Ratpack is built on Netty, which provides
the infrastructure for highly performant,
non-blocking networking
17. • Netty is an extremely mature, super low-level
networking library
• Excellent documentation, very involved
community
• Heavy emphasis on high throughput and
performance
18. • Netty provides the infrastructure for non-
blocking networking, but doesn’t help
much in the way of web application
structure
• Provides an asynchronous API for working
with network data (including HTTP)
19. • Computers “think” very good in asynchronous
terms; humans do not…
• Without app structure, programming toward this
paradigm is difficult
• Ratpack ensures the most performant structures of
Netty are being utilized, while providing a sensible
app structure and programming model
20. • Ratpack provides applications with a Netty-based, non-
blocking HTTP client
• Can be used to integrate with external RESTful services
• Utilizes the same event loop as the server, so resources
are appropriately utilized
• Provides a robust API for programmatically crafting
requests
23. • The JVM doesn’t have any concept of continuations, so
the only option we have is asynchronous APIs
• Async APIs allow callers to provide a completion
handler (or callback), which is to be invoked when some
processing has finished
• There is no temporal relationship between the caller
and the invocation of the callback
24. handler { req, res ->!
... (1) do some work ...!
!
async {!
... (2) do some async work ...!
}!
async {!
... (3) do some more async ...!
}!
!
... (4) send response ...!
}!
(1) – Definitely finishes first
(2) – May finish before or after (3)
and (4)
(3) – May finish before or after (2) or
(4)
(4) – May finish before or after (2) or
(3)
Async APIs create non-determinism in control flow
25. • The temporal disconnect creates non-determinism
in request processing
• This is a big problem for web applications, because
they demand a deterministic control flow
• Ratpack provides the concept of an Execution,
which creates determinism in asynchronous
processing
26. handler { req, res ->!
... (1) do some work ...!
!
async {!
... (3) do some async work ...!
}!
async {!
... (4) do some more async ...!
}!
!
... (2) send response ...!
}!
(1) – Definitely finishes first
(3) – Definitely finishes third
(4) – Definitely finishes fourth
(2) – Definitely finishes second
Ratpack creates a deterministic control flow
27. • Through Ratpack’s promise API, the Execution
is able to schedule async segments to be
invoked after the handler code has finished
• Promise API ensures that developers can work
with asynchronous processing in a sensible
way
28. • In non-blocking, it is of paramount importance
to not block the thread
• Since a single thread is handling processing
for many clients, blocking one blocks all
• Need to adopt libraries that are non-blocking
or provide async APIs
• This is not always practical…
29. • Not all interfaces are able to be non-blocking or
asynchronous
• Most non-blocking frameworks force you to be either
entirely async or wholesale define your handlers as
blocking
• This is limiting and makes it difficult to work with legacy
APIs or those not crafted for non-blocking work
• Ratpack gives you a mechanism to define blocking
execution segments in your handler code
30. handler(r -> (ctx) -> {
ModelDAO dao = ctx.get(ModelDAO.class);
ctx.blocking(() ->
dao.load(ctx.getPathTokens().get("id")))
.then(model -> {
... do some work with the data ...
ctx.render(model);
});
})
Handler with blocking operation
31. • Blocking operations are scheduled to an I/O
bound thread pool
• Once the blocking operation is completed,
the data is then returned to the request taking
thread, where processing can finish
• Blocking operations are invoked when they
are subscribed to in the request-taking thread
32. ...
ctx.blocking(() -> {
... do some blocking io ...
return result;
}).then(result -> {
... subscribe to the blocking promise ...
... process in the request-taking thread ...
})
...
Blocking with a subscription
33. • Data is being delivered to web consumers in
an increasingly real time way
• Web applications must be able to support
streaming protocols like SSE and WebSockets
• Ratpack has built-in fixtures that make it easy
to develop real-time web applications
34. • Because of its non-blocking nature, Ratpack can
support a high volume of concurrent real-time
streams
• Valuable in app-to-app communication too, where
a consumer wants to be reactively informed about
some data
• Ratpack’s HTTP client also supports reading
streams of data from external producers, making
stream processing a great integration
35.
36. • Ratpack applications are defined through a
handler chain
• Handler chain is a programmatic construct
for managing the flow of request data
• Handlers can be bound to request path
routes and HTTP verbs
37. import static ratpack.groovy.Groovy.ratpack!
!
ratpack {!
handlers {!
get {!
response.send "I'm the default route!"!
}!
get("route1") {!
response.send "I'm in route1"!
}!
get("route2/:param") {!
response.send "I'm in route2 and received param: ${pathTokens.param}"!
}!
}!
}!
Handler chain in a Ratpack Script-backed app
38. RatpackServer.start(b -> b
.config(ServerConfig.noBaseDir())
.handlers(chain -> chain
.get(ctx -> ctx.getResponse()
.send("I'm in the default route!"))
!
.get("route1", (ctx) -> ctx.getResponse()
.send("I'm in route1!"))
!
.get("route2/:param", (ctx) -> ctx.getResponse()
.send(String
.format(” received param: %s",
ctx.getPathTokens().get("param"))))
)
);"
Handler chain in using Java 8 APIs
39. • Ratpack applications are defined through a
handler chain
• Handler chain is a programmatic construct
for managing the flow of request data
• Handlers can be bound to request path
routes and HTTP verbs
40. handlers {!
get { ... }!
get("route") { ... }!
!
post { ... }!
post("route") { ... }!
!
put { ... }!
put("route") { ... }!
!
delete { ... }!
delete("route") { ... }!
!
patch { ... }!
patch("route") { ... }!
}!
Semantic handler API for binding to HTTP verbs and routes
41. • Handlers can be nested within a route…
handlers {
prefix("api") { ModelDAO dao ->
get {
blocking { dao.getAll() }.
then { models -> render JsonOutput.toJson(models) }
}
post {
Model model = parse(fromJson(Model))
blocking { dao.save(model) }.
then { m -> render m }
}
put(":id") {
blocking { dao.load(pathTokens.id) }.
map { model -> model.merge(parse(fromJson(Model))) }.
blockingMap { model -> dao.save(model) }.
then { model -> render model }
}
}
}!
42. • There’s a special handler type for serving
static assets from the app’s baseDir!
• Static assets must be defined as the last
handler in the chain
• Can be scoped to routes
43. • Use the assets handler to serve static content
handlers {
prefix("api") {
get {
response.send "some API data"
}
}
assets("public", "index.html”)
}!
44. • You can also use a handler with byMethod to perform common processing
within a route…
handlers {
handler("api") { ModelDAO dao ->
dao.beginTransaction()
byMethod {
get {}
post {}
put {}
delete {}
}
dao.endTransaction()
}!
}!
45. • Can discriminate on content type, allowing you to build HyperMedia APIs…
handlers {
handler {
byContent {
json {
response.send(toJson([msg: "regular json"]))
}
xml {
response.send(...)
}
type("application/vnd.app.org+json;v=1") {
response.send(toJson([newmsg: "hypermedia json"]))
}
}
}
}!
46. • Handlers define the edge of your application
• In Servlet API terms, handlers can be thought
of as a marriage between filters and servlets
• Allows request introspection and
programmatic injection of handler chain
47. • This allows handlers to be constructed and dependency injected, etc…
class UserHandler implements Handler {
private final String message
UserHandler(String message) {
this.message = message
}
@Override
void handle(Context context) !
!throws Exception {
context.response.send(message)
}
}!
ratpack {
bindings {
bindInstance(new UserHandler("user handler"))
}
handlers {
handler { UserHandler userHandler ->
if (request!
.headers.contains("X-Routing-Header")) {
def routingHeader = request!
.headers.get("X-Routing-Header")
if (routingHeader == "user") {
insert(userHandler)
}
}
next()
}
get {
response.send "default system handler"
}
}
}!
New
Handler
is
programma1cally
inserted
into
the
processing
chain
48.
49. • Dependency injection is an abstraction in
Ratpack, through the concept of a Registry
• Components are bound to, and resolvable
from, a Registry instance
• Registries can be backed in a DI framework
50. • Out of the box support for Guice and Spring
Boot
• Registries can be inherited, allowing
components to be resolved in a cascading
manner
• Every request context gets a registry that
components can be extracted from
51. • In a Groovy script that uses closures as
handlers, the variable arguments to that
closure are “injected” from the registry
• In Java 8, they are able to be resolved from
the request context object
52. • You don’t need to use a DI framework to get injection support, you can build
your own registry from objects you construct…
public static void main(String[] args) throws Exception {
Registry registry = Registries.registry()
.add(new ModelDAO()).add(new DB()).build();
RatpackServer.start(spec -> spec
.config(ServerConfig.noBaseDir())
.handlers(chain -> {
chain.register(registry);
chain.handler(":id", ctx -> {
ModelDAO dao = ctx.get(ModelDAO.class);
ctx.blocking(() ->
dao.load(ctx.getPathTokens().get("id")))
.then(ctx::render);
});
})
);
}!
53. • Variables arguments to Groovy closure handlers are resolved from the
registry
def myRegistry = Registries.registry()
.add(new ModelDAO())
.build()
ratpack {
handlers {
register(myRegistry)
prefix("api") {
get(":id") { ModelDAO dao ->
render dao.load(pathTokens.id)
}
}
assets("public", "index.html”)
}
}!
54. • In Groovy, you get a bindings block, which you can use to bind components
to the Registry. With Guice, annotations can be used to Inject
class UserHandler implements Handler {
private final ModelDAO dao
@javax.inject.Inject!
UserHandler(ModelDAO dao) {
this.message = message
}
@Override
void handle(Context ctx) !
!throws Exception {
ctx.blocking {!
dao.getAll()!
} then { ctx.render(it) }
}
}!
ratpack {
bindings {
binder { b ->
b.bind(ModelDAO).in(Scopes.SINGLETON)
b.bind(UserHandler).in(Scopes.SINGLETON)
}
}!
handlers {
handler { UserHandler userHandler ->
if (request!
.headers.contains("X-Routing-Header")) {
def routingHeader = request!
.headers.get("X-Routing-Header")
if (routingHeader == "user") {
insert(userHandler)
}
}
next()
}
get {
response.send "default system handler"
}
}
}!
Can
get
a
handle
on
a
Guice
binder
to
perform
annota1on-‐based
Injec1ng
55. • Likewise, a Guice Module can be “added” to the registry…
ratpack {
bindings {!
// Any Guice module can be added this way!
// this is how Ratpack modules are"
// introduced... "
add(new SqlModule())
}!
handlers {
...!
}
}!
56. • Spring application context can be used to
back a registry using the
ratpack.spring.Spring class
h>p://www.ratpack.io/manual/0.9.13/api/ratpack/spring/Spring.html
57. • Like handlers, registries can be
programmatically registered into the
handler chain based on request data
• Can allow your app to resolve components
specific to the context of a request
60. • Including framework modules in your
Gradle based project is really easy
• Can utilize helper methods from the
Ratpack Gradle plugin to include named
modules
• Allows framework versions to stay in sync
62. • Including framework modules in your
Gradle based project is really easy
• Can utilize helper methods from the
Ratpack Gradle plugin to include named
modules
• Allows framework versions to stay in sync
65. • NetflixOSS Hystrix support, via the ratpack-
hystrix module
• Calls to remote services can be made fault
tolerant
• Ability to stream Hystrix metrics to the Hystrix
Dashboard
Great Support for building MICROSERVICES!!
66. • The ratpack-hikari module uses HikariCP
to create a super fast pooled SQL DataSource
• Can be used in conjunction with Groovy SQL
to query databases
• Configurable using the fixtures from the
ratpack-config module
Great Support for DATABASES!!
67. • The ratpack-jackson module provides
request data parsing and object rendering
from and to JSON
• Data can be worked with in free-form nodes,
or bound to command objects
• Arbitrary models can be rendered as JSON
using simply context.render(obj)!
Great Support for DATA BINDING!!
68. • Ratpack’s Promise API is an implementation of
Reactive Streams Specification
• The ratpack-rxjava module provides a
bridge between a Ratpack Promise and an
RxJava Observable
• The ratpack-reactor module allows data
to be processed using Project Reactor
Great Support for REACTIVE PROGRAMMING!!
69. • View templates can be rendered through a variety
of means
• Support for server-side templating with
Handlebars, Thymeleaf, Groovy Templates, and
Groovy Markup
• Ongoing work to integrate @davydotcom’s asset-
pipeline, which will give robust support for all types
of static content
Great Support for FULL-STACK FEATURES!!
70.
71. • Ratpack has been built from the ground-up with
testing considered at every turn
• Even more-so – considering testing from the
perspective of the developer
• The concept of the Registry gives the framework
control over components
• Makes it easy to provide fixtures for mocking and
stubbing data
72. • The EmbeddedApp class from the ratpack-
test module supports functional and
integration testing
• Can be used to test an application module
or a subset of handlers and functionality
• Can be used outside of Ratpack too!
73. • Spock is the choice framework, though
there’s no strict integration there
• Functional tests are easy to bootstrap and
the TestHttpClient helper makes it easy to
programmatically craft test calls
74. • Great resource for seeing Ratpack’s testing
in action is the example-books project
• Rus Hart keeps this up to date with changes
to the framework.
• https://github.com/ratpack/example-books