Get to Production Quicker with
        Spring, Vaadin and Cloud Foundry

        Josh Long
        @starbuxman
        josh.long@springsource.com




Wednesday, February 15, 12
About Josh Long

    Spring Developer Advocate
    twitter: @starbuxman
    josh.long@springsource.com




                             NOT CONFIDENTIAL -- TELL EVERYONE   2

Wednesday, February 15, 12
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
Flexible Administration

     Application Lifecycle API                                      Services API
     • Create, start, stop, update                                  • Enumerate system services
     • Set URL(s), instance count, memory                           • Select and create service instance
     • Get stats, logs, crashes, files                              • Bind and unbind service & app(s)




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




                                                                                                      4

Wednesday, February 15, 12
Cloud Foundry: Choice of Runtimes




                                         5

Wednesday, February 15, 12
Frameworks and Runtimes Supported

    • 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




                                                                                           6

Wednesday, February 15, 12
Deploying an Application




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




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




                                                       Application URL




                                                                                                            7

Wednesday, February 15, 12
Deploying an Application

         $ vmc push cf1 --path target 
               --url cer-cf1.cloudfoundry.com
         Detected a Java Web Application, is this correct?
            [Yn]:




Wednesday, February 15, 12
Deploying an Application

         $ vmc push cf1 --path target 
               --url cer-cf1.cloudfoundry.com
         Detected a Java Web Application, is this correct?
            [Yn]:

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




Wednesday, February 15, 12
Deploying an Application

         $ vmc push cf1 --path target 
               --url cer-cf1.cloudfoundry.com
         Detected a Java Web Application, is this correct?
            [Yn]:

          Memory Reservation [Default:512M] (64M, 128M, 256M,
             512M, 1G or 2G)
         Creating Application: OK
         Would you like to bind any services to 'cf1'? [yN]:




Wednesday, February 15, 12
Deploying an Application

         $ vmc push cf1 --path target 
               --url cer-cf1.cloudfoundry.com
         Detected a Java Web Application, is this correct?
            [Yn]:

          Memory Reservation [Default:512M] (64M, 128M, 256M,
             512M, 1G or 2G)
         Creating Application: OK
         Would you like to bind any services to 'cf1'? [yN]:

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

Wednesday, February 15, 12
Deploying an Application (with a Manifest)

         $ vmc push
         Would you like to deploy from the current directory?
            [Yn]: y
         Pushing application 'html5expenses'...
         Creating Application: OK
         Creating Service [expenses-mongo]: OK
         Binding Service [expenses-mongo]: OK
         Creating Service [expenses-postgresql]: OK
         Binding Service [expenses-postgresql]: OK
         Uploading Application:
           Checking for available resources: OK
           Processing resources: OK
           Packing application: OK
           Uploading (6K): OK
         Push Status: OK

Wednesday, February 15, 12
Deploying an Application (with a manifest.yml)

         ---
         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




Wednesday, February 15, 12
Deployment with STS




Wednesday, February 15, 12
Cloud Foundry: Choice of Clouds




                                       12

Wednesday, February 15, 12
Main Risk: Lock In




                             Welcome to the hotel california
                             Such a lovely place
                             Such a lovely face
                             Plenty of room at the hotel california
                             Any time of year, you can find it here

                             Last thing I remember, I was
                             Running for the door
                             I had to find the passage back
                             To 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




                                                                      13

Wednesday, February 15, 12
Open Source Advantage




    14

Wednesday, February 15, 12
Open Source Advantage




Wednesday, February 15, 12
Cloud Foundry: Clouds


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


                              Joyent
                              • community lead for Node.js




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




                                                                     16

Wednesday, February 15, 12
Cloud Foundry Community
           Foundry.org




                               17

Wednesday, February 15, 12
Micro Cloud Foundry (beta)
     Micro Cloud Foundry




Wednesday, February 15, 12
Cloud Foundry: Services




                               19

Wednesday, February 15, 12
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
Cloud Foundry: Services

           $ vmc create-service mysql --name mysql1
           Creating 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   |
           +-------------+---------+




                                                                              21

Wednesday, February 15, 12
Cloud Foundry: Services Creation and Binding



    $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”:………………….



                                                                 22

