cloud foundry, spring and vaadin

87
Get to Production Quicker with Spring, Vaadin and Cloud Foundry Josh Long @starbuxman [email protected] Wednesday, February 15, 12

Upload: josh-long

Post on 11-May-2015

3.396 views

Category:

Technology


8 download

DESCRIPTION

Want to get to production quickly? RAD tools like Spring Roo, with its support for beautiful, quick UI generation through addons like the Vaadin Roo addon, and Cloud Foundry, which take care of everything under the code, are an ideal combination. In this talk Josh Long, Spring Developer Advocate for SpringSource, introduces the 1-2-3 punch of Cloud Foundry, Roo and Vaadin.

TRANSCRIPT

Page 1: Cloud Foundry, Spring and Vaadin

Get to Production Quicker with

Spring, Vaadin and Cloud Foundry

Josh Long @[email protected]

Wednesday, February 15, 12

Page 2: Cloud Foundry, Spring and Vaadin

NOT CONFIDENTIAL -- TELL EVERYONE

About Josh Long

Spring Developer Advocatetwitter: @[email protected]

2

Wednesday, February 15, 12

Page 3: Cloud Foundry, Spring and Vaadin

Cloud Developer Bill of Rights (www.developerrights.org)

The Right to Code use the best tools for the job The Right to Build Applications (and Only Applications) : devs != admins The Right to Cloud Portability : write once, run anywhere (really!) The Right to a Choice of Frameworks I say “potato,” you say “Node.js” The Right to a Choice of Application Services MySQL, Redis, Mongo, All? More? The Right to Platform Transparency simple != opaque; I need logs damnit!The Right to Emigrate it’s your code, your data, always. you can take it and leave.The Right of Ownership it’s your code, your data, always. you own access rights.The Right to Be Left Alone even applications need personal space, respect!The Right to Open Source lots of clouds during spring - both Apache2 licensed!

3

Wednesday, February 15, 12

Page 4: Cloud Foundry, Spring and Vaadin

Flexible Administration

4

Application Lifecycle API• Create, start, stop, update• Set URL(s), instance count, memory• Get stats, logs, crashes, files

Services API• Enumerate system services• Select and create service instance• Bind and unbind service & app(s)

Cloud Foundry

APIs

Also includes• account spacing• clients: STS, VMC• Info API for both system and account space

Wednesday, February 15, 12

Page 5: Cloud Foundry, Spring and Vaadin

Cloud Foundry: Choice of Runtimes

5

Wednesday, February 15, 12

Page 6: Cloud Foundry, Spring and Vaadin

Frameworks and Runtimes Supported

6

•Out of the Box• Java (.WAR files, on Tomcat. Spring’s an ideal choice here, of course..)•Scala (Lift, Play!)•Ruby (Rails, Sinatra, etc.)•Node.js•Other•Python (Stackato)•PHP (AppFog)•Haskell (1)•Erlang (2)

1) http://www.cakesolutions.net/teamblogs/2011/11/25/haskell-happstack-on-cloudfoundry/2) https://github.com/cloudfoundry/vcap/pull/20

Wednesday, February 15, 12

Page 7: Cloud Foundry, Spring and Vaadin

Deploying an Application

7

$ vmc push cf1 --path target \ --url cer-cf1.cloudfoundry.com

CLI Application name Dir containing application (or, .WAR for Java)

Application URL

Wednesday, February 15, 12

Page 8: Cloud Foundry, Spring and Vaadin

$ vmc push cf1 --path target \ --url cer-cf1.cloudfoundry.comDetected a Java Web Application, is this correct?

[Yn]:

Deploying an Application

Wednesday, February 15, 12

Page 9: Cloud Foundry, Spring and Vaadin

$ vmc push cf1 --path target \ --url cer-cf1.cloudfoundry.comDetected a Java Web Application, is this correct?

[Yn]:

Memory Reservation [Default:512M] (64M, 128M, 256M, 512M, 1G or 2G)

Deploying an Application

Wednesday, February 15, 12

Page 10: Cloud Foundry, Spring and Vaadin

$ vmc push cf1 --path target \ --url cer-cf1.cloudfoundry.comDetected a Java Web Application, is this correct?

[Yn]:

Memory Reservation [Default:512M] (64M, 128M, 256M, 512M, 1G or 2G)

Creating Application: OKWould you like to bind any services to 'cf1'? [yN]:

Deploying an Application

Wednesday, February 15, 12

Page 11: Cloud Foundry, Spring and Vaadin

$ vmc push cf1 --path target \ --url cer-cf1.cloudfoundry.comDetected a Java Web Application, is this correct?

[Yn]:

Memory Reservation [Default:512M] (64M, 128M, 256M, 512M, 1G or 2G)

Creating Application: OKWould you like to bind any services to 'cf1'? [yN]:

Uploading Application: Checking for available resources: OK Packing application: OK Uploading (2K): OK Push Status: OKStarting Application: OK

Deploying an Application

Wednesday, February 15, 12

