Overview
This article explains how to generate an access token from a service account JSON file using User Defined Java Class (UDJC) step. Once a token is generated then you can use it to access Google APIs using Pentaho Rest Client or other steps.
Prerequisites
- Create a project in Google Cloud Platform.
- Activate the API you want to query
- Create a Google Service Account and download the key as JSON file.
Steps
- Create a UDJC step and the following code:
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.security.GeneralSecurityException;
import java.util.Collections;
import org.pentaho.di.core.variables.Variables;
import com.google.api.client.googleapis.auth.oauth2.GoogleCredential;
import com.google.api.services.drive.DriveScopes;
String googleAccessToken = "";
String fileName = "";
public boolean init(StepMetaInterface stepMetaInterface, StepDataInterface stepDataInterface)
throws FileNotFoundException, IOException, GeneralSecurityException {
fileName = getParameter(“GOOGLE_APPLICATION_CREDENTIALS”);
googleAccessToken = getGoogleAccessToken(fileName);
logBasic("Token: " + googleAccessToken);
return parent.initImpl(stepMetaInterface, stepDataInterface);
}
public boolean processRow(StepMetaInterface smi, StepDataInterface sdi) throws KettleException {
Object[] r = getRow();
if (r == null) {
setOutputDone();
return false;
}
if (first) {
first = false;
}
Object[] outputRow = createOutputRow(r, data.outputRowMeta.size());
get(Fields.Out, “googleAccessToken”).setValue(outputRow, googleAccessToken);
putRow(data.outputRowMeta, outputRow);
return true;
}
public static String getGoogleAccessToken(String jsonKeyFilePath)
throws FileNotFoundException, IOException, GeneralSecurityException {
GoogleCredential credential = GoogleCredential.fromStream(new FileInputStream(jsonKeyFilePath))
.createScoped(Collections.singleton(DriveScopes.DRIVE));
credential.refreshToken();
return credential.getAccessToken();
}
- Add the following jar files into Pentaho lib folder:
google-api-client-1.19.0.jar
jackson-core-2.x.x.jar
google-oauth-client-1.19.0.jar
google-http-client-jackson2-1.19.0.jar
google-http-client-1.19.0.jar
google-api-services-drive-v3-rev122-1.23.0.jar