Thursday, October 10, 2019

External Data Service

As mentioned in my previous blog : https://chintanblog.blogspot.com/2017/05/odataheroku-with-salesforce-integrate.html  , if we can expose the external data as OData 2.0 or 4.0, we can directly consume them in salesforce as External Objects. The second option would be to directly consume those web service using External Data Service and consume them as external objects.



As you can see above, either you can put thin layer against external web service to do protocol conversion to support Odata (as mentioned in https://chintanblog.blogspot.com/2017/05/odataheroku-with-salesforce-integrate.html) or write the plugin in Apex.

Here we will discuss how to write External Data Service in Apex.

1) I created a sample external web service to just for the demo - It is HR service, which return list of employees, and also employees by name, account, etc..

https://github.com/c-shah/basic-authentication






2) As next step, we need to write

ExternalDataSourceProvider -> ExternalDataSourceConnection -> ExternalDataService

a) ExternalDataSourceProvider

this class basically extends DataSource.Provider, and provides what capability are supported from both authentication and database support (e.g. query, update)



/**
 * Created by chint on 10/4/2019.
 */

global without sharing class ExternalDataSourceProvider extends DataSource.Provider {

    override global List<DataSource.AuthenticationCapability> getAuthenticationCapabilities() {
        System.debug(' ExternalDataSourceProvider.getAuthenticationCapabilities ');
        List<DataSource.AuthenticationCapability> capabilities =  new List<DataSource.AuthenticationCapability> {
                DataSource.AuthenticationCapability.ANONYMOUS
        };
        System.debug(' ExternalDataSourceProvider.getAuthenticationCapabilities ' + JSON.serialize(capabilities) );
        return capabilities;
    }

    override global List<DataSource.Capability> getCapabilities() {
        System.debug(' ExternalDataSourceProvider.getCapabilities ');
        List<DataSource.Capability> capabilities = new List<DataSource.Capability> {
            DataSource.Capability.ROW_QUERY
        };
        System.debug(' ExternalDataSourceProvider.getCapabilities ' + JSON.serialize(capabilities) );
        return capabilities;
    }

    override global DataSource.Connection getConnection(DataSource.ConnectionParams connectionParams) {
        System.debug(' ExternalDataSourceProvider.getConnection connectionParams: ' + connectionParams);
        DataSource.Connection connection = new ExternalDataSourceConnection(connectionParams);
        System.debug(' ExternalDataSourceProvider.getConnection connection: ' + connection);
        return connection;
    }

}


b) ExternalDataSourceConnection

This class extends DataSource.Connection, and responsible for providing table structures and as well as data results which will be consumed by query associated with External Objects



/**
 * Created by chint on 10/4/2019.
 */

global without sharing class ExternalDataSourceConnection extends DataSource.Connection {

    private DataSource.ConnectionParams connectionInfo ;

    global ExternalDataSourceConnection(DataSource.ConnectionParams connectionInfo) {
        System.debug(' ExternalDataSourceConnection.ExternalDataSourceConnection connectionInfo: ' + JSON.serialize(connectionInfo));
        this.connectionInfo = connectionInfo;
    }

    override global List<DataSource.Table> sync() {
        System.debug(' ExternalDataSourceConnection.sync ');
        List<DataSource.Table> tables = ExternalDataService.getInstance().getTables();
        System.debug(' ExternalDataSourceConnection.sync tables ' + JSON.serialize(tables) );
        return tables;
    }

    override global DataSource.TableResult query(DataSource.QueryContext context) {
        try {
            printContent(context);
            DataSource.TableResult tableResult = DataSource.TableResult.get(context, ExternalDataService.getInstance().getData(context) );
            System.debug(' ExternalDataSourceConnection.query tableResult ' + JSON.serialize(tableResult));
            return tableResult;
        } catch (Exception currentException) {
            String message = currentException.getMessage() + currentException.getStackTraceString() ;
            System.debug(' ExternalDataSourceConnection.query exception : ' + message );
            throw new DataSource.DataSourceException(message);
        }
    }

    public static void printContent(DataSource.QueryContext context) {
        System.debug(' ExternalDataSourceConnection.printContent queryMoreToken ' + context.queryMoreToken + ' tableSelected ' + context.tableSelection.tableSelected );
        DataSource.Filter filter = context.tableSelection.filter;
        List<DataSource.Order> orders = context.tableSelection.order;
        List<DataSource.ColumnSelection> columnsSelected = context.tableSelection.columnsSelected;
        if( filter != null ) {
            System.debug('ExternalDataSourceConnection.printContent filter columnName ' + filter.columnName + ' columnValue ' + filter.columnValue + ' subfilters ' + filter.subfilters + ' tableName ' + filter.tableName + ' type ' + filter.type );
        }
        if( orders != null ) {
            for(DataSource.Order order : orders ) {
                System.debug('ExternalDataSourceConnection.printContent order columnName ' + order.columnName  + ' tableName ' + order.tableName + ' direction ' + order.direction );
            }
        }
        if( columnsSelected != null ) {
            for(DataSource.ColumnSelection columnSelected : columnsSelected ) {
                System.debug('ExternalDataSourceConnection.printContent columnSelected columnName ' + columnSelected.columnName  + ' tableName ' + columnSelected.tableName + ' aggregation ' + columnSelected.aggregation );
            }
        }
    }
}



