📜 ⬆️ ⬇️

Ratpack - rewarded with talent

Historically, Groovy takes a lot of good from Ruby. First of all, of course Grails (from Rails), but also Spock (from Spec) and even somewhere Gradle (from Buildr, although no one is recognized). Today I will tell you about another sensible "dumb" thing - the web framework Ratpack .
image
Written off Ratpack with Sinatra, about which much is written on Habré, for example , here .
In my opinion, the main advantage of Sinatra is that he is a talented singer that it is the simplest to use and instantly in development framework. Create a few simple pages, change them and see the results on the fly, and within a few hours, building a fairly non-trivial website with dynamic content is exactly what Sinatra was invented for. This is a kind of response to the "obese" Rails. Exactly in the same role (the answer to the "overweight" Grails) Sinatra and migrated to Gruvy.

I have to say that this time the Groove community was not the first to bother Sinatra. The first were Scala, with its Skalathra (yeah, the answer to the "overweight" Play). As far as I know, the decision not to make the name sound like a rumor, but to search for an association by meaning, was made first of all, horrified by the sound of the name of the version of the Rock :)

Ratpack translates into Russian as the Rat Pack, and is tied to Sinatra in that it’s a party in which Frank Sinatra hung out .
')
And where does Java?

Well, here, it seems to me, everything is clear. Unlike Ruby, where lightweight RoR used to be, or from Gruvy with his Grails, Java never had mainstream “lightweight” frameworks *. We have either cumbersome server-side component frameworks like JSF and Wicket, or MVC frameworks, which, of course, are easier component monsters, but still, require MVC to pile up for the simplest page. Here, of course, I'm talking about Spring MVC and Struts2. And all this with the terribly slow development cycle "changed the word? reboot! Brrr.

As rightly noted by antonarhipov , you can use frameworks for REST APIs, such as Jersey and RESTlet, but this, in my opinion, is an application.

Java already has a clone of Sinatra called Spark , so why not use it? I see several reasons for this:

As always, the advantage of Gruvy for Java programmers is that they feel at home. 99% of Java code works in Groovy without changes, therefore any Gruvy framework or tool can be immediately used by a Java programmer.
The situation with the ratpack is even better - the developers specifically tried to write in pure Java without using Gruvy at any development stage. So you can start without knowing anything about Gruvy, and slowly discovering Ratpack features for yourself, start writing on Gruvy. One of the examples in this article will be written 100% in Java. Who in the first stage is not interested in all this Gruvino shamanism, twists right on the last example. The rest start here:

Hello, World!

Well, I think we should start with Hello, World !, right? A full-fledged ratpack web application looks like this:
@GrabResolver('http://oss.jfrog.org/artifactory/libs-snapshot') //(1) @Grab('org.ratpack-framework:ratpack-groovy:0.9.0-SNAPSHOT') import static org.ratpackframework.groovy.RatpackScript.ratpack ratpack { //(2) handlers { get { response.send 'Hello, world!' //(3) } } } 

Everything. Fair. We write this to a file (for example, ratpack.groovy), run through groovy ratpack.groovy :
INFO: Ratpack started for localhost:5050
Obediently go on localhost:5050 localhost:5050 and find the expected there:

Let's see what we wrote:
  1. This is an instruction to download all the necessary libraries from a free opensource Artifactory account.
  2. This is an application declaration, it consists of handlers and modules.
  3. This is a get command handler. Since it has no parameters, it will work by calling the root url. This is where we ask for the return of Hello World.

Add another handler

We add another handler to our ratpack.groovy:
 ratpack { handlers { get { response.send 'Hello, world!' } get('habr'){ response.send 'Hello, habr!' //   } } } 

Save the file, go to the browser localhost:5050/habr localhost:5050/habr , enjoy.

Reboot? Nah, this is not for us. Who is well done? Spring-loaded well done .
Add Dynamism

Add speed and interest. Code:
 ratpack { handlers { get('hello/:username') { response.send "Hello, ${pathTokens.username}" } } } 

Result:

Or like this. Code:
 ratpack { handlers { get('hello') { response.send "Hello, ${request.queryParams.username}" } } } 

Result:

We connect templates

We can mention many other interesting features, but the article is no longer so short, and I will still have an example on pure Java, so let's look at working with templates. For example, take the Groovy template:
Templates are in the templates directory. Save there, for example, index.html with the following content:
 <html> <head> <title>${model.title}</title> </head> <body> <h5>${model.content}</h5> <br/> <img src="http://habr.habrastorage.org/post_images/9a5/14b/49a/9a514b49a2017e50f386f154c8cb0da2.png"/> </body> </html> 

The script with the handler now looks like this:
 @GrabResolver('http://oss.jfrog.org/artifactory/libs-snapshot') @Grab('org.ratpack-framework:ratpack-groovy:0.9.0-SNAPSHOT') import static org.ratpackframework.groovy.RatpackScript.ratpack import static org.ratpackframework.groovy.Template.groovyTemplate ratpack { handlers { get { render groovyTemplate("index.html", title: '   Ratpack', content: ' :') } } } 

Notice the new static import.
The result is expected:

Who was waiting for Java? We have them!

Well, there will not be a running script, and do not wait. There will be a serious application, with the directory structure, modules, with the assembly file.
Dependency injection will be on Guice, a web server on netty, build and run on a gradle, reload using Spring-loaded.
Go:
Project structure:

The ratpack.properties file says who is the HandlerFactory (where do you get handlers from):
 handlerFactory=example.HandlerFactory 

The example.HandlerFactory class is, naturally, a factory for handlers. We have only one there, Hello, %username% :
 package example; import ... public class HandlerFactory implements org.ratpackframework.launch.HandlerFactory { public Handler create(LaunchConfig launchConfig) { return chain(new Action<Chain>() { public void execute(Chain chain) { chain.add(get("hello/:username", new Handler() { public void handle(Context context) { Map<String, String> pathTokens = context.getPathTokens(); context.getResponse().send("Hello from Java, " + pathTokens.get("username")); } })); } }); } } 

Yes, Java 8 would not hurt.
Here everything looks like a Gruvian version - we add a handler to the path hello /: username, then we take the value of the dynamic part of the path from the context.getPathTokens() .

Run the task run , recompile the changes in the task classes (in another window, do not need to stop run ):

Result:


Honestly, the Java example was not very attractive. Fenced off classes and directories, when you can write all this in 4 lines Groove. So why?
The benefits of Java begin with an increase in complexity and size. Suddenly, the division into classes and packages, hard typing and the possibility of tests become much more important than the number of files and lines. To see these benefits, take a look at a more complete example of a Java application on Ratpack right here . I am sure you will understand what advantages I am talking about.

Conclusion

Naturally, these are the very basics, naturally, there are a lot more buns in Ratpack than I just showed. These are Guice modules, services, and integration with MongoDB and GORM.

Using Java classes for handlers, modules and services makes it possible to create a modular and easily testable application of average complexity.
Using Groovy scripts allows for much faster development of something simple, “on the knee,” with impressive results.

I hope that I managed to interest you in this framework. As you can see, even the first version has not yet been released (although soon), so I would not write mission-critical applications to it, but it is worthy of paying attention to it, and trying to play your next “on it” creepy home page »

PS

If you want to continue, write in the comments.
If you want to talk to Ratpack personally, as well as listen to other interesting things, come to JUG on August 31st .

Source: https://habr.com/ru/post/190452/


All Articles