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 com.sforce.ws.tools.wsdlc 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 com.sforce.ws.tools.wsdlc 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 location.as 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 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 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;
import com.sforce.ws.ConnectorConfig;
import com.sforce.ws.ConnectionException;



public class QuickstartApiSample {
  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);

    }

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

    if ( sample.login() ) {

      sample.describeGlobalSample();

      sample.describeSample();

      sample.querySample();

    }

  }
  public QuickstartApiSample(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: ");
    try {
      ConnectorConfig config = new ConnectorConfig();
      config.setUsername(userId);
      config.setPassword(passwd);
      System.out.println("AuthEndPoint: " + authEndPoint);
      config.setAuthEndpoint(authEndPoint);
      config.setTraceFile("traceLogs.txt");
      config.setTraceMessage(true);
      config.setPrettyPrintXml(true);
      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: " +
          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();
      success = true;
    } catch (ConnectionException ce) {
      ce.printStackTrace();
    } catch (FileNotFoundException fnfe) {
      fnfe.printStackTrace();
    }
    return success;
  }
    public 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.
   */    
  public void describeGlobalSample() {
   try {
      DescribeGlobalResult describeGlobalResult = connection.describeGlobal();
      DescribeGlobalSObjectResult[] sobjectResults = describeGlobalResult.getSobjects();

      for (int i = 0; i < sobjectResults.length; i++) {
        System.out.println(sobjectResults[i].getName());
      }

    } catch (ConnectionException ce) {
      ce.printStackTrace();
    }
  }
  /**

   * 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 =
          connection.describeSObject(objectToDescribe);
      if (describeSObjectResult != null) {
        Field[] fields = describeSObjectResult.getFields();
        System.out.println("Metadata for the " +
            describeSObjectResult.getName() + " SObject"
        );
        System.out.println("\tActivateable: " +
            describeSObjectResult.isActivateable()
        );

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

        if (fields != null) {

          for (Field field :  fields) {

            String name = field.getName();

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

                field.getName()

            );

            PicklistEntry[] picklistValues =
                field.getPicklistValues();
            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) {
     ce.printStackTrace();
    }

  }

  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 =

                connection.queryMore(result.getQueryLocator());

          }

        }

      } else {

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

      }

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

    } catch (ConnectionException ce) {

      ce.printStackTrace();

    }

  }

}

4 comments:

  1. Thanks for the post. It was a lot easier to follow this tutorial than Salesforce's...I am however running into a problem though....my 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

    ReplyDelete
  2. I have tried using different endpoints including:

    https://login.salesforce.com/services/Soap/c/23.0

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

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

    ReplyDelete