I want to get first and last name of a google account using gdata library. I have the auth token(I take it from android device - send it to my java servlet- then should add an insert into a mysql db with first, last, display name and provider_uid(provider_uid is the form of https://www.google.com/accounts/o8/id?id=AItOawmyn...)).
I used Contacts feed like this(without success):
public String tryGoogleAuthentication(String auth_token){
ContactsService contactsService = new ContactsService("...");
contactsService.setUserToken(auth_token);
//contactsService.setAuthSubToken(auth_token);
ContactFeed feed = null;
try {
feed = contactsService.getFeed(new URL("https://www.google.com/m8/feeds/contacts/" + "someEmail#gmail.com" + "/full?max-results=10000"), ContactFeed.class);
} catch (IOException e) {
e.printStackTrace();
return CONST.GOOGLE_AUTH_INVALID_TOKEN;
} catch (ServiceException e) {
e.printStackTrace();
return CONST.GOOGLE_AUTH_INVALID_TOKEN;
} catch (NullPointerException e) {
e.printStackTrace();
return CONST.GOOGLE_AUTH_INVALID_TOKEN;
}
if (feed == null)
return "";
String externalId = feed.getId();
Person person = feed.getAuthors().get(0);
String email = person.getEmail();
String name = person.getName();
String nameLang = person.getNameLang();
String extensionLocalName = person.getExtensionLocalName();
String uri = person.getUri();
System.out.println("externalId: " + externalId);
System.out.println("email: " + email);
System.out.println("name: " + name);
System.out.println("nameLang: " + nameLang);
System.out.println("extension local name: " + extensionLocalName);
System.out.println("URI: " + uri);
System.out.println(feed.getSelf().getEntries().get(0).getTitle().getPlainText());
return CONST.STATUS_OK;
}
Also,
System.out.println("ID: " + feed.getSelf().getEntries().get(0).getId());
will output:
ID: http://www.google.com/m8/feeds/contacts/someEmail%40gmail.com/base/c....
but I want something like this:
https://www.google.com/accounts/o8/id?id=AItOawmyn...
I need this to insert into an existing data base.
Please note that I want the info only for the account, not for it's contacts.
Thanks,
Alex
Please see this answer from google groups for resolution. The problem is that I cannot access user profile with the auth_token taken from the android because it's a Client Login token, and Client Login does not have a scope for accessing user's profile. I integrated OAUTH login in android like this and with the token returned, I can access user's profile.
Alex.
Related
I'm learning Javamail these days following this website:
http://www.tutorialspoint.com/javamail_api/
I test the sending & added some extra stuff because it was on Android & it worked!
But things have changed completely when I tried to follow receiving email Tutorial which makes me wonder..
Is it possible to make this code :
https://www.tutorialspoint.com/javamail_api/javamail_api_fetching_emails.htm
works on android but using XML interface?!
You can use the following code:
public static void receiveEmail(String pop3Host, String storeType, user, String password) {
try {
//1) get the session object
Properties properties = new Properties();
properties.put("mail.pop3.host", pop3Host);
Session emailSession = Session.getDefaultInstance(properties);
//2) create the POP3 store object and connect with the pop server
POP3Store emailStore = (POP3Store) emailSession.getStore(storeType);
emailStore.connect(user, password);
//3) create the folder object and open it
Folder emailFolder = emailStore.getFolder("INBOX");
emailFolder.open(Folder.READ_ONLY);
//4) retrieve the messages from the folder in an array and print it
Message[] messages = emailFolder.getMessages();
for (int i = 0; i < messages.length; i++) {
Message message = messages[i];
System.out.println("---------------------------------");
System.out.println("Email Number " + (i + 1));
System.out.println("Subject: " + message.getSubject());
System.out.println("From: " + message.getFrom()[0]);
System.out.println("Text: " + message.getContent().toString());
}
//5) close the store and folder objects
emailFolder.close(false);
emailStore.close();
} catch (NoSuchProviderException e) {
e.printStackTrace();
} catch (MessagingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
call your method passing some parameters:
String host = "pop.gmail.com";//change accordingly
String mailStoreType = "pop3";
String username= "example#gmail.com";
String password= "xxxxx";//change accordingly
receiveEmail(host, mailStoreType, username, password);
Source: Steps for receiving the email using JavaMail API
i have a openfire server running on my localhost and i am successfully able to send and receive messages to registered users. however i am not been able to get all users from server. i am logged in with user that doesn't have a administration access. so do i need to give any permission on server side?
The code i am using for getting all users is..
if ( xmpp.getConnection()== null || !xmpp.getConnection().isConnected())
return;
try {
UserSearchManager usm = new UserSearchManager(xmpp.getConnection());
Form searchForm = usm.getSearchForm("search." + xmpp.getConnection().getServiceName());
Form answerForm = searchForm.createAnswerForm();
UserSearch userSearch = new UserSearch();
answerForm.setAnswer("Username", true);
answerForm.setAnswer("search", userName);
ReportedData data = userSearch.sendSearchForm(xmpp.getConnection(), answerForm, "search." + xmpp.getConnection().getServiceName());
for (ReportedData.Row row : data.getRows())
{
arrayList.add(row.getValues("Username").toString());
}
} catch (Exception e) {
e.printStackTrace();
}
i tried some solutions that shows to use Roster class, however that is also not helping me. Can anyone show what i am doing wrong or if i need to give any permission as i am not logged in as admin?
The error i am getting is..
org.jivesoftware.smack.XMPPException$XMPPErrorException: XMPPError: remote-server-not-found
Thanks :)
This is how I am getting all users from openfire
You actually have to pass wildcard(*) for the username
Here's the working code
Utils.getConnection() - my xmpp connection
public static void getAllXmppUsers()
{
try {
UserSearchManager manager = new UserSearchManager(Utils.getConnection());
String searchFormString = "search." + Utils.getConnection().getServiceName();
Log.d("***", "SearchForm: " + searchFormString);
Form searchForm = null;
searchForm = manager.getSearchForm(searchFormString);
Form answerForm = searchForm.createAnswerForm();
UserSearch userSearch = new UserSearch();
answerForm.setAnswer("Username", true);
answerForm.setAnswer("search", "*");
ReportedData results = userSearch.sendSearchForm(Utils.getConnection(), answerForm, searchFormString);
if (results != null) {
List<ReportedData.Row> rows = results.getRows();
for (ReportedData.Row row : rows) {
Log.d("***", "row: " + row.getValues("Username").toString());
}
} else {
Log.d("***", "No result found");
}
} catch (SmackException.NoResponseException e) {
e.printStackTrace();
} catch (XMPPException.XMPPErrorException e) {
e.printStackTrace();
} catch (SmackException.NotConnectedException e) {
e.printStackTrace();
}
}
Try this code. I tweak this code from this answer
UserSearchManager usm= new UserSearchManager(xmpp.getConnection());
Form searchForm = usm.getSearchForm("search." +xmpp.getConnection().getServiceName());
Form answerForm = searchForm.createAnswerForm();
answerForm.setAnswer("Username", true);
answerForm.setAnswer("search", userName);
ReportedData data = usm
.getSearchResults(answerForm, "search." + xmpp.getConnection().getServiceName());
if (data.getRows() != null) {
for (ReportedData.Row row: data.getRows()) {
for (String jid:row.getValues("jid")) {
System.out.println(jid);
}
}
}
Smack is used to create a client. A client is used by one user. A user typically does not have access to all users of the server. Users do have contact lists, or rosters though, where you an add other users.
Receiving:
SignatureDoesNotMatchThe request signature we calculated does not match the signature you provided. Check your AWS Secret Access Key and signing method. Consult the service documentation for details.
With the following:
String associateTag = "example-20";
String awsAccessKeyId = "accessKeyId";
String awsSecretKey = "secretKey";
String endpoint = "webservices.amazon.com";
String uri = "/onca/xml";
String charset = "UTF8";
private String buildQueryString(String keywords) {
Map<String,String> params = new ArrayMap<>();
List<String> pairs = new ArrayList<>();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", Locale.US);
sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
params.put("Service","AWSECommerceService");
params.put("Operation","ItemSearch");
params.put("AWSAccessKeyId",awsAccessKeyId);
params.put("AssociateTag",associateTag);
params.put("SearchIndex","All");
params.put("ResponseGroup","Images,ItemAttributes");
params.put("Timestamp",sdf.format(new Date()));
params.put("Keywords", keywords);
Map<String, String> treeMap = new TreeMap<>(params);
try {
for (Map.Entry<String, String> param : treeMap.entrySet()) {
pairs.add(URLEncoder.encode(param.getKey(), charset) + "=" + URLEncoder.encode(param.getValue(), charset));
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
String queryString = "";
for (int i = 0; i < pairs.size(); i++) {
if (i != 0) {
queryString += "&";
}
queryString += pairs.get(i);
}
Log.d(TAG, "queryString: " + queryString);
return queryString;
}
private String buildSignature(String queryString) {
String hash = "";
try {
String message = "GET\n" + endpoint + "\n" + uri + "\n" + queryString;
Log.d(TAG, "message: " + message);
Mac sha_HMAC = Mac.getInstance("HmacSHA256");
SecretKeySpec secret_key = new SecretKeySpec(awsSecretKey.getBytes(charset), "HmacSHA256");
sha_HMAC.init(secret_key);
hash = Base64.encodeToString(sha_HMAC.doFinal(message.getBytes(charset)), Base64.DEFAULT);
}
catch (Exception e){
System.out.println("Error");
}
return hash;
}
public void searchProducts(String keywords) {
String requestUrl = "";
String queryString = buildQueryString(keywords);
String signature = buildSignature(queryString);
Log.d(TAG, "signature: " + signature);
try {
requestUrl = "http://" + endpoint + uri + "?" + queryString + "&Signature=" + URLEncoder.encode(signature, charset);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
Log.d(TAG, "requestUrl: " + requestUrl);
Ion.with(context)
.load(requestUrl)
.asString()
.setCallback(new FutureCallback<String>() {
#Override
public void onCompleted(Exception e, String result) {
Log.d(TAG, "searchProducts result: " + result);
}
});
}
What could be the problem?
Make sure that your system clock is correct. It will be good idea to sync it using NTP. In the past I have seen signature errors when the time is out of sync.
What I've seen before is that this is normally down to permissions . Check access and secret key is correct and you have adequate permissions.
Changed:
Base64.DEFAULT;
To:
Base64.NO_WRAP;
It's hard to tell from the code. A few things to check:
Make sure the service you want to reach uses SigV2 signing (or query string signing). New services follow version 4 signing standard.
URLEncoder.encode doesn't meet AWS' encoding requirement RFC 3986. You need to apply some fixes to the encoded string.
Query strings should be sorted in a case insensitive way.
Your credentials are indeed correct.
It's a good idea to see how QueryStringSigner.java is implemented in the official SDK , and Signature Version 2 Signing Process.
PS: what's the reason of not using the offical SDK?
In the past when I have had this issue, it was to do with system time. Syncing time with NTP fix issue for me
Can be caused by
A space in the name (or path) of the file.
Characters that are not being properly encoded. Mostly / or +.
Generating new keys that does not contain these characters could help. More info on this issue or this one.
I'm trying to retrieve tweets that mention an specific user either using fabric for android or twitter4j, but I'm not getting anything.
-With Fabric for Android I'm doing it with "twitterApiClient.getSearchService().tweets" (logged in as a guest previously)
-With twitter4j, this is my code:
public List<Long> twList (String user){
List<Long> listTw = new ArrayList<>();
lastID = Long.MAX_VALUE;
int tamano = 0;
ArrayList<Status> tweets = new ArrayList<Status>();
String mention = "#"+user.trim();
query = new Query(user);
while (tweets.size() < numberOfTweets) {
tamano = tweets.size();
if (numberOfTweets - tweets.size() > 100) {
query.setCount(100);
} else {
query.setCount(numberOfTweets - tweets.size());
}
try {
QueryResult result = twitter.search(query);
tweets.addAll(result.getTweets());
Log.d("App", "Gathered " + tweets.size() + " tweets");
for (Status t : tweets) {
if (t.getId() < lastID) {
lastID = t.getId();
}
}
} catch (TwitterException te) {
Log.d("App", "Couldn't connect: " + te);
}
query.setMaxId(lastID - 1);
if (tamano == tweets.size()) break;
}
for (Status s: tweets){
if (s.getText().matches(mention)){
listTw.add(s.getId());
Log.d("App", s.getText());
}
}
tweets.clear();
return listTw;
}
When I look for the username on Twitter website, I get those tweets where it's mentioned.
Any idea?
When was the last time a Tweet including the username you're searching for, posted? The Search API (which is used by both Fabric and Twitter4j) only covers around 7 days of data. The website has the complete archive, but that is not available in the public Twitter API.
Im trying to access youtube account with account manager, meaning i want to access youtube with a account linked to my device and with this get youtube token to access user playlist and whatever. Freedi application for android doing somthing like this.
I used this code to get token
am.getAuthToken(accounts[0], "youtube", true, new AccountManagerCallback<Bundle>() {
#Override
public void run(AccountManagerFuture<Bundle> future) {
try {
Bundle bundle = future.getResult();
if (bundle.containsKey(AccountManager.KEY_INTENT)) {
Intent intent = bundle.getParcelable(AccountManager.KEY_INTENT);
intent.setFlags(intent.getFlags() & ~Intent.FLAG_ACTIVITY_NEW_TASK);
startActivityForResult(intent, 0);
} else if (bundle.containsKey(AccountManager.KEY_AUTHTOKEN)) {
my_access_token = bundle.getString(AccountManager.KEY_AUTHTOKEN);
onActivityResult(0,1,null);
}
} catch (Exception e) {
Log.e("TEST", e.getMessage(), e);
}
}
}, null);
but the var my_access_token filled with token that youtube not recognize...
how can i get youtube token from it? and how to get the user playlist?
you're in luck as I just finished cracking this problem on the app I'm developing.
AccountManager.get(getApplicationContext()).getAuthTokenByFeatures("com.google", "oauth2:https://gdata.youtube.com", null, this,
null, null, new AccountManagerCallback<Bundle>() {
#Override
public void run(AccountManagerFuture<Bundle> future) {
try {
Bundle bundle = future.getResult();
String acc_name = bundle.getString(AccountManager.KEY_ACCOUNT_NAME);
String auth_token = bundle.getString(AccountManager.KEY_AUTHTOKEN);
Log.d(DEBUG_TAG, "name: " + acc_name + "; token: " + auth_token);
} catch (Exception e) {
Log.e(DEBUG_TAG, e.getClass().getSimpleName() + ": " + e.getMessage());
}
}
}, null);
I haven't used it myself in an app yet, and it might not be available on all Android devices, but my understanding is that the Google Play services now provides the best approach to getting OAuth 2 tokens (including those scoped to https://gdata.youtube.com). There's more info at
http://android-developers.blogspot.com/2012/09/google-play-services-and-oauth-identity.html
You could go with the AccountManager approach for wider compatibility, though.
The confusing part is the authTokenType parameter, it must be complete with the spec for OAuth2 access, e.g.
"oauth2:https://gdata.youtube.com"
or
"oauth2:https://www.googleapis.com/auth/tasks"