3. Google APIs Binding

Spring Social Google's Google interface and its implementation, GoogleTemplate provide the operations needed to interact with Google 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 OAuth2 authorization
Google google = new GoogleTemplate(accessToken);
	

In addition, GoogleTemplate has a default constructor that creates an instance without any OAuth2 credentials:

Google google = new GoogleTemplate();
	

When constructed with the default constructor, GoogleTemplate will allow a few Google+ operations that do not require authorization, such as retrieving a specific Google+ user's profile. Attempting other operations, such as creating an app activity 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 on behalf of the user. Spring Social's Google API binding is divided into 4 sub-APIs exposes through the methods of Google , and a method that lets you fetch the access token to easily integrate with other Java libraries for Google APIs that have no Spring Social binding yet:

public interface Google {

    PlusOperations plusOperations();

    TaskOperations taskOperations();

    DriveOperations driveOperations();
    
    String getAccessToken();

}
	

The sub-API interfaces returned from Google 's methods are described in Table 3.1, “Google's Sub-APIs” .

Table 3.1. Google's Sub-APIs

Sub-API InterfaceDescription
PlusOperationsRead Google+ activities and people profiles and create app activities.
TaskOperationsRead and manage the user's tasks.
DriveOperationsRead and manage the user's files in Google Drive.

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 Reading Google+ Profiles

If you know a user's Google profile ID, you can get their public profile by calling getPerson():

Person person =	google.plusOperations().getPerson("123456789...");
		

This operation works without authentication, as it is used to access public profiles. After authentication, it is possible to use "me" instead of a profile ID as argument to the method, or equivalently use the getGoogleProfile() method to get the authenticated user's profile.

To search for public profiles, call the searchPeople() method:

PeoplePage people = google.plusOperations().searchPeople("John Smith", null);
		

Or you can get a list of people in the user's circles by calling getPeopleInCircles() :

PeoplePage people = google.plusOperations().getPeopleInCircles("me", null);
		

3.2 Reading Google+ Activities

To get a user's visible activities, call PlusOperations ' getActivities() method with the user ID as first argument, or "me" for the authenticated user:

ActivitiesPage activities = google.plusOperations().getActivities("123456789...");
		

You can search all public activities without authenticating by calling the searchPublicActivities() methos:

ActivitiesPage activities = google.plusOperations().searchPublicActivities("Spring", null);
		

3.3 Managing app activities

Google+ App activities, or moments, appear in the profile page, and are associated with the application that was used to create them. Moment is an abstract superclass of the specific types of app activities. To post a new app activity, call insertMoment() with a specific moment implementation:

Moment moment = google.plusOperations().insertMoment(new AddActivity("http://target-url..."));
		

You can list the moments created by your application by calling getMoments():

MomentsPage moments = google.plusOperations().getMoments(null);
		

To delete a moment, call deleteMoment() with the ID which you can fetch from the moment instance:

google.plusOperations().deleteMoment("mf4l2j3ws...");
		

3.4 Managing Tasks

Depending on the OAuth2 scope, you can access the Google Tasks API either with full access or with read-only access. Tasks are organizad in task lists, and the default task list's ID is "@default". To retrieve the user's task lists, call the getTaskLists() method:

TaskListsPage taskLists = google.taskOperations().getTaskLists();
		

Create a new task list or update an existing one by calling saveTaskList():

TaskList taskList = google.taskOperations().saveTaskList(new TaskList("Todo"));
		

To retrieve the tasks, call getTasks():

TasksPage tasks = google.taskOperations().getTasks();
		

Create or update a task by calling saveTask():

Task task = google.taskOperations().saveTask(new Task("Do or do not", "There is no try", new Date()));
		

If you want to hide all completed tasks in a task list, call clearCompletedTasks():

TaskList taskList = ... // get or create the task list instance
google.taskOperations().clearCompletedTasks(taskList);
		

3.5 Managing files in Google Drive

Google Drive API can be used to upload, manage and download files. Applications can be granted read/write or read-only access to the entire content of the user's Google Drive account, to file metadata, or just to files created by the application.

To list the visible files and folders in a folder, call getFiles() with the folder ID, or "root" to get top-level files and folders:

DriveFilesPage files = google.driveOperations().getFiles("root", null);
		

Create a folder by calling createFolder() with the folder ID in which to create the new folder and a name:

DriveFile folder = google.driveOperations().createFolder("root", "New Folder");
		

Uploading files is implemented using Spring's resource abstraction. When you upload a file, you also define its metadata (name, description, etc') and upload parameters (whether to convert office files, whether to run OCR, etc'). To upload a file call the upload() method:

Resource resource = new FileSystemResource("/path/to/file");  // any Resource implementation can be used
DriveFile metadata = DriveFile.builder()  // use this builder to set metadata
                         .setTitle("My File")
                         .build();
UploadParameters parameters = new UploadParameters();  // call setters to modify upload parameters
DriveFile file = google.driveOperations().upload(resource, metadata, parameters);
		

Downloading files also uses the resource abstraction. Call the downloadFile() Method with either the file ID or the file metadata instance to get a Resource for the file:

Resource resource = google.driveOperations().downloadFile("NX01...");