Rapid application development with Apache Turbine and Maven · Rapid application development with...

115
Rapid application development with Apache Turbine and Maven Henning Schmiedehausen <[email protected]> Gesellschaft für Mehrwertdienste mbH

Transcript of Rapid application development with Apache Turbine and Maven · Rapid application development with...

Page 1: Rapid application development with Apache Turbine and Maven · Rapid application development with Apache Turbine and Maven Henning Schmiedehausen  Gesellschaft

Rapid application development with Apache Turbine and Maven

Henning Schmiedehausen

<[email protected]>

Gesellschaft für Mehrwertdienste mbH

Page 2: Rapid application development with Apache Turbine and Maven · Rapid application development with Apache Turbine and Maven Henning Schmiedehausen  Gesellschaft

Introduction

� This tutorial shows how to develop web applications with the Turbine web framework

� Apache Maven is used as the build tool which glues the build process together.

� This tutorial will show the basics

� Target is to get you „over the hump“

Page 3: Rapid application development with Apache Turbine and Maven · Rapid application development with Apache Turbine and Maven Henning Schmiedehausen  Gesellschaft

About the Speaker

� Working with Turbine since 2001(Turbine 2.1)

� Committer on the Turbine project (Fall 2002)

� ASF member (May 2005)

� Did many of the reworkings in the 2.2 -> 2.3 development cycle and made the 2.3 and 2.3.1 releases

� Developed and deployed ~ 20 Turbine based applications ranging from 1-500 kLOC

Page 4: Rapid application development with Apache Turbine and Maven · Rapid application development with Apache Turbine and Maven Henning Schmiedehausen  Gesellschaft

Agenda

� 1) Preliminaries

� 1.1) Introduction to Turbine and Maven

� 1.2) Maven and M.E.T.A. installation

� 1.3) „Hello World“

� 2) Turbine Overview

� 3) Turbine example: ApacheFaces

Page 5: Rapid application development with Apache Turbine and Maven · Rapid application development with Apache Turbine and Maven Henning Schmiedehausen  Gesellschaft

Part 1.1

Introduction to Maven and Turbine

Page 6: Rapid application development with Apache Turbine and Maven · Rapid application development with Apache Turbine and Maven Henning Schmiedehausen  Gesellschaft

Apache Maven

� Integrated Project management tool

� “ant on steroids”

� Project descriptor (project.xml)

� Definition of custom build goals (maven.xml)

� Pre- and Post-Goals control build sequence

� Plugin-oriented approach

� Plugins are written in Jelly

� ~ 90 plugins included with Maven itself

Page 7: Rapid application development with Apache Turbine and Maven · Rapid application development with Apache Turbine and Maven Henning Schmiedehausen  Gesellschaft

Apache Maven Architecture

(Siegfried Göschl / it20one)

Page 8: Rapid application development with Apache Turbine and Maven · Rapid application development with Apache Turbine and Maven Henning Schmiedehausen  Gesellschaft

Apache Maven

� Integrated artifact repository (jars, plugins)

� Web repo at http://www.ibiblio.org/maven/

� Current release version is 1.0.2(1.1 is Beta level, 2.0 is Alpha level)

� Get it from http://maven.apache.org/

� Binary and Source versions available

� Even a Windows Installer!

Page 9: Rapid application development with Apache Turbine and Maven · Rapid application development with Apache Turbine and Maven Henning Schmiedehausen  Gesellschaft

Jakarta Turbine

� „A platform for building applications, not just running them“

� A Toolbox for building web applications

� 100% pure Java, JDK 1.3+

� J2EE compilant, servlet based

� MVC oriented

Page 10: Rapid application development with Apache Turbine and Maven · Rapid application development with Apache Turbine and Maven Henning Schmiedehausen  Gesellschaft

Jakarta Turbine: Architecture

Servlet Core

Tool

Box

Service Broker Module management

Services

Actio

ns

Pages

Screens Layouts Navig.

Servlet Core

Tool

Box

Service Broker Module management

Services

Actio

ns

Pages

Screens Layouts Navig.

Page 11: Rapid application development with Apache Turbine and Maven · Rapid application development with Apache Turbine and Maven Henning Schmiedehausen  Gesellschaft

Jakarta Turbine: Architecture

� View and Controller Framework

� Service framework with ~20 services

� „Tool“ infrastructure

� Utility classes

� Jakarta Velocity to render View templates

� DB Torque for persistence

Page 12: Rapid application development with Apache Turbine and Maven · Rapid application development with Apache Turbine and Maven Henning Schmiedehausen  Gesellschaft

Jakarta Turbine: How to get it

� http://jakarta.apache.org/turbine/

� Current „official“ release is 2.3.1. A new major relase with architectural changes (2.4) is under development

� The Turbine project is looking for contributors helping with the code and the docs!

Page 13: Rapid application development with Apache Turbine and Maven · Rapid application development with Apache Turbine and Maven Henning Schmiedehausen  Gesellschaft

Turbine Development Kit

� Turbine up to 2.3 knew only the “TDK”(Turbine Development Kit)

� Large collection of ant scripts that in the end spawned the Maven project

� No official version since Turbine 2.2

� Heavy (includes servlet container and jars)

� Rigid (path structure dictated by the TDK)

� Underdocumented

Page 14: Rapid application development with Apache Turbine and Maven · Rapid application development with Apache Turbine and Maven Henning Schmiedehausen  Gesellschaft

M.E.T.A.

� Maven Environment for Turbine Applications

� Custom Maven plugin

� First release with Turbine 2.3.1(supporting 2.3 and 2.3.1)

