Wednesday, 7 December 2011

Accessing Salesforce Data from Java

To access salesforce data from java we follow the following steps
1)You  need to generate wsdl file from your salesforce organization.To do that

2)Go to ->Setup->Develop->Api->Generate Enterprise WSDL
Then one “WSDL” file generated with the extension either “.wsdl,.xml”

3)Now you need to download wsc-20.jar file from the site
Now follow create a jar file for your “Enterprise WSDL” using this WSC-20.jar from command prompt
4)Before do this you need to check java is installed on your system or not.If java is installed then proceed further.
To create jar you follow the follow the following method as show.
5)At command prompt you type like below/
java -classpath D:\balujava\wsc-20.jar D:\balujava\Enterprise.xml D:\balujava\Enterprise.jar

If you’re facing Version conflict then u need to change the command like
Java -DcompileTarget=1.7 -classpath D:\balujava\wsc-20.jar D:\balujava\Enterprise.xml  D:\balujava\Enterprise.jar
Here” D:\balujava” is the location where our files “wsc-20.jar and Enterprise.xml” stored and Enterprise.jar is a jar file we want to create for Enterprise.xml(wsdl file) using wsc-20.jar.See the below screenshot.

7)Now the Jar file is created  for our “Enter Prise Wsdl” as shown below

8)After that create a new javaproject  in eclipse   as shown below

9)Now click on” javaproject” then new Java project will be opened.

10)Then click on “Next” button

11)Now Click on “Libraries” tab .Then one window opened as shown below.

 12)Now click on “Add External Jar’s” button then one window opened as shown below and then select  wsc-20.jar and Enterprise.jar files as shown below

13)After adding these two files the  newproject look like  as shown below.

14)Now Click on Finish button.

Now go to “Test Java Project1” and click on that and then click on “ReferencedLibraries” to check whether the “two jar files are added or not”.

15)We can add these Jar files after saving Project also.
Now we are going through that also.
First “Right click on  Project Name You have created”
Click on Properties as shown below.

16)Now the window open for adding  External jar files from our stored shown below

17)Now “Click on Add External JARs”button and add “WSC-20.jar ,Enterprise.jar” files to Project as explain above images after this image.

Now paste the following code and run it “Runas”java application.
Once you have imported your WSDL file, you can begin building client applications that use the API. Use the following samples to create a basic client application. Comments embedded in the sample explain each section of code.
18)Java Sample Code
This section walks through a sample Java client application that uses the WSC SOAP client. The purpose of this sample application is to show the required steps for logging into the login server and to demonstrate the invocation and subsequent handling of several API calls. This sample application performs the following main tasks:
1.    Prompts the user for their Salesforce username and password.
2.    Calls login() to log in to the single login server and, if the login succeeds:
o    Turns on trace logs so that SOAP messages are printed to a file on the client host.
o    Retrieves user information and prints it to the console.
3.    Calls describeGlobal() to retrieve a list of all available objects for the organization’s data.
4.    Calls describeSObject() to retrieve metadata (field list and object properties) for a specified object.
5.    Calls query(), passing a simple query string ( "SELECT FirstName, LastName FROM Contact"), and iterating through the returned QueryResult.
Note the error handling code that follows each API call.

package com.example.samples;




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 co.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;

public class QuickstartApiSample {
  private static BufferedReader reader =
      new BufferedReader(new InputStreamReader(;
 EnterpriseConnection connection;
 String authEndPoint = "";
  public static void main(String[] args) {
   if ( args.length < 1 ) {
     System.out.println("Usage: com.example.samples." +
         "QuickstartApiSamples <AuthEndPoint>");


    QuickstartApiSample sample = new QuickstartApiSample(args[0]);

    if ( sample.login() ) {





  public QuickstartApiSample(String authEndPoint) {
   this.authEndPoint = authEndPoint;
  public String getUserInput(String prompt) {
   String result = "";
   try {
     result = reader.readLine();
   } catch (IOException ioe) {
   return result;

  public boolean login() {
    boolean success = false;
    String userId = getUserInput("UserID: ");
    String passwd = getUserInput("Password: ");
    try {
      ConnectorConfig config = new ConnectorConfig();
      System.out.println("AuthEndPoint: " + authEndPoint);
      connection = new EnterpriseConnection(config);
      GetUserInfoResult userInfo = connection.getUserInfo();
      System.out.println("\nLogging in ...\n");
      System.out.println("UserID: " + userInfo.getUserId());
      System.out.println("User Full Name: " +
      System.out.println("User Email: " +

      System.out.println("SessionID: " +
      System.out.println("Auth End Point: " +
      System.out.println("Service End Point: " +
      success = true;
    } catch (ConnectionException ce) {
    } catch (FileNotFoundException fnfe) {
    return success;
    public void logout() {
    try {
      System.out.println("Logged out");
    } catch (ConnectionException ce) {


   * 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.
  public void describeGlobalSample() {
   try {
      DescribeGlobalResult describeGlobalResult = connection.describeGlobal();
      DescribeGlobalSObjectResult[] sobjectResults = describeGlobalResult.getSobjects();

      for (int i = 0; i < sobjectResults.length; i++) {

    } catch (ConnectionException ce) {

   * The following code segment 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 describeSample() {
    String objectToDescribe = getUserInput("\nType the name of the object to " +
         "describe (try Account): ");

    try {

      DescribeSObjectResult describeSObjectResult =
      if (describeSObjectResult != null) {
        Field[] fields = describeSObjectResult.getFields();
        System.out.println("Metadata for the " +
            describeSObjectResult.getName() + " SObject"
        System.out.println("\tActivateable: " +

        System.out.println("\tNumber of fields: " + fields.length );

        if (fields != null) {

          for (Field field :  fields) {

            String name = field.getName();

            System.out.println("\tField name: " +



            PicklistEntry[] picklistValues =
            if (picklistValues != null && picklistValues.length > 0) {
              System.out.println("\t\tPicklist values: ");
              for (int j = 0; j < picklistValues.length; j++) {
                if (picklistValues[j].getLabel() != null) {
                  System.out.println("\t\tValue: " +
                      picklistValues[j].getLabel() );


           String[] referenceTos = field.getReferenceTo();
           if (referenceTos != null && referenceTos.length > 0) {
             System.out.println("\t\tThis field references the " +
                 "following objects:"

              for (int j = 0; j < referenceTos.length; j++) {
               System.out.println("\t\t" + referenceTos[j]);





    } catch (ConnectionException ce) {


  public void querySample() {
   try {
      String soqlQuery = "SELECT FirstName, LastName FROM Contact";

      QueryResult result = connection.query(soqlQuery);
     boolean done = false;
      if (result.getSize() > 0) {
        System.out.println("\nLogged-in user can see " +
            result.getRecords().length +

            " contact records."


        while (! done) {

          SObject[] records = result.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 (result.isDone()) {

            done = true;

          } else {

            result =




      } else {

        System.out.println("No records found.");


      System.out.println("\nQuery succesfully executed.");

    } catch (ConnectionException ce) {






  1. Thanks for the post. It was a lot easier to follow this tutorial than Salesforce's...I am however running into a problem programs compiles and runs with the following output:

    Usage: com.example.samples.QuickstartApiSamples

    I dont get the prompt for the UserID and password.

    If you could explain, that would be great. Thanks

  2. I have tried using different endpoints including:

    but it seems there is no support for these...

  3. I got it to work...I had to add endpoint to the run configuration once I did that it worked.

  4. Situs Sabung ayam terbaik se indonesia ^^

    situs sabung ayam

  5. Ayan ayam Petarung terbaik se indonesia ^^

    sabung ayam peru


Create Dynamic Picklists for Your Custom Components (design:component)

Hi, We can expose a component property as a picklist when the component is configured in the Lightning App Builder. The picklist’s value...