Wednesday, February 15, 12
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
Tunneling
    gem install caldecott
    vmc tunnel <mongodb>




                             24

Wednesday, February 15, 12
Using your favorite tools




                                25

Wednesday, February 15, 12
26

Wednesday, February 15, 12
intro to Spring




                             27

Wednesday, February 15, 12
The Spring framework

     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




Wednesday, February 15, 12
Spring’s aim:
     bring simplicity to java development
                                                                               data
       web tier
                                                batch       integration &     access
         &                   service tier                                                      mobile
                                             processing      messaging      / NoSQL /
        RIA
                                                                            Big Data


                                            The Spring framework
  the cloud:                                  lightweight                      traditional

            CloudFoundry                                  tc Server                  WebSphere
          Google App Engine                                Tomcat                     JBoss AS
         Amazon Web Services                                 Jetty                   WebLogic
                                                                                 (on legacy versions, too!)




                                                                                                              29

Wednesday, February 15, 12
The Spring Framework

                              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
                                             provides first-class support for service
      Spring Mobile, Spring Android
                                             creation and consumption for iPhone, Android
                        Spring GemFire       Provides the easiest interface for the GemFire enterprise data grid technology



                                                                                                                              30

Wednesday, February 15, 12
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:
                   ApplicationContext ctx =
                    new GenericAnnotationApplicationContext( “com.foo.bar.my.package”);


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


                 <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>




                                                                                                      31

Wednesday, February 15, 12
Tell Spring About Your Objects




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

     ...

     }




                                                            32

Wednesday, February 15, 12
Tell Spring About Your Objects




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




                                                                                    33

Wednesday, February 15, 12
Tell Spring About Your Objects

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

        @Service
        public class CustomerService {

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

            }

            ...

        }




                                                               34

Wednesday, February 15, 12
Tell Spring About Your Objects


      I want Database Access ...

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


         @Bean
         public DataSource dataSource() throws Exception {
           SimpleDriverDataSource simpleDriverDataSource =
              new SimpleDriverDataSource();
            ....
           return simpleDriverDataSource;
         }

     }




                                                             35

Wednesday, February 15, 12
Tell Spring About Your Objects


      I want Database Access ... with Hibernate 4 Support

     package org.springsource.examples.spring31.services;
     ...
     @Configuration
     public 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();
         }

     }


                                                                      36

Wednesday, February 15, 12
Tell Spring About Your Objects

        package the.package.with.beans.in.it;
        ...
        @Service
        public 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;
            }

            ...

        }
                                                                       37

Wednesday, February 15, 12
Tell Spring About Your Objects


      I want Declarative Transaction Management

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

         ...

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




                                                                             38

Wednesday, February 15, 12
Tell Spring About Your Objects

        package the.package.with.beans.in.it;
        ...
        @Service
        public 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;
            }

            ...

        }                                                              39

Wednesday, February 15, 12
Tell Spring About Your Objects


      I want Declarative Cache Management

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

         ...

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


                                                                40

Wednesday, February 15, 12
Tell Spring About Your Objects

        package the.package.with.beans.in.it;
        ...
        @Service
        public 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;
            }

            ...
                                                                       41

        }
Wednesday, February 15, 12
Buuut....

     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




Wednesday, February 15, 12
the Pyramid of Opinionation




                             Spring Roo, Grails




                                                                  More opinionated
                             the Spring framework




                             straight Java EE, assembler


                              Not confidential - tell everyone!                      43

Wednesday, February 15, 12
What Is Spring Roo?




                             Not confidential - tell everyone!   44

Wednesday, February 15, 12
What Is Spring Roo?
     Rapid Application Development tool
       • 100% Java




                               Not confidential - tell everyone!   44

Wednesday, February 15, 12
What Is Spring Roo?
     Rapid Application Development tool
       • 100% Java
     Based on other Spring projects
       • Spring, Spring @MVC, Spring Security, WebFlow...




                                       Not confidential - tell everyone!   44

Wednesday, February 15, 12
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.*)




                                        Not confidential - tell everyone!   44

Wednesday, February 15, 12
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




                                        Not confidential - tell everyone!   44

