I'm using Facebook4j to get status with a keyword
facebook4j.conf.ConfigurationBuilder fac = new facebook4j.conf.ConfigurationBuilder();
fac.setDebugEnabled(true)
.setOAuthAppId("******")
.setOAuthAppSecret("********")
.setOAuthPermissions("email,publish_stream,...");
FacebookFactory ff = new FacebookFactory(fac.build());
facebook = ff.getInstance();
new Thread(new Runnable() {
#Override
public void run() {
try {
search();
}
catch (Exception e) {
// TODO: handle exception
System.out.println(e +" ERROOOOOOR");
}}}).start();
}
//search
public void search() throws Exception {
ResponseList<JSONObject> results = facebook.search("%23morocco");
System.out.println(results);
for (JSONObject result : results) {
System.out.println(result);
}
results = facebook.search("orange", new Reading().until("yesterday"));
System.out.println(results);
for (JSONObject result : results) {
System.out.println(result);
}
}
I replaced * with facebook api key
I have a exception probleme , the error is :
java.lang.IllegalStateException: No Token available. ERROOOOOOR
This is how you could use facebook4j without external configuration files. The code below provides a minimal example. Here is my simple demo:
import facebook4j.Facebook;
import facebook4j.FacebookException;
import facebook4j.FacebookFactory;
import facebook4j.auth.AccessToken;
public class Facebook4JMinimalExample {
/**
* A simple Facebook4J client.
*
*
* #param args
* #throws FacebookException
*/
public static void main(String[] args) throws FacebookException {
// Generate facebook instance.
Facebook facebook = new FacebookFactory().getInstance();
// Use default values for oauth app id.
facebook.setOAuthAppId("", "");
// Get an access token from:
// https://developers.facebook.com/tools/explorer
// Copy and paste it below.
String accessTokenString = "PASTE_YOUR_ACCESS_TOKEN_STRING_HERE";
AccessToken at = new AccessToken(accessTokenString);
// Set access token.
facebook.setOAuthAccessToken(at);
// We're done.
// Write some stuff to your wall.
facebook.postStatusMessage("Wow, it works...");
}
}
Note that it is important to FIRST make a call to "facebook.setOAuthAppId(..)" and THEN set the access token. Otherwise you'll get an IllegalStateException saying "OAuth app id/secret combination not supplied".
In this case, I've just used a default value for OAuthAppId.
You forgot to set the access token with fac.setOAuthAccessToken("*****"). From the docs (emphasis mine):
All Graph API search queries require an access token passed in with the access_token=<token> parameter. The type of access token you need depends on the type of search you're executing.
Searches across page and place objects requires an app access token.
All other endpoints require a user access token.
You can generate one for yourself here, but remember that these access tokens have an expiration time.
Related
I am implementing "Login with Microsoft button" and I need to store the refresh token in my database so that I can use that to obtain new access tokens in future. I am trying to do this with Java sdk for microsoft graph.
Edit 1: I actually want to create calendar events using my web application. So, the goal is for the web app to access Graph API without having a signed in user present.
This is what the code looks like:
AuthorizationCode authorizationCode = new AuthorizationCode(httpServletRequest.getParameter("code"));
String currentUri = httpServletRequest.getRequestURL().toString();
IAuthenticationResult result;
ConfidentialClientApplication app;
try {
app = createClientApplication();
String authCode = authorizationCode.getValue();
Set<String> scopes = new HashSet<String>();
scopes.add("Calendars.ReadWrite");
AuthorizationCodeParameters parameters = AuthorizationCodeParameters.builder(authCode, new URI(currentUri)).scopes(scopes)
.build();
Future<IAuthenticationResult> future = app.acquireToken(parameters);
result = future.get();
} catch (ExecutionException e) {
throw e.getCause();
}
String accessToken = result.accessToken();
/*
IAuthenticationResult does not contain any method to get the refresh token - how do I get the refresh token??
I want to do something like: result.refreshToken();
*/
IAuthenticationResult is implemented by AuthenticationResult -- but, AuthenticationResult is declared in another class and is not public. AuthenticationResult exposes a method to obtain refreshToken but, I am not able to access it.
Can someone help me access the refresh token?
Thanks!
I got the answer from this link: https://github.com/AzureAD/microsoft-authentication-library-for-java/issues/228
Short Answer: Use reflection
try {
//see com.microsoft.aad.msal4j.AuthenticationResult#refreshToken
final Field refreshTokenField = result.getClass()
.getDeclaredField("refreshToken");
refreshTokenField.setAccessible(true);
return refreshTokenField.get(result).toString();
} catch (IllegalAccessException | NoSuchFieldException e) {
throw new RuntimeException(e);
}
I frequently get the following exception using twitter4j:
2015-06-02 10:04:30,802 DEBUG [Twitter Stream consumer-1[Establishing connection]] TwitterBot(116): Got an exception 420:Returned by the Search and Trends API when you are being rate limited (https://dev.twitter.com/docs/rate-limiting).
Returned by the Streaming API:
Too many login attempts in a short period of time.
Running too many copies of the same application authenticating with the same account name.
Exceeded connection limit for user
Since i try to avoid being banned from Twitter, i would like to ask, if I am doing something wrong in my code:
I am using a StatusListener on the Stream API, which is filtered by my own ID and some string values.
If a status matches the criteria an answer for this status is send via twitter. This does not happen very often and therefore this should not be the problem of the rate limitation exception.
The whole thing runs in a TomEE EJB environment, if this is important?
#Startup
#Singleton
public class TwitterBot implements Service {
private static final org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger(TwitterBot.class);
//this is fix for this twitter bot
public static final String TWITTER_BOT_NAME = "botname";
public static final long TWITTER_BOT_USER_ID = 99999L; //the bot's user id
private final TwitterStream twitterStream;
private final Twitter twitter;
public TwitterBot() {
this.twitterStream = new TwitterStreamFactory().getInstance();
this.twitter = TwitterFactory.getSingleton();
}
#PostConstruct
public void listen() {
StatusListener listener = new StatusListener() {
#Override
public void onStatus(Status status) {
//this is to avoid a circle... ignore tweets coming from ourselves.
if (status.getUser().getScreenName().equalsIgnoreCase(TWITTER_BOT_NAME)) {
return;
}
try {
//do something and update own status
StatusUpdate update = new StatusUpdate("Hello World!");
update.setInReplyToStatusId(status.getId());
twitter.updateStatus(update);
} catch (TwitterException e) {
logger.error("Could not complete twitter update, {}", e.getLocalizedMessage(), e);
}
}
//other Status Listener methods, which are not used (default implementation)
};
//filtering for ourselves here
long[] userFilter = {TWITTER_BOT_USER_ID};
String[] termFilter = {TWITTER_EXPERTIZER_BOT_NAME};
FilterQuery filter = new FilterQuery(0, userFilter, termFilter);
twitterStream.addListener(listener);
twitterStream.filter(filter);
}
}
The answer on this How to handle rate limit using twitter4j to avoid being banned tells me, that the Streaming API has no rate limitation.
So what is the issue? Is there an explanation in the API documentation?
Thank you in advance!
Edit:
The Problem is related to
FilterQuery filter = new FilterQuery(0, userFilter, termFilter);
Using the query like this produces some kind of polling on the Twitter API and therefore exceeds connection limit.
Instead use:
FilterQuery filter = new FilterQuery(termFilter);
In my front end Javascript code, I call Twilio.Device.connect(), and it is not firing a request to my Voice Request URL. I am not sure what is going on here. I ensure that I setup my capability token before hand, and there are no errors, but it still doesn't work. Here is front end JS code.
Twilio.Device.setup(resp.token);
Twilio.Device.connect({autoDial: true});
// respond to "connect" event
Twilio.Device.connect(function (conn) {
alert("Got here!");
}
Also here is my code to generate the token.
public static void getToken()
{
TwilioCapability t = new TwilioCapability(ACCOUNT_SID, AUTH_TOKEN);
t.allowClientOutgoing(APP_SID);
t.allowClientIncoming("test");
try {
throw new OKResponse(ImmutableMap.of("token", t.generateToken(3600)));
} catch (DomainException e) {
Logger.error(e, "Error generating twilio token: %s", e.getMessage());
}
}
I had the same problem,
You need to call the function generateToken() after calling allowClientOutgoing() and allowClientIncoming() so that the object created by Services_Twilio_Capability() has the app link.
This works:
$objToken = new Services_Twilio_Capability($accountSid, $authToken);
$objToken->allowClientOutgoing('APXXXXXXXXXX');
$objToken->allowClientIncoming($_REQUEST['name']);
$strToken = $objToken->generateToken();
This does not:
$objToken = new Services_Twilio_Capability($accountSid, $authToken);
$strToken = $objToken->generateToken();
$objToken->allowClientOutgoing('APXXXXXXXXXX');
$objToken->allowClientIncoming($_REQUEST['name']);
Also, it will not throw an error but your js will always show as "disconnected"
UPDATE
Here is an edit of my backend:
/**
* Create an instance of Services_Twilio_Capability();
*
* #return object
*/
private function instantiateCapability(){
if(is_null($this->objCapability))
$this->objCapability = new \Services_Twilio_Capability(TWILIO_ID, TWILIO_KEY);
return $this->objCapability;
}
/**
* Generate a token
*
* #link http://twilio-php.readthedocs.org/en/latest/usage/token-generation.html
* #param bool $boolOutgoing Allow outgoing connections
* #param bool $boolIncoming Allow incoming connections
* #return string
*/
public function generateToken($boolOutgoing = true, $boolIncoming = true){
$objCapability = $this->instantiateCapability();
if($boolOutgoing) $objCapability->allowClientOutgoing(TWILIO_SID]);
if($boolIncoming) $objCapability >allowClientIncoming($_SESSION[$GLOBALS['APP_NAME'] . 'ID']);
$strToken = $objCapability->generateToken(TOKEN_DURATION);
return json_encode(array('status' => 1, 'token' => $strToken));
}
And here is the frontend (AJAX response callback):
function(result){
if(result.status == 1) {
//Load the twilio object
Twilio.Device.setup(result.token);
}
}
In my code, I am trying to send to Paypal REST API the needed information and Paypal is giving me an "APPROVED" status but in order to finalize the payment, I need to execute the payment.
payment.execute(accesstoken,paymentExecution)... but I couldn't get the payer_id from the response.
Here is my code for further information and thanks for your help in advance!
public class PaypalPaymentWithCreditCardServlet {
// private static final long serialVersionUID = 734220724945040319L;
// #Override
public void init () throws Exception {
InputStream is = PaypalPaymentWithCreditCardServlet.class.getResourceAsStream("/sdk_config.properties");
try {
PayPalResource.initConfig(is);
} catch (PayPalRESTException e) {
// goto failure page. can't do anything without configuration file
e.printStackTrace();
}
}
public boolean doPost (PaymentPojo paymentpojo) throws Exception {
try {
String accessToken = GenerateAccessToken.getAccessToken();
APIContext apiContext = new APIContext(accessToken);
final Payment payment = new PaymentBuilder().setBillingAddress(paymentpojo.getBillingAddress())
.setCreditCard(paymentpojo.getCreditCard())
.setPaymentDetail(paymentpojo.getDetails())
.setTransactionAmount(paymentpojo.getAmount())
.build();
Payment createdPayment = payment.create(apiContext);
System.out.println(Payment.getLastResponse());
System.out.println(String.format("created payment with id [%s] and status=[%s]", createdPayment.getId(), createdPayment.getState()));
if(!createdPayment.getState().toLowerCase().equalsIgnoreCase(PaypalState.APPROVED.getStatus())) {
// payment is not created. throw an exception
System.out.println("Payment handshake did not go through!!!");
return false;
}
// if it is not created throw exception
// payment.execute(accessToken, paymentExecution);
return true;
} catch (PayPalRESTException e) {
}
return false;
}
}
For credit card payments, payer_id is the unique attribute (e.g email address) that you use to identify the user in your system and you would provide that for payment each time in payerID.
If you are not aware of the user's information, such as a guest checkout, you should not need to provide a payerID.
For paypal payments, payer_id always needs to be provided and is appended to redirect_url once the user approves the payment. Full docs are at https://developer.paypal.com/webapps/developer/docs/integration/web/accept-paypal-payment/
Where can I find Jira issue type values that we pass to IssueBuilder class constructor?
For ex: If i want to create a issue type of bug using jira rest api , We pass value '1L' to Issue Builder class constructor.
IssueInputBuilder issueBuilder = new IssueInputBuilder("Key", 1l);
Similarly what are the values of other jira issue types ?.. Anybody know the values we need to pass ?
If you are using later Jira REST Java Client API (e.g. 4.0), the interface has been changed. You must use following code to browsing all issue types:
private static final String JIRA_SERVER = "http://jiralab";
public static void main(String[] args) {
try {
JiraRestClientFactory factory = new AsynchronousJiraRestClientFactory();
URI uri = new URI(JIRA_SERVER);
JiraRestClient client = factory.createWithBasicHttpAuthentication(uri, "admin", "admin");
listAllIssueTypes(client);
}
catch (Exception ex) {
}
}
private static void listAllIssueTypes(JiraRestClient client) throws Exception {
Promise<Iterable<IssueType>> promise = client.getMetadataClient().getIssueTypes();
Iterable<IssueType> issueTypes = promise.claim();
for (IssueType it : issueTypes) {
System.out.println("Type ID = " + it.getId() + ", Name = " + it.getName());
}
}
If you want to get a list of all available issuetypes, you can use the REST API (/rest/api/2/issuetype). To try that on your JIRA instance, I like to recommend the Atlassian REST API Browser.
Or just look here: Finding the Id for Issue Types
In Java you can get a list of all issuetype object using getAllIssueTypeObjects().