已弃用的“GoogleCredential"的替代方案是什么?

I'd been employing the following Java method to set a bucket notification in GCS.

private void setBucketNotification(String bucketName, String topicId) {

List<String> eventType = new ArrayList<>();
eventType.add("OBJECT_FINALIZE");

try {
  Notification notification = new Notification();
  notification.setTopic(topicId);
  notification.setEventTypes(eventType);
  notification.setPayloadFormat("JSON_API_V1");

  final GoogleCredential googleCredential = GoogleCredential
      .fromStream(Objects.requireNonNull(classloader.getResourceAsStream("Key.json")))
      .createScoped(Collections.singletonList(StorageScopes.DEVSTORAGE_FULL_CONTROL));  

  final com.google.api.services.storage.Storage myStorage = new com.google.api.services.storage.Storage.Builder(
      new NetHttpTransport(), new JacksonFactory(), googleCredential).build();

  Notification v = myStorage.notifications().insert(bucketName, notification).execute();

} catch (IOException e) {
  log.error("Caught an IOException {}",e);
  }
}

It's been working fine so far, but lately, I'm getting a complaint regarding the deprecation of GoogleCredential class, and tried doing some research with a hope to find a possible replacement, but couldn't find anything. Can anyone help me point in the right direction?

解决方案

After a while of looking around, I managed to fix it, using GoogleCredentials and HttpRequestInitializer. The code changes are as follows.

final GoogleCredential googleCredential = GoogleCredential
  .fromStream(Objects.requireNonNull(classloader.getResourceAsStream("Key.json")))
  .createScoped(Collections.singletonList(StorageScopes.DEVSTORAGE_FULL_CONTROL));

final com.google.api.services.storage.Storage myStorage = new com.google.api.services.storage.Storage.Builder(
      new NetHttpTransport(), new JacksonFactory(), googleCredential).build();

becomes

final GoogleCredentials googleCredentials = serviceAccountCredentials
                    .createScoped(Collections.singletonList(StorageScopes.DEVSTORAGE_FULL_CONTROL));
            HttpRequestInitializer requestInitializer = new HttpCredentialsAdapter(googleCredentials);        

final com.google.api.services.storage.Storage myStorage = new com.google.api.services.storage.Storage.Builder(
                new NetHttpTransport(), new JacksonFactory(), requestInitializer).build();

相关文章