Ratpack - Talented

    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 recognizes it). Today I will tell you about another sensible "stupid" thing - web framework Ratpack .
    image
    Decommissioned Ratpack from 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 singerthat it is the easiest to use and instant in development framework. To create some simple pages, change them and see the results on the fly, and in a few hours to pile a rather non-trivial website with dynamic content - this is exactly what Sinatra was invented for. This is a kind of answer to the "fat" Rails. Exactly in the same role (the answer to the "obese" Grails), Sinatra migrated to Groove.

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

    Ratpack is translated into Russian as the Rat Pack, and the link to Sinatra is that it is the party in which Frank Sinatra hung out .

    And where does Java?

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

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

    There is already a Sinatra clone in Java called Sparkso why not use it? I see several reasons for this:
    • Freemarker or Velocity for templating. The first, of course, is not as terrible as the second, but also not a gift. Both worse than Groovy Templates
    • Hot Swap - a clone of Sinatra must be able to "changed, F5, saw." If not, then alas.
    • Ratpack - a great opportunity to smoothly immerse yourself in Groove. And I think this is the main advantage.

    As always, Groove's advantage for Java programmers is that they feel right at home. 99% of Java code works in Grooves without changes, so any Groove framework or tool can be immediately used by a Java programmer.
    The situation with ratpack is even better - the developers made special efforts so that they could write in pure Java without using Groove at any stage of development. Thus, you can start without knowing anything about Groove, and slowly discovering the features of Ratpack for yourself, start writing in Groove. One example in this article will be written 100% in Java. Who at the first stage is not interested in all this Gruvian shamanism, twists directly to the last example. The rest start here:

    Hello World!

    Well, I think we should start with Hello, World !, right? A full 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)
            }
        }
    }

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

    Let's see what we wrote:
    1. This instruction download all the necessary libraries from a free opensource account Artifactory
    2. This application declaration, it consists of handlers and modules
    3. This is the get handler. Since it has no parameters, it will work by calling root url. Here we ask to return 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!' //наш новый обработчик
            }
        }
    }
    

    We save the file, go to the browser 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. The code:
    ratpack {
        handlers {
            get('hello/:username') {
                response.send "Hello, ${pathTokens.username}"
            }
        }
    }

    Result:

    Well, or so. The code:
    ratpack {
        handlers {
            get('hello') {
                response.send "Hello, ${request.queryParams.username}"
            }
        }
    }
    

    Result:

    We connect templates

    You can mention many more interesting features, but the article is not so short already, and I will still be an example in pure Java, so let's look at working with templates. For example, take the Groovy template:
    Templates are in a directory templates. Save there, for example, index.htmlwith the following contents:
    ${model.title}
    ${model.content}


    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: 'Тут логотипы:')
            }
        }
    }
    

    Check out the new static import.
    The result is expected:

    Who was waiting for Java? We have them!

    Well, there won't be a script to run, and don't wait. There will be a serious application, with a directory structure, modules, with an assembly file.
    Dependency injection will be on Guice, web server on netty, build and run on gradle, reboot using Spring-loaded.
    Let's go:
    Project structure:

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

    The class example.HandlerFactoryis, 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() {
                public void execute(Chain chain) {
                    chain.add(get("hello/:username", new Handler() {
                        public void handle(Context context) {
                            Map pathTokens = context.getPathTokens();
                            context.getResponse().send("Hello from Java, " + pathTokens.get("username"));
                        }
                    }));
                }
            });
        }
    }
    

    Yes, Java 8 would not hurt.
    Everything here is similar to the Groovy version - we add a handler to the hello /: username path, then we take the value of the dynamic part of the path from context.getPathTokens().

    We start the task run, recompile the changes with the task classes (in another window, run no need to stop):

    Result:


    Honestly, the Java example was not very attractive. Piled classes and directories, when all this can be written in 4 lines of Groove. So why?
    The benefits of Java begin with growth in complexity and size. Suddenly, separation into classes and packages, hard typing and the ability to test become much more important than the number of files and lines. To see these benefits, take a look at a more complete Java application example on Ratpackright here . I’m sure you will understand what benefits I’m talking about.

    Conclusion

    Naturally, these are the very basics, naturally, Ratpack has a lot more goodies 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 medium 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 have to transfer mission-critical applications to it, but it is worthy to pay attention to it and try to build your next one on it " creepy home page "

    PS

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

    Also popular now: