Home > Cloud Computing, Software Development > Google Cloud Platform: Hello World with OAuth 2

Google Cloud Platform: Hello World with OAuth 2

March 16th, 2016 Leave a comment Go to comments

Google Cloud is the 3rd public cloud I tried after Amazon AWS and Microsoft Azure. I used its AppEngine before and it worked pretty well. Google started very early in the cloud game but it lost the opportunity to Amazon because it over-estimated the attractiveness of its own infrastructure that runs Google search.

There is little doubt about Google’s technology, but the real issue is that no customers would like to be locked by Google. Both technically and business wise, no company can easily, if possible, replicate the same state-of-art infrastructure as Google did. If you use Google App Engine for production, you’re pretty much locked forever.

Time to learn how to "Google" and manage your VMware and clouds in a fast and secure

HTML5 App

Anyway, Google finally realized the problem and started to invest on the compute engine. Although there are probably a few things Google can do better than others, but the prime windows of opportunity is gone. Marketing wise, Google is still over confident on its starving strategies that made gmail successful. To attract enterprise users, Microsoft and Amazon seem to know better how to recruit new users in addition to good products.

Google recently hired former VMware CEO Diane Greene who knows enterprises very well to head its cloud initiatives. I still see the hope there for Google to be an important player in public cloud services.

I started to play with the Google cloud platform last week, still in the same virtual machine or IaaS level of services. Google’s GUI is pretty clean and easy to use once you into the management console. That is the always the first place to start with.

As always my real interest is the management APIs. Google has its REST APIs and open sourced at GitHub. Here is a sample for getting started with Google cloud compute engine.

As a first Hello World like sample, it may be a bit too complicated. Therefore, I created a simpler one so that you can get started right away.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
package org.doublecloud.googleclouddemo;
 
import com.google.api.client.auth.oauth2.Credential;
import com.google.api.client.extensions.java6.auth.oauth2.AuthorizationCodeInstalledApp;
import com.google.api.client.extensions.jetty.auth.oauth2.LocalServerReceiver;
import com.google.api.client.googleapis.auth.oauth2.GoogleAuthorizationCodeFlow;
import com.google.api.client.googleapis.auth.oauth2.GoogleClientSecrets;
import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.jackson2.JacksonFactory;
import com.google.api.services.compute.Compute;
import com.google.api.services.compute.ComputeScopes;
import com.google.api.services.compute.model.Instance;
import com.google.api.services.compute.model.InstanceList;
 
import java.io.IOException;
import java.io.InputStreamReader;
import java.security.GeneralSecurityException;
import java.util.Arrays;
 
public class ComputeEngineHelloWorldOAuth2
{
  /** project name must be lower case even you see ComputeEngineDemo on GUI */
  private static final String projectId = "computeenginedemo";
  private static HttpTransport httpTransport;
  private static final JsonFactory JSON_FACTORY = JacksonFactory.getDefaultInstance();
 
  public static void main(String[] args) throws IOException, GeneralSecurityException, Exception
  {
    httpTransport = GoogleNetHttpTransport.newTrustedTransport();
 
    Credential credential = authorize();  // Authorization
 
    // Create compute engine object for listing instances
    Compute compute = new Compute.Builder(httpTransport, JSON_FACTORY, null)
            .setApplicationName("doublecloud/1.0") // give it a name or warning.
            .setHttpRequestInitializer(credential).build();
 
    // List out instances
    printInstances(compute, projectId);
  }
 
  /** Authorizes the installed application to access user's protected data. */
  // https://code.google.com/apis/console/ 
  // src/main/resources/client_secrets.json
  private static Credential authorize() throws Exception
  {
    GoogleClientSecrets clientSecrets = GoogleClientSecrets.load(JSON_FACTORY,
      new InputStreamReader(ComputeEngineHelloWorldOAuth2.class.getResourceAsStream("/client_secrets.json")));
    GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(
            httpTransport, JSON_FACTORY, clientSecrets, Arrays.asList(ComputeScopes.COMPUTE))
            .build();
 
    LocalServerReceiver lsr = new LocalServerReceiver();
    AuthorizationCodeInstalledApp acia = new AuthorizationCodeInstalledApp(flow, lsr);
 
    return acia.authorize("user");
  }
 
