Click here to Skip to main content
Click here to Skip to main content
Go to top

Obtaining the Customer ID in Google Apps Admin Audit API

, 24 Jun 2012
Rate this:
Please Sign up or sign in to vote.
Programming with Google Apps Admin Audit API

Introduction 

This is the code from our original article illustrating how to perform 3-legged OAuth authentication in order to perform the customerID operation in Google Apps Admin Audit API. The customerId is necessary for subsequent API calls. In addition, the code parses the JSON output received by API in order to isolate the customerId value. 

Using the code

You need to download the google-api-java-client libraries in order to use this code. 

/*
 * Copyright (c) 2012 Linkgard International, Inc.
 * 
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not 
 * use this file except in compliance with the License. You may obtain a copy 
 * of the License at
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software 
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 
 * License for the specific language governing permissions and limitations 
 * under the License.
 */

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.List;

import com.google.api.client.auth.oauth2.Credential;
import com.google.api.client.googleapis.auth.oauth2.GoogleAuthorizationCodeFlow;
import com.google.api.client.googleapis.auth.oauth2.GoogleAuthorizationCodeFlow.Builder;
import com.google.api.client.googleapis.auth.oauth2.GoogleTokenResponse;
import com.google.api.client.http.GenericUrl;
import com.google.api.client.http.HttpRequest;
import com.google.api.client.http.HttpRequestFactory;
import com.google.api.client.http.HttpResponse;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.jackson.JacksonFactory;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

public class CustomerIdSample {

    // URL for the CustomerID operation. We prefer JSON output.. you can strip
    // the "?alt=json" for RSS
    private static String customerIdOperationUrl = 
      "https://apps-apis.google.com/a/feeds/customer/2.0/customerId?alt=json";

    // Scope for the customerID operation.
    private static String customerIdOperationScope = 
       "https://apps-apis.google.com/a/feeds/policies/";

    // API Client Console -- YOU MUST PROVIDE CORRECT VALUES.
    // Make sure you create a project and specify "installed applications" or
    // you will not see a "client secret"
    private static String clientID = "FIXME";
    private static String clientSecret = "FIXME";
    // Verify this in the console.
    private static String redirectUri = "urn:ietf:wg:oauth:2.0:oob"; 

    // We defined some template JSON classes so that we can parse the output of
    // the operation.
    final class CustomerIdResponse { String version; String encoding; Entry entry; }
    final class Entry { String xmlns; String xmlns$apps; Id id; 
          Updated updated; Link[] link; AppsProperty[] apps$property; }
    final class Id { String $t; }
    final class Updated { String $t; }
    final class Link { String rel; String type; String href; }
    final class AppsProperty { String name; String value; }

    // END JSON template classes.

    public static void main(String[] args) {
        try {
            try {
                // Build a list of scopes that your application needs.
                List<string> scopeList = Arrays
                        .asList(customerIdOperationScope);

                // authorization
                Credential credential = buildCredential(clientID, clientSecret,
                        redirectUri, scopeList);

                final HttpTransport HTTPTRANSPORT = new NetHttpTransport();

                // Get a request factory
                HttpRequestFactory rf = HTTPTRANSPORT
                        .createRequestFactory(credential);

                HttpRequest request = rf.buildGetRequest(new GenericUrl(
                        customerIdOperationUrl));
                HttpResponse response = request.execute();

                // InputStream is = response.getContent();

                BufferedReader reader = new BufferedReader(
                        new InputStreamReader(response.getContent(), "UTF-8"));
                StringBuilder builder = new StringBuilder();

                for (String line = null; (line = reader.readLine()) != null;) {
                    builder.append(line).append("\n");
                }

                System.out.println(parseCustomerId(builder.toString()));
                return;
            } catch (IOException e) {
                System.err.println(e.getMessage());
            }
        } catch (Throwable t) {
            t.printStackTrace();
        }
        System.exit(1);
    }

    private static String parseCustomerId(String json) {
        GsonBuilder builder = new GsonBuilder();
        Gson gson = builder.create();
        CustomerIdResponse customerIdResponse = gson.fromJson(json,
                CustomerIdResponse.class);
        // Navigate through the JSON structure to get to the right value.
        return customerIdResponse.entry.apps$property[1].value;
    }

    private static Credential buildCredential(String client_id,
            String client_secret, String redirect_url, Iterable<string> scopes) {

        String code;
        GoogleTokenResponse tokenResponse;
        Credential cred = null;

        JsonFactory jsonFactory = new JacksonFactory();
        HttpTransport httpTransport = new NetHttpTransport();

        // Create the authentication flow builder.
        Builder flowBuilder = new GoogleAuthorizationCodeFlow.Builder(
                httpTransport, jsonFactory, client_id, client_secret, scopes);

        // Build the flow.
        GoogleAuthorizationCodeFlow flow = flowBuilder.setAccessType("online")
                .setApprovalPrompt("auto").build();

        // Obtain the authorization URL
        String url = flow.newAuthorizationUrl().setRedirectUri(redirectUri)
                .build();

        // Normally, for installed programs, you may decide to launch your own
        // local web server and redirect Google's response in order to avoid
        // the manual process below.
        System.out.println("AUTHORIZATION URL: " + url);

        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        System.out
                .println("Open the URL above and paste the code (Access Token) here.");

        // Obtain token response, generate token, and save.
        try {
            code = br.readLine();
            tokenResponse = flow.newTokenRequest(code)
                    .setRedirectUri(redirect_url).execute();
            cred = flow.createAndStoreCredential(tokenResponse, null);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        return cred;
    }
}

History

  • 06/24/2012 - Initial submission. 

License

This article, along with any associated source code and files, is licensed under The Apache License, Version 2.0

Share

About the Author

Hovanes Manucharyan
CEO Linkgard Systems
United States United States
Follow me on twitter: http://twitter.com/linkgard

Comments and Discussions

 
-- There are no messages in this forum --
| Advertise | Privacy | Mobile
Web04 | 2.8.140926.1 | Last Updated 24 Jun 2012
Article Copyright 2012 by Hovanes Manucharyan
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid