How to use the twitter4j library? - java

I was overwhelmed by the amount of information on https://dev.twitter.com/docs and then I went to twitter4j and downloaded the library. I got a consumer key and secret by registering on their website. What are these for?
What I am trying to is get tweet text from certain twitter account( not my personal one but public one) and other information( account user, time and other stuff).
I couldn't find useful tutorial online. So please help me. Thank you very much!

The keys are so that your application can authenticate to the Twitter API. I put them in a properties file and made them available on the classpath. Once your application has authenticated, you will be able to use the API to get the account information you need. I don't know any good tutorials, but you could use an open source project I wrote as a reference if you like: https://github.com/rossh/gift-findr.

This is an example of how to get hold of a org.twitter4j.Twitter object. Once you have that, you can do a great many operations - just inspect the interface for org.twitter4j.Twitter.
Twitter twitter = new TwitterFactory().getInstance(twitter4JConfiguration);
twitter.setOAuthConsumer(consumerKey, consumerSecret);
twitter.setOAuthAccessToken(new AccessToken(oauthToken, oauthTokenSecret));
String screenName = twitter.getScreenName(); // Returns authenticating user's screen name.
User stephenfry = twitter.showUser("stephenfry"); // Returns extended information of a given user ...
List<User> friends = twitter.getFriendsList("stephenfry", -1L); // Returns a cursored collection of user objects ...
This is a link to the javadoc for the org.twitter4j.Twitter interface

Related

Google Cloud Resource Management Java Api Projects List

I'm finding a way to programatically list Google Cloud projects inside an organization. I'm trying to use a service account exported json credential to achieve such purpose in this way:
// More info on the endpoint here:
// https://cloud.google.com/resource-manager/reference/rest/v1/projects/list
final CloudResourceManager cloudResourceManagerService = createCloudResourceManagerService();
final CloudResourceManager.Projects.List listRequest = cloudResourceManagerService
.projects()
.list()
.setFilter("labels.it-restoring:false name:IT-TEST-*");
final ListProjectsResponse listResponse = listRequest.execute();
if (listResponse.isEmpty()) {
throw new RuntimeException("The API did not get any response"); // I never get past here
}
log.info("Listing projects returned: {}", listResponse);
The problem I find is that I always get an empty response. Even though I assigned the service account the role of owner. According to docs, I could use roles/
resourcemanager.organizationAdmin which I also set but with no luck. I create the CloudResourceManagement api object using getApplicationDefault.
However if I do gcloud beta auth application-default login which triggers an auth flow in the browser and authenticate with the user which is the owner of the organization this works and lists all the projects that I have.
Can anybody explain to me what I should do to store a proper credential which would emulate he user owner? I already set the service account with the Owner role which in theory gives virtually access to all resources and still no luck.
In order to list the projects on your organization, you need the permission resourcemanager.projects.get. Please find more information in this link The service account might have the owner role of 1 project, and not enought to list them all.
An alternative solution is to grant the account the cloudasset.assets.searchAllResources permission at org level by using one of the following roles:
roles/cloudasset.viewer
roles/cloudasset.owner
roles/viewer
roles/editor
roles/owner
With this permission, you can list all the projects within an organization 456:
gcloud asset search-all-resources \
--asset-types="cloudresourcemanager.googleapis.com/Project"
--scope=organizations/456
Documentation: https://cloud.google.com/asset-inventory/docs/searching-resources
Related post: How to find, list, or search resources across services (APIs) and projects in Google Cloud Platform?

Java Read Facebook Wall

I'm building a web portal by using Java; besides other requirements, I'm struggling my mind one one very simple (at least at first view) requirement:
my customer wants on his portal the first N posts of his facebook wall
and he wants to read the first N tweets of his twitter page
Since my java code is based on Spring, I wanted to use spring social, spring social twitter and spring social facebook in order to satisfy the requirement
With twitter I had no problem; in fact I
created an app on twitter
got twitter app id and app secret
prepared code
In a couple of hours, all worked pretty good
Problems were born with facebook and it's a lot of time I'm fighting with it
I passed from spring social to facebook4j (since this last one seems to me stronger).
I did the following
created an app on FB
got the facebook appId and appSecret
told to the code that I need the read_stream permission
prepared the code
But I'm not able in reading posts from my wall
Is there anyone who was able in satisfying this kind of scenario?
here my facebook4j code
private static final Logger log = LoggerFactory.getLogger(FacebookTest.class.getName());
public static void main (String[] a)
{
try
{
ConfigurationBuilder cfgBui = new ConfigurationBuilder();
cfgBui.setDebugEnabled(true);
cfgBui.setOAuthAppId(myAppId);
cfgBui.setOAuthAppSecret(myAppSecret);
cfgBui.setUseSSL(true);
Configuration cfg = cfgBui.build();
FacebookFactory ff = new FacebookFactory(cfg);
OAuthSupport support = new OAuthAuthorization(cfg);
support.setOAuthPermissions("read_stream");
AccessToken appAccessToken = support.getOAuthAppAccessToken();
Facebook face = ff.getInstance(appAccessToken );
ResponseList<Post> posts = face.searchPosts("test");
for (Post post : posts)
{
System.out.println(post.getId());
}
} catch (Exception e)
{
log.error("Errore", e);
}
}
As far as I understood, I should need the user access token, but I don't know how to generate it; should I create a login flow and show to the user the FB login dialog? If so, why should I create app id and app secret? They have no sense in my scenario
Moreover...in my case...the server side should authenticate on FB and read posts from a well know user wall (the wall of my customer...) so....where should I present the login dialog? where should I redirect after the FB login?
Is there any good man :) who can clarify to me the FB read post flow?
You MUST use one of the possibilities to authorize the user (with read_stream) in order to get access to his stream. Here´s the link to all the possibilities: https://developers.facebook.com/docs/facebook-login/v2.2
You can also generate Access Tokens with the Graph API Explorer: https://developers.facebook.com/tools/explorer/
Detailed information about Access Tokens and how to generate them can be found in the following links:
https://developers.facebook.com/docs/facebook-login/access-tokens
http://www.devils-heaven.com/facebook-access-tokens/
Keep in mind that an Extended User Token only lasts for 60 days, after that your customer would have to refresh it manually. In general, you are not allowed to use User Profiles for commercial reasons, and it´s very unusual to show a User stream on a website.
Better: Use a Facebook Page. /page-id/feed with an Extended Page Token that lasts forever.
If you use spring-social-facebook, you could let the user login via (front-end login flow) and then you can access the users wall. However, user would need to login and authorize your app to perform the operations.
Here is a spring social sample project that demo's how spring-social-facebook login is done https://github.com/spring-projects/spring-social-samples
Also, within your java code you can use feedoperations to gather information about home feed and also query against it. Checkout the documentation.
facebook.feedOperations().

How to use Java and Twitter API to get tweets sent by given Twitter ID?

I want to use java and Twitter API to collect Twitter data for researching, especially to collect tweets sent by a given Twitter ID.
Now I can only collect my own tweets by using Twitter4j and OAuth setting. How could I get others tweets if I could not get their OAuth?
There is no restriction to collect others tweets, so what I mean is you don't need to have a specific authhentication token for this. Only restriction might be protected accounts owners because protected accounts don't allow anyone to get their tweets without establishing friendship association like following mechanism.
You can look at both dev.twitter.com and twitter4j sites how to do that. By the way, I recommend twitter4j. If you have further questions, let me know I can help more as well.
Java4j Code Examples
The method you're looking for is:
getUserTimeline(java.lang.String screenName)
or:
getUserTimeline(long userId)
This will give you the latest 20 Tweets of the required user. So your code should look something like this:
Twitter twitterConnection = getConnection(); //I assume you already know how to init a connection
ResponseList<Status> results = twitterConnection.getUserTimeline("justinbieber");

java :direct gmail url

I am completely new to this site. I was searching for an answer for my problem. But I saw the same problem asked by someone in this website. The question is here
I am using windows 7. I didn't not get answer there in that link..so I am asking the same question again. I want to open a gmail account link in a browser from a java application. Yes I do know about browse() method in Desktop class. The thing is that I can open the gmail website but I need to open directly the specified gmail account while username and password are provided. Any ideas?
Okay, so take this with a couple of caveats: 1. the last time I played with Google APIs was in an older version, so this may be quite different now, 2. this code isn't tested, I'm just writing it up partially from memory and partially from an old project of mine. Think of it more like pseudo-code, and 3. if this does by chance work, this is a pretty dirty solution. Hopefully this can set you on the track of finding a better way to do this with the API.
GoogleOAuthParameters oauthParameters = new GoogleOAuthParameters();
oauthParameters.setOAuthConsumerKey( [insert consumer key here] );
oauthParameters.setOAuthConsumerSecret( [insert consumer secret here] );
OAuthSigner signer = new OAuthHmacSha1Signer();
GoogleOAuthHelper oauthHelper = new GoogleOAuthHelper(signer);
oauthParameters.setScope("https://mail.google.com/mail"); //no clue if this is a valid scope or not
oauthHelper.getUnauthorizedRequestToken(oauthParameters);
String requestUrl = oauthHelper.createUserAuthorizationUrl(oauthParameters);
Desktop desktop = Desktop.getDesktop();
URI url;
url = new URI(requestUrl);
//this will make the user log in to authorize your app
desktop.browse(url);
//auth token response from Google, you can use this to authenticate your app if there are other requests you want to make against the user account
String token = oauthHelper.getAccessToken(oauthParameters);
//since you made sure the user is logged into their account to authorize your app, their gmail can now just be opened. Yes, very dirty. I know. (if it all works)
desktop.browse("https://www.gmail.com/");

How to get Connections of Linkedin profile in android

I am trying to get the Connections or user's friends info from LinkedIn using LinkedIn jar for android and example given in google code, but i wont get Connections using linkedInApiClient.getConnectionsForCurrentUser() this method call it returns null, but i can access user current profile info using linkedInApiClient.getProfileForCurrentUser()
can any body suggest me how to get User connections information in linkedIn in android. Or guide me the the wright way.
I got the solution for the above ask question, what I was doing wrong, was that we have to pass an argument of the ProfileField information we want, like this:
final Set<ProfileField> connectionFields = EnumSet.of(ProfileField.ID, ProfileField.MAIN_ADDRESS,
ProfileField.PHONE_NUMBERS, ProfileField.LOCATION,
ProfileField.LOCATION_COUNTRY, ProfileField.LOCATION_NAME,
ProfileField.FIRST_NAME, ProfileField.LAST_NAME, ProfileField.HEADLINE,
ProfileField.INDUSTRY, ProfileField.CURRENT_STATUS,
ProfileField.CURRENT_STATUS_TIMESTAMP, ProfileField.API_STANDARD_PROFILE_REQUEST,
ProfileField.EDUCATIONS, ProfileField.PUBLIC_PROFILE_URL, ProfileField.POSITIONS,
ProfileField.LOCATION, ProfileField.PICTURE_URL);
Connections connections = client.getConnectionsForCurrentUser(connectionFields);

Categories