2

EDIT I am struggling to add the correct formatting to the code post below. if someone can edit this question and apply the proper formatting to code, i would appreciate it.

I am fairly new to salesforce and as a required to our project in have to create a standalone java client for chatter. I have already developed clients for reading, writing data to salesforce custom objects using WSDL from apex classes. Since Chatter is REST based, i am not able to integrate it. I am facing problem with generating the oAuth access tokens. When i am making calls to the https://login.salesforce.com/services/oauth2/token i am getting error message as connection refused. Most of the tutorial i checked get access token using cUrl but i want it all to be done through a JAVA application.

I am behind a corporate firewall and have configured my proxy accordingly. Here is the code that i have developed.

package com.chatter.sf;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.xml.rpc.ServiceException;
import javax.xml.soap.SOAPException;


import org.apache.http.HttpException;
import org.apache.http.HttpResponse;
import org.apache.http.ParseException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.params.CookiePolicy;
import org.apache.http.client.params.HttpClientParams;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.json.simple.parser.JSONParser;

public class SfChatter {






    @SuppressWarnings("unchecked")
    public static void oAuthSessionProvider(String loginHost, String username,
            String password, String clientId, String secret)
            throws HttpException, IOException, ParseException, org.json.simple.parser.ParseException, ServiceException, SOAPException 
    {

        JSONParser parser = new JSONParser();

        // Set up an HTTP client that makes a connection to REST API.
        DefaultHttpClient client = new DefaultHttpClient();
        HttpParams params = client.getParams();
       HttpClientParams.setCookiePolicy(params, CookiePolicy.RFC_2109);
        params.setParameter(HttpConnectionParams.CONNECTION_TIMEOUT,100000);

        // Set the SID.
        System.out.println("Logging in as " + username + " in environment " + loginHost);

       //String baseUrl = loginHost;


         String baseUrl = loginHost + "/services/oauth2/token";

        HttpPost oauthPost = new HttpPost(baseUrl);





        // The request body must contain these 5 values.
        List<BasicNameValuePair> parametersBody = new ArrayList<BasicNameValuePair>();



       parametersBody.add(new BasicNameValuePair("grant_type", "password"));
       parametersBody.add(new BasicNameValuePair("username", username));
       parametersBody.add(new BasicNameValuePair("password", password));
       parametersBody.add(new BasicNameValuePair("client_id", clientId));
       parametersBody.add(new BasicNameValuePair("client_secret", secret));
        oauthPost.setEntity(new UrlEncodedFormEntity(parametersBody, HTTP.UTF_8));

        // Execute the request.
        System.out.println("POST " + baseUrl + "...\n");
        HttpResponse response=null;
        try{
         response= client.execute(oauthPost);
        }
        catch(Exception e)
        {
            System.out.println("Exception is= "+e.getMessage());
        }
        @SuppressWarnings("unused")
        int code = response.getStatusLine().getStatusCode();
        Map<String, String> oauthLoginResponse = (Map<String, String>)
            parser.parse(EntityUtils.toString(response.getEntity()));
        System.out.println("OAuth login response");
        for (Map.Entry<String, String> entry : oauthLoginResponse.entrySet()) 
        {
            System.out.println(String.format("  %s = %s", entry.getKey(), entry.getValue()));
        }
        System.out.println("");

        // Get user info.
        String userIdEndpoint = oauthLoginResponse.get("id");
        String accessToken = oauthLoginResponse.get("access_token");
        List<BasicNameValuePair> qsList = new ArrayList<BasicNameValuePair>();
        qsList.add(new BasicNameValuePair("oauth_token", accessToken));
        String queryString = URLEncodedUtils.format(qsList, HTTP.UTF_8);
        HttpGet userInfoRequest = new HttpGet(userIdEndpoint + "?" + queryString);
        HttpResponse userInfoResponse = client.execute(userInfoRequest);
        Map<String, Object> userInfo = (Map<String, Object>)
            parser.parse(EntityUtils.toString(userInfoResponse.getEntity()));
        System.out.println("User info response");
        for (Map.Entry<String, Object> entry : userInfo.entrySet()) 
        {
            System.out.println(String.format("  %s = %s", entry.getKey(), entry.getValue()));
        }
        System.out.println("");

        // Use the user info in interesting ways.
        System.out.println("Username is " + userInfo.get("username"));
        System.out.println("User's email is " + userInfo.get("email"));
        Map<String, String> urls = (Map<String, String>)userInfo.get("urls");
        System.out.println("REST API url is " + urls.get("rest").replace("{version}", "31.0"));
    }




public static void main(String args[]) throws ParseException, HttpException, IOException, org.json.simple.parser.ParseException, ServiceException, SOAPException    
{
     String loginhost="https://login.salesforce.com";


    String username="balaji.sozharajan@wipro.com";
 String password="*****";
 String client_id="3MVG9Y6d_Btp4xp5EMJiZPLQ0WUTN2aYG5RxGBlTZsB8xM97W4ehLHQKYMGTxSIAR6SGVsjLm3a.opMthTIE2";
 String client_key="************";



    System.getProperties().put("http.proxyHost", "proxy2.wipro.com");
    System.getProperties().put("http.proxyPort", "80");
    System.getProperties().put("http.proxyUser", "sh265993");
    System.getProperties().put("http.proxyPassword", "*********");


 oAuthSessionProvider(loginhost,username,password, client_id, client_key);

}



}

I have spent enire week finding a solution but still haven't found a way out. Any solution or suggestion would be highly appreciated.

Here is the stacktrace after executing the code given by @Mohith

Logging in as balaji.sozharajan@wipro.com in environment https://login.salesforce.com
POST https://login.salesforce.com/services/oauth2/token...