Wednesday, February 15, 12
Out Of The Box
     Project management
     General object services
     Entity support
     Field management
     Persistence w/JPA, Neo4J, etc.
     JUnit testing
     Dynamic finders
     Spring MVC, Spring Web Flow and Selenium
     GWT, Vaadin, Flex
     JMS, SMTP and build system integration
     Spring Security, Bundlor, Logging Setup.....
     DBRE




                                Not confidential - tell everyone!   45

Wednesday, February 15, 12
Roo overview




                             Not confidential - tell everyone!   46

Wednesday, February 15, 12
Active code generation




                             Not confidential - tell everyone!   47

Wednesday, February 15, 12
Creating a Roo App




                             48

Wednesday, February 15, 12
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)




                                        Not confidential - tell everyone!                   49

Wednesday, February 15, 12
DBRE - the domain




                             Not confidential - tell everyone!

Wednesday, February 15, 12
DBRE - the domain




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


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




                                          Not confidential - tell everyone!   51

Wednesday, February 15, 12
Setting Up The Domain Model

    persistence setup --provider ECLIPSELINK --database
    HYPERSONIC_IN_MEMORY

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

    perform tests

                                                                52

Wednesday, February 15, 12
/ _, _/ /_/ / /_/ /
    Setup the Vaadin Addon
 /_/ |_|____/____/ 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 0xBF0451C0
 Added 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 <artur@vaadin.com>
      Signed By: Key 0xBF0451C0 (Artur Signell <artur@vaadin.com>)
   Subkey ID: 0x17EBEE72 [ELGAMAL_ENCRYPT]




                                                                                         53

Wednesday, February 15, 12
/ _, _/ /_/ / /_/ /
    Setup the Vaadin Addon
 /_/ |_|____/____/ 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 0xBF0451C0
 Added 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 <artur@vaadin.com>
      Signed By: Key 0xBF0451C0 (Artur Signell <artur@vaadin.com>)
   Subkey ID: 0x17EBEE72 [ELGAMAL_ENCRYPT]

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




                                                                                         54

Wednesday, February 15, 12
/ _, _/ /_/ / /_/ /
   Setup the Vaadin Addon
/_/ |_|____/____/ 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 0xBF0451C0
Added 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 <artur@vaadin.com>
     Signed By: Key 0xBF0451C0 (Artur Signell <artur@vaadin.com>)
  Subkey ID: 0x17EBEE72 [ELGAMAL_ENCRYPT]

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

 roo> addon search vaadin
 Successfully downloaded Roo add-on Data
 1 found, sorted by rank; T = trusted developer; R = Roo 1.1 compatible
 ID 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        55
 [HINT] use 'addon install id --searchResultId ..' to install a specific search result, or
Wednesday, February 15, 12
Setup the Vaadin Addon




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

 Deploying...done.

 roo>




                                             56

Wednesday, February 15, 12
Building the UI

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

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




                                          ....That’s it!
                                                                       57

Wednesday, February 15, 12
Building the UI




                             58

Wednesday, February 15, 12
Building the UI with the Eclipse Visual UI




                                                 59

Wednesday, February 15, 12
Building the UI




                             60

Wednesday, February 15, 12
Summary
     Cloud Foundry provides the Platform
     Spring 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
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
Auto-Reconfiguration: Relational DB
     Detects beans of type javax.sql.DataSource
     Connects to MySQL or PostgreSQL services
       • Specifies driver, url, username, password, validation query
     Creates Commons DBCP or Tomcat DataSource
     Replaces existing DataSource


     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;
     }
                                                                       63

Wednesday, February 15, 12
Auto-Reconfiguration: ORM


     Adjusts Hibernate Dialect
     Changes 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)




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

Wednesday, February 15, 12
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
The Environment
     Asking Questions
       • You can introspect the environment variables (System.getenv(“VCAP_SERVICES”)),
         or...
       • import the CloudFoundry runtime API from Java!
          • (much simpler)



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




                                                                                          66

Wednesday, February 15, 12
The Spring Developer’s Perspective: The Environment
      @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";
        }

      }




                                                                               67

