Searching data in Salesforce using JAVA (Web Service API)

Searching data in Salesforce using JAVA (Web Service API)

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

search ()
Execute a text search in your organization’s data. Use
search () to search for records based on a search string. The search () call
supports searching custom objects. For an extensive discussion about the syntax
and rules used for text searches, see Salesforce Object Search Language (SOSL).
Certain objects cannot be searched via the API, such as Attachment objects. To
search an object via the search () call, the object must be configured as
searchable (isSearchable is true). To determine whether an object can be
searched, your client application can invoke the describeSObjects() call on the
object and inspect its searchable property.
Syntax
SearchResult
= connection.search(String searchString);
where connection is an object of EnterpriseConnection.
Sample JAVA Program to
search data in Salesforce
package wsc;

import
java.io.BufferedReader;
import
java.io.FileNotFoundException;
import java.io.IOException;
import
java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import
com.sforce.soap.enterprise.EnterpriseConnection;
import
com.sforce.soap.enterprise.GetUserInfoResult;
import
com.sforce.soap.enterprise.SearchRecord;
import
com.sforce.soap.enterprise.SearchResult;
import
com.sforce.soap.enterprise.sobject.Account;
import
com.sforce.soap.enterprise.sobject.Contact;
import
com.sforce.soap.enterprise.sobject.Lead;
import
com.sforce.soap.enterprise.sobject.SObject;
import
com.sforce.ws.ConnectionException;
import
com.sforce.ws.ConnectorConfig;

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

            public static void main(String[] args)
            {          
                        Search
sample =
new Search(“https://login.salesforce.com/services/Soap/c/24.0/0DF90000000PX8r”);
                        if ( sample.login() )
                        {
                                    sample.searchRecords
();
                        }
            }
            public Search(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(“3.209.92.6”, 80);
                                    System.out.println(“nAuthEndPoint: “ + authEndPoint + “n”);
                                    config.setTraceFile(“updateLogs.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 searchRecords ()
            {
                        try
                        {                      
                                    String
searchWord = getUserInput(
“Enter the text
to search:”
);
                                    System.out.println(“n”);

                                    String
soslQuery =
“FIND {“ + searchWord + “} IN name
fields “
+
                                    “returning contact(id, phone, firstname, lastname), “ +
                                    “lead(id, phone, firstname, lastname), “ +
                                    “account(id, phone, name)”;

                                    SearchResult
sr =
con.search(soslQuery);
                                    SearchRecord[]
records = sr.getSearchRecords();
                                    if (records != null && records.length > 0)
                                    {
                                                List<SObject>
objects =
new
ArrayList<SObject>();
                                                for (SearchRecord record : records)
                                                {
                                                            objects.add(record.getRecord());
                                                }
                                                if (! objects.isEmpty())
                                                {
                                                            Iterator<SObject>
iter = objects.iterator();
                                                            while (iter.hasNext())
                                                            {
                                                                        SObject
record = iter.next();
                                                                             
/* Account */
                                                                        if (record instanceof Account)
                                                                        {
                                                                                    Account
account = (Account) record;
                                                                                    System.out.println(“Account: “ +
account.getName()
                                                                                    );
                                                                        }
                                                                             
/* Contact */
                                                                        else if (record instanceof Contact)
                                                                        {
                                                                                    Contact
contact = (Contact) record;
                                                                                    System.out.println(“Contact: “ +
                                                                                                            contact.getFirstName()
+
                                                                                                            ” “ +
contact.getLastName()
                                                                                    );
                                                                        }
                                                                             
/* Lead */
                                                                        else
                                                                        {
                                                                                    Lead
lead = (Lead) record;
                                                                                    System.out.println(“Lead: “ + lead.getFirstName()
+
                                                                                                            ” “ + lead.getLastName()
                                                                                    );
                                                                        }
                                                            }
                                                }
                                    }
                                    else
                                    {
                                                System.out.println(“No records found for the search.”);
                                    }
                        }
                        catch (ConnectionException
ce)
                        {
                                    ce.printStackTrace();
                        }
            }
}
Output:

Password + Security Token: pdfdafmJO3dfdnhHUdfdfW9kEw
AuthEndPoint:
https://login.salesforce.com/services/Soap/c/24.0/0DF9dfdfdfdr
[WSC][Search.login:69]Log file
already exists, appending to updateLogs.txt
Logging in …
UserID: 005adfdf00qXHsAAM
Logged in Successfully
Enter the text to search:test
Contact: Test Test
Contact: Magu Test
Account: Test SFDC POC
Account: test poc
Account: Test
Account: Test_Acct3
Account: Test Acct3
Account: Test Acct2
Account: Test Acct1
Account: Test Acct

Leave a Reply