Skip to content

Using Java to connect to Salesforce

March 23, 2013

We are able to connect to Salesforce using JAVA in the following way.

public LoginResult login(String un, String pw, String token, boolean isSandbox) {
  final String URL;
  if (isSandbox) {
    URL = "https://test.salesforce.com/services/Soap/u/26.0";
  }
  else {
    URL = "https://login.salesforce.com/services/Soap/u/26.0";
  }
  try {
    ConnectorConfig config = new ConnectorConfig();
    config.setAuthEndpoint(URL);
    config.setServiceEndpoint(URL);
    config.setManualLogin(true);
    PartnerConnection conn = new PartnerConnection(config);
    com.sforce.soap.partner.LoginResult plr = conn.login(un, pw + token);

    LoginResult lr = new LoginResult();
    lr.endPoint = plr.getServerUrl();
    lr.errorMessage = "";
    lr.sessionId = plr.getSessionId();
    lr.success = true;
    return lr;
  }
  catch (Exception ex) {
    LoginResult lr = new LoginResult();
    lr.endPoint = "";
    lr.errorMessage = ex.getMessage();
    lr.sessionId = "";
    lr.success = false;
    return lr;
  }
}

With the returned loginResult we can create a partnerConnection that can then be used to perform various operations.

To create a partnerConnection we can use the following;

public PartnerConnection createPartnerConnection(String sessionId, String endPoint) {
  try {
    ConnectorConfig config = new ConnectorConfig();
    config.setAuthEndpoint(endPoint);
    config.setServiceEndpoint(endPoint);
    config.setSessionId(sessionId);
    config.setManualLogin(true);
    PartnerConnection conn = new PartnerConnection(config);
    return conn;
  }
  catch (ConnectionException e) {
    e.printStackTrace();
    return null;
  }
}

And using the partnerConnection we can perform a query.

String soqlQuery = "SELECT FirstName, LastName FROM Contact";
QueryResult qr = partnerConnection.query(soqlQuery);

A blog post by Federico Larsen explains nicely how queries should be structured to making use of Salesforce’s queryMore feature to ensure a full set or results is retrieved. The blog post can be found at this URL: http://larsenfed.wordpress.com/2013/03/15/handy-java-queryiterator-for-salesforce-com/

About these ads

From → Java, Salesforce

Leave a Comment

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

%d bloggers like this: