Salesforce System Integration Interview Prep

Remote Process Invocation – Request and Reply

Best solutions

  1. External Services – invokes a REST API call – allows to invoke externally hosted service in declarative manner. External REST service are available in a an OpenAPI or Integrant schema definition. Contains primitive data types, nested objects not supported. Transaction invoked from Lightning Flow. Integration transaction doesn’t risk exceeding the synchronous Apex governor limits.
  2. Salesforce Lighting – consume WSDL and generate Apex proxy. Enable HTTP (REST) services, GET, PUT, POST, DELETE methods.
  3. Custom Visualforce page or button initiates Apex HTTP callout – user initiated action calls and Apex action that executed this proxy Apex class

Suboptimal

  1. Trigger – calls must be asynchronous (@future)
  2. Batch job callout – bundle responses together and make 1 callout for every 200 records processed.

Endpoint capability

Endpoint should be able to receive a web services call via HTTP. Salesforce must be able to access endpoint via the internet, curl or postman. Apex SOAP callout- WSDL 1.1, SOAP 1.1

Apex HTTP callout -REST service using standard GET, POST, PUT, DELETE methods

Data Volumes

Small volume, real time activities, due to small timeout values and maximum size of the request or response from Apex call solution.

Timeliness

  1. Request is typically invoked from user interface, must not keep user waiting
  2. Governor limit of 120 second timeout for callouts
  3. Remote process needs to be completed in SF limit and user expectations else seen as slow system
  4. Apex synchronous apex limits are 10 transaction than run for 5 seconds
    • Make sure external server callout is less than 5 seconds

State management

  1. Salesforce stores the external system External Id for specific record
  2. The remote system stores the Salesforce unique record ID or other unique key

Security

Any call to external service should maintain:

  1. Confidentiality
  2. Integrity
  3. Availability

Apex SOAP and HTTP callouts security considerations

  1. One way SSL is enabled by default
  2. 2 way SSL is enabled by self-signed certificate or CA-signed certificate
  3. WS-Security is not supported
  4. If necessary use one way hash or digital signature using Apex Crypto to ensure message integrity
  5. Remote system must be protected by appropriate firewall mechanism

Error Handling – error occurs in form of error http error codes

400 – Bad request, 401 – Unauthorized, 404 – Not Found, 500 – Internal server error

Recovery – changes not committed to Salesforce until successful response, retry

x amount of times until success received else log error.

Idempotent Design consideration – duplicate calls when something goes wrong needs

need to have a message ID to make sure duplicates are not created

Http h = new Http();
HttpRequest req = new HttpRequest();
req.setEndpoint(url); //
req.setMethod('GET'); //

//Basic Authentication - specify in Named Credentials so no code change needed
String username = 'myname';
String password = 'mypwd';

Blob headerValue = Blob.valueOf(username + ':' + password);
String authorizationHeader = 'Basic ' +
EncodingUtil.base64Encode(headerValue);
req.setHeader('Authorization', authorizationHeader);

HttpResponse response = h.send(req);

if (response.getStatusCode() == 200) {
    Map<String, Object> results = (Map<String, Object>) JSON.deserializeUntyped(response.getBody());
    List<Object> animals = (List<Object>) results.get('animals');
    System.debug('Received the following animals:');
    for (Object animal: animals) {
        System.debug(animal);
    }
}

