Posted on by & filed under Content - Highlights and Reviews, Programming & Development.

A guest post by Josh Long, the lead author on Apress’ Spring Recipes, 2nd Edition, O’Reilly’s Spring Roo, and a SpringSource open-source project committer and contributor. You can reach him on his personal blog, the SpringSource Blog and on Twitter (@starbuxman).

Hi! I’ve just released a new video series introducing the Spring framework for Pearson’s Livelessons series. The video series runs the gamut of Spring’s various technnologies and introduces – among other things – container basics, web application development, (big-) data processing, messaging and integration, mobile- and cloud-computing with Spring.

In the last two posts, we looked at how to build REST services using Spring’s rich REST support and then looked at how to secure our services with Spring Security. In this example, we’ll look at the Java client-side with Spring core’s RestTemplate, Spring Social, and Spring for Android.

Spring’s REST Client, the RestTemplate

The RestTemplate – in core Spring – is the pillar of Spring’s REST story on the client. The RestTemplate reduces common HTTP operations to one liners like JdbcTemplate does JDBC operations. The RestTemplate features the ability to plugin HTTP message conversion using the same HttpMessageConverter hierarchy available on the service-side for REST content negotiation. The RestTemplate also supports an interceptor model for processing all requests. This makes it easy to handle things like security in an single place.

Easy OAuth Clients with Spring Social

The RestTemplate is powerful, and makes a great foundation for any REST client, but it’s too low-level for something like consuming OAuth service. Implementing OAuth does introduce some complexity that straight REST calls don’t have. This complexity can’t be avoided either. After all, between OAuth 1.0, 1.0.a, and 2.0, and the various inconsistencies among their implementations (OAuth 2.0 isn’t even really a specification – it’s more like a framework!), building an OAuth client can be quite challenging. There are enough popular service providers out there with APIs exposed using OAuth that simply ignoring OAuth isn’t an option either! Spring Social fills the gap.

Spring Social is an extension of the Spring Framework that allows you to connect your applications with Software-as-a-Service (SaaS) providers, like Facebook and Twitter. As part of that charge, it makes it dead simple to build OAuth clients by building on top of the RestTemplate to support transparent, secured REST calls, and manage HTTP callbacks.

This core support for OAuth authorization and authentication underpins a rich catalog of API bindings for popular service-providers like Twitter, Facebook, LinkedIn, and more. You should take a quick look at all the repositories on the SpringSource GitHub repository to see the API bindings that SpringSource maintains directly. I, however, think the (very incomplete) list of some of the third party API bindings is a far more interesting list!

Writing a Spring Social CRM Client

Spring Social is probably most often going to be used inside of a web container. We’re going to build our Spring Social CRM client to be used in an Android client, outside of a web container. OAuth works best when the client to the service provider is itself a web application that can receive callbacks. Spring Social, when used inside of a Spring MVC web application, is almost trivial to setup. That scenario is very well documented elsewhere, and what we really need is a client that can run in Android, so we’ll cover that instead.

All Spring Social clients share basically the same arrangement as the one we’ll implement here. Once you understand how to exercise one, then – while accounting for some small variations between OAuth versions – you’ll use the API in roughly the same way thanks to Spring Social’s abstractions.

The CrmOperations interface

A Spring Social binding centers around an API interface and an implementation. The interface for the CRM is, unsurprisingly, CrmOperations, and the implementation CrmTemplate. This follows a Spring-project convention: JdbcOperations and JdbcTemplate, JmsOperations and JmsTemplate, FacebookOperations and FacebookTemplate, etc. Our client interface is shown here:

For our API binding to do any work, it needs to establish a Spring Social connection to the service provider. The connection may only be obtained after the token provider (our REST service from the oauth module) has given the client an accessToken. Spring Social handles all of the work involved in obtaining the valid accessToken and connection, so let’s focus on writing our REST client using the RestTemplate.

We won’t rehash the entire implementation. For that, it might be easier to simply look at the source code online. Instead, let’s look at some of the salient excerpts and the things common to all of them.

Some of the code for our implementation – CrmTemplate – is shown below. Note that we’re using a client side mirror API of types from the service implementation, not sharing. This is important because our service-side API might depend on classes that we don’t want polluting all users of our client library. In particular, this situation is particularly troublesome in Android where only a subset of the JDK classes are available (whitelisted).

The CrmTemplate implements our client API and is where we provide an HTTP client to the REST API:

There’s a lot in this code listing. The client extends Spring Social’s AbstractOAuth2ApiBinding and gets a sweet restTemplate instance pre-configured to send the OAuth access token on each request (transparently) in the deal. One less thing for us to do! The createCustomer method demonstrates fairly typical use of the RestTemplate. To keep things simple, the class just sends Map<String,Object> instances to the service endpoint. These map-payloads get translated into acceptable JSON input by the RestTemplate, which then sends them to the service.

The currentUser() method calls the REST endpoint /user, which is the one new REST endpoint that we added when we installed Spring Security. It simply returns the user that is currently authenticated. This service call will be useful later, when writing the Spring Social binding code.

Working with Binary Data

The implementation of the setUserProfilePhoto(byte[] bytesOfImage, final MediaType mediaType) method is interesting because it demonstrates how easy it is to do multipart file uploads. The getUserProfilePhoto() method does the opposite — it reads the profile photo. Here again, the RestTemplate makes short work of reading the bytes, the MediaType, and returning that back to the client.

Teaching Spring Social about our Client

We need to write a few classes to teach Spring Social about the API we’re writing a client for. We need to introduce Spring Social to our API Binding through the ingenious use of three interfaces: ConnectionFactory<CrmOperations>, ServiceProvider<CrmOperations>, and ApiAdapter<CrmOperations>.

Let’s start with the ConnectionFactory<CrmOperations> implementation:

The ServiceProvider implementation — CrmServiceProvider — is where the rubber meets the road: given an accessToken, this object needs to be able to hand back a concrete implementation of the service provider API interface (in our case, CrmTemplate is a concrete implementation of CrmOperations).

The getApi method is the critical part. It’s where the rubber meets the road and you get back a live API implementation:

The ApiAdapter<CrmOperations> implementation — CrmApiAdapter — asks questions that most service providers can answer. Spring Social doesn’t try to provide an all-singing, all-dancing unified API for all service-providers (far from it!), but there is some overlap in terms of what operations most service-provider APIs can handle, including returning whether the connection itself is valid, returning the currently signed-in user’s profile, and updating the service-provider’s concept of a status, if it exists. On Facebook, for example, the updateStatus method would translate to posting something to the user’s wall and on Twitter this would translate to tweeting.

The ApiAdapter implementation can answer commands like: “is the connection live?,” “what’s the current user’s general profile information?,” and “update my status!”

All Together Now…

We now have everything we need to use our Spring Social binding in any application, whether it is a web application, a unit test, or an Android application. The code below demonstrates the interaction with the API in a regular application. We won’t reprint the entire configuration class to run Spring Social standalone, but feel free to checkout the source code.

The program launches the system browser to the authorization URI (assumed to be running on localhost at port 8080). You must then authenticate and confirm the permission prompts. You’ll ultimately be sent back to the /crm/welcome.html page with an access_token in the URI. Extract that, and then paste it into the Swing input dialog that’ll be running.

The following code demonstrates the entire interaction with the API including the initial connection:

Connected Android Applications with Spring Android

The Android classloader can be a pain in the neck because it whitelists a subset of a full JDK. Spring Android does not attempt to port all of Spring to Android. It doesn’t even attempt to port the container. Spring Android focuses on enabling delivering value for Android clients and – specifically for our application – Spring Android provides a port of the RestTemplate available in the core Spring framework.

Dodging Android Loader Issues

The Spring RestTemplate delegates conversion between a content type and well-known object types to the HttpMessageConverter hierarchy. The implementation that handles XML to object marshalling on Java SE delegates to JAXB. JAXB’s a safe choice with Java SE, but on Android it causes the application to be rejected because it uses classes that are not available there and thus can’t be loaded. Spring Android still supports XML REST request marshalling, but does so by delegating to a Simple XML-powered SimpleXmlHttpMessageConverter instead.

We’re using the Spring Android core types, but want to bring in our Spring Social binding, and that in turn depends on a few libraries from standard Spring. I’ve done a fair amount of work to exclude as much as possible so that I only have my dependencies and hard runtime dependencies on my CLASSPATH. Check out the android module’s pom.xml build file for details.

Dagger, a Dependency Injection Framework for Android

Spring Android does not provide a dependency injection solution on Android because – at the moment – there’s no really elegant way to do so and the jury’s still out on whether anything less is worth the effort. There are dependency injection solutions for Android. Some options support JSR 330-compliant dependency injection, including RoboGuice and Square’s Dagger.

Most dependency injection frameworks suffer from the same basic problem: Android manages the lifecycle of interesting components itself, and affords a framework no opportunity to provide instances that the framework manages instead. By the time you have a reference to one of them, they’re already constructed and alive. Dependency injection has to be done retroactively for these types of objects. For other, non-Android objects, the Dagger dependency injection container works as you’d expect given experience with JSR 330 and Spring’s Java configuration API. Our Android application, in the android Maven module, uses Dagger, Spring Social and Spring Android to drive a CRM Android client. We’ll focus specifically on the authorization screen here.

Dagger’s pretty good. It feels natural if you’re familiar with Spring Java configuration and JSR 330. Some of the integration code that you end up having to write is pretty ugly, but arguably better than the alternative. Integrating Dagger is pretty uninteresting, so I’ll instead defer you to the BaseActivity class, which integrates Dagger, and to our Android Application subclass, Crm, where Dagger is initialized.

