-
Notifications
You must be signed in to change notification settings - Fork 137
doc: add MutableCredentials Example #4382
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: main
Are you sure you want to change the base?
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change | ||||||||
|---|---|---|---|---|---|---|---|---|---|---|
| @@ -0,0 +1,98 @@ | ||||||||||
| /* | ||||||||||
| * Copyright 2026 Google LLC | ||||||||||
| * | ||||||||||
| * 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. | ||||||||||
| */ | ||||||||||
|
|
||||||||||
| package com.example.spanner; | ||||||||||
|
|
||||||||||
| // [START spanner_mutable_credentials] | ||||||||||
|
|
||||||||||
| import com.google.auth.oauth2.ServiceAccountCredentials; | ||||||||||
| import com.google.cloud.spanner.MutableCredentials; | ||||||||||
| import com.google.cloud.spanner.Spanner; | ||||||||||
| import com.google.cloud.spanner.SpannerOptions; | ||||||||||
| import com.google.cloud.spanner.admin.database.v1.DatabaseAdminClient; | ||||||||||
| import java.io.FileInputStream; | ||||||||||
| import java.io.IOException; | ||||||||||
| import java.nio.file.Files; | ||||||||||
| import java.nio.file.Path; | ||||||||||
| import java.nio.file.Paths; | ||||||||||
| import java.nio.file.attribute.FileTime; | ||||||||||
| import java.util.concurrent.Executors; | ||||||||||
| import java.util.concurrent.ScheduledExecutorService; | ||||||||||
| import java.util.concurrent.ThreadFactory; | ||||||||||
| import java.util.concurrent.TimeUnit; | ||||||||||
|
|
||||||||||
| public class MutableCredentialsExample { | ||||||||||
|
|
||||||||||
| static void createClientWithMutableCredentials() throws IOException { | ||||||||||
| final String credentialsPath = "location_of_service_account_credential_json"; | ||||||||||
| Path path = Paths.get(credentialsPath); | ||||||||||
| // Use an array to hold the mutable lastModifiedTime so it can be accessed in the lambda | ||||||||||
| FileTime[] lastModifiedTime = new FileTime[] {Files.getLastModifiedTime(path)}; | ||||||||||
|
|
||||||||||
| // 1 - create service account credentials | ||||||||||
| ServiceAccountCredentials serviceAccountCredentials; | ||||||||||
| try (FileInputStream is = new FileInputStream(credentialsPath)) { | ||||||||||
| serviceAccountCredentials = ServiceAccountCredentials.fromStream(is); | ||||||||||
| } | ||||||||||
|
|
||||||||||
| // 2 - wrap credentials from step 1 in a MutableCredentials instance | ||||||||||
| MutableCredentials mutableCredentials = new MutableCredentials(serviceAccountCredentials); | ||||||||||
|
|
||||||||||
| // 3 - set credentials on your SpannerOptions builder to your mutableCredentials | ||||||||||
| SpannerOptions options = SpannerOptions.newBuilder().setCredentials(mutableCredentials).build(); | ||||||||||
|
|
||||||||||
| // 4 - include logic for when/how to update your mutableCredentials | ||||||||||
| // In this example we'll use a SchedulerExecutorService to periodically check for updates | ||||||||||
| ThreadFactory daemonThreadFactory = | ||||||||||
| runnable -> { | ||||||||||
| Thread thread = new Thread(runnable, "spanner-mutable-credentials-rotator"); | ||||||||||
| thread.setDaemon(true); | ||||||||||
| return thread; | ||||||||||
| }; | ||||||||||
| ScheduledExecutorService executorService = | ||||||||||
| Executors.newSingleThreadScheduledExecutor(daemonThreadFactory); | ||||||||||
| executorService.scheduleAtFixedRate( | ||||||||||
| () -> { | ||||||||||
| try { | ||||||||||
| FileTime currentModifiedTime = Files.getLastModifiedTime(path); | ||||||||||
| if (currentModifiedTime.compareTo(lastModifiedTime[0]) > 0) { | ||||||||||
| lastModifiedTime[0] = currentModifiedTime; | ||||||||||
|
Comment on lines
+71
to
+72
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. As part of refactoring to use
Suggested change
|
||||||||||
| try (FileInputStream is = new FileInputStream(credentialsPath)) { | ||||||||||
| ServiceAccountCredentials credentials = ServiceAccountCredentials.fromStream(is); | ||||||||||
| mutableCredentials.updateCredentials(credentials); | ||||||||||
| } | ||||||||||
| } | ||||||||||
| } catch (IOException e) { | ||||||||||
| System.err.println("Failed to check or update credentials: " + e.getMessage()); | ||||||||||
| } | ||||||||||
| }, | ||||||||||
| 15, | ||||||||||
| 15, | ||||||||||
| TimeUnit.MINUTES); | ||||||||||
|
|
||||||||||
| // 5. Use the client | ||||||||||
| try (Spanner spanner = options.getService(); | ||||||||||
| DatabaseAdminClient databaseAdminClient = spanner.createDatabaseAdminClient()) { | ||||||||||
| // Perform operations... | ||||||||||
| // long running client operations will always use the latest credentials wrapped in | ||||||||||
| // mutableCredentials | ||||||||||
| } finally { | ||||||||||
| // Ensure the executor is shut down when the application exits or the client is closed | ||||||||||
| executorService.shutdown(); | ||||||||||
| } | ||||||||||
|
Comment on lines
+87
to
+95
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. This example is intended to demonstrate credential updates for a long-running client, but the To make the example more illustrative, consider adding a // 5. Use the client
try (Spanner spanner = options.getService();
DatabaseAdminClient databaseAdminClient = spanner.createDatabaseAdminClient()) {
// Perform operations...
// long running client operations will always use the latest credentials wrapped in
// mutableCredentials.
// This example demonstrates this by keeping the client alive for 60 seconds.
System.out.println("Client created. It will remain active for 60 seconds.");
try {
TimeUnit.SECONDS.sleep(60);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
System.out.println("60 seconds passed. Closing client.");
} finally {
// Ensure the executor is shut down when the application exits or the client is closed
executorService.shutdown();
} |
||||||||||
| } | ||||||||||
| } | ||||||||||
| // [END spanner_mutable_credentials] | ||||||||||
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
For better clarity and to use modern Java concurrency utilities, consider using
java.util.concurrent.atomic.AtomicReferenceinstead of a single-element array to hold a mutable reference. This makes the intent of sharing a mutable object with the lambda more explicit. This change should be applied along with an update to the lambda that uses this variable.