42
Ratpack Classy and Compact Groovy Web Apps James Williams

Ratpack - Classy and Compact Groovy Web Apps

Embed Size (px)

Citation preview

Page 1: Ratpack - Classy and Compact Groovy Web Apps

RatpackClassy and Compact Groovy Web Apps

James Williams

Page 2: Ratpack - Classy and Compact Groovy Web Apps

About Me

• Co-founder of Griffon

• Author of "Learning HTML5 Game Programming"

       http://amzn.to/HTML5-Game-Book

• Blog: http://jameswilliams.be

• Twitter: @ecspike

• Google+: http://gplus.to/ecspike

Page 3: Ratpack - Classy and Compact Groovy Web Apps

Agenda

• What are Groovy and Ratpack?• Routes• Templates• Running the App• Deploying to Servlet Containers• Deployment• Demos / Live Coding

Page 4: Ratpack - Classy and Compact Groovy Web Apps

What is Groovy?

• Dynamic language on the JVM inspired by Java, Ruby, and Python

• Compiles Java source - yay!

• Can mix Java and Groovy classes and libraries

• Do alot more with less code

• http://groovy.codehaus.org

Page 5: Ratpack - Classy and Compact Groovy Web Apps

What is Ratpack?

• Apache 2 Licensed

• Inspired by Sinatra (Ruby)

• Logic is largely driven by Routes 

• Powered by Jetty

• Built-in support for Groovy SimpleTemplateEngine

• Github: https://github.com/bleedingwolf/Ratpack

Page 6: Ratpack - Classy and Compact Groovy Web Apps

Ratpack vs (G)rails

 

Page 7: Ratpack - Classy and Compact Groovy Web Apps

When to use Grails...

• Data-driven model

• Large number of models with differing endpoints

• Spring Security is a definite need 

• Out of the box persistence integration is required

• Plan to make great use of the Grails plugin ecosystem

Page 8: Ratpack - Classy and Compact Groovy Web Apps

When to use Ratpack...

• Low number of domain classes

• Limited number of routes/endpoints

• Model - View - Controller paradigm is not needed

• Small but evolving REST API

Page 9: Ratpack - Classy and Compact Groovy Web Apps

Routes

• Composed of a HTTP verb, an endpoint, and a code block

• Verb can be one of the nine canonical verbs or you can create your own

• Endpoint corresponds to URL fragment.

• :<identifier> injects that value into the urlparams object

• Code block is injected with:o requesto responseo renderer     o urlparams

Page 10: Ratpack - Classy and Compact Groovy Web Apps

Routes

