by Sudipta Deb | Feb 26, 2015 | 501, Apex, dev 501, integration, Salesforce, SOAP, xml
Preface – This post is part of “Salesforce Integration with SOAP API” series.
In today’s post, I will explain how you can do Upsert operation using SOAP API and Java Program. Before that we should know what is so special about Upsert? Upsert will allow you to create a new record or update the existing record. Now I am sure you have this question is mind – “How Salesforce will know that the record is already there in the system?”, right!!!! Good. The answer is that you can pass the custom field which will be used to determine the presence of the existing record. So easy!!!
It is always recommended to use upsert() rather that create() because of the obvious reason i.e. upsert() will eliminate the chance of creating duplicate record in the system.
Syntax –
UpsertResult[] = connection.upsert(String externalIdFieldName, sObject[] sObjects);
Important point –
Note: I have written a helper class ConnectionHelper.java which I am using to connect to Salesforce using Enterprise WSDL. To know more about that, please refer my previous post @
Below is the Java program – UpsertOperation.java
import com.sforce.soap.enterprise.EnterpriseConnection;
import com.sforce.soap.enterprise.Error;
import com.sforce.soap.enterprise.UpsertResult;
import com.sforce.soap.enterprise.sobject.Account;
import com.sforce.soap.enterprise.sobject.SObject;
import com.sforce.ws.ConnectionException;
public class UpsertOperation {
private EnterpriseConnection enterpriseConnection;
private UpsertOperation(){
setEnterpriseConnection(ConnectionHelper.doConnect());
}
public static void main(String[] args) {
UpsertOperation upsertOperation = new UpsertOperation();
upsertOperation.doUpsertOperation();
}
private void doUpsertOperation(){
SObject[] allUpserts = new Account[2];
//Create an Account - Let's say this is a complete new account
Account account1 = new Account();
account1.setName("New Account");
account1.setAccountNumber("11111");
account1.setRating("Hot");
account1.setPhone("888888");
account1.setAccount_External_ID__c("11111");
//Create an Account - Let's say this is an already present account
Account account2 = new Account();
account2.setName("United Oil & Gas Corp");
account2.setAccountNumber("MN355118");
account2.setRating("Hot");
account2.setPhone("888888");
account2.setAccount_External_ID__c("CD355118");
allUpserts[0] = account1;
allUpserts[1] = account2;
try{
//Here the comparison will happen based on the field "Account_External_ID__c"
//This field will determine whether the record is already there is the system or not
//If the record is already there, then it will do update operation, otherwise
//it will do insert operation
UpsertResult[] results = getEnterpriseConnection().upsert("Account_External_ID__c", allUpserts);
for(UpsertResult eachResult : results){
if(eachResult.isSuccess()){
System.out.println("Upsert successful");
System.out.println((eachResult.isCreated() ? "Insert" : "Update") + " was performed!!");
}else{
for(Error eachError : eachResult.getErrors()){
System.out.println("Error occured with error message: " + eachError.getMessage());
}
}
}
}catch(ConnectionException e){
e.printStackTrace();
}
}
public EnterpriseConnection getEnterpriseConnection() {
return enterpriseConnection;
}
public void setEnterpriseConnection(EnterpriseConnection enterpriseConnection) {
this.enterpriseConnection = enterpriseConnection;
}
}
The output should look like –Upsert successful
Insert was performed!!
Upsert successful
Update was performed!!
It’s really easy, right!!! If you have any question/feedback, please provide your comment.
In my next post, I will write about delete() operation. Till then enjoy.
by Sudipta Deb | Feb 23, 2015 | 501, Apex, dev 501, integration, Salesforce, SOAP
Preface – This post is part of “Salesforce Integration with SOAP API” series.
In today’s post, we will go through the code to understand how we can update records using SOAP API and Java program. Before going into the Java program, I would request you guys to check the documentation @
Update core call with SOAP API
Note: I have written a helper class ConnectionHelper.java which I am using to connect to Salesforce using Enterprise WSDL. To know more about that, please refer my previous post @
Now below code will update Account record – import com.sforce.soap.enterprise.EnterpriseConnection;
import com.sforce.soap.enterprise.Error;
import com.sforce.soap.enterprise.SaveResult;
import com.sforce.soap.enterprise.sobject.Account;
import com.sforce.ws.ConnectionException;
public class UpdateAccount {
private EnterpriseConnection enterpriseConnection;
private UpdateAccount(){
setEnterpriseConnection(ConnectionHelper.doConnect());
}
public static void main(String[] args){
UpdateAccount updateAccount = new UpdateAccount();
//Here you need to provide Account ID here
updateAccount.doUpdateAccount(new String[]{"0019000001ByhBI","0019000000tvEQo"});
}
private void doUpdateAccount(String[] ids){
Account[] toBeUpdatedAccount = new Account[ids.length];
for(int i = 0 ; i < ids.length ; i++){
Account tempAccount = new Account();
tempAccount.setId(ids[i]);
tempAccount.setRating("Hot");
toBeUpdatedAccount[i] = tempAccount;
}
//Update the account
try{
SaveResult[] results = getEnterpriseConnection().update(toBeUpdatedAccount);
for(SaveResult eachResult : results){
if(eachResult.isSuccess()){
System.out.println("Account updated with ID: " + eachResult.getId());
}else{
for(Error eachError : eachResult.getErrors()){
System.out.println("Error message is: " + eachError.getMessage());
}
}
}
}catch(ConnectionException e){
e.printStackTrace();
}
}
public EnterpriseConnection getEnterpriseConnection() {
return enterpriseConnection;
}
public void setEnterpriseConnection(EnterpriseConnection enterpriseConnection) {
this.enterpriseConnection = enterpriseConnection;
}
}
Now in the below post, I would like to add an existing account to an existing opportunity. I can do that with update() method by passing the opportunity ID and the External ID value of the account record. Important: Keep in mind you need to pass the External ID value of the account record. In my Org, I have setup a custom field Account_External_ID__c and marked that as External ID.Below code will help you to understand how you can achieve the above requirement – import com.sforce.soap.enterprise.EnterpriseConnection;
import com.sforce.soap.enterprise.Error;
import com.sforce.soap.enterprise.SaveResult;
import com.sforce.soap.enterprise.sobject.Account;
import com.sforce.soap.enterprise.sobject.Opportunity;
import com.sforce.soap.enterprise.sobject.SObject;
import com.sforce.ws.ConnectionException;
public class UpdateOpportunityAccount {
private EnterpriseConnection enterpriseConnection;
private UpdateOpportunityAccount(){
setEnterpriseConnection(ConnectionHelper.doConnect());
}
public static void main(String[] args) {
UpdateOpportunityAccount updateOpportunityAccount = new UpdateOpportunityAccount();
updateOpportunityAccount.doUpdateOpportunityAccount("0069000000ReDgi","EXID1111");
}
private void doUpdateOpportunityAccount(String opportunityId, String accountExternalId){
try{
//Link an existing opportunity
Opportunity toBeUpdatedOpportunity = new Opportunity();
toBeUpdatedOpportunity.setId(opportunityId);
//Link an existing account
Account toBeLinkedAccount = new Account();
toBeLinkedAccount.setAccount_External_ID__c(accountExternalId);
//Link Opportunity with Account
toBeUpdatedOpportunity.setAccount(toBeLinkedAccount);
SaveResult[] results = getEnterpriseConnection().update(new SObject[]{toBeUpdatedOpportunity});
for(SaveResult eachResult : results){
if(eachResult.isSuccess()){
System.out.println("Created succesfully with ID: " + eachResult.getId());
}else{
for(Error eachError : eachResult.getErrors()){
System.out.println("Error message is: " + eachError.getMessage());
}
}
}
}catch(ConnectionException e){
e.printStackTrace();
}
}
public EnterpriseConnection getEnterpriseConnection() {
return enterpriseConnection;
}
public void setEnterpriseConnection(EnterpriseConnection enterpriseConnection) {
this.enterpriseConnection = enterpriseConnection;
}
}
Appreciate your feedback. Thanks.
In my next post, I will explain the upsert operation. Till then keep learning Salesforce.
by Sudipta Deb | Feb 20, 2015 | 501, Apex, dev 501, integration, Salesforce, SOAP
Preface – This post is part of “
Salesforce Integration with SOAP API” series.
As of now we have understood how we can query one or more record from Salesforce using query() and queryMore() methods. The posts are @
But what about creating records –
Create() method is used to create one or more records in the Salesforce Org. This is basically doing the INSERT operation. The basic steps are given below –
- Create an array of sObject[] where each sObject is basically the record you want to create. You need to populate all the required fields.
- Call create(), passing the sObject[] array
- Process the results in the SaveResult[] object.
We should understand the below important points before going into the coding –
- API generates the unique ID fields automatically. As a developer, we can’t explicitly set the value of ID
- There are few other fields also getting generated automatically and we can’t set them explicitly. The fields are CreatedDate, CreatedById, LastModifiedDate, LastModifiedById and SystemModstamp.
- For all required fields, if there is no default values, as a developer you need to provide the values.
- For all non-required fields, if you don’t provide any values, API will put null.
- As a developer, you need to respect the referential integrity. For example – while creating the child record you need to supply the foreign key information that will link child with parent.
- While creating Account, Case or Lead, developer can make sure newly created Cases or Leads can be assigned to one or more users as per the assignment rule configured. You need to check AssignmentRuleHeader option.
- Your client application can create maximum 200 records in a single call of create(). If the create request exceeds 200 records, then the entire operation will fail.
- The AllOrNoneHeaderallows you to define the roll back behavior. The default behavior is to allow successful records to be committed while marking records with error as failed.
- As a developer, you can create multiple different types of object in a single create() call. You can create upto 10 different object type records in a single call. Records of different object types are broken into chunks and committed chunk wise. If there is any trigger on that object, that trigger will be called once per chunk. Each call can process upto 10 chunks.
- Records are always saved in the same order that they are entered in the sObject[] array. So if you are entering two object records having parent-child relationship, you need to make sure parent is added first followed by child in the sObject[] array.
- You can’t add a record that references another record of same object type in the same call. It’s like self – reference. If an account is having parent account, then you can’t insert account and parent account in the same call.
Note: I have written a helper class ConnectionHelper.java which I am using to connect to Salesforce using Enterprise WSDL. To know more about that, please refer my previous post @
Now below code will create two Account records –
import com.sforce.soap.enterprise.EnterpriseConnection;
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.soap.enterprise.Error;
public class CreateAccount {
private EnterpriseConnection connection;
private CreateAccount(){
setConnection(ConnectionHelper.doConnect());
}
public static void main(String[] args) {
CreateAccount createAccount = new CreateAccount();
createAccount.doCreateAccount();
}
private void doCreateAccount(){
Account account1 = new Account();
account1.setName("Test Account 1");
account1.setAccountNumber("11111");
account1.setRating("Hot");
account1.setPhone("888888");
Account account2 = new Account();
account2.setName("Test Account 2");
account2.setAccountNumber("11111");
account2.setRating("Hot");
account2.setPhone("888888");
try{
SaveResult[] results = getConnection().create(new SObject[]{account1, account2});
//Check the result
for(SaveResult result : results){
if(result.isSuccess()){
System.out.println("Account created with ID: " + result.getId());
}else{
for(Error anError : result.getErrors()){
System.out.println("Error occurred: " + anError.getMessage());
}
}
}
}catch(ConnectionException e){
e.printStackTrace();
}
}
public EnterpriseConnection getConnection() {
return connection;
}
public void setConnection(EnterpriseConnection connection) {
this.connection = connection;
}
}
We can create parent – child object relationship also using java program. Before that please find what Salesforce documented –
Now let’s check the code below –
import java.util.Calendar;
import com.sforce.soap.enterprise.EnterpriseConnection;
import com.sforce.soap.enterprise.Error;
import com.sforce.soap.enterprise.SaveResult;
import com.sforce.soap.enterprise.sobject.Account;
import com.sforce.soap.enterprise.sobject.Opportunity;
import com.sforce.soap.enterprise.sobject.SObject;
import com.sforce.ws.ConnectionException;
public class CreateOpportunityWithAccount {
private EnterpriseConnection connection;
private CreateOpportunityWithAccount(){
setConnection(ConnectionHelper.doConnect());
}
public static void main(String[] args) {
CreateOpportunityWithAccount createOpportunityWithAccount = new CreateOpportunityWithAccount();
createOpportunityWithAccount.doCreateOpportunityWithAccount();
}
private void doCreateOpportunityWithAccount(){
try{
Opportunity anOpportunity = new Opportunity();
anOpportunity.setName("TEST OPPORTUNITY");
anOpportunity.setStageName("Prospecting");
Calendar date = getConnection().getServerTimestamp().getTimestamp();
date.add(Calendar.DAY_OF_MONTH, 7);
anOpportunity.setCloseDate(date);
//Create the parent reference. This will be used only for foreign key reference and this should not contain any other field.
Account refAccount = new Account();
refAccount.setAccount_External_ID__c("TEST00001");
anOpportunity.setAccount(refAccount);
//Create the account object. This will be used to create the account
Account parentAccount = new Account();
parentAccount.setName("TEST PARENT ACCOUNT");
parentAccount.setAccount_External_ID__c("TEST00001");
//Create both Account and Opportunity
//Here the order is very important. parentAccount should be created first followed by anOpportunity,
//otherwise the creation of opportunity will fail due to foreign key, but
//Account will still be created
SaveResult[] results = getConnection().create(new SObject[]{parentAccount, anOpportunity});
//Check the results
for(SaveResult aResult : results){
if (aResult.isSuccess()){
System.out.println("Successfully created with ID: " + aResult.getId());
}else{
for(Error anError : aResult.getErrors()){
System.out.println("Error message: " + anError.getMessage());
}
}
}
}catch(ConnectionException e){
e.printStackTrace();
}
}
public EnterpriseConnection getConnection() {
return connection;
}
public void setConnection(EnterpriseConnection connection) {
this.connection = connection;
}
}
Hope this will help you to understand the process. Appreciate your feedback.
Wishing you a nice weekend. Cheers
by Sudipta Deb | Feb 19, 2015 | 501, Apex, dev 501, integration, Salesforce, SOAP
Preface – This post is part of “Salesforce Integration with SOAP API” series.
In my previous post, I have explained how to query Account record. The post is @
Salesforce Integration with SOAP API – Part 5 – Query Account Record with Java program
But say for example, if you have huge amount of record you need to fetch from Salesforce using SOAP API, then what you should do? Basically how you can bulkify your code?
Below is what Salesforce documented –
Please have a look what Salesforce tells about QueryLocator. Before going to the code, you need to understand the importance of QueryLocator.
Note: I have written a helper class ConnectionHelper.java which I am using to connect to Salesforce using Enterprise WSDL. To know more about that, please refer my previous post @
Now below is the Java code –
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.SObject;
import com.sforce.ws.ConnectionException;
public class QueryAllAccounts {
private EnterpriseConnection connection;
private QueryAllAccounts() {
setConnection(ConnectionHelper.doConnect());
}
public static void main(String[] args) {
QueryAllAccounts queryAllAccounts = new QueryAllAccounts();
queryAllAccounts.doQuery();
}
private void doQuery(){
QueryResult queryResult = new QueryResult();
try{
queryResult = getConnection().query("SELECT Id,Name,Phone,Rating FROM Account");
boolean done = false;
if(queryResult.getSize() > 0){
System.out.println("Found " + queryResult.getSize() + " records.");
while(!done){
for(SObject sObject : queryResult.getRecords()){
Account anAccount = (Account)sObject;
System.out.println("Account ID: " + anAccount.getId() + " Account Name: " + anAccount.getName() + " Phone: " + anAccount.getPhone() + " Rating: " + anAccount.getRating());
}
if(queryResult.isDone()){
done = true;
}else{
queryResult = getConnection().queryMore(queryResult.getQueryLocator());
}
}
}else{
System.out.println("No record found");
}
}catch(ConnectionException e){
e.printStackTrace();
}
}
public EnterpriseConnection getConnection() {
return connection;
}
public void setConnection(EnterpriseConnection connection) {
this.connection = connection;
}
}
I have marked the important line in the above code snippet. Hope this post and code snippet will help you to understand the concept. Please provide your feedback.
In my next post, I will explain how you can create records using SOAP API. Till then enjoy learning Salesforce.
by Sudipta Deb | Feb 18, 2015 | 501, dev 501, integration, Salesforce, SOAP
Preface – This post is part of “Salesforce Integration with SOAP API” series.
In my previous post, I have explained how can you configure your Eclipse IDE so that you can start writing you own Java program for connecting to Salesforce using SOAP API and also the Java program to check the connectivity. If you are not familiar, I would request you to go through my previous posts. The links are given below –
From this post, I will try to become more technical and concentrate on CRUD (Create, Read, Update and Delete) operation using Java Program and Salesforce’s SOAP API methods.
This is the first post where I will explain how you can query Salesforce records using Java program and SOAP API. The below program will fetch a specific Account record and display the information in console –
Note: I have written a helper class ConnectionHelper.java which I am using to connect to Salesforce using Enterprise WSDL. To know more about that, please refer my previous post @
Below is the java program which will fetch details of the account named “Burlington Textiles Corp of America”.
FindAccount.java
import com.sforce.soap.enterprise.EnterpriseConnection;
import com.sforce.soap.enterprise.QueryResult;
import com.sforce.soap.enterprise.sobject.Account;
import com.sforce.ws.ConnectionException;
public class FindAccount {
private EnterpriseConnection connection;
private FindAccount() {
setConnection(ConnectionHelper.doConnect());
}
public static void main(String[] args) {
FindAccount findAccount = new FindAccount();
findAccount.doFind();
}
private void doFind(){
QueryResult result = new QueryResult();
try{
result = getConnection().query("SELECT Id,Name,Phone,Rating FROM Account WHERE Name = 'Burlington Textiles Corp of America'");
if(result.getSize() > 0){
System.out.println("Found " + result.getSize() + " records.");
Account anAccount = (Account)result.getRecords()[0];
System.out.println("ID: " + anAccount.getId() + " Name: " + anAccount.getName() + " Phone: " + anAccount.getPhone() + " Rating: " + anAccount.getRating());
}
}catch(ConnectionException e){
e.printStackTrace();
}
}
public EnterpriseConnection getConnection() {
return connection;
}
public void setConnection(EnterpriseConnection connection) {
this.connection = connection;
}
}
Explanation:
Below is what Salesforce’s developer guide tells us regarding query() method:
I hope this post will help you to understand how you can fetch a single record using query() method. In my next post, I will explain how you can handle huge amount of data while doing the query. Till then good bye and keep learning.
Any feedback, please let me know. Thanks.