Posting on wall using Facebook4j - facebook4j

im new to Facebook4j and im looking for a way to post message using it. i just learned few of the coding in the internet. Please someone help me.
This are what i have done :
import facebook4j.Facebook;
import facebook4j.FacebookException;
import facebook4j.FacebookFactory;
import facebook4j.conf.Configuration;
import facebook4j.conf.ConfigurationBuilder;
public class post {
public static void main(String[] args)
throws FacebookException
{
// Create conf builder and set authorization and access keys
ConfigurationBuilder configurationBuilder = new ConfigurationBuilder();
configurationBuilder.setDebugEnabled(true);
configurationBuilder.setOAuthAppId("xxxx");
configurationBuilder.setOAuthAppSecret("xxxx");
configurationBuilder.setOAuthAccessToken("xxxx");
configurationBuilder .setOAuthPermissions("email, publish_stream, id, name, first_name, last_name, read_stream , generic");
configurationBuilder.setUseSSL(true);
// Create configuration and get Facebook instance
Configuration configuration = configurationBuilder.build();
FacebookFactory ff = new FacebookFactory(configuration);
Facebook Facebook = ff.getInstance();
Facebook.postStatusMessage("Hello World from Facebook4J.");
}
}
so, what i need to do next?

Have you created and authorized your app on https://developers.facebook.com ?
This is actually the first step.

Related

Unable to like a tweet using twitter4j but everything else is working fine

Here is the code which is working fine for other methods of twitter variable but only createfavorite is giving this error :
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import twitter4j.TwitterFactory;
import twitter4j.conf.ConfigurationBuilder;
public class TwitterAutoLikerPart1 {
private static Logger logger = LoggerFactory.getLogger(TwitterAutoLikerPart1.class);
public static void main(String[] args) throws Exception {
ConfigurationBuilder cb = new ConfigurationBuilder();
cb.setDebugEnabled(true)
.setOAuthConsumerKey("E")
.setOAuthConsumerSecret("F")
.setOAuthAccessToken("G")
.setOAuthAccessTokenSecret("H");
TwitterFactory tf = new TwitterFactory(cb.build());
var twitter = tf.getInstance();
long tweetid=tweetid;
logger.info("Tweet id is "+tweetid);
logger.info(twitter.createFavorite(tweetid).getText());
/*
Whereas this is working
for(var x:twitter.getFavorites())
logger.info(x.toString());*/
}
}
Here's the logs for your referrence :
Exception in thread "main" 401:Authentication credentials (https://dev.twitter.com/pages/auth) were missing or incorrect. Ensure that you have set valid consumer key/secret, access token/secret, and the system clock is in sync.
{"request":"\/1.1\/favorites\/create.json","error":"Read-only application cannot POST."}
Relevant discussions can be found on the Internet at:
http://www.google.co.jp/search?q=038fb9e8 or
http://www.google.co.jp/search?q=480cbeca
TwitterException{exceptionCode=[038fb9e8-480cbeca], statusCode=401, message=null, code=-1, retryAfter=-1, rateLimitStatus=null, version=4.0.7}
at twitter4j.HttpClientImpl.handleRequest(HttpClientImpl.java:170)
at twitter4j.HttpClientBase.request(HttpClientBase.java:57)
at twitter4j.HttpClientBase.post(HttpClientBase.java:86)
at twitter4j.TwitterImpl.post(TwitterImpl.java:2102)
at twitter4j.TwitterImpl.createFavorite(TwitterImpl.java:1241)
at com.twiiterapi.mt.twitterapi.TwitterAutoLikerPart1.main(TwitterAutoLikerPart1.java:30)
Process finished with exit code 1
Kindly let me know where am I faultering.
Edit: So, the issue was app permission as pointed by the kind person Mr Andy Piper . I changed the permission and it started working like a charm .

how auth token flow can be handled in java using gmail api call [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 3 years ago.
Improve this question
.I want to integrate whole gmail functionalities like read, list, send using myApp. I have tried using http://securetoken.googleapis.com/v1/token HTTP/1.1
but couldn't get access token. Kindly provide flow.
Tried using POST : http://securetoken.googleapis.com/v1/token HTTP/1.1 and POST : https://www.googleapis.com/oauth2/v4/token though getting error 404 not found.
You may want to consult Java Quickstart It contains a full authorization example.
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.javanet.NetHttpTransport;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.jackson2.JacksonFactory;
import com.google.api.client.util.store.FileDataStoreFactory;
import com.google.api.services.gmail.Gmail;
import com.google.api.services.gmail.GmailScopes;
import com.google.api.services.gmail.model.Label;
import com.google.api.services.gmail.model.ListLabelsResponse;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.security.GeneralSecurityException;
import java.util.Collections;
import java.util.List;
public class GmailQuickstart {
private static final String APPLICATION_NAME = "Gmail API Java Quickstart";
private static final JsonFactory JSON_FACTORY = JacksonFactory.getDefaultInstance();
private static final String TOKENS_DIRECTORY_PATH = "tokens";
/**
* Global instance of the scopes required by this quickstart.
* If modifying these scopes, delete your previously saved tokens/ folder.
*/
private static final List<String> SCOPES = Collections.singletonList(GmailScopes.GMAIL_LABELS);
private static final String CREDENTIALS_FILE_PATH = "/credentials.json";
/**
* Creates an authorized Credential object.
* #param HTTP_TRANSPORT The network HTTP Transport.
* #return An authorized Credential object.
* #throws IOException If the credentials.json file cannot be found.
*/
private static Credential getCredentials(final NetHttpTransport HTTP_TRANSPORT) throws IOException {
// Load client secrets.
InputStream in = GmailQuickstart.class.getResourceAsStream(CREDENTIALS_FILE_PATH);
if (in == null) {
throw new FileNotFoundException("Resource not found: " + CREDENTIALS_FILE_PATH);
}
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(new FileDataStoreFactory(new java.io.File(TOKENS_DIRECTORY_PATH)))
.setAccessType("offline")
.build();
LocalServerReceiver receiver = new LocalServerReceiver.Builder().setPort(8888).build();
return new AuthorizationCodeInstalledApp(flow, receiver).authorize("user");
}
public static void main(String... args) throws IOException, GeneralSecurityException {
// Build a new authorized API client service.
final NetHttpTransport HTTP_TRANSPORT = GoogleNetHttpTransport.newTrustedTransport();
Gmail service = new Gmail.Builder(HTTP_TRANSPORT, JSON_FACTORY, getCredentials(HTTP_TRANSPORT))
.setApplicationName(APPLICATION_NAME)
.build();
// Print the labels in the user's account.
String user = "me";
ListLabelsResponse listResponse = service.users().labels().list(user).execute();
List<Label> labels = listResponse.getLabels();
if (labels.isEmpty()) {
System.out.println("No labels found.");
} else {
System.out.println("Labels:");
for (Label label : labels) {
System.out.printf("- %s\n", label.getName());
}
}
}
}
application verification
Remember gmail scopes are considered to be the most sensitive. You should consider submitting your application now for verification as it can take time to go though the process. Also remember you may be charged for the verification of a gmail scope because the review is done by a third party and not google themselves.

OAuth2RestTemplate for Salesforce is giving error - HTTP 400 Bad Request

I am trying to integrate Spring Boot with Salesforce using OAuth2RestTemplate but it is giving me Access token denied error even though credentials are correct. Upon debugging I found that Salesforce is sending 400 HTTP status code.
package com.sentryds.advis.salesforce;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.security.oauth2.client.OAuth2RestTemplate;
import org.springframework.security.oauth2.client.token.grant.password.ResourceOwnerPasswordResourceDetails;
import org.springframework.security.oauth2.common.AuthenticationScheme;
#SpringBootApplication
public class SalesforceApplication {
public static void main(String[] args) {
SpringApplication.run(SalesforceApplication.class, args);
ResourceOwnerPasswordResourceDetails resourceDetails = new ResourceOwnerPasswordResourceDetails();
resourceDetails.setAuthenticationScheme(AuthenticationScheme.form);
resourceDetails.setAccessTokenUri("https://test.salesforce.com/services/oauth2/token");
resourceDetails.setGrantType("password");
resourceDetails.setClientId("xxxxxxxx");
resourceDetails.setClientSecret("xxxxxxxx");
resourceDetails.setUsername("xxxxxxxx");
resourceDetails.setPassword("xxxxxxxx");
OAuth2RestTemplate auth2RestTemplate = new OAuth2RestTemplate(resourceDetails);
try {
System.out.println(auth2RestTemplate.getAccessToken());
} catch (Throwable t) {
System.out.println(t.getMessage());
}
}
}
However if I following this technique then everything works. Only reason I am using OAuth2RestTemplate is because it takes care of the token refresh automatically. If there is another way to do so without using OAuthRestTemplate then please let me know that as well.
Finally I was able to solve this problem. I am posting my answer with a hope that it will help someone.
ResourceOwnerPasswordResourceDetails resource = new ResourceOwnerPasswordResourceDetails();
resource.setAccessTokenUri("https://test.salesforce.com/services/oauth2/token");
resource.setClientId("client_id");
resource.setClientSecret("client_secret");
resource.setClientAuthenticationScheme(AuthenticationScheme.form);
resource.setUsername("username");
resource.setPassword("password");
OAuth2RestTemplate operations = new OAuth2RestTemplate(resource(), new DefaultOAuth2ClientContext(new DefaultAccessTokenRequest()));
operations.getMessageConverters().add(new MappingJackson2HttpMessageConverter()); // Not required if you are not doing any conversion
operations.getMessageConverters().add(new StringHttpMessageConverter()); // Not required if you are not doing any conversion
try {
System.out.println(auth2RestTemplate.getAccessToken());
} catch (Throwable t) {
System.out.println(t.getMessage());
}

Has anyone successfully implemented Azure Active Directory B2C for auth using Microsoft.Identity.Client 1.1.0-preview?

I have been struggling with this for several days (three actually). I have AAD B2C working on a web app and an api. I cannot get it running on my Xamarin mobile project. I am using the UWP project to test my configuration since it has the easiest app to troubleshoot on a Windows 10 machine. I am using Visual Studio 2015 Pro.
I am using the Microsoft.Identity.Client 1.1.0-preview.
I used this as my starting point for my attempt to implement.
https://github.com/Azure-Samples/active-directory-b2c-xamarin-native
Right now the project will compile and launch. When I click on Sign in, I get a WebView, but it doesn't look exactly right....
[First Image in Screenshots]
Here are my variables...
public class Constants
{
public static string ApplicationID = "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx";
public static string[] Scopes = {""};
public static string SignUpSignInPolicy = "B2C_1_Standard_SignUpSignIn";
public static string ResetPasswordPolicy = "B2C_1_Standard_PasswordReset";
public static string EditProfilePolicy = "B2C_1_Standard_EditProfile";
public static string Authority = "https://login.microsoftonline.com/[MyTennantName].onmicrosoft.com/B2C_1_Standard_SignUpSignIn";
public static string AuthorityEditProfile = "https://login.microsoftonline.com/[MyTennantName].onmicrosoft.com/B2C_1_Standard_EditProfile";
public static string ApiEndpoint = "https://[MyTennantName].onmicrosoft.com/apiservices";
public static UIParent UiParent = null;
}
My Login method is....
async void OnSignInSignOut(object sender, EventArgs e)
{
try
{
if (btnSignInSignOut.Text == "Sign in")
{
AuthenticationResult ar = await App.PCA.AcquireTokenAsync(Constants.Scopes, GetUserByPolicy(App.PCA.Users, Constants.SignUpSignInPolicy), Constants.UiParent);
UpdateUserInfo(ar);
UpdateSignInState(true);
}
else
{
foreach (var user in App.PCA.Users)
{
App.PCA.Remove(user);
}
UpdateSignInState(false);
}
}
catch (Exception ex)
{
// Checking the exception message
// should ONLY be done for B2C
// reset and not any other error.
if (ex.Message.Contains("AADB2C90118"))
OnPasswordReset();
// Alert if any exception excludig user cancelling sign-in dialog
else if (((ex as MsalException)?.ErrorCode != "authentication_canceled"))
await DisplayAlert($"Exception:", ex.ToString(), "Dismiss");
}
}
However before I can even enter my password I get the following....
[Second image in Screenshots]
My application definition looks like this...[Third image in screenshots]
I don't think it is recognizing my tenant and trying to log me in with a Microsoft account. I have double checked my Tenant name and Application ID.
Screenshots
I don't have enough reputation to post more than one link and one picture.
Also, the Azure AD B2C api application works for a web app. I have created a web app that can authenticate and works with the API.
It looks like while modifying the authorization value in the Sample you removed the /tfp/ part.
You should update your values as follows:
public static string Authority = "https://login.microsoftonline.com/tfp/[MyTennantName].onmicrosoft.com/B2C_1_Standard_SignUpSignIn";
public static string AuthorityEditProfile = "https://login.microsoftonline.com/tfp/[MyTennantName].onmicrosoft.com/B2C_1_Standard_EditProfile";

Google OAuth 2 is generating redirect_uri instead of using one defined in client_secret.json

I would like to use the Google Calendar API, but in order to do that, I need to be authorized using Googles OAuth 2.0 API. I am running into trouble with the redirect_uri. The following is a sample of my client_secret.json.
{
"web": {
"client_id": "deleted",
"client_secret": "deleted",
"redirect_uris": ["http://localhost:8080/CommunityUmcPasadena/Callback"],
"auth_uri": "https://accounts.google.com/o/oauth2/auth",
"token_uri": "https://accounts.google.com/o/oauth2/token"
}
}
When I run my Quickstart application, I get the following error:
Apr 20, 2017 10:45:42 PM com.google.api.client.util.store.FileDataStoreFactory setPermissionsToOwnerOnly
WARNING: unable to change permissions for everybody: C:\Users\Gary\.credentials\calendar-java-quickstart
Apr 20, 2017 10:45:42 PM com.google.api.client.util.store.FileDataStoreFactory setPermissionsToOwnerOnly
WARNING: unable to change permissions for owner: C:\Users\Gary\.credentials\calendar-java-quickstart
2017-04-20 22:45:42.485:INFO::Logging to STDERR via org.mortbay.log.StdErrLog
2017-04-20 22:45:42.485:INFO::jetty-6.1.26
2017-04-20 22:45:42.498:INFO::Started SocketConnector#localhost:34940
Please open the following address in your browser:
https://accounts.google.com/o/oauth2/auth?access_type=offline&client_id=deleted&redirect_uri=http://localhost:34940/Callback&response_type=code&scope=https://www.googleapis.com/auth/calendar.readonly
Attempting to open that address in the default browser now...
As you can see, it has the redirect_uri as http://localhost:34940/Callback. This is not what is defined in client_secret.json though. It is using the correct client_id and secret though. Therefore, I'm not sure why the api is generating a random callback. I would also like to note that the redirect_uri listed in the client_secret.json is the same as the API Manager.
Does anyone know why the redirect_uri is being generated by the API instead of using the one defined in the client_secret.json?
Any help is greatly appreciated.
Also, here is the code for the quick start application...
package sample;
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.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.client.util.DateTime;
import com.google.api.services.calendar.CalendarScopes;
import com.google.api.services.calendar.model.*;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.List;
public class Quickstart {
private static final String APPLICATION_NAME = "Google Calendar API Java Quickstart";
private static final java.io.File DATA_STORE_DIR = new java.io.File(System.getProperty("user.home"), ".credentials/calendar-java-quickstart");
private static FileDataStoreFactory DATA_STORE_FACTORY;
private static final JsonFactory JSON_FACTORY = JacksonFactory.getDefaultInstance();
private static HttpTransport HTTP_TRANSPORT;
private static final List<String> SCOPES = Arrays.asList(CalendarScopes.CALENDAR_READONLY);
static {
try {
HTTP_TRANSPORT = GoogleNetHttpTransport.newTrustedTransport();
DATA_STORE_FACTORY = new FileDataStoreFactory(DATA_STORE_DIR);
}
catch(Throwable t) {
t.printStackTrace();
System.exit(1);
}
}
public static Credential authorize() throws IOException {
InputStream in = Quickstart.class.getResourceAsStream("/client_secret.json");
GoogleClientSecrets clientSecrets =
GoogleClientSecrets.load(JSON_FACTORY, new InputStreamReader(in));
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 com.google.api.services.calendar.Calendar getCalendarService() throws IOException {
Credential credential = authorize();
return new com.google.api.services.calendar.Calendar.Builder(HTTP_TRANSPORT, JSON_FACTORY, credential)
.setApplicationName(APPLICATION_NAME)
.build();
}
public static void main(String[] args) throws IOException {
com.google.api.services.calendar.Calendar service = getCalendarService();
}
}
Your code doesn't specify a redirect_url. I suspect that the Java library is making the assumption that if you don't specify a redirect_url, it's because you don't have one, so it defaults to a fake URL. It looks like you've copy/pasted the Quickstart code which says at the top of the page "a simple Java command-line application", whereas I think you're building a web server application.
Sooo, dig into the Java OAuth library docs (good luck - try https://developers.google.com/api-client-library/java/google-oauth-java-client/reference/1.20.0/com/google/api/client/auth/oauth2/AuthorizationCodeFlow) and see where to set the redirect URL to your ttp://localhost:8080/CommunityUmcPasadena/Callback
I have been looking an answer for quite some time...
You need to use
LocalServerReceiver
Example usage:
LocalServerReceiver localServerReceiver = new LocalServerReceiver.Builder().setHost("localhost").setPort(8181).build();
Credential credential = new AuthorizationCodeInstalledApp(flow, localServerReceiver).authorize("user");

Resources