Wednesday, February 15, 12
Giving Your Application Clues with the env command

     env <appname>
          List application environment variables


      env-add <appname> <variable[=]value>
           Add an environment variable to an application

      env-del <appname> <variable>
           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




                                                                68

Wednesday, February 15, 12
Introducing... the Cloud Namespace
     <cloud:> namespace for use in Spring app contexts
     Provides application-level control of bean service bindings
     Recommended for development of new cloud apps
     Use 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
<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




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

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



                                                                                                70

Wednesday, February 15, 12
<cloud:data-source> Example




    <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 ;




                                                                  71

Wednesday, February 15, 12
<cloud:properties>
     Exposes basic information about services that can be consumed with
      Spring’s property placeholder support
     Basic attributes:
       • id: the name of the properties bean
     Properties automatically available when deploying Spring 3.1
       applications


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

       @Autowired private Environment environment;

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

Wednesday, February 15, 12
Spring 3.1 Environment Abstraction
     Bean 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
Isolating Cloud Foundry Configuration
     Switch 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
Isolating Cloud Foundry Configuration


      <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>




                                                                              75

Wednesday, February 15, 12
Profile Support: How It Works
     Cloud Foundry installs a custom ApplicationContextInitializer in your
       app during staging
       • Modifies web.xml
          • Adds to contextInitializerClasses context-param
     Adds “cloud” as an active profile
     Adds a PropertySource to the Environment




                                                                              76

Wednesday, February 15, 12
Java Configuration
     Alternative 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
Java Configuration with Profiles


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

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

         }


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

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

         }




                                                                   78

Wednesday, February 15, 12
Using ServiceCreator



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

     DataSource dataSource = dataSourceCreator.createService(mysqlSvc);




                                                                                  79

Wednesday, February 15, 12
Using ServiceInfo



     //Provides access to CF service and application env info
     CloudEnvironment 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 service
     Mongo mongoDB = new Mongo(mongoSvc.getHost(), mongoSvc.getPort());




                                                                                 80

Wednesday, February 15, 12

