Cloud Foundry, Spring and Vaadin
Upcoming SlideShare
Loading in...5
×
 

Cloud Foundry, Spring and Vaadin

on

  • 3,623 views

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

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.

Statistics

Views

Total Views
3,623
Views on SlideShare
3,621
Embed Views
2

Actions

Likes
1
Downloads
69
Comments
0

1 Embed 2

https://twitter.com 2

Accessibility

Upload Details

Uploaded via as Adobe PDF

Usage Rights

CC Attribution License

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Processing…
Post Comment
Edit your comment

Cloud Foundry, Spring and Vaadin Cloud Foundry, Spring and Vaadin Presentation Transcript

  • Get to Production Quicker with Spring, Vaadin and Cloud Foundry Josh Long @starbuxman josh.long@springsource.comWednesday, February 15, 12
  • About Josh Long Spring Developer Advocate twitter: @starbuxman josh.long@springsource.com NOT CONFIDENTIAL -- TELL EVERYONE 2Wednesday, 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! 3Wednesday, 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 4Wednesday, February 15, 12
  • Cloud Foundry: Choice of Runtimes 5Wednesday, 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 6Wednesday, 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 7Wednesday, 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: OKWednesday, 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: OKWednesday, 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: :postgresqlWednesday, February 15, 12
  • Deployment with STSWednesday, February 15, 12
  • Cloud Foundry: Choice of Clouds 12Wednesday, 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 13Wednesday, February 15, 12
  • Open Source Advantage 14Wednesday, February 15, 12
  • Open Source AdvantageWednesday, 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 16Wednesday, February 15, 12
  • Cloud Foundry Community Foundry.org 17Wednesday, February 15, 12
  • Micro Cloud Foundry (beta) Micro Cloud FoundryWednesday, February 15, 12
  • Cloud Foundry: Services 19Wednesday, 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 20Wednesday, 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 | +-------------+---------+ 21Wednesday, 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”:…………………. 22Wednesday, 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. 23Wednesday, February 15, 12
  • Tunneling gem install caldecott vmc tunnel <mongodb> 24Wednesday, February 15, 12
  • Using your favorite tools 25Wednesday, February 15, 12
  • 26Wednesday, February 15, 12
  • intro to Spring 27Wednesday, 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 compatibilityWednesday, 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!) 29Wednesday, 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 30Wednesday, 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> 31Wednesday, 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 { ... } 32Wednesday, 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); ... } } 33Wednesday, 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) { } ... } 34Wednesday, 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; } } 35Wednesday, 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(); } } 36Wednesday, 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; } ... } 37Wednesday, 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()); } } 38Wednesday, 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; } ... } 39Wednesday, 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; } } 40Wednesday, 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 RooWednesday, February 15, 12
  • the Pyramid of Opinionation Spring Roo, Grails More opinionated the Spring framework straight Java EE, assembler Not confidential - tell everyone! 43Wednesday, February 15, 12
  • What Is Spring Roo? Not confidential - tell everyone! 44Wednesday, February 15, 12
  • What Is Spring Roo?  Rapid Application Development tool • 100% Java Not confidential - tell everyone! 44Wednesday, 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! 44Wednesday, 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! 44Wednesday, 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! 44Wednesday, 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! 45Wednesday, February 15, 12
  • Roo overview Not confidential - tell everyone! 46Wednesday, February 15, 12
  • Active code generation Not confidential - tell everyone! 47Wednesday, February 15, 12
  • Creating a Roo App 48Wednesday, 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! 49Wednesday, 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! 51Wednesday, 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 52Wednesday, 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] 53Wednesday, 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. 54Wednesday, 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 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 <artur@vaadin.com> Signed By: Key 0xBF0451C0 (Artur Signell <artur@vaadin.com>) Subkey ID: 0x17EBEE72 [ELGAMAL_ENCRYPT]roo> download accept terms of useThank 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, orWednesday, 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> 56Wednesday, 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! 57Wednesday, February 15, 12
  • Building the UI 58Wednesday, February 15, 12
  • Building the UI with the Eclipse Visual UI 59Wednesday, February 15, 12
  • Building the UI 60Wednesday, 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 61Wednesday, 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 62Wednesday, 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; } 63Wednesday, 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; } 64Wednesday, 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 65Wednesday, 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> 66Wednesday, 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"; } } 67Wednesday, 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 68Wednesday, 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 69Wednesday, 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> 70Wednesday, 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 ; 71Wednesday, 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; } 72Wednesday, 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) 73Wednesday, 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 74Wednesday, 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> 75Wednesday, 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 76Wednesday, 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 77Wednesday, 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() { ... } } 78Wednesday, 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); 79Wednesday, 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()); 80Wednesday, February 15, 12