3) ExternalDataService, which takes care of calling web service and returning the data needed for ExternalDataSourceConnection.


/**
 * Created by chint on 10/4/2019.
 */

public without sharing class ExternalDataService {

    private static ExternalDataService instance;

    private ExternalDataService() {
        System.debug(' ExternalDataService.ExternalDataService ');
    }

    public static ExternalDataService getInstance() {
        System.debug(' ExternalDataService.getInstance ');
        if( instance == null ) {
            instance = new ExternalDataService();
        }
        return instance;
    }

    public List<DataSource.Table> getTables() {
        System.debug(' ExternalDataService.getTables ');
        List<DataSource.Table> tables = new List<DataSource.Table> {
                getEmployeeTable(),
                getAddressTable() };
        System.debug(' ExternalDataService.getTables tables ' + JSON.serialize(tables) );
        return tables;
    }

    public List<Map<String, Object>> getData(DataSource.QueryContext context) {
        System.debug(' ExternalDataService.getData context ' + context );
        return getEmployeeData(context);
    }

    private DataSource.Table getEmployeeTable() {
        List<DataSource.Column> columns;
        columns = new List<DataSource.Column>();
        columns.add(DataSource.Column.text('ExternalId', 255));
        columns.add(DataSource.Column.text('Name', 255));
        columns.add(DataSource.Column.url('DisplayUrl'));
        columns.add(DataSource.Column.indirectLookup('EmployeeAccountKey', 'Account', 'Account_Key__c'));
        return DataSource.Table.get('Employee', 'ExternalId', columns);
    }

    private List<Map<String, Object>> getDummyData() {
        Map<String,Object> row1 = new Map<String,Object> {
                'ExternalId' => 'Emp1',
                'Name' => 'Chintan Shah',
                'EmployeeAccountKey' => 'ACN1'
        };
        Map<String,Object> row2 = new Map<String,Object> {
                'ExternalId' => 'Emp2',
                'Name' => 'Mark Twain',
                'EmployeeAccountKey' => 'ACN1'
        };
        Map<String,Object> row3 = new Map<String,Object> {
                'ExternalId' => 'Emp3',
                'Name' => 'John Doe',
                'EmployeeAccountKey' => 'ACN2'
        };
        List<Map<String,Object>> dataRows = new List<Map<String,Object>> { row1, row2, row3 };
        return dataRows;
    }

    private List<Map<String, Object>> getEmployeeData(DataSource.QueryContext context) {
        if( context.tableSelection != null && context.tableSelection.tableSelected == 'Employee' ) {
            DataSource.Filter filter = context.tableSelection.filter;
            String url = '/hr/employees';
            if( filter != null ) {
                url = '/hr/employee/' + filter.columnName + '/' + filter.columnValue;
            }
            List<Map<String,Object>> response = httpGetCallout('HerokuBasicAuth', url);
            return response;
        }
        return new List<Map<String,Object>>();
    }

    public static List<Map<String,Object>> httpGetCallout(String namedCredentials, String url) {
        List<Map<String,Object>> returnEmployees = new List<Map<String,Object>>();
        Http http = new Http();
        HttpRequest request = new HttpRequest();
        request.setEndpoint('callout:' + namedCredentials + url );
        request.setMethod('GET');
        HttpResponse response = http.send(request);
        if (response.getStatusCode() == 200) {
            System.debug(' response.getBody() ' + response.getBody() );
            List<Object> employees = (List<Object>) JSON.deserializeUntyped( response.getBody() );
            for(Object employee : employees ) {
                Map<String, Object> currentEmployee = ( Map<String, Object> ) ( employee );
                returnEmployees.add( currentEmployee );
            }
        }
        system.debug( ' ExternalDataService.httpGetCallout returnEmployees ' + returnEmployees  );
        return returnEmployees;
    }

    private DataSource.Table getAddressTable() {
        DataSource.Table table = new DataSource.Table();
        List<DataSource.Column> columns;
        columns = new List<DataSource.Column>();
        columns.add(DataSource.Column.text('ExternalId', 255));
        columns.add(DataSource.Column.text('Street', 255));
        columns.add(DataSource.Column.text('ZipCode', 255));
        columns.add(DataSource.Column.url('DisplayUrl'));
        columns.add(DataSource.Column.indirectLookup('AddressAccountKey', 'Account', 'Account_Key__c'));
        return DataSource.Table.get('Address', 'ExternalId', columns);
    }

    private List<Map<String, Object>> getAddressData(DataSource.QueryContext context) {
        List<Map<String,Object>> dataRows = new List<Map<String,Object>>();
        return dataRows;
    }


}

This basically :
  • understand the context (name of the table, query criteria
  • calls the webservice 
  • returns the data in List> format. 

We can see external Objects now:







Once it is done, it is ready to be tested on Account page layout, due to indirect lookup relationship, Employee external object would be available in Account Page layout.






This way we can consume external service as external object without external Odata layer.


Source Code : 

https://github.com/springsoa/springsoa-salesforce/tree/master/classes
https://github.com/c-shah/basic-authentication

Tuesday, October 8, 2019

Lightning Component Web Service Integration

When calling web service from lightning component, we can either call it from apex using @AuraEnabled method, or we can call from lightning component client side controller. This is specially important when you want to avoid governor limits on Apex side, e.g. uploading file bigger than 7MB or calling web service which could potentially take more than 120s. We can directly use browser to call the web service.

Calling web service from client side controller (browser integration)



1) We need to make sure that web service we call, allows cross origin and it is https enabled

We wrote simple web service in Heroku
https://basic-authentication-ws.herokuapp.com/echo




2) We need to make sure the web service URL is added to CSP trusted site for locker service

https://basic-authentication-ws.herokuapp.com




3) Now, lightning component (client side controller)

We can make call to web service


({
    doInit: function (c, e, h) {
    },
    postData: function (c, e, h) {
        c.set('v.isProcessing', true);
        var xhr = new XMLHttpRequest();
        var url = 'https://basic-authentication-ws.herokuapp.com/echo';
        xhr.open('POST', url, true);
        xhr.onload = function () {
            if (this.status === 200) {
                c.set('v.isProcessing', false);
                c.set('v.response', this.response);
            }
        };

        xhr.setRequestHeader('Content-Type', 'application/json;charset=UTF-8');
        xhr.send(JSON.stringify({message: c.get('v.message')}));
    }
});


Source Code

Heroku
https://github.com/c-shah/basic-authentication

Salesforce
https://github.com/springsoa/springsoa-salesforce/tree/master/aura/webserviceTest

Monday, December 11, 2017

SOSL - platform encryption

Salesforce platform encryption encrypts the data at rest, hence we can not run SOQL against it. SOSL is good work around but have its own limitation. (side note: SOSL also has limitation of 2000 rows returned)

Enable Platform Encryption
Encrypt Fields
Create Acount
SOQL
SOSL


Enable Platform Encryption 

a) create permission set




b) assign system permission for this permission set




c) Assign permission set to current user





Encrypt Fields

Fields to encrypt (Setup -> Platform Encryption)



Create Account

Created account with name : My Account



SOQL

If we run SOQL against account, now it would return error.

 select id, name, description from Account where name like '%My%'  

 [object Object]: description from Account where name like '%My%' ^ ERROR at Row:1:Column:49 encrypted field 'Account.name' cannot be filtered in a query call  



SOSL

If we run below SOSL, we can access our account:

 FIND {My} IN ALL FIELDS RETURNING Account(Name, Description, AnnualRevenue)  
 FIND {M*} IN ALL FIELDS RETURNING Account(Name, Description, AnnualRevenue)  