  public static void printInstances(Compute compute, String projectId) throws IOException
  {
    Compute.Instances.List instances = compute.instances().list(projectId, "us-central1-a");
    InstanceList list = instances.execute();
    for (Instance instance : list.getItems())
    {
      System.out.println(instance.toPrettyString());
    }
  }
}

To get it work, you want to first get your own client_secrets.json. You can find the API Manager from the console, or simple try this URL: https://console.cloud.google.com/apis

On the left side pane, you would see two icons “Overview” and “Credentials”. You want to go to the Overview, and pick the “Compute Engine API” under the “Google Cloud APIs”. You want to first enable it.

Then you can click on the “Credentials” on the left pane and then the big blue button “Create Credentials” on the main page. You will pick “OAuth client ID” and choose “Other” as application type and give it a name. Then you can download the newly created OAuth key to your local drive. Rename it to client_secrets.json and move it to your project home as src/main/resources/client_secrets.json.

You can then run the Hello World program. Interestingly, you will see a browser windows popping up with Google page for your approval. Once you click “Allow”, the program will run though with the following output.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
{
  "canIpForward" : false,
  "creationTimestamp" : "2016-02-25T20:23:10.340-08:00",
  "description" : "",
  "disks" : [ {
    "autoDelete" : true,
    "boot" : true,
    "deviceName" : "instance-1",
    "index" : 0,
    "interface" : "SCSI",
    "kind" : "compute#attachedDisk",
    "mode" : "READ_WRITE",
    "source" : "https://www.googleapis.com/compute/v1/projects/computeenginedemo/zones/us-central1-a/disks/instance-1",
    "type" : "PERSISTENT"
  } ],
  "id" : "16169229807982161536",
  "kind" : "compute#instance",
  "machineType" : "https://www.googleapis.com/compute/v1/projects/computeenginedemo/zones/us-central1-a/machineTypes/f1-micro",
  "metadata" : {
    "fingerprint" : "c5140FVIUlg=",
    "kind" : "compute#metadata"
  },
  "name" : "instance-1",
  "networkInterfaces" : [ {
    "accessConfigs" : [ {
      "kind" : "compute#accessConfig",
      "name" : "External NAT",
      "natIP" : "104.197.11.111",
      "type" : "ONE_TO_ONE_NAT"
    } ],
    "name" : "nic0",
    "network" : "https://www.googleapis.com/compute/v1/projects/computeenginedemo/global/networks/default",
    "networkIP" : "10.128.0.21",
    "subnetwork" : "https://www.googleapis.com/compute/v1/projects/computeenginedemo/regions/us-central1/subnetworks/default"
  } ],
  "scheduling" : {
    "automaticRestart" : true,
    "onHostMaintenance" : "MIGRATE",
    "preemptible" : false
  },
  "selfLink" : "https://www.googleapis.com/compute/v1/projects/computeenginedemo/zones/us-central1-a/instances/instance-1",
  "serviceAccounts" : [ {
    "email" : "1007174531749-compute@developer.gserviceaccount.com",
    "scopes" : [ "https://www.googleapis.com/auth/cloud.useraccounts.readonly", "https://www.googleapis.com/auth/devstorage.read_only", "https://www.googleapis.com/auth/logging.write", "https://www.googleapis.com/auth/monitoring.write" ]
  } ],
  "status" : "RUNNING",
  "tags" : {
    "fingerprint" : "6smc4R4d39I=",
    "items" : [ "https-server", "http-server" ]
  },
  "zone" : "https://www.googleapis.com/compute/v1/projects/computeenginedemo/zones/us-central1-a",
  "cpuPlatform" : "Intel Sandy Bridge"
}

This works fine, but you don’t want manual interaction to run the program. Google provides another way to authenticate, which is the “Service Account Key.” I will be covered it the next post. Stay tuned.

  1. No comments yet.
  1. No trackbacks yet.