Im trying to post some status message on my facebook page, not my personal facebook profile account, but on page i created separately.
My current code looks like this:
import facebook4j.Facebook;
import facebook4j.FacebookException;
import facebook4j.FacebookFactory;
import facebook4j.Post;
import facebook4j.ResponseList;
import facebook4j.conf.Configuration;
import facebook4j.conf.ConfigurationBuilder;
public class FacebookImpl {
// from https://developers.facebook.com/apps/
static String appId = "11removed";
// from https://developers.facebook.com/apps/
static String appSecret = "c0removed";
// from https://developers.facebook.com/tools/accesstoken/
static String appToken = "11removed";
// my facebook page
static String myFaceBookPage = "niremoved";
public static void main(String[] args) throws FacebookException {
// Make the configuration builder
ConfigurationBuilder confBuilder = new ConfigurationBuilder();
confBuilder.setDebugEnabled(true);
// Set application id, secret key and access token
confBuilder.setOAuthAppId(appId);
confBuilder.setOAuthAppSecret(appSecret);
confBuilder.setOAuthAccessToken(appToken);
// Set permission
// https://developers.facebook.com/docs/facebook-login/permissions
confBuilder.setOAuthPermissions("manage_pages,publish_pages,publish_actions");
confBuilder.setUseSSL(true);
confBuilder.setJSONStoreEnabled(true);
// Create configuration object
Configuration configuration = confBuilder.build();
// Create FacebookFactory and Facebook instance
FacebookFactory ff = new FacebookFactory(configuration);
Facebook facebook = ff.getInstance();
// this one works fine
System.out.println(getFacebookPostes(facebook, myFaceBookPage));
// try to post status
// FacebookException{statusCode=403, errorType='OAuthException',
// errorMessage='(#200) The user hasn't authorized the application to perform this action', errorCode=200, errorSubcode=-1, version=2.4.5}
facebook.postStatusMessage(myFaceBookPage, "Test Facebook4J.");
}
public static String getFacebookPostes(Facebook facebook, String page) throws FacebookException {
ResponseList<Post> results = facebook.getPosts(page);
// as example just to see if i get any data
return results.get(0).getMessage();
}
}
Problem is that i cant post any message on page using this code: facebook.postStatusMessage(myFaceBookPage, "Test Facebook4J."); but i can get messages already posted (via facebook web interfaces) with method getFacebookPostes.
Can anyone help me with this one ? And please do not paste some random dev.Facebook link to look into API.
What i did:
- create app on https://developers.facebook.com/apps/ i have appid, appsecret
Thanks
Related
Searched a lot but there is no precise answer on how to get started with dialogflow in spring boot.
Aim: To detect intent from GDF knowledgebase and return back the response.
What I have done so far:
Tried executing this code https://github.com/googleapis/java-dialogflow/blob/HEAD/samples/snippets/src/main/java/com/example/dialogflow/DetectIntentTexts.java
by creating a main app.
App.java
package com.example.dialogflow;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public class App {
public static void main(String[] args) {
DetectIntentTexts theDetectIntentTexts = new DetectIntentTexts();
String projectId = "abc";
String sessionId = "xyz";
String lang = "en";
List<String> myTexts = new ArrayList<>();
myTexts.add("hi");
String ans = null;
try {
ans = String.valueOf(theDetectIntentTexts.detectIntentTexts(projectId, myTexts, sessionId, lang));
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("Bot reply:" + ans);
}
}
But it fails to run.
I have my service account GCP set in local machine and export GOOGLE_APPLICATION_CREDENTIALS=/path/to/your-project-credentials.json is set too
Any help would be appreciated.
Finally was able to solve it.
Steps:
First run
gcloud auth application-default revoke
This will remove user account & service account credentials.
Now login into gcloud using service account credentials.
gcloud auth activate-service-account --key-file=key.json
Wonder why we have to revoke user account credentials because keeping both the accounts and activating service account didn't work.
Now it works.
I'm trying to implement 2 phase authentication for my application using authy authentication.
While trying to verify the token generated in authy mobile app m getting UnknownHostException.
package tes.resource;
import com.authy.*;
import com.authy.api.*;
public class SampleAuthenticator {
AuthyApiClient client=null;
public void init(){
String apiKey = "API_KEY";
String apiUrl = "http://api.authy.com";
boolean debugMode = true;
client = new AuthyApiClient(apiKey, apiUrl, debugMode);
}
public void register(String userid,String phone){
Users user=client.getUsers();
user.createUser(userid,phone, "57");
}
public boolean verify(){
Tokens tokens = client.getTokens();
Token verification = tokens.verify(27319980, "7983610");
return verification.isOk();
}
public static void main(String[] args){
SampleAuthenticator objSampleAuthenticator=new SampleAuthenticator();
objSampleAuthenticator.init();
System.out.println(objSampleAuthenticator.verify());
}
}
I have created a application to test whether authy is verifying the user based on the random token generated in authy app.
Any help is appreciated.
Authy developer evangelist here.
First I would recommend you change your Authy API key, since you seem to have leaked it in this question.
Secondly, the Authy API URL requires HTTPS. My guess is that you need to change
String apiUrl = "http://api.authy.com";
to an HTTPS url:
String apiUrl = "https://api.authy.com";
Let me know if that helps.
I have a Task that is to retrieve some Information from a JIRA account through Java. I downloaded the Jira API which is working with Java, but I have no idea how to make it work. I have to pass somewhere my username and password for log in and after that to retrieve what Information I want from what project I want.
JiraRestClientFactory factory = new AsynchronousJiraRestClientFactory();
URI uri = new URI(JIRA_URL);
JiraRestClient client = factory.createWithBasicHttpAuthentication(uri, JIRA_ADMIN_USERNAME, JIRA_ADMIN_PASSWORD);
// Invoke the JRJC Client
Promise<User> promise = client.getUserClient().getUser("admin");
// Here I am getting the error!!
User user = promise.claim();
///////////////////////////////////////
// Print the result
System.out.println(String.format("Your admin user's email address is: %s\r\n", user.getEmailAddress()));
// Done
System.out.println("Example complete. Now exiting.");
System.exit(0);
That above code is not working, because either if I pass a wrong password and a wrong username is showing me the same result. I have to know how to connect properly to JIRA and retrive some Information in JSON from there! Thank you for your time!
Here is the error
Caused by: com.atlassian.jira.rest.client.api.RestClientException: org.codehaus.jettison.json.JSONException: A JSONObject text must begin with '{' at character 9 of
I think you don't have the necessary permission to acces Jira , you have to connect with jira with an account that have the correct permissions!
The only thing I can think of is that you are sending incorrect creds. Try using the email address instead of just "admin".
Here is some code that might help: https://github.com/somaiah/jrjc
I check for an issue, but getting user info would be similar.
You can use the below code the get the results.Remember I am using this in my gradle project where I am downloading all the dependencies of JRCJ
import com.atlassian.jira.rest.client.api.JiraRestClientFactory
import com.atlassian.jira.rest.client.api.domain.User
import com.atlassian.jira.rest.client.internal.async.AsynchronousJiraRestClientFactory
import com.atlassian.util.concurrent.Promise
/**
* TODO: Class description
*
* on 20 Jul 2017
*/
class Jira {
private static final String JIRA_URL = "https://JIRA.test.com"
private static final String JIRA_ADMIN_USERNAME = "ABCDE"
private static final String JIRA_ADMIN_PASSWORD = "******"
static void main(String[] args) throws Exception
{
// Construct the JRJC client
System.out.println(String.format("Logging in to %s with username '%s' and password '%s'", JIRA_URL, JIRA_ADMIN_USERNAME, JIRA_ADMIN_PASSWORD))
JiraRestClientFactory factory = new AsynchronousJiraRestClientFactory()
URI uri = new URI(JIRA_URL)
JiraRestClient client = factory.createWithBasicHttpAuthentication(uri, JIRA_ADMIN_USERNAME, JIRA_ADMIN_PASSWORD)
// Invoke the JRJC Client
Promise<User> promise = client.getUserClient().getUser(JIRA_ADMIN_USERNAME)
User user = promise.claim()
// Print the result
System.out.println(String.format("Your user's email address is: %s\r\n", user.getEmailAddress()))
// Done
//System.out.println("Example complete. Now exiting.")
//System.exit(0)
}
}
I just started using YouTube API for Java and I'm having a tough time trying to figure out why things don't work since exception/stack trace is no where to be found. What I'm trying to do is to get list of videos uploaded by current user.
GoogleTokenResponse tokenFromExchange = new GoogleTokenResponse();
tokenFromExchange.setAccessToken(accessToken);
GoogleCredential credential = new GoogleCredential.Builder().setJsonFactory(JSON_FACTORY).setTransport(TRANSPORT).build();
credential.setFromTokenResponse(tokenFromExchange);
YouTube.Channels.List channelRequest = youtube.channels().list("contentDetails");
channelRequest.setMine(true);
channelRequest.setFields("items/contentDetails,nextPageToken,pageInfo");
ChannelListResponse channelResult = channelRequest.execute();
I don't see anything wrong with this code and also tried removing multiple things, but still not able to get it to work. Please let me know if you have run into a similar issue. The version of client library I'm using is v3-rev110-1.18.0-rc.
YouTube API has some working code and you can use it.
public static YouTubeService service;
public static String USER_FEED = "http://gdata.youtube.com/feeds/api/users/";
public static String CLIENT_ID = "...";
public static String DEVELOPER_KEY = "...";
public static int getVideoCountOf(String uploader) {
try {
service = new YouTubeService(CLIENT_ID, DEVELOPER_KEY);
String uploader = "UCK-H1e0S8jg-8qoqQ5N8jvw"; // sample user
String feedUrl = USER_FEED + uploader + "/uploads";
VideoFeed videoFeed = service.getFeed(new URL(feedUrl), VideoFeed.class);
return videoFeed.getTotalResults();
} catch (Exception ex) {
Logger.getLogger(YouTubeCore.class.getName()).log(Level.SEVERE, null, ex);
}
return 0;
}
This simple give you the number of videos a user has. You can read through videoFeed using printEntireVideoFeed prepared on their api page.
I want to write a simple java (or java web app) program that will allow a user to log in and post a twit. I don't even need a user interface. I can simply hard code the twit, userId, and password. I just want to know the process. I have been looking for a while now, and I have had no success so far. The following code which was finally supposed to work does not work.
The code is a simple application as opposed to a web-app. Does anyone have some code that will work with the present Twitter API? I have been trying to use twitter4j.
import twitter4j.Twitter;
import twitter4j.TwitterException;
import twitter4j.TwitterFactory;
import twitter4j.auth.AccessToken;
import twitter4j.auth.RequestToken;
public class TwitterUtils {
public static void main(String[] args) {
try {
final String consumerKey = "**********";
final String consumerSecret = "**********";
Twitter twitter = new TwitterFactory().getInstance();
twitter.setOAuthConsumer(consumerKey, consumerSecret);
RequestToken requestToken = twitter.getOAuthRequestToken();
String token = requestToken.getToken();
String tokenSecret = requestToken.getTokenSecret();
System.out.println("My token :: " + token);
System.out.println("My token Secret :: " + tokenSecret);
//AccessToken a = new AccessToken(token, tokenSecret);
//twitter.setOAuthAccessToken(a);
twitter.updateStatus("If you're reading this on Twitter, it worked!");
} catch (TwitterException e) {
e.printStackTrace();
}
}//main
}//TwitterUtils
With the AccessToken lines commented I get the error
Exception in thread "main" java.lang.IllegalStateException: Authentication credentials are missing. See http://twitter4j.org/configuration.html for the detail. at twitter4j.TwitterBaseImpl.ensureAuthorizationEnabled(TwitterBaseImpl.java:205)
at twitter4j.TwitterImpl.updateStatus(TwitterImpl.java:453)
at playaround.TwitterUtils.main(TwitterUtils.java:55)
Java Result: 1
When I uncomment the lines, the error reads
Exception in thread "main" java.lang.IllegalArgumentException: Invalid access token format. at twitter4j.auth.AccessToken.<init>(AccessToken.java:50)
at playaround.TwitterUtils.main(TwitterUtils.java:53)
Does anyone have a complete solution I may use? Thanks.
Besides consumerKey and consumerSecret (your application's key and secret) you need accessToken from the user that is using your application. You get this accessToken from Twitter using OAuth protocol.
Through this link (
http://module.minic.ro/how-to-make-a-twitter-application-tutorial/ ) you can generate consumer key,consumer secret, access token, and access token secret keys
Use this code when you get keys for Twitter object:
ConfigurationBuilder cb = new ConfigurationBuilder();
cb.setDebugEnabled(true)
.setOAuthConsumerKey("*********************")
.setOAuthConsumerSecret("******************************************")
.setOAuthAccessToken("**************************************************")
.setOAuthAccessTokenSecret("******************************************");
TwitterFactory tf = new TwitterFactory(cb.build());
Twitter twitter = tf.getInstance();
http://twitter4j.org/en/configuration.html