Upserting data into Salesforce using JAVA (Web Service API)

Upserting data into Salesforce using JAVA (Web Service API)

To upsert data in Salesforce using external application, upsert
() method is used.

upsert()
Creates new records and updates existing records; uses a custom
field to determine the presence of existing records. In most cases, we
recommend that you use upsert () instead of
create() to avoid creating
unwanted duplicate records (idempotent). You can process records for one more
than object type in an create() or update()
call, but all records must have the same object type in an upsert ()
call.
Upsert is a merging of the words insert and update. This call is
available for objects if the object has an external ID field or a field with
the
idLookup field property. On custom objects,
this call uses an indexed custom field called an external ID to determine
whether to create a new record or update an existing record. On standard
objects, this call can use the name of any field with the
idLookup field property instead
of the external ID.
Note:
Starting with API version 15.0, if you specify a value for a field
that contains a string, and the value is too big for the field, the call fails
and an error is returned. In previous versions of the API the value was
truncated and the call succeeded. If you wish to keep the old behavior with
versions 15.0 and later, use
the AllowFieldTruncationHeader SOAP header.
Syntax
UpsertResult[]
= connection.upsert(String externalIdFieldName, sObject[] sObjects);
Sample JAVA Program to
upsert data in Salesforce

package wsc;

import
java.io.BufferedReader;
import
java.io.FileNotFoundException;
import java.io.IOException;
import
java.io.InputStreamReader;

import
com.sforce.soap.enterprise.EnterpriseConnection;
import
com.sforce.soap.enterprise.GetUserInfoResult;
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;
import com.sforce.ws.ConnectorConfig;

public class UpsertAccount
{
            public String authEndPoint = “”;
            EnterpriseConnection
con;
            private static BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));

            public static void main(String[] args)
            {          
                        UpsertAccount
sample =
new UpsertAccount(“https://login.salesforce.com/services/Soap/c/24.0/0DF90000000PX8r”);
                        if ( sample.login() )
                        {
                                    sample.updateAcct();
                        }
            }
            public UpsertAccount(String
authEndPoint)
            {
                        this.authEndPoint = authEndPoint;
            }
            public String
getUserInput(String prompt)
            {
                        String
result =
“”;
                        try
                        {
                                    System.out.print(prompt);
                                    result
=
reader.readLine();
                        }
                        catch (IOException ioe)
                        {
                                    ioe.printStackTrace();
                        }
                        return result;
            }
            public boolean login()
            {
                        boolean success = false;
                        String
userId = getUserInput(
“UserID: “);
                        String
passwd = getUserInput(
“Password + Security Token:
);
                        try
                        {
                                    /* Setting up Username and Password */
                                    ConnectorConfig
config =
new
ConnectorConfig();
                                    config.setAuthEndpoint(authEndPoint);
                                    config.setUsername(userId);
                                    config.setPassword(passwd);
                                    config.setCompression(true);
                                    //config.setProxy(“Your Proxy”, 80);
                                    System.out.println(“AuthEndPoint: “ + authEndPoint);
                                    config.setTraceFile(“upsertLogs.txt”);
                                    config.setTraceMessage(true);




                                    config.setPrettyPrintXml(true);

                                    System.out.println(“nLogging in …n”);
                                    /* Setting up connection to Salesforce */
                                    con = new EnterpriseConnection(config);
                                    GetUserInfoResult
userInfo =
con.getUserInfo();   
                                    System.out.println(“UserID: “ +
userInfo.getUserId());
                                    System.out.println(“nLogged in Successfullyn”);
                                    success
=
true;
                        }
                        catch (ConnectionException
ce)
                        {
                                    ce.printStackTrace();
                        }
                        catch
(FileNotFoundException fnfe)
                        {
                                    fnfe.printStackTrace();
                        }
                        return success;
            }
            public void updateAcct()
            {
                        try
                        {                      
                                    /* Getting Account details */
                                    SObject[]
upserts =
new Account[1];
                                    Account
upsertAccount =
new Account();
                                    String
acctName = getUserInput(
“Enter Account
name:”
);
                                    String
acctNo = getUserInput(
“Enter Account no:”);
                                    String
phoneNo = getUserInput(
“Enter phone
no:”
);
                                    String
extId = getUserInput(
“Enter External Id:”);
                                   
                                    upsertAccount.setName(acctName);
                                    upsertAccount.setPhone(phoneNo);
                                    upsertAccount.setAccountNumber(acctNo);
                                    upsertAccount.setExternal_ID__c(extId);
                                   
                                    upserts[0]
= upsertAccount;
                                    System.out.println(“nUpserting…”);
                                    /* Upserting account records */   
                                    UpsertResult[]
upsertResults =
con.upsert(“External_ID__c”,upserts);
                                    for (UpsertResult result :
upsertResults)
                                    {
                                                if (result.isSuccess())
                                                {
                                                            System.out.println(“nUpsert succeeded.”);
                                                            System.out.println(
                                                                                    (result.isCreated()
?
“Insert” : “Update”) +
                                                                                    ” was performed.”
                                                            );
                                                            System.out.println(“Account ID: “ +
result.getId());
                                                }
                                                else
                                                {
                                                            System.out.println(“The Upsert failed because: “ +
                                                                                    result.getErrors()[0].getMessage());
                                                }
                                    }
                        }
                        catch (ConnectionException
ce)
                        {
                                    ce.printStackTrace();
                        }
            }
}

Output:
Password + Security Token: user01xmJO32dqadfdwB1kFNW9kEw
AuthEndPoint: https://login.salesforce.com/services/Soap/c/24.0/0DF90adfadf00PX8r
[WSC][UpsertAccount.login:63]Log
file already exists, appending to upsertLogs.txt
Logging in …
UserID: 0059dfadffqXHsAAM
Logged in Successfully
Enter Account name:Test Poc111
Enter Account no:222
Enter phone no:22223456543
Enter External Id:1024
Upserting…
Upsert succeeded.
Insert was performed.
Account ID: 0019000000BOU6ZAAX

Leave a Reply