Showing posts with label Java. Show all posts
Showing posts with label Java. Show all posts

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();
        }
       
    }
 }

Monday, 30 January 2012

Download Salesforce Attachments on Drive.

Many a times in salesforce we need to download selective attachments, in that case the SFDC's Data Export tool doesn't seem helpful as it will download all the attachments (yes you can select objects but not the records in that object). So for this purpose i have written a small Java code, that will take help of the enterprise wsdl of the org from which i need to extract the data.

To generate code stub from enterprise wsdl you need WSC jar, which can be downloaded easily from net, once you get it, go to command prompt and paste the below mentioned command, with your own directory structure and it will generate the required jar to make connections to your org.

java -classpath  < YOUR PATH OF WSC JAR>\wsc-20.jar com.sforce.ws.tools.wsdlc  <PATH where you have kept your enterprise wsdl> \enterprise.wsdl  <PATH where you want to genrate the jar> \Enterprise.jar

Include this newly generated jar into your Java(Eclipse's) build path, and you are ready to make connection to your org.

This code will also create a CSV file to relate the parent with that to its attachment(s).


package com.mypackage;

import java.io.BufferedWriter;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.sforce.soap.enterprise.Connector;
import com.sforce.soap.enterprise.EnterpriseConnection;
import com.sforce.soap.enterprise.QueryResult;
import com.sforce.soap.enterprise.sobject.Account;
import com.sforce.soap.enterprise.sobject.Attachment;
import com.sforce.ws.ConnectionException;
import com.sforce.ws.ConnectorConfig;

public class ExportAttachments {
 
  static final String USERNAME = "<YOUR USER NAME>";
  static final String PASSWORD = "<YOUR PASSWORD>";
  static EnterpriseConnection connection;
  static final String ATTACHIDS ="00P50000007HYMJEA4,00P50000007HmAjEAK,00P50000004CmZ3EAK";
  static final String AccountIds = "0015000000SQSmIAAX,0015000000bBP1pAAG,0015000000bCfjTAAS,0015000000LKHCFAA5";
 
  static List<String> str = new ArrayList<String>();
  static List<String> stracct = new ArrayList<String>();
  static Map<String,String> idMap = new HashMap<String,String>();
  static Map<String,String> csvMap = new HashMap<String,String>();
 

  public static void main(String[] args) {

    ConnectorConfig config = new ConnectorConfig();
    config.setUsername(USERNAME);
    config.setPassword(PASSWORD);
    //config.setTraceMessage(true);
    str = Arrays.asList(ATTACHIDS.split(","));
    stracct = Arrays.asList(AccountIds.split(","));
    for(String s:stracct){
        idMap.put(s,s);
    }
    try {
     
      connection = Connector.newConnection(config);
     
      // display some current settings
      System.out.println("Auth EndPoint: "+config.getAuthEndpoint());
      System.out.println("Service EndPoint: "+config.getServiceEndpoint());
      System.out.println("Username: "+config.getUsername());
      System.out.println("SessionId: "+config.getSessionId());
   
      queryAccounts();
      createCSV();
      queryAttachments();
     
    } catch (ConnectionException e1) {
        e1.printStackTrace();
    } 

  }
 
 private static void queryAccounts() {
       
        
        try {
          for(String s:idMap.keySet()){
          // query for the 5 newest contacts     
          QueryResult queryResults = connection.query("SELECT Id, VSX_ID__c " +
                  "FROM Account WHERE Id in ('"+s+"')");
          if (queryResults.getSize() > 0) {
            for (int i=0;i<queryResults.getRecords().length;i++) {
              // cast the SObject to a strongly-typed Account
              Account a = (Account)queryResults.getRecords()[i];
              csvMap.put(a.getId(),a.getVSX_ID__c());
            }
          }
           }
        } catch (Exception e) {
          e.printStackTrace();
        }   
       
      }
 
  private static void queryAttachments() {
      try{
          for(String s:str){
           QueryResult queryResults = connection.query("Select Id, ParentId, Name, ContentType, Body " +
            "From Attachment WHERE id in('"+s+"')");
       
           if (queryResults.getSize() > 0) {
               for (int i=0;i<queryResults.getRecords().length;i++) {
                  // cast the SObject to a strongly-typed Contact
                    Attachment a = (Attachment)queryResults.getRecords()[i];
                    writeOnDisk(a.getId()+"-"+a.getName(),a.getBody());
                    System.out.println("Id: " + a.getId() + " - Name: "+a.getName()+" "+" - Account: "+a.getParentId());
                }
              }
          }
      }catch (Exception e) {
          e.printStackTrace();
        }   
     
     
  }
 
  private static void writeOnDisk(String fileName, byte[] bdy){
      try
      {
          String filePath = "C://Documents and Settings//varun//Desktop//JavaExport//"+fileName;
          FileOutputStream fos = new FileOutputStream(filePath);//File OutPutStream is used to write Binary Contents like pictures
          fos.write(bdy);
          fos.close();
      }
      catch (IOException e)
      {
      System.out.println(e.getMessage());
      }
  }
 
  private static void createCSV(){
      try
      {   
          String toWrite="";
   
          if(csvMap!=null){
              for(String s:csvMap.keySet()){
                  toWrite +="\""+s+"\""+","+"\""+csvMap.get(s)+"\"\n";
              }
         
          System.out.println(toWrite);
          String file_name = "C://Documents and Settings//varun//Desktop//JavaExport/AccountVSX.csv";
          FileWriter file = new FileWriter(file_name);
          BufferedWriter out = new BufferedWriter (file);
          out.write(toWrite);
          out.close();
          }
      }
      catch (IOException e)
      {
          System.out.println(e.getMessage());
      }
  }


}