SlideShare uma empresa Scribd logo
1 de 79
Baixar para ler offline
Spring and the Many Faces of the Web
   (or, Thin,   Thick, Web, Mobile and Rich Clients with Spring)


Josh Long
@starbuxman
Spring Developer Advocate
SpringSource, a division of VMware




                                                          © 2009 VMware Inc. All rights reserved
About Josh Long
SpringSource Developer Advocate
twitter: @starbuxman
josh.long@springsource.com




                       NOT CONFIDENTIAL -- TELL EVERYONE   2
Agenda

 Introduction to Spring
 Web Applications
 • Spring MVC, JSF, Others
 REST
 • the final frontier: TV, tablets, operating systems
 Mobile Clients
 • Android, iPhone
 RIA / SOFEA
 • Flex, GWT, Vaadin
 OAuth
 • Spring Social, Spring Security OAuth




                                NOT CONFIDENTIAL -- TELL EVERYONE   3
About

 SpringSource is the organization that develops the Spring
  framework, the leading enterprise Java framework

 SpringSource was acquired by VMware in 2009

 VMware and SpringSource bring you to the cloud and
  deliver on the mission of “build, run, manage”
  • established partnerships with the major players in the business,
   including Adobe, SalesForce, and Google to help deliver the
   best experience for Spring users across multiple platforms


 Leading contributor to projects like
  Apache HTTPD and Apache Tomcat




                               NOT CONFIDENTIAL -- TELL EVERYONE       4
Introduction to Spring




                         NOT CONFIDENTIAL -- TELL EVERYONE   5
At its core, the Spring Framework...

 Provide comprehensive infrastructural support for developing
 enterprise Java™ applications
 • Spring deals with the plumbing
 • So you can focus on solving the domain problem




                             NOT CONFIDENTIAL -- TELL EVERYONE   6
Spring’s aim:
 bring simplicity to java development
                                                                      data
  web tier                                    integration
                                batch                                access
    &        service tier                          &                                  mobile
                             processing                            / NoSQL /
   RIA                                        messaging
                                                                   Big Data


                            The Spring framework
the cloud:                    lightweight                             traditional
     CloudFoundry                                                           WebSphere
                                          tc Server
       VMForce                                                               JBoss AS
                                           Tomcat
   Google App Engine                                                        WebLogic
                                             Jetty
  Amazon Web Services                                                   (on legacy versions, too!)



                               NOT CONFIDENTIAL -- TELL EVERYONE                                     7
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


                                       NOT CONFIDENTIAL -- TELL EVERYONE                                  8
Web Applications with Spring




                      NOT CONFIDENTIAL -- TELL EVERYONE   9
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>/WEB-INF/spring/myAppContext*.xml</param-value>
          </init-param>
          <load-on-startup>1</load-on-startup>
        </servlet>



                                   NOT CONFIDENTIAL -- TELL EVERYONE                 10
Thin, Thick, Web, Mobile and Rich Clients: Web Core

 Spring Dispatcher Servlet
 • Objects don’t have to be web-specific.
 • Spring web supports lower-level web machinery: ‘
   •   HttpRequestHandler (supports remoting: Caucho, Resin, JAX RPC)
   •   DelegatingFilterProxy.
   •   HandlerInterceptor wraps requests to HttpRequestHandlers
   •   ServletWrappingController lets you force requests to a servlet through the Spring
       Handler chain
   • OncePerRequestFilter ensures that an action only occurs once, no matter how many
       filters are applied. Provides a nice way to avoid duplicate filters
 • Spring provides access to the Spring application context using
   WebApplicationContextUtils, which has a static method to look up the context,
   even in environments where Spring isn’t managing the web components




                                     NOT CONFIDENTIAL -- TELL EVERYONE
Thin, Thick, Web, Mobile and Rich Clients: Web Core

 Spring provides the easiest way to integrate with your web
 framework of choice
 • Spring Faces for JSF 1 and 2
 • Struts support for Struts 1
 • Tapestry, Struts 2, Stripes, GWT, Wicket, Vaadin, Play framework, etc.




                                 NOT CONFIDENTIAL -- TELL EVERYONE
Thin, Thick, Web, Mobile and Rich Clients: Spring MVC




                       NOT CONFIDENTIAL -- TELL EVERYONE   13