However issues comes when we want to narrow down the result. If we apply the where clause to the SOSL, it breaks. I believe it is because behind the scene SOSL still runs as SOQL.

 FIND {M*} IN ALL FIELDS RETURNING Account(Name, Description, AnnualRevenue WHERE Name LIKE 'M%')  

Error Message

 Description, AnnualRevenue WHERE Name LIKE 'M%')  
                                                                         ^  
 ERROR at Row:1:Column:82  
 encrypted field 'Account.Name' cannot be filtered in a query call     


So, we need to be careful when we write SOSL or SOQL where clause (especially in managed package) given that fields could be encrypted.


Saturday, November 11, 2017

Salesforce Canvas : what and how?

When we are integrating third party UI application, there are quite a few options

  • Including iframe inside Visualforce or Lightning component
    • mostly one way integration (salesforce to UI application)
    • security issues
    • sizing problems
  • Canvas
    • lightning and classic
    • seamless and two way integration
  • Lightning container component (Winter'18 - for lightning)
    • only for lightning
Canvas by far the most feature rich and seamless integration between salesforce and third party UI application, especially we have two way interaction. E.g. salesforce passing data to third party application and UI application updating/creating data back in salesforce.
How to configure it

  • Create Connected application

Step 1) Connected App -> Allow users to install canvas personal apps

Step 2) Create New App






Step 3) Configure Canvas App Settings  (Note: check Publisher and Create Actions, if we plan to publish canvas app there)



Step 4)



Step 5) Grab the consumer secret and key



Step 6) Assign canvas app the users or profiles







Step 7) Canvas app viewer






  • Sample Third Party application
    • From Canvas App viewer, we can create canned "heroku quick start" app, however I decided to use create my own so that I can test out all the features in controller environment
    • Create heroku application, and make sure to sign the request for the URL provided in canvas salesforce app



Main Features

Security
  • Salesforce sends signed request to third party application, and it can be decrypted using consumer key. Hence the request is secure.
  • Also when json request payload is decrypted, we get session id and all the information of the page context  






Two way event
- Events can be raised from Visual Force and can be sent to Third Party App, and Third party app can send event back to Salesforce






Resize
- Third party App can use resize API to resize the canvas size in Salesforce. When we put canvas in visualforce and then in layout, we are restricted by iFrame size and height, but if canvas is put in directly in page layout we can have much better control over the size.







Api calls (e.g. chatter)

Third party application can use OAuth token provided in JSON request and make any API call. Below is example of chatter post




Where canvas can be used 
Once it is configured correctly, it can be used at many places:


Canvas App Previewer : this is just for testing your canvas app



Page layout via Visual Force
Canvas can be added in visual force page, however if we go that route, when we add the page to layout, we will be restricted by iframe size.



VisualForce code:




Page Layout Directly
This is very advantageous as we can resize and don't have to use iframe




Lightning Component
We can add canvas in lightning component







Chatter / Publish Action
We can also put canvas chatter or publisher action as shown below





Source Code

Heroku code 
https://github.com/c-shah/canvasly

Salesforce code
https://github.com/c-shah/sf.canvasly

Thursday, October 19, 2017

Community User Test Data

Always find a hassle to create community user for test data, so just thought putting it out here: 

Normal user creation:

User communityUser = new User(
 ProfileId = [SELECT Id FROM Profile WHERE Name = 'Interconnection Community User Plus User'].Id,
 FirstName = 'first',
 LastName = 'last',
 Email = 'test.test@test.com',
 Username = 'test.' + System.currentTimeMillis() + '@test.com',
 Title = 'Title',
 Alias = 'alias',
 TimeZoneSidKey = 'America/Los_Angeles',
 EmailEncodingKey = 'UTF-8',
 LanguageLocaleKey = 'en_US',
 LocaleSidKey = 'en_US'
);


But we get below errors:

System.DmlException: Insert failed. First exception on row 0; first error: INVALID_CROSS_REFERENCE_KEY, Cannot create a portal user without contact: [ContactId]

System.DmlException: Insert failed. First exception on row 0; first error: UNKNOWN_EXCEPTION, portal account owner must have a role: []

System.DmlException: Insert failed. First exception on row 0; first error: MIXED_DML_OPERATION, DML operation on setup object is not permitted after you have updated a non-setup object (or vice versa): Account, original object: User: []


To solve it : use below approach : 

1) Create Portal Owner

   private static User createPortalAccountOwner() {  
     UserRole portalRole = new UserRole(DeveloperName = 'MyCustomRole', Name = 'My Role', PortalType='None' );  
     insert portalRole;  
     System.debug('portalRole is ' + portalRole);  
     Profile sysAdminProfile = [Select Id from Profile where name = 'System Administrator'];  
     User portalAccountOwner = new User(  
         UserRoleId = portalRole.Id,  
         ProfileId = sysAdminProfile.Id,  
         Username = 'portalOwner' + System.currentTimeMillis() + '@test.com',  
         Alias = 'Alias',  
         Email='portal.owner@test.com',  
         EmailEncodingKey='UTF-8',  
         Firstname='Portal',  
         Lastname='Owner',  
         LanguageLocaleKey='en_US',  
         LocaleSidKey='en_US',  
         TimeZoneSidKey = 'America/Los_Angeles'  
     );  
     Database.insert(portalAccountOwner);  
     return portalAccountOwner;  
   }  

2) Create Community User

   private static void createCommunityUser(User portalAccountOwner) {  
     System.runAs ( portalAccountOwner ) {  
       //Create account  
       Account portalAccount = new Account(  
           Name = 'portalAccount',  
           OwnerId = portalAccountOwner.Id  
       );  
       Database.insert(portalAccount);  
       //Create contact  
       Contact portalContact = new Contact(  
           FirstName = 'portalContactFirst',  
           Lastname = 'portalContactLast',  
           AccountId = portalAccount.Id,  
           Email = 'portalContact' + System.currentTimeMillis() + '@test.com'  
       );  
       Database.insert(portalContact);  
       User communityUser = new User(  
           ProfileId = [SELECT Id FROM Profile WHERE Name = 'Interconnection Community User Plus User'].Id,  
           FirstName = 'CommunityUserFirst',  
           LastName = 'CommunityUserLast',  
           Email = 'community.user@test.com',  
           Username = 'community.user.' + System.currentTimeMillis() + '@test.com',  
           Title = 'Title',  
           Alias = 'Alias',  
           TimeZoneSidKey = 'America/Los_Angeles',  
           EmailEncodingKey = 'UTF-8',  
           LanguageLocaleKey = 'en_US',  
           LocaleSidKey = 'en_US',  
           ContactId = portalContact.id  
       );  
       Database.insert(communityUser);  
     }  
   }  

3) We can use below code in testSetup or test method.

 User portalAccountOwner = createPortalAccountOwner();  
 createCommunityUser(portalAccountOwner);  

Wednesday, October 11, 2017

Salesforce Streaming API Summary

Was just working on streaming API and just putting thoughts together with different variations of streaming API :


  1. Push Topic
  2. Generic Topic
  3. Platform Event 

Even though underneath the cover, they all use same technology stack, they provide very different features.


Push TopicGeneric TopicPlatform Events
OverviewPush topic is used for SOQL based subscriptionGeneric Topic is used to subscribe and publish arbitrary events
Platform Events is used for structured publish and subscribe

There is a lot more native support for both publish and subscribe

Full control over structure (payload) of the event

Replay : 

When client disconnect and reconnect again, they can replay from last 24 hours with id where they left from
special ids : -1 from the beginning, -2 : all new events

Supported (version 36.0 +)Supported (version 36.0 +)Supported (version 36.0 +)
Create (Setup)
1) Using Apex Insert Statements

or 

2) workbench 
- it defaults all the param except SOQL query

Using Streaming Channel Tab

or

2) Workbench
Create __e object
Support for Trigger SubscriptionNoNoYes
How to Publishupon SOQLUsing Rest API
EventBus.publish;

API : Post like sobject /services/data/v41.0/sobjects/Low_Ink__e/ 

Process Builder

Flow
How to Subscribe
workbench (36.0) (later are causing problems)

using Java (cometd lib)

Using Javascript (cometd lib)
workbench

using Java (cometd lib)

Using Javascript (cometd lib)
using Java (cometd)

Using Javascript (cometd)

Using Visualforce (cometd)

Process Flow

Flow

Trigger

Workbench
Channel Name

This is useful when we subscribe using cometd library
/topic/<>

e.g.
/topic/AccountUpdatePushTopic
/u/<>

e.g.
/u/GenericUpdateTopic
/event/<>

e.g.
/event/UpdateObjectEvent__e


Push Topic


Push Topic Setup


Workbench
we can setup a push topic using workbench, but it doesn't allow granular control over topic configuration.