Page 12: Cloud Foundry, Spring and Vaadin

$ vmc push Would you like to deploy from the current directory?

[Yn]: yPushing application 'html5expenses'...Creating Application: OKCreating Service [expenses-mongo]: OKBinding Service [expenses-mongo]: OKCreating Service [expenses-postgresql]: OKBinding Service [expenses-postgresql]: OKUploading Application: Checking for available resources: OK Processing resources: OK Packing application: OK Uploading (6K): OK Push Status: OK

Deploying an Application (with a Manifest)

Wednesday, February 15, 12

Page 13: Cloud Foundry, Spring and Vaadin

---

applications:

target:

name: html5expenses

url: ${name}.${target-base}

framework:

name: spring

info:

mem: 512M

description: Java SpringSource Spring Application

exec:

mem: 512M

instances: 1

services:

expenses-mongo:

type: :mongodb

expenses-postgresql:

type: :postgresql

Deploying an Application (with a manifest.yml)

Wednesday, February 15, 12

Page 14: Cloud Foundry, Spring and Vaadin

Deployment with STS

Wednesday, February 15, 12

Page 15: Cloud Foundry, Spring and Vaadin

Cloud Foundry: Choice of Clouds

12

Wednesday, February 15, 12

Page 16: Cloud Foundry, Spring and Vaadin

Main Risk: Lock In

13

Welcome to the hotel californiaSuch a lovely placeSuch a lovely facePlenty of room at the hotel californiaAny time of year, you can find it here

Last thing I remember, I wasRunning for the doorI had to find the passage backTo the place I was before’relax,’ said the night man,We are programmed to receive.You can checkout any time you like,But you can never leave!

-the Eagles

Wednesday, February 15, 12

Page 17: Cloud Foundry, Spring and Vaadin

Open Source Advantage

14

Open Source Advantage

Wednesday, February 15, 12

Page 18: Cloud Foundry, Spring and Vaadin

Open Source AdvantageOpen Source Advantage

Wednesday, February 15, 12

Page 19: Cloud Foundry, Spring and Vaadin

Cloud Foundry: Clouds

16

Joyent• community lead for Node.js

ActiveState• community lead for Python, Perl•Providers of Stackato private PaaS

AppFog.com• community lead for PHP•PaaS for PHP

Wednesday, February 15, 12

Page 20: Cloud Foundry, Spring and Vaadin

17

Cloud Foundry.orgCloud Foundry Community

Wednesday, February 15, 12

Page 21: Cloud Foundry, Spring and Vaadin

Micro Cloud Foundry (beta)Micro Cloud Foundry

Wednesday, February 15, 12

Page 22: Cloud Foundry, Spring and Vaadin

Cloud Foundry: Services

19

Wednesday, February 15, 12

Page 23: Cloud Foundry, Spring and Vaadin

Cloud Foundry: Services

Services are one of the extensibility planes in Cloud Foundry• there are more services being contributed by the community daily!

MySQL, Redis, MongoDB, RabbitMQ, PostgreSQL

Services may be shared across applications

Cloud Foundry abstracts the provisioning aspect of services through a uniform API hosted in the cloud controller

It’s very easy to take an app and add a service to the app in a uniform way•Cassandra? COBOL / CICS, Oracle

20

Wednesday, February 15, 12

Page 24: Cloud Foundry, Spring and Vaadin

Cloud Foundry: Services

21

$ vmc create-service mysql --name mysql1Creating Service: OK

$ vmc services

============== System Services ==============+------------+---------+---------------------------------------+| Service | Version | Description |+------------+---------+---------------------------------------+| mongodb | 1.8 | MongoDB NoSQL store || mysql | 5.1 | MySQL database service || postgresql | 9.0 | PostgreSQL database service (vFabric) || rabbitmq | 2.4 | RabbitMQ messaging service || redis | 2.2 | Redis key-value store service |+------------+---------+---------------------------------------+

=========== Provisioned Services ============

+-------------+---------+| Name | Service |+-------------+---------+| mysql1 | mysql |+-------------+---------+

Wednesday, February 15, 12

Page 25: Cloud Foundry, Spring and Vaadin

Cloud Foundry: Services Creation and Binding

22

$VCAP_SERVICES: {"redis-2.2":[{"name":"redis_sample","label":"redis-2.2","plan":"free","tags":["redis","redis-2.2","key-value","nosql"],"credentials":{"hostname":"172.30.48.40","host":"172.30.48.40","port":5023,"password":"8e9a901f-987d-4544-9a9e-ab0c143b5142","name":"de82c4bb-bd08-46c0-a850-af6534f71ca3"}}],"mongodb-1.8":[{"name":"mongodb-e7d29","label":"mongodb-1.8","plan":"free","tags”:………………….

Wednesday, February 15, 12

Page 26: Cloud Foundry, Spring and Vaadin

Accessing Your Services

Debugging and accessing the data locally• Caldecott --> Service tunneling. Access your Cloud Foundry service as if it was local.

23

Wednesday, February 15, 12

Page 27: Cloud Foundry, Spring and Vaadin

Tunneling

24

gem install caldecottvmc tunnel <mongodb>

Wednesday, February 15, 12

Page 28: Cloud Foundry, Spring and Vaadin

Using your favorite tools

25

Wednesday, February 15, 12

Page 29: Cloud Foundry, Spring and Vaadin

26

Wednesday, February 15, 12

Page 30: Cloud Foundry, Spring and Vaadin

intro to Spring

27

Wednesday, February 15, 12

Page 31: Cloud Foundry, Spring and Vaadin

de-facto standard programming model for enterprise Java Two million+ developers Rapid evolution• Spring 1.0 – March 2004• Spring 2.0 – October 2006• Spring 2.5 – December 2007• Spring 3.0 – November 2009• Spring 3.1 - December 2011

Complete backward compatibility

The Spring framework

Wednesday, February 15, 12

Page 32: Cloud Foundry, Spring and Vaadin

Spring’s aim:

bring simplicity to java development

29

web tier &

RIAservice tier batch

processingintegration & messaging

data access

/ NoSQL / Big Data

mobile

tc ServerTomcat

Jetty

lightweight

CloudFoundryGoogle App Engine

Amazon Web Services

the cloud:

WebSphereJBoss ASWebLogic

(on legacy versions, too!)

traditional

The Spring framework

Wednesday, February 15, 12

Page 33: Cloud Foundry, Spring and Vaadin

The Spring Framework

30

Framework Description

Spring Core The foundation

Spring @MVC the web leading framework (comes with the core framework)

Spring Security Extensible framework providing authentication, authorization

Spring Webflow An excellent web framework for building multi-page flows

Spring Web Services Contract-first, document–centric SOAP and XML web services

Spring Batch Powerful batch processing framework

Spring Integration Implements enterprise integration patterns

Spring BlazeDS Support for Adobe BlazeDS

Spring AMQP interface with AMQP message brokers, like RabbitMQ

Spring Data NoSQL options: HBase, MongoDB, Redis, Riak, CouchDB, Neo4J, etc.

Spring Social integrate Twitter, Facebook, Tripit, MySpace, LinkedIn, etc.

Spring Hadoop Provides a POJO-centric approach to building Hadoop applications

Spring Mobile, Spring Android provides first-class support for service creation and consumption for iPhone, Android

Spring GemFire Provides the easiest interface for the GemFire enterprise data grid technology

Wednesday, February 15, 12

Page 34: Cloud Foundry, Spring and Vaadin

The Spring ApplicationContext

Spring Beans are Managed by An ApplicationContext•whether you’re in an application server, a web server, in regular Java SE application, in

the cloud, Spring is initialized through an ApplicationContext• In a Java SE application:

• In a web application, you will configure an application context in your web.xml

31

ApplicationContext ctx = new GenericAnnotationApplicationContext( “com.foo.bar.my.package”);

<servlet> <servlet-name>Spring Dispatcher Servlet</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value>my.spring.ConfigurationClass</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet>

Wednesday, February 15, 12

Page 35: Cloud Foundry, Spring and Vaadin

Tell Spring About Your Objects

32

package org.springsource.examples.spring31.services;... @Configuration@ComponentScan(“the.package.with.beans.in.it”)public class ServicesConfiguration { ...

}

Wednesday, February 15, 12

Page 36: Cloud Foundry, Spring and Vaadin

Tell Spring About Your Objects

33

public class Main { static public void main (String [] args) throws Throwable { ApplicationContext ac = new AnnotationConfigApplicationContext( org.springsource.examples.spring31.services.ServicesConfiguration.class); ... }}

Wednesday, February 15, 12

Page 37: Cloud Foundry, Spring and Vaadin

Tell Spring About Your Objects

34

package the.package.with.beans.in.it;

@Servicepublic class CustomerService {

public Customer createCustomer(String firstName, String lastName, Date signupDate) {

}

...

}

Wednesday, February 15, 12

Page 38: Cloud Foundry, Spring and Vaadin

Tell Spring About Your Objects

35

package org.springsource.examples.spring31.services;... @Configurationpublic class ServicesConfiguration { @Bean public DataSource dataSource() throws Exception { SimpleDriverDataSource simpleDriverDataSource = new SimpleDriverDataSource(); .... return simpleDriverDataSource; } }

I want Database Access ...

Wednesday, February 15, 12

Page 39: Cloud Foundry, Spring and Vaadin

Tell Spring About Your Objects

36

package org.springsource.examples.spring31.services;... @Configurationpublic class ServicesConfiguration {

@Bean public SessionFactory sessionFactory() throws Exception { Properties props = new Properties(); // ... show_sql, dialect, etc. return new LocalSessionFactoryBuilder(this.dataSource()) .addAnnotatedClasses(Customer.class) .addProperties(props) .buildSessionFactory(); }

}

I want Database Access ... with Hibernate 4 Support

Wednesday, February 15, 12

Page 40: Cloud Foundry, Spring and Vaadin

Tell Spring About Your Objects

37

package the.package.with.beans.in.it;...@Servicepublic class CustomerService {

@javax.inject.Inject private SessionFactory sessionFactory;

public Customer createCustomer(String firstName, String lastName, Date signupDate) { Customer customer = new Customer(); customer.setFirstName(firstName); customer.setLastName(lastName); customer.setSignupDate(signupDate);

sessionFactory.getCurrentSession().save(customer); return customer; }

...

}

Wednesday, February 15, 12

Page 41: Cloud Foundry, Spring and Vaadin

Tell Spring About Your Objects

38

package org.springsource.examples.spring31.services;... @Configuration@EnableTransactionManagementpublic class ServicesConfiguration {

...

@Bean public PlatformTransactionManager transactionManager() throws Exception { return new HibernateTransactionManager(this.sessionFactory()); }}

I want Declarative Transaction Management

Wednesday, February 15, 12

Page 42: Cloud Foundry, Spring and Vaadin

Tell Spring About Your Objects

39

package the.package.with.beans.in.it;...@Servicepublic class CustomerService {

@javax.inject.Inject private SessionFactory sessionFactory;

@Transactional public Customer createCustomer(String firstName, String lastName, Date signupDate) { Customer customer = new Customer(); customer.setFirstName(firstName); customer.setLastName(lastName); customer.setSignupDate(signupDate);

sessionFactory.getCurrentSession().save(customer); return customer; }

...

}Wednesday, February 15, 12

Page 43: Cloud Foundry, Spring and Vaadin

Tell Spring About Your Objects

40

package org.springsource.examples.spring31.services;... @Configuration@EnableTransactionManagement@EnableCachingpublic class ServicesConfiguration {

...

@Bean public CacheManager cacheManager() { SimpleCacheManager scm = new SimpleCacheManager(); Cache cache = new ConcurrentMapCache("customers"); scm.setCaches(Arrays.asList(cache)); return scm; }}

I want Declarative Cache Management

Wednesday, February 15, 12

Page 44: Cloud Foundry, Spring and Vaadin

Tell Spring About Your Objects

41

package the.package.with.beans.in.it;...@Servicepublic class CustomerService {

@javax.inject.Inject private SessionFactory sessionFactory;

@Transactional @Cacheable(“customers”) public Customer createCustomer(String firstName, String lastName, Date signupDate) { Customer customer = new Customer(); customer.setFirstName(firstName); customer.setLastName(lastName); customer.setSignupDate(signupDate);

sessionFactory.getCurrentSession().save(customer); return customer; }

...

}Wednesday, February 15, 12

Page 45: Cloud Foundry, Spring and Vaadin

Spring makes Java as powerful as can be... Java’s still missing a few things• dynanicism• Java EE still filled with too much boilerplate code• UI generation is still not appropriate with Java, and requires an alternative view technology

• Domain Driven Design isn’t particularly elegant

Answer: Spring Roo

Buuut....

Wednesday, February 15, 12

Page 46: Cloud Foundry, Spring and Vaadin

Not confidential - tell everyone!

the Pyramid of Opinionation

43

Spring Roo, Grails

the Spring framework

straight Java EE, assembler Mor

e op

inio

nate

d

Wednesday, February 15, 12

Page 47: Cloud Foundry, Spring and Vaadin

Not confidential - tell everyone! 44

What Is Spring Roo?

Wednesday, February 15, 12

Page 48: Cloud Foundry, Spring and Vaadin

Not confidential - tell everyone! 44

What Is Spring Roo?

Rapid Application Development tool• 100% Java

Wednesday, February 15, 12

Page 49: Cloud Foundry, Spring and Vaadin

Not confidential - tell everyone! 44

What Is Spring Roo?

Rapid Application Development tool• 100% Java

Based on other Spring projects•Spring, Spring @MVC, Spring Security, WebFlow...

Wednesday, February 15, 12

Page 50: Cloud Foundry, Spring and Vaadin

Not confidential - tell everyone! 44

What Is Spring Roo?

Rapid Application Development tool• 100% Java

Based on other Spring projects•Spring, Spring @MVC, Spring Security, WebFlow...

Supports standards• JPA 2• JSR 303 (javax.validation.*)

Wednesday, February 15, 12

Page 51: Cloud Foundry, Spring and Vaadin

Not confidential - tell everyone! 44

What Is Spring Roo?

Rapid Application Development tool• 100% Java

Based on other Spring projects•Spring, Spring @MVC, Spring Security, WebFlow...

Supports standards• JPA 2• JSR 303 (javax.validation.*)

Uses a command-line tool for smart code generation

Wednesday, February 15, 12

Page 52: Cloud Foundry, Spring and Vaadin

Not confidential - tell everyone! 45

Out Of The Box

Project managementGeneral object servicesEntity supportField managementPersistence w/JPA, Neo4J, etc.JUnit testingDynamic findersSpring MVC, Spring Web Flow and SeleniumGWT, Vaadin, FlexJMS, SMTP and build system integrationSpring Security, Bundlor, Logging Setup.....DBRE

Wednesday, February 15, 12

Page 53: Cloud Foundry, Spring and Vaadin

Not confidential - tell everyone!

Roo overview

46

Wednesday, February 15, 12

Page 54: Cloud Foundry, Spring and Vaadin

Not confidential - tell everyone!

Active code generation

47

Wednesday, February 15, 12

Page 55: Cloud Foundry, Spring and Vaadin

Creating a Roo App

48

Wednesday, February 15, 12

Page 56: Cloud Foundry, Spring and Vaadin

Not confidential - tell everyone!

Domain Models

Multiple routes:• on the fly, declarative domain development •DBRE (good for tool driven MDA (just add the Roo annotations as well as existing

schema)

49

Wednesday, February 15, 12

Page 57: Cloud Foundry, Spring and Vaadin

Not confidential - tell everyone!

DBRE - the domain

Wednesday, February 15, 12

Page 58: Cloud Foundry, Spring and Vaadin

Not confidential - tell everyone!

DBRE - the domain

51

database properties set --key database.url \ --value jdbc:h2:tcp://localhost/~/roo_crm

1)

2) database reverse engineer \ --package ~.domain --schema PUBLIC

Wednesday, February 15, 12

Page 59: Cloud Foundry, Spring and Vaadin

Setting Up The Domain Model

52

persistence setup --provider ECLIPSELINK --database HYPERSONIC_IN_MEMORY

entity --class ~.domain.Topping --testAutomaticallyfield string --fieldName name --notNull --sizeMin 2entity --class ~.domain.Base --testAutomaticallyfield string --fieldName name --notNull --sizeMin 2entity --class ~.domain.Pizza --testAutomaticallyfield string --fieldName name --notNull --sizeMin 2field number --fieldName price --type java.lang.Floatfield set --fieldName toppings --type ~.domain.Toppingfield reference --fieldName base --type ~.domain.Baseentity --class ~.domain.PizzaOrder --testAutomaticallyfield string --fieldName name --notNull --sizeMin 2field string --fieldName address --sizeMax 30field number --fieldName total --type java.lang.Floatfield date --fieldName deliveryDate --type java.util.Datefield set --fieldName pizzas --type ~.domain.Pizza

perform tests

Wednesday, February 15, 12

Page 60: Cloud Foundry, Spring and Vaadin

____ ____ ____ / __ \/ __ \/ __ \ / /_/ / / / / / / / / _, _/ /_/ / /_/ / /_/ |_|\____/\____/ 1.1.5.RELEASE [rev d3a68c3]

Welcome to Spring Roo. For assistance press CTRL+SPACE or type "hint" then hit ENTER.roo> pgp trust --keyId 0xBF0451C0Added trust for key:>>>> KEY ID: 0xBF0451C0 <<<< More Info: http://keyserver.ubuntu.com/pks/lookup?fingerprint=on&op=index&search=0xBF0451C0 Created: 2009-Aug-14 11:54:20 +0000 Fingerprint: cc57399d74cd7e4768ed6fa4ca62973fbf0451c0 Algorithm: DSA User ID: Artur Signell <[email protected]> Signed By: Key 0xBF0451C0 (Artur Signell <[email protected]>) Subkey ID: 0x17EBEE72 [ELGAMAL_ENCRYPT]

Setup the Vaadin Addon

53

Wednesday, February 15, 12

Page 61: Cloud Foundry, Spring and Vaadin

____ ____ ____ / __ \/ __ \/ __ \ / /_/ / / / / / / / / _, _/ /_/ / /_/ / /_/ |_|\____/\____/ 1.1.5.RELEASE [rev d3a68c3]

Welcome to Spring Roo. For assistance press CTRL+SPACE or type "hint" then hit ENTER.roo> pgp trust --keyId 0xBF0451C0Added trust for key:>>>> KEY ID: 0xBF0451C0 <<<< More Info: http://keyserver.ubuntu.com/pks/lookup?fingerprint=on&op=index&search=0xBF0451C0 Created: 2009-Aug-14 11:54:20 +0000 Fingerprint: cc57399d74cd7e4768ed6fa4ca62973fbf0451c0 Algorithm: DSA User ID: Artur Signell <[email protected]> Signed By: Key 0xBF0451C0 (Artur Signell <[email protected]>) Subkey ID: 0x17EBEE72 [ELGAMAL_ENCRYPT]

____ ____ ____ / __ \/ __ \/ __ \ / /_/ / / / / / / / / _, _/ /_/ / /_/ / /_/ |_|\____/\____/ 1.1.5.RELEASE [rev d3a68c3]

Welcome to Spring Roo. For assistance press CTRL+SPACE or type "hint" then hit ENTER.roo> pgp trust --keyId 0xBF0451C0Added trust for key:>>>> KEY ID: 0xBF0451C0 <<<< More Info: http://keyserver.ubuntu.com/pks/lookup?fingerprint=on&op=index&search=0xBF0451C0 Created: 2009-Aug-14 11:54:20 +0000 Fingerprint: cc57399d74cd7e4768ed6fa4ca62973fbf0451c0 Algorithm: DSA User ID: Artur Signell <[email protected]> Signed By: Key 0xBF0451C0 (Artur Signell <[email protected]>) Subkey ID: 0x17EBEE72 [ELGAMAL_ENCRYPT]

roo> download accept terms of useThank you. All Spring Roo download features have now been enabled.

54

Setup the Vaadin Addon

Wednesday, February 15, 12

Page 62: Cloud Foundry, Spring and Vaadin

____ ____ ____ / __ \/ __ \/ __ \ / /_/ / / / / / / / / _, _/ /_/ / /_/ / /_/ |_|\____/\____/ 1.1.5.RELEASE [rev d3a68c3]

Welcome to Spring Roo. For assistance press CTRL+SPACE or type "hint" then hit ENTER.roo> pgp trust --keyId 0xBF0451C0Added trust for key:>>>> KEY ID: 0xBF0451C0 <<<< More Info: http://keyserver.ubuntu.com/pks/lookup?fingerprint=on&op=index&search=0xBF0451C0 Created: 2009-Aug-14 11:54:20 +0000 Fingerprint: cc57399d74cd7e4768ed6fa4ca62973fbf0451c0 Algorithm: DSA User ID: Artur Signell <[email protected]> Signed By: Key 0xBF0451C0 (Artur Signell <[email protected]>) Subkey ID: 0x17EBEE72 [ELGAMAL_ENCRYPT]

roo> download accept terms of useThank you. All Spring Roo download features have now been enabled.

roo> addon search vaadinSuccessfully downloaded Roo add-on Data1 found, sorted by rank; T = trusted developer; R = Roo 1.1 compatibleID T R DESCRIPTION -------------------------------------------------------------01 Y Y 1.0.1 Spring Roo addon for creating rich internet applications with Vaadin.--------------------------------------------------------------------------------[HINT] use 'addon info id --searchResultId ..' to see details about a search result[HINT] use 'addon install id --searchResultId ..' to install a specific search result, or[HINT] use 'addon install bundle --bundleSymbolicName TAB' to install a specific add-on version

____ ____ ____ / __ \/ __ \/ __ \ / /_/ / / / / / / / / _, _/ /_/ / /_/ / /_/ |_|\____/\____/ 1.1.5.RELEASE [rev d3a68c3]

Welcome to Spring Roo. For assistance press CTRL+SPACE or type "hint" then hit ENTER.roo> pgp trust --keyId 0xBF0451C0Added trust for key:>>>> KEY ID: 0xBF0451C0 <<<< More Info: http://keyserver.ubuntu.com/pks/lookup?fingerprint=on&op=index&search=0xBF0451C0 Created: 2009-Aug-14 11:54:20 +0000 Fingerprint: cc57399d74cd7e4768ed6fa4ca62973fbf0451c0 Algorithm: DSA User ID: Artur Signell <[email protected]> Signed By: Key 0xBF0451C0 (Artur Signell <[email protected]>) Subkey ID: 0x17EBEE72 [ELGAMAL_ENCRYPT]

____ ____ ____ / __ \/ __ \/ __ \ / /_/ / / / / / / / / _, _/ /_/ / /_/ / /_/ |_|\____/\____/ 1.1.5.RELEASE [rev d3a68c3]

Welcome to Spring Roo. For assistance press CTRL+SPACE or type "hint" then hit ENTER.roo> pgp trust --keyId 0xBF0451C0Added trust for key:>>>> KEY ID: 0xBF0451C0 <<<< More Info: http://keyserver.ubuntu.com/pks/lookup?fingerprint=on&op=index&search=0xBF0451C0 Created: 2009-Aug-14 11:54:20 +0000 Fingerprint: cc57399d74cd7e4768ed6fa4ca62973fbf0451c0 Algorithm: DSA User ID: Artur Signell <[email protected]> Signed By: Key 0xBF0451C0 (Artur Signell <[email protected]>) Subkey ID: 0x17EBEE72 [ELGAMAL_ENCRYPT]

roo> download accept terms of useThank you. All Spring Roo download features have now been enabled.

55

Setup the Vaadin Addon

Wednesday, February 15, 12

Page 63: Cloud Foundry, Spring and Vaadin

roo> addon install id --searchResultId 01roo> Target resource(s):------------------- Vaadin Plug-in for Spring Roo (1.0.1)

Deploying...done.

roo>

56

Setup the Vaadin Addon

Wednesday, February 15, 12

Page 64: Cloud Foundry, Spring and Vaadin

Building the UI

57

vaadin setup --applicationPackage ~.web --baseName PizzaShop --themeName pizza --useJpaContainer false

vaadin generate all --package ~.web.ui --visuallyComposable true

....That’s it!Wednesday, February 15, 12

Page 65: Cloud Foundry, Spring and Vaadin

Building the UI

58

Wednesday, February 15, 12

Page 66: Cloud Foundry, Spring and Vaadin

Building the UI with the Eclipse Visual UI

59

Wednesday, February 15, 12

Page 67: Cloud Foundry, Spring and Vaadin

Building the UI

60

Wednesday, February 15, 12

Page 68: Cloud Foundry, Spring and Vaadin

Summary

Cloud Foundry provides the PlatformSpring Provides the API Glue•Roo Takes Care of the Rest

Vaadin Makes it Look Great (TM)• and does so, quickly!

Resources• Cloud Foundry http://cloudfoundry.org • Vaadin Roo addon http://vaadin.com/springroo• Spring Framework http://www.springframework.org

61

Wednesday, February 15, 12

Page 69: Cloud Foundry, Spring and Vaadin

Auto-Reconfiguration: Getting Started

Deploy Spring apps to the cloud without changing a single line of code

Cloud Foundry automatically re-configures bean definitions to bind to cloud services

Works with Spring and Grails

62

Wednesday, February 15, 12

Page 70: Cloud Foundry, Spring and Vaadin

Auto-Reconfiguration: Relational DB

Detects beans of type javax.sql.DataSourceConnects to MySQL or PostgreSQL services•Specifies driver, url, username, password, validation query

Creates Commons DBCP or Tomcat DataSourceReplaces existing DataSource

63

import org.apache.commons.dbcp.BasicDataSource;...@Bean(destroyMethod = "close")public BasicDataSource dataSource(){

BasicDataSource bds = new BasicDataSource(); bds.setUrl( "jdbc:h2:mem"); bds.setPassword(""); bds.setUsername("sa"); bds.setDriverClass( Driver.class); return bds;}

Wednesday, February 15, 12

Page 71: Cloud Foundry, Spring and Vaadin

Auto-Reconfiguration: ORM

Adjusts Hibernate DialectChanges hibernate.dialect property to

MySQLDialect (MyISAM) or PostgreSQLDialect• org.springframework.orm.jpa.AbstractEntityManagerFactoryBean• org.springframework.orm.hibernate3.AbstractSessionFactoryBean

(Spring 2.5 and 3.0)• org.springframework.orm.hibernate3.SessionFactoryBuilderSupport

(Spring 3.1)

64

@Bean public LocalContainerEntityManagerFactoryBean entityManager(){ LocalContainerEntityManagerFactoryBean lcem = new LocalContainerEntityManagerFactoryBean(); lcem.setDataSource( dataSource()); return lcem;}

Wednesday, February 15, 12

Page 72: Cloud Foundry, Spring and Vaadin

Auto-Reconfiguration: How It Works

Cloud Foundry installs a BeanFactoryPostProcessor in your application context during staging•Adds jar to your application•Modifies web.xml to load BFPP

• Adds context file to contextConfigLocation• web-app context-param• Spring MVC DispatcherServlet init-param

Adds PostgreSQL and MySQL driver jars as needed for DataSource reconfiguration

65

Wednesday, February 15, 12

Page 73: Cloud Foundry, Spring and Vaadin

The Environment

Asking Questions•You can introspect the environment variables (System.getenv(“VCAP_SERVICES”)),

or...• import the CloudFoundry runtime API from Java!

• (much simpler)

66

<dependency> <groupId>org.cloudfoundry</groupId> <artifactId>cloudfoundry-runtime</artifactId> <version>0.8.0</version> </dependency>

Wednesday, February 15, 12

Page 74: Cloud Foundry, Spring and Vaadin

The Spring Developer’s Perspective: The Environment

67

@Controller public class HomeController {

@RequestMapping(value = "/", method = RequestMethod.GET) public String home(Map<String, Object> model) { CloudEnvironment cloudEnvironment = new CloudEnvironment(); if (cloudEnvironment.getCloudApiUri() != null) { model.put("host", cloudEnvironment.getInstanceInfo().getHost()); model.put("port", cloudEnvironment.getInstanceInfo().getPort()); } return "home"; }

}

Wednesday, February 15, 12

Page 75: Cloud Foundry, Spring and Vaadin

Giving Your Application Clues with the env command

68

env <appname> List application environment variables

env-add <appname> <variable[=]value>

env-del <appname> <variable>

Add an environment variable to an application

Delete an environment variable to an application

$ env-add html5expenses PAYMENT_GATEWAY=http://blah.com

is the same as..

$ export PAYMENT_GATEWAY=http://blah.com

Wednesday, February 15, 12

Page 76: Cloud Foundry, Spring and Vaadin

Introducing... the Cloud Namespace

<cloud:> namespace for use in Spring app contextsProvides application-level control of bean service bindingsRecommended for development of new cloud appsUse when:•You have multiple services of the same type•You have multiple connecting beans of the same type

• e.g. DataSource, MongoDBFactory•You have custom bean configuration

• e.g. DataSource pool size, connection properties

69

Wednesday, February 15, 12

Page 77: Cloud Foundry, Spring and Vaadin

<cloud:data-source>Configures a DataSource bean•Commons DBCP or Tomcat DataSource

Basic attributes:• id: defaults to service name• service-name: only needed if you have multiple relational database services bound to

the app

70

<cloud:data-source id="dataSource"/>

<bean class="org.sf.orm.jpa.LocalContainerEntityManagerFactoryBean"id="entityManagerFactory"> <property name="dataSource" ref="dataSource"/></bean>

Wednesday, February 15, 12

Page 78: Cloud Foundry, Spring and Vaadin

<cloud:data-source> Example

71

<cloud:data-source id="dataSource" service-name="mySQLSvc"><cloud:pool pool-size="1-5"/><cloud:connection properties="charset=utf-8"/>

</cloud:data-source>

...

@Autowired private DataSource dataSource ;

Wednesday, February 15, 12

Page 79: Cloud Foundry, Spring and Vaadin

<cloud:properties>Exposes basic information about services that can be consumed with

Spring’s property placeholder supportBasic attributes:• id: the name of the properties bean

Properties automatically available when deploying Spring 3.1 applications

72

<cloud:properties id="cloudProperties" /><context:property-placeholder properties-ref="cloudProperties"/>

@Autowired private Environment environment;

@Beanpublic ComboPooledDataSource dataSource() throws Exception { String user = this.environment.getProperty ("cloud.services.mysql.connection.username"); ComboPooledDataSource cpds = new ComboPooledDataSource(); cpds.setUser(user); return cpds; }

Wednesday, February 15, 12

Page 80: Cloud Foundry, Spring and Vaadin

Spring 3.1 Environment AbstractionBean definitions for a specific environment (Profiles)• e.g. development, testing, production•Possibly different deployment environments•Activate profiles by name

• spring.profiles.active system property• Other means outside deployment unit • “default” profile activates if no other profiles specified

Custom resolution of placeholders•Dependent on the actual environment •Ordered property sources

Requires Spring 3.1 (or later)

73

Wednesday, February 15, 12

Page 81: Cloud Foundry, Spring and Vaadin

Isolating Cloud Foundry ConfigurationSwitch between local, testing and Cloud Foundry deployments with

Profiles“cloud” profile automatically activates on Cloud Foundry• usage of the cloud namespace should occur within the cloud profile block

74

Wednesday, February 15, 12

Page 82: Cloud Foundry, Spring and Vaadin

Isolating Cloud Foundry Configuration

75

<bean class="org.sf.orm.jpa.LocalContainerEntityManagerFactoryBean"> <property name="dataSource" ref="dataSource"/></bean>

<beans profile="cloud"> <cloud:data-source id="dataSource" /></beans><beans profile="default"> <bean class="org.a.commons.dbcp.BasicDataSource" id="dataSource"> <property name="url" value="jdbc:mysql://localhost/my_db" /> </bean></beans>

Wednesday, February 15, 12

Page 83: Cloud Foundry, Spring and Vaadin

Profile Support: How It WorksCloud Foundry installs a custom ApplicationContextInitializer in your

app during staging•Modifies web.xml

• Adds to contextInitializerClasses context-param

Adds “cloud” as an active profileAdds a PropertySource to the Environment

76

Wednesday, February 15, 12

Page 84: Cloud Foundry, Spring and Vaadin

Java ConfigurationAlternative to <cloud:*> namespace•Spring Java Configuration•Non-Spring apps

Programmatic creation of service connection factories•Using ServiceCreator and ServiceInfo classes

Works well with CloudEnvironment Included in cloudfoundry-runtime lib

77

Wednesday, February 15, 12

Page 85: Cloud Foundry, Spring and Vaadin

Java Configuration with Profiles

78

@Configuration @Profile(“local”)public class LocalDataSourceConfiguration {

@Bean public javax.sql.DataSource dataSource() { ... }

}

@Configuration @Profile(“cloud”)public class CloudDataSourceConfiguration {

@Bean public javax.sql.DataSource dataSource() { ... }

}

Wednesday, February 15, 12

Page 86: Cloud Foundry, Spring and Vaadin

Using ServiceCreator

79

//Provides access to CF service and application env infoCloudEnvironment environment = new CloudEnvironment(); //Retrieve env info for bound service named "mysqlService"RdbmsServiceInfo mysqlSvc = environment.getServiceInfo("mysqlService", RdbmsServiceInfo.class); //create a DataSource bound to the serviceRdbmsServiceCreator dataSourceCreator = new RdbmsServiceCreator();

DataSource dataSource = dataSourceCreator.createService(mysqlSvc);

Wednesday, February 15, 12

Page 87: Cloud Foundry, Spring and Vaadin

Using ServiceInfo

80

//Provides access to CF service and application env infoCloudEnvironment environment = new CloudEnvironment(); //Retrieve env info for bound service named "mongoService"MongoServiceInfo mongoSvc = environment.getServiceInfo("mongoService", MongoServiceInfo.class); //create a Mongo DB bound to the serviceMongo mongoDB = new Mongo(mongoSvc.getHost(), mongoSvc.getPort());

Wednesday, February 15, 12