I was working on a project CONAG where I had to create a mapping page for Google Analytics (similar to what Adobe Analytics provide for AEM) in which I needed all the dimensions of Google Analytics so that I could map these dimensions with AEM variables.
To get these dimensions of an account, we need to have Analytics object for which we need to have GoogleCredential object.
In this blog, I will be discussing the approach to get GoogleCredential object in AEM as rest of the part is straightforward and Google has already given an example for the same.
To get GoogleCredential object, we need to set private key of service account.
There are two ways of doing this; even Google provides two different methods for this:
- setServiceAccountPrivateKeyFromP12File (java.io.File file)
In this method, we need to get File object of .p12 file (provided by Google). Getting a java.io.File object is very tedious in AEM as it does not interact with the file system directly.
So, first we need to get inputstream of the resource containing .p12 file data from content hierarchy (in AEM, everything is content) and write it into a temporary file. But converting the .p12 file into a temporary file would give the exception because it is encrypted.
So we have to use setServiceAccountPrivateKey which takes java.security.PrivateKey as a parameter.
- setServiceAccountPrivateKey(java.security.PrivateKey privateKey)
To get the java.security.PrivateKey from .p12 file, we need to get the inputstream of file as
Resource fileResource = resourceResolver.getResource(filePath); final Node node = fileResource.adaptTo(Node.class); final InputStream is = node.getProperty("jcr:data").getBinary().getStream();
Now when we have the inputstream of the file, we need to get the java.security.KeyStore as
final KeyStore keyStore = KeyStore.getInstance(keyStoreType, keystoreProvider);
Load the KeyStore object as
Finally get the PrivateKey as:
PrivateKey privateKey = (PrivateKey) keyStore.getKey(keyAliasName,filePassword.toCharArray());
Get the HttpTransport object:
final HttpTransport httpTransport = GoogleNetHttpTransport.newTrustedTransport();
GsonFactory JSON_FACTORY = GsonFactory.getDefaultInstance();
Now, we can get the GoogleCredential object:
final GoogleCredential credential = new GoogleCredential.Builder().setTransport(httpTransport).setJsonFactory(JSON_FACTORY).setServiceAccountId(serviceAccountEmail).setServiceAccountPrivateKey(serviceAccountPrivateKey).setServiceAccountScopes(AnalyticsScopes.all()).build();
And get the Analytics object from GoogleCredential:
analytics = new Analytics.Builder(httpTransport, JSON_FACTORY, credential).setApplicationName(appName).build();
Now, we have Google Analytics java object and we can perform any operation like create dimension, get dimension, create a report and many other operations which this API provides.