APEX

  • NotifyForFields can be Referenced (part of query - default), Where (in where condition), All (all changes)
  • Once topic is inserted, we can use PushTopic object to make any update
 PushTopic pushTopic = new PushTopic();  
 pushTopic.Name = 'AccountUpdatePushTopic';  
 pushTopic.Query = 'SELECT Id, Name, AccountNumber from Account';  
 pushTopic.ApiVersion = 40.0;  
 pushTopic.NotifyForOperationCreate = true;  
 pushTopic.NotifyForOperationUpdate = true;  
 pushTopic.NotifyForOperationUndelete = true;  
 pushTopic.NotifyForOperationDelete = true;  
 pushTopic.NotifyForFields = 'Referenced';  
 insert pushTopic;  
   



Push Topic Publish

There is no API support for publish. Any change in the data based on condition (e.g. Notify Operation and fields configured) would fire the event on the topic.


Push Topic Subscribe

Workbench

  • This is quick way to test and also record the channel, as we will need it later for cometd library

Java/JavaScript
covered later


Generic Topic



Generic Topic Setup

  • We must setup generic toipc using salesforce UI
  • There is no apex or workbench support to create generic topic



Generic Topic Publish

Rest API (Workbench)

URL : /services/data/v/sobjects/StreamingChannel//push

We can find streaming channel id using query (SELECT Name, ID FROM StreamingChannel)

e.g. /services/data/v40.0/sobjects/StreamingChannel/0M61I000000TN1FSAW/push

payload : 

{
  "pushEvents": [
      {
          "payload": "Broadcast message to all subscribers",
          "userIds": []
      }
   ]

}



Generic Topic Subscribe

WorkBench


Java/JavaScript:
Covered Later


Platform Events


Platform Event Setup


  • Essentially created two attributes (ObjectName__c and RecordId__c) so that we can publish the event having those attributes


Platform Event Publish

Apex


  • Publish event call doesn't fail, hence we have to go through the results
  • Also publish call doesn't participate in transaction, meaning if transaction has to fail, event will still publish


 List events = new List();  
 UpdateObjectEvent__e event = new UpdateObjectEvent__e(objectName__c='Account', recordId__c='1234');  
 events.add( event );  
 List results = EventBus.publish(events);  
 if( results != null && results.size() > 0 ) {  
   for (Database.SaveResult sr : results) {  
     if (sr.isSuccess()) {  
       System.debug('Successfully published event. ' + results.size() );  
     } else {  
       for(Database.Error err : sr.getErrors()) {  
         System.debug('Error returned: ' + err.getStatusCode() + ' - ' + err.getMessage());  
       }  
     }  
   }  
 } else {  
   System.debug(' Noting is published. ');  
 }  
   


Rest API

Endpoint  : /services/data/v40.0/sobjects/UpdateObjectEvent__e/
Payload    : { "RecordId__c" : "123455634343", "ObjectName__c" : "Account" }



Soap API
Similar to rest api, it is just call to insert into sObject

Process Builder 
not covered, but straightforward

Visual Flow 
not covered, but straightforward


Platform Event Subscribe

Trigger

  • only after insert is supported

 trigger UpdateObjectEventTrigger on UpdateObjectEvent__e (after insert) {  
   System.debug(' UpdateObjectEventTrigger ' );  
     
   for (UpdateObjectEvent__e event : Trigger.New) {  
     System.debug(' : ' + event.RecordId__c + ' ' + event.ObjectName__c );  
   }  
     
 }  

Process Builder 
not covered, but straightforward

Visual Flow 
not covered, but straightforward

Java/JavaScript 
Covered later


Platform Event Debug

  • debug statements in trigger doesn't show up in debug logs, we need to enable them using below







Generic Java Subscriber Client



