2

I am playing around with the Google Cloud DLP Java library. I've set up my service credentials and saved them in a JSON file as per the instructions here:

https://cloud.google.com/dlp/docs/libraries.

The documentation states that the preferred way to authenticate is by setting the environment variable GOOGLE_APPLICATION_CREDENTIALS to point to the path of the JSON file that contains the credentials. This is not all that practical in my case. I have a Spring Boot application where all the code (as well as the JSON file with the credentials) is embedded in a "fat jar". I can easily use the class loader to obtain an InputStream to the resource, but I can't really point to it inside the jar file from an environment variable. It's also not practical to create an environment variable from within a running JVM without resorting to hacks like using reflection, etc.

Some other Google Cloud libraries have service classes that can be initialized with a GoogleCredentials object, but I haven't found a way of doing this with the DLP library. Is there any way of passing a GoogleCredentials into the DlpServiceClient?

user2337270
  • 1,183
  • 2
  • 10
  • 27

2 Answers2

4

I ended up figuring it out after quite a bit of Googling. This worked fine:

Resource r = new ClassPathResource("/path-to-my-cred-file.json");

GoogleCredentials creds = GoogleCredentials.fromStream(r.getInputStream());

DlpServiceSettings settings = DlpServiceSettings.newBuilder()
        .setCredentialsProvider(FixedCredentialsProvider.create(creds)).build();

try (DlpServiceClient dlpServiceClient = DlpServiceClient.create(settings)) {
    ///... other stuff here ...
}
nakhodkin
  • 1,327
  • 1
  • 17
  • 27
user2337270
  • 1,183
  • 2
  • 10
  • 27
1

Using Document AI the following worked for me:

GoogleCredentials credentials = GoogleCredentials.fromStream(new FileInputStream("path-to-json-file"))
  .createScoped(Lists.newArrayList("https://www.googleapis.com/auth/cloud-platform"));

DocumentProcessorServiceClient client = DocumentProcessorServiceClient.create(
DocumentProcessorServiceSettings.newBuilder()
  .setEndpoint("eu-documentai.googleapis.com:443")
  .setCredentialsProvider(FixedCredentialsProvider.create(credentials))
  .build()
);
...
ProcessResponse result = client.processDocument(request);

Taken from here https://www.googlecloudcommunity.com/gc/AI-ML/DocAI-Response-in-a-single-json-file/m-p/491257

If you use maven, "GoogleCredentials" is not visible at compile-time but only at runtime. You have to configure something like that:

<dependencyManagement>
    <dependencies>
        <dependency>
            <groupId>com.google.auth</groupId>
            <artifactId>google-auth-library-oauth2-http</artifactId>
            <version>1.11.0</version>
            <scope>compile</scope>
        </dependency>
    </dependencies>
</dependencyManagement>
nakhodkin
  • 1,327
  • 1
  • 17
  • 27
Oliver
  • 11
  • 2