Skip to content

jart/gcloud-java

 
 

Repository files navigation

Google Cloud Java Client

Java idiomatic client for Google Cloud Platform services.

Build Status Coverage Status Maven Codacy Badge Dependency Status

This client supports the following Google Cloud Platform services:

  • [Google Cloud BigQuery] (#google-cloud-bigquery-alpha) (Alpha)
  • [Google Cloud Datastore] (#google-cloud-datastore)
  • [Google Cloud Resource Manager] (#google-cloud-resource-manager-alpha) (Alpha)
  • [Google Cloud Storage] (#google-cloud-storage)

Note: This client is a work-in-progress, and may occasionally make backwards-incompatible changes.

Quickstart

If you are using Maven, add this to your pom.xml file

<dependency>
  <groupId>com.google.gcloud</groupId>
  <artifactId>gcloud-java</artifactId>
  <version>0.1.4</version>
</dependency>

If you are using Gradle, add this to your dependencies

compile 'com.google.gcloud:gcloud-java:0.1.4'

If you are using SBT, add this to your dependencies

libraryDependencies += "com.google.gcloud" % "gcloud-java" % "0.1.4"

Example Applications

  • BigQueryExample - A simple command line interface providing some of Cloud BigQuery's functionality
  • Bookshelf - An App Engine app that manages a virtual bookshelf.
    • This app uses gcloud-java to interface with Cloud Datastore and Cloud Storage. It also uses Cloud SQL, another Google Cloud Platform service.
  • DatastoreExample - A simple command line interface for the Cloud Datastore
  • ResourceManagerExample - A simple command line interface providing some of Cloud Resource Manager's functionality
  • SparkDemo - An example of using gcloud-java-datastore from within the SparkJava and App Engine Managed VM frameworks.
    • Read about how it works on the example's README page.
  • StorageExample - A simple command line interface providing some of Cloud Storage's functionality

Specifying a Project ID

Most gcloud-java libraries require a project ID. There are multiple ways to specify this project ID.

  1. When using gcloud-java libraries from within Compute/App Engine, there's no need to specify a project ID. It is automatically inferred from the production environment.
  2. When using gcloud-java elsewhere, you can do one of the following:
  • Supply the project ID when building the service options. For example, to use Datastore from a project with ID "PROJECT_ID", you can write:
Datastore datastore = DatastoreOptions.builder().projectId("PROJECT_ID").build().service(); 
  • Specify the environment variable GCLOUD_PROJECT to be your desired project ID.
  • Set the project ID using the Google Cloud SDK. To use the SDK, download the SDK if you haven't already, and set the project ID from the command line. For example:
gcloud config set project PROJECT_ID

gcloud-java determines the project ID from the following sources in the listed order, stopping once it finds a value:

  1. Project ID supplied when building the service options
  2. Project ID specified by the environment variable GCLOUD_PROJECT
  3. App Engine project ID
  4. Google Cloud SDK project ID
  5. Compute Engine project ID

Authentication

First, ensure that the necessary Google Cloud APIs are enabled for your project. To do this, follow the instructions on the authentication document shared by all the gcloud language libraries.

Next, choose a method for authenticating API requests from within your project:

  1. When using gcloud-java libraries from within Compute/App Engine, no additional authentication steps are necessary.
  2. When using gcloud-java libraries elsewhere, there are two options:
  • Generate a JSON service account key. After downloading that key, you must do one of the following:
    • Define the environment variable GOOGLE_APPLICATION_CREDENTIALS to be the location of the key. For example:
    export GOOGLE_APPLICATION_CREDENTIALS=/path/to/my/key.json
    • Supply the JSON credentials file when building the service options. For example, this Storage object has the necessary permissions to interact with your Google Cloud Storage data:
    Storage storage = StorageOptions.builder()
      .authCredentials(AuthCredentials.createForJson(new FileInputStream("/path/to/my/key.json"))
      .build()
      .service();
  • If running locally for development/testing, you can use use Google Cloud SDK. Download the SDK if you haven't already, then login using the SDK (gcloud auth login in command line). Be sure to set your project ID as described above.

gcloud-java looks for credentials in the following order, stopping once it finds credentials:

  1. Credentials supplied when building the service options
  2. App Engine credentials
  3. Key file pointed to by the GOOGLE_APPLICATION_CREDENTIALS environment variable
  4. Google Cloud SDK credentials
  5. Compute Engine credentials

Google Cloud BigQuery (Alpha)

Preview

Here is a code snippet showing a simple usage example from within Compute/App Engine. Note that you must supply credentials and a project ID if running this snippet elsewhere. Complete source code can be found at CreateTableAndLoadData.java.

import com.google.gcloud.bigquery.BigQuery;
import com.google.gcloud.bigquery.BigQueryOptions;
import com.google.gcloud.bigquery.Field;
import com.google.gcloud.bigquery.FormatOptions;
import com.google.gcloud.bigquery.Job;
import com.google.gcloud.bigquery.Schema;
import com.google.gcloud.bigquery.StandardTableDefinition;
import com.google.gcloud.bigquery.Table;
import com.google.gcloud.bigquery.TableId;
import com.google.gcloud.bigquery.TableInfo;

BigQuery bigquery = BigQueryOptions.defaultInstance().service();
TableId tableId = TableId.of("dataset", "table");
Table table = bigquery.getTable(tableId);
if (table == null) {
  System.out.println("Creating table " + tableId);
  Field integerField = Field.of("fieldName", Field.Type.integer());
  Schema schema = Schema.of(integerField);
  table = bigquery.create(TableInfo.of(tableId, StandardTableDefinition.of(schema)));
}
System.out.println("Loading data into table " + tableId);
Job loadJob = table.load(FormatOptions.csv(), "gs://bucket/path");
while (!loadJob.isDone()) {
  Thread.sleep(1000L);
}
if (loadJob.status().error() != null) {
  System.out.println("Job completed with errors");
} else {
  System.out.println("Job succeeded");
}

Google Cloud Datastore

Follow the activation instructions to use the Google Cloud Datastore API with your project.

Preview

Here are two code snippets showing simple usage examples from within Compute/App Engine. Note that you must supply credentials and a project ID if running this snippet elsewhere.

The first snippet shows how to create a Datastore entity. Complete source code can be found at CreateEntity.java.

import com.google.gcloud.datastore.Datastore;
import com.google.gcloud.datastore.DatastoreOptions;
import com.google.gcloud.datastore.DateTime;
import com.google.gcloud.datastore.Entity;
import com.google.gcloud.datastore.Key;
import com.google.gcloud.datastore.KeyFactory;

Datastore datastore = DatastoreOptions.defaultInstance().service();
KeyFactory keyFactory = datastore.newKeyFactory().kind("keyKind");
Key key = keyFactory.newKey("keyName");
Entity entity = Entity.builder(key)
    .set("name", "John Doe")
    .set("age", 30)
    .set("access_time", DateTime.now())
    .build();
datastore.put(entity);

The second snippet shows how to update a Datastore entity if it exists. Complete source code can be found at UpdateEntity.java.

import com.google.gcloud.datastore.Datastore;
import com.google.gcloud.datastore.DatastoreOptions;
import com.google.gcloud.datastore.DateTime;
import com.google.gcloud.datastore.Entity;
import com.google.gcloud.datastore.Key;
import com.google.gcloud.datastore.KeyFactory;

Datastore datastore = DatastoreOptions.defaultInstance().service();
KeyFactory keyFactory = datastore.newKeyFactory().kind("keyKind");
Key key = keyFactory.newKey("keyName");
Entity entity = datastore.get(key);
if (entity != null) {
  System.out.println("Updating access_time for " + entity.getString("name"));
  entity = Entity.builder(entity)
      .set("access_time", DateTime.now())
      .build();
  datastore.update(entity);
}

Google Cloud Resource Manager (Alpha)

Preview

Here is a code snippet showing a simple usage example. Note that you must supply Google SDK credentials for this service, not other forms of authentication listed in the Authentication section. Complete source code can be found at UpdateAndListProjects.java.

import com.google.gcloud.resourcemanager.Project;
import com.google.gcloud.resourcemanager.ResourceManager;
import com.google.gcloud.resourcemanager.ResourceManagerOptions;

import java.util.Iterator;

ResourceManager resourceManager = ResourceManagerOptions.defaultInstance().service();
Project project = resourceManager.get("some-project-id"); // Use an existing project's ID
if (project != null) {
  Project newProject = project.toBuilder()
      .addLabel("launch-status", "in-development")
      .build()
      .replace();
  System.out.println("Updated the labels of project " + newProject.projectId()
      + " to be " + newProject.labels());
}
Iterator<Project> projectIterator = resourceManager.list().iterateAll();
System.out.println("Projects I can view:");
while (projectIterator.hasNext()) {
  System.out.println(projectIterator.next().projectId());
}

Google Cloud Storage

Follow the activation instructions to use the Google Cloud Storage API with your project.

Preview

Here are two code snippets showing simple usage examples from within Compute/App Engine. Note that you must supply credentials and a project ID if running this snippet elsewhere.

The first snippet shows how to create a Storage blob. Complete source code can be found at CreateBlob.java.

import static java.nio.charset.StandardCharsets.UTF_8;

import com.google.gcloud.storage.Blob;
import com.google.gcloud.storage.BlobId;
import com.google.gcloud.storage.BlobInfo;
import com.google.gcloud.storage.Storage;
import com.google.gcloud.storage.StorageOptions;

Storage storage = StorageOptions.defaultInstance().service();
BlobId blobId = BlobId.of("bucket", "blob_name");
BlobInfo blobInfo = BlobInfo.builder(blobId).contentType("text/plain").build();
Blob blob = storage.create(blobInfo, "Hello, Cloud Storage!".getBytes(UTF_8));

The second snippet shows how to update a Storage blob if it exists. Complete source code can be found at UpdateBlob.java.

import static java.nio.charset.StandardCharsets.UTF_8;

import com.google.gcloud.storage.Blob;
import com.google.gcloud.storage.BlobId;
import com.google.gcloud.storage.Storage;
import com.google.gcloud.storage.StorageOptions;

import java.nio.ByteBuffer;
import java.nio.channels.WritableByteChannel;

Storage storage = StorageOptions.defaultInstance().service();
BlobId blobId = BlobId.of("bucket", "blob_name");
Blob blob = storage.get(blobId);
if (blob != null) {
  byte[] prevContent = blob.content();
  System.out.println(new String(prevContent, UTF_8));
  WritableByteChannel channel = blob.writer();
  channel.write(ByteBuffer.wrap("Updated content".getBytes(UTF_8)));
  channel.close();
}

Troubleshooting

To get help, follow the gcloud-java links in the gcloud-* shared Troubleshooting document.

Java Versions

Java 7 or above is required for using this client.

Testing

This library provides tools to help write tests for code that uses gcloud-java services.

See TESTING to read more about using our testing helpers.

Versioning

This library follows [Semantic Versioning] (http://semver.org/).

It is currently in major version zero (0.y.z), which means that anything may change at any time and the public API should not be considered stable.

Contributing

Contributions to this library are always welcome and highly encouraged.

See gcloud-java's CONTRIBUTING documentation and the gcloud-* shared documentation for more information on how to get started.

Please note that this project is released with a Contributor Code of Conduct. By participating in this project you agree to abide by its terms. See Code of Conduct for more information.

License

Apache 2.0 - See LICENSE for more information.

Packages

No packages published

Languages

  • Java 98.0%
  • CSS 1.1%
  • Other 0.9%