Let’s look at our Dagger CrmModule configuration class below. This is most similar to a Spring Java configuration class. We use it to wire up the beans required to work with Spring Social. Once Spring Social’s up and running, we’ll drive an OAuth flow inside of an Android Activity subclass (AuthenticationActivity).

The @Module annotation marks this class as a class to be consulted for bean definitions, just as @Configuration does with Spring. Because of the performance constraints, scanning packages for beans is cumbersome on Android, and best avoided. Dagger uses an injects attribute on its modules to declare which classes beans might be injected into. The @Provides annotation tells Dagger that the method annotated provides bean definitions, just like @Bean in Spring. Unfortunately, in Dagger, things are not singleton by default, so we have to explicitly mark every singleton with the @Singleton annotation.

Driving OAuth Authentication from within an Android Activity

With these pieces in place, we can write Activity subclasses that leverage beans we’ve configured in Dagger to support our OAuth flow.

Having an HTTP conversation using Spring Social’s OAuth support is slightly more difficult when one party can’t hear. Our client runs on a mobile device and exports no HTTP endpoints, so it’s something of a one-sided conversation as far as OAuth is concerned. We’ll drive the HTTP flow from inside of a WebView subclass that handles the OAuth dance for us, based on URIs that we build up using Spring Social. We can’t really receive redirect requests, but we can detect them as an event in the WebView subclass. The following code shows the entire Android authorization screen, AuthenticationActivity:

This code is not easy to follow, at first blush, because there’s so much code related to running certain parts of the program on Android’s main thread, vs. Android’s UI thread. The program flow tends to get lost in the callback soup. The basic flow is as follows:

  • When the Activity starts, it installs a custom WebView subclass widget that handles the OAuth-dance for us. The Activity checks to see if there are already any Spring Social connections established in the local SQLite-powered ConnectionRepository implementation.
  • If there are existing connections, then it simply re-instantiates the connection. If there are no existing connections, it triggers the WebView subclass to begin the OAuth flow.
  • In either case, flow eventually lands at the connectionEstablished() method, where we launch a new Activity that may do what it pleases with the Dagger-injected CrmOperations crmOperations field, which will be created per-request, and thus always reflect the latest connection.

The following Figure shows the Android signin screen, delegating directly to the view rendered from the web application:


Once signed in, the user must approve the requested permissions, as shown in this Figure:


The whole thing culminates in connectionEstablished(), which launches another Activity where we may inject a reference to our CrmOperations instance, secure in the knowledge that our connection is already setup and working.


In this three part series, we’ve introduced Spring’s powerful support for building REST services, employing Spring HATEOAS to elevate make our APIs easier for clients to use. We used Spring Data REST to remove the boilerplate, and we used Spring’s REST Shell to easily interact with our service. Finally, we introduced security for both human and automatic clients using Spring Security and Spring Security OAuth, respectively. We built out a client using Spring Social that makes short work of consuming our OAuth-secured REST services. Then, thanks to the magic of Spring Android, we reused all that functionality in an Android application.

Be sure to look at the Spring resources below that you can find in Safari Books Online.

Not a subscriber? Sign up for a free trial.

Safari Books Online has the content you need

Spring Framework LiveLessons (Video Training) provides a walking tour of all of the Spring projects, including: Spring, Spring MVC, Spring Data, Spring Batch, Spring Integration, Spring Security, Spring Social, and more. Josh introduces how to get started building modern day Spring applications while introducing the concepts behind them. In the lessons, Josh guides viewers through a look at the Spring stack and the features designed to support relational data access, NoSQL and big-data access, batch processing, integration and messaging, REST services, mobile clients, OAuth-secured, connected web applications, service provider APIs, and more!
Spring Recipes
continues upon the bestselling success of the previous edition but focuses on the latest Spring 3 features for building enterprise Java applications. This book provides elementary to advanced code recipes to account for the following, found in the new Spring 3.
Spring in Action, Third Edition is totally revised for Spring 3.0, and covers the latest features, tools, and practices including Spring MVC, REST, Security, Web Flow, and more. Following short code snippets and an ongoing example developed throughout the book, you’ll learn how to build simple and efficient J2EE applications.

About the author

joshlongprofile Josh Long is the Spring developer advocate at SpringSource, by Pivotal. Josh is the lead author on Apress’ Spring Recipes, 2nd Edition, O’Reilly’s Spring Roo, and a SpringSource open-source project committer and contributor. When he’s not hacking on code, he can be found at the local Java User Group or at the local coffee shop. Josh likes solutions that push the boundaries of the technologies that enable them. Continue the discussion on his personal blog, the SpringSource Blog and on Twitter (@starbuxman).

Tags: android, Josh Long, livelessons, REST, RestTemplate, Smart Client, spring, Spring for Android, Spring Social,

Comments are closed.