Requesting long lived access_token on serverside flow - java

I have a Java web app that posts items to our users facebook walls, when the user initially signs up we get a 60 day access_token which is persisted to our database, now that the offline_access is be removed I using our 'Login with facebook' button to update the tokens when the user logs into our website, this is all good as they will typically visit more than 60 days apart.
I have implemented the above and it works well...but then I found that the access tokens that are being generated from the login action expire after 1 hour....obviously not good a we cant post to their walls while they are away.
The code below demonstrates how we are getting the tokens via the signed_request method (in Java SEAM App), this works ok, but the tokens are short-lived
Can anyone suggest how to ensure the tokens are the 60-day type
Thanks
public void loginWithFacebook(){
accessToken = null;
try {
accessToken = FaceBookSecurity.getFBAccessToken();
} catch (Exception e) {
log.error("Error getting FB access token: "+e);
}
FacebookClient facebookClient = new DefaultFacebookClient(accessToken);
com.restfb.types.User facebookUser = facebookClient.fetchObject("me", com.restfb.types.User.class);
facebookEmail = facebookUser.getEmail();
if (facebookEmail != null) {
new RunAsOperation(true) {
public void execute() {
user = ((UserDAO)Component.getInstance("userDAO")).findByEmail(StringUtils.lowerCase(facebookEmail));
if (user != null && user.getFacebookToken() != null && !accessToken.equals(user.getFacebookToken())) {
user.setFacebookToken(accessToken);
log.error("FB: updating "+user.getFirstname()+" "+user.getSurname()+"s FB token to: "+accessToken);
}
}
}.run();
if (user != null) {
//set the user as logged in
return;
}
}
messagePoster.postPopupErrorMessage(messages.get("facebookLoginFailed"));
}
public static String getFBAccessToken()
throws Exception {
HttpServletRequest request = (HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext().getRequest();
Cookie fbCookie = getFBCookie(request);
String fbCookieValue = fbCookie.getValue();
String[] stringArgs = fbCookieValue.split("\\.");
String encodedPayload = stringArgs[1];
JsonObject data;
try{
String payload = base64UrlDecode(encodedPayload);
// gets the js object from the cookie
data = new JsonObject(payload);
}catch (Exception e){
return "";
}
String authUrl = getAuthURL(data.getString("code"));
URL url = new URL(authUrl);
URI uri = new URI(url.getProtocol(), url.getHost(), url.getPath(),
url.getQuery(), null);
String result = readURL(uri.toURL());
String[] resultSplited = result.split("&");
return resultSplited[0].split("=")[1];
}
// creates the url for calling to oauth.
public static String getAuthURL(String authCode) {
String url = "https://graph.facebook.com/oauth/access_token?client_id="
+ FacebookApp.appId
+ "&redirect_uri=&client_secret="
+ FacebookApp.appSecret + "&code="
+ authCode;
return url;
}
// reads the url.
private static String readURL(URL url) throws IOException {
InputStream is = url.openStream();
InputStreamReader inStreamReader = new InputStreamReader(is);
BufferedReader reader = new BufferedReader(inStreamReader);
String s = "";
int r;
while ((r = is.read()) != -1) {
s = reader.readLine();
}
reader.close();
return s;
}
private static String base64UrlDecode(String input){
return new String(Base64.decodeBase64(input.getBytes()));
}

If all you need is to post to the user's wall, then you can also use app_access_token provided you have asked for publish_stream permission.
You can call :
https://graph.facebook.com/oauth/access_token?
client_id=YOUR_APP_ID
&client_secret=YOUR_APP_SECRET
&grant_type=client_credentials
Read this.
Edit: app access_tokens do not expire until the app secret is reset.

Related

Token is showing expired when sending from android

When I'm sending a token(Bearer) from postman it is working fine. But when I'm sending the same token from the android app and it is showing token is expired but is it fresh and not expired and token is working fine with the postman.
I tried sending a get request without token and it is working fine. The server is running fine the class is working as excepted except authetication.
Node js code for checking the token:
const jwt = require('jsonwebtoken');
const JWT_KEY = require('../../config').getJwtSecrete();
module.exports = async (req, res, next) => {
try {
let token = req.headers.authorization;
token = getTokenFromHeader(token);
const decoded = jwt.verify(token, JWT_KEY);
req.email = decoded.email;
next();
} catch (error) {
return res.status(401).json({
message: 'Auth failed'
});
}
};
function getTokenFromHeader(token) {
return token.split(" ")[1];
}
Android: My get request method for sending the request
public class GET_Request extends AsyncTask<String, Void, Bundle> {
private static final String REQUEST_METHOD = "GET";
private static final int READ_TIMEOUT = 10000;
private static final int CONNECTION_TIMEOUT = 10000;
private GETAsyncResponse delegate;
public GET_Request(GETAsyncResponse delegate) {
this.delegate = delegate;
}
#Override
protected Bundle doInBackground(String... params) {
String Url = params[0];
Bundle bundle = new Bundle();
String result = null;
BufferedInputStream bufferedInputStream;
ByteArrayOutputStream byteArrayOutputStream;
try {
URL requestUrl = new URL(Url);
HttpURLConnection connection = (HttpURLConnection) requestUrl.openConnection();
connection.setRequestMethod(REQUEST_METHOD);
connection.setReadTimeout(READ_TIMEOUT);
connection.setConnectTimeout(CONNECTION_TIMEOUT);
connection.setDoInput(true);
connection.setUseCaches(false);
connection.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
connection.setRequestProperty("Accept", "application/json");
connection.setRequestProperty("Authorization", "Bearer " + UserInfo.getToken());
connection.connect();
if (connection.getResponseCode() == HTTP_OK) {
bufferedInputStream = new BufferedInputStream(connection.getInputStream());
int bisReadResult = bufferedInputStream.read();
byteArrayOutputStream = new ByteArrayOutputStream();
while (bisReadResult != -1) {
byteArrayOutputStream.write((byte) bisReadResult);
bisReadResult = bufferedInputStream.read();
}
result = byteArrayOutputStream.toString();
} else { //reading error
Log.e("doInBackground: ", String.valueOf(connection.getResponseCode()));
String error;
bufferedInputStream = new BufferedInputStream(connection.getInputStream());
int bisRealError = bufferedInputStream.read();
byteArrayOutputStream = new ByteArrayOutputStream();
while (bisRealError != -1) {
byteArrayOutputStream.write((byte) bisRealError);
bisRealError = bufferedInputStream.read();
}
/*This error string is for debugging*/
error = byteArrayOutputStream.toString();
Log.e("Error Buffer: ", error);
}
bundle.putString(JSON, result);
bundle.putInt(RESPONSE_CODE, connection.getResponseCode());
connection.disconnect();
} catch (FileNotFoundException f) {
f.printStackTrace();
bundle.putInt(RESPONSE_CODE, 400);
}
/*Internet not connected*/ catch (SocketTimeoutException s) {
bundle.putInt(RESPONSE_CODE, 0);
}
/*Any other error*/ catch (IOException e) {
e.printStackTrace();
bundle.putInt(RESPONSE_CODE, 500);
}
return bundle;
}
protected void onPostExecute(Bundle result) {
super.onPostExecute(result);
delegate.AfterGetRequestFinish(result);
}
public interface GETAsyncResponse {
void AfterGetRequestFinish(Bundle bundle);
}
}
I want it to authenticate successfully. But I don't know why it is failing and showing code '401' and 'java.io.FileNotFoundException'.
One of the features of JWT is that they are essentially tamper-proof. That is, assuming your suspect JWT has a valid signature and checksum on the Node JS server side, then it means that your Android Java code could not possibly have altered the expiration date of that token.
That being said, the most likely explanation here is that the token you are passing in fact has already expired. This could come about for a number of reasons, most likely that you have cached an old token somewhere, perhaps in shared preferences.

how to solve this 403 io exception?

i want to give whole google drive access from my application to users.
and i use following code to authorize from google and oauth2.0.
function OpenGoogleLogin()
{
var url = "https://accounts.google.com/o/oauth2/auth?scope=https://www.googleapis.com/auth/drive&redirect_uri=http://localhost:8080/Abc/Oauth2callback&response_type=code&client_id=xxxxxxxxxxxxxxxxxxxxxxxxxx&access_type=offline&approval_prompt=force";
window.location = url;
}
from the above code i got authorization code.
on redirected page i put following servlet code
public class Oauth2callback extends HttpServlet {
private static final long serialVersionUID = 1L;
public Oauth2callback() {
super();
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
* response)
*/
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
System.out.println("entering doGet");
try {
// get code
String code = request.getParameter("code");
// format parameters to post
String urlParameters = "code="
+ code
+ "&client_id=xxxxxxxxxxxxxxxxxxxxx"
+ "&client_secret=xxxxxxxxxxxxxxxxxx"
+ "&redirect_uri=http://localhost:8080/Abc/Oauth2callback"
+ "&grant_type=authorization_code";
//post parameters
URL url = new URL("https://accounts.google.com/o/oauth2/token");
URLConnection urlConn = url.openConnection();
urlConn.setDoOutput(true);
OutputStreamWriter writer = new OutputStreamWriter(
urlConn.getOutputStream());
writer.write(urlParameters);
writer.flush();
//get output in outputString
String line, outputString = "";
BufferedReader reader = new BufferedReader(new InputStreamReader(
urlConn.getInputStream()));
while ((line = reader.readLine()) != null) {
outputString += line;
}
System.out.println(outputString);
//get Access Token
JsonObject json = (JsonObject)new JsonParser().parse(outputString);
String access_token = json.get("access_token").getAsString();
System.out.println(access_token);
//get User Info
url = new URL(
"https://www.googleapis.com/oauth2/v1/userinfo?access_token="
+ access_token);
urlConn = url.openConnection();
outputString = "";
reader = new BufferedReader(new InputStreamReader(
urlConn.getInputStream()));
while ((line = reader.readLine()) != null) {
outputString += line;
}
System.out.println(outputString);
// Convert JSON response into Pojo class
GooglePojo data = new Gson().fromJson(outputString, GooglePojo.class);
System.out.println(data);
writer.close();
reader.close();
} catch (MalformedURLException e) {
System.out.println( e);
} catch (ProtocolException e) {
System.out.println( e);
} catch (IOException e) {
System.out.println( e);
}
System.out.println("leaving doGet");
}
}
in the above code , google pojo is just a pojo class, but i don't know when i run that servlet, it give me access and refrshtoken..
but with that it gives me error
java.io.IOException: Server returned HTTP response code: 403 for URL: https://www.googleapis.com/oauth2/v1/userinfo?access_token=xxxxxxxxxxxxx.
You are making the initial authorization request with scope https://www.googleapis.com/auth/drive, and using it's code to call https://www.googleapis.com/oauth2/v1/userinfo.
If you want to get user profile information, you will have to use one of these scopes in your initial request,
https://www.googleapis.com/auth/userinfo.email : View email address
https://www.googleapis.com/auth/userinfo.profile : View basic profile info
So, change your first url to
var url = "https://accounts.google.com/o/oauth2/auth?scope=https://www.googleapis.com/auth/userinfo.profile&redirect_uri=http://localhost:8080/Abc/Oauth2callback&response_type=code&client_id=xxxxxxxxxxxxxxxxxxxxxxxxxx&access_type=offline&approval_prompt=force";
You need to URLEncode the request parameters. A URL isn't valid as a parameter without encoding.

