OpenID Connect Examples using Multiple Providers? [closed] - java

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.
Closed 5 years ago.
Improve this question
I'm trying to figure out how to use the Google OAuth Client Library for Java to authenticate against multiple OpenID connect providers. The example they have here works with Daily Motion. I'd like to see how it works with other providers so I can abstract the differences.
Are there any other examples around that authenticate against say Google perhaps?

At this repo, is an example of how to do this using their library. Here's the code from the main sample:
package com.google.api.services.samples.dailymotion.cmdline;
import com.google.api.client.auth.oauth2.AuthorizationCodeFlow;
import com.google.api.client.auth.oauth2.BearerToken;
import com.google.api.client.auth.oauth2.ClientParametersAuthentication;
import com.google.api.client.auth.oauth2.Credential;
import com.google.api.client.extensions.java6.auth.oauth2.AuthorizationCodeInstalledApp;
import com.google.api.client.extensions.jetty.auth.oauth2.LocalServerReceiver;
import com.google.api.client.http.GenericUrl;
import com.google.api.client.http.HttpRequest;
import com.google.api.client.http.HttpRequestFactory;
import com.google.api.client.http.HttpRequestInitializer;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.JsonObjectParser;
import com.google.api.client.json.jackson2.JacksonFactory;
import com.google.api.client.util.store.DataStoreFactory;
import com.google.api.client.util.store.FileDataStoreFactory;
import java.io.IOException;
import java.util.Arrays;
/**
* A sample application that demonstrates how the Google OAuth2 library can be used to authenticate
* against Google.
*
* #author Brad Parks
*/
public class GoogleAuthExample {
// **********************************************************************
// CHANGE THE FOLLOWING values to the keys you get after following the steps at the following page:
// https://developers.google.com/accounts/docs/OAuth2Login#appsetup
// This should be all you need to do to get this sample to work.
// **********************************************************************
public static final String API_KEY = "Enter your key here";
public static final String API_SECRET = "Enter your key here";
/** Directory to store user credentials. */
private static final java.io.File DATA_STORE_DIR =
new java.io.File(System.getProperty("user.home"), ".store/google_oauth_sample");
/**
* Global instance of the {#link DataStoreFactory}. The best practice is to make it a single
* globally shared instance across your application.
*/
private static FileDataStoreFactory DATA_STORE_FACTORY;
/** OAuth 2 scope. */
private static final String SCOPE = "openid email profile https://www.googleapis.com/auth/userinfo.email https://www.googleapis.com/auth/userinfo.profile";
/** Global instance of the HTTP transport. */
private static final HttpTransport HTTP_TRANSPORT = new NetHttpTransport();
/** Global instance of the JSON factory. */
static final JsonFactory JSON_FACTORY = new JacksonFactory();
private static final String TOKEN_SERVER_URL = "https://accounts.google.com/o/oauth2/token";
private static final String AUTHORIZATION_SERVER_URL = "https://accounts.google.com/o/oauth2/auth";
public static final int PORT = 8080;
public static final String DOMAIN = "127.0.0.1";
/** Authorizes the installed application to access user's protected data. */
private static Credential authorize() throws Exception {
errorIfNotSpecified();
AuthorizationCodeFlow flow = new AuthorizationCodeFlow.Builder(BearerToken
.queryParameterAccessMethod(),
HTTP_TRANSPORT,
JSON_FACTORY,
new GenericUrl(TOKEN_SERVER_URL),
new ClientParametersAuthentication(
API_KEY, API_SECRET),
API_KEY,
AUTHORIZATION_SERVER_URL).setScopes(Arrays.asList(SCOPE))
.setDataStoreFactory(DATA_STORE_FACTORY).build();
// authorize
LocalServerReceiver receiver = new LocalServerReceiver.Builder().setHost(DOMAIN).setPort(PORT).build();
return new AuthorizationCodeInstalledApp(flow, receiver).authorize("user");
}
public static void errorIfNotSpecified() {
if (API_KEY.startsWith("Enter ") || API_SECRET.startsWith("Enter ")) {
System.out.println(
"Enter API Key and API Secret from https://developers.google.com/accounts/docs/OAuth2Login#appsetup"
+ " into API_KEY and API_SECRET in " + GoogleAuthExample.class);
System.exit(1);
}
}
private static void run(HttpRequestFactory requestFactory) throws IOException {
GenericUrl url = new GenericUrl("https://www.googleapis.com/oauth2/v1/tokeninfo");
HttpRequest request = requestFactory.buildGetRequest(url);
UserInfo userInfo = request.execute().parseAs(UserInfo.class);
System.out.println("Got user info from API after authorization:");
System.out.println("-----------------------------------------------");
System.out.println("issued_to: " + userInfo.issued_to);
System.out.println("audience: " + userInfo.audience);
System.out.println("user_id: " + userInfo.user_id);
System.out.println("scope: " + userInfo.scope);
System.out.println("expires_in: " + userInfo.expires_in);
System.out.println("email: " + userInfo.email);
System.out.println("verified_email: " + userInfo.verified_email);
System.out.println("access_type: " + userInfo.access_type);
}
public static void main(String[] args) {
try {
DATA_STORE_FACTORY = new FileDataStoreFactory(DATA_STORE_DIR);
final Credential credential = authorize();
HttpRequestFactory requestFactory =
HTTP_TRANSPORT.createRequestFactory(new HttpRequestInitializer() {
#Override
public void initialize(HttpRequest request) throws IOException {
credential.initialize(request);
request.setParser(new JsonObjectParser(JSON_FACTORY));
}
});
run(requestFactory);
// Success!
return;
} catch (IOException e) {
System.err.println(e.getMessage());
} catch (Throwable t) {
t.printStackTrace();
}
System.exit(1);
}
}
UserInfo.java
package com.google.api.services.samples.dailymotion.cmdline;
import com.google.api.client.util.Key;
public class UserInfo {
#Key
public String issued_to;
#Key
public String audience;
#Key
public String user_id;
#Key
public String scope;
#Key
public Integer expires_in;
#Key
public String email;
#Key
public Boolean verified_email;
#Key
public String access_type;
}