� Lightweight (downloads lots of stuff from the 'net, though)

� IDE support (tested with Eclipse)

� Docs: http://jakarta.apache.org/turbine/meta/

Page 15: Rapid application development with Apache Turbine and Maven · Rapid application development with Apache Turbine and Maven Henning Schmiedehausen  Gesellschaft

Part 1.2

Maven and M.E.T.A. installation

Page 16: Rapid application development with Apache Turbine and Maven · Rapid application development with Apache Turbine and Maven Henning Schmiedehausen  Gesellschaft

The M.E.T.A. environment

� Custom plugin for Maven

� Setup of a new Turbine-based application

� Compilation of Turbine and Torque based code

� Generation of necessary SQL files for persistence

� Deployment and WAR generation

� Can be used with “old fashioned editor”(OFE) environment or IDE

Page 17: Rapid application development with Apache Turbine and Maven · Rapid application development with Apache Turbine and Maven Henning Schmiedehausen  Gesellschaft

Prerequisites

� A J2SDK, supporting Java 1.3 or Java 1.4

� A servlet container (Unlike the TDK, you are free to choose one)

� A database for persistence.

� Something for code editing. Either an IDE oder an editor. Or both.

Page 18: Rapid application development with Apache Turbine and Maven · Rapid application development with Apache Turbine and Maven Henning Schmiedehausen  Gesellschaft

Software used in the tutorial

� Sun J2SDK 1.4.2 – http://java.sun.com/

� Apache Tomcat 5.0.x –http://jakarta.apache.org/tomcat/

� MySQL 4.1 – http://www.mysql.org/

� Eclipse 3.x – http://www.eclipse.org/

� GNU emacs –http://www.gnu.org/software/emacs/

Page 19: Rapid application development with Apache Turbine and Maven · Rapid application development with Apache Turbine and Maven Henning Schmiedehausen  Gesellschaft

Installing Maven

� http://maven.apache.org/start/download.html

� Get maven 1.0.x, don’t even think about the 1.1 or 2.0 alpha / beta versions

� Windows

� The Installer works nicely

� Unix / Linux

� Create ~/.maven and unpack there

Page 20: Rapid application development with Apache Turbine and Maven · Rapid application development with Apache Turbine and Maven Henning Schmiedehausen  Gesellschaft

Caveat

� JAVA_HOME

� On Windows: Settings -> System -> Environment

� On RPM based Linux: Use the excellent JPackage RPMs which do a really good job to seamlessly integrate Java

� MAVEN_HOME

� On Windows: Windows Installer does it right

� global build.properties file

� Don‘t forget maven.appserver.home setting!

� On Windows: Make sure to use forward („/“) slashes

� Add MAVEN_HOME/bin to your PATH

Page 21: Rapid application development with Apache Turbine and Maven · Rapid application development with Apache Turbine and Maven Henning Schmiedehausen  Gesellschaft

Does Maven work?

Page 22: Rapid application development with Apache Turbine and Maven · Rapid application development with Apache Turbine and Maven Henning Schmiedehausen  Gesellschaft

Installing M.E.T.A.

� Maven can load M.E.T.A. directly from the central repository at ibiblio

maven –DartifactId=maven-turbine-plugin \

–DgroupId=turbine \

–Dversion=1.2 plugin:download

Page 23: Rapid application development with Apache Turbine and Maven · Rapid application development with Apache Turbine and Maven Henning Schmiedehausen  Gesellschaft

Did it install correctly?

Running maven –g must show

Turbine related Maven goals.

Page 24: Rapid application development with Apache Turbine and Maven · Rapid application development with Apache Turbine and Maven Henning Schmiedehausen  Gesellschaft

Ready to go!

� The M.E.T.A. workbench consists of

� Java SDK

� Servlet Container

� Maven

� M.E.T.A. plugin

� Optional components

� IDE

� Database

Page 25: Rapid application development with Apache Turbine and Maven · Rapid application development with Apache Turbine and Maven Henning Schmiedehausen  Gesellschaft

Part 1.3

„Hello World“

Page 26: Rapid application development with Apache Turbine and Maven · Rapid application development with Apache Turbine and Maven Henning Schmiedehausen  Gesellschaft

� Setup build environment� maven –Dturbine.app.name=helloworld turbine:setup

� Compile application� maven java:compile

� Deploy it to the web container� maven turbine:deploy

� Run the container

Instant “Hello World”

Page 27: Rapid application development with Apache Turbine and Maven · Rapid application development with Apache Turbine and Maven Henning Schmiedehausen  Gesellschaft

“Hello, World”

Page 28: Rapid application development with Apache Turbine and Maven · Rapid application development with Apache Turbine and Maven Henning Schmiedehausen  Gesellschaft

What has happened?

� turbine:setup generates a new application

� java:compile builds the .class files

� turbine:deploy installs the web application

� Skeleton contains a few demo pages

� “normal” development mode using an editor (“for the emacs folks”)

� Note: no setup.properties file necessary

Page 29: Rapid application development with Apache Turbine and Maven · Rapid application development with Apache Turbine and Maven Henning Schmiedehausen  Gesellschaft

Caveat

� Make sure your Maven setup is correct!

� You must have Internet connectivity when building your project for the first time

� The “missing libraries” problem

� Starting / Stopping your Servlet Container

Page 30: Rapid application development with Apache Turbine and Maven · Rapid application development with Apache Turbine and Maven Henning Schmiedehausen  Gesellschaft

M.E.T.A. goals in“normal” mode

� Skeleton setup� turbine:setup

� Development cycle� java:compile

� turbine:deploy

� Bind WAR for deployment� turbine:war

� Documentation� site

Page 31: Rapid application development with Apache Turbine and Maven · Rapid application development with Apache Turbine and Maven Henning Schmiedehausen  Gesellschaft

Using an IDE – “inplace” mode

� “inplace” development mode

� Custom setup.properties file necessary:

turbine.app.name = inplace

turbine.app.subdir = true

turbine.app.flavor = turbine-2.3.1

turbine.app.om.layer = torque

turbine.plugin.mode = inplace

turbine.plugin.inplace.dir = tomcat

Page 32: Rapid application development with Apache Turbine and Maven · Rapid application development with Apache Turbine and Maven Henning Schmiedehausen  Gesellschaft

Setup for Eclipse

� Setup build environment� maven turbine:setup

� Generate persistence classes� maven torque:om

� Fetch all necessary libraries� maven turbine:install-libs

� Generate Eclipse Configuration� maven eclipse

� Import project into Eclipse

� (optional) Add Information for Tomcat plugin

Page 33: Rapid application development with Apache Turbine and Maven · Rapid application development with Apache Turbine and Maven Henning Schmiedehausen  Gesellschaft

Eclipse Tomcat plugin

� Eclipse plugin for Tomcat Start/Stop

� Also integrates configuration with Project

� Download fromhttp://www.sysdeo.com/eclipse/tomcatPlugin.html

Page 34: Rapid application development with Apache Turbine and Maven · Rapid application development with Apache Turbine and Maven Henning Schmiedehausen  Gesellschaft

“Hello, World”, inplace style

Page 35: Rapid application development with Apache Turbine and Maven · Rapid application development with Apache Turbine and Maven Henning Schmiedehausen  Gesellschaft

What has happened?

� turbine:setup generates a new application

� torque:om builds persistence layer sources

� turbine:install-libs fetches the libs

� eclipse generates .project and .classpath

� Skeleton contains a few demo pages

� “inplace” development mode for IDE users

� A setup.properties file must be present!

Page 36: Rapid application development with Apache Turbine and Maven · Rapid application development with Apache Turbine and Maven Henning Schmiedehausen  Gesellschaft

M.E.T.A. goals in “inplace” mode

� Skeleton setup� turbine:setup

� Eclipse setup� turbine:install-libs

� Update source code� torque:om

� Documentation� site

Page 37: Rapid application development with Apache Turbine and Maven · Rapid application development with Apache Turbine and Maven Henning Schmiedehausen  Gesellschaft

“normal” vs. “inplace” Mode

� Maven builds project

� Development cycle� java:compile

� turbine:deploy

� Webapp location outside source tree

� Autogenerated classes are automatically updated

� IDE builds project

� Maven prepares project� torque:om

� turbine:install-

libs

� Webapp location insidesource tree

� Autogenerated classes must be updated� torque:om

Page 38: Rapid application development with Apache Turbine and Maven · Rapid application development with Apache Turbine and Maven Henning Schmiedehausen  Gesellschaft

What about SQL code?

� M.E.T.A. also builds SQL code if a persistence layer is configured� turbine:sql – builds SQL code

� Torque specific support:� torque:insert-sql – insert SQL into

database

� torque:create-db – create the database

Page 39: Rapid application development with Apache Turbine and Maven · Rapid application development with Apache Turbine and Maven Henning Schmiedehausen  Gesellschaft

End of Part 1

� What have we done?

� set up our workbench

� installed M.E.T.A.

� talked about development modes

� old-fashioned and IDE-based “Hello World”

� What have we not done?

� Talked about APIs or programming

� Wrote a single line of code. No Java, XML, …

Page 40: Rapid application development with Apache Turbine and Maven · Rapid application development with Apache Turbine and Maven Henning Schmiedehausen  Gesellschaft

five minute break

Page 41: Rapid application development with Apache Turbine and Maven · Rapid application development with Apache Turbine and Maven Henning Schmiedehausen  Gesellschaft

Part 2

Turbine Overview

Page 42: Rapid application development with Apache Turbine and Maven · Rapid application development with Apache Turbine and Maven Henning Schmiedehausen  Gesellschaft

Why Turbine?

� Well suited for “spontanous development”(aka “agile processes” aka “hacking”)

� Turbine applications can “grow”

� The Turbine concepts are easy to understand

� A Number of helper classes for “boring” tasks

Page 43: Rapid application development with Apache Turbine and Maven · Rapid application development with Apache Turbine and Maven Henning Schmiedehausen  Gesellschaft

Turbine buzzwords

� Modules. Generic term for View parts and Actions. Modules are organized in Java packages.

� Tool. Part of the tool box provided by Turbine

� Action. Part of the Controller, responsible for changing model state.

� Service. Plug-in part of the framework

Page 44: Rapid application development with Apache Turbine and Maven · Rapid application development with Apache Turbine and Maven Henning Schmiedehausen  Gesellschaft

Model 2+1

� blurs the MVC concept by integrating View and Controller

� “paradigm” for writing Turbine applications

� expression coined by Jon S. Stevens

� based on MVC (Model 2)

Page 45: Rapid application development with Apache Turbine and Maven · Rapid application development with Apache Turbine and Maven Henning Schmiedehausen  Gesellschaft

Turbine MVC

You are not expected to be able to read this slide from the last row in the audience. This is why you got hand-outs.If you are able to read this message, call NASA at +1 202 358 0001 to become a test pilot instead of a Java Hacker

Page 46: Rapid application development with Apache Turbine and Maven · Rapid application development with Apache Turbine and Maven Henning Schmiedehausen  Gesellschaft

Turbine View Model

� The Turbine View is composed from

� Page “Everything you see”

� Screen “Content of the page”

� Navigation “Top, Bottom, Menu”

� Layout “Where to put everything”

� Each part of the View is a Module

Page 47: Rapid application development with Apache Turbine and Maven · Rapid application development with Apache Turbine and Maven Henning Schmiedehausen  Gesellschaft

Turbine View composition

Page 48: Rapid application development with Apache Turbine and Maven · Rapid application development with Apache Turbine and Maven Henning Schmiedehausen  Gesellschaft

Turbine View quirks

� Most web frameworks use a Templating solution or JSPs for the View

� Turbine uses Java classes for Page, Layout, Screen and Navigation

� Turbine provides classes that implement templating with Velocity or JSPs

� Using Java classes as View makes things like PDF rendering screens easy

Page 49: Rapid application development with Apache Turbine and Maven · Rapid application development with Apache Turbine and Maven Henning Schmiedehausen  Gesellschaft

Turbine View Classes

� View classes are controlled by the module manager (Assembler Broker)

� Java class names are composed from the module names and packages

� Default module package is org.apache.turbine.modules

� additional packages can be added in the configuration

Page 50: Rapid application development with Apache Turbine and Maven · Rapid application development with Apache Turbine and Maven Henning Schmiedehausen  Gesellschaft

Templating - Velocity

� A View should be built from web pages, JSPs or Templates, not Java classes

� Turbine leans heavily towards Templates and uses the Velocity templating engine

� Building the View with templates needs “glue”for calling the templating engine

Page 51: Rapid application development with Apache Turbine and Maven · Rapid application development with Apache Turbine and Maven Henning Schmiedehausen  Gesellschaft

Velocity in a nutshell

� “The other ugly duckling”

� Designed to replace WebMacro

� Simple notation for conditionals and loops

� Contains macro definition and execution

� Can load its templates from many sources

� Provides Context between Java and Template code

� Integrated bean access in template code

Page 52: Rapid application development with Apache Turbine and Maven · Rapid application development with Apache Turbine and Maven Henning Schmiedehausen  Gesellschaft

Velocity and Turbine

� Turbine provides classes for Velocity integration:

� Pages: VelocityPage

� Screens: VelocityScreen, VelocitySecureScreen

� Layouts: VelocityOnlyLayout, VelocityDirectLayout

� Navigation: VelocityNavigation

� These classes are used as defaults

Page 53: Rapid application development with Apache Turbine and Maven · Rapid application development with Apache Turbine and Maven Henning Schmiedehausen  Gesellschaft

Velocity View composition

Content

Page Top

Page BottomM

enu

Navigation Templates

provide static content

Layout Template

controls the Position of the elements on the

page

Screen Template

application content

Page 54: Rapid application development with Apache Turbine and Maven · Rapid application development with Apache Turbine and Maven Henning Schmiedehausen  Gesellschaft

Navigation Template

References

Screen Template

Reference

<html>

<head/>

<body>

<table>

<tr><td colspan=“2”>$navigation.setTemplate(“Top.vm”)</td></tr>

<tr>

<td>$navigation.setTemplate(“Menu.vm”)</td>

<td>$screen_placeholder</td>

</tr>

<tr><td colspan=“2”>$navigation.setTemplate(“Bottom.vm”)</td></tr>

</table>

</body>

</html>

Example: A Layout Template

Page 55: Rapid application development with Apache Turbine and Maven · Rapid application development with Apache Turbine and Maven Henning Schmiedehausen  Gesellschaft

Requesting a Page

Pages are requested with the“template” CGI parameter

http://localhost:8080/helloworld/app/template/Demo.vm

Templates name parts are separatedwith commasDemo.vm

demo,Demo.vm

complex,page,Example.vm

Page 56: Rapid application development with Apache Turbine and Maven · Rapid application development with Apache Turbine and Maven Henning Schmiedehausen  Gesellschaft

Template names are not file paths!

� Prior to T2.3, template naming was a mess

� T2.3 introduced the two golden rules for templates:� “Template Names never contain slashes”

� “Template names are no paths. They’re not absolute and have no leading slash”

� A template name can resolve to a very different filename

Page 57: Rapid application development with Apache Turbine and Maven · Rapid application development with Apache Turbine and Maven Henning Schmiedehausen  Gesellschaft

View rendering with Velocity

Page 58: Rapid application development with Apache Turbine and Maven · Rapid application development with Apache Turbine and Maven Henning Schmiedehausen  Gesellschaft

Matching templates

� Page class, Screen and Layout templates are found by a search mechanism

� Java classes and Templates are looked up using various search patterns

� Each search pattern has a default value

� Most search mechanisms work in a hierarchical fashion

Page 59: Rapid application development with Apache Turbine and Maven · Rapid application development with Apache Turbine and Maven Henning Schmiedehausen  Gesellschaft

Matchmaking

� When requesting a Page, Turbine fetches Layout, Screen and Navigation

� Finding a Layout template:

Request: demo,page,Page.vm

1. match: demo,page,Page.vm

2. match: demo,page,Default.vm

3. match: demo,Default.vm

4. match: Default.vm

Page 60: Rapid application development with Apache Turbine and Maven · Rapid application development with Apache Turbine and Maven Henning Schmiedehausen  Gesellschaft

Template Files

� File lookup through Velocity

� Separate trees for all template types

� Templates are kept in sub directories

� This is just the default!

Page 61: Rapid application development with Apache Turbine and Maven · Rapid application development with Apache Turbine and Maven Henning Schmiedehausen  Gesellschaft

Dynamic content

� Until now we have seen only static content

� A Web application (of course) needs active content

� And we haven’t programmed a single line of Java code yet!

� But there were some strange place holders starting with a dollar sign…

Page 62: Rapid application development with Apache Turbine and Maven · Rapid application development with Apache Turbine and Maven Henning Schmiedehausen  Gesellschaft

The Velocity context

� Vehicle between templates and Java code

� The context can contain arbitrary Java objects referenced by a key (hash table)

� Velocity provides access to Bean getters with a short hand notation

� Velocity can call any method on an object in the context.

Page 63: Rapid application development with Apache Turbine and Maven · Rapid application development with Apache Turbine and Maven Henning Schmiedehausen  Gesellschaft

Getting Stuff in the Context

� All Screens in the View are rendered by Java classes

� A mechanism similar to the template lookup exists for the Java classes

� And, of course, we can provide our own class…

Page 64: Rapid application development with Apache Turbine and Maven · Rapid application development with Apache Turbine and Maven Henning Schmiedehausen  Gesellschaft

Example: A Screen class

public class DateScreen

extends VelocityScreen

{

public void doBuildTemplate(RunData data,

Context context)

throws Exception

{

Date d = new Date();

context.put(“date”, d);

}

}

Page 65: Rapid application development with Apache Turbine and Maven · Rapid application development with Apache Turbine and Maven Henning Schmiedehausen  Gesellschaft

Example: Screen Template

The current date is $date.

Page 66: Rapid application development with Apache Turbine and Maven · Rapid application development with Apache Turbine and Maven Henning Schmiedehausen  Gesellschaft

Side Track: RunData Object

� Turbine instantiates a RunData object for each request/response cycle

� This object gives access to user, session and Turbine related information

� It is only valid for one request cycle

“Don’t keep a reference in application objects unless you know exactly what you’re doing!”

Page 67: Rapid application development with Apache Turbine and Maven · Rapid application development with Apache Turbine and Maven Henning Schmiedehausen  Gesellschaft

Screen classes make sense?

� Writing a class for each Screen is much work

� Lots of Code duplication!

� Code and Template must be kept in sync

� All objects must be put in the context by every screen

Screen classes are the push model

Page 68: Rapid application development with Apache Turbine and Maven · Rapid application development with Apache Turbine and Maven Henning Schmiedehausen  Gesellschaft

Turbine Tools

� Tools are small Java classes that implement a turbine-specific tool interface

� Tools are managed and added to the context by Turbine

� Tools have defined scopes and lifetime

Tools are the pull model

Page 69: Rapid application development with Apache Turbine and Maven · Rapid application development with Apache Turbine and Maven Henning Schmiedehausen  Gesellschaft

public class DateTool

implements ApplicationTool

{

private Date d = null;

public DateTool() { /* empty */ }

public void init(Object data)

{

d = new Date();

}

public void refresh() { /* empty */ }

public String getDate() {

return d.toString();

}

}

Example: Date Tool

Application Tool

Interface

Custom Tool Code

Page 70: Rapid application development with Apache Turbine and Maven · Rapid application development with Apache Turbine and Maven Henning Schmiedehausen  Gesellschaft

Activating the Date Tool

� Adding the tool to Turbine configuration

# Request Tool. Refreshed with every request cycle

tool.request.requestDateTool = de.intermeta.demo.tools.DateTool

# Global Tool. Instantiated only once

Tool.global.globalDateTool = de.intermeta.demo.tools.DateTool

� Usage

<p>Request Tool: The current date is $requestDateTool.getDate()</p>

<p>Global Tool: The current date is $globalDateTool.getDate()</p>

Page 71: Rapid application development with Apache Turbine and Maven · Rapid application development with Apache Turbine and Maven Henning Schmiedehausen  Gesellschaft

Tool Scopes

� global global for all sessions

� request per request cycle

� session per user session

� authorized per users session, after login

� persistent per user, is put in storage

Page 72: Rapid application development with Apache Turbine and Maven · Rapid application development with Apache Turbine and Maven Henning Schmiedehausen  Gesellschaft

Predefined tools

� Turbine contains a number of pull tools

� Some tools are even activated by default� $link builds URI for linking template

pages

� $content URI for container provided pageslike images or style sheets

� $page controls HTML HEAD and BODYattributes.

� The RunData object is available as $data

Page 73: Rapid application development with Apache Turbine and Maven · Rapid application development with Apache Turbine and Maven Henning Schmiedehausen  Gesellschaft

Using predefined tools

$page.setBgColor(“red”)

<a href=“$link.setPage(“demo,Target.vm”)”>Go to the Target</a>

<img src=“$content.getURI(“images/apache.png”)”>

Resulting HTML code

<html>

<head><title></title></head>

<body BGCOLOR=“red">

<a href="/demo/app/template/demo%2CTarget.vm">Go to the Target</a>

<img src="/demo/images/apache.png">

</body>

</html>

Page 74: Rapid application development with Apache Turbine and Maven · Rapid application development with Apache Turbine and Maven Henning Schmiedehausen  Gesellschaft

Tool lifecycle

� Tool interface methods� init()

� refresh()

� init() is called at tool initialization

� refresh() is called each time the tool is put

to the context

Page 75: Rapid application development with Apache Turbine and Maven · Rapid application development with Apache Turbine and Maven Henning Schmiedehausen  Gesellschaft

Turbine Actions

� In Model 2+1, the Controller is part of the Turbine servlet

� Turbine provides Actions to map Controller actions to Java classes

� Actions are modules which are managed by the Assembler Broker

� There are no default actions

Page 76: Rapid application development with Apache Turbine and Maven · Rapid application development with Apache Turbine and Maven Henning Schmiedehausen  Gesellschaft

Requesting a Turbine Action

� Actions are requested by providing the action parameter

http://localhost:8080/helloworld/app/action/LoginUser

� The $link Tool contains a few convenience

methods for building Action requests

� Every action has its own class

Page 77: Rapid application development with Apache Turbine and Maven · Rapid application development with Apache Turbine and Maven Henning Schmiedehausen  Gesellschaft

Example: Action

import org.apache.turbine.modules.actions.VelocityAction;

import org.apache.turbine.util.RunData;

import org.apache.velocity.context.Context;

public class DemoAction

extends VelocityAction

{

public void doPerform(RunData data, Context context)

throws Exception

{

String msg = “Action was executed!”;

context.put(“done”, msg);

}

}

Page 78: Rapid application development with Apache Turbine and Maven · Rapid application development with Apache Turbine and Maven Henning Schmiedehausen  Gesellschaft

Executing Actions

� Due to historic reasons, Actions are actually part of the Page

� You can’t change the page from an Action!

Page Execution

Execute ActionExec. Screen,

Layout & Navigation

skip, if no Action defined

Page 79: Rapid application development with Apache Turbine and Maven · Rapid application development with Apache Turbine and Maven Henning Schmiedehausen  Gesellschaft

Action Events

� Grouping actions together in classes is done with ActionEvents

� Action Events are very useful for Forms

� Action Event avoid having lots of classes with just one method

� The $link tool provides methods for dealing

with Action Events

Page 80: Rapid application development with Apache Turbine and Maven · Rapid application development with Apache Turbine and Maven Henning Schmiedehausen  Gesellschaft

Form Submission

� Action Events are called by providing special named parameters to a request

� The method name is prefixed with “eventSubmit_”

<form method=“post”

action=“$link.setPage(“FormResult.vm”).setAction(“FormAction”)”>

Enter a value: <input type=“text” size=“10” name=“value”><br/>

<input type=“submit” value=“Cancel” name=“eventSubmit_doCancel”>

<input type=“submit” value=“Enter” name=“eventSubmit_doEnter”>

</form>

Page 81: Rapid application development with Apache Turbine and Maven · Rapid application development with Apache Turbine and Maven Henning Schmiedehausen  Gesellschaft

Example: Action Event

public class FormAction

extends VelocityAction

{

[…]

public void doCancel(RunData data, Context context)

throws Exception

{

data.setScreenTemplate(“Cancel.vm”);

}

public void doEnter(RunData data, Context context)

throws Exception

{

context.put(“value”, data.getParameters().getString(“value”, “”));

}

}

Page 82: Rapid application development with Apache Turbine and Maven · Rapid application development with Apache Turbine and Maven Henning Schmiedehausen  Gesellschaft

Action Event in a link

� $link provides support for Action events

<a href=“$link.setActionEvent(“FormAction”, “doEnter”)”>

� Resulting HTML Code

<a href=“/demo/app/action/FormAction/eventSubmit_doEnter/1”>

Page 83: Rapid application development with Apache Turbine and Maven · Rapid application development with Apache Turbine and Maven Henning Schmiedehausen  Gesellschaft

Turbine Services

� Singleton based architecture

� Most parts of the Turbine core are services

� Only one Service object per Service for all sessions and users

� Service broker provides management for startup and shutdown

Page 84: Rapid application development with Apache Turbine and Maven · Rapid application development with Apache Turbine and Maven Henning Schmiedehausen  Gesellschaft

Existing Services

� Services used by the HelloWorld application

� AssemblerBroker (Module Management)

� RunData Service (Run Data Management)

� Template Service (Template Lookup)

� Velocity Service (Velocity Rendering)

� Pull Service (Tools)

� Factory & Pool Service (Object Management)

Page 85: Rapid application development with Apache Turbine and Maven · Rapid application development with Apache Turbine and Maven Henning Schmiedehausen  Gesellschaft

Service Management

� Services are configured in the Turbine configuration file

� “late init”: Initialization at first lookup

� “early init”: Initialization at Turbine startup

� Default is “late init”

Page 86: Rapid application development with Apache Turbine and Maven · Rapid application development with Apache Turbine and Maven Henning Schmiedehausen  Gesellschaft

Service lifecycle

Page 87: Rapid application development with Apache Turbine and Maven · Rapid application development with Apache Turbine and Maven Henning Schmiedehausen  Gesellschaft

Turbine Services

� Turbine provides ~ 20 different services

� Security Service (User authentication)

� Intake (Input validation)

� Localization

� Upload (file uploading)

Page 88: Rapid application development with Apache Turbine and Maven · Rapid application development with Apache Turbine and Maven Henning Schmiedehausen  Gesellschaft

Accessing Turbine Services

� Most Turbine services provide a static Façade for calling its methods

� Using the Façade hides the Service lookup and makes the calling code more readable

� Each façade should provide a getService() method for fetching a

reference to the Service object

Page 89: Rapid application development with Apache Turbine and Maven · Rapid application development with Apache Turbine and Maven Henning Schmiedehausen  Gesellschaft

Example: Accessing a Service

public class CryptoTool

implements ApplicationTool

{

private CryptoService cs = null;

[…]

public void init(Object data)

{

cs = TurbineCrypto.getService();

}

[…]

public String encrypt(String value)

throws Exception

{

CryptoAlgorithm ca = cs.getCryptoAlgorithm(“MD5”);

return ca.encrypt(value);

}

}

Page 90: Rapid application development with Apache Turbine and Maven · Rapid application development with Apache Turbine and Maven Henning Schmiedehausen  Gesellschaft

import org.apache.turbine.services.BaseService;

public DemoService

extends BaseService

{

public void init() throws InitializationException

{

setInit(true);

}

public void shutdown()

{

setInit(false);

}

[… add your service methods here …]

}

Example: Service skeleton

Page 91: Rapid application development with Apache Turbine and Maven · Rapid application development with Apache Turbine and Maven Henning Schmiedehausen  Gesellschaft

Activating a Service

� Services are added in the Turbine Configuration

services.DemoService.classname=de.intermeta.demo.DemoService

� For early initialization, an optional parameter can be added

services.DemoService.earlyInit = true

Page 92: Rapid application development with Apache Turbine and Maven · Rapid application development with Apache Turbine and Maven Henning Schmiedehausen  Gesellschaft

Turbine parameter passing

� Turbine allows an application to use three types of parameters

� CGI GET (…?param=value)

� CGI POST (stdin on a POST request)

� PATH_INFO (…/param/value)

� All three methods are equal

� PATH_INFO allows bookmarking

� PATH_INFO params must be in pairs!

Page 93: Rapid application development with Apache Turbine and Maven · Rapid application development with Apache Turbine and Maven Henning Schmiedehausen  Gesellschaft

Getting Parameters

� All CGI and PATH_INFO parameters are pulled together

� Multiple params are available as Arrays

� The RunData object provides access to the parameters

� The values can be queried as various types

Page 94: Rapid application development with Apache Turbine and Maven · Rapid application development with Apache Turbine and Maven Henning Schmiedehausen  Gesellschaft

Getting Parameters

String s = data.getParameters().getString(“val”);

String s = data.getParameters().getString(“val”, “default”);

int i = data.getParameters().getInt(“val”);

int i = data.getParameters().getInt(“val”, 0);

int [ ] i = data.getParameters().getInts(“val”);

boolean b = data.getParameters().getBoolean(“bool”, false);

Set allParamNames = data.getParameters().keySet();

Page 95: Rapid application development with Apache Turbine and Maven · Rapid application development with Apache Turbine and Maven Henning Schmiedehausen  Gesellschaft

Turbine Configuration

� Turbine uses commons-configuration to read its configuration

� Default is properties based configuration fromTurbineResources.properties file

� multiple lines or comma-separated values are provided as multiple values for a property

� M.E.T.A. separates application and core configuration

Page 96: Rapid application development with Apache Turbine and Maven · Rapid application development with Apache Turbine and Maven Henning Schmiedehausen  Gesellschaft

End of Part 2

� What have we done?

� Learned about the main parts of Turbine

� View with Page, Screen, Navigation, Layout

� Tools

� Pull and Push model

� Controller with Action and Action Events

� Services

Page 97: Rapid application development with Apache Turbine and Maven · Rapid application development with Apache Turbine and Maven Henning Schmiedehausen  Gesellschaft

five minute break

Page 98: Rapid application development with Apache Turbine and Maven · Rapid application development with Apache Turbine and Maven Henning Schmiedehausen  Gesellschaft

Part 3

Turbine example: ApacheFaces

Page 99: Rapid application development with Apache Turbine and Maven · Rapid application development with Apache Turbine and Maven Henning Schmiedehausen  Gesellschaft

About ApacheFaces

� An application to be able to “match faces to names”

� Written as an entry to the ApacheCon 2004 Derby programming contest

� Written in about six hours during AC2004

� Built with M.E.T.A. in “normal” mode

� Made 2nd place

Page 100: Rapid application development with Apache Turbine and Maven · Rapid application development with Apache Turbine and Maven Henning Schmiedehausen  Gesellschaft

Requirements

� User Self service

� Authentication

� Image upload

� Confirmation through mail

� Turbine “best practices”

Page 101: Rapid application development with Apache Turbine and Maven · Rapid application development with Apache Turbine and Maven Henning Schmiedehausen  Gesellschaft

Turbine core

Model

Login/Logout

Images

Password

Program structure

Login

Actio

n

Requ

estA

ctio

n

EditA

ctio

n

Passw

ord

Actio

n

Top.vmBottom.vm

Index.vmEdit.vmRequest.vm

Default.vm

Beans

otherHelpers

TR.propsApp cfg

Intake cfgTorque cfgSchema

Page 102: Rapid application development with Apache Turbine and Maven · Rapid application development with Apache Turbine and Maven Henning Schmiedehausen  Gesellschaft

Code highlighting

� Main Page

� User Login from Template to Model

� Image Upload

Page 103: Rapid application development with Apache Turbine and Maven · Rapid application development with Apache Turbine and Maven Henning Schmiedehausen  Gesellschaft

Main Page

Bottom.vm

Top.vm

Index.vm

Page 104: Rapid application development with Apache Turbine and Maven · Rapid application development with Apache Turbine and Maven Henning Schmiedehausen  Gesellschaft

#set($userModel = $!model.User)

#set($userList = $!userModel.List)

#set($imageModel = $!model.Image)

<table class="userlist">

<tr class="userlist">

<th class="userlist">Apache Login</th>

<th class="userlist">Mail address (outside Apache)</th>

<th class="userlist">User name</th>

<th class="userlist">Image</th>

</tr>

#foreach ($u in $userList)

<tr class="userlist">

<td class="userlist"><a href="mailto:${u.Name}@apache.org">$u.Name</a></td>

<td class="userlist"><a href="mailto:$!u.Email">$!u.Email</a></td>

<td class="userlist">$!u.FirstName $!u.LastName</td>

$imageModel.setUser($u)

#if ($imageModel.hasImage())

<td class="userlist"><img src="$link.setPage("ImageScreen.vm")" width="72 height="101"/></td>

#else

<td class="userlist">(no image yet)</td>

#end

</tr>

#end

</table>

Index.vm

$model Tool usage

Velocity Loop

Bean properties

$link tool usage / Raw Screen

Page 105: Rapid application development with Apache Turbine and Maven · Rapid application development with Apache Turbine and Maven Henning Schmiedehausen  Gesellschaft

#if ($user.hasLoggedIn())<table class="login"><tr><td>Logged in as $user.Name ($user.FirstName $user.LastName)</td></tr><tr><td><a class="login" href="$link.setAction("LogoutUser")">Logout</a></td></tr><tr><td><a class="login" href="$link.setActionEvent("edit.EditAction", "doEdit")">Edit Entry</a></td></tr><tr><td><a class="login" href="$link.setActionEvent("passwd.PasswordAction", "doEdit")">Change

Password</a></td></tr></table>

#else#set ($frm = $intake.get("Login").Default)<form method="post" action=“$link.setAction("login.LoginAction") "><table class="login"><tr class="login">

#inputRow_text_style("Login" $frm "Login" "16" "64" "login")#inputRow_password_style("Passwort" $frm "Password" "16" "64" "login" )

</tr>#inputRow_error_size($frm "Login" 4)#inputRow_error_size($frm "Password" 4)<tr class="login"><td class="login_submit" colspan="2"><input type="submit" name="eventSubmit_doLogin" value="Log on"></td><td colspan="2"><a class="login" href="$link.setActionEvent("request.RequestAction", "doRequest")">Request

Password</a></td></tr></table>

#DisplayMessage($data "1")$intake.declareGroups()

</form>#end

Top.vm

User is logged in

Action and Action event in form

Action event in link

Velocity Macros

Page 106: Rapid application development with Apache Turbine and Maven · Rapid application development with Apache Turbine and Maven Henning Schmiedehausen  Gesellschaft

Intake for Login form

<group name="Login" key="log"><field name="Login" key="l" type="String" >

<rule name="maxLength" value="64">The user name must have lessthan 64 characters</rule>

<rule name="required" value="true">You must supply an username</rule>

<rule name="mask" value="^[a-zA-Z][\w\d\.\-]*$">This user name isillegal</rule>

</field><field name="Password" key="p" type="String">

<rule name="maxLength" value="16">Password must be 16characters or less!</rule>

<rule name="required" value="true">You must enter a password!</rule>

</field></group>

Page 107: Rapid application development with Apache Turbine and Maven · Rapid application development with Apache Turbine and Maven Henning Schmiedehausen  Gesellschaft

Login Action Event

public class LoginAction extends BaseAction {

public void doLogin(RunData data, Context context) throws Exception {

IntakeTool intake = (IntakeTool) context.get("intake");

if (!intake.isAllValid()) return;

Group grp = intake.get("Login", IntakeTool.DEFAULT_KEY);

String username = grp.get("Login").toString();

String password = grp.get("Password").toString();

LoginModel loginModel = LoginModel.getModel(data);

loginModel.login(username, password);

intake.remove(grp);

}

[…]

Test if Intake fields are valid

Get LoginModel throughstatic service facade

Page 108: Rapid application development with Apache Turbine and Maven · Rapid application development with Apache Turbine and Maven Henning Schmiedehausen  Gesellschaft

Login Modelpublic class LoginModel extends ApachefacesModel implements Model {

public static LoginModel getModel(RunData data) throws Exception {

return (LoginModel) TurbineModel.getModel("ApachefacesLogin", data);

}

public void login(String username, String password) throws Exception {

User user = data.getUser();

if ((user == null) || TurbineSecurity.isAnonymousUser(user)) {

if (StringUtils.equals(password, "")) {

data.setMessage("Login failed");

return;

}

try {

user = TurbineSecurity.getAuthenticatedUser(username, password);

data.setUser(user);

user.setHasLoggedIn(Boolean.TRUE);

user.updateLastLogin();

data.save();

} catch (TurbineSecurityException tse) {

data.setUser(TurbineSecurity.getAnonymousUser());

data.setMessage("Login failed");

}

} else {

data.setUser(TurbineSecurity.getAnonymousUser());

data.setMessage("Double Login attempted");

}

}

static Model facade

User authentication

Page 109: Rapid application development with Apache Turbine and Maven · Rapid application development with Apache Turbine and Maven Henning Schmiedehausen  Gesellschaft

Model Service and Models

services.ModelService.classname =

org.apache.turbine.services.model.ModelServiceImpl

services.ModelService.model.ApachefacesLogin =

org.apache.turbine.apachefaces.model.LoginModel

services.ModelService.model.User =

org.apache.turbine.apachefaces.model.UserModel

services.ModelService.model.Image =

org.apache.turbine.apachefaces.model.ImageModel

Page 110: Rapid application development with Apache Turbine and Maven · Rapid application development with Apache Turbine and Maven Henning Schmiedehausen  Gesellschaft

Image Uploadpublic class EditAction extends BaseAction {

public void doSave(RunData data, Context context) throws Exception {

IntakeTool intake = (IntakeTool) context.get("intake");

if (!intake.isAllValid()) return;

Group grp = IntakeHelper.get(data, context, "User");

Group grp2 = IntakeHelper.get(data, context, "Image");

ApacheUser user = (ApacheUser) data.getUser();

grp.setProperties(user);

String fkey = grp2.get("Image").getKey();

FileItem [] fi = data.getParameters().getFileItems(fkey);

if ((fi != null) && (fi.length > 0)) {

byte [] img = fi[0].get();

if ((img != null) && (img.length > 0)) {

user.setImage(img);

}

}

data.save();

data.setScreenTemplate("Index.vm");

intake.remove(grp);

}

set bean properties

Get uploaded file

Save user data

Change template

Page 111: Rapid application development with Apache Turbine and Maven · Rapid application development with Apache Turbine and Maven Henning Schmiedehausen  Gesellschaft

User Schema

<table name="APACHE_USER" idMethod="idbroker"><column name="USER_ID" required="true" primaryKey="true" type="INTEGER"/><column name="LOGIN_NAME" required="true" size="64" type="VARCHAR" javaName="UserName"/><column name="PASSWORD_VALUE" required="true" size="16" type="VARCHAR"

javaName="Password"/><column name="FIRST_NAME" required="true" size="64" type="VARCHAR"/><column name="LAST_NAME" required="true" size="64" type="VARCHAR"/><column name="EMAIL" size="64" type="VARCHAR"/><column name="CONFIRM_VALUE" size="16" type="VARCHAR" javaName="Confirmed"/><column name="MODIFIED" type="TIMESTAMP" size="0"/><column name="CREATED" type="TIMESTAMP" size="0" javaName="CreateDate"/><column name="LAST_LOGIN" type="TIMESTAMP" size="0"/><column name="OBJECTDATA" type="VARBINARY"/>

<column name="IMAGE" type="VARBINARY"/>

<unique><unique-column name="LOGIN_NAME"/>

</unique>

</table>

Turbine Security

Custom extension

Page 112: Rapid application development with Apache Turbine and Maven · Rapid application development with Apache Turbine and Maven Henning Schmiedehausen  Gesellschaft

Application stats

� ~ 1400 lines of Java code (with comments!)

� ~ 760 lines of Velocity templates

� ~ 300 lines other code (.xml, .properties)

� 4 action classes

� 1 custom service

Page 113: Rapid application development with Apache Turbine and Maven · Rapid application development with Apache Turbine and Maven Henning Schmiedehausen  Gesellschaft

Where to go from here

� The Turbine home page

� http://jakarta.apache.org/turbine/

� All materials from this talk are available at

� http://henning.schmiedehausen.org/turbine/

Page 114: Rapid application development with Apache Turbine and Maven · Rapid application development with Apache Turbine and Maven Henning Schmiedehausen  Gesellschaft

Any questions?

Page 115: Rapid application development with Apache Turbine and Maven · Rapid application development with Apache Turbine and Maven Henning Schmiedehausen  Gesellschaft

Thanks a lot for your attention!