Wednesday, February 19, 2020
Sunday, February 2, 2020
Rest API Salesforce Java Integration
>>Add below Jars in the eclipse to the project. You can download them from the maven repository.
httpclient-4.2.1.jar
httpcore-4.2.1.jar
json-20090211.jar
commons-logging-1.1.1.jar
>> Run below code to get the access token and perform further operations.
===============================================
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import org.apache.http.Header;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicHeader;
import org.apache.http.util.EntityUtils;
import org.json.JSONException;
import org.json.JSONObject;
/**
* This program demonstrates the following basic use cases for the REST API:
* - authentication with OAuth 2.0 (This is for development purposes only. Not a real implementation.)
* - querying (using account records)
* - inserting (using a contact record related to one of the retrieved account records)
* - updating (updates contact record added in previous step)
*
* @author salesforce training
*/
public class RESTApp extends Object {
//---------REST and OAuth-------
//Portions of the URI for REST access that are re-used throughout the code
private static String OAUTH_ENDPOINT = "/services/oauth2/token";
private static String REST_ENDPOINT = "/services/data";
//Basic header information added to each HTTP object that is used
//to invoke the REST API.
private static Header prettyPrintHeader = new BasicHeader("X-PrettyPrint", "1");
//================Code starts here===================
public static void main(String[] args) {
new RESTApp();
}
/**
* Constructor drives console interaction and calls appropriate methods.
*/
public RESTApp() {
RestConnectionHelper restConn = this.oauth2Login();
if (restConn.baseUri!= null) {
//Retrieved accountId that is used when contact is added.
String accountId = this.queryAccount(restConn);
if (accountId != null) {
//Id of inserted contact. Used to update contact.
String contactId = this.insertContact(restConn,accountId);
if (contactId != null) {
this.updateContact(restConn, contactId);
} else {
System.out.println("Contact not found.");
}
} else {
System.out.println("Account not found.");
}
}
}
/**
* This method connects the program to the Salesforce organization using OAuth.
* It stores returned values for further access to organization.
* @param userCredentials Contains all credentials necessary for login
* @return
*/
public RestConnectionHelper oauth2Login() {
System.out.println("_______________ Login _______________");
OAuth2Response oauth2Response = null;
HttpResponse response = null;
UserCredentials userCredentials = new UserCredentials();
RestConnectionHelper restConn = new RestConnectionHelper();
String loginHostUri = "https://" +
userCredentials.loginInstanceDomain + OAUTH_ENDPOINT;
try {
//Construct the objects for making the request
HttpClient httpClient = new DefaultHttpClient();
// If you are behind a proxy server, uncomment
// the next line of code after supplying values for your proxy server
// httpClient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, new HttpHost("myProxy.domain.com", 8088 /*this may need to change as well*/, "http"));
HttpPost httpPost = new HttpPost(loginHostUri);
StringBuffer requestBodyText =
new StringBuffer("grant_type=password");
requestBodyText.append("&username=");
requestBodyText.append(userCredentials.userName);
requestBodyText.append("&password=");
requestBodyText.append(userCredentials.password);
requestBodyText.append("&client_id=");
requestBodyText.append(userCredentials.consumerKey);
requestBodyText.append("&client_secret=");
requestBodyText.append(userCredentials.consumerSecret);
StringEntity requestBody =
new StringEntity(requestBodyText.toString());
requestBody.setContentType("application/x-www-form-urlencoded");
httpPost.setEntity(requestBody);
httpPost.addHeader(prettyPrintHeader);
System.out.println("body is " + requestBodyText);
//Make the request and store the result
response = httpClient.execute(httpPost);
//Parse the result if we were able to connect.
if ( response.getStatusLine().getStatusCode() == 200 ) {
String response_string = EntityUtils.toString(response.getEntity());
try {
JSONObject json = new JSONObject(response_string);
oauth2Response = new OAuth2Response(json);
System.out.println("JSON returned by response: +\n" + json.toString(1));
} catch (JSONException je) {
je.printStackTrace();
}
restConn.baseUri = oauth2Response.instance_url + REST_ENDPOINT
+ "/v" + userCredentials.apiVersion +".0";
restConn.oauthHeader = new BasicHeader("Authorization", "OAuth " +
oauth2Response.access_token);
System.out.println("\nSuccessfully logged in to instance: "
+ restConn.baseUri);
} else {
System.out.println("An error has occured. Http status: " + response.getStatusLine().getStatusCode());
System.out.println(getBody(response.getEntity().getContent()));
System.exit(-1);
}
} catch (UnsupportedEncodingException uee) {
uee.printStackTrace();
} catch (IOException ioe) {
ioe.printStackTrace();
} catch (NullPointerException npe) {
npe.printStackTrace();
}
return restConn;
}
/**
* This method demonstrates
* - How to use HTTPGet and a constructed URI to retrieve data from Salesforce.
* - Simple parsing of a JSON object.
*/
public String queryAccount(RestConnectionHelper restConn) {
System.out.println("\n_______________ Account QUERY _______________");
String accountId = null;
try {
//Set up the HTTP objects needed to make the request.
HttpClient httpClient = new DefaultHttpClient();
/********************************************************
* TODO:
* Set the value of uri on the line below to the baseURI concatenated
* with the query parameter and the query string.
********************************************************/
String uri = restConn.baseUri + "/query?q=SELECT+id+,+name+FROM+Account+limit+2";
System.out.println("Query URL: " + uri);
HttpGet httpGet = new HttpGet(uri);
httpGet.addHeader(restConn.oauthHeader);
httpGet.addHeader(prettyPrintHeader);
// Make the request.
HttpResponse response = httpClient.execute(httpGet);
// Process the result
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode == 200) {
String response_string = EntityUtils.toString(response.getEntity());
try {
JSONObject json = new JSONObject(response_string);
System.out.println("JSON result of Query:\n" + json.toString(1));
/********************************************************
* TODO:
* Add an assignment statement the line below
* to store the account id of the first object returned to
* use later when creating the Contact record.
********************************************************/
accountId = json.getJSONArray("records").getJSONObject(0).getString("Id");
System.out.println("accountId value is " + accountId);
} catch (JSONException je) {
je.printStackTrace();
}
} else {
System.out.println("Query was unsuccessful. Status code returned is " + statusCode);
}
} catch (IOException ioe) {
ioe.printStackTrace();
} catch (NullPointerException npe) {
npe.printStackTrace();
}
return accountId;
}
/**
* This method demonstrates
* - How to use HTTPPost and a constructed URI to insert data into Salesforce.
* - Simple creation of a JSON object.
*/
public String insertContact(RestConnectionHelper restConn, String accountId) {
System.out.println("\n_______________ Contact INSERT _______________");
String contactId = null;
/********************************************************
* TODO:
* On the line below add code to the URI
* to indicate the type of object that will be inserted into the database
********************************************************/
String uri = restConn.baseUri + "/sobjects/Contact/";
try {
//create the JSON object containing the new contact details.
JSONObject contact = new JSONObject();
contact.put("LastName", "Chin");
contact.put("FirstName", "Jasmine");
contact.put("MobilePhone", "(415)222-3333");
contact.put("Phone", "(650)123-3211");
/********************************************************
* TODO:
* On the line below add the key value pair for the accountId
* to the JSON contact data.
********************************************************/
contact.put("AccountId", accountId);
System.out.println("JSON for contact record to be inserted:\n" + contact.toString(1));
//Construct the objects needed for the request
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(uri);
httpPost.addHeader(restConn.oauthHeader);
httpPost.addHeader(prettyPrintHeader);
// The message we are going to post
StringEntity body = new StringEntity(contact.toString(1));
body.setContentType("application/json");
httpPost.setEntity(body);
//Make the request
HttpResponse response = httpClient.execute(httpPost);
//Process the results
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode == 201) {
String response_string = EntityUtils.toString(response.getEntity());
JSONObject json = new JSONObject(response_string);
// Store the retrieved contact id to use when we update the contact.
contactId = json.getString("id");
System.out.println("New contact id from response: " + contactId);
} else {
System.out.println("Insertion unsuccessful. Status code returned is " + statusCode);
}
} catch (JSONException e) {
System.out.println("Issue creating JSON or processing results");
e.printStackTrace();
} catch (IOException ioe) {
ioe.printStackTrace();
} catch (NullPointerException npe) {
npe.printStackTrace();
}
return contactId;
}
/**
* This method demonstrates
* - How to use HTTPPatch and a constructed URI to update data in Salesforce.
* NOTE: You have to create the HTTPPatch, as it does not exist in the standard library.
* - Simple creation of a JSON object.
*/
public void updateContact(RestConnectionHelper restConn, String contactid) {
System.out.println("\n_______________ Contact UPDATE _______________");
//Notice, the id for the record to update is part of the URI, not part of the JSON
String uri = restConn.baseUri + "/sobjects/Contact/" + contactid;
try {
//Create the JSON object containing the updated contact phone number
//and the id of the contact we are updating.
JSONObject contact = new JSONObject();
contact.put("Phone", "(415)555-1234");
System.out.println("JSON for update of contact record:\n" + contact.toString(1));
//Set up the objects necessary to make the request.
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPatch httpPatch = new HttpPatch(uri);
httpPatch.addHeader(restConn.oauthHeader);
httpPatch.addHeader(prettyPrintHeader);
StringEntity body = new StringEntity(contact.toString(1));
body.setContentType("application/json");
httpPatch.setEntity(body);
//Make the request
HttpResponse response = httpClient.execute(httpPatch);
//Process the response
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode == 204) {
System.out.println("Updated the contact successfully.");
} else {
System.out.println("Contact update NOT successfully. Status code is " + statusCode);
}
} catch (JSONException e) {
System.out.println("Issue creating JSON or processing results");
e.printStackTrace();
} catch (IOException ioe) {
ioe.printStackTrace();
} catch (NullPointerException npe) {
npe.printStackTrace();
}
}
/**
* Extend the Apache HttpPost method to implement an HttpPost
* method.
*/
private static class HttpPatch extends HttpPost {
public HttpPatch(String uri) {
super(uri);
}
public String getMethod() {
return "PATCH";
}
}
/**
* This class is used to hold values returned by the OAuth request.
*/
static class OAuth2Response {
String id;
String issued_at;
String instance_url;
String signature;
String access_token;
public OAuth2Response() {
}
public OAuth2Response(JSONObject json) {
try {
id =json.getString("id");
issued_at = json.getString("issued_at");
instance_url = json.getString("instance_url");
signature = json.getString("signature");
access_token = json.getString("access_token");
} catch (JSONException e) {
e.printStackTrace();
}
}
}
/**
* This class holds all the values related to the credentials needed to
* make the OAuth2 request for authentication. Normally they would not be set in
* this manner.
*/
class UserCredentials {
String loginInstanceDomain = "light601dep-dev-ed.my.salesforce.com";
String apiVersion = "47";
//---------Credentials----------
//Credentials providing access to a specific Salesforce organization.
/********************************************************
* TODO:
* 1. Enter Salesforce login userName
* 2. Enter Salesforce login password
* 3. Enter consumerKey
* 4. Enter consumerSecret
********************************************************/
String userName = "David@lightning601.com";
String password = "xxxxxxxxxG841Lq4OPaBc3nvtMcGmhC5GH";
String consumerKey = "3MVG9G9pzCUSkzZvyptQFNKyeFZLuFEuMqSNrj_gLpwyqgHTmUSLK0qb0EvWiNm6VYzLixRXeULtJZlm3LevO";
String consumerSecret = "32B4AFDB1FD3E9B8FD62FD2333ACC9B33A65778C35634F8D618745746A2A6C86";
String grantType = "password";
}
/**
* This class holds information gained from login that are used in subsequent calls.
*/
class RestConnectionHelper {
//Holds URI returned from OAuth call, which is then used throughout the code.
String baseUri;
//The oauthHeader set in the oauth2Login method, and then added to
//each HTTP object that is used to invoke the REST API.
Header oauthHeader;
}
//==========utility methods=============
/**
* Utility method for changing a stream into a String.
* @param inputStream
* @return
*/
private String getBody(InputStream inputStream) {
String result = "";
try {
BufferedReader in = new BufferedReader(
new InputStreamReader(inputStream)
);
String inputLine;
while ( (inputLine = in.readLine() ) != null ) {
result += inputLine;
result += "\n";
}
in.close();
} catch (IOException ioe) {
ioe.printStackTrace();
}
return result;
}
}
httpclient-4.2.1.jar
httpcore-4.2.1.jar
json-20090211.jar
commons-logging-1.1.1.jar
>> Run below code to get the access token and perform further operations.
===============================================
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import org.apache.http.Header;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicHeader;
import org.apache.http.util.EntityUtils;
import org.json.JSONException;
import org.json.JSONObject;
/**
* This program demonstrates the following basic use cases for the REST API:
* - authentication with OAuth 2.0 (This is for development purposes only. Not a real implementation.)
* - querying (using account records)
* - inserting (using a contact record related to one of the retrieved account records)
* - updating (updates contact record added in previous step)
*
* @author salesforce training
*/
public class RESTApp extends Object {
//---------REST and OAuth-------
//Portions of the URI for REST access that are re-used throughout the code
private static String OAUTH_ENDPOINT = "/services/oauth2/token";
private static String REST_ENDPOINT = "/services/data";
//Basic header information added to each HTTP object that is used
//to invoke the REST API.
private static Header prettyPrintHeader = new BasicHeader("X-PrettyPrint", "1");
//================Code starts here===================
public static void main(String[] args) {
new RESTApp();
}
/**
* Constructor drives console interaction and calls appropriate methods.
*/
public RESTApp() {
RestConnectionHelper restConn = this.oauth2Login();
if (restConn.baseUri!= null) {
//Retrieved accountId that is used when contact is added.
String accountId = this.queryAccount(restConn);
if (accountId != null) {
//Id of inserted contact. Used to update contact.
String contactId = this.insertContact(restConn,accountId);
if (contactId != null) {
this.updateContact(restConn, contactId);
} else {
System.out.println("Contact not found.");
}
} else {
System.out.println("Account not found.");
}
}
}
/**
* This method connects the program to the Salesforce organization using OAuth.
* It stores returned values for further access to organization.
* @param userCredentials Contains all credentials necessary for login
* @return
*/
public RestConnectionHelper oauth2Login() {
System.out.println("_______________ Login _______________");
OAuth2Response oauth2Response = null;
HttpResponse response = null;
UserCredentials userCredentials = new UserCredentials();
RestConnectionHelper restConn = new RestConnectionHelper();
String loginHostUri = "https://" +
userCredentials.loginInstanceDomain + OAUTH_ENDPOINT;
try {
//Construct the objects for making the request
HttpClient httpClient = new DefaultHttpClient();
// If you are behind a proxy server, uncomment
// the next line of code after supplying values for your proxy server
// httpClient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, new HttpHost("myProxy.domain.com", 8088 /*this may need to change as well*/, "http"));
HttpPost httpPost = new HttpPost(loginHostUri);
StringBuffer requestBodyText =
new StringBuffer("grant_type=password");
requestBodyText.append("&username=");
requestBodyText.append(userCredentials.userName);
requestBodyText.append("&password=");
requestBodyText.append(userCredentials.password);
requestBodyText.append("&client_id=");
requestBodyText.append(userCredentials.consumerKey);
requestBodyText.append("&client_secret=");
requestBodyText.append(userCredentials.consumerSecret);
StringEntity requestBody =
new StringEntity(requestBodyText.toString());
requestBody.setContentType("application/x-www-form-urlencoded");
httpPost.setEntity(requestBody);
httpPost.addHeader(prettyPrintHeader);
System.out.println("body is " + requestBodyText);
//Make the request and store the result
response = httpClient.execute(httpPost);
//Parse the result if we were able to connect.
if ( response.getStatusLine().getStatusCode() == 200 ) {
String response_string = EntityUtils.toString(response.getEntity());
try {
JSONObject json = new JSONObject(response_string);
oauth2Response = new OAuth2Response(json);
System.out.println("JSON returned by response: +\n" + json.toString(1));
} catch (JSONException je) {
je.printStackTrace();
}
restConn.baseUri = oauth2Response.instance_url + REST_ENDPOINT
+ "/v" + userCredentials.apiVersion +".0";
restConn.oauthHeader = new BasicHeader("Authorization", "OAuth " +
oauth2Response.access_token);
System.out.println("\nSuccessfully logged in to instance: "
+ restConn.baseUri);
} else {
System.out.println("An error has occured. Http status: " + response.getStatusLine().getStatusCode());
System.out.println(getBody(response.getEntity().getContent()));
System.exit(-1);
}
} catch (UnsupportedEncodingException uee) {
uee.printStackTrace();
} catch (IOException ioe) {
ioe.printStackTrace();
} catch (NullPointerException npe) {
npe.printStackTrace();
}
return restConn;
}
/**
* This method demonstrates
* - How to use HTTPGet and a constructed URI to retrieve data from Salesforce.
* - Simple parsing of a JSON object.
*/
public String queryAccount(RestConnectionHelper restConn) {
System.out.println("\n_______________ Account QUERY _______________");
String accountId = null;
try {
//Set up the HTTP objects needed to make the request.
HttpClient httpClient = new DefaultHttpClient();
/********************************************************
* TODO:
* Set the value of uri on the line below to the baseURI concatenated
* with the query parameter and the query string.
********************************************************/
String uri = restConn.baseUri + "/query?q=SELECT+id+,+name+FROM+Account+limit+2";
System.out.println("Query URL: " + uri);
HttpGet httpGet = new HttpGet(uri);
httpGet.addHeader(restConn.oauthHeader);
httpGet.addHeader(prettyPrintHeader);
// Make the request.
HttpResponse response = httpClient.execute(httpGet);
// Process the result
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode == 200) {
String response_string = EntityUtils.toString(response.getEntity());
try {
JSONObject json = new JSONObject(response_string);
System.out.println("JSON result of Query:\n" + json.toString(1));
/********************************************************
* TODO:
* Add an assignment statement the line below
* to store the account id of the first object returned to
* use later when creating the Contact record.
********************************************************/
accountId = json.getJSONArray("records").getJSONObject(0).getString("Id");
System.out.println("accountId value is " + accountId);
} catch (JSONException je) {
je.printStackTrace();
}
} else {
System.out.println("Query was unsuccessful. Status code returned is " + statusCode);
}
} catch (IOException ioe) {
ioe.printStackTrace();
} catch (NullPointerException npe) {
npe.printStackTrace();
}
return accountId;
}
/**
* This method demonstrates
* - How to use HTTPPost and a constructed URI to insert data into Salesforce.
* - Simple creation of a JSON object.
*/
public String insertContact(RestConnectionHelper restConn, String accountId) {
System.out.println("\n_______________ Contact INSERT _______________");
String contactId = null;
/********************************************************
* TODO:
* On the line below add code to the URI
* to indicate the type of object that will be inserted into the database
********************************************************/
String uri = restConn.baseUri + "/sobjects/Contact/";
try {
//create the JSON object containing the new contact details.
JSONObject contact = new JSONObject();
contact.put("LastName", "Chin");
contact.put("FirstName", "Jasmine");
contact.put("MobilePhone", "(415)222-3333");
contact.put("Phone", "(650)123-3211");
/********************************************************
* TODO:
* On the line below add the key value pair for the accountId
* to the JSON contact data.
********************************************************/
contact.put("AccountId", accountId);
System.out.println("JSON for contact record to be inserted:\n" + contact.toString(1));
//Construct the objects needed for the request
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(uri);
httpPost.addHeader(restConn.oauthHeader);
httpPost.addHeader(prettyPrintHeader);
// The message we are going to post
StringEntity body = new StringEntity(contact.toString(1));
body.setContentType("application/json");
httpPost.setEntity(body);
//Make the request
HttpResponse response = httpClient.execute(httpPost);
//Process the results
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode == 201) {
String response_string = EntityUtils.toString(response.getEntity());
JSONObject json = new JSONObject(response_string);
// Store the retrieved contact id to use when we update the contact.
contactId = json.getString("id");
System.out.println("New contact id from response: " + contactId);
} else {
System.out.println("Insertion unsuccessful. Status code returned is " + statusCode);
}
} catch (JSONException e) {
System.out.println("Issue creating JSON or processing results");
e.printStackTrace();
} catch (IOException ioe) {
ioe.printStackTrace();
} catch (NullPointerException npe) {
npe.printStackTrace();
}
return contactId;
}
/**
* This method demonstrates
* - How to use HTTPPatch and a constructed URI to update data in Salesforce.
* NOTE: You have to create the HTTPPatch, as it does not exist in the standard library.
* - Simple creation of a JSON object.
*/
public void updateContact(RestConnectionHelper restConn, String contactid) {
System.out.println("\n_______________ Contact UPDATE _______________");
//Notice, the id for the record to update is part of the URI, not part of the JSON
String uri = restConn.baseUri + "/sobjects/Contact/" + contactid;
try {
//Create the JSON object containing the updated contact phone number
//and the id of the contact we are updating.
JSONObject contact = new JSONObject();
contact.put("Phone", "(415)555-1234");
System.out.println("JSON for update of contact record:\n" + contact.toString(1));
//Set up the objects necessary to make the request.
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPatch httpPatch = new HttpPatch(uri);
httpPatch.addHeader(restConn.oauthHeader);
httpPatch.addHeader(prettyPrintHeader);
StringEntity body = new StringEntity(contact.toString(1));
body.setContentType("application/json");
httpPatch.setEntity(body);
//Make the request
HttpResponse response = httpClient.execute(httpPatch);
//Process the response
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode == 204) {
System.out.println("Updated the contact successfully.");
} else {
System.out.println("Contact update NOT successfully. Status code is " + statusCode);
}
} catch (JSONException e) {
System.out.println("Issue creating JSON or processing results");
e.printStackTrace();
} catch (IOException ioe) {
ioe.printStackTrace();
} catch (NullPointerException npe) {
npe.printStackTrace();
}
}
/**
* Extend the Apache HttpPost method to implement an HttpPost
* method.
*/
private static class HttpPatch extends HttpPost {
public HttpPatch(String uri) {
super(uri);
}
public String getMethod() {
return "PATCH";
}
}
/**
* This class is used to hold values returned by the OAuth request.
*/
static class OAuth2Response {
String id;
String issued_at;
String instance_url;
String signature;
String access_token;
public OAuth2Response() {
}
public OAuth2Response(JSONObject json) {
try {
id =json.getString("id");
issued_at = json.getString("issued_at");
instance_url = json.getString("instance_url");
signature = json.getString("signature");
access_token = json.getString("access_token");
} catch (JSONException e) {
e.printStackTrace();
}
}
}
/**
* This class holds all the values related to the credentials needed to
* make the OAuth2 request for authentication. Normally they would not be set in
* this manner.
*/
class UserCredentials {
String loginInstanceDomain = "light601dep-dev-ed.my.salesforce.com";
String apiVersion = "47";
//---------Credentials----------
//Credentials providing access to a specific Salesforce organization.
/********************************************************
* TODO:
* 1. Enter Salesforce login userName
* 2. Enter Salesforce login password
* 3. Enter consumerKey
* 4. Enter consumerSecret
********************************************************/
String userName = "David@lightning601.com";
String password = "xxxxxxxxxG841Lq4OPaBc3nvtMcGmhC5GH";
String consumerKey = "3MVG9G9pzCUSkzZvyptQFNKyeFZLuFEuMqSNrj_gLpwyqgHTmUSLK0qb0EvWiNm6VYzLixRXeULtJZlm3LevO";
String consumerSecret = "32B4AFDB1FD3E9B8FD62FD2333ACC9B33A65778C35634F8D618745746A2A6C86";
String grantType = "password";
}
/**
* This class holds information gained from login that are used in subsequent calls.
*/
class RestConnectionHelper {
//Holds URI returned from OAuth call, which is then used throughout the code.
String baseUri;
//The oauthHeader set in the oauth2Login method, and then added to
//each HTTP object that is used to invoke the REST API.
Header oauthHeader;
}
//==========utility methods=============
/**
* Utility method for changing a stream into a String.
* @param inputStream
* @return
*/
private String getBody(InputStream inputStream) {
String result = "";
try {
BufferedReader in = new BufferedReader(
new InputStreamReader(inputStream)
);
String inputLine;
while ( (inputLine = in.readLine() ) != null ) {
result += inputLine;
result += "\n";
}
in.close();
} catch (IOException ioe) {
ioe.printStackTrace();
}
return result;
}
}
===================================================================
Integrate Java with Salesforce through Soap API
Steps I followed to get Enterpise.jar
>>First and foremost, I took the Enterprise wsdl from Salesforce and downloaded "force-wsc-40.0.0.jar","ST4-4.0.8.jar",antlr-runtime-3.5.2.jar, js.jar(Rhino) and then took tools.jar from JDK.
>> Kept all these files in one single folder(alljars).
>> Given the path of this folder in the cmd(C:\Users\thimma.v\Desktop\alljars).
>> Then then adjusted JAVA_HOME, CLASSPATH and Path(please exact path which I had set in my environment variables)
path: .;%JAVA_HOME%
ClASSPATH : .;%JAVA_HOME%\lib;%JAVA_HOME%\lib\tools.jar;%JAVA_HOME%\lib\dt.jar;%JAVA_HOME%\jre\lib;%JAVA_HOME%\jre\lib\rt.jar;.\force-wsc-40.0.0.jar;.\enterprise.jar;
JAVA_HOME: C:\Program Files\Java\jdk1.8.0_241\bin
C:\Users\thimma.v\Desktop\alljars>java -classpath ST4-4.0.8.jar;tools.jar;js.jar;antlr-runtime-3.5.2.jar;force-wsc-40.0.0.jar com.sforce.ws.tools.wsdlc ent.wsdl.xml enterprise.jar
[WSC][wsdlc.main:71]Generating Java files from schema ...
[WSC][wsdlc.main:71]Generated 990 java files.
[WSC][wsdlc.main:71]Compiling to target 1.6...
warning: [options] bootstrap class path not set in conjunction with -source 1.6
1 warning
[WSC][wsdlc.main:71]Compiled 994 java files.
[WSC][wsdlc.main:71]Generating jar file ... enterprise.jar
[WSC][wsdlc.main:71]Generated jar file enterprise.jar
>> Now I received generated Enterprise.jar.
>> Add Below Jars in the Eclipse.
force-wsc-40.0.0.jar(retrieved from Maven repository) and enterprise.jar(retrieved with the below cmd)
java -classpath ST4-4.0.8.jar;tools.jar;js.jar;antlr-runtime-3.5.2.jar;force-wsc-40.0.0.jar com.sforce.ws.tools.wsdlc ent.wsdl.xml enterprise.jar
>> Now run below code to get session ID and do further operations.
import com.sforce.soap.enterprise.Connector;
import com.sforce.soap.enterprise.EnterpriseConnection;
import com.sforce.soap.enterprise.Error;
import com.sforce.soap.enterprise.QueryResult;
import com.sforce.soap.enterprise.SaveResult;
import com.sforce.soap.enterprise.sobject.Account;
import com.sforce.soap.enterprise.sobject.SObject;
import com.sforce.ws.ConnectionException;
import com.sforce.ws.ConnectorConfig;
/*
* This class exercises the following functionality of the Web Services API
* using the enterprise.wsdl:
* - Login
* - Query
* - Update
*/
public class QueryAndUpdateaccountApp {
static final String USERNAME = "David@701.com";
static final String PASSWORD = "xxxxxxx";
static final String TOKEN = "AlDF5HNLniEjYxtvwuNFSheqp";
// the variable that will contain the connection that will be used to execute all
// SalesForce Web Services API.
static EnterpriseConnection connection;
// class constructor
public QueryAndUpdateaccountApp() {
// upon instantiation invoke process to perform the application logic
doWork();
}
// this is the entry point into the application
public static void main(String[] args) {
// create a new instance of the class to begin processing
new QueryAndUpdateaccountApp();
}
// this method comprises the bulk of the application logic
private void doWork() {
//TODO (Exercise 4-2): Set doQuery to true.
boolean doQuery = true;
//TODO (Exercise 4-3): Set doUpdate to true.
boolean doUpdate = true;
if (doLogin() && doQuery) {
// perform a sample query and output account information
Account account = doaccountQuery();
// if a record was returned, proceed with update
if (account != null && doUpdate) {
// update account
doaccountUpdate(account);
}
}
}
// this function encapsulates the logic necessary to login to salesforce.com
private boolean doLogin() {
ConnectorConfig config = new ConnectorConfig();
config.setUsername(USERNAME);
//append token to password if needed.
config.setPassword(PASSWORD + TOKEN);
//config.setTraceMessage(true);
//If using a proxy to get through a firewall, uncomment the following code and set appropriate values.
//config.setProxy("proxyServer.corp.myCorp.com",8080);
//config.setNtlmDomain("NtlmDom");
//config.setProxyUsername("proxyUserName");
//config.setProxyPassword("***");
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());
System.out.println("Sforce service created.");
return true;
} catch (ConnectionException e1) {
e1.printStackTrace();
return false;
}
}
// this function encapsulates the logic necessary to query salesforce.com and
// output information about existing accounts
private Account doaccountQuery() {
// declare local vars
QueryResult qr = null; // create a variable to hold the query result
Account account = null; // create a variable to hold the return value
/***********************************************************************
* TODO - (Exercise 4-2): WRITE THE LOGIC NECESSARY TO QUERY AND RETURN A SINGLE account
* 1. Declare a string to hold the SOQL query which will retrieve the id, first name, last name of a single account
* 2. Using the connection obtained in the doLogin() method, execute the query and obtain the result
* 3. This will need to be wrapped in a try-catch block. Simply catch a generic Exception and print out the
* error message to the console.
***********************************************************************/
String query = "select id, Name, Phone from Account LIMIT 1"; // query for account data
// call the query saving the results in qr
try {
qr = connection.query(query);
} catch (Exception e) {
System.out.println("Error getting accounts " + e.getMessage());
}
/***********************************************************************
* TODO - (Exercise 4-2):
* 4. Using the query result, obtain the account record from the first element in the list of records
* 5. Print out account's first and last name to the console.
***********************************************************************/
// iterate over the results and output the returned information
if (qr != null && qr.getSize() > 0) {
SObject[] records = qr.getRecords();
if (records.length != 0) {
// get a handle on the retrieved account
account = (Account) records[0];
// output information about the account
System.out.println("Retrieved account: ");
System.out.println(account);
System.out.println(account.getId());
}
}
// return the account
return account;
}
// this function encapsulates the logic necessary to update a received account
// within salesforce.com and output the results
private void doaccountUpdate(Account account) {
// First we will create a account object array, all calls are batch ours is a single element batch
Account[] accounts = new Account[1];
/***********************************************************************
* TODO (Exercise 4-3) - WRITE THE LOGIC NECESSARY TO UPDATE THE PHONE AND MOBILE FOR THE RECIEVED account
*
* 6. Set the phone and mobile fields on the account object
* 7. Add the account object to the array of accounts
***********************************************************************/
// set the values for the account
account.setName("Dave");
account.setPhone("777-666-5555");
// add the account to the array of objects
accounts[0] = account;
// we are now ready to update the record
// create an array for the results
SaveResult[] saveResults = null;
/***********************************************************************
* TODO (Exercise 4-3)
* 8. Using the connection object initialized in the doLogin method, update the list of accounts and put the result in the saveResults array
* 9. This will need to be wrapped in a try-catch block. Simply catch a generic Exception and print out the error message to the console.
***********************************************************************/
try {
saveResults = connection.update(accounts);
} catch (Exception e) {
System.out.println("Error updating accounts " + e.getMessage());
}
// we will create a separate save result object for clarity
for (SaveResult saveResult : saveResults) {
// check to see if the first update was a success
if (saveResult.isSuccess())
// the id that we passed should be the one we get back.
{
System.out.println("Updated account with id: " + saveResult.getId());
} else {
// an error occurred on this record
System.out.println("Error: ");
Error error = saveResult.getErrors()[0];
System.out.println(error.getMessage());
}
}
}
}
====================Finally got below result=====================
Auth EndPoint: https://login.salesforce.com/services/Soap/c/47.0/0DF2v0000000ofJ
Service EndPoint: https://david701-dev-ed.my.salesforce.com/services/Soap/c/47.0/00D2v000001uTD6/0DF2v0000000ofJ
Username: David@701.com
SessionId: 00D2v000001uTD6!AQIAQB45BK1HOuJjUacxaDOcpUkyZje4GkwMGp3ra86PrkVThlgbCGaX1wpk45SMt3U3jLeTotQdplyrzzUXpwIfW_oEocuW
Sforce service created.
Retrieved account:
[Account [SObject fieldsToNull='{[0]}'
Id='0012v00002bjSF7AAM'
]
.
.
Phone='777-666-5555'
.
.
]
0012v00002bjSF7AAM
Updated account with id: 0012v00002bjSF7AAM
Note: If you have a trouble in getting enterprise.jar, you can use any jar which were retrieved by any developer earlier(to avoid the head of path setting and other errors related to it). You can ping me on thimma.salesforce@gmail.com in case if you want to get enterprise.jar for your POC.
>>First and foremost, I took the Enterprise wsdl from Salesforce and downloaded "force-wsc-40.0.0.jar","ST4-4.0.8.jar",antlr-runtime-3.5.2.jar, js.jar(Rhino) and then took tools.jar from JDK.
>> Kept all these files in one single folder(alljars).
>> Given the path of this folder in the cmd(C:\Users\thimma.v\Desktop\alljars).
>> Then then adjusted JAVA_HOME, CLASSPATH and Path(please exact path which I had set in my environment variables)
path: .;%JAVA_HOME%
ClASSPATH : .;%JAVA_HOME%\lib;%JAVA_HOME%\lib\tools.jar;%JAVA_HOME%\lib\dt.jar;%JAVA_HOME%\jre\lib;%JAVA_HOME%\jre\lib\rt.jar;.\force-wsc-40.0.0.jar;.\enterprise.jar;
JAVA_HOME: C:\Program Files\Java\jdk1.8.0_241\bin
C:\Users\thimma.v\Desktop\alljars>java -classpath ST4-4.0.8.jar;tools.jar;js.jar;antlr-runtime-3.5.2.jar;force-wsc-40.0.0.jar com.sforce.ws.tools.wsdlc ent.wsdl.xml enterprise.jar
[WSC][wsdlc.main:71]Generating Java files from schema ...
[WSC][wsdlc.main:71]Generated 990 java files.
[WSC][wsdlc.main:71]Compiling to target 1.6...
warning: [options] bootstrap class path not set in conjunction with -source 1.6
1 warning
[WSC][wsdlc.main:71]Compiled 994 java files.
[WSC][wsdlc.main:71]Generating jar file ... enterprise.jar
[WSC][wsdlc.main:71]Generated jar file enterprise.jar
>> Now I received generated Enterprise.jar.
>> Add Below Jars in the Eclipse.
force-wsc-40.0.0.jar(retrieved from Maven repository) and enterprise.jar(retrieved with the below cmd)
java -classpath ST4-4.0.8.jar;tools.jar;js.jar;antlr-runtime-3.5.2.jar;force-wsc-40.0.0.jar com.sforce.ws.tools.wsdlc ent.wsdl.xml enterprise.jar
>> Now run below code to get session ID and do further operations.
import com.sforce.soap.enterprise.Connector;
import com.sforce.soap.enterprise.EnterpriseConnection;
import com.sforce.soap.enterprise.Error;
import com.sforce.soap.enterprise.QueryResult;
import com.sforce.soap.enterprise.SaveResult;
import com.sforce.soap.enterprise.sobject.Account;
import com.sforce.soap.enterprise.sobject.SObject;
import com.sforce.ws.ConnectionException;
import com.sforce.ws.ConnectorConfig;
/*
* This class exercises the following functionality of the Web Services API
* using the enterprise.wsdl:
* - Login
* - Query
* - Update
*/
public class QueryAndUpdateaccountApp {
static final String USERNAME = "David@701.com";
static final String PASSWORD = "xxxxxxx";
static final String TOKEN = "AlDF5HNLniEjYxtvwuNFSheqp";
// the variable that will contain the connection that will be used to execute all
// SalesForce Web Services API.
static EnterpriseConnection connection;
// class constructor
public QueryAndUpdateaccountApp() {
// upon instantiation invoke process to perform the application logic
doWork();
}
// this is the entry point into the application
public static void main(String[] args) {
// create a new instance of the class to begin processing
new QueryAndUpdateaccountApp();
}
// this method comprises the bulk of the application logic
private void doWork() {
//TODO (Exercise 4-2): Set doQuery to true.
boolean doQuery = true;
//TODO (Exercise 4-3): Set doUpdate to true.
boolean doUpdate = true;
if (doLogin() && doQuery) {
// perform a sample query and output account information
Account account = doaccountQuery();
// if a record was returned, proceed with update
if (account != null && doUpdate) {
// update account
doaccountUpdate(account);
}
}
}
// this function encapsulates the logic necessary to login to salesforce.com
private boolean doLogin() {
ConnectorConfig config = new ConnectorConfig();
config.setUsername(USERNAME);
//append token to password if needed.
config.setPassword(PASSWORD + TOKEN);
//config.setTraceMessage(true);
//If using a proxy to get through a firewall, uncomment the following code and set appropriate values.
//config.setProxy("proxyServer.corp.myCorp.com",8080);
//config.setNtlmDomain("NtlmDom");
//config.setProxyUsername("proxyUserName");
//config.setProxyPassword("***");
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());
System.out.println("Sforce service created.");
return true;
} catch (ConnectionException e1) {
e1.printStackTrace();
return false;
}
}
// this function encapsulates the logic necessary to query salesforce.com and
// output information about existing accounts
private Account doaccountQuery() {
// declare local vars
QueryResult qr = null; // create a variable to hold the query result
Account account = null; // create a variable to hold the return value
/***********************************************************************
* TODO - (Exercise 4-2): WRITE THE LOGIC NECESSARY TO QUERY AND RETURN A SINGLE account
* 1. Declare a string to hold the SOQL query which will retrieve the id, first name, last name of a single account
* 2. Using the connection obtained in the doLogin() method, execute the query and obtain the result
* 3. This will need to be wrapped in a try-catch block. Simply catch a generic Exception and print out the
* error message to the console.
***********************************************************************/
String query = "select id, Name, Phone from Account LIMIT 1"; // query for account data
// call the query saving the results in qr
try {
qr = connection.query(query);
} catch (Exception e) {
System.out.println("Error getting accounts " + e.getMessage());
}
/***********************************************************************
* TODO - (Exercise 4-2):
* 4. Using the query result, obtain the account record from the first element in the list of records
* 5. Print out account's first and last name to the console.
***********************************************************************/
// iterate over the results and output the returned information
if (qr != null && qr.getSize() > 0) {
SObject[] records = qr.getRecords();
if (records.length != 0) {
// get a handle on the retrieved account
account = (Account) records[0];
// output information about the account
System.out.println("Retrieved account: ");
System.out.println(account);
System.out.println(account.getId());
}
}
// return the account
return account;
}
// this function encapsulates the logic necessary to update a received account
// within salesforce.com and output the results
private void doaccountUpdate(Account account) {
// First we will create a account object array, all calls are batch ours is a single element batch
Account[] accounts = new Account[1];
/***********************************************************************
* TODO (Exercise 4-3) - WRITE THE LOGIC NECESSARY TO UPDATE THE PHONE AND MOBILE FOR THE RECIEVED account
*
* 6. Set the phone and mobile fields on the account object
* 7. Add the account object to the array of accounts
***********************************************************************/
// set the values for the account
account.setName("Dave");
account.setPhone("777-666-5555");
// add the account to the array of objects
accounts[0] = account;
// we are now ready to update the record
// create an array for the results
SaveResult[] saveResults = null;
/***********************************************************************
* TODO (Exercise 4-3)
* 8. Using the connection object initialized in the doLogin method, update the list of accounts and put the result in the saveResults array
* 9. This will need to be wrapped in a try-catch block. Simply catch a generic Exception and print out the error message to the console.
***********************************************************************/
try {
saveResults = connection.update(accounts);
} catch (Exception e) {
System.out.println("Error updating accounts " + e.getMessage());
}
// we will create a separate save result object for clarity
for (SaveResult saveResult : saveResults) {
// check to see if the first update was a success
if (saveResult.isSuccess())
// the id that we passed should be the one we get back.
{
System.out.println("Updated account with id: " + saveResult.getId());
} else {
// an error occurred on this record
System.out.println("Error: ");
Error error = saveResult.getErrors()[0];
System.out.println(error.getMessage());
}
}
}
}
====================Finally got below result=====================
Auth EndPoint: https://login.salesforce.com/services/Soap/c/47.0/0DF2v0000000ofJ
Service EndPoint: https://david701-dev-ed.my.salesforce.com/services/Soap/c/47.0/00D2v000001uTD6/0DF2v0000000ofJ
Username: David@701.com
SessionId: 00D2v000001uTD6!AQIAQB45BK1HOuJjUacxaDOcpUkyZje4GkwMGp3ra86PrkVThlgbCGaX1wpk45SMt3U3jLeTotQdplyrzzUXpwIfW_oEocuW
Sforce service created.
Retrieved account:
[Account [SObject fieldsToNull='{[0]}'
Id='0012v00002bjSF7AAM'
]
.
.
Phone='777-666-5555'
.
.
]
0012v00002bjSF7AAM
Updated account with id: 0012v00002bjSF7AAM
Note: If you have a trouble in getting enterprise.jar, you can use any jar which were retrieved by any developer earlier(to avoid the head of path setting and other errors related to it). You can ping me on thimma.salesforce@gmail.com in case if you want to get enterprise.jar for your POC.
Subscribe to:
Posts (Atom)