Thin, Thick, Web, Mobile and Rich Clients: Spring MVC
Spring MVC configuration - config

 @Configuration @EnableWebMvc @Import(Config.class)
 public class WebConfig extends WebMvcConfigurerAdapter{
     @Bean public UrlBasedViewResolver resolver() {
         UrlBasedViewResolver url = new UrlBasedViewResolver();
         url.setPrefix("views/");
         url.setViewClass(JstlView.class);
         url.setSuffix(".jsp");
         return url;
     }
     public void configureViewControllers(ViewControllerConfigurer configurer) {
         configurer.mapViewName("/", "welcome") ;
     }
 }
            A Controller - config

       @Controller
       public class CustomerController {
           @Autowired private CustomerService customerService;

             @ModelAttribute public Customer customer() { return new Customer(); }

             @RequestMapping(value = "/display", method = RequestMethod.GET)
             public Map<String, Object> customer(@RequestParam("id") Long id) {
                 Map<String, Object> out = new HashMap<String, Object>();
                 out.put("customer", customerService.getCustomerById(id) );
                 return out;
             }                  NOT CONFIDENTIAL -- TELL EVERYONE                 14
Thin, Thick, Web, Mobile and Rich Clients: Spring MVC

 Demos
 • Spring MVC and associated configuration




                            NOT CONFIDENTIAL -- TELL EVERYONE
REST




       NOT CONFIDENTIAL -- TELL EVERYONE   16
Thin, Thick, Web, Mobile and Rich Clients: REST

 Spring MVC is basis for REST support
 • Spring’s server side REST support is based on the standard controller model
 • RestTemplate
   • provides dead simple, idiomatic RESTful services consumption
   • can use Spring OXM, too.
 • Spring Integration and Spring Social both build on the RestTemplate where
   possible.
 • JavaScript and HTML5 can consume JSON-data payloads
 • REST is the ultimate connectivity mechanism: everything can speak HTTP.




                                NOT CONFIDENTIAL -- TELL EVERYONE
Thin, Thick, Web, Mobile and Rich Clients: REST
RestCustomerController - server

@Controller @RequestMapping(headers = "Accept=application/json, application/xml")
public class RestCustomerController {

  @Autowired private CustomerService cs;

  @RequestMapping(value = "/customer/{cid}", method = RequestMethod.POST)
  @ResponseBody public Customer updateCustomer(@RequestBody Customer c) {
        return cs.updateCustomer( c.getId(), c.getFirstName(), c.getLastName());
  }

     WebConfig - server

      @EnableWebMvc
      @Import(Config.class)
      @Configuration
      public class WebConfig
       extends WebMvcConfigurerAdapter {}


                      client

                 Customer customer1 = restTemplate.getForEntity(
                      url + "customer/{customerId}",
                      Customer.class, c.getId()).getBody();
                 log.info("fetched customer " + customer1.toString());


                                  NOT CONFIDENTIAL -- TELL EVERYONE           18
Thin, Thick, Web, Mobile and Rich Clients: REST

 Demos:
• Spring REST service
• Spring REST client




                        NOT CONFIDENTIAL -- TELL EVERYONE
Mobile (pt 1.)




                 NOT CONFIDENTIAL -- TELL EVERYONE   20
Thin, Thick, Web, Mobile and Rich Clients: Mobile

 Best strategy? Develop Native
 • Fallback to client-optimized web applications
 Spring MVC 3.1 mobile client-specific content negotiation and
 rendering
 • for other devices
   • (there are other devices besides Android??)




                                NOT CONFIDENTIAL -- TELL EVERYONE   21
Thin, Thick, Web, Mobile and Rich Clients: Mobile
     WebConfig - server

!   @Bean
     public ViewResolver viewResolver() {
         UrlBasedViewResolver viewResolver = new UrlBasedViewResolver();
         viewResolver.setViewClass(TilesView.class);
         return viewResolver;
     }

    @Bean
    public TilesConfigurer tilesConfigurer() {
        TilesConfigurer configurer = new TilesConfigurer();
        configurer.setDefinitions(new String[]{
                "/WEB-INF/layouts/tiles.xml",
                "/WEB-INF/views/**/tiles.xml"
        });
        configurer.setCheckRefresh(true);
        return configurer;
    }

    @Override
    public void configureInterceptors(InterceptorConfigurer configurer) {
        configurer.addInterceptor(new DeviceResolverHandlerInterceptor());
    }




                               NOT CONFIDENTIAL -- TELL EVERYONE             22
Thin, Thick, Web, Mobile and Rich Clients: REST

 Demos:
• Mobile clients using client specific rendering




                                 NOT CONFIDENTIAL -- TELL EVERYONE
Mobile (pt 2.)




                 NOT CONFIDENTIAL -- TELL EVERYONE   24
Thin, Thick, Web, Mobile and Rich Clients: Mobile

               Spring REST is ideal for mobile devices
               Spring MVC 3.1 mobile client-specific content
                negotiation and rendering
                • for other devices
               Spring Android
                • RestTemplate




                          NOT CONFIDENTIAL -- TELL EVERYONE     25
Thin, Thick, Web, Mobile and Rich Clients: Mobile

     CustomerServiceClient - client



!    private <T> T extractResponse( ResponseEntity<T> response) {
!    !    if (response != null && response().value() == 200) {
!    !    !   return response.getBody();
!    !    }
!    !    throw new RuntimeException("couldn't extract response.");
!    }

!    @Override
!    public Customer updateCustomer(long id, String fn, String ln) {
!    !    String urlForPath = urlForPath("customer/{customerId}");!   !
!    !    return extractResponse(this.restTemplate.postForEntity(
                   urlForPath, new Customer(id, fn, ln), Customer.class, id));
!    }




                                      NOT CONFIDENTIAL -- TELL EVERYONE          26
Thin, Thick, Web, Mobile and Rich Clients: Mobile

 Demos:
• consuming the Spring REST service from Android




                             NOT CONFIDENTIAL -- TELL EVERYONE
Rich Internet Applications




                        NOT CONFIDENTIAL -- TELL EVERYONE   28
Thin, Thick, Web, Mobile and Rich Clients: Flex

       Spring Flex
      • Dead-simple to expose Spring beans as Flex services
      • Developed with support from Adobe
      • But it still has strengths:
        • form driven apps
        • video, 2D and 3D graphics, sound
        • Adobe AIR
        • blazing fast communication
        • server side push
      • Spring ActionScript is a cool framework “sponsored” by SpringSource




                               NOT CONFIDENTIAL -- TELL EVERYONE
Thin, Thick, Web, Mobile and Rich Clients: Flex
                                                                             crm-flex-servlet.xml - server
<?xml version="1.0" encoding="UTF-8"?>
<beans ...>

   <context:component-scan base-package="org.springsource.examples.sawt.web.flex"/>

   <mvc:default-servlet-handler/>

   <flex:message-broker mapping-order="1">
       <flex:mapping pattern="/messagebroker/*"/>
       <flex:message-service default-channels="my-streaming-amf,my-longpolling-amf,my-polling-amf"/>
   </flex:message-broker>

   <flex:remoting-destination ref="jdbcCustomerService" destination-id="customerService"/>

</beans>



                                                                              CustomerForm.mxml - client

<fx:Declarations><s:RemoteObject id="cs" destination="customerService"
endpoint="{serviceUrl}">
  <s:method name="createCustomer" result="create_resultHandler(event)"/>
  <s:method name="updateCustomer" result="update_resultHandler(event)"/>
 </s:RemoteObject> </fx:Declarations>
<fx:Script><![CDATA[ cs.updateCustomer( c.id, c.firstName, c.lastName); ]]>
</fx:Script>




                                         NOT CONFIDENTIAL -- TELL EVERYONE                              30
Thin, Thick, Web, Mobile and Rich Clients: RIA with Flex

 Demos:
• exposing Spring services through BlazeDS
• consuming it from a Flex client




                                NOT CONFIDENTIAL -- TELL EVERYONE
Thin, Thick, Web, Mobile and Rich Clients: GWT

             Google Web Toolkit
            • Lots of popular options
            • We’ll look at building a simple example by simple delegating as
             appropriate
            • Server-side: standard DispatcherServlet




                           NOT CONFIDENTIAL -- TELL EVERYONE
Thin, Thick, Web, Mobile and Rich Clients: GWT
                                                        GwtCustomerService - client

import com.google.gwt.user.client.rpc.*;

@RemoteServiceRelativePath("crm")
public interface GwtCustomerService extends RemoteService {
    void updateCustomer(long cid, String f, String l);
    CustomerDto getCustomerById(long customerId);
    CustomerDto createCustomer(String f, String ln);
}



GwtCustomerServiceImpl - server

 private <T> T beanOfType(Class t) {
   ApplicationContext ac = WebApplicationContextUtils.getWebApplicationContext(
         getServletContext());
   return (T) ac.getBean(t);
 }

 public void updateCustomer(long cid, String f, String l) {
   try {
     CustomerService customerService = beanOfType(CustomerService.class);
     customerService.updateCustomer(cid, f, l);
   } catch (Exception ex) {
     throw new RuntimeException(ex);
   }
 }
                                  NOT CONFIDENTIAL -- TELL EVERYONE                   33
Thin, Thick, Web, Mobile and Rich Clients: GWT

 Demos:
• building a simple GWT client that consumes services in Spring




                               NOT CONFIDENTIAL -- TELL EVERYONE
Social Communication




                       NOT CONFIDENTIAL -- TELL EVERYONE   35
Spring Social

 Extension to Spring Framework to enable connectivity with
  Software-as-a-Service providers
 Features...
 • An extensible connection framework
 • A connect controller
 • Java API bindings
 • A sign-in controller
 http://www.springsource.org/spring-social




                                                              36
Spring Social Projects

   Spring Social Core
   Spring Social Facebook
   Spring Social Twitter
   Spring Social LinkedIn
   Spring Social TripIt
   Spring Social GitHub
   Spring Social Gowalla
   Spring Social Samples
    • Includes Showcase, Quickstart, Movies, Canvas, Twitter4J, Popup




                                                                        37
Key Steps to Socializing an Application

 Configure Spring Social beans
 • Connection Factory Locator and Connection Factories
 • Connection Repository
 • Connect Controller
 • API Bindings
 Create connection status views
 Inject/use API bindings




                                                         38
Configuration: ConnectionFactoryLocator


@Bean
@Scope(value="singleton", proxyMode=ScopedProxyMode.INTERFACES)
public ConnectionFactoryLocator connectionFactoryLocator() {
 ConnectionFactoryRegistry registry = new ConnectionFactoryRegistry();

    registry.addConnectionFactory(
       new TwitterConnectionFactory(
          environment.getProperty("twitter.consumerKey"),
          environment.getProperty("twitter.consumerSecret")));

    registry.addConnectionFactory(
       new FacebookConnectionFactory(
          environment.getProperty("facebook.clientId"),
          environment.getProperty("facebook.clientSecret")));

    return registry;
}


                                                                         39
Configuration: ConnectionFactoryLocator


@Bean
@Scope(value="singleton", proxyMode=ScopedProxyMode.INTERFACES)
public ConnectionFactoryLocator connectionFactoryLocator() {
 ConnectionFactoryRegistry registry = new ConnectionFactoryRegistry();

    registry.addConnectionFactory(
       new TwitterConnectionFactory(
          environment.getProperty("twitter.consumerKey"),
          environment.getProperty("twitter.consumerSecret")));

    registry.addConnectionFactory(
       new FacebookConnectionFactory(
          environment.getProperty("facebook.clientId"),
          environment.getProperty("facebook.clientSecret")));

    return registry;
}


                                                                         39
Configuration: ConnectionFactoryLocator


@Bean
@Scope(value="singleton", proxyMode=ScopedProxyMode.INTERFACES)
public ConnectionFactoryLocator connectionFactoryLocator() {
 ConnectionFactoryRegistry registry = new ConnectionFactoryRegistry();

    registry.addConnectionFactory(
       new TwitterConnectionFactory(
          environment.getProperty("twitter.consumerKey"),
          environment.getProperty("twitter.consumerSecret")));

    registry.addConnectionFactory(
       new FacebookConnectionFactory(
          environment.getProperty("facebook.clientId"),
          environment.getProperty("facebook.clientSecret")));

    return registry;
}


                                                                         39
Configuration: ConnectionFactoryLocator


@Bean
@Scope(value="singleton", proxyMode=ScopedProxyMode.INTERFACES)
public ConnectionFactoryLocator connectionFactoryLocator() {
 ConnectionFactoryRegistry registry = new ConnectionFactoryRegistry();

    registry.addConnectionFactory(
       new TwitterConnectionFactory(
          environment.getProperty("twitter.consumerKey"),
          environment.getProperty("twitter.consumerSecret")));

    registry.addConnectionFactory(
       new FacebookConnectionFactory(
          environment.getProperty("facebook.clientId"),
          environment.getProperty("facebook.clientSecret")));

    return registry;
}


                                                                         39
Configuration: Connection Repository


@Bean
@Scope(value="request", proxyMode=ScopedProxyMode.INTERFACES)	
public ConnectionRepository connectionRepository() {
  Authentication authentication = SecurityContextHolder.getContext().
            getAuthentication();
  if (authentication == null) {
    throw new IllegalStateException(
        "Unable to get a ConnectionRepository: no user signed in");
  }
  return usersConnectionRepository().createConnectionRepository(
          authentication.getName());
}




                                                                        40
Configuration: Connection Repository


@Bean
@Scope(value="request", proxyMode=ScopedProxyMode.INTERFACES)	
public ConnectionRepository connectionRepository() {
  Authentication authentication = SecurityContextHolder.getContext().
            getAuthentication();
  if (authentication == null) {
    throw new IllegalStateException(
        "Unable to get a ConnectionRepository: no user signed in");
  }
  return usersConnectionRepository().createConnectionRepository(
          authentication.getName());
}

@Bean
@Scope(value="singleton", proxyMode=ScopedProxyMode.INTERFACES)
public UsersConnectionRepository usersConnectionRepository() {
  return new JdbcUsersConnectionRepository(
          dataSource,
          connectionFactoryLocator(),
          Encryptors.noOpText());
}

                                                                        40
Configuration: ConnectController


 @Bean
 public ConnectController connectController() {
   return new ConnectController(connectionFactoryLocator(),
                 connectionRepository());
 }




                                                              41
Configuration: ConnectController


 @Bean
 public ConnectController connectController() {
   return new ConnectController(connectionFactoryLocator(),
                 connectionRepository());
 }




                                                              41
Configuration: ConnectController


 @Bean
 public ConnectController connectController() {
   return new ConnectController(connectionFactoryLocator(),
                 connectionRepository());
 }




                                                              41
Configuration: API Bindings



@Bean
@Scope(value="request", proxyMode=ScopedProxyMode.INTERFACES)	
public Facebook facebook() {
  Connection<Facebook> facebook =
        connectionRepository().findPrimaryConnection(Facebook.class);
  return facebook != null ? facebook.getApi() : new FacebookTemplate();
}
	
@Bean
@Scope(value="request", proxyMode=ScopedProxyMode.INTERFACES)	
public Twitter twitter() {
  Connection<Twitter> twitter =
       connectionRepository().findPrimaryConnection(Twitter.class);
  return twitter != null ? twitter.getApi() : new TwitterTemplate();
}



                                                                          42
Configuration: API Bindings



@Bean
@Scope(value="request", proxyMode=ScopedProxyMode.INTERFACES)	
public Facebook facebook() {
  Connection<Facebook> facebook =
        connectionRepository().findPrimaryConnection(Facebook.class);
  return facebook != null ? facebook.getApi() : new FacebookTemplate();
}
	
@Bean
@Scope(value="request", proxyMode=ScopedProxyMode.INTERFACES)	
public Twitter twitter() {
  Connection<Twitter> twitter =
       connectionRepository().findPrimaryConnection(Twitter.class);
  return twitter != null ? twitter.getApi() : new TwitterTemplate();
}



                                                                          42
Configuration: API Bindings



@Bean
@Scope(value="request", proxyMode=ScopedProxyMode.INTERFACES)	
public Facebook facebook() {
  Connection<Facebook> facebook =
        connectionRepository().findPrimaryConnection(Facebook.class);
  return facebook != null ? facebook.getApi() : new FacebookTemplate();
}
	
@Bean
@Scope(value="request", proxyMode=ScopedProxyMode.INTERFACES)	
public Twitter twitter() {
  Connection<Twitter> twitter =
       connectionRepository().findPrimaryConnection(Twitter.class);
  return twitter != null ? twitter.getApi() : new TwitterTemplate();
}



                                                                          42
Configuration: API Bindings



@Bean
@Scope(value="request", proxyMode=ScopedProxyMode.INTERFACES)	
public Facebook facebook() {
  Connection<Facebook> facebook =
        connectionRepository().findPrimaryConnection(Facebook.class);
  return facebook != null ? facebook.getApi() : new FacebookTemplate();
}
	
@Bean
@Scope(value="request", proxyMode=ScopedProxyMode.INTERFACES)	
public Twitter twitter() {
  Connection<Twitter> twitter =
       connectionRepository().findPrimaryConnection(Twitter.class);
  return twitter != null ? twitter.getApi() : new TwitterTemplate();
}



                                                                          42
Injecting and Using the API Bindings


 @Controller
 public class TwitterTimelineController {

 	   private final Twitter twitter;
 	
 	   @Inject
 	   public TwitterTimelineController(Twitter twitter) {
 	   	  this.twitter = twitter;
 	   }

 	   @RequestMapping(value="/twitter/tweet",
                        method=RequestMethod.POST)
 	   public String postTweet(String message) {
 	   	  twitter.timelineOperations().updateStatus(message);
 	   	  return "redirect:/twitter";
 	   }
 }

                                                              43
Injecting and Using the API Bindings


 @Controller
 public class TwitterTimelineController {

 	   private final Twitter twitter;
 	
 	   @Inject
 	   public TwitterTimelineController(Twitter twitter) {
 	   	  this.twitter = twitter;
 	   }

 	   @RequestMapping(value="/twitter/tweet",
                        method=RequestMethod.POST)
 	   public String postTweet(String message) {
 	   	  twitter.timelineOperations().updateStatus(message);
 	   	  return "redirect:/twitter";
 	   }
 }

                                                              43
Injecting and Using the API Bindings


 @Controller
 public class TwitterTimelineController {

 	   private final Twitter twitter;
 	
 	   @Inject
 	   public TwitterTimelineController(Twitter twitter) {
 	   	  this.twitter = twitter;
 	   }

 	   @RequestMapping(value="/twitter/tweet",
                        method=RequestMethod.POST)
 	   public String postTweet(String message) {
 	   	  twitter.timelineOperations().updateStatus(message);
 	   	  return "redirect:/twitter";
 	   }
 }

                                                              43
ConnectController Endpoints
 GET /connect
 • Displays connection status for all providers
 GET /connect/{provider}
 • Displays connection status for a given provider
 POST /connect/{provider}
 • Initiates the authorization flow, redirecting to the provider
 GET /connect/{provider}?oauth_token={token}
 • Handles an OAuth 1 callback
 GET /connect/{provider}?code={authorization code}
 • Handles an OAuth 2 callback
 DELETE /connect/{provider}
 • Removes all connections for a user to the given provider
 DELETE /connect/{provider}/{provider user ID}
 • Removes a specific connection for the user to the given provider
                                                                      44
ConnectController Flow



                                                     Your Application


                                                    ConnectController




                            Service Provider
                         (Twitter, Facebook, etc)




                                                                        45
ConnectController Flow



                                                     Your Application

                     GET /connect/{provider ID}
                                                    ConnectController




                            Service Provider
                         (Twitter, Facebook, etc)




                 Display connection status page
                                                                        45
ConnectController Flow



                                                     Your Application

                     POST /connect/{provider ID}
                                                    ConnectController




                            Service Provider
                         (Twitter, Facebook, etc)




                    Initiate connection flow
                                                                        45
ConnectController Flow



                                                     Your Application


                                                    ConnectController




                            Service Provider
                         (Twitter, Facebook, etc)




            Fetch request token (OAuth 1.0/1.0a only)
                                                                        45
ConnectController Flow



                                                      Your Application


                                                     ConnectController




                            Service Provider
                         (Twitter, Facebook, etc)




          Redirect browser to provider’s authorization page
                                                                         45
ConnectController Flow



                                                      Your Application


                                                     ConnectController




                            Service Provider
                         (Twitter, Facebook, etc)




          Redirect browser to provider’s authorization page
                                                                         45
ConnectController Flow



                                                      Your Application


                                                     ConnectController




                            Service Provider
                         (Twitter, Facebook, etc)




          Redirect browser to provider’s authorization page
                                                                         45
ConnectController Flow



                                                                 Your Application
               GET /connect/{provider ID}?oauth_token={token}
                  GET /connect/{provider ID}?code={code}
                                                                ConnectController




                             Service Provider
                          (Twitter, Facebook, etc)




                Provider redirects to callback URL
                                                                                    45
ConnectController Flow



                                                     Your Application


                                                    ConnectController




                            Service Provider
                         (Twitter, Facebook, etc)




        Exchange request token and/or code for access token
                                                                        45
ConnectController Flow



                                                        Your Application


                                                       ConnectController




                              Service Provider
                           (Twitter, Facebook, etc)




  ConnectController stores connection details in connection repository
                                                                           45
ConnectController Flow



                                                      Your Application


                                                     ConnectController




                            Service Provider
                         (Twitter, Facebook, etc)




           Application can make API calls via API binding
                                                                         45
Connection Status Page View


<form action="<c:url value="/connect/twitter" />" method="POST">
 <div class="formInfo">
  <p>
  You haven't created any connections with Twitter yet.
  Click the button to connect with your Twitter account.
  </p>
 </div>
 <p>
  <button type="submit">
  <img src="<c:url value="/resources/social/twitter/connect-with-twitter.png" />"/>
  </button>
 </p>
</form>




                                                                                      46
Provider Sign In

 A convenience for users
 Enables authentication to an app using their connection as
 credentials
 Implemented with ProviderSignInController
 Works consistently with any provider




                                                               47
Configuration: ProviderSignInController

   Performs a similar flow as ConnectController
   Compares connections (by user ID)
   If there’s a match, the user is signed into the application
   Otherwise, the user is sent to signup page
    • Connection is be established after signup




@Bean
public ProviderSignInController providerSignInController(
        RequestCache requestCache) {
  return new ProviderSignInController(connectionFactoryLocator(),
                    usersConnectionRepository(),
                    new SimpleSignInAdapter(requestCache));
}

                                                                    48
Configuration: ProviderSignInController

   Performs a similar flow as ConnectController
   Compares connections (by user ID)
   If there’s a match, the user is signed into the application
   Otherwise, the user is sent to signup page
    • Connection is be established after signup




@Bean
public ProviderSignInController providerSignInController(
        RequestCache requestCache) {
  return new ProviderSignInController(connectionFactoryLocator(),
                    usersConnectionRepository(),
                    new SimpleSignInAdapter(requestCache));
}

                                                                    48
Configuration: ProviderSignInController

   Performs a similar flow as ConnectController
   Compares connections (by user ID)
   If there’s a match, the user is signed into the application
   Otherwise, the user is sent to signup page
    • Connection is be established after signup




@Bean
public ProviderSignInController providerSignInController(
        RequestCache requestCache) {
  return new ProviderSignInController(connectionFactoryLocator(),
                    usersConnectionRepository(),
                    new SimpleSignInAdapter(requestCache));
}

                                                                    48
Configuration: ProviderSignInController

   Performs a similar flow as ConnectController
   Compares connections (by user ID)
   If there’s a match, the user is signed into the application
   Otherwise, the user is sent to signup page
    • Connection is be established after signup




@Bean
public ProviderSignInController providerSignInController(
        RequestCache requestCache) {
  return new ProviderSignInController(connectionFactoryLocator(),
                    usersConnectionRepository(),
                    new SimpleSignInAdapter(requestCache));
}

                                                                    48
ProviderSignInController Endpoints

 POST /signin/{provider}
 • Initiates the authorization flow, redirecting to the provider
 GET /signin/{provider}?oauth_token={token}
 • Handles an OAuth 1 callback
 GET /signin/{provider}?code={authorization code}
 • Handles an OAuth 2 callback
 GET /signin
 • Handles a callback when no oauth token or code is sent
 • Likely indicates that the user declined authorization




                                                                   49
Social Security OAuth




                        NOT CONFIDENTIAL -- TELL EVERYONE   50
Spring Security OAuth

 Extension to Spring Security
 • originally a community contribution (now officially part of the project)
 Features...
 • endpoint management for OAuth service types
 • (along with corresponding client management)
 • token management (persistence, authentication)
 • integrations for the web, as well as through standard Spring Security
 springsource.org/spring-security/oauth




                                                                              51
Setup Spring Security with Spring MVC...



<http access-denied-page="/login.jsp"
    xmlns="http://www.springframework.org/schema/security">

	       <form-login authentication-failure-url="/login.jsp"
            default-target-url="/index.jsp"
            login-page="/login.jsp"
            login-processing-url="/login.do" />

	       <logout logout-success-url="/index.jsp" logout-url="/logout.do" />

    	   <anonymous />

	       <intercept-url pattern="/sparklr/**" access="ROLE_USER" />

	       <custom-filter ref="oauth2ClientFilter" after="EXCEPTION_TRANSLATION_FILTER" />

</http>




                                                                                     52
Then Tell Spring Security About Our OAuth Endpoints

<authentication-manager
   xmlns="http://www.springframework.org/schema/security">
	    <authentication-provider>
	    	    <user-service>
   	      	     <user name="marissa" password="wombat"
                        authorities="ROLE_USER" />
   	      	     <user name="sam" password="kangaroo"
                        authorities="ROLE_USER" />
	    	    </user-service>
	    </authentication-provider>
</authentication-manager>

<oauth:client id="oauth2ClientFilter"
   redirect-on-error="${redirectOnError:false}" />

<oauth:resource id="sparklr"
   type="authorization_code" client-id="tonr"
   client-secret="secret" access-token-uri="${accessTokenUri}"
   user-authorization-uri="${userAuthorizationUri}" scope="read" />

                                                                      53
Then get an Instance of a RestTemplate for the client...




<bean class="org.springframework.security.oauth2.client.OAuth2RestTemplate">
  <constructor-arg ref = “sparklr”/>
</bean>




                                                                         54
Questions?




Josh Long | josh.long@springsource.com | @starbuxman
                   NOT CONFIDENTIAL -- TELL EVERYONE

Mais conteúdo relacionado

Mais procurados

a Running Tour of Cloud Foundry
a Running Tour of Cloud Foundrya Running Tour of Cloud Foundry
a Running Tour of Cloud FoundryJoshua Long
 
Spring MVC
Spring MVCSpring MVC
Spring MVCyuvalb
 
Spring in the Cloud - using Spring with Cloud Foundry
Spring in the Cloud - using Spring with Cloud FoundrySpring in the Cloud - using Spring with Cloud Foundry
Spring in the Cloud - using Spring with Cloud FoundryJoshua Long
 
Spring Portlet MVC
Spring Portlet MVCSpring Portlet MVC
Spring Portlet MVCJohn Lewis
 
Java Spring MVC Framework with AngularJS by Google and HTML5
Java Spring MVC Framework with AngularJS by Google and HTML5Java Spring MVC Framework with AngularJS by Google and HTML5
Java Spring MVC Framework with AngularJS by Google and HTML5Tuna Tore
 
Java EE and Spring Side-by-Side
Java EE and Spring Side-by-SideJava EE and Spring Side-by-Side
Java EE and Spring Side-by-SideReza Rahman
 
Spring 3.x - Spring MVC
Spring 3.x - Spring MVCSpring 3.x - Spring MVC
Spring 3.x - Spring MVCGuy Nir
 
Java Server Faces + Spring MVC Framework
Java Server Faces + Spring MVC FrameworkJava Server Faces + Spring MVC Framework
Java Server Faces + Spring MVC FrameworkGuo Albert
 
springmvc-150923124312-lva1-app6892
springmvc-150923124312-lva1-app6892springmvc-150923124312-lva1-app6892
springmvc-150923124312-lva1-app6892Tuna Tore
 
Rest with Java EE 6 , Security , Backbone.js
Rest with Java EE 6 , Security , Backbone.jsRest with Java EE 6 , Security , Backbone.js
Rest with Java EE 6 , Security , Backbone.jsCarol McDonald
 
Spring 3.x - Spring MVC - Advanced topics
Spring 3.x - Spring MVC - Advanced topicsSpring 3.x - Spring MVC - Advanced topics
Spring 3.x - Spring MVC - Advanced topicsGuy Nir
 
The Cloud Foundry bootcamp talk from SpringOne On The Road - Europe
The Cloud Foundry bootcamp talk from SpringOne On The Road - EuropeThe Cloud Foundry bootcamp talk from SpringOne On The Road - Europe
The Cloud Foundry bootcamp talk from SpringOne On The Road - EuropeJoshua Long
 
Vue routing tutorial getting started with vue router
Vue routing tutorial getting started with vue routerVue routing tutorial getting started with vue router
Vue routing tutorial getting started with vue routerKaty Slemon
 
Spring 4 final xtr_presentation
Spring 4 final xtr_presentationSpring 4 final xtr_presentation
Spring 4 final xtr_presentationsourabh aggarwal
 
Spring Cairngorm
Spring CairngormSpring Cairngorm
Spring Cairngormdevaraj ns
 
JavaOne India 2011 - Servlets 3.0
JavaOne India 2011 - Servlets 3.0JavaOne India 2011 - Servlets 3.0
JavaOne India 2011 - Servlets 3.0Arun Gupta
 
Spring framework in depth
Spring framework in depthSpring framework in depth
Spring framework in depthVinay Kumar
 

Mais procurados (20)

Spring mvc
Spring mvcSpring mvc
Spring mvc
 
a Running Tour of Cloud Foundry
a Running Tour of Cloud Foundrya Running Tour of Cloud Foundry
a Running Tour of Cloud Foundry
 
Spring MVC
Spring MVCSpring MVC
Spring MVC
 
Spring in the Cloud - using Spring with Cloud Foundry
Spring in the Cloud - using Spring with Cloud FoundrySpring in the Cloud - using Spring with Cloud Foundry
Spring in the Cloud - using Spring with Cloud Foundry
 
Spring Portlet MVC
Spring Portlet MVCSpring Portlet MVC
Spring Portlet MVC
 
Java Spring MVC Framework with AngularJS by Google and HTML5
Java Spring MVC Framework with AngularJS by Google and HTML5Java Spring MVC Framework with AngularJS by Google and HTML5
Java Spring MVC Framework with AngularJS by Google and HTML5
 
Java EE and Spring Side-by-Side
Java EE and Spring Side-by-SideJava EE and Spring Side-by-Side
Java EE and Spring Side-by-Side
 
Spring 3.x - Spring MVC
Spring 3.x - Spring MVCSpring 3.x - Spring MVC
Spring 3.x - Spring MVC
 
Java Server Faces + Spring MVC Framework
Java Server Faces + Spring MVC FrameworkJava Server Faces + Spring MVC Framework
Java Server Faces + Spring MVC Framework
 
springmvc-150923124312-lva1-app6892
springmvc-150923124312-lva1-app6892springmvc-150923124312-lva1-app6892
springmvc-150923124312-lva1-app6892
 
Rest with Java EE 6 , Security , Backbone.js
Rest with Java EE 6 , Security , Backbone.jsRest with Java EE 6 , Security , Backbone.js
Rest with Java EE 6 , Security , Backbone.js
 
Spring MVC Basics
Spring MVC BasicsSpring MVC Basics
Spring MVC Basics
 
Spring 3.x - Spring MVC - Advanced topics
Spring 3.x - Spring MVC - Advanced topicsSpring 3.x - Spring MVC - Advanced topics
Spring 3.x - Spring MVC - Advanced topics
 
The Cloud Foundry bootcamp talk from SpringOne On The Road - Europe
The Cloud Foundry bootcamp talk from SpringOne On The Road - EuropeThe Cloud Foundry bootcamp talk from SpringOne On The Road - Europe
The Cloud Foundry bootcamp talk from SpringOne On The Road - Europe
 
Spring MVC 3.0 Framework
Spring MVC 3.0 FrameworkSpring MVC 3.0 Framework
Spring MVC 3.0 Framework
 
Vue routing tutorial getting started with vue router
Vue routing tutorial getting started with vue routerVue routing tutorial getting started with vue router
Vue routing tutorial getting started with vue router
 
Spring 4 final xtr_presentation
Spring 4 final xtr_presentationSpring 4 final xtr_presentation
Spring 4 final xtr_presentation
 
Spring Cairngorm
Spring CairngormSpring Cairngorm
Spring Cairngorm
 
JavaOne India 2011 - Servlets 3.0
JavaOne India 2011 - Servlets 3.0JavaOne India 2011 - Servlets 3.0
JavaOne India 2011 - Servlets 3.0
 
Spring framework in depth
Spring framework in depthSpring framework in depth
Spring framework in depth
 

Semelhante a Multi client Development with Spring

Web API or WCF - An Architectural Comparison
Web API or WCF - An Architectural ComparisonWeb API or WCF - An Architectural Comparison
Web API or WCF - An Architectural ComparisonAdnan Masood
 
vFabric - Ideal Platform for SaaS Apps
vFabric - Ideal Platform for SaaS AppsvFabric - Ideal Platform for SaaS Apps
vFabric - Ideal Platform for SaaS AppsVMware vFabric
 
Convertigo Mobile Application Development platform for Enterprises
Convertigo Mobile Application Development platform for EnterprisesConvertigo Mobile Application Development platform for Enterprises
Convertigo Mobile Application Development platform for EnterprisesConvertigo | MADP & MBaaS
 
Web Component Development Using Servlet & JSP Technologies (EE6) - Chapter 1...
 Web Component Development Using Servlet & JSP Technologies (EE6) - Chapter 1... Web Component Development Using Servlet & JSP Technologies (EE6) - Chapter 1...
Web Component Development Using Servlet & JSP Technologies (EE6) - Chapter 1...WebStackAcademy
 
Java servlet technology
Java servlet technologyJava servlet technology
Java servlet technologyMinal Maniar
 
Spring Mvc,Java, Spring
Spring Mvc,Java, SpringSpring Mvc,Java, Spring
Spring Mvc,Java, Springifnu bima
 
Enterprise Java in 2012 and Beyond, by Juergen Hoeller
Enterprise Java in 2012 and Beyond, by Juergen Hoeller Enterprise Java in 2012 and Beyond, by Juergen Hoeller
Enterprise Java in 2012 and Beyond, by Juergen Hoeller Codemotion
 
The spring 32 update final
The spring 32 update finalThe spring 32 update final
The spring 32 update finalJoshua Long
 
Introduction to Cloud Application Platform
Introduction to Cloud Application PlatformIntroduction to Cloud Application Platform
Introduction to Cloud Application PlatformVMware vFabric
 
WebSocket Perspectives and Vision for the Future
WebSocket Perspectives and Vision for the FutureWebSocket Perspectives and Vision for the Future
WebSocket Perspectives and Vision for the FutureFrank Greco
 
App Mod 01: Moving existing apps to the cloud
App Mod 01: Moving existing apps to the cloudApp Mod 01: Moving existing apps to the cloud
App Mod 01: Moving existing apps to the cloudJudy Breedlove
 
Best of Microsoft Dev Camp 2015
Best of Microsoft Dev Camp 2015Best of Microsoft Dev Camp 2015
Best of Microsoft Dev Camp 2015Bluegrass Digital
 
GigaSpaces CCF 4 Xap
GigaSpaces CCF 4 XapGigaSpaces CCF 4 Xap
GigaSpaces CCF 4 XapShay Hassidim
 

Semelhante a Multi client Development with Spring (20)

Spring Mvc
Spring MvcSpring Mvc
Spring Mvc
 
V fabric overview
V fabric overviewV fabric overview
V fabric overview
 
Web API or WCF - An Architectural Comparison
Web API or WCF - An Architectural ComparisonWeb API or WCF - An Architectural Comparison
Web API or WCF - An Architectural Comparison
 
vFabric - Ideal Platform for SaaS Apps
vFabric - Ideal Platform for SaaS AppsvFabric - Ideal Platform for SaaS Apps
vFabric - Ideal Platform for SaaS Apps
 
sMash_for_zOS-users
sMash_for_zOS-userssMash_for_zOS-users
sMash_for_zOS-users
 
Convertigo Mobile Application Development platform for Enterprises
Convertigo Mobile Application Development platform for EnterprisesConvertigo Mobile Application Development platform for Enterprises
Convertigo Mobile Application Development platform for Enterprises
 
Web Component Development Using Servlet & JSP Technologies (EE6) - Chapter 1...
 Web Component Development Using Servlet & JSP Technologies (EE6) - Chapter 1... Web Component Development Using Servlet & JSP Technologies (EE6) - Chapter 1...
Web Component Development Using Servlet & JSP Technologies (EE6) - Chapter 1...
 
Net Services
Net ServicesNet Services
Net Services
 
Java servlet technology
Java servlet technologyJava servlet technology
Java servlet technology
 
Intro to Sails.js
Intro to Sails.jsIntro to Sails.js
Intro to Sails.js
 
Spring Mvc,Java, Spring
Spring Mvc,Java, SpringSpring Mvc,Java, Spring
Spring Mvc,Java, Spring
 
Enterprise Java in 2012 and Beyond, by Juergen Hoeller
Enterprise Java in 2012 and Beyond, by Juergen Hoeller Enterprise Java in 2012 and Beyond, by Juergen Hoeller
Enterprise Java in 2012 and Beyond, by Juergen Hoeller
 
Spring Into the Cloud
Spring Into the CloudSpring Into the Cloud
Spring Into the Cloud
 
The spring 32 update final
The spring 32 update finalThe spring 32 update final
The spring 32 update final
 
Introduction to Cloud Application Platform
Introduction to Cloud Application PlatformIntroduction to Cloud Application Platform
Introduction to Cloud Application Platform
 
WebSocket Perspectives and Vision for the Future
WebSocket Perspectives and Vision for the FutureWebSocket Perspectives and Vision for the Future
WebSocket Perspectives and Vision for the Future
 
App Mod 01: Moving existing apps to the cloud
App Mod 01: Moving existing apps to the cloudApp Mod 01: Moving existing apps to the cloud
App Mod 01: Moving existing apps to the cloud
 
Google App Engine overview (GAE/J)
Google App Engine overview (GAE/J)Google App Engine overview (GAE/J)
Google App Engine overview (GAE/J)
 
Best of Microsoft Dev Camp 2015
Best of Microsoft Dev Camp 2015Best of Microsoft Dev Camp 2015
Best of Microsoft Dev Camp 2015
 
GigaSpaces CCF 4 Xap
GigaSpaces CCF 4 XapGigaSpaces CCF 4 Xap
GigaSpaces CCF 4 Xap
 

Mais de Joshua Long

Economies of Scaling Software
Economies of Scaling SoftwareEconomies of Scaling Software
Economies of Scaling SoftwareJoshua Long
 
Bootiful Code with Spring Boot
Bootiful Code with Spring BootBootiful Code with Spring Boot
Bootiful Code with Spring BootJoshua Long
 
Microservices with Spring Boot
Microservices with Spring BootMicroservices with Spring Boot
Microservices with Spring BootJoshua Long
 
Have You Seen Spring Lately?
Have You Seen Spring Lately?Have You Seen Spring Lately?
Have You Seen Spring Lately?Joshua Long
 
Java Configuration Deep Dive with Spring
Java Configuration Deep Dive with SpringJava Configuration Deep Dive with Spring
Java Configuration Deep Dive with SpringJoshua Long
 
the Spring Update from JavaOne 2013
the Spring Update from JavaOne 2013the Spring Update from JavaOne 2013
the Spring Update from JavaOne 2013Joshua Long
 
Multi Client Development with Spring for SpringOne 2GX 2013 with Roy Clarkson
Multi Client Development with Spring for SpringOne 2GX 2013 with Roy ClarksonMulti Client Development with Spring for SpringOne 2GX 2013 with Roy Clarkson
Multi Client Development with Spring for SpringOne 2GX 2013 with Roy ClarksonJoshua Long
 
REST APIs with Spring
REST APIs with SpringREST APIs with Spring
REST APIs with SpringJoshua Long
 
the Spring 4 update
the Spring 4 updatethe Spring 4 update
the Spring 4 updateJoshua Long
 
Extending spring
Extending springExtending spring
Extending springJoshua Long
 
Integration and Batch Processing on Cloud Foundry
Integration and Batch Processing on Cloud FoundryIntegration and Batch Processing on Cloud Foundry
Integration and Batch Processing on Cloud FoundryJoshua Long
 
using Spring and MongoDB on Cloud Foundry
using Spring and MongoDB on Cloud Foundryusing Spring and MongoDB on Cloud Foundry
using Spring and MongoDB on Cloud FoundryJoshua Long
 
Spring in-the-cloud
Spring in-the-cloudSpring in-the-cloud
Spring in-the-cloudJoshua Long
 
Spring Batch Behind the Scenes
Spring Batch Behind the ScenesSpring Batch Behind the Scenes
Spring Batch Behind the ScenesJoshua Long
 
Cloud Foundry Bootcamp
Cloud Foundry BootcampCloud Foundry Bootcamp
Cloud Foundry BootcampJoshua Long
 
Spring and Cloud Foundry; a Marriage Made in Heaven
Spring and Cloud Foundry; a Marriage Made in HeavenSpring and Cloud Foundry; a Marriage Made in Heaven
Spring and Cloud Foundry; a Marriage Made in HeavenJoshua Long
 
Spring 3.1: a Walking Tour
Spring 3.1: a Walking TourSpring 3.1: a Walking Tour
Spring 3.1: a Walking TourJoshua Long
 
Extending Spring for Custom Usage
Extending Spring for Custom UsageExtending Spring for Custom Usage
Extending Spring for Custom UsageJoshua Long
 
Using Spring's IOC Model
Using Spring's IOC ModelUsing Spring's IOC Model
Using Spring's IOC ModelJoshua Long
 

Mais de Joshua Long (20)

Economies of Scaling Software
Economies of Scaling SoftwareEconomies of Scaling Software
Economies of Scaling Software
 
Bootiful Code with Spring Boot
Bootiful Code with Spring BootBootiful Code with Spring Boot
Bootiful Code with Spring Boot
 
Microservices with Spring Boot
Microservices with Spring BootMicroservices with Spring Boot
Microservices with Spring Boot
 
Boot It Up
Boot It UpBoot It Up
Boot It Up
 
Have You Seen Spring Lately?
Have You Seen Spring Lately?Have You Seen Spring Lately?
Have You Seen Spring Lately?
 
Java Configuration Deep Dive with Spring
Java Configuration Deep Dive with SpringJava Configuration Deep Dive with Spring
Java Configuration Deep Dive with Spring
 
the Spring Update from JavaOne 2013
the Spring Update from JavaOne 2013the Spring Update from JavaOne 2013
the Spring Update from JavaOne 2013
 
Multi Client Development with Spring for SpringOne 2GX 2013 with Roy Clarkson
Multi Client Development with Spring for SpringOne 2GX 2013 with Roy ClarksonMulti Client Development with Spring for SpringOne 2GX 2013 with Roy Clarkson
Multi Client Development with Spring for SpringOne 2GX 2013 with Roy Clarkson
 
REST APIs with Spring
REST APIs with SpringREST APIs with Spring
REST APIs with Spring
 
the Spring 4 update
the Spring 4 updatethe Spring 4 update
the Spring 4 update
 
Extending spring
Extending springExtending spring
Extending spring
 
Integration and Batch Processing on Cloud Foundry
Integration and Batch Processing on Cloud FoundryIntegration and Batch Processing on Cloud Foundry
Integration and Batch Processing on Cloud Foundry
 
using Spring and MongoDB on Cloud Foundry
using Spring and MongoDB on Cloud Foundryusing Spring and MongoDB on Cloud Foundry
using Spring and MongoDB on Cloud Foundry
 
Spring in-the-cloud
Spring in-the-cloudSpring in-the-cloud
Spring in-the-cloud
 
Spring Batch Behind the Scenes
Spring Batch Behind the ScenesSpring Batch Behind the Scenes
Spring Batch Behind the Scenes
 
Cloud Foundry Bootcamp
Cloud Foundry BootcampCloud Foundry Bootcamp
Cloud Foundry Bootcamp
 
Spring and Cloud Foundry; a Marriage Made in Heaven
Spring and Cloud Foundry; a Marriage Made in HeavenSpring and Cloud Foundry; a Marriage Made in Heaven
Spring and Cloud Foundry; a Marriage Made in Heaven
 
Spring 3.1: a Walking Tour
Spring 3.1: a Walking TourSpring 3.1: a Walking Tour
Spring 3.1: a Walking Tour
 
Extending Spring for Custom Usage
Extending Spring for Custom UsageExtending Spring for Custom Usage
Extending Spring for Custom Usage
 
Using Spring's IOC Model
Using Spring's IOC ModelUsing Spring's IOC Model
Using Spring's IOC Model
 

Último

Comparing Sidecar-less Service Mesh from Cilium and Istio
Comparing Sidecar-less Service Mesh from Cilium and IstioComparing Sidecar-less Service Mesh from Cilium and Istio
Comparing Sidecar-less Service Mesh from Cilium and IstioChristian Posta
 
UiPath Solutions Management Preview - Northern CA Chapter - March 22.pdf
UiPath Solutions Management Preview - Northern CA Chapter - March 22.pdfUiPath Solutions Management Preview - Northern CA Chapter - March 22.pdf
UiPath Solutions Management Preview - Northern CA Chapter - March 22.pdfDianaGray10
 
ADOPTING WEB 3 FOR YOUR BUSINESS: A STEP-BY-STEP GUIDE
ADOPTING WEB 3 FOR YOUR BUSINESS: A STEP-BY-STEP GUIDEADOPTING WEB 3 FOR YOUR BUSINESS: A STEP-BY-STEP GUIDE
ADOPTING WEB 3 FOR YOUR BUSINESS: A STEP-BY-STEP GUIDELiveplex
 
The Kubernetes Gateway API and its role in Cloud Native API Management
The Kubernetes Gateway API and its role in Cloud Native API ManagementThe Kubernetes Gateway API and its role in Cloud Native API Management
The Kubernetes Gateway API and its role in Cloud Native API ManagementNuwan Dias
 
IESVE Software for Florida Code Compliance Using ASHRAE 90.1-2019
IESVE Software for Florida Code Compliance Using ASHRAE 90.1-2019IESVE Software for Florida Code Compliance Using ASHRAE 90.1-2019
IESVE Software for Florida Code Compliance Using ASHRAE 90.1-2019IES VE
 
OpenShift Commons Paris - Choose Your Own Observability Adventure
OpenShift Commons Paris - Choose Your Own Observability AdventureOpenShift Commons Paris - Choose Your Own Observability Adventure
OpenShift Commons Paris - Choose Your Own Observability AdventureEric D. Schabell
 
Crea il tuo assistente AI con lo Stregatto (open source python framework)
Crea il tuo assistente AI con lo Stregatto (open source python framework)Crea il tuo assistente AI con lo Stregatto (open source python framework)
Crea il tuo assistente AI con lo Stregatto (open source python framework)Commit University
 
IEEE Computer Society’s Strategic Activities and Products including SWEBOK Guide
IEEE Computer Society’s Strategic Activities and Products including SWEBOK GuideIEEE Computer Society’s Strategic Activities and Products including SWEBOK Guide
IEEE Computer Society’s Strategic Activities and Products including SWEBOK GuideHironori Washizaki
 
100+ ChatGPT Prompts for SEO Optimization
100+ ChatGPT Prompts for SEO Optimization100+ ChatGPT Prompts for SEO Optimization
100+ ChatGPT Prompts for SEO Optimizationarrow10202532yuvraj
 
20230202 - Introduction to tis-py
20230202 - Introduction to tis-py20230202 - Introduction to tis-py
20230202 - Introduction to tis-pyJamie (Taka) Wang
 
KubeConEU24-Monitoring Kubernetes and Cloud Spend with OpenCost
KubeConEU24-Monitoring Kubernetes and Cloud Spend with OpenCostKubeConEU24-Monitoring Kubernetes and Cloud Spend with OpenCost
KubeConEU24-Monitoring Kubernetes and Cloud Spend with OpenCostMatt Ray
 
All in AI: LLM Landscape & RAG in 2024 with Mark Ryan (Google) & Jerry Liu (L...
All in AI: LLM Landscape & RAG in 2024 with Mark Ryan (Google) & Jerry Liu (L...All in AI: LLM Landscape & RAG in 2024 with Mark Ryan (Google) & Jerry Liu (L...
All in AI: LLM Landscape & RAG in 2024 with Mark Ryan (Google) & Jerry Liu (L...Daniel Zivkovic
 
Building Your Own AI Instance (TBLC AI )
Building Your Own AI Instance (TBLC AI )Building Your Own AI Instance (TBLC AI )
Building Your Own AI Instance (TBLC AI )Brian Pichman
 
COMPUTER 10 Lesson 8 - Building a Website
COMPUTER 10 Lesson 8 - Building a WebsiteCOMPUTER 10 Lesson 8 - Building a Website
COMPUTER 10 Lesson 8 - Building a Websitedgelyza
 
How Accurate are Carbon Emissions Projections?
How Accurate are Carbon Emissions Projections?How Accurate are Carbon Emissions Projections?
How Accurate are Carbon Emissions Projections?IES VE
 
9 Steps For Building Winning Founding Team
9 Steps For Building Winning Founding Team9 Steps For Building Winning Founding Team
9 Steps For Building Winning Founding TeamAdam Moalla
 
UWB Technology for Enhanced Indoor and Outdoor Positioning in Physiological M...
UWB Technology for Enhanced Indoor and Outdoor Positioning in Physiological M...UWB Technology for Enhanced Indoor and Outdoor Positioning in Physiological M...
UWB Technology for Enhanced Indoor and Outdoor Positioning in Physiological M...UbiTrack UK
 
UiPath Community: AI for UiPath Automation Developers
UiPath Community: AI for UiPath Automation DevelopersUiPath Community: AI for UiPath Automation Developers
UiPath Community: AI for UiPath Automation DevelopersUiPathCommunity
 
UiPath Studio Web workshop series - Day 8
UiPath Studio Web workshop series - Day 8UiPath Studio Web workshop series - Day 8
UiPath Studio Web workshop series - Day 8DianaGray10
 

Último (20)

Comparing Sidecar-less Service Mesh from Cilium and Istio
Comparing Sidecar-less Service Mesh from Cilium and IstioComparing Sidecar-less Service Mesh from Cilium and Istio
Comparing Sidecar-less Service Mesh from Cilium and Istio
 
UiPath Solutions Management Preview - Northern CA Chapter - March 22.pdf
UiPath Solutions Management Preview - Northern CA Chapter - March 22.pdfUiPath Solutions Management Preview - Northern CA Chapter - March 22.pdf
UiPath Solutions Management Preview - Northern CA Chapter - March 22.pdf
 
ADOPTING WEB 3 FOR YOUR BUSINESS: A STEP-BY-STEP GUIDE
ADOPTING WEB 3 FOR YOUR BUSINESS: A STEP-BY-STEP GUIDEADOPTING WEB 3 FOR YOUR BUSINESS: A STEP-BY-STEP GUIDE
ADOPTING WEB 3 FOR YOUR BUSINESS: A STEP-BY-STEP GUIDE
 
The Kubernetes Gateway API and its role in Cloud Native API Management
The Kubernetes Gateway API and its role in Cloud Native API ManagementThe Kubernetes Gateway API and its role in Cloud Native API Management
The Kubernetes Gateway API and its role in Cloud Native API Management
 
IESVE Software for Florida Code Compliance Using ASHRAE 90.1-2019
IESVE Software for Florida Code Compliance Using ASHRAE 90.1-2019IESVE Software for Florida Code Compliance Using ASHRAE 90.1-2019
IESVE Software for Florida Code Compliance Using ASHRAE 90.1-2019
 
OpenShift Commons Paris - Choose Your Own Observability Adventure
OpenShift Commons Paris - Choose Your Own Observability AdventureOpenShift Commons Paris - Choose Your Own Observability Adventure
OpenShift Commons Paris - Choose Your Own Observability Adventure
 
Crea il tuo assistente AI con lo Stregatto (open source python framework)
Crea il tuo assistente AI con lo Stregatto (open source python framework)Crea il tuo assistente AI con lo Stregatto (open source python framework)
Crea il tuo assistente AI con lo Stregatto (open source python framework)
 
IEEE Computer Society’s Strategic Activities and Products including SWEBOK Guide
IEEE Computer Society’s Strategic Activities and Products including SWEBOK GuideIEEE Computer Society’s Strategic Activities and Products including SWEBOK Guide
IEEE Computer Society’s Strategic Activities and Products including SWEBOK Guide
 
100+ ChatGPT Prompts for SEO Optimization
100+ ChatGPT Prompts for SEO Optimization100+ ChatGPT Prompts for SEO Optimization
100+ ChatGPT Prompts for SEO Optimization
 
20230202 - Introduction to tis-py
20230202 - Introduction to tis-py20230202 - Introduction to tis-py
20230202 - Introduction to tis-py
 
KubeConEU24-Monitoring Kubernetes and Cloud Spend with OpenCost
KubeConEU24-Monitoring Kubernetes and Cloud Spend with OpenCostKubeConEU24-Monitoring Kubernetes and Cloud Spend with OpenCost
KubeConEU24-Monitoring Kubernetes and Cloud Spend with OpenCost
 
All in AI: LLM Landscape & RAG in 2024 with Mark Ryan (Google) & Jerry Liu (L...
All in AI: LLM Landscape & RAG in 2024 with Mark Ryan (Google) & Jerry Liu (L...All in AI: LLM Landscape & RAG in 2024 with Mark Ryan (Google) & Jerry Liu (L...
All in AI: LLM Landscape & RAG in 2024 with Mark Ryan (Google) & Jerry Liu (L...
 
Building Your Own AI Instance (TBLC AI )
Building Your Own AI Instance (TBLC AI )Building Your Own AI Instance (TBLC AI )
Building Your Own AI Instance (TBLC AI )
 
COMPUTER 10 Lesson 8 - Building a Website
COMPUTER 10 Lesson 8 - Building a WebsiteCOMPUTER 10 Lesson 8 - Building a Website
COMPUTER 10 Lesson 8 - Building a Website
 
How Accurate are Carbon Emissions Projections?
How Accurate are Carbon Emissions Projections?How Accurate are Carbon Emissions Projections?
How Accurate are Carbon Emissions Projections?
 
9 Steps For Building Winning Founding Team
9 Steps For Building Winning Founding Team9 Steps For Building Winning Founding Team
9 Steps For Building Winning Founding Team
 
201610817 - edge part1
201610817 - edge part1201610817 - edge part1
201610817 - edge part1
 
UWB Technology for Enhanced Indoor and Outdoor Positioning in Physiological M...
UWB Technology for Enhanced Indoor and Outdoor Positioning in Physiological M...UWB Technology for Enhanced Indoor and Outdoor Positioning in Physiological M...
UWB Technology for Enhanced Indoor and Outdoor Positioning in Physiological M...
 
UiPath Community: AI for UiPath Automation Developers
UiPath Community: AI for UiPath Automation DevelopersUiPath Community: AI for UiPath Automation Developers
UiPath Community: AI for UiPath Automation Developers
 
UiPath Studio Web workshop series - Day 8
UiPath Studio Web workshop series - Day 8UiPath Studio Web workshop series - Day 8
UiPath Studio Web workshop series - Day 8
 

Multi client Development with Spring

  • 1. Spring and the Many Faces of the Web (or, Thin, Thick, Web, Mobile and Rich Clients with Spring) Josh Long @starbuxman Spring Developer Advocate SpringSource, a division of VMware © 2009 VMware Inc. All rights reserved
  • 2. About Josh Long SpringSource Developer Advocate twitter: @starbuxman josh.long@springsource.com NOT CONFIDENTIAL -- TELL EVERYONE 2
  • 3. Agenda  Introduction to Spring  Web Applications • Spring MVC, JSF, Others  REST • the final frontier: TV, tablets, operating systems  Mobile Clients • Android, iPhone  RIA / SOFEA • Flex, GWT, Vaadin  OAuth • Spring Social, Spring Security OAuth NOT CONFIDENTIAL -- TELL EVERYONE 3
  • 4. About  SpringSource is the organization that develops the Spring framework, the leading enterprise Java framework  SpringSource was acquired by VMware in 2009  VMware and SpringSource bring you to the cloud and deliver on the mission of “build, run, manage” • established partnerships with the major players in the business, including Adobe, SalesForce, and Google to help deliver the best experience for Spring users across multiple platforms  Leading contributor to projects like Apache HTTPD and Apache Tomcat NOT CONFIDENTIAL -- TELL EVERYONE 4
  • 5. Introduction to Spring NOT CONFIDENTIAL -- TELL EVERYONE 5
  • 6. At its core, the Spring Framework...  Provide comprehensive infrastructural support for developing enterprise Java™ applications • Spring deals with the plumbing • So you can focus on solving the domain problem NOT CONFIDENTIAL -- TELL EVERYONE 6
  • 7. Spring’s aim: bring simplicity to java development data web tier integration batch access & service tier & mobile processing / NoSQL / RIA messaging Big Data The Spring framework the cloud: lightweight traditional CloudFoundry WebSphere tc Server VMForce JBoss AS Tomcat Google App Engine WebLogic Jetty Amazon Web Services (on legacy versions, too!) NOT CONFIDENTIAL -- TELL EVERYONE 7
  • 8. 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 NOT CONFIDENTIAL -- TELL EVERYONE 8
  • 9. Web Applications with Spring NOT CONFIDENTIAL -- TELL EVERYONE 9
  • 10. 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>/WEB-INF/spring/myAppContext*.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> NOT CONFIDENTIAL -- TELL EVERYONE 10
  • 11. Thin, Thick, Web, Mobile and Rich Clients: Web Core  Spring Dispatcher Servlet • Objects don’t have to be web-specific. • Spring web supports lower-level web machinery: ‘ • HttpRequestHandler (supports remoting: Caucho, Resin, JAX RPC) • DelegatingFilterProxy. • HandlerInterceptor wraps requests to HttpRequestHandlers • ServletWrappingController lets you force requests to a servlet through the Spring Handler chain • OncePerRequestFilter ensures that an action only occurs once, no matter how many filters are applied. Provides a nice way to avoid duplicate filters • Spring provides access to the Spring application context using WebApplicationContextUtils, which has a static method to look up the context, even in environments where Spring isn’t managing the web components NOT CONFIDENTIAL -- TELL EVERYONE
  • 12. Thin, Thick, Web, Mobile and Rich Clients: Web Core  Spring provides the easiest way to integrate with your web framework of choice • Spring Faces for JSF 1 and 2 • Struts support for Struts 1 • Tapestry, Struts 2, Stripes, GWT, Wicket, Vaadin, Play framework, etc. NOT CONFIDENTIAL -- TELL EVERYONE
  • 13. Thin, Thick, Web, Mobile and Rich Clients: Spring MVC NOT CONFIDENTIAL -- TELL EVERYONE 13
  • 14. Thin, Thick, Web, Mobile and Rich Clients: Spring MVC Spring MVC configuration - config @Configuration @EnableWebMvc @Import(Config.class) public class WebConfig extends WebMvcConfigurerAdapter{ @Bean public UrlBasedViewResolver resolver() { UrlBasedViewResolver url = new UrlBasedViewResolver(); url.setPrefix("views/"); url.setViewClass(JstlView.class); url.setSuffix(".jsp"); return url; } public void configureViewControllers(ViewControllerConfigurer configurer) { configurer.mapViewName("/", "welcome") ; } } A Controller - config @Controller public class CustomerController { @Autowired private CustomerService customerService; @ModelAttribute public Customer customer() { return new Customer(); } @RequestMapping(value = "/display", method = RequestMethod.GET) public Map<String, Object> customer(@RequestParam("id") Long id) { Map<String, Object> out = new HashMap<String, Object>(); out.put("customer", customerService.getCustomerById(id) ); return out; } NOT CONFIDENTIAL -- TELL EVERYONE 14
  • 15. Thin, Thick, Web, Mobile and Rich Clients: Spring MVC  Demos • Spring MVC and associated configuration NOT CONFIDENTIAL -- TELL EVERYONE
  • 16. REST NOT CONFIDENTIAL -- TELL EVERYONE 16
  • 17. Thin, Thick, Web, Mobile and Rich Clients: REST  Spring MVC is basis for REST support • Spring’s server side REST support is based on the standard controller model • RestTemplate • provides dead simple, idiomatic RESTful services consumption • can use Spring OXM, too. • Spring Integration and Spring Social both build on the RestTemplate where possible. • JavaScript and HTML5 can consume JSON-data payloads • REST is the ultimate connectivity mechanism: everything can speak HTTP. NOT CONFIDENTIAL -- TELL EVERYONE
  • 18. Thin, Thick, Web, Mobile and Rich Clients: REST RestCustomerController - server @Controller @RequestMapping(headers = "Accept=application/json, application/xml") public class RestCustomerController { @Autowired private CustomerService cs; @RequestMapping(value = "/customer/{cid}", method = RequestMethod.POST) @ResponseBody public Customer updateCustomer(@RequestBody Customer c) { return cs.updateCustomer( c.getId(), c.getFirstName(), c.getLastName()); } WebConfig - server @EnableWebMvc @Import(Config.class) @Configuration public class WebConfig extends WebMvcConfigurerAdapter {} client Customer customer1 = restTemplate.getForEntity( url + "customer/{customerId}", Customer.class, c.getId()).getBody(); log.info("fetched customer " + customer1.toString()); NOT CONFIDENTIAL -- TELL EVERYONE 18
  • 19. Thin, Thick, Web, Mobile and Rich Clients: REST  Demos: • Spring REST service • Spring REST client NOT CONFIDENTIAL -- TELL EVERYONE
  • 20. Mobile (pt 1.) NOT CONFIDENTIAL -- TELL EVERYONE 20
  • 21. Thin, Thick, Web, Mobile and Rich Clients: Mobile  Best strategy? Develop Native • Fallback to client-optimized web applications  Spring MVC 3.1 mobile client-specific content negotiation and rendering • for other devices • (there are other devices besides Android??) NOT CONFIDENTIAL -- TELL EVERYONE 21
  • 22. Thin, Thick, Web, Mobile and Rich Clients: Mobile WebConfig - server ! @Bean public ViewResolver viewResolver() { UrlBasedViewResolver viewResolver = new UrlBasedViewResolver(); viewResolver.setViewClass(TilesView.class); return viewResolver; } @Bean public TilesConfigurer tilesConfigurer() { TilesConfigurer configurer = new TilesConfigurer(); configurer.setDefinitions(new String[]{ "/WEB-INF/layouts/tiles.xml", "/WEB-INF/views/**/tiles.xml" }); configurer.setCheckRefresh(true); return configurer; } @Override public void configureInterceptors(InterceptorConfigurer configurer) { configurer.addInterceptor(new DeviceResolverHandlerInterceptor()); } NOT CONFIDENTIAL -- TELL EVERYONE 22
  • 23. Thin, Thick, Web, Mobile and Rich Clients: REST  Demos: • Mobile clients using client specific rendering NOT CONFIDENTIAL -- TELL EVERYONE
  • 24. Mobile (pt 2.) NOT CONFIDENTIAL -- TELL EVERYONE 24
  • 25. Thin, Thick, Web, Mobile and Rich Clients: Mobile  Spring REST is ideal for mobile devices  Spring MVC 3.1 mobile client-specific content negotiation and rendering • for other devices  Spring Android • RestTemplate NOT CONFIDENTIAL -- TELL EVERYONE 25
  • 26. Thin, Thick, Web, Mobile and Rich Clients: Mobile CustomerServiceClient - client ! private <T> T extractResponse( ResponseEntity<T> response) { ! ! if (response != null && response().value() == 200) { ! ! ! return response.getBody(); ! ! } ! ! throw new RuntimeException("couldn't extract response."); ! } ! @Override ! public Customer updateCustomer(long id, String fn, String ln) { ! ! String urlForPath = urlForPath("customer/{customerId}");! ! ! ! return extractResponse(this.restTemplate.postForEntity( urlForPath, new Customer(id, fn, ln), Customer.class, id)); ! } NOT CONFIDENTIAL -- TELL EVERYONE 26
  • 27. Thin, Thick, Web, Mobile and Rich Clients: Mobile  Demos: • consuming the Spring REST service from Android NOT CONFIDENTIAL -- TELL EVERYONE
  • 28. Rich Internet Applications NOT CONFIDENTIAL -- TELL EVERYONE 28
  • 29. Thin, Thick, Web, Mobile and Rich Clients: Flex  Spring Flex • Dead-simple to expose Spring beans as Flex services • Developed with support from Adobe • But it still has strengths: • form driven apps • video, 2D and 3D graphics, sound • Adobe AIR • blazing fast communication • server side push • Spring ActionScript is a cool framework “sponsored” by SpringSource NOT CONFIDENTIAL -- TELL EVERYONE
  • 30. Thin, Thick, Web, Mobile and Rich Clients: Flex crm-flex-servlet.xml - server <?xml version="1.0" encoding="UTF-8"?> <beans ...> <context:component-scan base-package="org.springsource.examples.sawt.web.flex"/> <mvc:default-servlet-handler/> <flex:message-broker mapping-order="1"> <flex:mapping pattern="/messagebroker/*"/> <flex:message-service default-channels="my-streaming-amf,my-longpolling-amf,my-polling-amf"/> </flex:message-broker> <flex:remoting-destination ref="jdbcCustomerService" destination-id="customerService"/> </beans> CustomerForm.mxml - client <fx:Declarations><s:RemoteObject id="cs" destination="customerService" endpoint="{serviceUrl}"> <s:method name="createCustomer" result="create_resultHandler(event)"/> <s:method name="updateCustomer" result="update_resultHandler(event)"/> </s:RemoteObject> </fx:Declarations> <fx:Script><![CDATA[ cs.updateCustomer( c.id, c.firstName, c.lastName); ]]> </fx:Script> NOT CONFIDENTIAL -- TELL EVERYONE 30
  • 31. Thin, Thick, Web, Mobile and Rich Clients: RIA with Flex  Demos: • exposing Spring services through BlazeDS • consuming it from a Flex client NOT CONFIDENTIAL -- TELL EVERYONE
  • 32. Thin, Thick, Web, Mobile and Rich Clients: GWT  Google Web Toolkit • Lots of popular options • We’ll look at building a simple example by simple delegating as appropriate • Server-side: standard DispatcherServlet NOT CONFIDENTIAL -- TELL EVERYONE
  • 33. Thin, Thick, Web, Mobile and Rich Clients: GWT GwtCustomerService - client import com.google.gwt.user.client.rpc.*; @RemoteServiceRelativePath("crm") public interface GwtCustomerService extends RemoteService { void updateCustomer(long cid, String f, String l); CustomerDto getCustomerById(long customerId); CustomerDto createCustomer(String f, String ln); } GwtCustomerServiceImpl - server private <T> T beanOfType(Class t) { ApplicationContext ac = WebApplicationContextUtils.getWebApplicationContext( getServletContext()); return (T) ac.getBean(t); } public void updateCustomer(long cid, String f, String l) { try { CustomerService customerService = beanOfType(CustomerService.class); customerService.updateCustomer(cid, f, l); } catch (Exception ex) { throw new RuntimeException(ex); } } NOT CONFIDENTIAL -- TELL EVERYONE 33
  • 34. Thin, Thick, Web, Mobile and Rich Clients: GWT  Demos: • building a simple GWT client that consumes services in Spring NOT CONFIDENTIAL -- TELL EVERYONE
  • 35. Social Communication NOT CONFIDENTIAL -- TELL EVERYONE 35
  • 36. Spring Social  Extension to Spring Framework to enable connectivity with Software-as-a-Service providers  Features... • An extensible connection framework • A connect controller • Java API bindings • A sign-in controller  http://www.springsource.org/spring-social 36
  • 37. Spring Social Projects  Spring Social Core  Spring Social Facebook  Spring Social Twitter  Spring Social LinkedIn  Spring Social TripIt  Spring Social GitHub  Spring Social Gowalla  Spring Social Samples • Includes Showcase, Quickstart, Movies, Canvas, Twitter4J, Popup 37
  • 38. Key Steps to Socializing an Application  Configure Spring Social beans • Connection Factory Locator and Connection Factories • Connection Repository • Connect Controller • API Bindings  Create connection status views  Inject/use API bindings 38
  • 39. Configuration: ConnectionFactoryLocator @Bean @Scope(value="singleton", proxyMode=ScopedProxyMode.INTERFACES) public ConnectionFactoryLocator connectionFactoryLocator() { ConnectionFactoryRegistry registry = new ConnectionFactoryRegistry(); registry.addConnectionFactory( new TwitterConnectionFactory( environment.getProperty("twitter.consumerKey"), environment.getProperty("twitter.consumerSecret"))); registry.addConnectionFactory( new FacebookConnectionFactory( environment.getProperty("facebook.clientId"), environment.getProperty("facebook.clientSecret"))); return registry; } 39
  • 40. Configuration: ConnectionFactoryLocator @Bean @Scope(value="singleton", proxyMode=ScopedProxyMode.INTERFACES) public ConnectionFactoryLocator connectionFactoryLocator() { ConnectionFactoryRegistry registry = new ConnectionFactoryRegistry(); registry.addConnectionFactory( new TwitterConnectionFactory( environment.getProperty("twitter.consumerKey"), environment.getProperty("twitter.consumerSecret"))); registry.addConnectionFactory( new FacebookConnectionFactory( environment.getProperty("facebook.clientId"), environment.getProperty("facebook.clientSecret"))); return registry; } 39
  • 41. Configuration: ConnectionFactoryLocator @Bean @Scope(value="singleton", proxyMode=ScopedProxyMode.INTERFACES) public ConnectionFactoryLocator connectionFactoryLocator() { ConnectionFactoryRegistry registry = new ConnectionFactoryRegistry(); registry.addConnectionFactory( new TwitterConnectionFactory( environment.getProperty("twitter.consumerKey"), environment.getProperty("twitter.consumerSecret"))); registry.addConnectionFactory( new FacebookConnectionFactory( environment.getProperty("facebook.clientId"), environment.getProperty("facebook.clientSecret"))); return registry; } 39
  • 42. Configuration: ConnectionFactoryLocator @Bean @Scope(value="singleton", proxyMode=ScopedProxyMode.INTERFACES) public ConnectionFactoryLocator connectionFactoryLocator() { ConnectionFactoryRegistry registry = new ConnectionFactoryRegistry(); registry.addConnectionFactory( new TwitterConnectionFactory( environment.getProperty("twitter.consumerKey"), environment.getProperty("twitter.consumerSecret"))); registry.addConnectionFactory( new FacebookConnectionFactory( environment.getProperty("facebook.clientId"), environment.getProperty("facebook.clientSecret"))); return registry; } 39
  • 43. Configuration: Connection Repository @Bean @Scope(value="request", proxyMode=ScopedProxyMode.INTERFACES) public ConnectionRepository connectionRepository() { Authentication authentication = SecurityContextHolder.getContext(). getAuthentication(); if (authentication == null) { throw new IllegalStateException( "Unable to get a ConnectionRepository: no user signed in"); } return usersConnectionRepository().createConnectionRepository( authentication.getName()); } 40
  • 44. Configuration: Connection Repository @Bean @Scope(value="request", proxyMode=ScopedProxyMode.INTERFACES) public ConnectionRepository connectionRepository() { Authentication authentication = SecurityContextHolder.getContext(). getAuthentication(); if (authentication == null) { throw new IllegalStateException( "Unable to get a ConnectionRepository: no user signed in"); } return usersConnectionRepository().createConnectionRepository( authentication.getName()); } @Bean @Scope(value="singleton", proxyMode=ScopedProxyMode.INTERFACES) public UsersConnectionRepository usersConnectionRepository() { return new JdbcUsersConnectionRepository( dataSource, connectionFactoryLocator(), Encryptors.noOpText()); } 40
  • 45. Configuration: ConnectController @Bean public ConnectController connectController() { return new ConnectController(connectionFactoryLocator(), connectionRepository()); } 41
  • 46. Configuration: ConnectController @Bean public ConnectController connectController() { return new ConnectController(connectionFactoryLocator(), connectionRepository()); } 41
  • 47. Configuration: ConnectController @Bean public ConnectController connectController() { return new ConnectController(connectionFactoryLocator(), connectionRepository()); } 41
  • 48. Configuration: API Bindings @Bean @Scope(value="request", proxyMode=ScopedProxyMode.INTERFACES) public Facebook facebook() { Connection<Facebook> facebook = connectionRepository().findPrimaryConnection(Facebook.class); return facebook != null ? facebook.getApi() : new FacebookTemplate(); } @Bean @Scope(value="request", proxyMode=ScopedProxyMode.INTERFACES) public Twitter twitter() { Connection<Twitter> twitter = connectionRepository().findPrimaryConnection(Twitter.class); return twitter != null ? twitter.getApi() : new TwitterTemplate(); } 42
  • 49. Configuration: API Bindings @Bean @Scope(value="request", proxyMode=ScopedProxyMode.INTERFACES) public Facebook facebook() { Connection<Facebook> facebook = connectionRepository().findPrimaryConnection(Facebook.class); return facebook != null ? facebook.getApi() : new FacebookTemplate(); } @Bean @Scope(value="request", proxyMode=ScopedProxyMode.INTERFACES) public Twitter twitter() { Connection<Twitter> twitter = connectionRepository().findPrimaryConnection(Twitter.class); return twitter != null ? twitter.getApi() : new TwitterTemplate(); } 42
  • 50. Configuration: API Bindings @Bean @Scope(value="request", proxyMode=ScopedProxyMode.INTERFACES) public Facebook facebook() { Connection<Facebook> facebook = connectionRepository().findPrimaryConnection(Facebook.class); return facebook != null ? facebook.getApi() : new FacebookTemplate(); } @Bean @Scope(value="request", proxyMode=ScopedProxyMode.INTERFACES) public Twitter twitter() { Connection<Twitter> twitter = connectionRepository().findPrimaryConnection(Twitter.class); return twitter != null ? twitter.getApi() : new TwitterTemplate(); } 42
  • 51. Configuration: API Bindings @Bean @Scope(value="request", proxyMode=ScopedProxyMode.INTERFACES) public Facebook facebook() { Connection<Facebook> facebook = connectionRepository().findPrimaryConnection(Facebook.class); return facebook != null ? facebook.getApi() : new FacebookTemplate(); } @Bean @Scope(value="request", proxyMode=ScopedProxyMode.INTERFACES) public Twitter twitter() { Connection<Twitter> twitter = connectionRepository().findPrimaryConnection(Twitter.class); return twitter != null ? twitter.getApi() : new TwitterTemplate(); } 42
  • 52. Injecting and Using the API Bindings @Controller public class TwitterTimelineController { private final Twitter twitter; @Inject public TwitterTimelineController(Twitter twitter) { this.twitter = twitter; } @RequestMapping(value="/twitter/tweet", method=RequestMethod.POST) public String postTweet(String message) { twitter.timelineOperations().updateStatus(message); return "redirect:/twitter"; } } 43
  • 53. Injecting and Using the API Bindings @Controller public class TwitterTimelineController { private final Twitter twitter; @Inject public TwitterTimelineController(Twitter twitter) { this.twitter = twitter; } @RequestMapping(value="/twitter/tweet", method=RequestMethod.POST) public String postTweet(String message) { twitter.timelineOperations().updateStatus(message); return "redirect:/twitter"; } } 43
  • 54. Injecting and Using the API Bindings @Controller public class TwitterTimelineController { private final Twitter twitter; @Inject public TwitterTimelineController(Twitter twitter) { this.twitter = twitter; } @RequestMapping(value="/twitter/tweet", method=RequestMethod.POST) public String postTweet(String message) { twitter.timelineOperations().updateStatus(message); return "redirect:/twitter"; } } 43
  • 55. ConnectController Endpoints  GET /connect • Displays connection status for all providers  GET /connect/{provider} • Displays connection status for a given provider  POST /connect/{provider} • Initiates the authorization flow, redirecting to the provider  GET /connect/{provider}?oauth_token={token} • Handles an OAuth 1 callback  GET /connect/{provider}?code={authorization code} • Handles an OAuth 2 callback  DELETE /connect/{provider} • Removes all connections for a user to the given provider  DELETE /connect/{provider}/{provider user ID} • Removes a specific connection for the user to the given provider 44
  • 56. ConnectController Flow Your Application ConnectController Service Provider (Twitter, Facebook, etc) 45
  • 57. ConnectController Flow Your Application GET /connect/{provider ID} ConnectController Service Provider (Twitter, Facebook, etc) Display connection status page 45
  • 58. ConnectController Flow Your Application POST /connect/{provider ID} ConnectController Service Provider (Twitter, Facebook, etc) Initiate connection flow 45
  • 59. ConnectController Flow Your Application ConnectController Service Provider (Twitter, Facebook, etc) Fetch request token (OAuth 1.0/1.0a only) 45
  • 60. ConnectController Flow Your Application ConnectController Service Provider (Twitter, Facebook, etc) Redirect browser to provider’s authorization page 45
  • 61. ConnectController Flow Your Application ConnectController Service Provider (Twitter, Facebook, etc) Redirect browser to provider’s authorization page 45
  • 62. ConnectController Flow Your Application ConnectController Service Provider (Twitter, Facebook, etc) Redirect browser to provider’s authorization page 45
  • 63. ConnectController Flow Your Application GET /connect/{provider ID}?oauth_token={token} GET /connect/{provider ID}?code={code} ConnectController Service Provider (Twitter, Facebook, etc) Provider redirects to callback URL 45
  • 64. ConnectController Flow Your Application ConnectController Service Provider (Twitter, Facebook, etc) Exchange request token and/or code for access token 45
  • 65. ConnectController Flow Your Application ConnectController Service Provider (Twitter, Facebook, etc) ConnectController stores connection details in connection repository 45
  • 66. ConnectController Flow Your Application ConnectController Service Provider (Twitter, Facebook, etc) Application can make API calls via API binding 45
  • 67. Connection Status Page View <form action="<c:url value="/connect/twitter" />" method="POST"> <div class="formInfo"> <p> You haven't created any connections with Twitter yet. Click the button to connect with your Twitter account. </p> </div> <p> <button type="submit"> <img src="<c:url value="/resources/social/twitter/connect-with-twitter.png" />"/> </button> </p> </form> 46
  • 68. Provider Sign In  A convenience for users  Enables authentication to an app using their connection as credentials  Implemented with ProviderSignInController  Works consistently with any provider 47
  • 69. Configuration: ProviderSignInController  Performs a similar flow as ConnectController  Compares connections (by user ID)  If there’s a match, the user is signed into the application  Otherwise, the user is sent to signup page • Connection is be established after signup @Bean public ProviderSignInController providerSignInController( RequestCache requestCache) { return new ProviderSignInController(connectionFactoryLocator(), usersConnectionRepository(), new SimpleSignInAdapter(requestCache)); } 48
  • 70. Configuration: ProviderSignInController  Performs a similar flow as ConnectController  Compares connections (by user ID)  If there’s a match, the user is signed into the application  Otherwise, the user is sent to signup page • Connection is be established after signup @Bean public ProviderSignInController providerSignInController( RequestCache requestCache) { return new ProviderSignInController(connectionFactoryLocator(), usersConnectionRepository(), new SimpleSignInAdapter(requestCache)); } 48
  • 71. Configuration: ProviderSignInController  Performs a similar flow as ConnectController  Compares connections (by user ID)  If there’s a match, the user is signed into the application  Otherwise, the user is sent to signup page • Connection is be established after signup @Bean public ProviderSignInController providerSignInController( RequestCache requestCache) { return new ProviderSignInController(connectionFactoryLocator(), usersConnectionRepository(), new SimpleSignInAdapter(requestCache)); } 48
  • 72. Configuration: ProviderSignInController  Performs a similar flow as ConnectController  Compares connections (by user ID)  If there’s a match, the user is signed into the application  Otherwise, the user is sent to signup page • Connection is be established after signup @Bean public ProviderSignInController providerSignInController( RequestCache requestCache) { return new ProviderSignInController(connectionFactoryLocator(), usersConnectionRepository(), new SimpleSignInAdapter(requestCache)); } 48
  • 73. ProviderSignInController Endpoints  POST /signin/{provider} • Initiates the authorization flow, redirecting to the provider  GET /signin/{provider}?oauth_token={token} • Handles an OAuth 1 callback  GET /signin/{provider}?code={authorization code} • Handles an OAuth 2 callback  GET /signin • Handles a callback when no oauth token or code is sent • Likely indicates that the user declined authorization 49
  • 74. Social Security OAuth NOT CONFIDENTIAL -- TELL EVERYONE 50
  • 75. Spring Security OAuth  Extension to Spring Security • originally a community contribution (now officially part of the project)  Features... • endpoint management for OAuth service types • (along with corresponding client management) • token management (persistence, authentication) • integrations for the web, as well as through standard Spring Security  springsource.org/spring-security/oauth 51
  • 76. Setup Spring Security with Spring MVC... <http access-denied-page="/login.jsp" xmlns="http://www.springframework.org/schema/security"> <form-login authentication-failure-url="/login.jsp" default-target-url="/index.jsp" login-page="/login.jsp" login-processing-url="/login.do" /> <logout logout-success-url="/index.jsp" logout-url="/logout.do" /> <anonymous /> <intercept-url pattern="/sparklr/**" access="ROLE_USER" /> <custom-filter ref="oauth2ClientFilter" after="EXCEPTION_TRANSLATION_FILTER" /> </http> 52
  • 77. Then Tell Spring Security About Our OAuth Endpoints <authentication-manager xmlns="http://www.springframework.org/schema/security"> <authentication-provider> <user-service> <user name="marissa" password="wombat" authorities="ROLE_USER" /> <user name="sam" password="kangaroo" authorities="ROLE_USER" /> </user-service> </authentication-provider> </authentication-manager> <oauth:client id="oauth2ClientFilter" redirect-on-error="${redirectOnError:false}" /> <oauth:resource id="sparklr" type="authorization_code" client-id="tonr" client-secret="secret" access-token-uri="${accessTokenUri}" user-authorization-uri="${userAuthorizationUri}" scope="read" /> 53
  • 78. Then get an Instance of a RestTemplate for the client... <bean class="org.springframework.security.oauth2.client.OAuth2RestTemplate"> <constructor-arg ref = “sparklr”/> </bean> 54
  • 79. Questions? Josh Long | josh.long@springsource.com | @starbuxman NOT CONFIDENTIAL -- TELL EVERYONE

Notas do Editor

  1. \n
  2. \n
  3. Hello, thank you or having me. Im pleased to have the opportunity to introduce you today to Spring and the SpringSource Tool Suite \n\nMy anem is Josh Long. I serve as the developer advocate for the Spring framework. I&amp;#x2019;ve used it in earnest and advocated it for many years now. i&amp;#x2019;m an author on 3 books on the technology, as well as a comitter to many of the Spring projects. Additionally, I take community activism very seriously and do my best to participate in the community. Sometimes this means answering question on Twitter, or in the forums, or helping contribute to the InfoQ.com and Artima.com communities\n
  4. \n
  5. \n\n
  6. \n
  7. highlight that yu shouldnt be required to write the muck. highlight that the framework buils on the soulders of giants and benefits from almost a decafe of community feedback\n\nat its heart spring addresses these problems by delivery DI, AOP, ESA \n
  8. these different framerworks let u tackle any problem youre likely to want to solve today \n- we support javee1.4 + 1.5 + 1.6; \n\nsits above target platform \nruns in cloud \n\n
  9. there are lots of frameworks to solve lots of problems\nthey all use the same pojo metaphor\nlets review some ofthem ... \nnaturally, the best part is that you can pick and choose - architecture a la carte! these are just lbiraris you can add to your applications, after all \n
  10. \n
  11. \n
  12. talk about how convenient the messaging support is, then roll back and start looking at how u might do the same thing manually. Explain that many of the pices are already there, and then seguqe into a discussion about the core Spring APIs. Lets imagine we&amp;#x2019;re going to build ourselves a file system poller to notify us of when something&amp;#x2019;s happened on the file system\n\n
  13. talk about how convenient the messaging support is, then roll back and start looking at how u might do the same thing manually. Explain that many of the pices are already there, and then seguqe into a discussion about the core Spring APIs. Lets imagine we&amp;#x2019;re going to build ourselves a file system poller to notify us of when something&amp;#x2019;s happened on the file system\n\n
  14. Familiar to somebody who&amp;#x2019;s used Struts:\n Models (like Struts ActionForms)\n Views (like Struts views: tiles, .jsp(x)s, velocity, PDF, Excel, etc.) \n Controllers (like Struts Actions)\n\n
  15. \n
  16. talk about how convenient the messaging support is, then roll back and start looking at how u might do the same thing manually. Explain that many of the pices are already there, and then seguqe into a discussion about the core Spring APIs. Lets imagine we&amp;#x2019;re going to build ourselves a file system poller to notify us of when something&amp;#x2019;s happened on the file system\n\n
  17. \n
  18. talk about how convenient the messaging support is, then roll back and start looking at how u might do the same thing manually. Explain that many of the pieces are already there, and then seguqe into a discussion about the core Spring APIs. Lets imagine we&amp;#x2019;re going to build ourselves a file system poller to notify us of when something&amp;#x2019;s happened on the file system\n\n
  19. \n
  20. talk about how convenient the messaging support is, then roll back and start looking at how u might do the same thing manually. Explain that many of the pices are already there, and then seguqe into a discussion about the core Spring APIs. Lets imagine we&amp;#x2019;re going to build ourselves a file system poller to notify us of when something&amp;#x2019;s happened on the file system\n\n
  21. \n
  22. \n
  23. \n
  24. talk about how convenient the messaging support is, then roll back and start looking at how u might do the same thing manually. Explain that many of the pices are already there, and then seguqe into a discussion about the core Spring APIs. Lets imagine we&amp;#x2019;re going to build ourselves a file system poller to notify us of when something&amp;#x2019;s happened on the file system\n\n
  25. \n
  26. \n
  27. \n
  28. talk about how convenient the messaging support is, then roll back and start looking at how u might do the same thing manually. Explain that many of the pices are already there, and then seguqe into a discussion about the core Spring APIs. Lets imagine we&amp;#x2019;re going to build ourselves a file system poller to notify us of when something&amp;#x2019;s happened on the file system\n\n
  29. \n
  30. talk about how convenient the messaging support is, then roll back and start looking at how u might do the same thing manually. Explain that many of the pices are already there, and then seguqe into a discussion about the core Spring APIs. Lets imagine we&amp;#x2019;re going to build ourselves a file system poller to notify us of when something&amp;#x2019;s happened on the file system\n\n
  31. \n
  32. talk about how convenient the messaging support is, then roll back and start looking at how u might do the same thing manually. Explain that many of the pices are already there, and then seguqe into a discussion about the core Spring APIs. Lets imagine we&amp;#x2019;re going to build ourselves a file system poller to notify us of when something&amp;#x2019;s happened on the file system\n\n
  33. another example of the fact that often the client side model won&amp;#x2019;t represent the server side model \n\n
  34. \n
  35. talk about how convenient the messaging support is, then roll back and start looking at how u might do the same thing manually. Explain that many of the pices are already there, and then seguqe into a discussion about the core Spring APIs. Lets imagine we&amp;#x2019;re going to build ourselves a file system poller to notify us of when something&amp;#x2019;s happened on the file system\n\n
  36. \n
  37. \n
  38. \n
  39. \n
  40. \n
  41. \n
  42. \n
  43. \n
  44. \n
  45. \n
  46. \n
  47. \n
  48. \n
  49. \n
  50. \n
  51. \n
  52. \n
  53. \n
  54. \n
  55. \n
  56. \n
  57. \n
  58. \n
  59. \n
  60. \n
  61. \n
  62. \n
  63. \n
  64. \n
  65. \n
  66. \n
  67. \n
  68. \n
  69. \n
  70. \n
  71. \n
  72. \n
  73. \n
  74. \n
  75. \n
  76. \n
  77. \n
  78. \n
  79. \n
  80. \n
  81. \n
  82. \n
  83. \n
  84. \n
  85. \n
  86. \n
  87. \n
  88. \n
  89. \n
  90. \n
  91. \n
  92. \n
  93. \n
  94. \n
  95. \n
  96. \n
  97. \n
  98. \n
  99. \n
  100. \n
  101. \n
  102. \n
  103. \n
  104. \n
  105. \n
  106. \n
  107. \n
  108. \n
  109. \n
  110. \n
  111. \n
  112. \n
  113. \n
  114. \n
  115. \n
  116. \n
  117. \n
  118. \n