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.
Related
I need an example in java to be able to consume an API using OAuth 1.0 to generate the token :
NB: i have only those informations (the consumerKey, ConsumerSecret, AccesToken and the acessTokenSecret).
I have searched int the internet but I have not found a result that can help me.
I'm looking for the same but, actually, I have an example provided by the admins of the API that I'm trying to consume.
Since no one replied to this thread, I'll paste the mentioned example here, hoping it could help in some way.
Also, if someone can give me a hand, understand the code and explain how to implement it, it would be great.
package com.example.entities;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.MultivaluedMap;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.WebResource;
import com.sun.jersey.api.client.filter.LoggingFilter;
import com.sun.jersey.oauth.client.OAuthClientFilter;
import com.sun.jersey.oauth.signature.HMAC_SHA1;
import com.sun.jersey.oauth.signature.OAuthParameters;
import com.sun.jersey.oauth.signature.OAuthSecrets;
public class SSRestServiceClient {
/*
* private constructor to avoid construction of object.
*/
private SSRestServiceClient(String url, String consumerKey, String consumerSecret, int timeoutSeconds) {
OAuthParameters params = new OAuthParameters().signatureMethod(HMAC_SHA1.NAME).consumerKey(consumerKey).version(OAUTH_VERSION);
OAuthSecrets secrets = new OAuthSecrets().consumerSecret(consumerSecret);
Client httpClient = Client.create();
httpClient.setConnectTimeout(timeoutSeconds * 1000);
httpClient.setReadTimeout(timeoutSeconds * 1000);
OAuthClientFilter filter = new OAuthClientFilter(httpClient.getProviders(), params, secrets);
httpClient.addFilter(filter);
httpClient.addFilter(new LoggingFilter());
this.consumerKey = consumerKey;
this.webResource = httpClient.resource(url);
}
/*
* Creates instance of the Client class, returns existing instance if it's already created.
*/
public static synchronized SSRestServiceClient getInstance(String url, String consumerKey, String consumerSecret) {
return getInstance(url, consumerKey, consumerSecret, 0);
}
/*
* Creates instance of the Client class, returns existing instance if it's already created.
*/
public static synchronized SSRestServiceClient getInstance(String url, String consumerKey,String consumerSecret, int timeoutSeconds) {
if (client == null || client.getConsumerKey() == null || !client.getConsumerKey().equals(consumerKey)) {
if (timeoutSeconds != 0 && timeoutSeconds < ONE_MINUTE) {
timeoutSeconds = ONE_MINUTE;
}
client = new SSRestServiceClient(url, consumerKey, consumerSecret, timeoutSeconds);
}
return client;
}
/*
* Return a list of all active source cities.
*/
#Override
public CityList getAllSources() {
return webResource.path(GET_ALL_SOURCES).get(CityList.class);
}
}
I'm new with CMIS and Alfresco and I got this error when in try to connect to my Alfresco's repository using AtomPUB binding. I have no idea about the source of my problem. Is it unless a functionality ? Is it my Credential ?
When I install it, I choose only :
- Alfresco community
- Solr4
How should I do if I want to use web services ? Should I install a specific plugin in my Alfresco ?
I got with error :
SLF4J: Class path contains multiple SLF4J bindings.
SLF4J: Found binding in [jar:file:/C:/Users/ME%2ME/.m2/repository/org/slf4j/slf4j-simple/1.7.9/slf4j-simple-1.7.9.jar!/org/slf4j/impl/StaticLoggerBinder.class]
SLF4J: Found binding in [jar:file:/C:/Users/ME%2ME/.m2/repository/ch/qos/logback/logback-classic/1.1.3/logback-classic-1.1.3.jar!/org/slf4j/impl/StaticLoggerBinder.class]
SLF4J: See http://www.slf4j.org/codes.html#multiple_bindings for an explanation.
SLF4J: Actual binding is of type [org.slf4j.impl.SimpleLoggerFactory]
Exception in thread "main" org.apache.chemistry.opencmis.commons.exceptions.CmisObjectNotFoundException: Introuvable
at org.apache.chemistry.opencmis.client.bindings.spi.atompub.AbstractAtomPubService.convertStatusCode(AbstractAtomPubService.java:499)
at org.apache.chemistry.opencmis.client.bindings.spi.atompub.AbstractAtomPubService.read(AbstractAtomPubService.java:701)
at org.apache.chemistry.opencmis.client.bindings.spi.atompub.AbstractAtomPubService.getRepositoriesInternal(AbstractAtomPubService.java:873)
at org.apache.chemistry.opencmis.client.bindings.spi.atompub.RepositoryServiceImpl.getRepositoryInfos(RepositoryServiceImpl.java:66)
at org.apache.chemistry.opencmis.client.bindings.impl.RepositoryServiceImpl.getRepositoryInfos(RepositoryServiceImpl.java:92)
at org.apache.chemistry.opencmis.client.runtime.SessionFactoryImpl.getRepositories(SessionFactoryImpl.java:120)
at org.apache.chemistry.opencmis.client.runtime.SessionFactoryImpl.getRepositories(SessionFactoryImpl.java:107)
at fr.omb.TestOMB.connect(TestOMB.java:160)
at fr.omb.TestOMB.main(TestOMB.java:35)
My code :
package fr.omb;
import java.io.ByteArrayInputStream;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import org.apache.chemistry.opencmis.client.api.CmisObject;
import org.apache.chemistry.opencmis.client.api.Document;
import org.apache.chemistry.opencmis.client.api.Folder;
import org.apache.chemistry.opencmis.client.api.Repository;
import org.apache.chemistry.opencmis.client.api.Session;
import org.apache.chemistry.opencmis.client.api.SessionFactory;
import org.apache.chemistry.opencmis.client.runtime.SessionFactoryImpl;
import org.apache.chemistry.opencmis.commons.PropertyIds;
import org.apache.chemistry.opencmis.commons.SessionParameter;
import org.apache.chemistry.opencmis.commons.data.ContentStream;
import org.apache.chemistry.opencmis.commons.enums.BaseTypeId;
import org.apache.chemistry.opencmis.commons.enums.BindingType;
import org.apache.chemistry.opencmis.commons.enums.UnfileObject;
import org.apache.chemistry.opencmis.commons.enums.VersioningState;
import org.apache.chemistry.opencmis.commons.exceptions.CmisObjectNotFoundException;
import org.apache.commons.lang3.StringUtils;
public class TestOMB {
private static Session session;
private static final String ALFRSCO_ATOMPUB_URL = "http://localhost:8080/alfresco/service/cmis";
private static final String TEST_FOLDER_NAME = "chemistryTestFolder";
private static final String TEST_DOCUMENT_NAME_1 = "chemistryTest1.txt";
private static final String TEST_DOCUMENT_NAME_2 = "chemistryTest2.txt";
public static void main(String[] args) {
Folder root = connect();
cleanup(root, TEST_FOLDER_NAME);
Folder newFolder = createFolder(root, TEST_FOLDER_NAME);
createDocument(newFolder, TEST_DOCUMENT_NAME_1);
createDocument(newFolder, TEST_DOCUMENT_NAME_2);
System.out.println("+++ List Folder +++");
listFolder(0, newFolder);
DeleteDocument(newFolder, "/" + TEST_DOCUMENT_NAME_2);
System.out.println("+++ List Folder +++");
listFolder(0, newFolder);
}
/**
* Clean up test folder before executing test
*
* #param target
* #param delFolderName
*/
private static void cleanup(Folder target, String delFolderName) {
try {
CmisObject object = session.getObjectByPath(target.getPath() + delFolderName);
Folder delFolder = (Folder) object;
delFolder.deleteTree(true, UnfileObject.DELETE, true);
} catch (CmisObjectNotFoundException e) {
System.err.println("No need to clean up.");
}
}
/**
*
* #param target
*/
private static void listFolder(int depth, Folder target) {
String indent = StringUtils.repeat("\t", depth);
for (Iterator<CmisObject> it = target.getChildren().iterator(); it.hasNext();) {
CmisObject o = it.next();
if (BaseTypeId.CMIS_DOCUMENT.equals(o.getBaseTypeId())) {
System.out.println(indent + "[Docment] " + o.getName());
} else if (BaseTypeId.CMIS_FOLDER.equals(o.getBaseTypeId())) {
System.out.println(indent + "[Folder] " + o.getName());
listFolder(++depth, (Folder) o);
}
}
}
/**
* Delete test document
*
* #param target
* #param delDocName
*/
private static void DeleteDocument(Folder target, String delDocName) {
try {
CmisObject object = session.getObjectByPath(target.getPath() + delDocName);
Document delDoc = (Document) object;
delDoc.delete(true);
} catch (CmisObjectNotFoundException e) {
System.err.println("Document is not found: " + delDocName);
}
}
/**
* Create test document with content
*
* #param target
* #param newDocName
*/
private static void createDocument(Folder target, String newDocName) {
Map<String, String> props = new HashMap<String, String>();
props.put(PropertyIds.OBJECT_TYPE_ID, "cmis:document");
props.put(PropertyIds.NAME, newDocName);
System.out.println("This is a test document: " + newDocName);
String content = "aegif Mind Share Leader Generating New Paradigms by aegif corporation.";
byte[] buf = null;
try {
buf = content.getBytes("UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
ByteArrayInputStream input = new ByteArrayInputStream(buf);
ContentStream contentStream = session.getObjectFactory().createContentStream(newDocName, buf.length,
"text/plain; charset=UTF-8", input);
target.createDocument(props, contentStream, VersioningState.MAJOR);
}
/**
* Create test folder directly under target folder
*
* #param target
* #param createFolderName
* #return newly created folder
*/
private static Folder createFolder(Folder target, String newFolderName) {
Map<String, String> props = new HashMap<String, String>();
props.put(PropertyIds.OBJECT_TYPE_ID, "cmis:folder");
props.put(PropertyIds.NAME, newFolderName);
Folder newFolder = target.createFolder(props);
return newFolder;
}
/**
* Connect to alfresco repository
*
* #return root folder object
*/
private static Folder connect() {
SessionFactory sessionFactory = SessionFactoryImpl.newInstance();
Map<String, String> parameters = new HashMap<String, String>();
// User credentials.
parameters.put(SessionParameter.USER, "myuser");
parameters.put(SessionParameter.PASSWORD, "mypassword");
// Connection settings.
parameters.put(SessionParameter.BINDING_TYPE, BindingType.ATOMPUB.value());
parameters.put(SessionParameter.ATOMPUB_URL, ALFRSCO_ATOMPUB_URL);
parameters.put(SessionParameter.AUTH_HTTP_BASIC, "true");
parameters.put(SessionParameter.COOKIES, "true");
parameters.put(SessionParameter.OBJECT_FACTORY_CLASS,
"org.alfresco.cmis.client.impl.AlfrescoObjectFactoryImpl");
// Create session.
// Alfresco only provides one repository.
Repository repository = sessionFactory.getRepositories(parameters).get(0);
Session session = repository.createSession();
return session.getRootFolder();
}
}
I found the solution, it's because of Alfresco's version. Since the V4.x the url of the AtomPUB is http://localhost:8080/alfresco/cmisatom.
https://community.alfresco.com/docs/DOC-5527-cmis
For Alfresco 3.x : http://[host]:[port]/alfresco/service/cmis
For Alfresco 4.0.x, Alfresco 4.1.x and Alfresco 4.2.a-c: http://[host]:[port]/alfresco/cmisatom
For Alfresco 4.2.d-f, Alfresco 5.0 and Alfresco 5.1: http://[host]:[port]/alfresco/api/-default-/public/cmis/versions/1.0/atom
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();
}
}
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).
I am looking for a simple java function that can accept an address and return the longitude and latitude coordinates for that address. Based on my research this is what i found thus far:
I am abit unsure how to implements this. I am not sure what order i will need to call the different methods.
E.g. would i have to do this? :
String address = 'Some Place, Venezuela';
Geocoder geo = new Geocoder();
String url = geo.encode(address);
String encodeUrl = geo.urlEncode(url);
GLatLng latLng = geo.decode(encodeUrl);
If there are others that you have used feel free to share it.
/*
*
* ==============================================================================
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package org.wicketstuff.gmap.geocoder;
import java.io.IOException;
import java.io.InputStream;
import java.io.Serializable;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.StringTokenizer;
import org.wicketstuff.gmap.api.GLatLng;
/**
* Geocoder. See: http://www.google.com/apis/maps/documentation/services.html# Geocoding_Direct
*
* #author Thijs Vonk
*/
public class Geocoder implements Serializable
{
private static final long serialVersionUID = 1L;
// Constants
public static final String OUTPUT_CSV = "csv";
public static final String OUTPUT_XML = "xml";
public static final String OUTPUT_KML = "kml";
public static final String OUTPUT_JSON = "json";
private final String output = OUTPUT_CSV;
public Geocoder()
{
}
public GLatLng decode(String response) throws GeocoderException
{
StringTokenizer gLatLng = new StringTokenizer(response, ",");
String status = gLatLng.nextToken();
gLatLng.nextToken(); // skip precision
String latitude = gLatLng.nextToken();
String longitude = gLatLng.nextToken();
if (Integer.parseInt(status) != GeocoderException.G_GEO_SUCCESS)
{
throw new GeocoderException(Integer.parseInt(status));
}
return new GLatLng(Double.parseDouble(latitude), Double.parseDouble(longitude));
}
/**
* builds the google geo-coding url
*
* #param address
* #return
*/
public String encode(final String address)
{
return "http://maps.google.com/maps/geo?q=" + urlEncode(address) + "&output=" + output;
}
/**
* #param address
* #return
* #throws IOException
*/
public GLatLng geocode(final String address) throws IOException
{
InputStream is = invokeService(encode(address));
if (is != null)
{
try
{
String content = org.apache.wicket.util.io.IOUtils.toString(is);
return decode(content);
}
finally
{
is.close();
}
}
return null;
}
/**
* fetches the url content
*
* #param address
* #return
* #throws IOException
*/
protected InputStream invokeService(final String address) throws IOException
{
URL url = new URL(address);
return url.openStream();
}
/**
* url-encode a value
*
* #param value
* #return
*/
private String urlEncode(final String value)
{
try
{
return URLEncoder.encode(value, "UTF-8");
}
catch (UnsupportedEncodingException ex)
{
throw new RuntimeException(ex.getMessage());
}
}
}
If you're using Google Maps API, you need to show a map with your application in order to use the data, as far as I understand their TOS.
Here's an example on GitHub that uses an address verification API from SmartyStreets to verify a US address and get the coordinates. There license restrictions are much more lenient this way. (I work at SmartyStreets and actually wrote this particular example.)
Alternatively, there's a small library for massively-batch geocoding in Java by exoanalytic.