Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP

Spring Social Google Reference Manual

GabiAxel edited this page · 7 revisions
Clone this wiki locally

Spring Social Google Reference Manual

1. Spring Social Google Introduction

1.1 Introduction

The Spring Social Google project is an extension to the http://www.springframework.org/spring-social project that enables introduction with Google APIs.

Spring Social Google enables integration with Google APIs with GoogleConnectionFactory, a connection factory that can be plugged into Spring Social’s service provider connection framework, and with an API binding to Google APIs.

1.2 How to get

The following Maven dependency will add Spring Social Google to your project:

<repository>
    <id>spring.social.google</id>
    <name>Spring Social Google</name>
    <url>https://github.com/GabiAxel/maven/raw/master/</url>
</repository>

...

<dependency>
   <groupId>org.springframework.social</groupId>
   <artifactId>spring-social-google</artifactId>
   <version>1.0.0.M2</version>
</dependency>

Note that Spring Social Google may release on a different schedule than Spring Social. Consequently, Spring Social’s version may differ from that of Spring Social Google.

Consult Spring Social’s reference documentation for more information on Spring Social dependencies.

2. Configuring Google Connectivity

Spring Social’s ConnectController works with one or more provider-specific ConnectionFactorys to exchange authorization details with the provider and to create connections. Spring Social Google provides GoogleConnectionFactory, a ConnectionFactory for creating connections with Google APIs.

So that ConnectController can find GoogleConnectionFactory, it must be registered with a ConnectionFactoryRegistry. The following class constructs a ConnectionFactoryRegistry containing a ConnectionFactory for Google using Spring’s Java configuration style:

@Configuration
public class SocialConfig {

    @Bean
    public ConnectionFactoryLocator connectionFactoryLocator() {
        ConnectionFactoryRegistry registry = new ConnectionFactoryRegistry();
        registry.addConnectionFactory(new GoogleConnectionFactory(
            environment.getProperty("google.clientId"),
            environment.getProperty("google.clientSecret")));
        return registry;
    }

}

Here, a Google connection factory is registered with ConnectionFactoryRegistry via the addConnectionFactory() method. If we wanted to add support for connecting to other providers, we would simply register their connection factories here in the same way as GoogleConnectionFactory.

Because client IDs and secrets may be different across environments (e.g., test, production, etc) it is recommended that these values be externalized. As shown here, Spring 3.1’s Environment is used to look up the application’s client ID and secret.

Optionally, you may also configure ConnectionFactoryRegistry and GoogleConnectionFactory in XML:

<bean id="connectionFactoryLocator" class="org.springframework.social.connect.support.ConnectionFactoryRegistry">
    <property name="connectionFactories">
        <list>
            <bean class="org.springframework.social.google.connect.GoogleConnectionFactory">
                <constructor-arg value="${google.clientId}" />
                <constructor-arg value="${google.clientSecret}" />				
            </bean>
        </list>
    </property>
</bean>

This is functionally equivalent to the Java-based configuration of ConnectionFactoryRegistry shown before. The only casual difference is that the connection factories are injected as a list into the connectionFactories property rather than with the addConnectionFactory() method. As in the Java-based configuration, the application’s client ID and secret are externalized (shown here as property placeholders).

Refer to http://static.springsource.org/spring-social/docs/1.0.x/reference/html/connecting.html for complete details on configuring ConnectController and its dependencies.

3. Google API Binding

Spring Social Googles’s Google interface and its implementation, GoogleTemplate provide the operations needed to interact with Google APIs on behalf of a user. Creating an instance of GoogleTemplate is as simple as constructing it by passing in an authorized access token to the constructor:

String accessToken = "f8FX29g..."; // access token received from Google after OAuth authorization
Google google = new GoogleTemplate(accessToken);
In addition, GoogleTemplate has a default constructor that creates an instance without any OAuth credentials:
Google google = new GoogleTemplate();
When constructed with the default constructor, GoogleTemplate will allow a few simple operations that do not require authorization, such as retrieving a specific Google+ profile. Attempting other operations, such as retrieving Google+ profile for “me” will fail with an MissingAuthorizationException being thrown.

If you are using Spring Social’s service provider framework, you can get an instance of Google from a Connection. For example, the following snippet calls getApi() on a connection to retrieve a Google:

Connection<Google> connection = connectionRepository.findPrimaryConnection(Google.class);
Google google = connection != null ? connection.getApi() : new GoogleTemplate();
Here, ConnectionRepository is being asked for the primary connection that the current user has with Google. If a connection to Google is found, a call to getApi() retrieves a Google instance that is configured with the connection details received when the connection was first established. If there is no connection, a default instance of GoogleTemplate is created.

With a Google in hand, there are several ways you can use it to interact with Google APIs on behalf of the user. Spring Social’s Google API binding is divided into 7 sub-APIs exposed through the methods of Google, plus a method for integrating with GData Java libraries, and an accessor method that returns the access token, allowing it to be used with Google APIs Client Library for Java :

public interface Google extends ApiBinding {

    LegacyProfileOperations userOperations();

    PersonOperations personOperations();

    ActivityOperations activityOperations();

    CommentOperations commentOperations();

    TaskOperations taskOperations();

    DriveOperations driveOperations();

    void applyAuthentication(Object client);

    String getAccessToken();
}
The sub-API interfaces returned from Google’s methods are described in the following table:
Sub-API Interface Description Google API Documentation
LegacyProfileOperations Retrieval of logged in profile
PersonOperations Retrieval or people from Google+ and Portable Contacts Google+ People , Portable Contacts
ActivityOperations Retrieval of Google+ activities Google+ Activities
CommentOperations Retrieval of Google+ comments Google+ Comments
TaskOperations Task management Google Tasks

DriveOperations | Google Drive integration | Google Drive

There are several services which are accessible via [[http://code.google.com/apis/gdata/docs/directory.html][GData APIs]. As a strategic decision, Spring Social Google integrates only with the new JSON-based APIs, and not the old XML-based GData APIs. However it does provide a way to integrate with the GData Java library, letting you use Spring Social Google for the initial authentication and authorization, and then use the OAuth2 access token with GData Java library by calling the applyAuthentication() method with an instance of Service :

AnalyticsService service = new AnalyticsService("MyApplication_1.0");
Google google = getGoogle(); // after authentication
google.applyAuthentication(service);

Not all of the new JSON-based APIs have corresponding Spring Social bindings. However, Google generates its own Java client libraries which can be used alongside Spring Social Google. After authenticating with Spring Social Google, you can use the access token with the generated Java client libraries:

Credential credential = new GoogleCredential();
Google google = newGoogle(); // after authentication
credential.setAccessToken(google.getAccessToken());
Plus plus = new Plus(new NetHttpTransport(), new JacksonFactory(), credential);

The following sections will give an overview of common tasks that can be performed via Google and its sub-APIs. For complete details on all of the operations available, refer to the JavaDoc.

3.1 Retrieving a user’s profile data

You can get the user’s basic details using LegacyProfileOperations:

LegacyGoogleProfile profile = google.getUserOperations().getUserProfile();
String name = profile.getName();
String email = profile.getEmail();
This operation requires OAuth scope https://www.googleapis.com/auth/userinfo.profile , and in order to fetch the e-mail it also requires the scope https://www.googleapis.com/auth/userinfo#email (otherwise email property will be null).

To Retrieve the Google+ profile, use PersonOperations:

Person person = google.personOperations().getGoogleProfile();
String displayName = person.getDisplayName();
This operations require OAuth scope https://www.googleapis.com/auth/plus.me

3.2 Retrieving other people’s profiles

To search for Google+ profiles by name, use PersonOperations:

PeoplePage page = google.personOperations().searchPeople("John Smith", null);
List<People> people = page.getItems();
boolean hasMore = page.getNextPageToken() != null;
If nextPageToken property is not null, you can use it to retrieve the next page of results by setting it as the second parameter of searchPeople.

If you want to customize the page size, you can use PersonQueryBuilder:

PeoplePage page = google.personOperations().personQuery()
    .searchFor("John Smith")
    .maxResultNumber(10)
    .getPage();

3.3 Managing Task Lists and Tasks

To work with task lists and tasks you need the OAuth scope depending on whether you want read-only access or read and write access: https://www.googleapis.com/auth/tasks.readonly or https://www.googleapis.com/auth/tasks

To fetch your task list and tasks use TaskOperations:

TaskListsPage taskListsPage = google.taskOperations().getTaskLists();
for(TaskList taskList : taskListsPage.getItems()) {
    TasksPage tasksPage = google.taskOperations().taskQuery()
        .fromTaskList(taskList.getId)
        .getPage();
}

If you used the read and write scope, you can also create task lists and tasks:

TaskList taskList = new TaskList("My Task List");
taskList = google.taskOperations.saveTaskList(taskList); // the returned instance has a populated id property
Task task = new Task("Do something", "Do it properly", null, null);
google.taskOperations.createTaskAt(taskList.getId(), null, null, task);
Something went wrong with that request. Please try again.