Google Cloud Programmatic Access from Java: Difference between revisions
Jump to navigation
Jump to search
Line 33: | Line 33: | ||
===Authentication Test Code=== | ===Authentication Test Code=== | ||
<syntaxhighlight lang='java'> | <syntaxhighlight lang='java'> | ||
import com.google.api.gax.paging.Page; | |||
import com.google.cloud.storage.Bucket; | |||
import com.google.cloud.storage.Storage; | |||
import com.google.cloud.storage.StorageOptions; | |||
public class Main { | |||
public static void main(String[] args) { | |||
Storage storage = StorageOptions.getDefaultInstance().getService(); | |||
System.out.println("Buckets:"); | |||
Page<Bucket> buckets = storage.list(); | |||
for (Bucket bucket : buckets.iterateAll()) { | |||
System.out.println(bucket.toString()); | |||
} | |||
} | |||
} | |||
</syntaxhighlight> | </syntaxhighlight> | ||
Alternatively, the client can be explicitly configured. | Alternatively, the client can be explicitly configured. |
Revision as of 00:15, 25 August 2021
External
- https://googleapis.dev/java/google-cloud-clients/latest/index.html
- https://github.com/googleapis/google-cloud-java
Internal
Overview
Service-Specific Libraries
Supported Java Versions
Gradle
repositories {
mavenCentral()
}
dependencies {
implementation platform('com.google.cloud:libraries-bom:21.0.0')
implementation 'com.google.cloud:google-cloud-storage'
}
Client Authentication
The programmatic client needs to assume the identity of an already existing service account that has sufficient permissions to access the desired resource.
The service account can be created, if it does not exist already, with gcloud iam service-accounts create
. The service account can then be granted permissions on resource with gcloud projects add-iam-policy-binding
. A key file for the service account can be generated with gcloud iam service-accounts keys create
.
Once the service account key file exists, the programmatic client is configured with the key file by setting the environment variable:
export GOOGLE_APPLICATION_CREDENTIALS="/Users/someuser/tmp/test-sa-key-file.json"
Authentication Test Code
import com.google.api.gax.paging.Page;
import com.google.cloud.storage.Bucket;
import com.google.cloud.storage.Storage;
import com.google.cloud.storage.StorageOptions;
public class Main {
public static void main(String[] args) {
Storage storage = StorageOptions.getDefaultInstance().getService();
System.out.println("Buckets:");
Page<Bucket> buckets = storage.list();
for (Bucket bucket : buckets.iterateAll()) {
System.out.println(bucket.toString());
}
}
}
Alternatively, the client can be explicitly configured.