|
| 1 | +/* |
| 2 | + * Copyright 2019 Google LLC |
| 3 | + * |
| 4 | + * Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | + * you may not use this file except in compliance with the License. |
| 6 | + * You may obtain a copy of the License at |
| 7 | + * |
| 8 | + * http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | + * |
| 10 | + * Unless required by applicable law or agreed to in writing, software |
| 11 | + * distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | + * See the License for the specific language governing permissions and |
| 14 | + * limitations under the License. |
| 15 | + */ |
| 16 | + |
| 17 | +package com.google.cloud.examples.nio.snippets; |
| 18 | + |
| 19 | +import com.google.auth.oauth2.ServiceAccountCredentials; |
| 20 | +import com.google.cloud.storage.StorageOptions; |
| 21 | +import com.google.cloud.storage.contrib.nio.CloudStorageConfiguration; |
| 22 | +import com.google.cloud.storage.contrib.nio.CloudStorageFileSystem; |
| 23 | +import java.io.FileInputStream; |
| 24 | +import java.io.IOException; |
| 25 | + |
| 26 | +/** |
| 27 | + * A snippet for Google Cloud Storage NIO that shows how to create a {@link CloudStorageFileSystem} |
| 28 | + * using explicitly-provided credentials instead of the default ones. |
| 29 | + */ |
| 30 | +public class UseExplicitCredentials { |
| 31 | + |
| 32 | + public static void main(String... args) throws IOException { |
| 33 | + // Create a file system for the bucket using the service account credentials |
| 34 | + // saved in the file below. |
| 35 | + String myCredentials = "/path/to/my/key.json"; |
| 36 | + CloudStorageFileSystem fs = |
| 37 | + CloudStorageFileSystem.forBucket( |
| 38 | + "mybucket", |
| 39 | + CloudStorageConfiguration.DEFAULT, |
| 40 | + StorageOptions.newBuilder() |
| 41 | + .setCredentials( |
| 42 | + ServiceAccountCredentials.fromStream(new FileInputStream(myCredentials))) |
| 43 | + .build()); |
| 44 | + // Can now read and write to the bucket using fs |
| 45 | + // (see e.g. ReadAllLines for an example). |
| 46 | + } |
| 47 | +} |
0 commit comments