Sunday 23 September 2012

Open Connection SalesForce Rest API

Hi

I have written a sample code in java to make a persistent connection to Salesforce's Rest API, This example uses Oauth Grant_Type ="password" to provide a fresh access_token each time the request is made.

Please find the code below. To make this code work you need to add package <httpcomponents-client> to your classpath. which can easily be downloaded from  http://hc.apache.org/httpcomponents-client-ga/

 


Please find the code :

package connection;

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

import org.apache.http.HttpException;
import org.apache.http.HttpResponse;
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.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.JSONValue;



public class OauthConnection {

    //Variables to be populated after gaining the Access token.
    private String accessToken = null;
    private Map<String, String> oauthLoginResponse;
   
    //Constants to be used in this class.
    private static final String clientId = <Your Client ID>;  
    private static final String clientSecret = <Your Client Secret>;
    private static final String environment = "<SalesForce Instance>";
    private static final String authUrl = "/services/oauth2/token";
    private static final String restUrl = "/services/data/v25.0/";
    private static final String queryUrl = "/services/data/v25.0/query";
    private static final String username = "<Your SFDC USER NAME>";
    private static final String password = <SFDC PASSWORD WITH SECURITY TOKEN>;
   
   
   
    public static void main(String[] args){
        try{
       
            OauthConnection oc = new OauthConnection();
            oc.oAuthSessionProvider();
           
            oc.executeQuery();
       
        }catch(Exception e){
            e.printStackTrace();
        }
      }
       
    public void oAuthSessionProvider()
            throws HttpException, IOException
    {
        // Set up an HTTP client that makes a connection to REST API.
        DefaultHttpClient client = new DefaultHttpClient();
        HttpParams params = client.getParams();
        params.setParameter(HttpConnectionParams.CONNECTION_TIMEOUT, 30000);

        // Set the SID.
        System.out.println("Logging in as " + username + " in environment " + environment);
        String baseUrl = environment + authUrl;
       
        // 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", clientSecret));
        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();
      
        System.out.println("Code >> " +code);
       
        //populate Response map to fetch ACCESS TOKEN for any future call.
        this.oauthLoginResponse = (Map<String, String>)JSONValue.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()));
        }
       
        //Populate Access Token 
        this.accessToken = oauthLoginResponse.get("access_token");
        System.out.println("");
    }
   
    public void executeQuery(){
         DefaultHttpClient httpClient = new DefaultHttpClient();
       
        List<BasicNameValuePair> qsList = new ArrayList<BasicNameValuePair>();
        qsList.add(new BasicNameValuePair("q", "Select a.ParentId, a.OwnerId, a.Name, a.IsPrivate,  a.Id, a.Description, a.ContentType, a.BodyLength, a.Body " +
                "                                From Attachment a where  a.ParentId = '00390000006DEGb'"));
       
        String queryString = URLEncodedUtils.format(qsList, HTTP.UTF_8);
        HttpGet get = new HttpGet(environment + queryUrl+"?"+queryString);
        get.setHeader("Authorization", "OAuth " + accessToken);
        try{
            HttpResponse queryResponse = httpClient.execute(get);
           
            System.out.println(queryResponse.getStatusLine().getReasonPhrase());
              Map<String, Object> querynfo = (Map<String, Object>)
                        JSONValue.parse(EntityUtils.toString(queryResponse.getEntity()));
             
              System.out.println("Query response");
                for (Map.Entry<String, Object> entry : querynfo.entrySet())
                {
                    System.out.println(String.format("  %s = %s", entry.getKey(), entry.getValue()));
                }
                System.out.println("");
             
        }catch(Exception e){
            e.printStackTrace();
        }
       
    }
 }

Tuesday 4 September 2012

com.salesforce.ide.api.metadata.types.Metadata$JaxbAccessorF_fullName cannot be cast to com.sun.xml.internal.bind.v2.runtime.reflect.Accessor

While creating New Force.com project or while adding new resource to your already existing projects, if you are getting the below mentioned error message.

com.salesforce.ide.api.metadata.types.Metadata$JaxbAccessorF_fullName cannot be cast to com.sun.xml.internal.bind.v2.runtime.reflect.Accessor

 Please follow the steps below.

This error is because of the Java 1.7 so till the time this release gets fixed, we need to downgrade our JRE to 1.6, this could be a really tedious task and the simplest way that I found and  I did was, Replaced the contents of floder C:\Program Files\Java\jre7 with that of C:\Program Files\Java\jre6 (i already had java 6 hence i could do so, If you do not have you would need to download Jre6).

Doing above mentioned swapping of files saved me from uninstalling (Java7) and reinstalling (Java6) just by copying files of these two folders i can anytime switch back to java7 or java6 as per my requirement.