Facebook login in java application and get basic Info of User

I am trying to implement facebook login in my java application. Till now on button click i have called the servlet where it according to client id and secret key generate code and redirect it to the redirect uri. I have registered my test app on facebook developer console.
Problem is that code is generating perfectly but access token is not getting generated through which I will get the basic Info. I have tried many codes. One of them is below.
CLIENT SIDE
google.addClickHandler(new ClickHandler()
{
#Override
public void onClick(ClickEvent event) {
String fbURL = "http://www.facebook.com/dialog/oauth?client_id=CLIENTID&redirect_uri=REDIRECT URL &scope=email&scope=user_friends";
Window.open(fbURL,"_blank","");
}
});
SERVLET
public userInfoServlet() {
super();
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
* response)
*/
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
try {
PrintWriter out = response.getWriter();
String rid = request.getParameter("request_ids");
if (rid != null) {
response.sendRedirect("https://www.facebook.com/dialog/oauth?client_id="
+ clientID + "&redirect_uri=" + redirectURI);
} else {
// Get code
String code = request.getParameter("code");
if (code != null) {
// Format parameters
URL url = new URL(
"https://graph.facebook.com/oauth/access_token?client_id="
+ clientID + "&redirect_uri=" + redirectURI
+ "&client_secret=" + clientSecret
+ "&code=" + code);
// request for Access Token
HttpURLConnection conn = (HttpURLConnection) url
.openConnection();
conn.setRequestMethod("GET");
String line, outputString = "";
BufferedReader reader = new BufferedReader(
new InputStreamReader(conn.getInputStream()));
while ((line = reader.readLine()) != null) {
outputString += line;
}
out.println(outputString);
// extract access token from response
String accessToken = null;
if(outputString.indexOf("access_token")!=-1) {
accessToken = outputString.substring(13,outputString.indexOf("&"));
}
// request for user info
url = new URL("https://graph.facebook.com/me?access_token="
+ accessToken);
out.println(url);
URLConnection conn1 = url.openConnection();
outputString = "";
reader = new BufferedReader(new InputStreamReader(
conn1.getInputStream()));
while ((line = reader.readLine()) != null) {
outputString += line;
}
reader.close();
out.println(outputString);
// convert response JSON to Pojo class
FaceBookPojo fbp = new Gson().fromJson(outputString,
FaceBookPojo.class);
out.println(fbp);
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
I am not getting what exactly the problem in generating the access token. Any help would be appreciable.
tried this code also but the problem is same
there is multiple scope parameters in your req. It should be only one.
Try this,
google.addClickHandler(new ClickHandler()
{
#Override
public void onClick(ClickEvent event) {
String fbURL = "http://www.facebook.com/dialog/oauth?client_id=CLIENTID&redirect_uri=REDIRECT URL &scope=email,user_friends";
Window.open(fbURL,"_blank","");
}
});
It should works.

How to search for tweets using twitter API 1.1 and java

Twitter API has been changed from 1.0 to 1.1. Now for any type of query it has to be authorized. I am using java for fetching tweets. Can anyone give me some java example of tweet fetching using OAuth authentication.
Update
Using twitter4j api it is possible. http://twitter4j.org/en/. An example is given below
Twitter twitter = new TwitterFactory().getInstance();
AccessToken accessToken = new AccessToken("Your-Access-Token", "Your-Access-Token-Secret");
twitter.setOAuthConsumer("Consumer-Key", "Consumer-Key-Secret");
twitter.setOAuthAccessToken(accessToken);
try {
Query query = new Query("#IPL");
QueryResult result;
result = twitter.search(query);
List<Status> tweets = result.getTweets();
for (Status tweet : tweets) {
System.out.println("#" + tweet.getUser().getScreenName() + " - " + tweet.getText());
}
}
catch (TwitterException te) {
te.printStackTrace();
System.out.println("Failed to search tweets: " + te.getMessage());
System.exit(-1);
}
Problems here
This example works independently when I ran as a Java class. But when I add this code in a JSP for testing in webapp it does not work. It shows me following exception
SEVERE: Servlet.service() for servlet [jsp] in context with path [/mypub] threw exception [java.lang.IllegalStateException: consumer key/secret pair already set.] with root cause
java.lang.IllegalStateException: consumer key/secret pair already set.
at twitter4j.TwitterBaseImpl.setOAuthConsumer(TwitterBaseImpl.java:264)
at com.me.framework.tag.core.TweetFetch.doTag(TweetFetch.java:50)
at org.apache.jsp.template.test_jsp._jspx_meth_wf_002dcore_005ftweetFetch_005f0(test_jsp.java:100)
at org.apache.jsp.template.test_jsp._jspService(test_jsp.java:74)
at org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
The problem is that you are setting the consumer secret and token multiple times, as indicated by the exception:
java.lang.IllegalStateException: consumer key/secret pair already set.
It's happening because TwitterFactory.getInstance() is returning a singleton of Twitter, this is then having setOAuthConsumer and setOAuthAccessToken invoked on it each time a request is made to your Servlet.
You need to ensure you only configure your Twitter instance once and not each time a request is made.
One way of achieving this is by asking the TwitterFactory to give you an authenticated instance of Twitter by using TwitterFactory.getInstance(AccessToken):
final AccessToken accessToken = new AccessToken("Your-Access-Token", "Your-Access-Token-Secret");
final Twitter twitter = TwitterFactory.getInstance(token);
...
An added benefit of this factory method is that it may return a cached, authenticated, instance of Twitter for you.
You can use the codebird js library for tweet search. All you need is to create an app on Twitter and note down the following:
Consumer Key
Consumer Secret Key
Access Token
Access Token Secret
Download codebird js Library from the GitHub repository here:
Usage:
var cb = new Codebird;
cb.setConsumerKey('YOURKEY', 'YOURSECRET');
cb.setToken('YOURTOKEN', 'YOURTOKENSECRET');
cb.__call(
'oauth2_token',
{},
function (reply) {
var bearer_token = reply.access_token;
}
);
cb.__call(
'search_tweets',
{
q : "your query which you want to search",
from : twitter_user
},
function (data)
{
console.log(data);
},
true // this parameter required
);
I used this tutorial to search for tweets using twitter api 1.1 with OAuth Authentication
I have modified the code for my usability and it does not use twitter4j, which is good at the moment because OAuth search is not available in the RC build (I read it somewhere unable to find the location at the moment)
Also added getting twitter timeline
Code is in Groovy
TweetsHelper tweetsHelper = new TweetsHelper()
def bearerToken=tweetsHelper.requestBearerToken(TWITTER_AUTH_URL)
List<TweetsInfo> tweets=tweetsHelper.fetchTimelineTweet(bearerToken)
private final def TWITTER_HOST = "api.twitter.com"
private final def TWITTER_AUTH_URL = "https://api.twitter.com/oauth2/token"
private final def TWITTER_URL = "https://api.twitter.com/1.1/statuses/user_timeline.json?screen_name=INFAsupport&count=200"
private HttpsURLConnection getHTTPSConnection(String method,String endpointUrl){
HttpsURLConnection connection = null
URL url = new URL(endpointUrl)
connection = (HttpsURLConnection) url.openConnection()
connection.setDoOutput(true)
connection.setDoInput(true)
connection.setRequestMethod(method)
connection.setRequestProperty("Host", TWITTER_HOST)
connection.setRequestProperty("User-Agent", TWITTER_HANDLE)
connection.setUseCaches(false)
return connection
}
//Fetch Bearertoken for getting tweets
public String requestBearerToken(String endPointUrl) throws IOException {
String encodedCredentials = encodeKeys()
HttpsURLConnection connection = null
try {
connection = getHTTPSConnection("POST",endPointUrl)
connection.setRequestProperty("Authorization", "Basic " + encodedCredentials)
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8")
connection.setRequestProperty("Content-Length", "29")
connection.setUseCaches(false)
}
catch (MalformedURLException e) {
throw new IOException("Invalid endpoint URL specified.", e)
}
finally {
if (connection != null) {
connection.disconnect()
}
}
writeRequest(connection, "grant_type=client_credentials")
JsonSlurper js=new JsonSlurper()
def result=js.parseText(readResponse(connection))
String tokenType = result?.token_type
String token = result?.access_token
return ((tokenType.equals("bearer")) && (token != null)) ? token : ""
}
//Search tweets
public List<TweetsInfo> fetchQueriedTweets(def bearerToken) throws IOException {
HttpsURLConnection connection = null
def dataCleanser = new DataCleanser()
try {
connection = getHTTPSConnection("GET",TWITTER_URL)
connection.setRequestProperty("Authorization", "Bearer " + bearerToken)
}
catch (MalformedURLException e) {
throw new IOException("Invalid endpoint URL specified.", e)
}
finally {
if (connection != null) {
connection.disconnect()
}
}
List<TweetsInfo> tweets= new ArrayList<TweetsInfo>()
try{
JSONObject obj = (JSONObject)JSONValue.parse(readResponse(connection))
JSONArray objArray = (JSONArray)obj.get(TWEET_STATUSES)
if (objArray != null) {
for(int i=0;i<objArray.length();i++){
String text = dataCleanser.escapeQuotes(((JSONObject)objArray.get(i)).get(TWEET_TEXT).toString())
String createdAt = DateUtils.convertToUTC(parseTweetDate(((JSONObject)objArray.get(i)).get(TWEET_CREATED_AT).toString()))
String fromUser = ((JSONObject)objArray.get(i)).get(TWEET_USER).get(TWEET_NAME).toString()
String expandedURL = ((JSONObject)objArray.get(i)).get(TWEET_ENTITIES).get(TWEET_URLS).get(0).get(TWEET_EXPANDED_URL).toString()
TweetsInfo tweet=new TweetsInfo(text,fromUser,expandedURL,createdAt)
tweets.push(tweet)
}
}
}
catch(Exception e){
log.info "Exception in TweetsHelper $e"
}
return tweets
}
//Fetch Twitter timeline
public List<TweetsInfo> fetchTimelineTweet(def bearerToken) throws IOException {
HttpsURLConnection connection = null
List<TweetsInfo> tweets= new ArrayList<TweetsInfo>()
def dataCleanser = new DataCleanser()
try {
connection = getHTTPSConnection("GET",TWITTER_URL)
connection.setRequestProperty("Authorization", "Bearer " + bearerToken)
}
catch (MalformedURLException e) {
throw new IOException("Invalid endpoint URL specified.", e)
}
finally {
if (connection != null) {
connection.disconnect()
}
}
JsonSlurper js=new JsonSlurper()
try{
def result=js.parseText(readResponse(connection))
result?.each{tweet->
String text = tweet?.text
String createdAt = DateUtils.convertToUTC(parseTweetDate(tweet?.created_at))
String fromUser = tweet?.user?.name
String expandedURL = tweet?.entities?.urls[0]?.expanded_url
if(validTweetForAWeek(createdAt)){
TweetsInfo tweetinfo=new TweetsInfo(text,fromUser,expandedURL,createdAt)
tweets.push(tweetinfo)
}
}
}
catch(Exception e){
log.info "Exception in TweetsHelper $e"
}
return tweets
}
TweetsInfo is a Pojo class with String text, String fromUser, String expandedURL, String createdAt (this was my requirement)
Hope this helps :)

Salesforce REST API Login?

I am examining a sample which is in the salesforce developer site.
In that sample when we click a link it will be redirected to the salesforce login page. If the login successful, then an access token is issued.
I dont want my application to redirect to the salesforce login page. In the existing sample the environment variable is set to,
"https://login.salesforce.com"
What should I do to avoid redirecting to salesforce login page.
What you're describing, sounds like OAuth (just because you mention access-token).
There's a good example of OAuth being used in Salesforce below...
http://wiki.developerforce.com/page/Digging_Deeper_into_OAuth_2.0_at_Salesforce.com
SOLUTION:
Hi all, I have arrived the solution to my problem. Actually, I was examining the sample given in the link http://wiki.developerforce.com/page/Getting_Started_with_the_Force.com_REST_API . Then implemented OAuth 2.0 Username-Password Flow which is from https://login.salesforce.com/help/doc/en/remoteaccess_oauth_username_password_flow.htm#send_up_response. It solves my problem.
This is sample Java code that uses Username-Password OAuth flow:
public class AccountQuery
{
// The connection data
private static final String query = "SELECT Name, Idfrom Account";
private static final String clientId = "theID";
private static final String clientSecret = "theSecret";
// THis is meaningless in our context
private static final String redirectUri = "https://localhost:8443/_callback";
private static final String environment = "https://login.salesforce.com";
private static String tokenUrl = null;
private static final String username = "username";
private static final String password = "passwordPlusSecret";
private static String accessToken = null;
private static String instanceUrl = null;
public static void main( String[] args )
{
// Step 0: Connect to SalesForce.
System.out.println("Getting a token");
tokenUrl = environment + "/services/oauth2/token";
HttpClient httpclient = new HttpClient();
PostMethod post = new PostMethod(tokenUrl);
post.addParameter("grant_type", "password");
post.addParameter("client_id", clientId);
post.addParameter("client_secret", clientSecret);
post.addParameter("redirect_uri", redirectUri);
post.addParameter("username", username);
post.addParameter("password", password);
try {
httpclient.executeMethod(post);
try {
JSONObject authResponse = new JSONObject(new JSONTokener(new InputStreamReader(post.getResponseBodyAsStream())));
System.out.println("Auth response: " + authResponse.toString(2));
accessToken = authResponse.getString("access_token");
instanceUrl = authResponse.getString("instance_url");
System.out.println("Got access token: " + accessToken);
} catch (JSONException e) {
e.printStackTrace();
}
} catch (HttpException e1) {
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
} finally {
post.releaseConnection();
}
System.out.println("We have an access token: " + accessToken + "\n" + "Using instance " + instanceUrl + "\n\n");
HttpClient httpclient = new HttpClient();
GetMethod get = new GetMethod(instanceUrl + "/services/data/v28.0/query");
// set the token in the header
get.setRequestHeader("Authorization", "OAuth " + accessToken);
// set the SOQL as a query param
NameValuePair[] params = new NameValuePair[1];
params[0] = new NameValuePair("q",query);
get.setQueryString(params);
try {
httpclient.executeMethod(get);
if (get.getStatusCode() == HttpStatus.SC_OK) {
// Now lets use the standard java json classes to work with the results
JSONObject response = new JSONObject( new JSONTokener( new InputStreamReader(get.getResponseBodyAsStream())));
System.out.println("Query response: "+ response.toString(2));//.substring(0, 500));
System.out.println(response.getString("totalSize") + " record(s) returned\n\n");
JSONArray results = response.getJSONArray("records");
Account[] accounts = new Gson().fromJson(results.toString(), Account[].class);
return accounts;
}
}
catch (Exception e){
e.printStackTrace();
}finally {
get.releaseConnection();
}
}
}
In case of Java, the easiest way is to use Spring Social Salesforce: https://github.com/iirekm/spring-social-salesforce
Just follow the Facebook tutorial at https://spring.io/guides/gs/accessing-facebook/, and shortly-speaking add dependency to Spring Social Salesforce and replace everywhere in code "facebook" with "salesforce".

Categories

Resources