We need to download and build the EMP connector from salesforce 
  • download : https://github.com/forcedotcom/EMP-Connector
  • unzip, and run "mvn clean install"
  • Use emp-connector-0.0.1-SNAPSHOT-phat.jar in the new project that we are going to create
  • Create a new project (java 1.8) and use below code. 
  • Please note that channel name can be changed as per which topic we are subscribing



 package com.spring.client;  
   
 import com.salesforce.emp.connector.BayeuxParameters;  
 import com.salesforce.emp.connector.EmpConnector;  
 import com.salesforce.emp.connector.TopicSubscription;  
   
 import java.util.Map;  
 import java.util.concurrent.TimeUnit;  
 import java.util.function.Consumer;  
   
 import static com.salesforce.emp.connector.LoginHelper.login;  
   
 public class StreamingClient {  
   
   public static void main(String args[]) throws Exception {  
     long replayFrom = EmpConnector.REPLAY_FROM_EARLIEST;  
     BayeuxParameters params = login("streaming@springsoa.com", "Welcome1");  
     EmpConnector connector = new EmpConnector(params);  
     Consumer<Map<String, Object>> consumer = event -> System.out.println(String.format("Received:\n%s", event));  
     connector.start().get(5, TimeUnit.SECONDS);  
     TopicSubscription subscription = connector.subscribe("/event/UpdateObjectEvent__e", replayFrom, consumer ).get(5, TimeUnit.SECONDS);  
     System.out.println(String.format("Subscribed: %s", subscription));  
     //subscription.cancel();  
     //connector.stop();  
   }  
 }  
   



Generic Javascript Subscriber Client


We can use cometD library to listen to the event, I had to write customer wrapper (cometdCustom.js) to greatly simply the visualforce page. We can also use this in independent HTML page,as long as we can get oauth session id.






Source Code

Java code                       :   https://github.com/c-shah/streaming-java-client    
Salesforce and JS code  :   https://github.com/c-shah/salesforce-streaming

Refresh VisualForce Page with Platform Events

Problem Statement 

A visual force page is embedded inside the standard page layout to display additional information from third party application as below.

A few use cases :
- Let's say there is change inside third party application content and we want to refresh the entire page
- If third party application is making change to sales force data on this page using API and we need to refresh the page



A few failed solutions

1) If third party application is rendered inside the iframe, we can not access the parent salesforce page.

E.g. if we try one of the below we get the error message, as salesforce will prevent third party iframe to access the parent page.

 window.parent.location.href = URL  
 parent.location.href=parent.location.href  
 parent.location.reload();  
 window.parent.location.href = window.parent.location.href  

error message:

 Unsafe JavaScript attempt to initiate navigation for frame with URL 'https://c.na59.visual.force.com/servlet/servlet.Integration?lid=066f4000001yE8F&ic=1&...'.   
 The frame attempting navigation is neither same-origin with the target, nor is it the target's parent or opener  


2) Polling : in parent visualforce page we can constantly do polling on server side to listen for changes and refresh the VF page as needed. Polling in general is not good idea and not very scalable.




Platform Event to Rescue

Event based solution comes quite handy here, where we can publish the event on server side and visualforce page can listen to event and on right criteria, it can alert the end user on change or refresh the page so that we can see the fresh data.

Platform event is glorified version of streaming api, and we can get more details on a separate post here.



Solution:

1. Create platform event
2. Upon change, publish event using rest api or on Apex
3. On visualforce page, listen to those event and refresh the page




Create platform event 

  • Essentially created two attributes (ObjectName__c and RecordId__c) so that we can publish the event having those attributes





Publish event using rest api or on Apex


1) Publish via Apex
  • Publish event call doesn't fail, hence we have to go through the results
  • Also publish call doesn't participate in transaction, meaning if transaction has to fail, event will still publish

 List<UpdateObjectEvent__e> events = new List<UpdateObjectEvent__e>();  
 UpdateObjectEvent__e event = new UpdateObjectEvent__e(objectName__c='Account', recordId__c='1234');  
 events.add( event );  
 List<Database.SaveResult> results = EventBus.publish(events);  
 if( results != null && results.size() > 0 ) {  
   for (Database.SaveResult sr : results) {  
     if (sr.isSuccess()) {  
       System.debug('Successfully published event. ' + results.size() );  
     } else {  
       for(Database.Error err : sr.getErrors()) {  
         System.debug('Error returned: ' + err.getStatusCode() + ' - ' + err.getMessage());  
       }  
     }  
   }  
 } else {  
   System.debug(' Noting is published. ');  
 }  
   

2) Publish via Rest API

Endpoint  : /services/data/v40.0/sobjects/UpdateObjectEvent__e/
Payload    : { "RecordId__c" : "123455634343", "ObjectName__c" : "Account" }





Listen to event on Visualforce Page 

We can use cometD library to listen to the event, I had to write customer wrapper (cometdCustom.js) to greatly simply the visualforce page. 




Source code 
It can be found at : https://github.com/c-shah/salesforce-streaming