Cloud Foundry, Spring and Vaadin

  • 1.
    Get to ProductionQuicker with Spring, Vaadin and Cloud Foundry Josh Long @starbuxman josh.long@springsource.com Wednesday, February 15, 12
  • 2.
    About Josh Long Spring Developer Advocate twitter: @starbuxman josh.long@springsource.com NOT CONFIDENTIAL -- TELL EVERYONE 2 Wednesday, February 15, 12
  • 3.
    Cloud Developer Billof 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
  • 4.
    Flexible Administration Application Lifecycle API Services API • Create, start, stop, update • Enumerate system services • Set URL(s), instance count, memory • Select and create service instance • Get stats, logs, crashes, files • Bind and unbind service & app(s) Cloud Foundry APIs Also includes • account spacing • clients: STS, VMC • Info API for both system and account space 4 Wednesday, February 15, 12
  • 5.
    Cloud Foundry: Choiceof Runtimes 5 Wednesday, February 15, 12
  • 6.
    Frameworks and RuntimesSupported • 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 6 Wednesday, February 15, 12
  • 7.
    Deploying an Application CLI Application name Dir containing application (or, .WAR for Java) $ vmc push cf1 --path target --url cer-cf1.cloudfoundry.com Application URL 7 Wednesday, February 15, 12
  • 8.
    Deploying an Application $ vmc push cf1 --path target --url cer-cf1.cloudfoundry.com Detected a Java Web Application, is this correct? [Yn]: Wednesday, February 15, 12
  • 9.
    Deploying an Application $ vmc push cf1 --path target --url cer-cf1.cloudfoundry.com Detected a Java Web Application, is this correct? [Yn]: Memory Reservation [Default:512M] (64M, 128M, 256M, 512M, 1G or 2G) Wednesday, February 15, 12
  • 10.
    Deploying an Application $ vmc push cf1 --path target --url cer-cf1.cloudfoundry.com Detected a Java Web Application, is this correct? [Yn]: Memory Reservation [Default:512M] (64M, 128M, 256M, 512M, 1G or 2G) Creating Application: OK Would you like to bind any services to 'cf1'? [yN]: Wednesday, February 15, 12
  • 11.
    Deploying an Application $ vmc push cf1 --path target --url cer-cf1.cloudfoundry.com Detected a Java Web Application, is this correct? [Yn]: Memory Reservation [Default:512M] (64M, 128M, 256M, 512M, 1G or 2G) Creating Application: OK Would you like to bind any services to 'cf1'? [yN]: Uploading Application: Checking for available resources: OK Packing application: OK Uploading (2K): OK Push Status: OK Starting Application: OK Wednesday, February 15, 12
  • 12.
    Deploying an Application(with a Manifest) $ vmc push Would you like to deploy from the current directory? [Yn]: y Pushing application 'html5expenses'... Creating Application: OK Creating Service [expenses-mongo]: OK Binding Service [expenses-mongo]: OK Creating Service [expenses-postgresql]: OK Binding Service [expenses-postgresql]: OK Uploading Application: Checking for available resources: OK Processing resources: OK Packing application: OK Uploading (6K): OK Push Status: OK Wednesday, February 15, 12
  • 13.
    Deploying an Application(with a manifest.yml) --- 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 Wednesday, February 15, 12
  • 14.
  • 15.
    Cloud Foundry: Choiceof Clouds 12 Wednesday, February 15, 12
  • 16.
    Main Risk: LockIn Welcome to the hotel california Such a lovely place Such a lovely face Plenty of room at the hotel california Any time of year, you can find it here Last thing I remember, I was Running for the door I had to find the passage back To 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 13 Wednesday, February 15, 12
  • 17.
    Open Source Advantage 14 Wednesday, February 15, 12
  • 18.
  • 19.
    Cloud Foundry: Clouds  AppFog.com • community lead for PHP • PaaS for PHP  Joyent • community lead for Node.js  ActiveState • community lead for Python, Perl • Providers of Stackato private PaaS 16 Wednesday, February 15, 12
  • 20.
    Cloud Foundry Community Foundry.org 17 Wednesday, February 15, 12
  • 21.
    Micro Cloud Foundry(beta) Micro Cloud Foundry Wednesday, February 15, 12
  • 22.
    Cloud Foundry: Services 19 Wednesday, February 15, 12
  • 23.
    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
  • 24.
    Cloud Foundry: Services $ vmc create-service mysql --name mysql1 Creating 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 | +-------------+---------+ 21 Wednesday, February 15, 12
  • 25.
    Cloud Foundry: ServicesCreation and Binding $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”:…………………. 22 Wednesday, February 15, 12
  • 26.
    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
  • 27.
    Tunneling gem install caldecott vmc tunnel <mongodb> 24 Wednesday, February 15, 12
  • 28.
    Using your favoritetools 25 Wednesday, February 15, 12
  • 29.
  • 30.
    intro to Spring 27 Wednesday, February 15, 12
  • 31.
    The Spring framework  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 Wednesday, February 15, 12
  • 32.
    Spring’s aim: bring simplicity to java development data web tier batch integration & access & service tier mobile processing messaging / NoSQL / RIA Big Data The Spring framework the cloud: lightweight traditional CloudFoundry tc Server WebSphere Google App Engine Tomcat JBoss AS Amazon Web Services Jetty WebLogic (on legacy versions, too!) 29 Wednesday, February 15, 12
  • 33.
    The Spring Framework 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 provides first-class support for service Spring Mobile, Spring Android creation and consumption for iPhone, Android Spring GemFire Provides the easiest interface for the GemFire enterprise data grid technology 30 Wednesday, February 15, 12
  • 34.
    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: ApplicationContext ctx = new GenericAnnotationApplicationContext( “com.foo.bar.my.package”); • In a web application, you will configure an application context in your web.xml <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> 31 Wednesday, February 15, 12
  • 35.
    Tell Spring AboutYour Objects package org.springsource.examples.spring31.services; ... @Configuration @ComponentScan(“the.package.with.beans.in.it”) public class ServicesConfiguration { ... } 32 Wednesday, February 15, 12
  • 36.
    Tell Spring AboutYour Objects public class Main { static public void main (String [] args) throws Throwable { ApplicationContext ac = new AnnotationConfigApplicationContext( org.springsource.examples.spring31.services.ServicesConfiguration.class); ... } } 33 Wednesday, February 15, 12
  • 37.
    Tell Spring AboutYour Objects package the.package.with.beans.in.it; @Service public class CustomerService { public Customer createCustomer(String firstName, String lastName, Date signupDate) { } ... } 34 Wednesday, February 15, 12
  • 38.
    Tell Spring AboutYour Objects I want Database Access ... package org.springsource.examples.spring31.services; ... @Configuration public class ServicesConfiguration { @Bean public DataSource dataSource() throws Exception { SimpleDriverDataSource simpleDriverDataSource = new SimpleDriverDataSource(); .... return simpleDriverDataSource; } } 35 Wednesday, February 15, 12
  • 39.
    Tell Spring AboutYour Objects I want Database Access ... with Hibernate 4 Support package org.springsource.examples.spring31.services; ... @Configuration public 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(); } } 36 Wednesday, February 15, 12
  • 40.
    Tell Spring AboutYour Objects package the.package.with.beans.in.it; ... @Service public 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; } ... } 37 Wednesday, February 15, 12
  • 41.
    Tell Spring AboutYour Objects I want Declarative Transaction Management package org.springsource.examples.spring31.services; ... @Configuration @EnableTransactionManagement public class ServicesConfiguration { ... @Bean public PlatformTransactionManager transactionManager() throws Exception { return new HibernateTransactionManager(this.sessionFactory()); } } 38 Wednesday, February 15, 12
  • 42.
    Tell Spring AboutYour Objects package the.package.with.beans.in.it; ... @Service public 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; } ... } 39 Wednesday, February 15, 12
  • 43.
    Tell Spring AboutYour Objects I want Declarative Cache Management package org.springsource.examples.spring31.services; ... @Configuration @EnableTransactionManagement @EnableCaching public class ServicesConfiguration { ... @Bean public CacheManager cacheManager() { SimpleCacheManager scm = new SimpleCacheManager(); Cache cache = new ConcurrentMapCache("customers"); scm.setCaches(Arrays.asList(cache)); return scm; } } 40 Wednesday, February 15, 12
  • 44.
    Tell Spring AboutYour Objects package the.package.with.beans.in.it; ... @Service public 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; } ... 41 } Wednesday, February 15, 12
  • 45.
    Buuut....  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 Wednesday, February 15, 12
  • 46.
    the Pyramid ofOpinionation Spring Roo, Grails More opinionated the Spring framework straight Java EE, assembler Not confidential - tell everyone! 43 Wednesday, February 15, 12
  • 47.
    What Is SpringRoo? Not confidential - tell everyone! 44 Wednesday, February 15, 12
  • 48.
    What Is SpringRoo?  Rapid Application Development tool • 100% Java Not confidential - tell everyone! 44 Wednesday, February 15, 12
  • 49.
    What Is SpringRoo?  Rapid Application Development tool • 100% Java  Based on other Spring projects • Spring, Spring @MVC, Spring Security, WebFlow... Not confidential - tell everyone! 44 Wednesday, February 15, 12
  • 50.
    What Is SpringRoo?  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.*) Not confidential - tell everyone! 44 Wednesday, February 15, 12
  • 51.
    What Is SpringRoo?  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 Not confidential - tell everyone! 44 Wednesday, February 15, 12
  • 52.
    Out Of TheBox  Project management  General object services  Entity support  Field management  Persistence w/JPA, Neo4J, etc.  JUnit testing  Dynamic finders  Spring MVC, Spring Web Flow and Selenium  GWT, Vaadin, Flex  JMS, SMTP and build system integration  Spring Security, Bundlor, Logging Setup.....  DBRE Not confidential - tell everyone! 45 Wednesday, February 15, 12
  • 53.
    Roo overview Not confidential - tell everyone! 46 Wednesday, February 15, 12
  • 54.
    Active code generation Not confidential - tell everyone! 47 Wednesday, February 15, 12
  • 55.
    Creating a RooApp 48 Wednesday, February 15, 12
  • 56.
    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) Not confidential - tell everyone! 49 Wednesday, February 15, 12
  • 57.
    DBRE - thedomain Not confidential - tell everyone! Wednesday, February 15, 12
  • 58.
    DBRE - thedomain 1) database properties set --key database.url --value jdbc:h2:tcp://localhost/~/roo_crm 2) database reverse engineer --package ~.domain --schema PUBLIC Not confidential - tell everyone! 51 Wednesday, February 15, 12
  • 59.
    Setting Up TheDomain Model persistence setup --provider ECLIPSELINK --database HYPERSONIC_IN_MEMORY entity --class ~.domain.Topping --testAutomatically field string --fieldName name --notNull --sizeMin 2 entity --class ~.domain.Base --testAutomatically field string --fieldName name --notNull --sizeMin 2 entity --class ~.domain.Pizza --testAutomatically field string --fieldName name --notNull --sizeMin 2 field number --fieldName price --type java.lang.Float field set --fieldName toppings --type ~.domain.Topping field reference --fieldName base --type ~.domain.Base entity --class ~.domain.PizzaOrder --testAutomatically field string --fieldName name --notNull --sizeMin 2 field string --fieldName address --sizeMax 30 field number --fieldName total --type java.lang.Float field date --fieldName deliveryDate --type java.util.Date field set --fieldName pizzas --type ~.domain.Pizza perform tests 52 Wednesday, February 15, 12
  • 60.
    / _, _//_/ / /_/ / Setup the Vaadin Addon /_/ |_|____/____/ 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 0xBF0451C0 Added 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 <artur@vaadin.com> Signed By: Key 0xBF0451C0 (Artur Signell <artur@vaadin.com>) Subkey ID: 0x17EBEE72 [ELGAMAL_ENCRYPT] 53 Wednesday, February 15, 12
  • 61.
    / _, _//_/ / /_/ / Setup the Vaadin Addon /_/ |_|____/____/ 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 0xBF0451C0 Added 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 <artur@vaadin.com> Signed By: Key 0xBF0451C0 (Artur Signell <artur@vaadin.com>) Subkey ID: 0x17EBEE72 [ELGAMAL_ENCRYPT] roo> download accept terms of use Thank you. All Spring Roo download features have now been enabled. 54 Wednesday, February 15, 12
  • 62.
    / _, _//_/ / /_/ / Setup the Vaadin Addon /_/ |_|____/____/ 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 0xBF0451C0 Added 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 <artur@vaadin.com> Signed By: Key 0xBF0451C0 (Artur Signell <artur@vaadin.com>) Subkey ID: 0x17EBEE72 [ELGAMAL_ENCRYPT] roo> download accept terms of use Thank you. All Spring Roo download features have now been enabled. roo> addon search vaadin Successfully downloaded Roo add-on Data 1 found, sorted by rank; T = trusted developer; R = Roo 1.1 compatible ID 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 55 [HINT] use 'addon install id --searchResultId ..' to install a specific search result, or Wednesday, February 15, 12
  • 63.
    Setup the VaadinAddon roo> addon install id --searchResultId 01 roo> Target resource(s): ------------------- Vaadin Plug-in for Spring Roo (1.0.1) Deploying...done. roo> 56 Wednesday, February 15, 12
  • 64.
    Building the UI vaadin setup --applicationPackage ~.web --baseName PizzaShop --themeName pizza --useJpaContainer false vaadin generate all --package ~.web.ui --visuallyComposable true ....That’s it! 57 Wednesday, February 15, 12
  • 65.
    Building the UI 58 Wednesday, February 15, 12
  • 66.
    Building the UIwith the Eclipse Visual UI 59 Wednesday, February 15, 12
  • 67.
    Building the UI 60 Wednesday, February 15, 12
  • 68.
    Summary  Cloud Foundry provides the Platform  Spring 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
  • 69.
    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
  • 70.
    Auto-Reconfiguration: Relational DB  Detects beans of type javax.sql.DataSource  Connects to MySQL or PostgreSQL services • Specifies driver, url, username, password, validation query  Creates Commons DBCP or Tomcat DataSource  Replaces existing DataSource 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; } 63 Wednesday, February 15, 12
  • 71.
    Auto-Reconfiguration: ORM  Adjusts Hibernate Dialect  Changes 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) @Bean public LocalContainerEntityManagerFactoryBean entityManager(){ LocalContainerEntityManagerFactoryBean lcem = new LocalContainerEntityManagerFactoryBean(); lcem.setDataSource( dataSource()); return lcem; } 64 Wednesday, February 15, 12
  • 72.
    Auto-Reconfiguration: How ItWorks  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
  • 73.
    The Environment  Asking Questions • You can introspect the environment variables (System.getenv(“VCAP_SERVICES”)), or... • import the CloudFoundry runtime API from Java! • (much simpler) <dependency> <groupId>org.cloudfoundry</groupId> <artifactId>cloudfoundry-runtime</artifactId> <version>0.8.0</version> </dependency> 66 Wednesday, February 15, 12
  • 74.
    The Spring Developer’sPerspective: The Environment @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"; } } 67 Wednesday, February 15, 12
  • 75.
    Giving Your ApplicationClues with the env command env <appname> List application environment variables env-add <appname> <variable[=]value> Add an environment variable to an application env-del <appname> <variable> 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 68 Wednesday, February 15, 12
  • 76.
    Introducing... the CloudNamespace  <cloud:> namespace for use in Spring app contexts  Provides application-level control of bean service bindings  Recommended for development of new cloud apps  Use 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
  • 77.
    <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 <cloud:data-source id="dataSource"/> <bean class="org.sf.orm.jpa.LocalContainerEntityManagerFactoryBean" id="entityManagerFactory"> <property name="dataSource" ref="dataSource"/> </bean> 70 Wednesday, February 15, 12
  • 78.
    <cloud:data-source> Example <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 ; 71 Wednesday, February 15, 12
  • 79.
    <cloud:properties>  Exposes basic information about services that can be consumed with Spring’s property placeholder support  Basic attributes: • id: the name of the properties bean  Properties automatically available when deploying Spring 3.1 applications <cloud:properties id="cloudProperties" /> <context:property-placeholder properties-ref="cloudProperties"/> @Autowired private Environment environment; @Bean public ComboPooledDataSource dataSource() throws Exception { String user = this.environment.getProperty ("cloud.services.mysql.connection.username"); ComboPooledDataSource cpds = new ComboPooledDataSource(); cpds.setUser(user); return cpds; } 72 Wednesday, February 15, 12
  • 80.
    Spring 3.1 EnvironmentAbstraction  Bean 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
  • 81.
    Isolating Cloud FoundryConfiguration  Switch 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
  • 82.
    Isolating Cloud FoundryConfiguration <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> 75 Wednesday, February 15, 12
  • 83.
    Profile Support: HowIt Works  Cloud Foundry installs a custom ApplicationContextInitializer in your app during staging • Modifies web.xml • Adds to contextInitializerClasses context-param  Adds “cloud” as an active profile  Adds a PropertySource to the Environment 76 Wednesday, February 15, 12
  • 84.
    Java Configuration  Alternative 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
  • 85.
    Java Configuration withProfiles @Configuration @Profile(“local”) public class LocalDataSourceConfiguration { @Bean public javax.sql.DataSource dataSource() { ... } } @Configuration @Profile(“cloud”) public class CloudDataSourceConfiguration { @Bean public javax.sql.DataSource dataSource() { ... } } 78 Wednesday, February 15, 12
  • 86.
    Using ServiceCreator //Provides access to CF service and application env info CloudEnvironment environment = new CloudEnvironment(); //Retrieve env info for bound service named "mysqlService" RdbmsServiceInfo mysqlSvc = environment.getServiceInfo("mysqlService", RdbmsServiceInfo.class); //create a DataSource bound to the service RdbmsServiceCreator dataSourceCreator = new RdbmsServiceCreator(); DataSource dataSource = dataSourceCreator.createService(mysqlSvc); 79 Wednesday, February 15, 12
  • 87.
    Using ServiceInfo //Provides access to CF service and application env info CloudEnvironment 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 service Mongo mongoDB = new Mongo(mongoSvc.getHost(), mongoSvc.getPort()); 80 Wednesday, February 15, 12