Google Cloud Platform pub/sub Publisher, how to supply credentials other than default application credentials

Viewed 2604

Using the com.google.cloud.google-cloud library (http://googlecloudplatform.github.io/google-cloud-java/0.21.1/index.html), I have the following code for the Google Cloud Platform pub/sub:

    TopicName topicName = TopicName.create("projectId...", "topic...");
    Publisher pub = Publisher.defaultBuilder(topicName).build();

How can I supply the credentials to be used by the publisher? I already have them in memory as they are provisioned through other means than hard coding them into a file.

All the examples for using custom credentials are as follows:

Storage storage = StorageOptions.newBuilder()
    .setProjectId(PROJECT_ID)
    .setCredentials(GoogleCredentials.fromStream(
    new FileInputStream(PATH_TO_JSON_KEY))).build();
Bucket bucket = storage.create(BucketInfo.of("myBucketName"));

But there is no PubSubOptions or PublisherOptions class to write similar code (I replace the FileInputStream with a ByteArrayInputStream).

Here's someone who has the same problem but the code sample doesn't work: https://github.com/GoogleCloudPlatform/google-cloud-java/issues/1751

2 Answers

The interface has changed slightly. You should now use:

 GoogleCredentials credentials = GoogleCredentials.fromStream(new FileInputStream("<path-to-service-account JSON file>"));
 Publisher publisher = Publisher
            .newBuilder(topicName)
            .setCredentialsProvider(FixedCredentialsProvider.create(credentials))
            .build();
Related