Connected App :
Create connected app in SFDC side and put call back url as : https://localhost:8443/_callback
CliendId and Secret :
Client_Id and Client_Secret would be generated by system automatically
Get Access Token :
Get the access token from salesforce.
Jar Files :
commons-codec-1.7.jar
commons-httpclient-3.1.jar
java-json.jar
org-apache-commons-logging.jar
org.json.jar
gson-2.2.2.jar
jackson-mapper-asl-1.2.0.jar
jackson-all-1.9.0.jar
httpcore-4.2.3.jar
Complete Java Class :
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Scanner;
import javax.swing.text.html.HTMLDocument.Iterator;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.DeleteMethod;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.RequestEntity;
import org.apache.commons.httpclient.methods.StringRequestEntity;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;
public class AccountQuery{
private static final String clientId = "3MVG9Y6d_Btp4xp5fHfBCvTWgHlfBKxrEf0lFIt9p71zfTmei0q9P8QxoaRowTIefchOoNdY8syyWOriUKYlV";
private static final String clientSecret = "7975635620731036814";
// THis is meaningless in our context
private static final String redirectUri = "https://localhost:8443/_callback";
private static final String environment = "https://ap1.salesforce.com";
private static String tokenUrl = null;
public static final String username = "Your userName";
public static final String password = "Your Password";
private static String accessToken = null;
private static String instanceUrl = null;
public void accessTokenSFDC(){
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);
System.out.println("-------------------Request has been done--------------------------\n\n");
} catch (JSONException e) {
e.printStackTrace();
}
} catch (HttpException e1) {
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
}
}
public static void main( String[] args ) throws Exception{
new AccountQuery().accessTokenSFDC();//getting access token from this method
//new AccountQuery().CreateAccount(instanceUrl,accessToken);//responsible for create account and contact records.
//new AccountQuery().queryAccountObject(instanceUrl, accessToken);//responsible for query account records.
//new AccountQuery().patch(instanceUrl, accessToken);//responsible for updating records
//new AccountQuery().showAccountId(instanceUrl, accessToken);//responsible for query account records.
//new AccountQuery().deleteRecords(instanceUrl, accessToken);//responsible for query account records.
new AccountQuery().patchRecord(instanceUrl, accessToken);
}
public String CreateAccount(String instanceUrl, String accessToken) throws Exception{
System.out.println("---------------------Creating Account Record in SFDC------------------------");
HttpClient httpclient = new HttpClient();
JSONObject account = new JSONObject();
Scanner scanner = new Scanner(System.in);
System.out.print("Enter Account name: ");
String name = scanner.next();
System.out.print("Enter AccountNumber Number : ");
String accountNumber = scanner.next();
System.out.print("Enter AnnualRevenue : ");
String annualRevenue = scanner.next();
System.out.print("Enter Description : ");
String description = scanner.next();
System.out.print("Enter Industry : ");
String industry = scanner.next();
System.out.print("Enter Phone : ");
String phone = scanner.next();
System.out.print("Enter Active (Yes/No) : ");
String isActive = scanner.next();
System.out.print("Enter Customer Priority : ");
String customerPriority = scanner.next();
System.out.print("Enter Number of Locations : ");
String numberofLocations = scanner.next();
System.out.print("Enter SLA (GOLD/Silver) : ");
String slaValue = scanner.next();
try{
account.put("Name",name);
account.put("AccountNumber",accountNumber);
account.put("AnnualRevenue",annualRevenue);
account.put("Description",description);
account.put("Industry",industry);
account.put("Phone",phone);
account.put("Active__c",isActive);
account.put("CustomerPriority__c",customerPriority);
account.put("NumberofLocations__c",numberofLocations);
account.put("SLA__c",slaValue);
PostMethod post = new PostMethod(instanceUrl+"/services/data/v20.0/sobjects/Account");
post.setRequestHeader("Authorization", "OAuth " + accessToken);
post.setRequestEntity(new StringRequestEntity(account.toString(),"application/json","UTF-8"));
httpclient.executeMethod(post);
System.out.println("Get HTTP status :"+post.getStatusCode());
if(post.getStatusCode()==201){
try{
JSONObject response = new JSONObject(new JSONTokener(new InputStreamReader(post.getResponseBodyAsStream())));
System.out.println("Create Response : "+response.toString(2));
if(response.getBoolean("success")){
String accountid= response.getString("id");
System.out.println("New Record has been created withe ID : "+accountid);
createContactRecords(accountid,instanceUrl,accessToken);
}
}catch (Exception e1) {
e1.printStackTrace();
}
}
}catch (Exception e1) {
e1.printStackTrace();
}
System.out.println("-----------------------Records has been create successfully-------------------------\n\n");
return null;
}
public String createContactRecords(String accountid,String instanceUrl, String accessToken) throws Exception{
HttpClient httpclientContact = new HttpClient();
JSONObject contact = new JSONObject();
contact.put("LastName", "SFDC-Fazu");
contact.put("AccountId",accountid);
PostMethod postContact = new PostMethod(instanceUrl+"/services/data/v20.0/sobjects/Contact");
postContact.setRequestHeader("Authorization", "OAuth " + accessToken);
postContact.setRequestEntity(new StringRequestEntity(contact.toString(),"application/json","UTF-8"));
try{
httpclientContact.executeMethod(postContact);
System.out.println("Get HTTP status :"+postContact.getStatusCode());
JSONObject responseContact = new JSONObject(new JSONTokener(new InputStreamReader(postContact.getResponseBodyAsStream())));
System.out.println("Create Response : "+responseContact.toString(2));
}catch (Exception e1) {
e1.printStackTrace();
}
return null;
}
public void queryAccountObject(String instanceUrl, String accessToken)throws Exception{
HttpClient httpClient= new HttpClient();
GetMethod get = new GetMethod(instanceUrl+"/services/data/v20.0/query");
get.setRequestHeader("Authorization", "OAuth " + accessToken);
NameValuePair[] params = new NameValuePair[1];
params[0]=new NameValuePair("q","select id,name from account");
get.setQueryString(params);
try{
httpClient.executeMethod(get);
if(get.getStatusCode()==HttpStatus.SC_OK){
try{
JSONObject response = new JSONObject(new JSONTokener(new InputStreamReader(get.getResponseBodyAsStream())));
System.out.println("Query Response :"+response.toString(2) );
System.out.println(response.get("totalSize")+"record(s) returned \n\n");
JSONArray results = response.getJSONArray("records");
for(int i = 0;i < results.length();i++){
System.out.println(results.getJSONObject(i).getString("Id")+"-----"+results.getJSONObject(i).getString("Name")+"\n" );
}
System.out.println("\n");
}catch (Exception e1) {
e1.printStackTrace();
}
}
}catch (Exception e1) {
e1.printStackTrace();
}
}
public void showAccountId(String instanceUrl, String accessToken)throws Exception{
HttpClient httpClient= new HttpClient();
GetMethod get = new GetMethod(instanceUrl+"/services/data/v20.0/sobjects/Account/0019000001qmYdAAAU");
get.setRequestHeader("Authorization", "OAuth " + accessToken);
try{
httpClient.executeMethod(get);
if(get.getStatusCode()==HttpStatus.SC_OK){
try{
JSONObject response = new JSONObject(new JSONTokener(new InputStreamReader(get.getResponseBodyAsStream())));
System.out.println("Query Response :"+response.toString(2) );
java.util.Iterator iterator = response.keys();
while(iterator.hasNext() ){
String key = (String)iterator.next();
String value = (String)iterator.next();
System.out.println(key + ":"+(value !=null ? value : "")+"\n");
}
}catch (Exception e1) {
e1.printStackTrace();
}
}
}catch (Exception e1) {
e1.printStackTrace();
}
}
public void deleteRecords(String instanceUrl, String accessToken)throws Exception{
Scanner scanner = new Scanner(System.in);
System.out.print("Enter Account ID : ");
String accountId = scanner.next();
HttpClient httpClient= new HttpClient();
DeleteMethod deleteMethod = new DeleteMethod(instanceUrl+"/services/data/v20.0/sobjects/Account/"+accountId);
deleteMethod.setRequestHeader("Authorization", "OAuth " + accessToken);
try{
httpClient.executeMethod(deleteMethod);
System.out.println("Http Status"+deleteMethod.getStatusCode()+"Deleting account \n\n");
}catch (Exception e1) {
e1.printStackTrace();
}
}
public static void patchRecord(String instanceUrl, String accessToken) throws Exception{
Scanner scanner = new Scanner(System.in);
System.out.print("Enter Account ID : ");
String accountId = scanner.next();
HttpClient httpClient = new HttpClient();
JSONObject update = new JSONObject();
try{
update.put("name", "SFDC-Fazu patch test");
}catch (Exception e1) {
e1.printStackTrace();
}
PostMethod post = new PostMethod(instanceUrl+"/services/data/v20.0/sobjects/Account/"+accountId) {
@Override public String getName() { return "PATCH"; }
};
post.setRequestHeader("Authorization", "OAuth " + accessToken);
post.setRequestEntity(new StringRequestEntity(update.toString(),"application/json","UTF-8"));
try{
httpClient.executeMethod(post);
System.out.println("Http Status"+post.getStatusCode()+" updated successfully \n\n");
}catch (Exception e1) {
e1.printStackTrace();
}
}
}
Create connected app in SFDC side and put call back url as : https://localhost:8443/_callback
CliendId and Secret :
Client_Id and Client_Secret would be generated by system automatically
Get Access Token :
Get the access token from salesforce.
Jar Files :
commons-codec-1.7.jar
commons-httpclient-3.1.jar
java-json.jar
org-apache-commons-logging.jar
org.json.jar
gson-2.2.2.jar
jackson-mapper-asl-1.2.0.jar
jackson-all-1.9.0.jar
httpcore-4.2.3.jar
Complete Java Class :
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Scanner;
import javax.swing.text.html.HTMLDocument.Iterator;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.DeleteMethod;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.RequestEntity;
import org.apache.commons.httpclient.methods.StringRequestEntity;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;
public class AccountQuery{
private static final String clientId = "3MVG9Y6d_Btp4xp5fHfBCvTWgHlfBKxrEf0lFIt9p71zfTmei0q9P8QxoaRowTIefchOoNdY8syyWOriUKYlV";
private static final String clientSecret = "7975635620731036814";
// THis is meaningless in our context
private static final String redirectUri = "https://localhost:8443/_callback";
private static final String environment = "https://ap1.salesforce.com";
private static String tokenUrl = null;
public static final String username = "Your userName";
public static final String password = "Your Password";
private static String accessToken = null;
private static String instanceUrl = null;
public void accessTokenSFDC(){
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);
System.out.println("-------------------Request has been done--------------------------\n\n");
} catch (JSONException e) {
e.printStackTrace();
}
} catch (HttpException e1) {
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
}
}
public static void main( String[] args ) throws Exception{
new AccountQuery().accessTokenSFDC();//getting access token from this method
//new AccountQuery().CreateAccount(instanceUrl,accessToken);//responsible for create account and contact records.
//new AccountQuery().queryAccountObject(instanceUrl, accessToken);//responsible for query account records.
//new AccountQuery().patch(instanceUrl, accessToken);//responsible for updating records
//new AccountQuery().showAccountId(instanceUrl, accessToken);//responsible for query account records.
//new AccountQuery().deleteRecords(instanceUrl, accessToken);//responsible for query account records.
new AccountQuery().patchRecord(instanceUrl, accessToken);
}
public String CreateAccount(String instanceUrl, String accessToken) throws Exception{
System.out.println("---------------------Creating Account Record in SFDC------------------------");
HttpClient httpclient = new HttpClient();
JSONObject account = new JSONObject();
Scanner scanner = new Scanner(System.in);
System.out.print("Enter Account name: ");
String name = scanner.next();
System.out.print("Enter AccountNumber Number : ");
String accountNumber = scanner.next();
System.out.print("Enter AnnualRevenue : ");
String annualRevenue = scanner.next();
System.out.print("Enter Description : ");
String description = scanner.next();
System.out.print("Enter Industry : ");
String industry = scanner.next();
System.out.print("Enter Phone : ");
String phone = scanner.next();
System.out.print("Enter Active (Yes/No) : ");
String isActive = scanner.next();
System.out.print("Enter Customer Priority : ");
String customerPriority = scanner.next();
System.out.print("Enter Number of Locations : ");
String numberofLocations = scanner.next();
System.out.print("Enter SLA (GOLD/Silver) : ");
String slaValue = scanner.next();
try{
account.put("Name",name);
account.put("AccountNumber",accountNumber);
account.put("AnnualRevenue",annualRevenue);
account.put("Description",description);
account.put("Industry",industry);
account.put("Phone",phone);
account.put("Active__c",isActive);
account.put("CustomerPriority__c",customerPriority);
account.put("NumberofLocations__c",numberofLocations);
account.put("SLA__c",slaValue);
PostMethod post = new PostMethod(instanceUrl+"/services/data/v20.0/sobjects/Account");
post.setRequestHeader("Authorization", "OAuth " + accessToken);
post.setRequestEntity(new StringRequestEntity(account.toString(),"application/json","UTF-8"));
httpclient.executeMethod(post);
System.out.println("Get HTTP status :"+post.getStatusCode());
if(post.getStatusCode()==201){
try{
JSONObject response = new JSONObject(new JSONTokener(new InputStreamReader(post.getResponseBodyAsStream())));
System.out.println("Create Response : "+response.toString(2));
if(response.getBoolean("success")){
String accountid= response.getString("id");
System.out.println("New Record has been created withe ID : "+accountid);
createContactRecords(accountid,instanceUrl,accessToken);
}
}catch (Exception e1) {
e1.printStackTrace();
}
}
}catch (Exception e1) {
e1.printStackTrace();
}
System.out.println("-----------------------Records has been create successfully-------------------------\n\n");
return null;
}
public String createContactRecords(String accountid,String instanceUrl, String accessToken) throws Exception{
HttpClient httpclientContact = new HttpClient();
JSONObject contact = new JSONObject();
contact.put("LastName", "SFDC-Fazu");
contact.put("AccountId",accountid);
PostMethod postContact = new PostMethod(instanceUrl+"/services/data/v20.0/sobjects/Contact");
postContact.setRequestHeader("Authorization", "OAuth " + accessToken);
postContact.setRequestEntity(new StringRequestEntity(contact.toString(),"application/json","UTF-8"));
try{
httpclientContact.executeMethod(postContact);
System.out.println("Get HTTP status :"+postContact.getStatusCode());
JSONObject responseContact = new JSONObject(new JSONTokener(new InputStreamReader(postContact.getResponseBodyAsStream())));
System.out.println("Create Response : "+responseContact.toString(2));
}catch (Exception e1) {
e1.printStackTrace();
}
return null;
}
public void queryAccountObject(String instanceUrl, String accessToken)throws Exception{
HttpClient httpClient= new HttpClient();
GetMethod get = new GetMethod(instanceUrl+"/services/data/v20.0/query");
get.setRequestHeader("Authorization", "OAuth " + accessToken);
NameValuePair[] params = new NameValuePair[1];
params[0]=new NameValuePair("q","select id,name from account");
get.setQueryString(params);
try{
httpClient.executeMethod(get);
if(get.getStatusCode()==HttpStatus.SC_OK){
try{
JSONObject response = new JSONObject(new JSONTokener(new InputStreamReader(get.getResponseBodyAsStream())));
System.out.println("Query Response :"+response.toString(2) );
System.out.println(response.get("totalSize")+"record(s) returned \n\n");
JSONArray results = response.getJSONArray("records");
for(int i = 0;i < results.length();i++){
System.out.println(results.getJSONObject(i).getString("Id")+"-----"+results.getJSONObject(i).getString("Name")+"\n" );
}
System.out.println("\n");
}catch (Exception e1) {
e1.printStackTrace();
}
}
}catch (Exception e1) {
e1.printStackTrace();
}
}
public void showAccountId(String instanceUrl, String accessToken)throws Exception{
HttpClient httpClient= new HttpClient();
GetMethod get = new GetMethod(instanceUrl+"/services/data/v20.0/sobjects/Account/0019000001qmYdAAAU");
get.setRequestHeader("Authorization", "OAuth " + accessToken);
try{
httpClient.executeMethod(get);
if(get.getStatusCode()==HttpStatus.SC_OK){
try{
JSONObject response = new JSONObject(new JSONTokener(new InputStreamReader(get.getResponseBodyAsStream())));
System.out.println("Query Response :"+response.toString(2) );
java.util.Iterator iterator = response.keys();
while(iterator.hasNext() ){
String key = (String)iterator.next();
String value = (String)iterator.next();
System.out.println(key + ":"+(value !=null ? value : "")+"\n");
}
}catch (Exception e1) {
e1.printStackTrace();
}
}
}catch (Exception e1) {
e1.printStackTrace();
}
}
public void deleteRecords(String instanceUrl, String accessToken)throws Exception{
Scanner scanner = new Scanner(System.in);
System.out.print("Enter Account ID : ");
String accountId = scanner.next();
HttpClient httpClient= new HttpClient();
DeleteMethod deleteMethod = new DeleteMethod(instanceUrl+"/services/data/v20.0/sobjects/Account/"+accountId);
deleteMethod.setRequestHeader("Authorization", "OAuth " + accessToken);
try{
httpClient.executeMethod(deleteMethod);
System.out.println("Http Status"+deleteMethod.getStatusCode()+"Deleting account \n\n");
}catch (Exception e1) {
e1.printStackTrace();
}
}
public static void patchRecord(String instanceUrl, String accessToken) throws Exception{
Scanner scanner = new Scanner(System.in);
System.out.print("Enter Account ID : ");
String accountId = scanner.next();
HttpClient httpClient = new HttpClient();
JSONObject update = new JSONObject();
try{
update.put("name", "SFDC-Fazu patch test");
}catch (Exception e1) {
e1.printStackTrace();
}
PostMethod post = new PostMethod(instanceUrl+"/services/data/v20.0/sobjects/Account/"+accountId) {
@Override public String getName() { return "PATCH"; }
};
post.setRequestHeader("Authorization", "OAuth " + accessToken);
post.setRequestEntity(new StringRequestEntity(update.toString(),"application/json","UTF-8"));
try{
httpClient.executeMethod(post);
System.out.println("Http Status"+post.getStatusCode()+" updated successfully \n\n");
}catch (Exception e1) {
e1.printStackTrace();
}
}
}