Connection refused: connect
java.net.ConnectException: Connection refused: connect
    at java.net.DualStackPlainSocketImpl.waitForConnect(Native Method)
    at java.net.DualStackPlainSocketImpl.socketConnect(Unknown Source)
    at java.net.AbstractPlainSocketImpl.doConnect(Unknown Source)
    at java.net.AbstractPlainSocketImpl.connectToAddress(Unknown Source)
    at java.net.AbstractPlainSocketImpl.connect(Unknown Source)
    at java.net.PlainSocketImpl.connect(Unknown Source)
    at java.net.SocksSocketImpl.connect(Unknown Source)
    at java.net.Socket.connect(Unknown Source)
    at sun.security.ssl.SSLSocketImpl.connect(Unknown Source)
    at org.apache.http.conn.ssl.SSLSocketFactory.connectSocket(SSLSocketFactory.java:524)
    at org.apache.http.conn.ssl.SSLSocketFactory.connectSocket(SSLSocketFactory.java:403)
    at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:177)
    at org.apache.http.impl.conn.ManagedClientConnectionImpl.open(ManagedClientConnectionImpl.java:304)
    at org.apache.http.impl.client.DefaultRequestDirector.tryConnect(DefaultRequestDirector.java:611)
    at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:446)
    at org.apache.http.impl.client.AbstractHttpClient.doExecute(AbstractHttpClient.java:863)
    at org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:82)
    at org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:106)
    at com.wipro.coe.Action.TestCallout.oAuthSessionProvider(TestCallout.java:54)
    at com.wipro.coe.Action.TestCallout.main(TestCallout.java:98)
  • To format when editing, select the code and click the {} button. – Keith C Jul 24 '14 at 10:02
  • based on the stack trace, your code is not trying to connect via a proxy, so you need to revisit that part of the code. – superfell Apr 8 '15 at 19:19
  • there doesn't appear to be any code in your example that is configuring the use of a proxy. – superfell Apr 8 '15 at 19:20
1

The documentation link is below for oauth using Java client .

http://www.salesforce.com/us/developer/docs/api_streaming/Content/code_sample_auth_oauth.htm

public static void oAuthSessionProvider(String loginHost, String username,
    String password, String clientId, String secret)
    throws HttpException, IOException {
// Set up an HTTP client that makes a connection to REST API.
DefaultHttpClient client = new DefaultHttpClient();
HttpParams params = client.getParams();
HttpClientParams.setCookiePolicy(params, CookiePolicy.RFC_2109);
params.setParameter(HttpConnectionParams.CONNECTION_TIMEOUT, 30000);

// Set the SID.
System.out.println("Logging in as " + username + " in environment " + loginHost);
String baseUrl = loginHost + "/services/oauth2/token";
// Send a post request to the OAuth URL.
HttpPost oauthPost = new HttpPost(baseUrl);
// The request body must contain these 5 values.
List<BasicNameValuePair> parametersBody = new ArrayList<BasicNameValuePair>();
parametersBody.add(new BasicNameValuePair("grant_type", "password"));
parametersBody.add(new BasicNameValuePair("username", username));
parametersBody.add(new BasicNameValuePair("password", password));
parametersBody.add(new BasicNameValuePair("client_id", clientId));
parametersBody.add(new BasicNameValuePair("client_secret", secret));
oauthPost.setEntity(new UrlEncodedFormEntity(parametersBody, HTTP.UTF_8));

// Execute the request.
System.out.println("POST " + baseUrl + "...\n");
HttpResponse response = client.execute(oauthPost);
int code = response.getStatusLine().getStatusCode();
Map<String, String> oauthLoginResponse = (Map<String, String>)
    JSON.parse(EntityUtils.toString(response.getEntity()));
System.out.println("OAuth login response");
for (Map.Entry<String, String> entry : oauthLoginResponse.entrySet()) 
{
    System.out.println(String.format("  %s = %s", entry.getKey(), entry.getValue()));
}
System.out.println("");

// Get user info.
String userIdEndpoint = oauthLoginResponse.get("id");
String accessToken = oauthLoginResponse.get("access_token");
List<BasicNameValuePair> qsList = new ArrayList<BasicNameValuePair>();
qsList.add(new BasicNameValuePair("oauth_token", accessToken));
String queryString = URLEncodedUtils.format(qsList, HTTP.UTF_8);
HttpGet userInfoRequest = new HttpGet(userIdEndpoint + "?" + queryString);
HttpResponse userInfoResponse = client.execute(userInfoRequest);
Map<String, Object> userInfo = (Map<String, Object>)
    JSON.parse(EntityUtils.toString(userInfoResponse.getEntity()));
System.out.println("User info response");
for (Map.Entry<String, Object> entry : userInfo.entrySet()) 
{
    System.out.println(String.format("  %s = %s", entry.getKey(), entry.getValue()));
}
System.out.println("");

// Use the user info in interesting ways.
System.out.println("Username is " + userInfo.get("username"));
System.out.println("User's email is " + userInfo.get("email"));
Map<String, String> urls = (Map<String, String>)userInfo.get("urls");
System.out.println("REST API url is " + urls.get("rest").replace("{version}", "31.0"));
}

The above code uses the Apache HttpClient library which may be downloaded from http://hc.apache.org/httpcomponents-client-ga/.

  • Thanks for your reply. i have posted the error stacktrace i got after running the code provided by you. I am getting connection refused error. I have given login host as login.salesforce.com – Sheikh Zubair Jul 24 '14 at 11:34
  • Can you come out of your network and try this .Expecting its proxy thats refusing your connection – Mohith Shrivastava Jul 24 '14 at 11:39
  • I have exposed some apex classes as webservices and am able to consume them with the same proxy settings. so i dont think that is the issue here. – Sheikh Zubair Jul 25 '14 at 5:50

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.