I am trying to post a message onto a facebook group (I am the admin for the page). Here is the java code that I am using:
public void makeTestPost() {
fbClient = new DefaultFacebookClient(groupPageAccessToken);
counter = 0;
fbClient.publish(groupID + "/posts", FacebookType.class, Parameter.with("message", Integer.toString(counter) + ": Hello, fb World!"));
counter++;
}
with:
private final string groupPageAccessToken = "XXXXXXXXXXXXXXXXXX";
private final String groupID = "XXXXXXX";
I got these values using the facebook graph explorer api online Graph API Explorer
But when I login to facebook I don't see any message/post on the group. Please tell me how to make it work?
You need an user access token with the permissions publish_actions and user_managed_groups.
Then you can publish a new message like this:
GraphResponse response = fbClient.publish(groupID + "/feed", GraphResponse.class, Parameter.with("message", Integer.toString(counter) + ": Hello, fb World!"));
Related
I have a Java application that integrates with One Drive through Microsoft Graph. I followed the documentation and I am able to pass the authorisation step but when interrogating the API I get this error:
"AADSTS70000121: The passed grant is from a personal Microsoft account and is required to be sent to the /consumers or /common endpoint."
What am I missing?
This is the code I am using:
Get an authorisation token using the URL bellow
private static final String RESPONSE_TYPE = "code";
private static final String SCOPE = "openid%20Files.Read%20Files.ReadWrite%20Contacts.Read%20offline_access";
String authorizeUrl = "https://login.microsoftonline.com/common/oauth2/v2.0/authorize?client_id=" + CLIENT_ID
+ "&scope=" + SCOPE + "&response_type=" + RESPONSE_TYPE + "&redirect_uri=" + REDIRECT_URL;
Exchange the received authorization token
List<String> scopes = new LinkedList<String>();
scopes.add("https://graph.microsoft.com/.default");
AuthorizationCodeCredential authCodeCredential = new AuthorizationCodeCredentialBuilder()
.clientId(CLIENT_ID)
.clientSecret(CLIENT_SECRET)
.authorizationCode(authorizationCode)
.redirectUrl(REDIRECT_URL)
.build();
TokenCredentialAuthProvider tokenCredAuthProvider = new TokenCredentialAuthProvider(scopes, authCodeCredential);
GraphServiceClient graphClient = GraphServiceClient.builder().authenticationProvider(tokenCredAuthProvider).buildClient();
User me = graphClient.me()
.buildRequest()
.get();
As you are using the personal account then please change the endpoint to consumers instead of common,
https://login.microsoftonline.com/consumers/oauth2/v2.0/authorize?
ref doc - https://learn.microsoft.com/en-au/azure/active-directory/develop/v2-oauth2-auth-code-flow
Hope this helps
Thanks
I'm trying to use the Authentication::login() API call in the DocuSign Java SDK and am receiving an error. Here's some code:
#Component
public class TestClass {
private ApiClient apiClient;
public void authenticate() {
this.apiClient = new ApiClient("account-d.docusign.com", "docusignAccessCode",
"mySecretIntegratorKey", "myClientSecret");
final AuthenticationApi authenticationApi = new AuthenticationApi(this.apiClient);
try {
// ERROR ON THE LINE BELOW
final LoginInformation loginInformation = authenticationApi.login();
} catch (final ApiException e) {
// do something appropriate
}
}
}
The mySecretIntegratorKey and myClientSecret values are not the real values I'm sending in obviously, but the other ones are.
Here is the error I am receiving when making the login() call:
Caused by: org.apache.oltu.oauth2.common.exception.OAuthSystemException: Missing grant_type/code
at com.docusign.esign.client.auth.OAuth$OAuthJerseyClient.execute(OAuth.java:184)
at org.apache.oltu.oauth2.client.OAuthClient.accessToken(OAuthClient.java:65)
at org.apache.oltu.oauth2.client.OAuthClient.accessToken(OAuthClient.java:55)
at org.apache.oltu.oauth2.client.OAuthClient.accessToken(OAuthClient.java:71)
at com.docusign.esign.client.auth.OAuth.updateAccessToken(OAuth.java:92)
... 123 common frames omitted
I realize that this is using the older legacy authentication, however I have a limitation that won't allow me to upgrade to the newer method of authentication until the first of the year. So for now I need to use this legacy method using SDK Version 2.2.1.
Any ideas what I'm doing wrong here? I'm sure it is something simple...
Thank you for your time.
You want to use Legacy authentication?
In that case you need to make a number of updates to your code.
Only call new ApiClient(base_url)
Set the X-DocuSign-Authentication header--
From an old Readme:
String authHeader = "{\"Username\":\"" + username +
"\",\"Password\":\"" + password +
"\",\"IntegratorKey\":\"" + integratorKey + "\"}";
apiClient.addDefaultHeader("X-DocuSign-Authentication", authHeader);
Then use the authenticationApi.login to look up the user's Account ID(s) and matching base urls.
The authenticationApi.login doe not actually log you in. (!)
Rather, that method just gives you information about the current user.
There is no login with the API since it does not use sessions. Instead, credentials are passed with every API call. The credentials can be an Access Token (preferred), or via Legacy Authentication, a name / password / integration key triplet.
When using Legacy Authentication, the client secret is not used.
More information: see the Readme section for using username/password in this old version of the repo.
Just in case someone was looking for complete legacy code that works! The below C# code snippet works. This is production ready code. I've tested it and it works. You will have to create an EnvelopeDefinition separately as this code is not included. However, the piece below will authenticate the user and will successfully send an envelope and get back the Envelope ID:
string username = "john.bunce#mail.com";
string password = "your_password";
string integratorKey = "your_integration_key";
ApiClient apiClient = new ApiClient("https://www.docusign.net/restapi");
string authHeader = "{\"Username\":\"" + username + "\", \"Password\":\"" + password + "\", \"IntegratorKey\":\"" + integratorKey + "\"}";
apiClient.Configuration.AddDefaultHeader("X-DocuSign-Authentication", authHeader);
AuthenticationApi authApi = new AuthenticationApi(apiClient.Configuration);
LoginInformation loginInfo = authApi.Login();
string accountId = loginInfo.LoginAccounts[0].AccountId;
string baseURL = loginInfo.LoginAccounts[0].BaseUrl;
string[] baseUrlArray= Regex.Split(baseURL, "/v2");
ApiClient apiClient2 = new ApiClient(baseUrlArray[0]);
string authHeader2 = "{\"Username\":\"" + username + "\", \"Password\":\"" + password + "\", \"IntegratorKey\":\"" + integratorKey + "\"}";
apiClient2.Configuration.AddDefaultHeader("X-DocuSign-Authentication", authHeader2);
EnvelopesApi envelopesApi = new EnvelopesApi(apiClient2.Configuration);
EnvelopeSummary results = envelopesApi.CreateEnvelope(accountId, envelopeDefinition);
string envelopeID = results.EnvelopeId;
I want to get tweets from certain user timelines using java library twitter4j, currently I have source code which can get ~ 3200 tweets from user time line but I can't get full tweet. I have searched in various sources on the internet but I can't find a solution to my problem. anyone can help me or can anyone provide an alternative to get a full tweet from the user timeline with java programming?
my source code :
public static void main(String[] args) throws SQLException {
ConfigurationBuilder cb = new ConfigurationBuilder();
cb.setDebugEnabled(true)
.setOAuthConsumerKey("aaa")
.setOAuthConsumerSecret("aaa")
.setOAuthAccessToken("aaa")
.setOAuthAccessTokenSecret("aaa");
TwitterFactory tf = new TwitterFactory(cb.build());
Twitter twitter = tf.getInstance();
int pageno = 1;
String user = "indtravel";
List statuses = new ArrayList();
while (true) {
try {
int size = statuses.size();
Paging page = new Paging(pageno++, 100);
statuses.addAll(twitter.getUserTimeline(user, page));
System.out.println("***********************************************");
System.out.println("Gathered " + twitter.getUserTimeline(user, page).size() + " tweets");
//get status dan user
for (Status status: twitter.getUserTimeline(user, page)) {
//System.out.println("*********Place Tweets :**************\npalce country :"+status.getPlace().getCountry()+"\nplace full name :"+status.getPlace().getFullName()+"\nplace name :"+status.getPlace().getName()+"\nplace id :"+status.getPlace().getId()+"\nplace tipe :"+status.getPlace().getPlaceType()+"\nplace addres :"+status.getPlace().getStreetAddress());
System.out.println("["+(no++)+".] "+"Status id : "+status.getId());
System.out.println("id user : "+status.getUser().getId());
System.out.println("Length status : "+status.getText().length());
System.out.println("#" + status.getUser().getScreenName() +" . "+status.getCreatedAt()+ " : "+status.getUser().getName()+"--------"+status.getText());
System.out.println("url :"+status.getUser().getURL());
System.out.println("Lang :"+status.getLang());
}
if (statuses.size() == size)
break;
}catch(TwitterException e) {
e.printStackTrace();
}
}
System.out.println("Total: "+statuses.size());
}
Update :
After the answer given by #AndyPiper
the my problem is every tweet that I get will be truncated or not complete. a tweets that I get will be truncated if the length of tweet more than 140 characters. I found the reference tweet_mode=extended, but I do not know how to use it. if you know something please tell me.
Your Configuration should be like this:
ConfigurationBuilder cb = new ConfigurationBuilder();
cb.setDebugEnabled(true)
.setOAuthConsumerKey("aaa")
.setOAuthConsumerSecret("aaa")
.setOAuthAccessToken("aaa")
.setOAuthAccessTokenSecret("aaa")
.setTweetModeExtended(true);
It is explained well here
The Twitter API limits the timeline history to 3200 Tweets. To get more than that you would need to use the (commercial) premium or enterprise APIs to search for Tweets by a specific user.
if you are streaming tweets
fist: you have to add .setTweetModeExtended(true); into your configurationbuilder
second(here is the code)
TwitterStream twitterStream = new TwitterStreamFactory(cb.build()).getInstance();
StatusListener listener = new StatusListener(){
public void onStatus(Status status) {
System.out.println("-------------------------------");
if(status.isRetweet()){
System.out.println(status.getRetweetedStatus().getText());
}
else{
System.out.println(status.getText());
}`
its totally works for me.
take care yourself :)
If you are implementing twitter api using twitter4j.properties file and getting truncated timeline text value,simply add the below property in it at the end.
tweetModeExtended=TRUE
I am using facebook4j-core-2.1.0 and trying to get the page likes. I don't know what I am doing wrong, I am kinda newbie at this.
public static void main(String[] args) throws FacebookException
{
// Generate facebook instance.
Facebook facebook = new FacebookFactory().getInstance();
// access token ...
AccessToken at = new AccessToken(accessTokenString);
// Set access token.
facebook.setOAuthAccessToken(at);
String facebookUserName = "Google";
Page pgId = facebook.getPage(facebookUserName);
Page pgL = facebook.getLikedPage(pgId.getId());
System.out.println("Page Likes :" + pgL);
}
http://www.facebook.com/Google shows that it have 18,281,664 likes, but when I ran the above code I got null value.
What am I missing here?
I think you should try something like this:
String userName = "google";
Page pgId = facebook.getPage(userName);
System.out.println("Page Likes :" + pgId.getLikes());
Hope it helps.
The page.getLikes() method return null to me so I opted for this:
RawAPIResponse facebookJson = facebook.callGetAPI("google?fields=engagement");
JSONObject jsonObject = facebookJson.asJSONObject();
String likesCount = ((JSONObject)jsonObject.get("engagement")).getString("count");
System.out.println("likes :" + likesCount);
Using Reading and api v2.6 see how to specify api version here http://facebook4j.org/en/faq.html#apiversion
Reading pageReading = new Reading();
pageReading.fields("name","id","fan_count");
Page page = facebook.getPage("google", pageReading);
System.out.println("likes :" + page.getFanCount());
I am trying to get the lastname of my profile using restfb.But but each time the username is returned as null.I already have the acess token and permissions.I guess t some problem with the JSon object passing.how can i pass the json objects to a javabean and later retrieve it?
This happens when the access token you provided doesn't have the correct permissions to access the data. Best way to check this is by using the facebook graph API interface; noting the version.
https://developers.facebook.com/tools/explorer/145634995501895/?method=GET&path=me&version=v2.4
FacebookClient fbClient = new DefaultFacebookClient(accessToken, Version.VERSION_2_4);
User me = fbClient.fetchObject("me", User.class, Parameter.with("fields", "email,first_name,last_name,gender"));
Note: Your FB.login function must contain the correct scope for fields you want to access.
FB.login(function(response) {
...
}, {scope: 'email'});
This works for me:
FacebookClient facebookClient = new DefaultFacebookClient(MY_ACCESS_TOKEN);
User user = facebookClient.fetchObject("me", User.class);
out.println("Last name: " + user.getLastName());
Here is the code snippet
FacebookClient facebookClient = new DefaultFacebookClient("register a facebook application with required permissions, get that application token and paste here");
User user = facebookClient.fetchObject("me", User.class);
Connection<User> myFriends = facebookClient.fetchConnection("me/friends", User.class);
for(User friend:myFriends.getData())
{
Connection<Page> myMovies = facebookClient.fetchConnection(friend.getId() + "/movies", Page.class);
content = content + "Name: " + friend.getName();
for(Page page:myMovies.getData())
{
content = content + "\n" + "Movies: " + page.getName() + "\n";
}
}
In this example your application needs "friends_likes" permission.
Hope this helps.