You may consider using oxProx, and openid connect proxy. http://ox.gluu.org/doku.php?id=oxprox:home
Its just being released now, but it solves a few problems: discovery and enabling clients behind the proxy to see the correct 'aud' (i.e. because the proxy issues a new id_token, the correct aud is set for the respective client).

Related

How to delete Users using the Java Google Admin SDK API

I went the Java Quickstart and got a working application that just shows the full list of all the users connected to the account logged into. I have gone over the Java docs and the only thing I have found that pertains to the deletion of a user is the "setDeletionTime" in the User class, but I have tried that with a dummy account and set the time to "null" and tried to create a time that was set to today and neither worked for deleting the user. I have no clue what I am missing here.
Code I am using, most of it copied from the google quickstart
import com.google.api.client.auth.oauth2.Credential;
import com.google.api.client.extensions.java6.auth.oauth2.AuthorizationCodeInstalledAp;
import com.google.api.client.extensions.jetty.auth.oauth2.LocalServerReceiver;
import com.google.api.client.googleapis.auth.oauth2.GoogleAuthorizationCodeFlow;
import com.google.api.client.googleapis.auth.oauth2.GoogleClientSecrets;
import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.json.jackson2.JacksonFactory;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.util.store.FileDataStoreFactory;
import com.google.api.services.admin.directory.DirectoryScopes;
import com.google.api.services.admin.directory.model.*;
import com.google.api.services.admin.directory.Directory;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.List;
public class Quickstart {
/** Application name. */
private static final String APPLICATION_NAME =
"Directory API Java Quickstart";
/** Directory to store user credentials for this application. */
private static final java.io.File DATA_STORE_DIR = new java.io.File(
System.getProperty("user.home"), ".credentials/admin-directory_v1-java-quickstart");
/** Global instance of the {#link FileDataStoreFactory}. */
private static FileDataStoreFactory DATA_STORE_FACTORY;
/** Global instance of the JSON factory. */
private static final JsonFactory JSON_FACTORY =
JacksonFactory.getDefaultInstance();
/** Global instance of the HTTP transport. */
private static HttpTransport HTTP_TRANSPORT;
/** Global instance of the scopes required by this quickstart.
*
* If modifying these scopes, delete your previously saved credentials
* at ~/.credentials/admin-directory_v1-java-quickstart
*/
private static final List<String> SCOPES =
Arrays.asList(DirectoryScopes.ADMIN_DIRECTORY_USER_READONLY);
static {
try {
HTTP_TRANSPORT = GoogleNetHttpTransport.newTrustedTransport();
DATA_STORE_FACTORY = new FileDataStoreFactory(DATA_STORE_DIR);
} catch (Throwable t) {
t.printStackTrace();
System.exit(1);
}
}
/**
* Creates an authorized Credential object.
* #return an authorized Credential object.
* #throws IOException
*/
public static Credential authorize() throws IOException {
// Load client secrets.
/* This does not work as of now
InputStream in = Quickstart.class.getResourceAsStream("src/resources/client_secret.json");
*/
InputStream in = new FileInputStream("src/resources/client_secret.json");
GoogleClientSecrets clientSecrets =
GoogleClientSecrets.load(JSON_FACTORY, new InputStreamReader(in));
// Build flow and trigger user authorization request.
GoogleAuthorizationCodeFlow flow =
new GoogleAuthorizationCodeFlow.Builder(
HTTP_TRANSPORT, JSON_FACTORY, clientSecrets, SCOPES)
.setDataStoreFactory(DATA_STORE_FACTORY)
.setAccessType("offline")
.build();
Credential credential = new AuthorizationCodeInstalledApp(
flow, new LocalServerReceiver()).authorize("user");
System.out.println(
"Credentials saved to " + DATA_STORE_DIR.getAbsolutePath());
return credential;
}
/**
* Build and return an authorized Admin SDK Directory client service.
* #return an authorized Directory client service
* #throws IOException
*/
public static Directory getDirectoryService() throws IOException {
Credential credential = authorize();
return new Directory.Builder(
HTTP_TRANSPORT, JSON_FACTORY, credential)
.setApplicationName(APPLICATION_NAME)
.build();
}
public static void main(String[] args) throws IOException {
// Build a new authorized API client service.
Directory service = getDirectoryService();
// Print the first 10 users in the domain.
Users result = service.users().list().setCustomer("my_customer").setOrderBy("email").execute();
List<User> users = result.getUsers();
if (users == null || users.size() == 0) {
System.out.println("No users found.");
} else {
for (User user : users) {
//This is where I tried to delete the users
//I have also tried using a normal for loop and nothing changes
that
System.out.println();
}
}
}
After reading everything I could find on this that google had to offer I finally figure it out.... I think. I am going to explain it here and have this as the answer because it worked; however, if I am doing something wrong then please tell me. Anyway, here is what I did:
So first thing's first. Every action (as far as I could tell) goes through http as a URL coupled with a command. This means in order for anything to happen you have to have a transport (given by the HttpTransport class) and a factory (given by the HttpRequestFactory class) to create the HttpRequest object that holds the action/command.
The request we will be making is the DELETE request shown here under "Delete a user account"
This can all be done by doing something like this:
HttpTransport HTTP_TRANSPORT = GoogleNetHttpTransport.newTrustedTransport();
HttpRequestFactory HTTP_REQUEST_FACTORY = HTTP_TRANSPORT.createRequestFactory();
HttpRequest deleteRequest = HTTP_REQUEST_FACTORY.buildDeleteRequest(new GenericUrl("https://www.googleapis.com/admin/directory/v1/users/userkey"));
BUT WAIT! We are missing a very important key element here. We have to supply the Factory with the correct credentials to mark the header. Basically it is to tell google that we are able to delete the user. So how do we do that?
First we must set the scope, what we want access to. Our scope is ADMIN_DIRECTORY_USER. Set the scope like this: (MAKE SURE YOU DELETE THE FILE IN THE .credentials DIRECTORY IF YOU HAVE ALREADY RAN THIS PROGRAM!!!!)
List<String> SCOPES = Arrays.asList(DirectoryScopes.ADMIN_DIRECTORY_USER);
Next we need to have a credentials object. This can be done by using the method google gives us in their quickstart (the authorize method). To give the credentials to our factory we simply edit the line above by passing it the credentials object:
HttpRequestFactory HTTP_REQUEST_FACTORY = HTTP_TRANSPORT.createRequestFactory(credentials);
Note: do not pass it a HttpRequestInitializer from the credentials.getRequestInitializer() method as this is null (At least for me, this could be with just the way I am doing it but I rather not try it).
Here I will attach my code to show you a completed version of this:
import com.google.api.client.auth.oauth2.Credential;
import com.google.api.client.extensions.java6.auth.oauth2.AuthorizationCodeInstalledApp;
import com.google.api.client.extensions.jetty.auth.oauth2.LocalServerReceiver;
import com.google.api.client.googleapis.auth.oauth2.GoogleAuthorizationCodeFlow;
import com.google.api.client.googleapis.auth.oauth2.GoogleClientSecrets;
import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport;
import com.google.api.client.http.GenericUrl;
import com.google.api.client.http.HttpRequest;
import com.google.api.client.http.HttpRequestFactory;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.json.jackson2.JacksonFactory;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.util.store.FileDataStoreFactory;
import com.google.api.services.admin.directory.DirectoryScopes;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.List;
public class Quickstart {
/** Application name. */
private static final String APPLICATION_NAME = "Deleting user example";
/** Directory to store user credentials for this application. */
private static final java.io.File DATA_STORE_DIR = new java.io.File(System.getProperty("user.home"), ".credentials/admin-directory_v1-java-quickstart");
/** Global instance of the {#link FileDataStoreFactory}. */
private static FileDataStoreFactory DATA_STORE_FACTORY;
/** Global instance of the JSON factory. */
private static final JsonFactory JSON_FACTORY = JacksonFactory.getDefaultInstance();
/** Global instance of the HTTP transport. */
private static HttpTransport HTTP_TRANSPORT;
//This creates the factory that is used for the user made requests
private static HttpRequestFactory HTTP_REQUEST_FACTORY;
//This is the credentials for the entire application
private static Credential credential;
/** Global instance of the scopes required by this quickstart.
*
* If modifying these scopes, delete your previously saved credentials
* at ~/.credentials/admin-directory_v1-java-quickstart
*/
private static final List<String> SCOPES = Arrays.asList(DirectoryScopes.ADMIN_DIRECTORY_USER);
static {
try {
HTTP_TRANSPORT = GoogleNetHttpTransport.newTrustedTransport();
DATA_STORE_FACTORY = new FileDataStoreFactory(DATA_STORE_DIR);
} catch (Throwable t) {
t.printStackTrace();
System.exit(1);
}
}
/**
* Creates an authorized Credential object.
* #return an authorized Credential object.
* #throws IOException
*/
public static Credential authorize() throws IOException {
// Load client secrets.
/* This does not work as of now
InputStream in = Quickstart.class.getResourceAsStream("src/resources/client_secret.json");
*/
InputStream in = new FileInputStream("src/resources/client_secret.json");
GoogleClientSecrets clientSecrets = GoogleClientSecrets.load(JSON_FACTORY, new InputStreamReader(in));
// Build flow and trigger user authorization request.
GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(HTTP_TRANSPORT, JSON_FACTORY, clientSecrets, SCOPES).setDataStoreFactory(DATA_STORE_FACTORY).setAccessType("offline").build();
Credential credential = new AuthorizationCodeInstalledApp(flow, new LocalServerReceiver()).authorize("user");
System.out.println("Credentials saved to " + DATA_STORE_DIR.getAbsolutePath());
return credential;
}
public static void main(String[] args) throws IOException {
System.out.println("Deleting user with email");
credential = authorize();
HTTP_REQUEST_FACTORY = HTTP_TRANSPORT.createRequestFactory(credential);
HttpRequest deleteRequest = HTTP_REQUEST_FACTORY.buildDeleteRequest(new GenericUrl("https://www.googleapis.com/admin/directory/v1/users/REPLACEMEWITHEMAILORUSERKEY"));
deleteRequest.execute();
}
}

How to authenticate a service account without download for the Google Cloud Java SDK (not on App Engine)

I am trying to create a service account key programmatically in Java with the Google Cloud SDK, for an application not running on App/Compute engine. This question is similar to mine, but it is running on App engine, so I cannot use the same code as it uses classes from the App Engine API.
The relevant code is below. My issue is that AppIdentityCredential is part of the AppEngine API and thus cannot be used here. What can I pass in as a parameter instead? The third parameter in the new Builder() method takes in an HttpRequestInitializer, but I don't understand what implementation of this interface I should pass in. Any help is appreciated.
import com.google.api.services.iam.v1.Iam;
import com.google.api.services.iam.v1.model.CreateServiceAccountKeyRequest;
import com.google.api.services.iam.v1.model.ServiceAccountKey;
AppIdentityCredential credential = new AppIdentityCredential(
Arrays.asList("https://www.googleapis.com/auth/cloud-platform"));
Iam iam = new Iam.Builder(httpTransport, JSON_FACTORY,credential)
.setApplicationName(APPLICATION_NAME).build();
ServiceAccountKey key = iam.projects().serviceAccounts().keys()
.create(SERVICE_ACCOUNT_RESOURCE_NAME, new CreateServiceAccountKeyRequest()).execute();
You can use Application Default Credentials which will allow you to use the same code to fetch the credentials based on the environment where the application is running.
For example, it lets you use your gcloud account credentials when you're developing on your system. When the code runs on Google Compute Engine or Google App Engine, the code will automatically use the associated service account credentials for authentication in the APIs. You can also override it using GOOGLE_APPLICATION_CREDENTIALS environment variable if required to load the credentials from a JSON file instead.
Here is a working example which creates a new key for an existing service account and prints it.
import com.google.api.client.googleapis.auth.oauth2.GoogleCredential;
import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.jackson2.JacksonFactory;
import com.google.api.services.iam.v1.Iam;
import com.google.api.services.iam.v1.IamScopes;
import com.google.api.services.iam.v1.model.CreateServiceAccountKeyRequest;
import com.google.api.services.iam.v1.model.ServiceAccountKey;
import java.io.IOException;
import java.security.GeneralSecurityException;
import java.util.ArrayList;
import java.util.List;
public class IamDemo {
/** Name of the application. */
private static final String APPLICATION_NAME = "IamDemoJava";
/** Project Name. */
private static final String PROJECT_NAME = "MY_PROJECT_NAME";
/** Name of the service account to create a new key for. */
private static final String SERVICE_ACCOUNT_NAME = "dummy-sa";
/** Full email address of the service account. */
private static final String SERVICE_ACCOUNT_EMAIL =
SERVICE_ACCOUNT_NAME + "#" + PROJECT_NAME + ".iam.gserviceaccount.com";
/** Full service account resource string expected by the IAM API. */
private static final String SERVICE_ACCOUNT_RESOURCE_NAME =
"projects/" + PROJECT_NAME + "/serviceAccounts/" + SERVICE_ACCOUNT_EMAIL;
/** Global instance of the HTTP transport. */
private static HttpTransport httpTransport;
/** Global instance of the JSON factory. */
private static final JsonFactory JSON_FACTORY = JacksonFactory.getDefaultInstance();
public static void main() throws IOException, GeneralSecurityException {
Iam iam = initIam();
ServiceAccountKey key = createServiceAccountKey(iam);
// Print the key
System.out.println(key.toString());
}
private static Iam initIam() throws IOException, GeneralSecurityException {
httpTransport = GoogleNetHttpTransport.newTrustedTransport();
// Authenticate using Google Application Default Credentials.
GoogleCredential credential = GoogleCredential.getApplicationDefault();
if (credential.createScopedRequired()) {
List<String> scopes = new ArrayList<>();
// Enable full Cloud Platform scope.
scopes.add(IamScopes.CLOUD_PLATFORM);
credential = credential.createScoped(scopes);
}
// Create IAM API object associated with the authenticated transport.
return new Iam.Builder(httpTransport, JSON_FACTORY, credential)
.setApplicationName(APPLICATION_NAME)
.build();
}
private static ServiceAccountKey createServiceAccountKey(Iam iam)
throws IOException, GeneralSecurityException {
CreateServiceAccountKeyRequest request = new CreateServiceAccountKeyRequest();
// Customize the request parameters if needed
return iam.projects()
.serviceAccounts()
.keys()
.create(SERVICE_ACCOUNT_RESOURCE_NAME, request)
.execute();
}
}

Making own queries Google Analytics (Java)

I am trying to implement the google analytics library in a website in order to make my own queries and obtain some kind of data to manage them afterwards.
I have followed the example and everything works fine. However, I am only able to code the example query (visitors in last week). I've read many information and documentation about that and I'm still having the same issue.
I'm sure there must be a way to accomplish that, but actually I'm not able to code anything to make my own queries.
The code is (I'm using maven):
import com.google.api.client.googleapis.auth.oauth2.GoogleCredential;
import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.gson.GsonFactory;
import com.google.api.services.analytics.Analytics;
import com.google.api.services.analytics.AnalyticsScopes;
import com.google.api.services.analytics.model.Accounts;
import com.google.api.services.analytics.model.GaData;
import com.google.api.services.analytics.model.Profiles;
import com.google.api.services.analytics.model.Webproperties;
import java.io.File;
import java.io.IOException;
/**
* A simple example of how to access the Google Analytics API using a service
* account.
*/
public class test {
private static final String APPLICATION_NAME = "example";
private static final JsonFactory JSON_FACTORY = GsonFactory.getDefaultInstance();
private static final String KEY_FILE_LOCATION = //route to p.12 file;
private static final String SERVICE_ACCOUNT_EMAIL = //mail example;
public static void main(String[] args) {
try {
Analytics analytics = initializeAnalytics();
String profile = getFirstProfileId(analytics);
System.out.println("First Profile Id: " + profile);
printResults(getResults(analytics, profile));
} catch (Exception e) {
e.printStackTrace();
}
}
private static Analytics initializeAnalytics() throws Exception {
// Initializes an authorized analytics service object.
// Construct a GoogleCredential object with the service account email
// and p12 file downloaded from the developer console.
HttpTransport httpTransport = GoogleNetHttpTransport.newTrustedTransport();
GoogleCredential credential = new GoogleCredential.Builder()
.setTransport(httpTransport)
.setJsonFactory(JSON_FACTORY)
.setServiceAccountId(SERVICE_ACCOUNT_EMAIL)
.setServiceAccountPrivateKeyFromP12File(new File(KEY_FILE_LOCATION))
.setServiceAccountScopes(AnalyticsScopes.all())
.build();
// Construct the Analytics service object.
return new Analytics.Builder(httpTransport, JSON_FACTORY, credential)
.setApplicationName(APPLICATION_NAME).build();
}
private static String getFirstProfileId(Analytics analytics) throws IOException {
// Get the first view (profile) ID for the authorized user.
String profileId = null;
// Query for the list of all accounts associated with the service account.
Accounts accounts = analytics.management().accounts().list().execute();
if (accounts.getItems().isEmpty()) {
System.err.println("No accounts found");
} else {
String firstAccountId = accounts.getItems().get(0).getId();
// Query for the list of properties associated with the first account.
Webproperties properties = analytics.management().webproperties()
.list(firstAccountId).execute();
if (properties.getItems().isEmpty()) {
System.err.println("No Webproperties found");
} else {
String firstWebpropertyId = properties.getItems().get(0).getId();
// Query for the list views (profiles) associated with the property.
Profiles profiles = analytics.management().profiles()
.list(firstAccountId, firstWebpropertyId).execute();
if (profiles.getItems().isEmpty()) {
System.err.println("No views (profiles) found");
} else {
// Return the first (view) profile associated with the property.
profileId = profiles.getItems().get(0).getId();
}
}
}
return profileId;
}
private static GaData getResults(Analytics analytics, String profileId) throws IOException {
// Query the Core Reporting API for the number of sessions
// in the past seven days.
return analytics.data().ga()
.get("ga:" + profileId, "7daysAgo", "today", "ga:sessions")
.execute();
}
private static void printResults(GaData results) {
// Parse the response from the Core Reporting API for
// the profile name and number of sessions.
if (results != null && !results.getRows().isEmpty()) {
System.out.println("View (Profile) Name: "
+ results.getProfileInfo().getProfileName());
System.out.println("Total Sessions: " + results.getRows().get(0).get(0));
} else {
System.out.println("No results found");
}
}
}
Note that the code that makes the queries is:
private static GaData getResults(Analytics analytics, String profileId) throws IOException {
// Query the Core Reporting API for the number of sessions
// in the past seven days.
return analytics.data().ga()
.get("ga:" + profileId, "7daysAgo", "today", "ga:sessions")
.execute();
}
The problem is: how I set dimensions of my queries using this code?
This query works (without dimensions):
private static GaData getMobileTraffic(Analytics analytics, String profileId) throws IOException {
return analytics.data().ga()
.get("ga:" + profileId, "30daysAgo", "today", "ga:sessions, ga:pageviews, ga:sessionDuration")
.execute();
}
This one doesn't work (with dimensions):
private static GaData getMobileTraffic(Analytics analytics, String profileId) throws IOException {
return analytics.data().ga()
.get("ga:" + profileId, "30daysAgo", "today", "ga:sessions, ga:pageviews, ga:sessionDuration",**"ga:userType"**)
.execute();
}
I would appreciate any help. Thanks a lot!
Well, seems that I've finally solved my issue. I answer myself in order to help someone with similar problems and hope it works for them too.
The answer is simply, the documentation about Google Analytics is a bit confusing, but if someone wants to add dimensions, metrics (or edit the example query from Google analytics) just need to add the code in the following link:
https://developers.google.com/analytics/devguides/reporting/core/v3/coreDevguide
Just adding this code just following the query example (if you want to add dimensions):
setDimensions("ga:userType")
So, the final code will be:
private static GaData getMobileTraffic(Analytics analytics, String profileId) throws IOException {
return analytics.data().ga()
.get("ga:" + profileId, "30daysAgo", "today", "ga:sessions, ga:pageviews, ga:sessionDuration").setDimensions("ga:userType")
.execute();
}
Note that in the main code, you need to add the print function, just like this:
public static void main(String[] args) {
try {
Analytics analytics = initializeAnalytics();
printMobileTraffic(getMobileTraffic(analytics, profile));
} catch (Exception e) {
e.printStackTrace();
}
}

Insert webProperty with Java's "Google APIs Client Library"

I am trying to create a webProperty using the Java client but without success (i have access to the beta testing group that allows the creation of webProperties). This is my code (it is actually a groovy class):
package com.creditpal.services
import com.google.api.client.auth.oauth2.Credential
import com.google.api.client.googleapis.auth.oauth2.GoogleCredential
import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport
import com.google.api.client.googleapis.json.GoogleJsonResponseException
import com.google.api.client.http.HttpTransport
import com.google.api.client.json.JsonFactory
import com.google.api.client.json.jackson2.JacksonFactory
import com.google.api.services.analytics.Analytics
import com.google.api.services.analytics.AnalyticsScopes
import com.google.api.services.analytics.model.Webproperty
import org.apache.commons.io.FileUtils
import org.slf4j.Logger
import org.slf4j.LoggerFactory
import org.springframework.stereotype.Service
import uk.co.futureroute.lib.logging.annotation.MethodLogging
#Service
#MethodLogging
class GoogleAnalyticsServiceImpl implements GoogleAnalyticsService {
private static final String APPLICATION_NAME = "##THE NAME##"
private static final String EMAIL_ADDRESS = "##THE EMAIL ADDRESS##"
private static Logger logger = LoggerFactory.getLogger(GoogleAnalyticsServiceImpl.class)
private JsonFactory jsonFactory
private HttpTransport httpTransport
private Analytics analytics
public GoogleAnalyticsServiceImpl(){
httpTransport = GoogleNetHttpTransport.newTrustedTransport()
jsonFactory = JacksonFactory.getDefaultInstance()
initializeAnalytics()
}
#Override
public Webproperty insertWebProperty(String name, String websiteUrl) throws GoogleJsonResponseException {
Webproperty webProperty = new Webproperty(
websiteUrl: websiteUrl,
name: name
)
try {
return analytics.management().webproperties().insert("##ACCOUNT_ID##", webProperty).execute()
} catch (GoogleJsonResponseException e) {
logger.error("There was a google Analytics service error: "
+ e.getDetails().getCode() + " : "
+ e.getDetails().getMessage());
throw e
}
}
private void initializeAnalytics() throws Exception {
analytics = new Analytics.Builder(httpTransport, jsonFactory, authorize()).setApplicationName(
APPLICATION_NAME).build();
}
private Credential authorize() throws Exception {
final File googlePrivateKey = File.createTempFile("googlePrivateKey", ".p12")
googlePrivateKey.deleteOnExit()
FileUtils.copyInputStreamToFile(this.class.classLoader.getResourceAsStream("resources/analytics.p12"), googlePrivateKey)
return new GoogleCredential.Builder()
.setTransport(httpTransport)
.setServiceAccountId(EMAIL_ADDRESS)
.setServiceAccountPrivateKeyFromP12File(googlePrivateKey)
.setServiceAccountScopes(Collections.singleton(AnalyticsScopes.ANALYTICS_MANAGE_USERS))
.build()
}
}
This is a Spring service and when this object is created i dont get any exceptions. The problem is when trying to call the insertWebProperty method, there i get this:
java.lang.NullPointerException: null
at com.google.api.client.json.webtoken.JsonWebSignature.signUsingRsaSha256(JsonWebSignature.java:498) ~[google-http-client-1.19.0.jar:1.19.0]
at com.google.api.client.googleapis.auth.oauth2.GoogleCredential.executeRefreshToken(GoogleCredential.java:378) ~[google-api-client-1.19.0.jar:1.19.0]
at com.google.api.client.auth.oauth2.Credential.refreshToken(Credential.java:489) ~[google-oauth-client-1.19.0.jar:1.19.0]
at com.google.api.client.auth.oauth2.Credential.intercept(Credential.java:217) ~[google-oauth-client-1.19.0.jar:1.19.0]
at com.google.api.client.http.HttpRequest.execute(HttpRequest.java:859) ~[google-http-client-1.19.0.jar:1.19.0]
at com.google.api.client.googleapis.services.AbstractGoogleClientRequest.executeUnparsed(AbstractGoogleClientRequest.java:410) ~[google-api-client-1.19.0.jar:1.19.0]
at com.google.api.client.googleapis.services.AbstractGoogleClientRequest.executeUnparsed(AbstractGoogleClientRequest.java:343) ~[google-api-client-1.19.0.jar:1.19.0]
at com.google.api.client.googleapis.services.AbstractGoogleClientRequest.execute(AbstractGoogleClientRequest.java:460) ~[google-api-client-1.19.0.jar:1.19.0]
at com.google.api.client.googleapis.services.AbstractGoogleClientRequest$execute.call(Unknown Source) ~[na:na]
Anyone any idea?? Thanks in advance!

Google Maps API - 'Method getUrl() is undefined'

I have no idea on what's happen about the error, please help me.
The method getUrl() is undefined for the type HttpRequest
The method createRequestFactory(new HttpRequestInitializer(){}) is undefined for the type HttpTransport
The constructor JsonHttpParser(JacksonFactory) is undefined
Am I missing any libraries?
thank you
import com.google.api.client.googleapis.GoogleHeaders;
import com.google.api.client.http.GenericUrl;
import com.google.api.client.http.HttpRequest;
import com.google.api.client.http.HttpRequestFactory;
import com.google.api.client.http.HttpRequestInitializer;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.http.json.JsonHttpParser;
import com.google.api.client.json.jackson.JacksonFactory;
public class GooglePlaces {
/** Global instance of the HTTP transport. */
private static final HttpTransport HTTP_TRANSPORT = new NetHttpTransport();
// Google API Key
private static final String API_KEY = "my-api-key";
// Google Places serach url's
private static final String PLACES_SEARCH_URL = "https://maps.googleapis.com/maps/api/place/search/json?";
private static final String PLACES_TEXT_SEARCH_URL = "https://maps.googleapis.com/maps/api/place/search/json?";
private static final String PLACES_DETAILS_URL = "https://maps.googleapis.com/maps/api/place/details/json?";
private double _latitude;
private double _longitude;
private double _radius;
/**
* Searching places
* #param latitude - latitude of place
* #params longitude - longitude of place
* #param radius - radius of searchable area
* #param types - type of place to search
* #return list of places
* */
public PlacesList search(double latitude, double longitude, double radius, String types)
throws Exception {
this._latitude = latitude;
this._longitude = longitude;
this._radius = radius;
try {
HttpRequestFactory httpRequestFactory = createRequestFactory(HTTP_TRANSPORT);
HttpRequest request = httpRequestFactory
.buildGetRequest(new GenericUrl(PLACES_SEARCH_URL));
request.getUrl().put("key", API_KEY);
request.getUrl().put("location", _latitude + "," + _longitude);
request.getUrl().put("radius", _radius); // in meters
request.getUrl().put("sensor", "false");
if(types != null)
request.getUrl().put("types", types);
PlacesList list = request.execute().parseAs(PlacesList.class);
// Check log cat for places response status
Log.d("Places Status", "" + list.status);
return list;
} catch (HttpResponseException e) {
Log.e("Error:", e.getMessage());
return null;
}
}
/**
* Searching single place full details
* #param refrence - reference id of place
* - which you will get in search api request
* */
public PlaceDetails getPlaceDetails(String reference) throws Exception {
try {
HttpRequestFactory httpRequestFactory = createRequestFactory(HTTP_TRANSPORT);
HttpRequest request = httpRequestFactory
.buildGetRequest(new GenericUrl(PLACES_DETAILS_URL));
request.getUrl().put("key", API_KEY);
request.getUrl().put("reference", reference);
request.getUrl().put("sensor", "false");
PlaceDetails place = request.execute().parseAs(PlaceDetails.class);
return place;
} catch (HttpResponseException e) {
Log.e("Error in Perform Details", e.getMessage());
throw e;
}
}
/**
* Creating http request Factory
* */
public static HttpRequestFactory createRequestFactory(
final HttpTransport transport) {
return transport.createRequestFactory(new HttpRequestInitializer() {
public void initialize(HttpRequest request) {
GoogleHeaders headers = new GoogleHeaders();
headers.setApplicationName("AndroidHive-Places-Test");
request.setHeaders(headers);
JsonHttpParser parser = new JsonHttpParser(new JacksonFactory());
request.addParser(parser);
}
});
}
}
This is pretty old. But in case someone gets here with a similar problem, here is what worked for me.
It seems I had some conflicting dependencies:
//implementation("com.google.api.client:google-api-client-json:1.2.3-alpha")
//implementation("com.google.api.client:google-api-client-util:1.2.3-alpha")
implementation("com.google.http-client:google-http-client:1.40.0")
implementation("com.google.http-client:google-http-client-jackson2:1.40.0")
When I removed the first two, it worked.
In my investigations, I saw that the jar file google-http-client-1.40.0-sources.jar had the missing method (on Intellij, I used the command "go to declaration or usage"), while in the HttpTransport.class file decompiled from External Libraries did not have it.

Categories

Resources