get("/index") {    // code}

post("/login") {    // code}

put("/post/:id") {    // code}

Page 11: Ratpack - Classy and Compact Groovy Web Apps

Routes

get("/index") {    // code}

post("/login") {    // code}

put("/post/:id") { ==>  /post/3    // code             urlparams.id == 3  }

Page 12: Ratpack - Classy and Compact Groovy Web Apps

Sample Ratpack App

import com.bleedingwolf.ratpack.*

class App {

public static void main(String []args) {

def app = Ratpack.app {

set 'public', 'public'

set 'templateRoot', 'templates'

post("/") {

request.toString() + "\n" +params.toString()

}

get("/") {

"Hello world"

}

}

RatpackServlet.serve(app)

}}

Page 13: Ratpack - Classy and Compact Groovy Web Apps

Demo

 

Page 14: Ratpack - Classy and Compact Groovy Web Apps

Templates

 

Page 15: Ratpack - Classy and Compact Groovy Web Apps

Templates

• Uses Groovy SimpleTemplateEngine by default • Can swap in other template engines

• SimpleTemplateEngine can be used in conjunction with others

Page 16: Ratpack - Classy and Compact Groovy Web Apps

SimpleTemplateEngine

• Means to generate text dynamically

• Uses JSP-style instructions for code blocks<% %>  and <%= %>

• Can also use Groovy expression evaluators${expression}

 

Page 17: Ratpack - Classy and Compact Groovy Web Apps

Markdown

• Created by John Gruber and Aaron Swartz

• Markup language for converting text to (X)HTML

• Supported by many frameworks and websites

• In many different languages

•  http://daringfireball.net/projects/markdown/

Page 18: Ratpack - Classy and Compact Groovy Web Apps

Markdown Basics

• Headers (#)

• Lists (* or numbers)

• Code Snippets (`)

• Emphasis (*)

• Strong/Bold (**)

• Links

Page 19: Ratpack - Classy and Compact Groovy Web Apps

Markdown + SimpleTemplateEngine

Page 20: Ratpack - Classy and Compact Groovy Web Apps

Sample Ratpack App

import com.petebevin.markdown.*import com.bleedingwolf.ratpack.*

class App {

public static void main(String []args) {

def app = Ratpack.app {

set 'public', 'public'

set 'templateRoot', 'templates'

                                get("/time") {

render "index.html", [time:new Date()]

}

get("/") {

def m = new MarkdownProcessor()

def p = render 'template.md', [num:4]

m.markdown(p)

}

}

RatpackServlet.serve(app)

}}

Page 21: Ratpack - Classy and Compact Groovy Web Apps

App Structure

/ main/src/groovy/ templates/ public/ lib                                  ==> contains Ratpack.jar/ resources/web.xml    ==> only needed for packaging war/ build.gradle                 ==> contains Ratpack's maven depos

Page 22: Ratpack - Classy and Compact Groovy Web Apps

Creating a Blog App with Ratpack

 

Page 23: Ratpack - Classy and Compact Groovy Web Apps

App Essentials

• Simple blog engine

• Uses NoSQL for persistence

• Uses a tweaked Tumblr template

• ~ 156 lines of Groovy code

• Source: http://github.com/jwill/Conference-Demos/user-groups

Page 24: Ratpack - Classy and Compact Groovy Web Apps

Blog CRUD Routes

get("/entry/create") {

render '/entry/create.html'}

get("/entry/show/:id") {

def entry = derby.get(urlparams.id)

render '/entry/show.html', [entry: entry]}get("/entry/delete/:id") {

derby.remove(urlparams.id)}

Page 25: Ratpack - Classy and Compact Groovy Web Apps

Blog CRUD Routes (cont'd)

get("/post/list") {

def list = derby.all()

list.sort(sortClosure.curry('dateCreated'))

list = list.reverse()

render '/post/index.html', [posts: list]}

post("/post/save") {

def post = new Post(params)

derby.save(post.properties, {obj ->

println "Finished saving."

new JSONObject([success:true]).toString()

})}

Page 26: Ratpack - Classy and Compact Groovy Web Apps

Demo

 

Page 27: Ratpack - Classy and Compact Groovy Web Apps

Creating a Todo Application

• Only 103 LOC

• Uses MongoDB for persistence

• uki.js and CoffeeScript for UI code

• Source: http://bit.ly/s12gx-ratpack

Page 28: Ratpack - Classy and Compact Groovy Web Apps

MongoDB

• Document-oriented store

• Querying

• Client Library Support

• Full Index Support

• Commercial and Web-Based Options

• GridFS 

• http://www.mongodb.org

Page 29: Ratpack - Classy and Compact Groovy Web Apps

Uki

• 34KB gzipped

• UI framework for creating web applications

• Rich widget library

• Code-based layout

• Constraints

• JQuery-like selectors

• http://ukijs.org

Page 30: Ratpack - Classy and Compact Groovy Web Apps

Uki example

uki({  view: "Button", text: "Hello world!",  rect: "120 80 180 24"}).attachTo(document.getElementById("test")); uki("Button[text^=Hello]").click(  function() { alert(this.text()); });

Page 31: Ratpack - Classy and Compact Groovy Web Apps

CoffeeScript

• Child of Ruby, Groovy, Python

• Compiles to JavaScript

• Produces *READABLE* Javascript

• Classes / Inheritance / Polymorphism

• Groovy style loops

• Aliases for Comparison Operators (is, isnt, not, and, or, yes/on, no/off)

• CoffeeScript for Groovy Devs - Scott Davis - Fri @ 12:45P

Page 32: Ratpack - Classy and Compact Groovy Web Apps

Live Coding

 

Page 33: Ratpack - Classy and Compact Groovy Web Apps

Running/Deploying the App

 

Page 34: Ratpack - Classy and Compact Groovy Web Apps

Gradle

• Language independent build system leveraging Groovy

• Build system for Grails, Spock, and many others

• Uses Maven for dependency management

• Vibrant plugin community

• http://gradle.org

Page 35: Ratpack - Classy and Compact Groovy Web Apps

Gradle Application Plugin

• Requires Gradle 1.0+

• Code: plugin 'application'

• Provides common tasks for the application lifecycle.

• Provides the following tasks:o run

o installApp

o distZip

Page 36: Ratpack - Classy and Compact Groovy Web Apps

Gradle File

apply plugin: 'groovy'apply plugin: 'application'

repositories {

flatDir name:'lib', dirs:'lib'

mavenCentral() }

dependencies {

groovy group:'org.codehaus.groovy', name:'groovy', version:'1.8.0'

groovy group:'com.bleedingwolf.ratpack', name: 'Ratpack', version:'0.2-SNAPSHOT'

// Ratpack's other dependencies}

Page 37: Ratpack - Classy and Compact Groovy Web Apps

Gradle File (cont'd)

installApp { into('build/install/'+applicationName){ from ('templates').into '/templates' } into('build/install/'+applicationName){ from ('public').into '/public' } }distZip { into(applicationName){ from ('templates').into applicationName+'/templates' } into(applicationName){ from ('public').into applicationName+'/public' }}

mainClassName = "BlogApp"

Page 38: Ratpack - Classy and Compact Groovy Web Apps

Deploying App as a War

 

Page 39: Ratpack - Classy and Compact Groovy Web Apps

Gradle File Additions

war {

into('/public') {

from('public')

}

into('/templates') {

from('templates')

}

classpath fileTree('lib')

webXml = file('resources/web.xml')}

Page 40: Ratpack - Classy and Compact Groovy Web Apps

Web.xml File<?xml version="1.0" encoding="ISO-8859-1"?><!DOCTYPE web-app    PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"    "http://java.sun.com/dtd/web-app_2_3.dtd"><web-app><servlet>        <servlet-name>AppServlet</servlet-name>        <servlet-class>AppServlet</servlet-class></servlet><servlet-mapping>        <servlet-name>AppServlet</servlet-name>        <url-pattern>/*</url-pattern></servlet-mapping></web-app>

Page 41: Ratpack - Classy and Compact Groovy Web Apps

Questions ?

 

Page 42: Ratpack - Classy and Compact Groovy Web Apps

Links

MarkdownJ - http://markdownj.org

Ratpack - http://github.com/bleedingwolf/Ratpack

Gradle - http://gradle.org

Demos - http://github.com/jwill/ConferenceDemos/strangeloop