Salesforce Integration With Java

Ever wondered how we can access the Salesforce Object’s data inside java classes. To achieve the functionality, we need to integrate Salesforce with Java.

Below mentioned are the steps to establish a connection between Salesforce and Java.

  • We need an enterprise WSDL, which can be downloaded from Salesforce instance, Setup>Develop>API>Generate Enterprise WSDL.
  • We need to convert the downloaded WSDL to JAR file in order to import it into Eclipse User Library.
  • To convert it, we need wsc-xx.jar file. This file can be downloaded from http://code.google.com/p/sfdc-wsc/downloads/list . Make sure to chose the correct version of jar file according to your JDK version.
  • To generate the stub code, we need to go to terminal or cmd for Windows.

    java -classpath wsc-xx.jar com.sforce.ws.tools.wsdlc *wsdl* *jar.file*

    or

    java -jar wsc-23.jar *wsdl* *jar.file*

    • wsdl is the name of the WSDL file
    • jar.file is the name of the output jar file that wsdlc generates
  • Once you get the jar file, you need to open eclipse and create a User Library.
  • To create a user library, go to Eclipse>Window>Preferences>Java>Build Path>User Libraries>New and add both the wsc-xx.jar file and the generated enterprise.jar file.
  • Create a new Java project and add the user library created in previous step.
  • Now the eclipse is ready to establish a connection b/w Salesforce and Java.
  • Next a ConnectorConfig object needs to be instantiated with Salesforce username, password and authendpoint, and needs to be passed to EnterpriseConnection Object.

As an example, below is the sample code from the net, which has 4 functions – login(), describeGlobalSample(), querySample() and logout(). The login() establishes the connection, describeGlobal() returns an array of object results that includes the object names that are available to the logged-in user, querySample() fetches the available contacts in the system, and finally the logout().

Make Sure to pass your AuthEndPoint (https://login.salesforce.com/services/Soap/c/22.0/) as an argument before running the code. Also ensure to append your security token after your password.

That’s it.

//Code Sample
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.InputStreamReader;
import java.io.IOException;
import com.sforce.soap.enterprise.DeleteResult;
import com.sforce.soap.enterprise.DescribeGlobalResult;
import com.sforce.soap.enterprise.DescribeGlobalSObjectResult;
import com.sforce.soap.enterprise.DescribeSObjectResult;
import com.sforce.soap.enterprise.EnterpriseConnection;
import com.sforce.soap.enterprise.Error;
import com.sforce.soap.enterprise.Field;
import com.sforce.soap.enterprise.FieldType;
import com.sforce.soap.enterprise.GetUserInfoResult;
import com.sforce.soap.enterprise.LoginResult;
import com.sforce.soap.enterprise.PicklistEntry;
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.Contact;
import com.sforce.soap.enterprise.sobject.SObject;
import com.sforce.ws.ConnectorConfig;
import com.sforce.ws.ConnectionException;

public class Main {

private static BufferedReader reader = new BufferedReader(
new InputStreamReader(System.in));

EnterpriseConnection connection;
String authEndPoint = "";

public static void main(String[] args) {
if (args.length < 1) {
System.out.println("Usage: com.example.samples."
+ "QuickstartApiSamples <AuthEndPoint>");

System.exit(-1);
}

Main sample = new Main(args[0]);
sample.run();
}

public void run() {
// Make a login call
if (login()) {
// Do a describe global
describeGlobalSample();

// Retrieve some data using a query
querySample();

// Log out
logout();
}
}

// Constructor
public Main(String authEndPoint) {
this.authEndPoint = authEndPoint;
}

private String getUserInput(String prompt) {
String result = "";
try {
System.out.print(prompt);
result = reader.readLine();
} catch (IOException ioe) {
ioe.printStackTrace();
}

return result;
}

private boolean login() {
boolean success = false;
String username = getUserInput("Enter username: ");
String password = getUserInput("Enter password: ");

try {
ConnectorConfig config = new ConnectorConfig();
config.setUsername(username);
config.setPassword(password);

System.out.println("AuthEndPoint: " + authEndPoint);
config.setAuthEndpoint(authEndPoint);

connection = new EnterpriseConnection(config);
printUserInfo(config);

success = true;
} catch (ConnectionException ce) {
ce.printStackTrace();
}

return success;
}

private void printUserInfo(ConnectorConfig config) {
try {
GetUserInfoResult userInfo = connection.getUserInfo();

System.out.println("\nLogging in ...\n");
System.out.println("UserID: " + userInfo.getUserId());
System.out.println("User Full Name: " + userInfo.getUserFullName());
System.out.println("User Email: " + userInfo.getUserEmail());
System.out.println();
System.out.println("SessionID: " + config.getSessionId());
System.out.println("Auth End Point: " + config.getAuthEndpoint());
System.out
.println("Service End Point: " + config.getServiceEndpoint());
System.out.println();
} catch (ConnectionException ce) {
ce.printStackTrace();
}
}

private void logout() {
try {
connection.logout();
System.out.println("Logged out.");
} catch (ConnectionException ce) {
ce.printStackTrace();
}
}

/**
* To determine the objects that are available to the logged-in user, the
* sample client application executes a describeGlobal call, which returns
* all of the objects that are visible to the logged-in user. This call
* should not be made more than once per session, as the data returned from
* the call likely does not change frequently. The DescribeGlobalResult is
* simply echoed to the console.
*/
private void describeGlobalSample() {
try {
// describeGlobal() returns an array of object results that
// includes the object names that are available to the logged-in user.
DescribeGlobalResult dgr = connection.describeGlobal();

System.out.println("\nDescribe Global Results:\n");
// Loop through the array echoing the object names to the console
for (int i = 0; i < dgr.getSobjects().length; i++) {
System.out.println(dgr.getSobjects()[i].getName());
}
} catch (ConnectionException ce) {
ce.printStackTrace();
}
}

/**
* The following method illustrates the type of metadata information that can
* be obtained for each object available to the user. The sample client
* application executes a describeSObject call on a given object and then
* echoes the returned metadata information to the console. Object metadata
* information includes permissions, field types and length and available
* values for picklist fields and types for referenceTo fields.
*/

private void querySample() {
String soqlQuery = "SELECT FirstName, LastName FROM Contact";
try {
QueryResult qr = connection.query(soqlQuery);
boolean done = false;

if (qr.getSize() > 0) {
System.out.println("\nLogged-in user can see "
+ qr.getRecords().length + " contact records.");

while (!done) {
System.out.println("");
SObject[] records = qr.getRecords();
for (int i = 0; i < records.length; ++i) {
Contact con = (Contact) records[i];
String fName = con.getFirstName();
String lName = con.getLastName();

if (fName == null) {
System.out.println("Contact " + (i + 1) + ": " + lName);
} else {
System.out.println("Contact " + (i + 1) + ": " + fName
+ " " + lName);
}
}

if (qr.isDone()) {
done = true;
} else {
qr = connection.queryMore(qr.getQueryLocator());
}
}
} else {
System.out.println("No records found.");
}
} catch (ConnectionException ce) {
ce.printStackTrace();
}
}
}

Leave a comment