//Implement httpCalloutMock
global class YourHttpCalloutMockImpl implements HttpCalloutMock {
    global HTTPResponse respond(HTTPRequest req) {
    

Test.setMock(HttpCalloutMock.class, new YourHttpCalloutMockImpl());

Remote Process Invocation – Fire and forget

Best solutions

  1. Process-driven platform events – using process builder/workflow rules to create process to publish insert or update event
  2. Event messages – the process of communicating changes and responding to them without writing complex logic. One or more subscribers can listen to the same event and carry out actions through CometD.
  3. Customized-driven platform events – events are created by Apex triggers or batch classes
  4. Workflow driven outbound messaging – remote process is invoked from an insert or update event. Salesforce provides workflow-driven outbound messaging capability that allow sending SOAP messages to remote systems.
  5. Outbound messaging and callbacks – callback helps mitigate out-of-sequence messaging also 2 things Idempotency and Retrieve of more data. When creating a new record and update externalId with the recordId from external system.

Suboptimal

  1. Lightning components – user interface based scenarios, must guarantee delivery of message in code
  2. Triggers – Apex triggers to perform automation based on records changes
  3. Batch jobs – calls to remote system can be performed from a batch job. Solution allows batch remote process execution and for processing of reposes from remote system.
MyEventObject__e newEvent = new MyEventObject__e();
newEvent.Name__c = 'Test Platform Event';
newEvent.Description__c = 'This is a test message';
List<Database.SaveResult> results = EventBus.publish(newEvent);

	
Test.startTest();
// Create test events
// ...
// Publish test events with EventBus.publish()
// ...
// Deliver test events
Test.getEventBus().deliver();
// Perform validation 
// ...
Test.stopTest();


//Listener - EMPConnector use login to and create EmpConnector(bayeuxParameters)
import static com.salesforce.emp.connector.LoginHelper.login;
//create consumer
SalesforceEventPayload eventPayload = new SalesforceEventPayload();
	Consumer<Map<String, Object>> consumer = event -> {
			eventPayload.setPayload(event);
			itsReqHandler.handleRequest(eventPayload.getPayload());
};

//add subscription to event
subscription = empConnector.subscribe("/event/" + EVENT_NAME, replayFrom, consumer).get(WAIT_TIME, TimeUnit.SECONDS);

Error handling and recovery

Error handling – because this pattern is asynchronous the callout of event publish handles need to be handles as well as the remote system needs to handle queuing, processing and error handling.

Recovery

More complex, need some retry strategy if no retry is receive in the QoS (Quality of Service) time period

Idempotent Design considerations

Platform events are published once, there is no retry on the Salesforce side. It is up to the ESB to request that the events be replayed. In a replay, the platform events reply ID remains the same and ESB can try to duplicate messages based on reply ID.

Unique Id for outbound messages is sent and needs to be tracked by the remote system to make sure duplicate messages or events are not repossessed.

Security

  1. Platform events – conforms to the security of the existing Salesforce org
  2. Outbound messages – One way SSL enabled, two way SSL can be used with outbound message certificate. Whitelist the IP ranges of the remote integration servers, remote server needs appropriate firewalls
  3. Apex callout – one way SSL enabled, 2 way SSL through self signed or CA signed certificates. Use one way hash or digital signature (Apex Crypto class) to ensure integrity of message. Remote system protected by appropriate firewall mechanisms.

Timeliness

Less important, control handed back to client immediate or after successful deliver message. Outbound message acknowledgment must occur in 24 hours (can be extended to seven days) otherwise message expires.

Platform events – send events to event bus and doesn’t wait for confirmation or acknowledgement from subscriber. If subscribe doesn’t pick up the message they can reply the event using replayID. High volume message are stored for 72 hours (3 days). Subscriber use CometD to subscribe to channel.

State management

Unique record identifiers are important for ongoing state tracking:

  1. Salesforce store remote system primary or unique surrogate key for remote record
  2. Remote system store Salesforce unique record ID or some unique surrogate key

Governor Limits

Limits depends on the type of outbound call and timing of the call

Reliable Messaging

  1. Platform Events – form of reliable messaging. Salesforce pushed the event to subscribers. If the message doesn’t gets picked up it can be replayed using reply ID.
  2. Apex callout – recommend that the remote system implement JMS, MQ however it doesn’t guarantee delivery to remote system, specific techniques such as processing positive acknowledgement from remote endpoint in addition to custom retry logic must be implemented.
  3. Outbound messaging – if no positive acknowledgment receive, retry up to 24 hours. Retry interval increase exponentially 15 sec to 60 min intervals.

Publisher and subscriber not in same transaction

Publish event before committed to the database, subscriber receives the event and does lookup to not find the record.

Publish behavior – publish immediately/publish after commit

Publish events – @future or @queueable to callout to events only when commit has complete

Message sequencing

Remote system discard message with duplicate message ID

Salesforce send RecordId, remote system makes callback to Salesforce

Handing Deletes

Salesforce workflow can’t track deletion of records, can’t call outbound message for deletion. Workaround:

  1. Create custom object called Deleted_Records__c
  2. Create trigger to store info (unique identifier) in custom object
  3. Implement workflow rule to initiate message based on the creation of custom object

Batch Data Synchronization

Best solutions

  1. Salesforce change data capture (Salesforce master)
  2. Replication via third party ETL Tool (Remote system master) – Bulk API
  3. Replication via third party ETL Tool (Salesforce master) – SOAP API getUpdated()

Suboptimal

  1. Remote call-in – call into SF, causes lots of traffic, error handling, locking
  2. Remote process invocation – call to remote system, causes traffic, error handing, locking

Extract and transform accounts, contacts, opportunities from current CRM to Salesforce (initial data load import)

Extract, transform, load billing data into Salesforce from remote system on weekly basis (ongoing)

Data master

Salesforce or Remote system

 

Salesforce Change Data Capture

Publish insert, update, delete, undelete events which represents changes to Salesforce. Receive near real time changes of records and sync to external data store.

Takes care of continuous synchronization part, needs integration app to receive events and perform update to external system

Channel – /data/{objectName}_Change

Error handling – Pattern is async remote system should handle message queuing, processing and error handling.

Recovery – initiate retry based on service quality of service requirement. Use replyID to reply stream of events. Use CometD to retrieve past messages up to 72 hours.

Bulk API – Replication via 3rd party ETL tool (more than 100 000 records)

Allow to run change data capture against source data. Tool reacts to change in the source data set, transforms the data and them call Salesforce Bulk API to issue DML statement, can also use SOAP API.

  1. Read control table to determine last time job ran, other control values needed
  2. Use above control values to filter query
  3. Apply predefine processing rules, validation rules, enrichments
  4. Use available connectors/transformation capability to create destination data set
  5. Write the data to Salesforce objects
  6. If processing is success update the control variable
  7. If process fail update control variable for process to restart

Consider

  1. Chain and sequence ETL jobs to provide cohesive process
  2. Use primary key for both systems to match incoming data
  3. Use specific API methods to extract only updated data
  4. Importing master-detail or lookup, consider using the parent key at the source to avoid locking. Group contacts for an account to be imported at the same time.
  5. Post-import processing should only process data selectively
  6. Disable Apex triggers, workflow and validation rules
  7. Use the defer calculations permission to defer sharing calculations until all data loaded

Error handling

If error occur during read operation, retry for errors. If errors repeat implement control tables/error tables in context of:

  1. Log the error
  2. Retry the read operation
  3. Terminate if successful
  4. Send a notification

Security

  1. Lightning Platform license with at least “API Only” user permission
  2. Standard encryption to keep password access secure
  3. Use HTTPS protocol

Timeliness

Take care to design the interface so all batch processes complete in a designated batch window

Loading batches during business hours not recommended

Global operations should run all batch processes at the same time

State management

Use surrogate key between two systems.

Standard optimistic locking occurs on platform and any updates made using the API require the user who is editing the record to initiate a refresh and initiate their transaction. Optimistic locking means:

  1. Salesforce doesn’t maintain state of record being edited
  2. Upon read, records time when data was extracted
  3. If user updated the record and before save checks if another user has updated
  4. System notified user update was made and use retrieve the latest version before updating

Middleware capabilities

Middleware tool that supports Bulk API

Supports the getUpdated() function – provide closest implementation to standard change data capture capability in Salesforce

Extracting data

Use the getUpdated() and getDeleted() SOAP API to sync an external system with Salesforce at intervals greater than 5 minutes. Use outbound messaging for more frequent syncing.

When querying can return more than an million results, consider the query capability of the Bulk API.

Remote Call-In

Best solutions

  1. SOAP API – Publish events, query data, CRUD. Synchronous API, waits until it receives a response. Generated WSDL – enterprise (strongly-typed), partner (loosely typed). Must have a valid login and obtain session to perform calls. Allows partial success if the records are marked with errors, also allows “all or nothing” behavior.
  2. REST API – Publish events, query data, CRUD. Synchronous API, waits until it receives a response. Lightweight and provides simple method for interacting with Salesforce. Must have a valid login and obtain session to perform calls. Allows partial success if the records are marked with errors, also allows “all or nothing” behavior. Output of one to use as input to next call.

Suboptimal

  1. Apex Web services – use when: full transaction support is required, custom logic needs to be applied before commenting.
  2. Apex REST services – lightweight implementation of REST services
  3. Bulk API – submitting a number of batches to query, update, upsert or delete large number of records.

Authentication

Salesforce supports SSL (Security Socket Layer) and TLS (Transport Later Security), Ciphers must be at least length 128 bits

Remote system has to authenticate before accessing any REST service. Remote system can use OAuth 2.0 or username/password. Client has to set the authorization HTTP header with the appropriate value.

Recommend client caches the session ID rather than creating a new session ID for every call.

Accessibility

Salesforce provides a REST API that remote system can use to:

  1. Query data in org
  2. Publish events to org
  3. CRUD of data
  4. Metadata

Synchronous API

After call to server it waits for a response, asynchronous call to Salesforce is not supported

REST vs SOAP

REST exposes resources as URI and uses HTTP verbs to define CRUD operations. Unlike SOAP, REST required no predefined contract, utilize XML and JSON for responses, and has loosely typed. Advantage includes ease of integration and great use for mobile and web apps.

Security

Client executing the REST needs a valid Salesforce login and obtain a access token. API respects the object and field level security for the logged in user

Transaction/Commit Behavior

By default every record is treated as a separate transaction and committed separately. Failure of one records does not cause rollback of other changes. Using the composite API makes a series of updates in one call.

Rest composite resource

Perform multiple operation in a single API call. Also use output of one call to be input of next call. All response bodies and HTTP statuses are returned in a single response body. The entire requires counts as single call towards API limit.

Bulk API

For bulk operations use Rest-based BULK API

Event driven architecture

Platform events are defined the same way as you define a Salesforce object. Publishing to event bus is same as inserting Salesforce record. Only create and insert is supported.

Error handling

All remote call-in methods or custom API require remote system to handle any subsequent errors such as timeouts and retries. Middleware can be used to provide logic for recovery and error handling

Recovery

A custom retry mechanism needs to be created if QoS requirements dictate it. Important to consider impotent design characteristic.

Timeliness

Session timeout – session timeout when no activity based on SF org session timeout

Query timeout – each query has a timeout limit of 120 seconds

Data volumes

CRUD – 200 records per time

Blob size – 2GB ContentVersion (Chatter)

Query – query(), queryMore() return 500 records, max 2000

State management

Salesforce stores remote system primary key or unique key for the remote record

The remote system stores the Salesforce ID unique record ID or some unique

Governor limits

5000 API calls per 24 hour

10 query cursors open at time

Reliable messaging

Resolve the issue that delivery of a message to remote system where the individual components may be unreliable. SOAP API and REST API are synchronous and don’t provide explicit support for any reliable messaging protocols.

Data visualization

Best solutions

  1. Salesforce Connect

Suboptimal

  1. 1. Request and reply – Salesforce web services APIs (SOAP or REST) to make ad-hoc data requests to access and update external system data

Access data from external sources along with Salesforce data. Pull data from legacy systems, SAP, Microsoft, Oracle in real time without making a copy of the data.

Salesforce connect maps data tables in external systems to external objects in your org. External objects are similar to custom objects, except they map to data located outside SF org. Uses live connection to external data to keep external objects up to date.

Salesforce connects lets you

  1. Query data in a external system
  2. CRUD data in external system
  3. Define relationships between external objects and standard or custom objects
  4. Enable Chatter feed on external object page for collaboration
  5. Run reports on external data

Salesforce Connect Adapters

OData adapter 2.0 or OData adapter 4.0connects data to exposed by any OData 2.0 or OData 4.0 producer

Cross-org adapter – connects to data that’s stored in another Salesforce org. Used the Lightning Platform REST API

Custom adapter created via Apex – develop own adapter with the Apex Connector framework

Calling mechanism

External Objects – maps SF external objects to data tables in external systems. Connect access the data on demand and in real time. Provides seamless integration with Lightning Platform can do global search, lookup relationships, record feeds.

Also available to Apex, SOSL, SOQL queries, Salesforce API, Metadata API, change sets and packages.

Error handling

Run Salesforce Connector Validator tool to run some common queries and notice error types and failure causes

Benefits

  1. Doesn’t consume data storage in SF
  2. Don’t have to worry about regular sync between systems
  3. Declarative setup can be setup quickly
  4. Users can access external data with same functionality
  5. Ability to do federated search
  6. Ability to run reports

Considerations

Impact reports performance

Security considerations

Adhere to Salesforce org-level security, use HTTPS connect to any remote system.

OData understand behaviors, limitations and recommendations for CSRF (Cross-Site Request Forgery)

Timeliness

Request invoked by user interface, should not keep the user waiting

May take long to relieve data from external system, SF configured 120 sec maximum timeout

Completion of remote process should execute in timely manner

Data volumes

Use mainly for small volume, real time activities, due to small timeout and maximum size of request or response for Apex call solution.

State management

Salesforce stores primary or unique surrogate key for the remote record

Remote system store SF unique record ID or other unique surrogate key

Salesforce Platform Events Streaming using Spring Boot

Create EmpConnector connection
The first thing is to create a configuration that on startup will connect to the EmpConnector and start listing for incoming events on a specific topic.

1. Set all your Bayeux Parameters (bayeuxParameters)
2. Create EmpConnector connection (empConnector)
3. Start listening to topic (startAndPublishAsyncEventToExchange)
4. Adding listeners to the topic (startAndPublishAsyncEventToExchange)

package com.app.core.events;

import com.app.core.service.IncomingRequestHandler;
import com.app.utils.AppPlanUtils;
import com.salesforce.emp.connector.BayeuxParameters;
import com.salesforce.emp.connector.EmpConnector;
import com.salesforce.emp.connector.TopicSubscription;
import com.salesforce.emp.connector.example.LoggingListener;
import org.cometd.bayeux.Channel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Lazy;

import java.net.URL;
import java.util.Map;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.function.Consumer;

import static com.salesforce.emp.connector.LoginHelper.login;

@Configuration
@ConfigurationProperties
@Lazy
public class SalesforceEventConfig {

    private static Logger itsLogger = LoggerFactory.getLogger(SalesforceEventConfig.class);

    @Value("${salesforce.username}")
    private String username;

    @Value("${salesforce.password}")
    private String password;

    @Value("${salesforce.token}")
    private String token;

    @Value("${salesforce.baseurl}")
    private String url;

    @Value("${salesforce.version:39.0}")
    private String version;

    @Autowired
    protected IncomingRequestHandler itsReqHandler;

    private static final Integer WAIT_TIME = 2;
    private static final Integer START_UP_WAIT_TIME = 5;
    private static final String EVENT_NAME = "App_Events__e";

    @Bean
    public BayeuxParameters bayeuxParameters() throws Exception {
        String theUrlEnv = AppUtils.getConfigVar("SALESFORCE_URL");
        String passwordAndToken = password + token;
        if (theUrlEnv != null) {
            url = getNextToken(0, theUrlEnv);
            username = getNextToken(url.length() + version.length() + 2, theUrlEnv);
            passwordAndToken = theUrlEnv.substring(url.length() + version.length() + username.length() + 3);
            itsLogger.info("Found SALESFORCE_URL to parse. url={}, version={}, username={}", url, version, username);
            url = url.split("/services/Soap/u/")[0];
        }

        BayeuxParameters bayeuxParams = getBayeuxParamWithSpecifiedAPIVersion(version);
        BayeuxParameters bayeuxParameters = login(new URL(url),username, passwordAndToken, bayeuxParams);
        return bayeuxParameters;
    }

    @Bean
    public EmpConnector empConnector(BayeuxParameters bayeuxParameters){
        itsLogger.debug("BayeuxParameters url {} version {}", bayeuxParameters.host(), bayeuxParameters.version());
        EmpConnector empConnector = new EmpConnector(bayeuxParameters);
        itsLogger.debug("EmpConnector isConnected {} isHandshook {}", empConnector.isConnected(), empConnector.isHandshook());
        return empConnector;
    }

    private static BayeuxParameters getBayeuxParamWithSpecifiedAPIVersion(String apiVersion) {
        BayeuxParameters params = new BayeuxParameters() {

            @Override
            public String version() {
                return apiVersion;
            }

            @Override
            public String bearerToken() {
                return null;
            }

        };
        return  params;
    }

    private String getNextToken(int startIdx, String origStr) {
        int theIdx = origStr.indexOf("|", startIdx);
        if (theIdx > 0) {
            return origStr.substring(startIdx, theIdx);
        } else {
            return origStr.substring(startIdx);
        }
    }

    @Bean
    public TopicSubscription startAndPublishAsyncEventToExchange(EmpConnector empConnector)  {
        TopicSubscription subscription = null;
        try {
            long replayFrom = EmpConnector.REPLAY_FROM_TIP;
            itsLogger.debug("Setup event consumer with replyFrom {}", replayFrom);

            SalesforceEventPayload eventPayload = new SalesforceEventPayload();
            Consumer<Map<String, Object>> consumer = event -> {
                eventPayload.setPayload(event);
                itsReqHandler.handleRequest(eventPayload.getPayload());
            };

            LoggingListener loggingListener = new LoggingListener(true, true);
            itsLogger.debug("Adding event listeners");
            empConnector.addListener(Channel.META_CONNECT, loggingListener)
                    .addListener(Channel.META_HANDSHAKE, loggingListener)
                    .addListener(Channel.META_DISCONNECT, loggingListener)
                    .addListener(Channel.META_SUBSCRIBE, loggingListener)
                    .addListener(Channel.META_UNSUBSCRIBE, loggingListener)
                    .addListener(Channel.META_DISCONNECT, loggingListener)
                    .addListener(Channel.SERVICE, loggingListener);

            itsLogger.debug("Starting Event Bus");
            empConnector.start().get(START_UP_WAIT_TIME, TimeUnit.SECONDS);

            itsLogger.debug("Subscribing to event {}", EVENT_NAME);
            subscription = empConnector.subscribe("/event/" + EVENT_NAME, replayFrom, consumer).get(WAIT_TIME, TimeUnit.SECONDS);

            itsLogger.debug(String.format("Subscribed: %s", subscription));

        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        } catch (TimeoutException e) {
            e.printStackTrace();
        }

        return subscription;
    }
}

Basic POJO to serialize events received for a specific topic

Note: as the ‘payload’ tag has some extra tags I remove them before serializing the payload to POJO.

package com.app.core.events;

import com.app.db.model.UserServiceRequestEvent;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.commons.lang3.StringEscapeUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.io.Serializable;
import java.util.Map;

public class SalesforceEventPayload implements Serializable{

    private static final String SALESFORCE_EVENT_KEY = "Event_Data__c=";

    private static Logger itsLogger = LoggerFactory.getLogger(SalesforceEventPayload.class);

    public SalesforceEventPayload() {}

    private UserServiceRequestEvent payload;

    public UserServiceRequestEvent getPayload() {
        return payload;
    }

    public void setPayload(Map<String, Object> fieldMappings) {
        ObjectMapper theMapper = new ObjectMapper();
        theMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        theMapper.configure(DeserializationFeature.FAIL_ON_IGNORED_PROPERTIES, false);
        theMapper.configure(DeserializationFeature.USE_JAVA_ARRAY_FOR_JSON_ARRAY, true);
        theMapper.configure(DeserializationFeature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT, true);
        theMapper.configure(DeserializationFeature.ACCEPT_EMPTY_ARRAY_AS_NULL_OBJECT, true);
        if (fieldMappings.containsKey("payload")){
            String eventPayload = fieldMappings.get("payload").toString();
            String splitEventString = eventPayload.toString().split(SALESFORCE_EVENT_KEY)[1];
            String removeLastTwo = splitEventString.substring(1, splitEventString.length() - 2);
            String unescapeJson = StringEscapeUtils.unescapeJson(removeLastTwo);
            try{
                payload = theMapper.readValue(unescapeJson, UserServiceRequestEvent.class);
            } catch (JsonParseException e) {
                itsLogger.error("Event json parse exception {}", e.getMessage());
            } catch (JsonMappingException e) {
                itsLogger.error("Event json mapping exception {}", e.getMessage());
            } catch (IOException e) {
                itsLogger.error("Event io exception {}", e.getMessage());
            }
        }
    }
}

Create a Salesforce EventBus

Create a new Planform Event Object and give it a name App Metadata (App_Metadata__e) which will also be the name of the topic. Create some fields you that you would like to listen to. In Apex add the following event

Build event payload

  List<App_Metadata.BPUpdateAccounts> updatedAccountList = new List<App_Metadata.BPUpdateAccounts>();
  App_Metadata.BPUpdateAccounts updatedAccount = new App_Metadata.BPUpdateAccounts();
  updatedAccount.setId(financialAccount.Id);
  updatedAccount.add(updatedAccount);
  new App_Rest_Events(new App_Rest_Events.Event(UserInfo.getUserId(), App_Rest_Events.EventType.UPDATE_ACCOUNT, 
  updatedAccountList)).publishToEventBus();

Publish Event to eventBus

  public void publishToEventBus(){
    Object eventPayload = buildEventPayload();
    EventBus.publish(new App_Metadata__e(Metadata_Json__c=JSON.serialize(eventPayload)));
  }

Now let’s create our event listen to subscript to the topic and consume the messages from the EventBus.

Add the emp-connector jar to project

<repositories>
        <repository>
            <id>emp-connector</id>
            <url>${project.basedir}/lib/emp-connector-0.0.1-SNAPSHOT-phat.jar</url>
        </repository>
    </repositories>

....

<dependency>
     <groupId>com.salesforce.conduit</groupId>
     <artifactId>emp-connector</artifactId>
     <version>0.0.1-SNAPSHOT</version>
</dependency>

Create TopicSubscription to your event table by name

package com.app.salesforce.eventbus;

import com.salesforce.emp.connector.BayeuxParameters;
import com.salesforce.emp.connector.EmpConnector;
import com.salesforce.emp.connector.TopicSubscription;

import java.net.URL;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.function.Consumer;

import static com.salesforce.emp.connector.LoginHelper.login;

/**
 * Created by thysmichels on 5/15/17.
 */
public class SalesforceEventBus {

    private static final String SALESFORCE_USERNAME="salesforceUsername";
    private static final String SALESFORCE_PASSWORD="salesforcePassword";

    public static void main(String[] argv) throws Exception {

        long replayFrom = EmpConnector.REPLAY_FROM_EARLIEST;

        BayeuxParameters params;
        BayeuxParameters custom = getBayeuxParamWithSpecifiedAPIVersion("39.0");
        try {
            params = login(new URL("https://test.salesforce.com"),SALESFORCE_USERNAME, SALESFORCE_PASSWORD, custom);

        } catch (Exception e) {
            e.printStackTrace(System.err);
            System.exit(1);
            throw e;
        }

        Consumer<Map<String, Object>> consumer = event -> System.out.println(String.format("Received:\n%s", event));
        EmpConnector connector = new EmpConnector(params);

        connector.start().get(5, TimeUnit.SECONDS);

        TopicSubscription subscription = connector.subscribe("/event/App_Metadata__e", replayFrom, consumer).get(5, TimeUnit.SECONDS);

        System.out.println(String.format("Subscribed: %s", subscription));
    }


    private static BayeuxParameters getBayeuxParamWithSpecifiedAPIVersion(String apiVersion) {
        BayeuxParameters params = new BayeuxParameters() {

            @Override
            public String version() {
                return apiVersion;
            }

            @Override
            public String bearerToken() {
                return null;
            }

        };
        return  params;
    }
}

Topic receives response from subscribed channel

Subscribed: Subscription [/event/App_Metadata__e:-2]
Received:
{schema=D6-eSgLDrahnNjuNI52XAg, payload={CreatedById=00521000000UcF0, CreatedDate=2017-05-15T18:35:10Z, 
Metadata_Json__c="{\"accounts\":[{\"id\":\"28706236\",\"providerAccountId\":14736,\"sfId\":\"a0721000001A6fOAAS\"},
{\"id\":\"YL1111\",\"providerAccountId\":1466,\"sfId\":\"a0721000001A6fPAAS\"}],\"event\":\"UPDATE_GOAL\",\"linkAccounts\":null,
\"financialAccountMap\":null,\"goals\":[{\"id\":\"a0821000000OVPUAA4\",\"linkedAccounts\":[\"a0721000001ADqkAAG\"],
\"status\":\"In Progress\"},{\"id\":\"a0821000000OVPZAA4\",\"linkedAccounts\":null,\"status\":\"In Progress\"},{\"id\":\"a0821000000OVPeAAO\",\"linkedAccounts\":[\"a0721000001ADqaAAG\"],\"status\":\"In Progress\"}],
\"linkUserContext\":{\"accountList\":null,\"additionalProperties\":null,\"deleteAccountList\":null,\"email\":\"blah@email.com\",
\"password\":\"p@assw0rd\",
\"providerAccountIds\":null,\"sfClientId\":\"0033600000NO1QjAAL\",\"sfHouseholdId\":\"0013600000VNXflAAH\",\"sfUserId\":\"00521000000UcF0AAK\",
\"type\":\"YL\",\"username\":\"YL00F0A\"},\"priority\":5,\"providerAccounts\":null,
\"updatedAccounts\":null,\"updatedGoals\":[{\"id\":\"a0821000000OVPZAA4\",\"linkedAccounts\":null}],\"mapKeys\":{\"event\":\"event\",\"priority\":\"priority\",\"linkUserContext\":\"linkUserContext\",\"goals\":\"goals\",
\"accounts\":\"accounts\",\"providerAccounts\":\"providerAccounts\",\"updatedAccounts\":\"updatedAccounts\",\"updatedGoals\":
\"updatedGoals\",\"goalFinancialAccountMap\":\"goalFinancialAccountMap\",\"fastlinkAccounts\":\"fastlinkAccounts\"},
\"mapKeysFlag\":true,\"serializeNulls\":false}"}, event={replayId=1}}

Salesforce Chatter Attaching Files to SObject

There are different ways you can use salesforce to attach a file to an SObject using Chatter.

  • Apex Code
  • Chatter REST Api
    public static void createAttachmentFeed(List<Attachment> attachments){
      for (Attachment attachment : attachments){
        // ContentVersion is how you upload a file!
       ContentVersion version = new ContentVersion();
       version.Title=attachment.Name;
       version.PathOnClient = '\\' + attachment.Name;
       version.VersionData = attachment.Body;
       version.NetWorkId = brightPlanWebCustomSettings.Community_Id__c;
       insert version;

       // After you insert the ContentVersion object, a base 'ContentDocument' is established
       // The ID of the ContentDocument is what you need to attach the file to the Chatter post.
       version = [SELECT ID,ContentDocumentId FROM ContentVersion WHERE ID=:version.id];

       // Form a basic post attached to our own feed.
       ConnectApi.FeedItemInput feedItem = new ConnectApi.FeedItemInput();
       feedItem.subjectId = attachment.ParentId; // This can also be an objectID to post the file to.

       // Now connect the feeditem to our already uploaded file.
       feedItem.capabilities = new ConnectAPI.FeedElementCapabilitiesInput();
       feedItem.capabilities.files = new ConnectAPI.FilesCapabilityInput();
       feedItem.capabilities.files.items = new List<ConnectAPI.FileIdInput>();
       ConnectAPI.FileIdInput attachFile = new ConnectAPI.FileIDInput();

       //**** Here is where we attach the specific file to the post!
       attachFile.id = version.contentDocumentid;
       feedItem.capabilities.files.items.add(attachFile);

       // Execute the posting
       ConnectApi.FeedElement feedElement = ConnectApi.ChatterFeeds.postFeedElement(brightPlanWebCustomSettings.Community_Id__c, feedItem);
      }
    }

Some limitations using this is using Blob for version.VersionData = attachment.Body; will run into Apex String length exceeds maximum: 6000000.

Chatter Rest API

POST https://cs43.salesforce.com/services/data/v35.0/connect/communities/0DB63000000003jGAA/chatter/feed-elements/batch

HEADER

Authorization         Bearer {sessionToken}

Content-Type          multipart/form-data; boundary=a7V4kRcFA8E79pivMuV2tukQ85cmNKeoEgJgq

Format is as follows:

{salesforceOrgUrl}/services/data/v35.0/connect/communities/{salesforceCommunityId}chatter/feed-elements/batch

The subjectId is the SObject Id to which you want to link the file, is this case we use our Case Id.

--a7V4kRcFA8E79pivMuV2tukQ85cmNKeoEgJgq
Content-Type: application/json; charset=UTF-8
Content-Disposition: form-data; name="json"
{
"inputs": [
{
"binaryPartNames": [
"file1"
],
"richInput": {
"subjectId": "50063000003YlSe",
"capabilities": {
"content": {
"title": "file1.pdf"
}
},
"feedElementType": "FeedItem"
}
},
{
"binaryPartNames": [
"file2"
],
"richInput": {
"subjectId": "50063000003YlSe",
"capabilities": {
"content": {
"title": "file2.pdf"
}
},
"feedElementType": "FeedItem"
}
}
]
}
--a7V4kRcFA8E79pivMuV2tukQ85cmNKeoEgJgq
Content-Type: application/octet-stream; charset=ISO-8859-1
Content-Disposition: form-data; name="file1"; filename="file1.pdf"

...contents of file1.pdf...

--a7V4kRcFA8E79pivMuV2tukQ85cmNKeoEgJgq
Content-Disposition: form-data; name="file2"; filename="file2.pdf"
Content-Type: application/octet-stream; charset=ISO-8859-1
...contents of file2.pdf...
--a7V4kRcFA8E79pivMuV2tukQ85cmNKeoEgJgq--

Benefits you can batch upload files without hitting an Apex limits.

Both the Chatter and Apex solutions can be used by Community Users to upload files.

Apache Camel Salesforce Integration

1. Setup SalesforceLoginConfig
2. Setup SalesforceCamelEndpointConfig
3. Setup SalesforceCamelComponent
4. Setup SalesforceCamelRouteConfig
5. Run SalesforceCamelIntegrationTest

1. Setup SalesforceLoginConfig

package com.sforce.core.camel;

import org.apache.camel.CamelContext;
import org.apache.camel.component.salesforce.SalesforceComponent;
import org.apache.camel.component.salesforce.SalesforceEndpointConfig;
import org.apache.camel.component.salesforce.SalesforceLoginConfig;
import org.apache.camel.impl.DefaultCamelContext;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * Created by tmichels on 4/8/15.
 */

@Configuration
public class SalesforceCamelConfig {

    @Value("${SF_USERNAME}")
    private String username;

    @Value("${SF_PASSWORD}")
    private String password;

    @Value("${SF_TOKEN}")
    private String token;

    @Value("${SF_BASE_URL}")
    private String url;

    @Value("${SF_VERSION}")
    private String version;

    @Value("${SF_CLIENT_ID}")
    private String clientId;

    @Value("${SF_CLIENT_SECRET}")
    private String clientSecret;


    @Bean
    public SalesforceLoginConfig salesforceLoginConfig(){
        SalesforceLoginConfig salesforceLoginConfig = new SalesforceLoginConfig();
        salesforceLoginConfig.setUserName(username);
        salesforceLoginConfig.setPassword(password+token);
        salesforceLoginConfig.setLoginUrl(url);
        salesforceLoginConfig.setClientId(clientId);
        salesforceLoginConfig.setClientSecret(clientSecret);
        salesforceLoginConfig.setLazyLogin(false);
        return salesforceLoginConfig;
    }
}

2. Setup SalesforceCamelEndpointConfig

package com.sforce.core.camel;

import org.apache.camel.Endpoint;
import org.apache.camel.component.salesforce.SalesforceComponent;
import org.apache.camel.component.salesforce.SalesforceEndpoint;
import org.apache.camel.component.salesforce.SalesforceEndpointConfig;
import org.apache.camel.component.salesforce.internal.OperationName;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * Created by tmichels on 4/13/15.
 */

@Configuration
public class SalesforceCamelEndpointConfig {
    
    @Bean
    public SalesforceEndpointConfig salesforceEndpointConfig(){
        SalesforceEndpointConfig salesforceEndpointConfig = new SalesforceEndpointConfig();
        salesforceEndpointConfig.setApiVersion("33.0");
        return salesforceEndpointConfig;
    }
}

3. Setup SalesforceCamelComponent

package com.sforce.core.camel;


import org.apache.camel.component.salesforce.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;

/**
 * Created by tmichels on 4/13/15.
 */

@Configuration
@Import({SalesforceCamelEndpointConfig.class, SalesforceCamelConfig.class})
public class SalesforceCamelComponent {

    @Autowired
    SalesforceEndpointConfig salesforceEndpointConfig;

    @Autowired
    SalesforceLoginConfig salesforceLoginConfig;

    @Bean
    public SalesforceComponent salesforceComponent(){
        SalesforceComponent salesforceComponent = new SalesforceComponent();
        salesforceComponent.setConfig(salesforceEndpointConfig);
        salesforceComponent.setLoginConfig(salesforceLoginConfig);
        salesforceComponent.setPackages("com.sfore.core.camel");
        return salesforceComponent;
    }
}

4. Setup SalesforceCamelRouteConfig

package com.sforce.core.camel;

import com.sforce.core.config.LcGroovyPropertiesConfig;
import org.apache.camel.CamelContext;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.component.salesforce.SalesforceComponent;
import org.apache.camel.spring.SpringCamelContext;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.*;
import org.apache.camel.spring.javaconfig.SingleRouteCamelConfiguration;
import org.apache.camel.spring.javaconfig.Main;

/**
 * Created by tmichels on 4/10/15.
 */

@Configuration
@ComponentScan({"com.sforce.core.camel"})
public class SalesforceCamelRouteConfig extends SingleRouteCamelConfiguration implements InitializingBean {

    @Autowired
    SalesforceComponent salesforceCamelComponent;

    public static void main(String[] args) throws Exception {
        Main main = new Main();
        main.run(args);
    }


    @Override
    protected CamelContext createCamelContext() throws Exception {
        SpringCamelContext camelContext = new SpringCamelContext();
        camelContext.setApplicationContext(getApplicationContext());
        camelContext.addComponent("salesforce", salesforceCamelComponent);
        camelContext.addRoutes(route());
        camelContext.start();
        return camelContext;
    }


    @Override
    public void afterPropertiesSet() throws Exception {}

    @Bean
    @Override
    public RouteBuilder route() {
        return new RouteBuilder() {
            public void configure() {
                from("direct:getBasicInfo").to("salesforce:getBasicInfo").bean(BasicInfoBean.class);
            }
        };
    }

    public static class BasicInfoBean {
        public void someMethod(String body) {
            System.out.println(">>>>>>> Salesforce Basics Info: " + body);
        }
    }
}

5. Run SalesforceCamelIntegrationTest

package com.sforce.core.camel;

import org.apache.camel.CamelContext;
import org.apache.camel.EndpointInject;
import org.apache.camel.Produce;
import org.apache.camel.ProducerTemplate;
import org.apache.camel.component.mock.MockEndpoint;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

/**
 * Created by tmichels on 7/27/15.
 */

@ContextConfiguration(classes = {SalesforceCamelRouteConfig.class})
@RunWith(SpringJUnit4ClassRunner.class)
public class SalesforceCamelIntegrationTest {

    @Autowired
    CamelContext camelContext;

    @EndpointInject(uri = "direct:getBasicInfo")
    ProducerTemplate producer;

    @Test
    public void testCamelContext() throws Exception {
        String body = "Account";
        producer.sendBody(body);
    }
}

OUTPUT:

>>>>>>> Salesforce Basics Info: {"objectDescribe":{"name":"Account","label":"Account","updateable":true,"keyPrefix":"001","custom":false,"urls":{"sobject":"/services/data/v33.0/sobjects/Account","describe":"/services/data/v33.0/sobjects/Account/describe","rowTemplate":"/services/data/v33.0/sobjects/Account/{ID}","approvalLayouts":"/services/data/v33.0/sobjects/Account/describe/approvalLayouts","quickActions":"/services/data/v33.0/sobjects/Account/quickActions","listviews":"/services/data/v33.0/sobjects/Account/listviews","layouts":"/services/data/v33.0/sobjects/Account/describe/layouts","compactLayouts":"/services/data/v33.0/sobjects/Account/describe/compactLayouts"},"searchable":true,"labelPlural":"Accounts","layoutable":true,"activateable":false,"createable":true,"deprecatedAndHidden":false,"deletable":true,"customSetting":false,"feedEnabled":true,"mergeable":true,"queryable":true,"replicateable":true,"retrieveable":true,"undeletable":true,"triggerable":true},"recentItems":[{"attributes":{"type":"Account","url":"/services/data/v33.0/sobjects/Account/001W000000JhUzlIAF"},"Name":"Pope John XXIII Regional High School","Id":"001W000000JhUzlIAF"},{"attributes":{"type":"Account","url":"/services/data/v33.0/sobjects/Account/001W000000JhZFQIA3"},"Name":"A PLAZA DRIVING SCHOOL","Id":"001W000000JhZFQIA3"},{"attributes":{"type":"Account","url":"/services/data/v33.0/sobjects/Account/001W000000JgxxXIAR"},"Name":"Advanced Reproductive Care, Inc. (ARC)","Id":"001W000000JgxxXIAR"},{"attributes":{"type":"Account","url":"/services/data/v33.0/sobjects/Account/001W000000JrwqvIAB"},"Name":"name","Id":"001W000000JrwqvIAB"},{"attributes":{"type":"Account","url":"/services/data/v33.0/sobjects/Account/001W000000JhXSnIAN"},"Name":"Stella Niagara Education Park","Id":"001W000000JhXSnIAN"},{"attributes":{"type":"Account","url":"/services/data/v33.0/sobjects/Account/001W000000Jr1WOIAZ"},"Name":"A J DIANA SONS INC","Id":"001W000000Jr1WOIAZ"},{"attributes":{"type":"Account","url":"/services/data/v33.0/sobjects/Account/001W000000Jr1TIIAZ"},"Name":"A J DIANA SONS COMPANY","Id":"001W000000Jr1TIIAZ"},{"attributes":{"type":"Account","url":"/services/data/v33.0/sobjects/Account/001W000000Jr1WNIAZ"},"Name":"A J DIANA SONS INC","Id":"001W000000Jr1WNIAZ"},{"attributes":{"type":"Account","url":"/services/data/v33.0/sobjects/Account/001W000000JqzmSIAR"},"Name":"A J DIANA SONS INC","Id":"001W000000JqzmSIAR"},{"attributes":{"type":"Account","url":"/services/data/v33.0/sobjects/Account/001W000000Jq8TeIAJ"},"Name":"A J DIANA SONS COMPANY","Id":"001W000000Jq8TeIAJ"},{"attributes":{"type":"Account","url":"/services/data/v33.0/sobjects/Account/001W000000JhZLTIA3"},"Name":"name","Id":"001W000000JhZLTIA3"},{"attributes":{"type":"Account","url":"/services/data/v33.0/sobjects/Account/001W000000Jq8LVIAZ"},"Name":"A PLAZA DRIVING SCHOOL","Id":"001W000000Jq8LVIAZ"},{"attributes":{"type":"Account","url":"/services/data/v33.0/sobjects/Account/001W000000JhZBTIA3"},"Name":"A J DIANA SONS INC","Id":"001W000000JhZBTIA3"},{"attributes":{"type":"Account","url":"/services/data/v33.0/sobjects/Account/001W000000JgxwjIAB"},"Name":"[First]Name [Last]Name","Id":"001W000000JgxwjIAB"},{"attributes":{"type":"Account","url":"/services/data/v33.0/sobjects/Account/001W000000JhUlVIAV"},"Name":"Central Texas Christian School","Id":"001W000000JhUlVIAV"},{"attributes":{"type":"Account","url":"/services/data/v33.0/sobjects/Account/001W000000JhKbtIAF"},"Name":"Sylvan Learning Center - 112","Id":"001W000000JhKbtIAF"}]}

Salesforce Export Database Records to CSV for Batch Upload

Exporting of Database records to csv can be done using:

1. OpenCSV CSVWriter
2. FileWriter

1. OpenCSV CSVWriter


	@Inject
    private Environment environment;

	@Inject @Named("proddataSource") DataSource dataSource;

	private FileWriter writer;
	
	@Override
	public ResultSet getDWRecords(String queryName) {
		try {
			java.sql.PreparedStatement ps = dataSource.getConnection().prepareStatement(environment.getProperty(queryName));
			ps.setMaxRows(10000);
			ResultSet rs = ps.executeQuery();
			return rs;
		} catch (SQLException e) {
			logger.error("CreateCSVDWDumpFileImpl.getDWRecords(): " + e.getMessage());
		}
      return null;
	}

	@Override
	public void createCSVDumpFromQuery(ResultSet resultSet, String[] salesforceColumnNames, String fileName) {
		if (resultSet!=null){
			try {
				CSVWriter writer = new CSVWriter(new FileWriter(fileName), ',', CSVWriter.NO_QUOTE_CHARACTER);
				writer.writeNext(salesforceColumnNames);
				writer.writeAll(resultSet, false);
	            writer.close();
			} catch (IOException e) {
				logger.error("CreateCSVDWDumpFileImpl.createCSVDumpFromQuery(): " + e.getMessage());
			} catch (SQLException e) {
				logger.error("CreateCSVDWDumpFileImpl.createCSVDumpFromQuery(): " + e.getMessage());
			}
		}
	}

2. FileWriter

private FileWriter writer;
public void writeToCSVFileAccount(Collection<SObject> sObjects, String[] salesforceColumnNames, String fileName) {
	try {
		writer = new FileWriter(fileName);
		for (int firstCol = 0; firstCol < salesforceColumnNames.length; firstCol++){
			 writer.append(salesforceColumnNames[firstCol]);
			 if (firstCol < salesforceColumnNames.length-1)
				 writer.append(',');
		}
		writer.append('\n');
		
		for (SObject sAccount : sObjects){
			for (int k = 0; k < salesforceColumnNames.length; k++){
				writer.append(sAccount.getField(salesforceColumnNames[k])!=null ? salesforceColumnNames[k].contains("Date") || salesforceColumnNames[k].contains("date") ?  String.format("%1$tF", sAccount.getField(salesforceColumnNames[k])) : sAccount.getField(salesforceColumnNames[k]).toString() : "");
				if (k < salesforceColumnNames.length-1)
					writer.append(',');
			}
			writer.append('\n');
		}
		
		writer.flush();
		writer.close();
	} catch (IOException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
		}
	}

Salesforce WSC Partner Connection Session Renew when Session Timeout

Implement SessionRenewer

package com.sforce.authentication;

import javax.inject.Inject;
import javax.xml.namespace.QName;


import org.slf4j.Logger;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;

import com.sforce.async.AsyncApiException;
import com.sforce.async.BulkConnection;
import com.sforce.soap.partner.Connector;
import com.sforce.soap.partner.PartnerConnection;
import com.sforce.ws.ConnectionException;
import com.sforce.ws.ConnectorConfig;
import com.sforce.ws.SessionRenewer;

/**
 * @author tmichels
 */
@PropertySource("classpath:salesforcesync.properties")
@Configuration
public class SalesforceAuthenticationConfigImpl implements SalesforceAuthenticationConfig {

	private static final Logger logger = org.slf4j.LoggerFactory.getLogger(SalesforceAuthenticationConfigImpl.class);
	
	@Inject private Environment environment;
		    
	private PartnerConnection partnerConnection = null;
	private BulkConnection bulkConnection = null;
	
	public ConnectorConfig productionConnectionConfig(){
		ConnectorConfig config = new ConnectorConfig();
		config.setUsername("username");
		config.setPassword("passwordtoken");
		config.setCompression(true);
		return config;
	}
	
    @Bean(name="loginToProductionSalesforce")
	public PartnerConnection loginToProductionSalesforce() {
    	try {
    		ConnectorConfig config = productionConnectionConfig();
    		config.setSessionRenewer(new productionSessionRenewer());
        	partnerConnection = Connector.newConnection(config);
		} catch (ConnectionException e) {
			logger.error("SalesforceAuthenticationConfigImpl.loginToProductionSalesforce(): " + e.getMessage());
			e.printStackTrace();
		}
		return partnerConnection;
	}
    
    public class productionSessionRenewer implements SessionRenewer {
		@Override
		public SessionRenewalHeader renewSession(ConnectorConfig config) throws ConnectionException {
			ConnectorConfig conConfig = productionConnectionConfig();
			partnerConnection = Connector.newConnection(conConfig);
            SessionRenewalHeader header = new SessionRenewalHeader();
            header.name = new QName("urn:partner.soap.sforce.com", "SessionHeader");
            header.headerElement = partnerConnection.getSessionHeader();
            return header;
		}
    }
}

Test SessionRenewer

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(loader=AnnotationConfigContextLoader.class, classes={SalesforceAuthenticationConfigImpl.class})
public class SalesforceAuthenticationServiceTest {

	@Inject @Named("loginToProductionSalesforce") PartnerConnection loginToProductionPartner;
	
	@Test
	public void testLoginToProductionSalesforce() {
		assertNotNull(loginToProductionPartner.getConfig().getSessionId());
		try {
			loginToProductionPartner.logout();
                        assertNotNull(loginToProductionPartner.getConfig().getSessionId());
		} catch (ConnectionException e) {
			e.printStackTrace();
		}
	}
}

Salesforce Integration JUnit Testing Using Spring

Spring Configuration to test integration to Salesforce using PartnerConnection, EnterpriseConnection and BulkConnection. Create a properties file called salesforcesync.properties with all the login details

salesforcesync.properties

salesforce.sandbox.username=***your username ***
salesforce.sandbox.password=***your password + security token ***
salesforce.sandbox.url=https://test.salesforce.com/services/Soap/u/29.0
salesforce.sandbox.enterprise.url=https://test.salesforce.com/services/Soap/c/29.0/
salesforce.sandbox.version=29.0

salesforce.production.username=***your username ***
salesforce.production.password=***your password + security token ***
salesforce.production.url=https://login.salesforce.com/services/Soap/u/29.0
salesforce.production.enterprise.url=https://login.salesforce.com/services/Soap/c/29.0
salesforce.production.version=29.0

Salesforce Authentication Spring Configuration

package com.sforce.authentication;

import javax.inject.Inject;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;

import com.sforce.async.AsyncApiException;
import com.sforce.async.BulkConnection;

import com.sforce.soap.partner.Connector;
import com.sforce.soap.partner.PartnerConnection;
import com.sforce.ws.ConnectionException;
import com.sforce.ws.ConnectorConfig;

/**
 * @author tmichels
 */
@PropertySource("classpath:/salesforcesync.properties")
@Configuration
public class SalesforceAuthenticationConfigImpl implements SalesforceAuthenticationConfig {

	@Inject
    private Environment environment;
		    
	private PartnerConnection partnerConnection = null;
	private BulkConnection bulkConnection = null;
	
    @Bean(name="loginToProductionSalesforce")
	public PartnerConnection loginToProductionSalesforce() {
    	try {
    		ConnectorConfig config = new ConnectorConfig();
    		config.setUsername(environment.getProperty("salesforce.production.username"));
    		config.setPassword(environment.getProperty("salesforce.production.password"));
			partnerConnection = Connector.newConnection(config);
		} catch (ConnectionException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return partnerConnection;
	}

	@Bean(name="loginToSandboxSalesforce")
	public PartnerConnection loginToSandboxSalesforce() {
		try {
			ConnectorConfig config = new ConnectorConfig();
			config.setUsername(environment.getProperty("salesforce.sandbox.username"));
			config.setPassword(environment.getProperty("salesforce.sandbox.password"));
			config.setAuthEndpoint(environment.getProperty("salesforce.sandbox.url"));
			partnerConnection = Connector.newConnection(config);
		} catch (ConnectionException ce) {
			ce.printStackTrace();
		}
		return partnerConnection;
	}

	
	@Bean(name="bulkLoginToProductionSalesforce")
	public BulkConnection bulkLoginToProductionSalesforce() {
		try {
			
			ConnectorConfig partnerConfig = new ConnectorConfig();
			partnerConfig.setUsername(environment.getProperty("salesforce.production.username"));
			partnerConfig.setPassword(environment.getProperty("salesforce.production.password"));
			partnerConfig.setAuthEndpoint(environment.getProperty("salesforce.production.url"));
			partnerConnection = Connector.newConnection(partnerConfig);
			
		    ConnectorConfig config = new ConnectorConfig();
		    config.setSessionId(partnerConfig.getSessionId());
		    String soapEndpoint = partnerConfig.getServiceEndpoint();
		    String restEndpoint = soapEndpoint.substring(0, soapEndpoint.indexOf("Soap/"))
		        + "async/" + environment.getProperty("salesforce.sandbox.version");
		    config.setRestEndpoint(restEndpoint);
		    // This should only be false when doing debugging.
		    config.setCompression(true);
		    // Set this to true to see HTTP requests and responses on stdout
		    config.setTraceMessage(false);
		    bulkConnection = new BulkConnection(config);
		} catch (AsyncApiException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ConnectionException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return bulkConnection;
	}

	@Bean(name="bulkLoginToSandboxSalesforce")
	public BulkConnection bulkLoginToSandboxSalesforce() {
		try {
			ConnectorConfig partnerConfig = new ConnectorConfig();
			partnerConfig.setUsername(environment.getProperty("salesforce.sandbox.username"));
			partnerConfig.setPassword(environment.getProperty("salesforce.sandbox.password"));
			partnerConfig.setAuthEndpoint(environment.getProperty("salesforce.sandbox.url"));
			partnerConnection = Connector.newConnection(partnerConfig);
			
		    ConnectorConfig bulkconfig = new ConnectorConfig();
		    bulkconfig.setSessionId(partnerConfig.getSessionId());
		    String soapEndpoint = partnerConfig.getServiceEndpoint();
		    String restEndpoint = soapEndpoint.substring(0, soapEndpoint.indexOf("Soap/"))
		        + "async/" + environment.getProperty("salesforce.sandbox.version");
		     bulkconfig.setRestEndpoint(restEndpoint);
		    // This should only be false when doing debugging.
		    bulkconfig.setCompression(true);
		    // Set this to true to see HTTP requests and responses on stdout
		    bulkconfig.setTraceMessage(false);
		    bulkConnection = new BulkConnection(bulkconfig);
		} catch (AsyncApiException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ConnectionException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return bulkConnection;
	}

	@Bean(name="loginToSalesforceSandboxEnterprise")
	public EnterpriseConnection loginToSandboxSalesforceEnterprise() {
		try {
			ConnectorConfig config = new ConnectorConfig();
			config.setUsername(environment.getProperty("salesforce.sandbox.username"));
			config.setPassword(environment.getProperty("salesforce.sandbox.password"));
			config.setAuthEndpoint(environment.getProperty("salesforce.sandbox.enterprise.url"));
			config.setValidateSchema(true);
			config.setCompression(false);
			config.setConnectionTimeout(360000);
			config.setTraceMessage(true);
			config.setPrettyPrintXml(true);
			enterpriseConnection = new EnterpriseConnection(config);
		} catch (ConnectionException ce) {
			ce.printStackTrace();
		}
		return enterpriseConnection;
	}

	@Bean(name="loginToSalesforceProductionEnterprise")
	public EnterpriseConnection loginToProductionSalesforceEnterprise() {
		try {
			ConnectorConfig config = new ConnectorConfig();
			config.setUsername(environment.getProperty("salesforce.production.username"));
			config.setPassword(environment.getProperty("salesforce.production.password"));
			config.setAuthEndpoint(environment.getProperty("salesforce.production.url"));
			config.setValidateSchema(true);
			config.setCompression(false);
			config.setConnectionTimeout(360000);
			config.setTraceMessage(true);
			config.setPrettyPrintXml(true);
		
			enterpriseConnection = new EnterpriseConnection(config);
		} catch (ConnectionException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return enterpriseConnection;
	}
}

Junit test class to assert login was successful

package com.sforce.authentication;

import static org.junit.Assert.*;

import javax.inject.Inject;
import javax.inject.Named;

import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.support.AnnotationConfigContextLoader;

import com.sforce.async.BulkConnection;
import com.sforce.authentication.SalesforceAuthenticationConfig;
import com.sforce.authentication.SalesforceAuthenticationConfigImpl;

import com.sforce.soap.partner.PartnerConnection;
import com.sforce.ws.ConnectionException;

/**
 * @author tmichels
 */
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(loader=AnnotationConfigContextLoader.class, classes={SalesforceAuthenticationConfigImpl.class})
public class SalesforceAuthenticationServiceTest {

	@Inject @Named("loginToProductionSalesforce") PartnerConnection loginToProductionPartner;
	@Inject @Named("loginToSandboxSalesforce") PartnerConnection loginToSandboxPartner;
	@Inject @Named("bulkLoginToProductionSalesforce") BulkConnection loginToProductionBulkConnection;
	@Inject @Named("bulkLoginToSandboxSalesforce") BulkConnection loginToSandboxBulkConnection;
	@Inject @Named("loginToSalesforceSandboxEnterprise") EnterpriseConnection loginToSalesforceEnterpriseConnection;

	@Test
	public void testLoginToProductionSalesforce() {
		assertNotNull(loginToProductionPartner.getConfig().getSessionId());
		try {
			loginToProductionPartner.logout();
		} catch (ConnectionException e) {
			e.printStackTrace();
		}
	}
	
	@Test
	public void testLoginToSandboxSalesforce(){
		assertNotNull(loginToSandboxPartner.getConfig().getSessionId());
		try {
			loginToSandboxPartner.logout();
		} catch (ConnectionException e) {
			e.printStackTrace();
		}
	}
	
	@Test
	public void testBulkLoginToProductionSalesforce(){
		assertNotNull(loginToProductionBulkConnection.getConfig().getSessionId());
	}
	
	@Test
	public void testBulkLoginToSandboxSalesforce(){
		assertNotNull(loginToSandboxBulkConnection.getConfig().getSessionId());
	}
	
	@Test
	public void testLoginToSalesforceEnterprise(){
		assertNotNull(loginToSalesforceEnterpriseConnection.getConfig().getSessionId());
	}
}