From 192e640eef3ebce509e5ef18c45aa43b07713781 Mon Sep 17 00:00:00 2001 From: Tom Gersic Date: Mon, 21 Nov 2011 14:50:08 -0600 Subject: [PATCH 01/60] Adding Utility function (getChatterFile) to query the Chatter API and download a file /** * Utility function to query the Chatter API and download a file * Note, raw XMLHttpRequest because JQuery mangles the arraybuffer * This should work on any browser that supports XMLHttpRequest 2 because arraybuffer is required. * For mobile, that means iOS >= 5 and Android >= Honeycomb * @author Tom Gersic * @param path resource path relative to /services/data * @param mimetype of the file * @param callback function to which response will be passed * @param [error=null] function to which request will be passed in case of error * @param rety true if we've already tried refresh token flow once **/ Signed-off-by: Tom Gersic --- forcetk.js | 60 ++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 60 insertions(+) diff --git a/forcetk.js b/forcetk.js index f58de58..c6a925f 100644 --- a/forcetk.js +++ b/forcetk.js @@ -181,6 +181,66 @@ if (forcetk.Client === undefined) { }); } + /** + * Utility function to query the Chatter API and download a file + * Note, raw XMLHttpRequest because JQuery mangles the arraybuffer + * This should work on any browser that supports XMLHttpRequest 2 because arraybuffer is required. + * For mobile, that means iOS >= 5 and Android >= Honeycomb + * @author Tom Gersic + * @param path resource path relative to /services/data + * @param mimetype of the file + * @param callback function to which response will be passed + * @param [error=null] function to which request will be passed in case of error + * @param rety true if we've already tried refresh token flow once + **/ + forcetk.Client.prototype.getChatterFile = function(path,mimeType,callback,error,retry) { + var that = this; + + var url = this.instanceUrl + path; + + var request = new XMLHttpRequest(); + + + request.open("GET", url, true); + request.responseType = "arraybuffer"; + + request.setRequestHeader(that.authzHeader, "OAuth " + that.sessionId); + request.setRequestHeader('X-User-Agent', 'salesforce-toolkit-rest-javascript/' + that.apiVersion); + + request.onreadystatechange = function() { + // continue if the process is completed + if (request.readyState == 4) { + // continue only if HTTP status is "OK" + if (request.status == 200) { + try { + // retrieve the response + callback(request.response); + } + catch(e) { + // display error message + alert("Error reading the response: " + e.toString()); + } + } + //refresh token in 401 + else if(request.status == 401 && !retry) { + that.refreshAccessToken(function(oauthResponse) { + that.setSessionToken(oauthResponse.access_token, null,oauthResponse.instance_url); + that.getChatterFile(path, mimeType, callback, error, true); + }, + error); + } + else { + // display status message + error(request,request.statusText,request.response); + } + } + + } + + request.send(); + + } + /* * Lists summary information about each Salesforce.com version currently * available, including the version, label, and a link to each version's From a2a56df028b0ee563db626651bc1dc7a78e05c47 Mon Sep 17 00:00:00 2001 From: Kazuki Nakajima Date: Fri, 20 Jan 2012 16:02:56 +0900 Subject: [PATCH 02/60] Update forcetk.js --- forcetk.js | 44 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 44 insertions(+) diff --git a/forcetk.js b/forcetk.js index f58de58..c1bce87 100644 --- a/forcetk.js +++ b/forcetk.js @@ -181,6 +181,50 @@ if (forcetk.Client === undefined) { }); } + /* + * Low level utility function to call the Salesforce endpoint specific for Apex REST API. + * @param path resource path relative to /services/apexrest + * @param callback function to which response will be passed + * @param [error=null] function to which jqXHR will be passed in case of error + * @param [method="GET"] HTTP method for call + * @param [payload=null] payload for POST/PATCH etc + */ + forcetk.Client.prototype.apexrest = function(path, callback, error, method, payload, retry) { + var that = this; + var url = this.instanceUrl + '/services/apexrest' + path; + + $j.ajax({ + type: method || "GET", + async: this.asyncAjax, + url: (this.proxyUrl !== null) ? this.proxyUrl: url, + contentType: 'application/json', + cache: false, + processData: false, + data: payload, + success: callback, + error: (!this.refreshToken || retry ) ? error : function(jqXHR, textStatus, errorThrown) { + if (jqXHR.status === 401) { + that.refreshAccessToken(function(oauthResponse) { + that.setSessionToken(oauthResponse.access_token, null, + oauthResponse.instance_url); + that.ajax(path, callback, error, method, payload, true); + }, + error); + } else { + error(jqXHR, textStatus, errorThrown); + } + }, + dataType: "json", + beforeSend: function(xhr) { + if (that.proxyUrl !== null) { + xhr.setRequestHeader('SalesforceProxy-Endpoint', url); + } + xhr.setRequestHeader(that.authzHeader, "OAuth " + that.sessionId); + xhr.setRequestHeader('X-User-Agent', 'salesforce-toolkit-rest-javascript/' + that.apiVersion); + } + }); + } + /* * Lists summary information about each Salesforce.com version currently * available, including the version, label, and a link to each version's From fcb372b78e1efedc1132a4cee11a3f6a0c8cf47d Mon Sep 17 00:00:00 2001 From: Kazuki Nakajima Date: Sat, 28 Jan 2012 17:53:58 +0900 Subject: [PATCH 03/60] Update proxy.php --- proxy.php | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/proxy.php b/proxy.php index cca675e..fdc47ff 100644 --- a/proxy.php +++ b/proxy.php @@ -169,7 +169,9 @@ // Change these configuration options if needed, see above descriptions for info. $enable_jsonp = false; $enable_native = true; -$valid_url_regex = '/https:\/\/.*salesforce.com/'; +$valid_forcecom_url_regex = '/https:\/\/.*.salesforce.com/'; +$valid_databasecom_url_regex = '/https:\/\/.*database.com/'; + $url_query_param = null; // 'url' $url_header = 'HTTP_SALESFORCEPROXY_ENDPOINT'; @@ -201,7 +203,7 @@ $status['http_code'] = 400; $status['status_text'] = 'Bad Request'; -} else if ( !preg_match( $valid_url_regex, $url ) ) { +} else if ( !preg_match( $valid_forcecom_url_regex, $url ) && !preg_match( $valid_databasecom_url_regex, $url )) { // Passed url doesn't match $valid_url_regex. $contents = 'ERROR: invalid url'; From a3180ec0994b5a74514b4f4d5a19491bac838d1f Mon Sep 17 00:00:00 2001 From: Ron Hess Date: Tue, 6 Mar 2012 11:25:18 -0800 Subject: [PATCH 04/60] update to 24.0 api default --- forcetk.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/forcetk.js b/forcetk.js index e08d5db..116ebde 100644 --- a/forcetk.js +++ b/forcetk.js @@ -124,7 +124,7 @@ if (forcetk.Client === undefined) { forcetk.Client.prototype.setSessionToken = function(sessionId, apiVersion, instanceUrl) { this.sessionId = sessionId; this.apiVersion = (typeof apiVersion === 'undefined' || apiVersion === null) - ? 'v21.0': apiVersion; + ? 'v24.0': apiVersion; if (typeof instanceUrl === 'undefined' || instanceUrl == null) { // location.hostname can be of the form 'abc.na1.visual.force.com' or // 'na1.salesforce.com'. Split on '.', and take the [1] or [0] element From 51c4388f07bb3cdc3053c8751f7d1d8a85c42e02 Mon Sep 17 00:00:00 2001 From: Ron Hess Date: Tue, 6 Mar 2012 14:39:00 -0800 Subject: [PATCH 05/60] getChatterFile should use the proxyUrl if it is set, required by Visualforce apps --- forcetk.js | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/forcetk.js b/forcetk.js index 116ebde..720e587 100644 --- a/forcetk.js +++ b/forcetk.js @@ -199,13 +199,16 @@ if (forcetk.Client === undefined) { var url = this.instanceUrl + path; var request = new XMLHttpRequest(); - - - request.open("GET", url, true); + + + request.open("GET", (this.proxyUrl !== null) ? this.proxyUrl: url, true); request.responseType = "arraybuffer"; request.setRequestHeader(that.authzHeader, "OAuth " + that.sessionId); request.setRequestHeader('X-User-Agent', 'salesforce-toolkit-rest-javascript/' + that.apiVersion); + if (that.proxyUrl !== null) { + request.setRequestHeader('SalesforceProxy-Endpoint', url); + } request.onreadystatechange = function() { // continue if the process is completed From c212a32cd35aa2a6dfcba5e1e861a70e107ac917 Mon Sep 17 00:00:00 2001 From: Ron Hess Date: Tue, 6 Mar 2012 15:20:29 -0800 Subject: [PATCH 06/60] minor change from that to this --- forcetk.js | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/forcetk.js b/forcetk.js index 720e587..f754db9 100644 --- a/forcetk.js +++ b/forcetk.js @@ -195,18 +195,16 @@ if (forcetk.Client === undefined) { **/ forcetk.Client.prototype.getChatterFile = function(path,mimeType,callback,error,retry) { var that = this; - var url = this.instanceUrl + path; var request = new XMLHttpRequest(); - - + request.open("GET", (this.proxyUrl !== null) ? this.proxyUrl: url, true); request.responseType = "arraybuffer"; request.setRequestHeader(that.authzHeader, "OAuth " + that.sessionId); request.setRequestHeader('X-User-Agent', 'salesforce-toolkit-rest-javascript/' + that.apiVersion); - if (that.proxyUrl !== null) { + if (this.proxyUrl !== null) { request.setRequestHeader('SalesforceProxy-Endpoint', url); } From 12a4b73a3fb3630f7f78369761de379d7dcc3006 Mon Sep 17 00:00:00 2001 From: Alex Berg Date: Sun, 18 Mar 2012 21:09:58 -0500 Subject: [PATCH 07/60] Add param to apexrest to allow to set REST headers. Signed-off-by: Alex Berg --- forcetk.js | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/forcetk.js b/forcetk.js index f754db9..19a1788 100644 --- a/forcetk.js +++ b/forcetk.js @@ -249,8 +249,9 @@ if (forcetk.Client === undefined) { * @param [error=null] function to which jqXHR will be passed in case of error * @param [method="GET"] HTTP method for call * @param [payload=null] payload for POST/PATCH etc + * @param [paramMap={}] parameters to send as header values for POST/PATCH etc */ - forcetk.Client.prototype.apexrest = function(path, callback, error, method, payload, retry) { + forcetk.Client.prototype.apexrest = function(path, callback, error, method, payload, paramMap, retry) { var that = this; var url = this.instanceUrl + '/services/apexrest' + path; @@ -280,6 +281,13 @@ if (forcetk.Client === undefined) { if (that.proxyUrl !== null) { xhr.setRequestHeader('SalesforceProxy-Endpoint', url); } + //Add any custom headers + if (paramMap === null) { + paramMap = {}; + } + for (paramName in paramMap) { + xhr.setRequestHeader(paramName, paramMap[paramName]); + } xhr.setRequestHeader(that.authzHeader, "OAuth " + that.sessionId); xhr.setRequestHeader('X-User-Agent', 'salesforce-toolkit-rest-javascript/' + that.apiVersion); } From 5eb681a51bea8e585d4c3e1a3aab36a36d0880fa Mon Sep 17 00:00:00 2001 From: Alex Berg Date: Tue, 20 Mar 2012 19:52:37 -0500 Subject: [PATCH 08/60] Change paramMap order in parameters and method name in error callback. Signed-off-by: Alex Berg --- forcetk.js | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/forcetk.js b/forcetk.js index 19a1788..a2ce975 100644 --- a/forcetk.js +++ b/forcetk.js @@ -250,6 +250,7 @@ if (forcetk.Client === undefined) { * @param [method="GET"] HTTP method for call * @param [payload=null] payload for POST/PATCH etc * @param [paramMap={}] parameters to send as header values for POST/PATCH etc + * @param [retry] specifies whether to retry on error */ forcetk.Client.prototype.apexrest = function(path, callback, error, method, payload, paramMap, retry) { var that = this; @@ -269,7 +270,7 @@ if (forcetk.Client === undefined) { that.refreshAccessToken(function(oauthResponse) { that.setSessionToken(oauthResponse.access_token, null, oauthResponse.instance_url); - that.ajax(path, callback, error, method, payload, true); + that.apexrest(path, callback, error, method, payload, paramMap, true); }, error); } else { From 5a4f31b432a56c4278b606ac178a770416cad3eb Mon Sep 17 00:00:00 2001 From: Paul Roth Date: Thu, 10 May 2012 16:46:01 -0500 Subject: [PATCH 09/60] UPDATE: add in a queryMore function to the forcetk to allow simpler handling of the rest pagination urls. Calling forcetkClient.ajax doesn't quite work as ajax adds on 'services/data' to the request, which is already present from successResponse.nextRecordsUrl. Signed-off-by: Paul Roth --- forcetk.js | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) diff --git a/forcetk.js b/forcetk.js index f754db9..2838e68 100644 --- a/forcetk.js +++ b/forcetk.js @@ -430,6 +430,31 @@ if (forcetk.Client === undefined) { this.ajax('/' + this.apiVersion + '/query?q=' + escape(soql) , callback, error); } + + /* + * Queries the next set of records based on pagination. + *

This should be used if performing a query that retrieves more than can be returned + * in accordance with http://www.salesforce.com/us/developer/docs/api_rest/Content/dome_query.htm

+ *

Ex: forcetkClient.queryMore( successResponse.nextRecordsUrl, successHandler, failureHandler )

+ * + * @param url - the url retrieved from nextRecordsUrl or prevRecordsUrl + * @param callback function to which response will be passed + * @param [error=null] function to which jqXHR will be passed in case of error + */ + forcetk.Client.prototype.queryMore = function( url, callback, error ){ + + //-- ajax call adds on services/data to the url call, so only send the url after + var serviceData = "services/data"; + var index = url.indexOf( serviceData ); + + if( index > -1 ){ + url = url.substr( index + serviceData.length ); + } else { + //-- leave alone + } + + this.ajax( url, callback, error ); + } /* * Executes the specified SOSL search. From 26285e40a9c86c6867182b07d6411099725cc3ee Mon Sep 17 00:00:00 2001 From: Paul Roth Date: Thu, 10 May 2012 16:47:52 -0500 Subject: [PATCH 10/60] Fix the whitespacing to be more inline with the rest of the forcetk toolkit. Signed-off-by: Paul Roth --- forcetk.js | 23 +++++++++++------------ 1 file changed, 11 insertions(+), 12 deletions(-) diff --git a/forcetk.js b/forcetk.js index 2838e68..ef02b46 100644 --- a/forcetk.js +++ b/forcetk.js @@ -442,18 +442,17 @@ if (forcetk.Client === undefined) { * @param [error=null] function to which jqXHR will be passed in case of error */ forcetk.Client.prototype.queryMore = function( url, callback, error ){ - - //-- ajax call adds on services/data to the url call, so only send the url after - var serviceData = "services/data"; - var index = url.indexOf( serviceData ); - - if( index > -1 ){ - url = url.substr( index + serviceData.length ); - } else { - //-- leave alone - } - - this.ajax( url, callback, error ); + //-- ajax call adds on services/data to the url call, so only send the url after + var serviceData = "services/data"; + var index = url.indexOf( serviceData ); + + if( index > -1 ){ + url = url.substr( index + serviceData.length ); + } else { + //-- leave alone + } + + this.ajax( url, callback, error ); } /* From e83eb3296825a6795eb1f2761e0b31d169432522 Mon Sep 17 00:00:00 2001 From: Paul Roth Date: Thu, 10 May 2012 16:49:16 -0500 Subject: [PATCH 11/60] cleanup: also adjust the whitespacing in the doc comments. Signed-off-by: Paul Roth --- forcetk.js | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/forcetk.js b/forcetk.js index ef02b46..550df93 100644 --- a/forcetk.js +++ b/forcetk.js @@ -432,13 +432,13 @@ if (forcetk.Client === undefined) { } /* - * Queries the next set of records based on pagination. - *

This should be used if performing a query that retrieves more than can be returned - * in accordance with http://www.salesforce.com/us/developer/docs/api_rest/Content/dome_query.htm

- *

Ex: forcetkClient.queryMore( successResponse.nextRecordsUrl, successHandler, failureHandler )

- * - * @param url - the url retrieved from nextRecordsUrl or prevRecordsUrl - * @param callback function to which response will be passed + * Queries the next set of records based on pagination. + *

This should be used if performing a query that retrieves more than can be returned + * in accordance with http://www.salesforce.com/us/developer/docs/api_rest/Content/dome_query.htm

+ *

Ex: forcetkClient.queryMore( successResponse.nextRecordsUrl, successHandler, failureHandler )

+ * + * @param url - the url retrieved from nextRecordsUrl or prevRecordsUrl + * @param callback function to which response will be passed * @param [error=null] function to which jqXHR will be passed in case of error */ forcetk.Client.prototype.queryMore = function( url, callback, error ){ From 329cde434aa4a0cae4a5a11bf7ace45ee8df47c4 Mon Sep 17 00:00:00 2001 From: Paul Roth Date: Thu, 10 May 2012 16:50:58 -0500 Subject: [PATCH 12/60] also remove tabs on the initial doc comment Signed-off-by: Paul Roth --- forcetk.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/forcetk.js b/forcetk.js index 550df93..80ea067 100644 --- a/forcetk.js +++ b/forcetk.js @@ -431,7 +431,7 @@ if (forcetk.Client === undefined) { , callback, error); } - /* + /* * Queries the next set of records based on pagination. *

This should be used if performing a query that retrieves more than can be returned * in accordance with http://www.salesforce.com/us/developer/docs/api_rest/Content/dome_query.htm

From 774a837f4e84a086770665cb37b7039c02696613 Mon Sep 17 00:00:00 2001 From: Pat Patterson Date: Mon, 1 Oct 2012 00:10:13 -0700 Subject: [PATCH 13/60] Added RemoteTK --- README.markdown | 45 ++++++-- RemoteTK.component | 187 ++++++++++++++++++++++++++++++++ RemoteTKController.cls | 235 +++++++++++++++++++++++++++++++++++++++++ RemoteTKExample.page | 150 ++++++++++++++++++++++++++ 4 files changed, 610 insertions(+), 7 deletions(-) create mode 100644 RemoteTK.component create mode 100644 RemoteTKController.cls create mode 100644 RemoteTKExample.page diff --git a/README.markdown b/README.markdown index 4812c6c..60bb358 100644 --- a/README.markdown +++ b/README.markdown @@ -1,17 +1,19 @@ Force.com JavaScript REST Toolkit ================================= -This minimal toolkit allows JavaScript in Visualforce pages to call the Force.com REST API either via the Ajax Proxy (in the case of web apps) or directly (from a PhoneGap app), providing an easy-to-use JavaScript wrapper. +This minimal toolkit allows JavaScript in Visualforce pages to call the Force.com REST API in a number of different ways. Background ---------- Due to the [same origin policy](http://en.wikipedia.org/wiki/Same_origin_policy), JavaScript running in Visualforce pages may not use [XmlHttpRequest](http://en.wikipedia.org/wiki/XMLHttpRequest) to directly invoke the REST API, since Visualforce pages have hostnames of the form abc.na1.visual.force.com, and the REST API endpoints are of the form na1.salesforce.com. -We can work around this restriction by using the [AJAX Proxy](http://www.salesforce.com/us/developer/docs/ajax/Content/sforce_api_ajax_queryresultiterator.htm#ajax_proxy). Since the AJAX proxy is present on all -Visualforce hosts with an endpoint of the form https://abc.na1.visual.force.com/services/proxy, our Visualforce-hosted JavaScript can invoke it, passing the desired resource URL in an HTTP header. +The RemoteTK Visualforce Component (comprising RemoteTK.component and RemoteTKController.cls) provides an abstraction very similar to the REST API, implemented via `@RemoteAction` methods in the component's controller. The advantage of this mechanism is that no API calls are consumed. A disadvantage is that upsert is not currently implemented. -Alternatively, to host JavaScript outside the Force.com platform, we can deploy a simple PHP proxy to perform the same function as the AJAX proxy. +Alternatively, the ForceTK JavaScript library works around the same origin restriction by using the [AJAX Proxy](http://www.salesforce.com/us/developer/docs/ajax/Content/sforce_api_ajax_queryresultiterator.htm#ajax_proxy) to give full access to the REST API. Since the AJAX proxy is present on all +Visualforce hosts with an endpoint of the form https://abc.na1.visual.force.com/services/proxy, our Visualforce-hosted JavaScript can invoke it, passing the desired resource URL in an HTTP header. A drawback here is that using the REST API, even from a Visualforce page, consumes API calls. + +To host JavaScript outside the Force.com platform, we can deploy a simple PHP proxy to perform the same function as the AJAX proxy. [PhoneGap](http://www.phonegap.com/) provides a way for HTML5/JavaScript apps to run as native applications; in this configuration a proxy is not required - the toolkit simply provides a convenient abstraction of the REST API. @@ -23,10 +25,39 @@ The toolkit uses [jQuery](http://jquery.com/). It has been tested on jQuery 1.4. Configuration ------------- -You must add the correct REST endpoint hostname for your instance (i.e. https://na1.salesforce.com/ or similar) as a remote site in *Your Name > Administration Setup > Security Controls > Remote Site Settings*. +RemoteTK requires no configuration. + +ForceTK requires that you add the correct REST endpoint hostname for your instance (i.e. https://na1.salesforce.com/ or similar) as a remote site in *Your Name > Administration Setup > Security Controls > Remote Site Settings*. + +Using RemoteTK in a Visualforce page +------------------------------------ + +Add RemoteTKController.cls and RemoteTK.component to your org by creating an Apex Class and a Component and pasting in the respective content, pasting the files into a [Force.com IDE](http://wiki.developerforce.com/page/Force.com_IDE) project, or by using the [Force.com Migration Tool](http://wiki.developerforce.com/page/Migration_Tool_Guide). + +Your Visualforce page will need to include the component, then create a client object, passing a session ID to the constructor. An absolutely minimal sample is: + + + + + + +

The first account I see is .

+
+ +A more fully featured sample is provided in [RemoteTKExample.page](Force.com-JavaScript-REST-Toolkit/blob/master/RemoteTKExample.page). -Using the Toolkit in a Visualforce page ---------------------------------------- +Using ForceTK in a Visualforce page +----------------------------------- Create a zip file containing app.js, forcetk.js, jquery.js, and any other static resources your project may need. Upload the zip via *Your Name > App Setup > Develop > Static Resources*. diff --git a/RemoteTK.component b/RemoteTK.component new file mode 100644 index 0000000..a21e089 --- /dev/null +++ b/RemoteTK.component @@ -0,0 +1,187 @@ + + + + \ No newline at end of file diff --git a/RemoteTKController.cls b/RemoteTKController.cls new file mode 100644 index 0000000..e651d01 --- /dev/null +++ b/RemoteTKController.cls @@ -0,0 +1,235 @@ +/* + * Copyright (c) 2012, salesforce.com, inc. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, are permitted provided + * that the following conditions are met: + * + * Redistributions of source code must retain the above copyright notice, this list of conditions and the + * following disclaimer. + * + * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and + * the following disclaimer in the documentation and/or other materials provided with the distribution. + * + * Neither the name of salesforce.com, inc. nor the names of its contributors may be used to endorse or + * promote products derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A + * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR + * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED + * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ + +public class RemoteTKController { + @remoteAction + public static String describe(String objtype) { + // Just enough to make the sample app work! + Schema.SObjectType targetType = Schema.getGlobalDescribe().get(objtype); + if (targetType == null) { + return '[{"message":"The requested resource does not exist","errorCode":"NOT_FOUND"}]'; + } + + Schema.DescribeSObjectResult sobjResult = targetType.getDescribe(); + + Map fieldMap = sobjResult.fields.getMap(); + + List fields = new List(); + for (String key : fieldMap.keySet()) { + Schema.DescribeFieldResult descField = fieldMap.get(key).getDescribe(); + Map field = new Map(); + + field.put('type', descField.getType().name().toLowerCase()); + field.put('name', descField.getName()); + field.put('label', descField.getLabel()); + + fields.add(field); + } + + Map result = new Map(); + result.put('fields', fields); + + return JSON.serialize(result); + } + + @remoteAction + public static String create(String objtype, String fields) { + Schema.SObjectType targetType = Schema.getGlobalDescribe().get(objtype); + if (targetType == null) { + return '[{"message":"The requested resource does not exist","errorCode":"NOT_FOUND"}]'; + } + + SObject obj = targetType.newSObject(); + + Map fieldMap = null; + try { + fieldMap = (Map)JSON.deserializeUntyped(fields); + } catch (JSONException je) { + return '[{"message":"'+je.getMessage()+'","errorCode":"JSON_PARSER_ERROR"}]'; + } + + try { + for (String key : fieldMap.keySet()) { + obj.put(key, fieldMap.get(key)); + } + } catch (SObjectException soe) { + return '[{"message":"'+soe.getMessage()+'","errorCode":"INVALID_FIELD"}]'; + } + + try { + insert obj; + } catch (DMLException dmle) { + String fieldNames = ''; + for (String field : dmle.getDmlFieldNames(0)) { + if (fieldNames.length() > 0) { + fieldNames += ','; + } + fieldNames += '"'+field+'"'; + } + return '[{"fields":['+fieldNames+'],"message":"'+dmle.getDmlMessage(0)+'","errorCode":"'+dmle.getDmlType(0).name()+'"}]'; + } + + Map result = new Map(); + result.put('id', obj.id); + result.put('errors', new List()); + result.put('success', true); + + return JSON.serialize(result); + } + + @remoteAction + public static String retrieve(String objtype, String id, String fieldlist) { + // TODO - handle missing fieldlist - retrieve all fields + String fieldString = ''; + for (String field : fieldlist.split(',')) { + fieldString += ','+field; + } + + String soql = 'SELECT Id'+fieldString+' FROM '+objtype+' WHERE Id = \''+id+'\''; + List records; + try { + records = Database.query(soql); + } catch (QueryException qe) { + return '[{"message":"'+qe.getMessage()+'","errorCode":"INVALID_QUERY"}]'; + } + + return JSON.serialize(records[0]); + } + + /* + @remoteAction + public static String upser(String objtype, String externalIdField, String externalId, String fields) { + Schema.SObjectType targetType = Schema.getGlobalDescribe().get(objtype); + + SObject obj = targetType.newSObject(); + obj.put(externalIdField, externalId); + + Map fieldMap = + (Map)JSON.deserializeUntyped(fields); + for (String key : fieldMap.keySet()) { + obj.put(key, fieldMap.get(key)); + } + + Schema.SObjectField sobjField = targetType.getDescribe().fields.getMap().get(externalIdField); + + // Database.Upsert(obj, sobjField); // error - upsert requires a concrete sobject type + + return null; + } + */ + + @remoteAction + public static String updat(String objtype, String id, String fields) { + Schema.SObjectType targetType = Schema.getGlobalDescribe().get(objtype); + if (targetType == null) { + return '[{"message":"The requested resource does not exist","errorCode":"NOT_FOUND"}]'; + } + + SObject obj = targetType.newSObject(id); + + Map fieldMap = null; + try { + fieldMap = (Map)JSON.deserializeUntyped(fields); + } catch (JSONException je) { + return '[{"message":"'+je.getMessage()+'","errorCode":"JSON_PARSER_ERROR"}]'; + } + + try { + for (String key : fieldMap.keySet()) { + obj.put(key, fieldMap.get(key)); + } + } catch (SObjectException soe) { + return '[{"message":"'+soe.getMessage()+'","errorCode":"INVALID_FIELD"}]'; + } + + try { + update obj; + } catch (DMLException dmle) { + String fieldNames = ''; + for (String field : dmle.getDmlFieldNames(0)) { + if (fieldNames.length() > 0) { + fieldNames += ','; + } + fieldNames += '"'+field+'"'; + } + return '[{"fields":['+fieldNames+'],"message":"'+dmle.getDmlMessage(0)+'","errorCode":"'+dmle.getDmlType(0).name()+'"}]'; + } + + return null; + } + + @remoteAction + public static String del(String objtype, String id) { + Schema.SObjectType targetType = Schema.getGlobalDescribe().get(objtype); + if (targetType == null) { + return '[{"message":"The requested resource does not exist","errorCode":"NOT_FOUND"}]'; + } + + SObject obj = targetType.newSObject(id); + + try { + delete obj; + } catch (DMLException dmle) { + String fieldNames = ''; + for (String field : dmle.getDmlFieldNames(0)) { + if (fieldNames.length() > 0) { + fieldNames += ','; + } + fieldNames += '"'+field+'"'; + } + return '[{"fields":['+fieldNames+'],"message":"'+dmle.getDmlMessage(0)+'","errorCode":"'+dmle.getDmlType(0).name()+'"}]'; + } + + return null; + } + + @remoteAction + public static String query(String soql) { + List records; + try { + records = Database.query(soql); + } catch (QueryException qe) { + return '[{"message":"'+qe.getMessage()+'","errorCode":"INVALID_QUERY"}]'; + } + + Map result = new Map(); + result.put('records', records); + + return JSON.serialize(result); + } + + @remoteAction + public static String search(String sosl) { + List> result; + try { + result = Search.query(sosl); + } catch (SearchException se) { + return '[{"message":"'+se.getMessage()+'","errorCode":"INVALID_SEARCH"}]'; + } + + return JSON.serialize(result); + } +} \ No newline at end of file diff --git a/RemoteTKExample.page b/RemoteTKExample.page new file mode 100644 index 0000000..2b89192 --- /dev/null +++ b/RemoteTKExample.page @@ -0,0 +1,150 @@ + + + + + + + + Force.com JavaScript REST Toolkit + + + + + + + + + + + +
+
+
+
+
+
+ + + + + + + + + +
\ No newline at end of file From 4cf56487be5a8c8f22500011424b40aa84f6e6e5 Mon Sep 17 00:00:00 2001 From: Pat Patterson Date: Mon, 1 Oct 2012 09:37:05 -0700 Subject: [PATCH 14/60] Only add Id to list of fields to be retrieved if it is not already there --- RemoteTKController.cls | 15 +++++++++++---- 1 file changed, 11 insertions(+), 4 deletions(-) diff --git a/RemoteTKController.cls b/RemoteTKController.cls index e651d01..2ae97b3 100644 --- a/RemoteTKController.cls +++ b/RemoteTKController.cls @@ -102,13 +102,20 @@ public class RemoteTKController { @remoteAction public static String retrieve(String objtype, String id, String fieldlist) { - // TODO - handle missing fieldlist - retrieve all fields - String fieldString = ''; + // TODO - handle null fieldlist - retrieve all fields + Boolean containsId = false; for (String field : fieldlist.split(',')) { - fieldString += ','+field; + if (field.equalsIgnoreCase('id')){ + containsId = true; + break; + } + } + + if (!containsId) { + fieldlist = 'Id,'+fieldlist; } - String soql = 'SELECT Id'+fieldString+' FROM '+objtype+' WHERE Id = \''+id+'\''; + String soql = 'SELECT '+fieldlist+' FROM '+objtype+' WHERE Id = \''+id+'\''; List records; try { records = Database.query(soql); From 19c6d636ebc7fa1447bf1e7d610875a0b44319ad Mon Sep 17 00:00:00 2001 From: Pat Patterson Date: Mon, 1 Oct 2012 09:43:24 -0700 Subject: [PATCH 15/60] Added mobile example for RemoteTK --- README.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.markdown b/README.markdown index 60bb358..1ae0034 100644 --- a/README.markdown +++ b/README.markdown @@ -54,7 +54,7 @@ Your Visualforce page will need to include the component, then create a client o

The first account I see is .

-A more fully featured sample is provided in [RemoteTKExample.page](Force.com-JavaScript-REST-Toolkit/blob/master/RemoteTKExample.page). +More fully featured samples are provided in [RemoteTKExample.page](Force.com-JavaScript-REST-Toolkit/blob/master/RemoteTKExample.page) and [RemoteTKMobile.page](Force.com-JavaScript-REST-Toolkit/blob/master/RemoteTKMobile.page). Using ForceTK in a Visualforce page ----------------------------------- From 8b18f9b3e748db5ef53a35354a9761c5b0c079ef Mon Sep 17 00:00:00 2001 From: Pat Patterson Date: Mon, 1 Oct 2012 18:32:08 -0700 Subject: [PATCH 16/60] Corrections --- README.markdown | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.markdown b/README.markdown index 1ae0034..7dd7edf 100644 --- a/README.markdown +++ b/README.markdown @@ -8,7 +8,7 @@ Background Due to the [same origin policy](http://en.wikipedia.org/wiki/Same_origin_policy), JavaScript running in Visualforce pages may not use [XmlHttpRequest](http://en.wikipedia.org/wiki/XMLHttpRequest) to directly invoke the REST API, since Visualforce pages have hostnames of the form abc.na1.visual.force.com, and the REST API endpoints are of the form na1.salesforce.com. -The RemoteTK Visualforce Component (comprising RemoteTK.component and RemoteTKController.cls) provides an abstraction very similar to the REST API, implemented via `@RemoteAction` methods in the component's controller. The advantage of this mechanism is that no API calls are consumed. A disadvantage is that upsert is not currently implemented. +The RemoteTK Visualforce Custom Component (comprising RemoteTK.component and RemoteTKController.cls) provides an abstraction very similar to the REST API, implemented via `@RemoteAction` methods in the component's controller. The advantage of this mechanism is that no API calls are consumed. A disadvantage is that upsert is not currently implemented. Alternatively, the ForceTK JavaScript library works around the same origin restriction by using the [AJAX Proxy](http://www.salesforce.com/us/developer/docs/ajax/Content/sforce_api_ajax_queryresultiterator.htm#ajax_proxy) to give full access to the REST API. Since the AJAX proxy is present on all Visualforce hosts with an endpoint of the form https://abc.na1.visual.force.com/services/proxy, our Visualforce-hosted JavaScript can invoke it, passing the desired resource URL in an HTTP header. A drawback here is that using the REST API, even from a Visualforce page, consumes API calls. @@ -34,7 +34,7 @@ Using RemoteTK in a Visualforce page Add RemoteTKController.cls and RemoteTK.component to your org by creating an Apex Class and a Component and pasting in the respective content, pasting the files into a [Force.com IDE](http://wiki.developerforce.com/page/Force.com_IDE) project, or by using the [Force.com Migration Tool](http://wiki.developerforce.com/page/Migration_Tool_Guide). -Your Visualforce page will need to include the component, then create a client object, passing a session ID to the constructor. An absolutely minimal sample is: +Your Visualforce page will need to include the component and create a client object. An absolutely minimal sample is: From 13d11f1a3728b31ee711bbaab58efdb70de69adb Mon Sep 17 00:00:00 2001 From: Pat Patterson Date: Mon, 15 Oct 2012 01:33:50 -0700 Subject: [PATCH 17/60] Added mobile version of RemoteTK demo --- RemoteTKMobile.page | 144 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 144 insertions(+) create mode 100644 RemoteTKMobile.page diff --git a/RemoteTKMobile.page b/RemoteTKMobile.page new file mode 100644 index 0000000..25e9673 --- /dev/null +++ b/RemoteTKMobile.page @@ -0,0 +1,144 @@ + + + + +"}"/> + + + + +Accounts + + + + + + + + + + + +
+ +
+

Account List

+
+
+
+ +
+
    +
+
+
+

Some Text

+
+
+
+
+

Account Detail

+
+
+ + + + +
Account Name:
Industry:
Ticker Symbol:
+
+ + + +
+
+
+

Some Text

+
+
+
+
+

New Account

+
+
+
+ + + + + + + + + + + + + + +
Account Name:
Industry:
Ticker Symbol:
+ +
+
+
+

Some Text

+
+
+ + +
\ No newline at end of file From 3abd646dddd474b078bc832928a8512139a77f7a Mon Sep 17 00:00:00 2001 From: Pat Patterson Date: Mon, 15 Oct 2012 01:34:57 -0700 Subject: [PATCH 18/60] Use escape:false option rather than unescaping remote action result --- RemoteTK.component | 24 +++++++++++++++++------- 1 file changed, 17 insertions(+), 7 deletions(-) diff --git a/RemoteTK.component b/RemoteTK.component index a21e089..cb06fb7 100644 --- a/RemoteTK.component +++ b/RemoteTK.component @@ -32,15 +32,9 @@ if (remotetk === undefined) { } if (remotetk.Client === undefined) { - function unescapeHTML(input) { - var y = document.createElement('textarea'); - y.innerHTML = input; - return y.value; - } - function handleResult(result, callback, error, nullok) { if (result) { - result = JSON.parse(unescapeHTML(result)); + result = JSON.parse(result); if ( Array.isArray(result) && result[0].message && result[0].errorCode ) { if ( typeof error === 'function' ) { error(result); @@ -74,6 +68,8 @@ if (remotetk.Client === undefined) { remotetk.Client.prototype.describe = function(objtype, callback, error) { RemoteTKController.describe(objtype, function(result){ handleResult(result, callback, error); + }, { + escape: false }); } @@ -89,6 +85,8 @@ if (remotetk.Client === undefined) { remotetk.Client.prototype.create = function(objtype, fields, callback, error) { RemoteTKController.create(objtype, JSON.stringify(fields), function(result){ handleResult(result, callback, error); + }, { + escape: false }); } @@ -104,6 +102,8 @@ if (remotetk.Client === undefined) { remotetk.Client.prototype.retrieve = function(objtype, id, fieldlist, callback, error) { RemoteTKController.retrieve(objtype, id, fieldlist, function(result){ handleResult(result, callback, error); + }, { + escape: false }); } @@ -123,6 +123,8 @@ if (remotetk.Client === undefined) { remotetk.Client.prototype.upsert = function(objtype, externalIdField, externalId, fields, callback, error) { RemoteTKController.upser(objtype, externalIdField, externalId, JSON.stringify(fields), function(result){ handleResult(result, callback, error, true); + }, { + escape: false }); } */ @@ -140,6 +142,8 @@ if (remotetk.Client === undefined) { remotetk.Client.prototype.update = function(objtype, id, fields, callback, error) { RemoteTKController.updat(objtype, id, JSON.stringify(fields), function(result){ handleResult(result, callback, error, true); + }, { + escape: false }); } @@ -154,6 +158,8 @@ if (remotetk.Client === undefined) { remotetk.Client.prototype.del = function(objtype, id, callback, error) { RemoteTKController.del(objtype, id, function(result){ handleResult(result, callback, error, true); + }, { + escape: false }); } @@ -167,6 +173,8 @@ if (remotetk.Client === undefined) { remotetk.Client.prototype.query = function(soql, callback, error) { RemoteTKController.query(soql, function(result){ handleResult(result, callback, error); + }, { + escape: false }); } @@ -180,6 +188,8 @@ if (remotetk.Client === undefined) { remotetk.Client.prototype.search = function(sosl, callback, error) { RemoteTKController.search(sosl, function(result){ handleResult(result, callback, error); + }, { + escape: false }); } } From b7c8f652b6b322cbf9fda78dbdfdcbf4bf2100a6 Mon Sep 17 00:00:00 2001 From: Pat Patterson Date: Mon, 15 Oct 2012 01:36:42 -0700 Subject: [PATCH 19/60] Clarify readme --- README.markdown | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.markdown b/README.markdown index 7dd7edf..d9b271d 100644 --- a/README.markdown +++ b/README.markdown @@ -1,7 +1,7 @@ Force.com JavaScript REST Toolkit ================================= -This minimal toolkit allows JavaScript in Visualforce pages to call the Force.com REST API in a number of different ways. +This minimal toolkit allows JavaScript in web pages to call the Force.com REST API in a number of different ways. Background ---------- @@ -13,7 +13,7 @@ The RemoteTK Visualforce Custom Component (comprising RemoteTK.component and Rem Alternatively, the ForceTK JavaScript library works around the same origin restriction by using the [AJAX Proxy](http://www.salesforce.com/us/developer/docs/ajax/Content/sforce_api_ajax_queryresultiterator.htm#ajax_proxy) to give full access to the REST API. Since the AJAX proxy is present on all Visualforce hosts with an endpoint of the form https://abc.na1.visual.force.com/services/proxy, our Visualforce-hosted JavaScript can invoke it, passing the desired resource URL in an HTTP header. A drawback here is that using the REST API, even from a Visualforce page, consumes API calls. -To host JavaScript outside the Force.com platform, we can deploy a simple PHP proxy to perform the same function as the AJAX proxy. +To host JavaScript *outside* the Force.com platform, we can deploy a simple PHP proxy to perform the same function as the AJAX proxy. [PhoneGap](http://www.phonegap.com/) provides a way for HTML5/JavaScript apps to run as native applications; in this configuration a proxy is not required - the toolkit simply provides a convenient abstraction of the REST API. From b187b60063ad05201515aa0d9d16c6ca0dfb9f67 Mon Sep 17 00:00:00 2001 From: "Christian G. Warden" Date: Fri, 16 Nov 2012 12:39:50 -0800 Subject: [PATCH 20/60] Check http-prefixed content-* headers The built-in web server in PHP 5.4 sets the Content-Length and Content-Type headers in $_SERVER['HTTP_CONTENT_LENGTH'] and $_SERVER['HTTP_CONTENT_TYPE'] rather than $_SERVER['CONTENT_LENGTH'] and $_SERVER['CONTENT_TYPE']. --- proxy.php | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-) diff --git a/proxy.php b/proxy.php index fdc47ff..8c3821a 100644 --- a/proxy.php +++ b/proxy.php @@ -234,7 +234,8 @@ isset($_SERVER['REQUEST_METHOD']) ? $_SERVER['REQUEST_METHOD'] : 'GET' ); // Pass on content, regardless of request method - if ( isset($_SERVER['CONTENT_LENGTH'] ) && $_SERVER['CONTENT_LENGTH'] > 0 ) { + if ( (isset($_SERVER['CONTENT_LENGTH'] ) && $_SERVER['CONTENT_LENGTH'] > 0) || + (isset($_SERVER['HTTP_CONTENT_LENGTH'] ) && $_SERVER['HTTP_CONTENT_LENGTH'] > 0) ) { curl_setopt( $ch, CURLOPT_POSTFIELDS, file_get_contents("php://input") ); } @@ -257,9 +258,12 @@ array_push($headers, "Authorization: ".$_SERVER[$authz_header] ); } if ( isset($_SERVER['CONTENT_TYPE']) ) { - // Pass through the Content-Type header - array_push($headers, "Content-Type: ".$_SERVER['CONTENT_TYPE'] ); - } + // Pass through the Content-Type header + array_push($headers, "Content-Type: ".$_SERVER['CONTENT_TYPE'] ); + } elseif ( isset($_SERVER['HTTP_CONTENT_TYPE']) ) { + // Pass through the Content-Type header + array_push($headers, "Content-Type: ".$_SERVER['HTTP_CONTENT_TYPE'] ); + } if ( isset($_SERVER['HTTP_X_USER_AGENT']) ) { // Pass through the X-User-Agent header array_push($headers, "X-User-Agent: ".$_SERVER['HTTP_X_USER_AGENT'] ); From fd049d826b8491e078552954e63ee762f43eadbe Mon Sep 17 00:00:00 2001 From: "Christian G. Warden" Date: Fri, 16 Nov 2012 12:43:02 -0800 Subject: [PATCH 21/60] Add support for SOAP API Pass through SOAPAction header, necessary when proxying requests to the SOAP API. --- proxy.php | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/proxy.php b/proxy.php index fdc47ff..eb935ea 100644 --- a/proxy.php +++ b/proxy.php @@ -260,6 +260,10 @@ // Pass through the Content-Type header array_push($headers, "Content-Type: ".$_SERVER['CONTENT_TYPE'] ); } + if ( isset($_SERVER['HTTP_SOAPACTION']) ) { + // Pass through the SOAPAction header + array_push($headers, "SOAPAction: ".$_SERVER['HTTP_SOAPACTION'] ); + } if ( isset($_SERVER['HTTP_X_USER_AGENT']) ) { // Pass through the X-User-Agent header array_push($headers, "X-User-Agent: ".$_SERVER['HTTP_X_USER_AGENT'] ); From 3d99e4b236411c56485031db0fcdc4969ddfe4bc Mon Sep 17 00:00:00 2001 From: Pat Patterson Date: Mon, 26 Nov 2012 10:12:23 -0800 Subject: [PATCH 22/60] Corrected search query param. Fixes #21 --- forcetk.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/forcetk.js b/forcetk.js index f754db9..84560b4 100644 --- a/forcetk.js +++ b/forcetk.js @@ -439,7 +439,7 @@ if (forcetk.Client === undefined) { * @param [error=null] function to which jqXHR will be passed in case of error */ forcetk.Client.prototype.search = function(sosl, callback, error) { - this.ajax('/' + this.apiVersion + '/search?s=' + escape(sosl) + this.ajax('/' + this.apiVersion + '/search?q=' + escape(sosl) , callback, error); } } \ No newline at end of file From 4954955a6ee724a727d9974fad25b18c43e0e10d Mon Sep 17 00:00:00 2001 From: "Christian G. Warden" Date: Tue, 8 Jan 2013 13:42:27 -0800 Subject: [PATCH 23/60] Add support for cloudforce.com instances Allow proxy to send requests to cloudforce.com instances in addition to *.salesforce.com and *.database.com ones. --- proxy.php | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/proxy.php b/proxy.php index fdc47ff..9126e33 100644 --- a/proxy.php +++ b/proxy.php @@ -169,8 +169,7 @@ // Change these configuration options if needed, see above descriptions for info. $enable_jsonp = false; $enable_native = true; -$valid_forcecom_url_regex = '/https:\/\/.*.salesforce.com/'; -$valid_databasecom_url_regex = '/https:\/\/.*database.com/'; +$valid_forcecom_url_regex = '/https:\/\/.*\.(salesforce|database|cloudforce)\.com/'; $url_query_param = null; // 'url' @@ -203,7 +202,7 @@ $status['http_code'] = 400; $status['status_text'] = 'Bad Request'; -} else if ( !preg_match( $valid_forcecom_url_regex, $url ) && !preg_match( $valid_databasecom_url_regex, $url )) { +} else if ( !preg_match( $valid_forcecom_url_regex, $url )) { // Passed url doesn't match $valid_url_regex. $contents = 'ERROR: invalid url'; From c2bd05f71168d3b9abcf70bda1bfda53d3aa0bdf Mon Sep 17 00:00:00 2001 From: "Christian G. Warden" Date: Thu, 10 Jan 2013 11:22:42 -0800 Subject: [PATCH 24/60] Support RemoteTK within a namespace Use Visualforce.remoting.Manager.invokeAction and $RemoteAction global variable so RemoteTK can be used within a managed package's namespace. --- RemoteTK.component | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/RemoteTK.component b/RemoteTK.component index cb06fb7..073db2d 100644 --- a/RemoteTK.component +++ b/RemoteTK.component @@ -66,7 +66,7 @@ if (remotetk.Client === undefined) { * @param [error=null] function to which jqXHR will be passed in case of error */ remotetk.Client.prototype.describe = function(objtype, callback, error) { - RemoteTKController.describe(objtype, function(result){ + Visualforce.remoting.Manager.invokeAction('{!$RemoteAction.RemoteTKController.describe}', objtype, function(result){ handleResult(result, callback, error); }, { escape: false @@ -83,7 +83,7 @@ if (remotetk.Client === undefined) { * @param [error=null] function to which jqXHR will be passed in case of error */ remotetk.Client.prototype.create = function(objtype, fields, callback, error) { - RemoteTKController.create(objtype, JSON.stringify(fields), function(result){ + Visualforce.remoting.Manager.invokeAction('{!$RemoteAction.RemoteTKController.create}', objtype, JSON.stringify(fields), function(result){ handleResult(result, callback, error); }, { escape: false @@ -100,7 +100,7 @@ if (remotetk.Client === undefined) { * @param [error=null] function to which jqXHR will be passed in case of error */ remotetk.Client.prototype.retrieve = function(objtype, id, fieldlist, callback, error) { - RemoteTKController.retrieve(objtype, id, fieldlist, function(result){ + Visualforce.remoting.Manager.invokeAction('{!$RemoteAction.RemoteTKController.retrieve}', objtype, id, fieldlist, function(result){ handleResult(result, callback, error); }, { escape: false @@ -121,7 +121,7 @@ if (remotetk.Client === undefined) { */ /* remotetk.Client.prototype.upsert = function(objtype, externalIdField, externalId, fields, callback, error) { - RemoteTKController.upser(objtype, externalIdField, externalId, JSON.stringify(fields), function(result){ + Visualforce.remoting.Manager.invokeAction('$RemoteAction.RemoteTKController.upser', objtype, externalIdField, externalId, JSON.stringify(fields), function(result){ handleResult(result, callback, error, true); }, { escape: false @@ -140,7 +140,7 @@ if (remotetk.Client === undefined) { * @param [error=null] function to which jqXHR will be passed in case of error */ remotetk.Client.prototype.update = function(objtype, id, fields, callback, error) { - RemoteTKController.updat(objtype, id, JSON.stringify(fields), function(result){ + Visualforce.remoting.Manager.invokeAction('{!$RemoteAction.RemoteTKController.updat}', objtype, id, JSON.stringify(fields), function(result){ handleResult(result, callback, error, true); }, { escape: false @@ -156,7 +156,7 @@ if (remotetk.Client === undefined) { * @param [error=null] function to which jqXHR will be passed in case of error */ remotetk.Client.prototype.del = function(objtype, id, callback, error) { - RemoteTKController.del(objtype, id, function(result){ + Visualforce.remoting.Manager.invokeAction('{!$RemoteAction.RemoteTKController.del}', objtype, id, function(result){ handleResult(result, callback, error, true); }, { escape: false @@ -171,7 +171,7 @@ if (remotetk.Client === undefined) { * @param [error=null] function to which jqXHR will be passed in case of error */ remotetk.Client.prototype.query = function(soql, callback, error) { - RemoteTKController.query(soql, function(result){ + Visualforce.remoting.Manager.invokeAction('{!$RemoteAction.RemoteTKController.query}', soql, function(result){ handleResult(result, callback, error); }, { escape: false @@ -186,7 +186,7 @@ if (remotetk.Client === undefined) { * @param [error=null] function to which jqXHR will be passed in case of error */ remotetk.Client.prototype.search = function(sosl, callback, error) { - RemoteTKController.search(sosl, function(result){ + Visualforce.remoting.Manager.invokeAction('{!$RemoteAction.RemoteTKController.search}', sosl, function(result){ handleResult(result, callback, error); }, { escape: false From a116718f054c5efbb8a74371d08c20e056854877 Mon Sep 17 00:00:00 2001 From: "Christian G. Warden" Date: Thu, 10 Jan 2013 11:26:10 -0800 Subject: [PATCH 25/60] Improve compatiblity of RemoteTK with ForceTK Changes to allow RemoteTK to be used as a drop-in replacement for ForceTK: Add setSessionToken, setRefreshToken, and setUserAgentString noop functions. Return referenceTo attribute with describe responses. Return totalSize and done attributes with query responses. --- RemoteTK.component | 6 ++++++ RemoteTKController.cls | 9 +++++++++ 2 files changed, 15 insertions(+) diff --git a/RemoteTK.component b/RemoteTK.component index cb06fb7..c53d2ec 100644 --- a/RemoteTK.component +++ b/RemoteTK.component @@ -57,6 +57,12 @@ if (remotetk.Client === undefined) { */ remotetk.Client = function(){ } + + /** NOOP: for compatibility with forcetk + */ + remotetk.Client.prototype.setSessionToken = function() {} + remotetk.Client.prototype.setRefreshToken = function() {} + remotetk.Client.prototype.setUserAgentString = function() {} /* * Completely describes the individual metadata at all levels for the diff --git a/RemoteTKController.cls b/RemoteTKController.cls index 2ae97b3..78e4e80 100644 --- a/RemoteTKController.cls +++ b/RemoteTKController.cls @@ -45,6 +45,13 @@ public class RemoteTKController { field.put('type', descField.getType().name().toLowerCase()); field.put('name', descField.getName()); field.put('label', descField.getLabel()); + List references = new List(); + for (Schema.sObjectType t: descField.getReferenceTo()) { + references.add(t.getDescribe().getName()); + } + if (!references.isEmpty()) { + field.put('referenceTo', references); + } fields.add(field); } @@ -224,6 +231,8 @@ public class RemoteTKController { Map result = new Map(); result.put('records', records); + result.put('totalSize', records.size()); + result.put('done', true); return JSON.serialize(result); } From 7c8bcdad32b38c7e49e27faade7f4480d09fed95 Mon Sep 17 00:00:00 2001 From: "Christian G. Warden" Date: Thu, 10 Jan 2013 11:29:35 -0800 Subject: [PATCH 26/60] Improve field-type support in create calls Check the type of fields being populated in create calls and convert values to the correct type. --- RemoteTKController.cls | 14 +++++++++++++- 1 file changed, 13 insertions(+), 1 deletion(-) diff --git a/RemoteTKController.cls b/RemoteTKController.cls index 2ae97b3..6634104 100644 --- a/RemoteTKController.cls +++ b/RemoteTKController.cls @@ -58,6 +58,7 @@ public class RemoteTKController { @remoteAction public static String create(String objtype, String fields) { Schema.SObjectType targetType = Schema.getGlobalDescribe().get(objtype); + Map targetFields = targetType.getDescribe().fields.getMap(); if (targetType == null) { return '[{"message":"The requested resource does not exist","errorCode":"NOT_FOUND"}]'; } @@ -73,7 +74,18 @@ public class RemoteTKController { try { for (String key : fieldMap.keySet()) { - obj.put(key, fieldMap.get(key)); + if (targetFields.get(key).getDescribe().getType() == Schema.DisplayType.Date) { + obj.put(key, Date.valueOf((String)fieldMap.get(key))); + } else if (targetFields.get(key).getDescribe().getType() == Schema.DisplayType.Percent || + targetFields.get(key).getDescribe().getType() == Schema.DisplayType.Currency) { + obj.put(key, String.valueOf(fieldMap.get(key)) == '' ? null : Decimal.valueOf((String)fieldMap.get(key))); + } else if (targetFields.get(key).getDescribe().getType() == Schema.DisplayType.Double) { + obj.put(key, String.valueOf(fieldMap.get(key)) == '' ? null : Double.valueOf(fieldMap.get(key))); + } else if (targetFields.get(key).getDescribe().getType() == Schema.DisplayType.Integer) { + obj.put(key, Integer.valueOf(fieldMap.get(key))); + } else { + obj.put(key, fieldMap.get(key)); + } } } catch (SObjectException soe) { return '[{"message":"'+soe.getMessage()+'","errorCode":"INVALID_FIELD"}]'; From e30e6373e2a841a925cfe6c00a905b6ca057c885 Mon Sep 17 00:00:00 2001 From: Jared Pearson Date: Tue, 5 Mar 2013 16:13:22 -0500 Subject: [PATCH 27/60] Added support for custom domains --- forcetk.js | 17 +++++++++++++---- 1 file changed, 13 insertions(+), 4 deletions(-) diff --git a/forcetk.js b/forcetk.js index 414bc49..34d6f6a 100644 --- a/forcetk.js +++ b/forcetk.js @@ -126,11 +126,20 @@ if (forcetk.Client === undefined) { this.apiVersion = (typeof apiVersion === 'undefined' || apiVersion === null) ? 'v24.0': apiVersion; if (typeof instanceUrl === 'undefined' || instanceUrl == null) { - // location.hostname can be of the form 'abc.na1.visual.force.com' or - // 'na1.salesforce.com'. Split on '.', and take the [1] or [0] element - // as appropriate + // location.hostname can be of the form 'abc.na1.visual.force.com', + // 'na1.salesforce.com' or 'abc.my.salesforce.com' (custom domains). + // Split on '.', and take the [1] or [0] element as appropriate var elements = location.hostname.split("."); - var instance = (elements.length == 3) ? elements[0] : elements[1]; + + var instance = null; + if(elements.length == 4 && elements[1] === 'my') { + instance = elements[0] + '.' + elements[1]; + } else if(elements.length == 3){ + instance = elements[0]; + } else { + instance = elements[1]; + } + this.instanceUrl = "https://" + instance + ".salesforce.com"; } else { this.instanceUrl = instanceUrl; From c943383f5623176706187c8cfb078e9913aeb7dc Mon Sep 17 00:00:00 2001 From: Nikita Yaroshevich Date: Mon, 11 Mar 2013 11:48:04 -0700 Subject: [PATCH 28/60] Added JQuery deferred objects support. Updating to return promises --- forcetk.js | 30 +++++++++++++++--------------- 1 file changed, 15 insertions(+), 15 deletions(-) diff --git a/forcetk.js b/forcetk.js index 34d6f6a..8ec2e93 100644 --- a/forcetk.js +++ b/forcetk.js @@ -96,7 +96,7 @@ if (forcetk.Client === undefined) { forcetk.Client.prototype.refreshAccessToken = function(callback, error) { var that = this; var url = this.loginUrl + '/services/oauth2/token'; - $j.ajax({ + return $j.ajax({ type: 'POST', url: (this.proxyUrl !== null) ? this.proxyUrl: url, cache: false, @@ -158,7 +158,7 @@ if (forcetk.Client === undefined) { var that = this; var url = this.instanceUrl + '/services/data' + path; - $j.ajax({ + return $j.ajax({ type: method || "GET", async: this.asyncAjax, url: (this.proxyUrl !== null) ? this.proxyUrl: url, @@ -265,7 +265,7 @@ if (forcetk.Client === undefined) { var that = this; var url = this.instanceUrl + '/services/apexrest' + path; - $j.ajax({ + return $j.ajax({ type: method || "GET", async: this.asyncAjax, url: (this.proxyUrl !== null) ? this.proxyUrl: url, @@ -312,7 +312,7 @@ if (forcetk.Client === undefined) { * @param [error=null] function to which jqXHR will be passed in case of error */ forcetk.Client.prototype.versions = function(callback, error) { - this.ajax('/', callback, error); + return this.ajax('/', callback, error); } /* @@ -322,7 +322,7 @@ if (forcetk.Client === undefined) { * @param [error=null] function to which jqXHR will be passed in case of error */ forcetk.Client.prototype.resources = function(callback, error) { - this.ajax('/' + this.apiVersion + '/', callback, error); + return this.ajax('/' + this.apiVersion + '/', callback, error); } /* @@ -332,7 +332,7 @@ if (forcetk.Client === undefined) { * @param [error=null] function to which jqXHR will be passed in case of error */ forcetk.Client.prototype.describeGlobal = function(callback, error) { - this.ajax('/' + this.apiVersion + '/sobjects/', callback, error); + return this.ajax('/' + this.apiVersion + '/sobjects/', callback, error); } /* @@ -342,7 +342,7 @@ if (forcetk.Client === undefined) { * @param [error=null] function to which jqXHR will be passed in case of error */ forcetk.Client.prototype.metadata = function(objtype, callback, error) { - this.ajax('/' + this.apiVersion + '/sobjects/' + objtype + '/' + return this.ajax('/' + this.apiVersion + '/sobjects/' + objtype + '/' , callback, error); } @@ -354,7 +354,7 @@ if (forcetk.Client === undefined) { * @param [error=null] function to which jqXHR will be passed in case of error */ forcetk.Client.prototype.describe = function(objtype, callback, error) { - this.ajax('/' + this.apiVersion + '/sobjects/' + objtype + return this.ajax('/' + this.apiVersion + '/sobjects/' + objtype + '/describe/', callback, error); } @@ -368,7 +368,7 @@ if (forcetk.Client === undefined) { * @param [error=null] function to which jqXHR will be passed in case of error */ forcetk.Client.prototype.create = function(objtype, fields, callback, error) { - this.ajax('/' + this.apiVersion + '/sobjects/' + objtype + '/' + return this.ajax('/' + this.apiVersion + '/sobjects/' + objtype + '/' , callback, error, "POST", JSON.stringify(fields)); } @@ -405,7 +405,7 @@ if (forcetk.Client === undefined) { * @param [error=null] function to which jqXHR will be passed in case of error */ forcetk.Client.prototype.upsert = function(objtype, externalIdField, externalId, fields, callback, error) { - this.ajax('/' + this.apiVersion + '/sobjects/' + objtype + '/' + externalIdField + '/' + externalId + return this.ajax('/' + this.apiVersion + '/sobjects/' + objtype + '/' + externalIdField + '/' + externalId + '?_HttpMethod=PATCH', callback, error, "POST", JSON.stringify(fields)); } @@ -420,7 +420,7 @@ if (forcetk.Client === undefined) { * @param [error=null] function to which jqXHR will be passed in case of error */ forcetk.Client.prototype.update = function(objtype, id, fields, callback, error) { - this.ajax('/' + this.apiVersion + '/sobjects/' + objtype + '/' + id + return this.ajax('/' + this.apiVersion + '/sobjects/' + objtype + '/' + id + '?_HttpMethod=PATCH', callback, error, "POST", JSON.stringify(fields)); } @@ -433,7 +433,7 @@ if (forcetk.Client === undefined) { * @param [error=null] function to which jqXHR will be passed in case of error */ forcetk.Client.prototype.del = function(objtype, id, callback, error) { - this.ajax('/' + this.apiVersion + '/sobjects/' + objtype + '/' + id + return this.ajax('/' + this.apiVersion + '/sobjects/' + objtype + '/' + id , callback, error, "DELETE"); } @@ -445,7 +445,7 @@ if (forcetk.Client === undefined) { * @param [error=null] function to which jqXHR will be passed in case of error */ forcetk.Client.prototype.query = function(soql, callback, error) { - this.ajax('/' + this.apiVersion + '/query?q=' + escape(soql) + return this.ajax('/' + this.apiVersion + '/query?q=' + escape(soql) , callback, error); } @@ -470,7 +470,7 @@ if (forcetk.Client === undefined) { //-- leave alone } - this.ajax( url, callback, error ); + return this.ajax( url, callback, error ); } /* @@ -481,7 +481,7 @@ if (forcetk.Client === undefined) { * @param [error=null] function to which jqXHR will be passed in case of error */ forcetk.Client.prototype.search = function(sosl, callback, error) { - this.ajax('/' + this.apiVersion + '/search?q=' + escape(sosl) + return this.ajax('/' + this.apiVersion + '/search?q=' + escape(sosl) , callback, error); } } \ No newline at end of file From 99242ec7f64e48bbab1aa839deb3f9e0c7eca481 Mon Sep 17 00:00:00 2001 From: Pat Patterson Date: Tue, 12 Mar 2013 22:18:55 -0700 Subject: [PATCH 29/60] Added upsert --- README.markdown | 2 +- RemoteTK.component | 10 ++++------ RemoteTKController.cls | 4 +--- 3 files changed, 6 insertions(+), 10 deletions(-) diff --git a/README.markdown b/README.markdown index d9b271d..92877d2 100644 --- a/README.markdown +++ b/README.markdown @@ -8,7 +8,7 @@ Background Due to the [same origin policy](http://en.wikipedia.org/wiki/Same_origin_policy), JavaScript running in Visualforce pages may not use [XmlHttpRequest](http://en.wikipedia.org/wiki/XMLHttpRequest) to directly invoke the REST API, since Visualforce pages have hostnames of the form abc.na1.visual.force.com, and the REST API endpoints are of the form na1.salesforce.com. -The RemoteTK Visualforce Custom Component (comprising RemoteTK.component and RemoteTKController.cls) provides an abstraction very similar to the REST API, implemented via `@RemoteAction` methods in the component's controller. The advantage of this mechanism is that no API calls are consumed. A disadvantage is that upsert is not currently implemented. +The RemoteTK Visualforce Custom Component (comprising RemoteTK.component and RemoteTKController.cls) provides an abstraction very similar to the REST API, implemented via `@RemoteAction` methods in the component's controller. The advantage of this mechanism is that no API calls are consumed. Alternatively, the ForceTK JavaScript library works around the same origin restriction by using the [AJAX Proxy](http://www.salesforce.com/us/developer/docs/ajax/Content/sforce_api_ajax_queryresultiterator.htm#ajax_proxy) to give full access to the REST API. Since the AJAX proxy is present on all Visualforce hosts with an endpoint of the form https://abc.na1.visual.force.com/services/proxy, our Visualforce-hosted JavaScript can invoke it, passing the desired resource URL in an HTTP header. A drawback here is that using the REST API, even from a Visualforce page, consumes API calls. diff --git a/RemoteTK.component b/RemoteTK.component index 82a9287..071114a 100644 --- a/RemoteTK.component +++ b/RemoteTK.component @@ -83,7 +83,7 @@ if (remotetk.Client === undefined) { * Creates a new record of the given type. * @param objtype object type; e.g. "Account" * @param fields an object containing initial field names and values for - * the record, e.g. {:Name "salesforce.com", :TickerSymbol + * the record, e.g. {Name: "salesforce.com", TickerSymbol: * "CRM"} * @param callback function to which response will be passed * @param [error=null] function to which jqXHR will be passed in case of error @@ -113,19 +113,18 @@ if (remotetk.Client === undefined) { }); } - /* NOT YET IMPLEMENTED!!! + /* * Upsert - creates or updates record of the given type, based on the * given external Id. * @param objtype object type; e.g. "Account" * @param externalIdField external ID field name; e.g. "accountMaster__c" * @param externalId the record's external ID value * @param fields an object containing field names and values for - * the record, e.g. {:Name "salesforce.com", :TickerSymbol + * the record, e.g. {Name: "salesforce.com", TickerSymbol: * "CRM"} * @param callback function to which response will be passed * @param [error=null] function to which jqXHR will be passed in case of error */ - /* remotetk.Client.prototype.upsert = function(objtype, externalIdField, externalId, fields, callback, error) { Visualforce.remoting.Manager.invokeAction('$RemoteAction.RemoteTKController.upser', objtype, externalIdField, externalId, JSON.stringify(fields), function(result){ handleResult(result, callback, error, true); @@ -133,14 +132,13 @@ if (remotetk.Client === undefined) { escape: false }); } - */ /* * Updates field values on a record of the given type. * @param objtype object type; e.g. "Account" * @param id the record's object ID * @param fields an object containing initial field names and values for - * the record, e.g. {:Name "salesforce.com", :TickerSymbol + * the record, e.g. {Name: "salesforce.com", TickerSymbol: * "CRM"} * @param callback function to which response will be passed * @param [error=null] function to which jqXHR will be passed in case of error diff --git a/RemoteTKController.cls b/RemoteTKController.cls index 5fcd004..394473e 100644 --- a/RemoteTKController.cls +++ b/RemoteTKController.cls @@ -145,7 +145,6 @@ public class RemoteTKController { return JSON.serialize(records[0]); } - /* @remoteAction public static String upser(String objtype, String externalIdField, String externalId, String fields) { Schema.SObjectType targetType = Schema.getGlobalDescribe().get(objtype); @@ -161,11 +160,10 @@ public class RemoteTKController { Schema.SObjectField sobjField = targetType.getDescribe().fields.getMap().get(externalIdField); - // Database.Upsert(obj, sobjField); // error - upsert requires a concrete sobject type + Database.Upsert(obj, sobjField); return null; } - */ @remoteAction public static String updat(String objtype, String id, String fields) { From eb51ef33b209df8c6583ad3c68a67359c55de5b2 Mon Sep 17 00:00:00 2001 From: Pat Patterson Date: Thu, 21 Mar 2013 13:05:58 -0700 Subject: [PATCH 30/60] Added tests for RemoteTKController.cls --- .gitignore | 1 + RemoteTKController.cls | 54 ++++++-- TestRemoteTKController.cls | 277 +++++++++++++++++++++++++++++++++++++ 3 files changed, 318 insertions(+), 14 deletions(-) create mode 100644 .gitignore create mode 100644 TestRemoteTKController.cls diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..e43b0f9 --- /dev/null +++ b/.gitignore @@ -0,0 +1 @@ +.DS_Store diff --git a/RemoteTKController.cls b/RemoteTKController.cls index 394473e..c39cff5 100644 --- a/RemoteTKController.cls +++ b/RemoteTKController.cls @@ -25,12 +25,24 @@ */ public class RemoteTKController { + private static String makeError(String message, String errorCode) { + JSONGenerator gen = JSON.createGenerator(false); + gen.writeStartArray(); + gen.writeStartObject(); + gen.writeStringField('message', message); + gen.writeStringField('errorCode', errorCode); + gen.writeEndObject(); + gen.writeEndArray(); + + return gen.getAsString(); + } + @remoteAction public static String describe(String objtype) { // Just enough to make the sample app work! Schema.SObjectType targetType = Schema.getGlobalDescribe().get(objtype); if (targetType == null) { - return '[{"message":"The requested resource does not exist","errorCode":"NOT_FOUND"}]'; + return makeError('The requested resource does not exist', 'NOT_FOUND'); } Schema.DescribeSObjectResult sobjResult = targetType.getDescribe(); @@ -65,9 +77,8 @@ public class RemoteTKController { @remoteAction public static String create(String objtype, String fields) { Schema.SObjectType targetType = Schema.getGlobalDescribe().get(objtype); - Map targetFields = targetType.getDescribe().fields.getMap(); if (targetType == null) { - return '[{"message":"The requested resource does not exist","errorCode":"NOT_FOUND"}]'; + return makeError('The requested resource does not exist', 'NOT_FOUND'); } SObject obj = targetType.newSObject(); @@ -76,11 +87,17 @@ public class RemoteTKController { try { fieldMap = (Map)JSON.deserializeUntyped(fields); } catch (JSONException je) { - return '[{"message":"'+je.getMessage()+'","errorCode":"JSON_PARSER_ERROR"}]'; + return makeError(je.getMessage(), 'JSON_PARSER_ERROR'); } + Map targetFields = targetType.getDescribe().fields.getMap(); + try { for (String key : fieldMap.keySet()) { + if (targetFields.get(key) == null) { + return '[{"message":"Field '+key+' does not exist on object type '+objtype+'","errorCode":"INVALID_FIELD"}]'; + } + if (targetFields.get(key).getDescribe().getType() == Schema.DisplayType.Date) { obj.put(key, Date.valueOf((String)fieldMap.get(key))); } else if (targetFields.get(key).getDescribe().getType() == Schema.DisplayType.Percent || @@ -95,7 +112,7 @@ public class RemoteTKController { } } } catch (SObjectException soe) { - return '[{"message":"'+soe.getMessage()+'","errorCode":"INVALID_FIELD"}]'; + return makeError(soe.getMessage(), 'INVALID_FIELD'); } try { @@ -139,7 +156,7 @@ public class RemoteTKController { try { records = Database.query(soql); } catch (QueryException qe) { - return '[{"message":"'+qe.getMessage()+'","errorCode":"INVALID_QUERY"}]'; + return makeError(qe.getMessage(), 'INVALID_QUERY'); } return JSON.serialize(records[0]); @@ -148,14 +165,21 @@ public class RemoteTKController { @remoteAction public static String upser(String objtype, String externalIdField, String externalId, String fields) { Schema.SObjectType targetType = Schema.getGlobalDescribe().get(objtype); + if (targetType == null) { + return makeError('The requested resource does not exist', 'NOT_FOUND'); + } SObject obj = targetType.newSObject(); obj.put(externalIdField, externalId); Map fieldMap = (Map)JSON.deserializeUntyped(fields); - for (String key : fieldMap.keySet()) { - obj.put(key, fieldMap.get(key)); + try { + for (String key : fieldMap.keySet()) { + obj.put(key, fieldMap.get(key)); + } + } catch (SObjectException soe) { + return makeError(soe.getMessage(), 'INVALID_FIELD'); } Schema.SObjectField sobjField = targetType.getDescribe().fields.getMap().get(externalIdField); @@ -169,7 +193,7 @@ public class RemoteTKController { public static String updat(String objtype, String id, String fields) { Schema.SObjectType targetType = Schema.getGlobalDescribe().get(objtype); if (targetType == null) { - return '[{"message":"The requested resource does not exist","errorCode":"NOT_FOUND"}]'; + return makeError('The requested resource does not exist', 'NOT_FOUND'); } SObject obj = targetType.newSObject(id); @@ -178,7 +202,7 @@ public class RemoteTKController { try { fieldMap = (Map)JSON.deserializeUntyped(fields); } catch (JSONException je) { - return '[{"message":"'+je.getMessage()+'","errorCode":"JSON_PARSER_ERROR"}]'; + return makeError(je.getMessage(), 'JSON_PARSER_ERROR'); } try { @@ -186,7 +210,7 @@ public class RemoteTKController { obj.put(key, fieldMap.get(key)); } } catch (SObjectException soe) { - return '[{"message":"'+soe.getMessage()+'","errorCode":"INVALID_FIELD"}]'; + return makeError(soe.getMessage(), 'INVALID_FIELD'); } try { @@ -209,7 +233,7 @@ public class RemoteTKController { public static String del(String objtype, String id) { Schema.SObjectType targetType = Schema.getGlobalDescribe().get(objtype); if (targetType == null) { - return '[{"message":"The requested resource does not exist","errorCode":"NOT_FOUND"}]'; + return makeError('The requested resource does not exist', 'NOT_FOUND'); } SObject obj = targetType.newSObject(id); @@ -236,7 +260,7 @@ public class RemoteTKController { try { records = Database.query(soql); } catch (QueryException qe) { - return '[{"message":"'+qe.getMessage()+'","errorCode":"INVALID_QUERY"}]'; + return makeError(qe.getMessage(), 'INVALID_QUERY'); } Map result = new Map(); @@ -252,8 +276,10 @@ public class RemoteTKController { List> result; try { result = Search.query(sosl); + } catch (QueryException qe) { + return makeError(qe.getMessage(), 'INVALID_SEARCH'); } catch (SearchException se) { - return '[{"message":"'+se.getMessage()+'","errorCode":"INVALID_SEARCH"}]'; + return makeError(se.getMessage(), 'INVALID_SEARCH'); } return JSON.serialize(result); diff --git a/TestRemoteTKController.cls b/TestRemoteTKController.cls new file mode 100644 index 0000000..b8ee2cf --- /dev/null +++ b/TestRemoteTKController.cls @@ -0,0 +1,277 @@ +@isTest +public class TestRemoteTKController{ + private static String tooLongAccName = 'LOTS OF '+ + 'CHARACTERS XXXXXXXXXXXXXXXXXXXXXXXX'+ + 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'+ + 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'+ + 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'+ + 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'+ + 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'+ + 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'+ + 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'+ + 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'+ + 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'+ + 'XXXXXXXXXXXXXXXX'; + + static private void assertError(String jsonResult, String expectedError, String method) { + List errorArray = (List)JSON.deserializeUntyped(jsonResult); + + System.assertNotEquals(null, errorArray, + 'error array missing from '+method+' result'); + System.assertNotEquals(0, errorArray.size(), + 'error array is empty in '+method+' result'); + + Map error = (Map)errorArray[0]; + String errorCode = (String)error.get('errorCode'); + System.assertNotEquals(null, errorCode, + 'errorCode property missing from '+method+' result'); + System.assertEquals(expectedError, errorCode, + 'errorCode should be '+expectedError+' in '+method+' result'); + } + + static testMethod void testDescribe() { + // Assume we have accounts + String jsonResult = RemoteTKController.describe('Account'); + + System.assertNotEquals(null, jsonResult, + 'RemoteTKController.describe returned null'); + + Map result = (Map)JSON.deserializeUntyped(jsonResult); + + System.assertNotEquals(null, result.get('fields'), + 'fields property missing from RemoteTKController.describe result'); + + // TODO - more assertions on describe results + + // Invalid object type + // Hope there isn't a QXZXQZXZQXZQ object type! + jsonResult = RemoteTKController.describe('QXZXQZXZQXZQ'); + assertError(jsonResult, 'NOT_FOUND', 'RemoteTKController.describe'); + } + + static private void assertRecord(Map record, String accName, String accNumber, String method) { + Map attributes = (Map)record.get('attributes'); + System.assertNotEquals(null, attributes, + 'attributes property missing from '+method+' result'); + System.assertNotEquals(0, attributes.keySet().size(), + 'empty attributes object in '+method+' result'); + + String type = (String)attributes.get('type'); + System.assertNotEquals(null, type, + 'type property missing from '+method+' result'); + System.assertEquals('Account', type, + 'Wrong type in '+method+' result'); + + String url = (String)attributes.get('url'); + System.assertNotEquals(null, url, + 'url property missing from '+method+' result'); + + Id id = (Id)record.get('Id'); + System.assertNotEquals(null, id, + 'Id property missing from '+method+' result'); + Account account = [SELECT Id, Name FROM Account WHERE Id = :id LIMIT 1]; + System.assertNotEquals(null, account, + 'Couldn\'t find account record identified by '+method+' result'); + System.assertEquals(accName, account.Name, + 'Account name doesn\'t match in '+method+' result'); + + String name = (String)record.get('Name'); + System.assertNotEquals(null, name, + 'Name property missing from '+method+' result'); + System.assertEquals(accName, name, + 'Wrong account name in '+method+' result'); + + String accountNumber = (String)record.get('AccountNumber'); + System.assertNotEquals(null, name, + 'AccountNumber property missing from '+method+' result'); + System.assertEquals(accNumber, accountNumber, + 'Wrong account number in '+method+' result'); + } + + static private Id testCreate(String accName, String accNumber) { + // Assume we can create an account + String jsonResult = RemoteTKController.create('Account', '{"Name": "'+accName+'", "AccountNumber" : "'+accNumber+'"}'); + + System.assertNotEquals(null, jsonResult, + 'RemoteTKController.create returned null'); + + Map result = (Map)JSON.deserializeUntyped(jsonResult); + + Boolean success = (Boolean)result.get('success'); + System.assertNotEquals(null, success, + 'success property missing from RemoteTKController.create result'); + System.assertNotEquals(false, success, + 'success is false in RemoteTKController.create result'); + + List errors = (List)result.get('errors'); + System.assertNotEquals(null, errors, + 'errors property missing from RemoteTKController.create result'); + System.assertEquals(0, errors.size(), + 'errors array is not empty in RemoteTKController.create result'); + + Id id = (Id)result.get('id'); + System.assertNotEquals(null, id, + 'id property missing from RemoteTKController.create result'); + Account account = [SELECT Id, Name, AccountNumber FROM Account LIMIT 1]; + System.assertNotEquals(null, account, + 'Couldn\'t find account record created by RemoteTKController.create result'); + System.assertEquals(accName, account.Name, + 'Account name doesn\'t match in RemoteTKController.create result'); + System.assertEquals(accNumber, account.AccountNumber, + 'Account number doesn\'t match in RemoteTKController.create result'); + + jsonResult = RemoteTKController.create('QXZXQZXZQXZQ', '{"Name": "'+accName+'"}'); + assertError(jsonResult, 'NOT_FOUND', 'RemoteTKController.create'); + + jsonResult = RemoteTKController.create('Account', '{"Name" "'+accName+'"}'); + assertError(jsonResult, 'JSON_PARSER_ERROR', 'RemoteTKController.create'); + + jsonResult = RemoteTKController.create('Account', '{"XQZXQZXQZXQZ" : "'+accName+'"}'); + assertError(jsonResult, 'INVALID_FIELD', 'RemoteTKController.create'); + + jsonResult = RemoteTKController.create('Account', '{"Name" : "'+tooLongAccName+'"}'); + assertError(jsonResult, 'STRING_TOO_LONG', 'RemoteTKController.create'); + + return id; + } + + static private void testRetrieve(String accName, String accNumber, Id id) { + String jsonResult = RemoteTKController.retrieve('Account', id, 'Name, AccountNumber'); + + System.assertNotEquals(null, jsonResult, + 'RemoteTKController.retrieve returned null'); + + Map result = (Map)JSON.deserializeUntyped(jsonResult); + + assertRecord(result, accName, accNumber, 'RemoteTKController.retrieve'); + + // TODO - test negative paths for retrieve + } + + static private void testQuery(String accName, String accNumber) { + String jsonResult = RemoteTKController.query('SELECT Id, Name, AccountNumber FROM Account WHERE Name = \''+accName+'\''); + + System.assertNotEquals(null, jsonResult, + 'RemoteTKController.query returned null'); + + Map result = (Map)JSON.deserializeUntyped(jsonResult); + + List records = (List)result.get('records'); + System.assertNotEquals(null, records, + 'records property missing from RemoteTKController.query result'); + System.assertEquals(1, records.size(), + 'records array should have single record in RemoteTKController.query result'); + + Map record = (Map)records[0]; + + assertRecord(record, accName, accNumber, 'RemoteTKController.query'); + + Integer totalSize = (Integer)result.get('totalSize'); + System.assertNotEquals(null, totalSize, + 'totalSize property missing from RemoteTKController.query result'); + System.assertEquals(1, totalSize, + 'totalSize should be 1 in RemoteTKController.query result'); + + Boolean done = (Boolean)result.get('done'); + System.assertNotEquals(null, done, + 'done property missing from RemoteTKController.query result'); + System.assertEquals(true, done, + 'done should be true in RemoteTKController.query result'); + + jsonResult = RemoteTKController.query('SSSSSS Id, Name FROM Account WHERE Name = \''+accName+'\''); + assertError(jsonResult, 'INVALID_QUERY', 'RemoteTKController.query'); + } + + static private void testSearch(String accName, String accNumber, Id id) { + Id [] fixedSearchResults= new Id[1]; + fixedSearchResults[0] = id; + Test.setFixedSearchResults(fixedSearchResults); + String jsonResult = RemoteTKController.search('FIND {'+accName+'} IN ALL FIELDS RETURNING Account (Id, Name, AccountNumber)'); + + System.assertNotEquals(null, jsonResult, + 'RemoteTKController.search returned null'); + + List result = (List)JSON.deserializeUntyped(jsonResult); + + List records = (List)result[0]; + + Map record = (Map)records[0]; + + assertRecord(record, accName, accNumber, 'RemoteTKController.search'); + + jsonResult = RemoteTKController.search('FFFF {'+accName+'} IN ALL FIELDS RETURNING Account (Id, Name)'); + assertError(jsonResult, 'INVALID_SEARCH', 'RemoteTKController.search'); + } + + static private void testUpdate(String accName, String accNumber, Id id) { + String jsonResult = RemoteTKController.updat('Account', id, '{"Name":"'+accName+'1", "AccountNumber":"'+accNumber+'1"}'); + System.assertEquals(null, jsonResult, + 'Non-null result from RemoteTKController.updat'); + Account account = [SELECT Id, Name, AccountNumber FROM Account WHERE Id = :id LIMIT 1]; + System.assertNotEquals(null, account, + 'Couldn\'t find account record after RemoteTKController.updat'); + System.assertEquals(accName+'1', account.Name, + 'Account name doesn\'t match after RemoteTKController.updat'); + System.assertEquals(accNumber+'1', account.AccountNumber, + 'Account number doesn\'t match after RemoteTKController.updat'); + + jsonResult = RemoteTKController.updat('QXZXQZXZQXZQ', id, '{"Name":"'+accName+'1"}'); + assertError(jsonResult, 'NOT_FOUND', 'RemoteTKController.updat'); + + jsonResult = RemoteTKController.updat('Account', id, '{"XQZXQZXQZXQZ" : "'+accName+'1"}'); + assertError(jsonResult, 'INVALID_FIELD', 'RemoteTKController.updat'); + + jsonResult = RemoteTKController.updat('Account', id, '{"Name" "'+accName+'"}'); + assertError(jsonResult, 'JSON_PARSER_ERROR', 'RemoteTKController.updat'); + + jsonResult = RemoteTKController.updat('Account', id, '{"Name" : "'+tooLongAccName+'"}'); + assertError(jsonResult, 'STRING_TOO_LONG', 'RemoteTKController.updat'); + } + + static private void testUpsert(String accName, String accNumber, Id id) { + String jsonResult = RemoteTKController.upser('Account', 'Id', (String)id, '{"Name":"'+accName+'2", "AccountNumber":"'+accNumber+'2"}'); + System.assertEquals(null, jsonResult, + 'Non-null result from RemoteTKController.upser'); + Account account = [SELECT Id, Name, AccountNumber FROM Account WHERE Id = :id LIMIT 1]; + System.assertNotEquals(null, account, + 'Couldn\'t find account record after RemoteTKController.upser'); + System.assertEquals(accName+'2', account.Name, + 'Account name doesn\'t match after RemoteTKController.upser'); + System.assertEquals(accNumber+'2', account.AccountNumber, + 'Account number doesn\'t match after RemoteTKController.upser'); + + jsonResult = RemoteTKController.upser('QXZXQZXZQXZQ', 'Id', (String)id, '{"Name":"'+accName+'2"}'); + assertError(jsonResult, 'NOT_FOUND', 'RemoteTKController.upser'); + + jsonResult = RemoteTKController.upser('Account', 'Id', (String)id, '{"XQZXQZXQZXQZ" : "'+accName+'2"}'); + assertError(jsonResult, 'INVALID_FIELD', 'RemoteTKController.upser'); + } + + static private void testDelete(Id id) { + String jsonResult = RemoteTKController.del('QXZXQZXZQXZQ', id); + assertError(jsonResult, 'NOT_FOUND', 'RemoteTKController.del'); + + jsonResult = RemoteTKController.del('Account', id); + System.assertEquals(null, jsonResult, + 'Non-null result from RemoteTKController.del'); + List accounts = [SELECT Id, Name FROM Account WHERE Id = :id]; + System.assertEquals(0, accounts.size(), + 'Account record was not deleted by RemoteTKController.del'); + + jsonResult = RemoteTKController.del('Account', id); + assertError(jsonResult, 'ENTITY_IS_DELETED', 'RemoteTKController.del'); + } + + static testMethod void testCRUD() { + String accName = 'Test1'; + String accNumber = '1234'; + + Id id = testCreate(accName, accNumber); + testRetrieve(accName, accNumber, id); + testQuery(accName, accNumber); + testSearch(accName, accNumber, id); + testUpdate(accName, accNumber, id); + testUpsert(accName, accNumber, id); + testDelete(id); + } +} \ No newline at end of file From 971566b58a92470c33f552a54dff61f785c0ea2a Mon Sep 17 00:00:00 2001 From: Raja Rao DV Date: Fri, 29 Mar 2013 13:52:22 -0700 Subject: [PATCH 31/60] fix arguments check in client.retrieve --- forcetk.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/forcetk.js b/forcetk.js index 8ec2e93..d19c885 100644 --- a/forcetk.js +++ b/forcetk.js @@ -382,7 +382,7 @@ if (forcetk.Client === undefined) { * @param [error=null] function to which jqXHR will be passed in case of error */ forcetk.Client.prototype.retrieve = function(objtype, id, fieldlist, callback, error) { - if (!arguments[4]) { + if (arguments.length == 4) { error = callback; callback = fieldlist; fieldlist = null; From be5cdd4cac41cb6418adc603fe658c77c96d781d Mon Sep 17 00:00:00 2001 From: Pat Patterson Date: Tue, 16 Apr 2013 22:20:50 -0700 Subject: [PATCH 32/60] Accept String or correctly typed arguments in create, update, upsert. Fixes #33 --- RemoteTKController.cls | 113 ++++++++++++++++++++----------------- TestRemoteTKController.cls | 63 +++++++++++++++------ 2 files changed, 106 insertions(+), 70 deletions(-) diff --git a/RemoteTKController.cls b/RemoteTKController.cls index c39cff5..859cd3a 100644 --- a/RemoteTKController.cls +++ b/RemoteTKController.cls @@ -37,6 +37,55 @@ public class RemoteTKController { return gen.getAsString(); } + private static String writeFields(String objtype, SObject obj, String fields) { + Map fieldMap = null; + try { + fieldMap = (Map)JSON.deserializeUntyped(fields); + } catch (JSONException je) { + return makeError(je.getMessage(), 'JSON_PARSER_ERROR'); + } + + Schema.SObjectType targetType = Schema.getGlobalDescribe().get(objtype); + + Map targetFields = targetType.getDescribe().fields.getMap(); + + try { + for (String key : fieldMap.keySet()) { + if (targetFields.get(key) == null) { + return '[{"message":"Field '+key+' does not exist on object type '+objtype+'","errorCode":"INVALID_FIELD"}]'; + } + + Object value = fieldMap.get(key); + Schema.DisplayType valueType = targetFields.get(key).getDescribe().getType(); + + if (value instanceof String && valueType != Schema.DisplayType.String) { + // Coerce an incoming String to the correct type + String svalue = (String)value; + + if (valueType == Schema.DisplayType.Date) { + obj.put(key, Date.valueOf(svalue)); + } else if (valueType == Schema.DisplayType.Percent || + valueType == Schema.DisplayType.Currency) { + obj.put(key, svalue == '' ? null : Decimal.valueOf(svalue)); + } else if (valueType == Schema.DisplayType.Double) { + obj.put(key, svalue == '' ? null : Double.valueOf(svalue)); + } else if (valueType == Schema.DisplayType.Integer) { + obj.put(key, Integer.valueOf(svalue)); + } else { + obj.put(key, svalue); + } + } else { + // Just try putting the incoming value on the object + obj.put(key, value); + } + } + } catch (SObjectException soe) { + return makeError(soe.getMessage(), 'INVALID_FIELD'); + } + + return null; + } + @remoteAction public static String describe(String objtype) { // Just enough to make the sample app work! @@ -82,39 +131,12 @@ public class RemoteTKController { } SObject obj = targetType.newSObject(); - - Map fieldMap = null; - try { - fieldMap = (Map)JSON.deserializeUntyped(fields); - } catch (JSONException je) { - return makeError(je.getMessage(), 'JSON_PARSER_ERROR'); - } - - Map targetFields = targetType.getDescribe().fields.getMap(); - - try { - for (String key : fieldMap.keySet()) { - if (targetFields.get(key) == null) { - return '[{"message":"Field '+key+' does not exist on object type '+objtype+'","errorCode":"INVALID_FIELD"}]'; - } - - if (targetFields.get(key).getDescribe().getType() == Schema.DisplayType.Date) { - obj.put(key, Date.valueOf((String)fieldMap.get(key))); - } else if (targetFields.get(key).getDescribe().getType() == Schema.DisplayType.Percent || - targetFields.get(key).getDescribe().getType() == Schema.DisplayType.Currency) { - obj.put(key, String.valueOf(fieldMap.get(key)) == '' ? null : Decimal.valueOf((String)fieldMap.get(key))); - } else if (targetFields.get(key).getDescribe().getType() == Schema.DisplayType.Double) { - obj.put(key, String.valueOf(fieldMap.get(key)) == '' ? null : Double.valueOf(fieldMap.get(key))); - } else if (targetFields.get(key).getDescribe().getType() == Schema.DisplayType.Integer) { - obj.put(key, Integer.valueOf(fieldMap.get(key))); - } else { - obj.put(key, fieldMap.get(key)); - } - } - } catch (SObjectException soe) { - return makeError(soe.getMessage(), 'INVALID_FIELD'); + + String error = writeFields(objType, obj, fields); + if (error != null) { + return error; } - + try { insert obj; } catch (DMLException dmle) { @@ -172,14 +194,9 @@ public class RemoteTKController { SObject obj = targetType.newSObject(); obj.put(externalIdField, externalId); - Map fieldMap = - (Map)JSON.deserializeUntyped(fields); - try { - for (String key : fieldMap.keySet()) { - obj.put(key, fieldMap.get(key)); - } - } catch (SObjectException soe) { - return makeError(soe.getMessage(), 'INVALID_FIELD'); + String error = writeFields(objType, obj, fields); + if (error != null) { + return error; } Schema.SObjectField sobjField = targetType.getDescribe().fields.getMap().get(externalIdField); @@ -198,21 +215,11 @@ public class RemoteTKController { SObject obj = targetType.newSObject(id); - Map fieldMap = null; - try { - fieldMap = (Map)JSON.deserializeUntyped(fields); - } catch (JSONException je) { - return makeError(je.getMessage(), 'JSON_PARSER_ERROR'); + String error = writeFields(objType, obj, fields); + if (error != null) { + return error; } - try { - for (String key : fieldMap.keySet()) { - obj.put(key, fieldMap.get(key)); - } - } catch (SObjectException soe) { - return makeError(soe.getMessage(), 'INVALID_FIELD'); - } - try { update obj; } catch (DMLException dmle) { diff --git a/TestRemoteTKController.cls b/TestRemoteTKController.cls index b8ee2cf..daade25 100644 --- a/TestRemoteTKController.cls +++ b/TestRemoteTKController.cls @@ -88,9 +88,14 @@ public class TestRemoteTKController{ 'Wrong account number in '+method+' result'); } - static private Id testCreate(String accName, String accNumber) { + static private Id testCreate(String accName, String accNumber, String fields) { // Assume we can create an account - String jsonResult = RemoteTKController.create('Account', '{"Name": "'+accName+'", "AccountNumber" : "'+accNumber+'"}'); + + // Try with data in correct types + String jsonResult = RemoteTKController.create('Account', + '{"Name": "'+accName+'", '+ + '"AccountNumber" : "'+accNumber+'",'+ + fields+'}'); System.assertNotEquals(null, jsonResult, 'RemoteTKController.create returned null'); @@ -203,22 +208,22 @@ public class TestRemoteTKController{ assertError(jsonResult, 'INVALID_SEARCH', 'RemoteTKController.search'); } - static private void testUpdate(String accName, String accNumber, Id id) { - String jsonResult = RemoteTKController.updat('Account', id, '{"Name":"'+accName+'1", "AccountNumber":"'+accNumber+'1"}'); + static private void testUpdate(String accName, String accNumber, Id id, String fields) { + String jsonResult = RemoteTKController.updat('Account', id, '{"Name":"'+accName+'", "AccountNumber":"'+accNumber+'"}'); System.assertEquals(null, jsonResult, 'Non-null result from RemoteTKController.updat'); Account account = [SELECT Id, Name, AccountNumber FROM Account WHERE Id = :id LIMIT 1]; System.assertNotEquals(null, account, 'Couldn\'t find account record after RemoteTKController.updat'); - System.assertEquals(accName+'1', account.Name, + System.assertEquals(accName, account.Name, 'Account name doesn\'t match after RemoteTKController.updat'); - System.assertEquals(accNumber+'1', account.AccountNumber, + System.assertEquals(accNumber, account.AccountNumber, 'Account number doesn\'t match after RemoteTKController.updat'); - jsonResult = RemoteTKController.updat('QXZXQZXZQXZQ', id, '{"Name":"'+accName+'1"}'); + jsonResult = RemoteTKController.updat('QXZXQZXZQXZQ', id, '{"Name":"'+accName+'"}'); assertError(jsonResult, 'NOT_FOUND', 'RemoteTKController.updat'); - jsonResult = RemoteTKController.updat('Account', id, '{"XQZXQZXQZXQZ" : "'+accName+'1"}'); + jsonResult = RemoteTKController.updat('Account', id, '{"XQZXQZXQZXQZ" : "'+accName+'"}'); assertError(jsonResult, 'INVALID_FIELD', 'RemoteTKController.updat'); jsonResult = RemoteTKController.updat('Account', id, '{"Name" "'+accName+'"}'); @@ -228,22 +233,27 @@ public class TestRemoteTKController{ assertError(jsonResult, 'STRING_TOO_LONG', 'RemoteTKController.updat'); } - static private void testUpsert(String accName, String accNumber, Id id) { - String jsonResult = RemoteTKController.upser('Account', 'Id', (String)id, '{"Name":"'+accName+'2", "AccountNumber":"'+accNumber+'2"}'); + static private void testUpsert(String accName, String accNumber, Id id, String fields) { + String jsonResult = RemoteTKController.upser('Account', + 'Id', + (String)id, + '{"Name":"'+accName+'", '+ + '"AccountNumber":"'+accNumber+'",'+ + fields+'}'); System.assertEquals(null, jsonResult, 'Non-null result from RemoteTKController.upser'); Account account = [SELECT Id, Name, AccountNumber FROM Account WHERE Id = :id LIMIT 1]; System.assertNotEquals(null, account, 'Couldn\'t find account record after RemoteTKController.upser'); - System.assertEquals(accName+'2', account.Name, + System.assertEquals(accName, account.Name, 'Account name doesn\'t match after RemoteTKController.upser'); - System.assertEquals(accNumber+'2', account.AccountNumber, + System.assertEquals(accNumber, account.AccountNumber, 'Account number doesn\'t match after RemoteTKController.upser'); - jsonResult = RemoteTKController.upser('QXZXQZXZQXZQ', 'Id', (String)id, '{"Name":"'+accName+'2"}'); + jsonResult = RemoteTKController.upser('QXZXQZXZQXZQ', 'Id', (String)id, '{"Name":"'+accName+'"}'); assertError(jsonResult, 'NOT_FOUND', 'RemoteTKController.upser'); - jsonResult = RemoteTKController.upser('Account', 'Id', (String)id, '{"XQZXQZXQZXQZ" : "'+accName+'2"}'); + jsonResult = RemoteTKController.upser('Account', 'Id', (String)id, '{"XQZXQZXQZXQZ" : "'+accName+'"}'); assertError(jsonResult, 'INVALID_FIELD', 'RemoteTKController.upser'); } @@ -266,12 +276,31 @@ public class TestRemoteTKController{ String accName = 'Test1'; String accNumber = '1234'; - Id id = testCreate(accName, accNumber); + // String field values + Id id = testCreate(accName, accNumber, '"AnnualRevenue" : "1000000",'+ + '"NumberOfEmployees" : "1000",'+ + '"Phone" : "(111) 222-3333"'); + testDelete(id); + + // Integer field values + id = testCreate(accName, accNumber, '"AnnualRevenue" : 1000000,'+ + '"NumberOfEmployees" : 1000,'+ + '"Phone" : "(111) 222-3333"'); testRetrieve(accName, accNumber, id); testQuery(accName, accNumber); testSearch(accName, accNumber, id); - testUpdate(accName, accNumber, id); - testUpsert(accName, accNumber, id); + testUpdate(accName+'1', accNumber+'1', id, '"AnnualRevenue" : "1100000",'+ + '"NumberOfEmployees" : "1100",'+ + '"Phone" : "(112) 222-3333"'); + testUpdate(accName+'2', accNumber+'2', id, '"AnnualRevenue" : "2000000",'+ + '"NumberOfEmployees" : "2000",'+ + '"Phone" : "(222) 222-3333"'); + testUpsert(accName+'3', accNumber+'3', id, '"AnnualRevenue" : 3000000,'+ + '"NumberOfEmployees" : 3000,'+ + '"Phone" : "(333) 222-3333"'); + testUpsert(accName+'4', accNumber+'4', id, '"AnnualRevenue" : 4000000,'+ + '"NumberOfEmployees" : 4000,'+ + '"Phone" : "(444) 222-3333"'); testDelete(id); } } \ No newline at end of file From bed85b46b5e0b6ce3f381786151cd1d7329b5bbe Mon Sep 17 00:00:00 2001 From: Raja Rao DV Date: Mon, 29 Apr 2013 16:48:48 -0700 Subject: [PATCH 33/60] dont send contentType for DELETE and update version to v27 --- ___forcetk___js___acyini | 0 forcetk.js | 4 ++-- 2 files changed, 2 insertions(+), 2 deletions(-) create mode 100644 ___forcetk___js___acyini diff --git a/___forcetk___js___acyini b/___forcetk___js___acyini new file mode 100644 index 0000000..e69de29 diff --git a/forcetk.js b/forcetk.js index d19c885..3b94914 100644 --- a/forcetk.js +++ b/forcetk.js @@ -124,7 +124,7 @@ if (forcetk.Client === undefined) { forcetk.Client.prototype.setSessionToken = function(sessionId, apiVersion, instanceUrl) { this.sessionId = sessionId; this.apiVersion = (typeof apiVersion === 'undefined' || apiVersion === null) - ? 'v24.0': apiVersion; + ? 'v27.0': apiVersion; if (typeof instanceUrl === 'undefined' || instanceUrl == null) { // location.hostname can be of the form 'abc.na1.visual.force.com', // 'na1.salesforce.com' or 'abc.my.salesforce.com' (custom domains). @@ -162,7 +162,7 @@ if (forcetk.Client === undefined) { type: method || "GET", async: this.asyncAjax, url: (this.proxyUrl !== null) ? this.proxyUrl: url, - contentType: 'application/json', + contentType: method == "DELETE" ? null : 'application/json', cache: false, processData: false, data: payload, From ff4319f1d14368a632be3a19a624b34b9c213139 Mon Sep 17 00:00:00 2001 From: Pat Patterson Date: Thu, 19 Sep 2013 16:08:39 -0700 Subject: [PATCH 34/60] Deleted leftover diff file --- ___forcetk___js___acyini | 0 1 file changed, 0 insertions(+), 0 deletions(-) delete mode 100644 ___forcetk___js___acyini diff --git a/___forcetk___js___acyini b/___forcetk___js___acyini deleted file mode 100644 index e69de29..0000000 From 5610b9b6aa89a07eb497f6a34723ab6296e5bad7 Mon Sep 17 00:00:00 2001 From: "Christian G. Warden" Date: Sun, 20 Apr 2014 12:24:29 -0700 Subject: [PATCH 35/60] Include picklistValues in describe result Include the picklistValues attribute with each field returned with describe. For Picklist, MultiPicklist, and Combobox fields, return the picklist options; otherwise, return an empty array. --- RemoteTKController.cls | 23 ++++++++++++++++++++++- 1 file changed, 22 insertions(+), 1 deletion(-) diff --git a/RemoteTKController.cls b/RemoteTKController.cls index 859cd3a..7e3419e 100644 --- a/RemoteTKController.cls +++ b/RemoteTKController.cls @@ -86,6 +86,26 @@ public class RemoteTKController { return null; } + private static List picklistOptions(Schema.DescribeFieldResult field) { + List picklistOptions = new List(); + Schema.DisplayType fieldType = field.getType(); + if (fieldType != Schema.DisplayType.Picklist && + fieldType != Schema.DisplayType.MultiPicklist && + fieldType != Schema.DisplayType.Combobox) { + return picklistOptions; + } + List picklistValues = field.getPicklistValues(); + for (Schema.PicklistEntry picklistValue: picklistValues) { + Map picklistOption = new Map(); + picklistOption.put('value', picklistValue.getValue()); + picklistOption.put('label', picklistValue.getValue()); + picklistOption.put('active', picklistValue.isActive()); + picklistOption.put('defaultValue', picklistValue.isDefaultValue()); + picklistOptions.add(picklistOption); + } + return picklistOptions; + } + @remoteAction public static String describe(String objtype) { // Just enough to make the sample app work! @@ -113,7 +133,8 @@ public class RemoteTKController { if (!references.isEmpty()) { field.put('referenceTo', references); } - + field.put('picklistValues', picklistOptions(descField)); + fields.add(field); } From 875df78c515d7978b5b06cb6eaebbd823b8fb7b7 Mon Sep 17 00:00:00 2001 From: Pomu Date: Thu, 11 Dec 2014 10:36:00 +0900 Subject: [PATCH 36/60] Fix typo in comment, code formatting, return type consistency --- forcetk.js | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/forcetk.js b/forcetk.js index 3b94914..55d00b4 100644 --- a/forcetk.js +++ b/forcetk.js @@ -117,7 +117,7 @@ if (forcetk.Client === undefined) { * Set a session token and the associated metadata in the client. * @param sessionId a salesforce.com session ID. In a Visualforce page, * use '{!$Api.sessionId}' to obtain a session ID. - * @param [apiVersion="21.0"] Force.com API version + * @param [apiVersion="27.0"] Force.com API version * @param [instanceUrl] Omit this if running on Visualforce; otherwise * use the value from the OAuth token. */ @@ -200,9 +200,9 @@ if (forcetk.Client === undefined) { * @param mimetype of the file * @param callback function to which response will be passed * @param [error=null] function to which request will be passed in case of error - * @param rety true if we've already tried refresh token flow once - **/ - forcetk.Client.prototype.getChatterFile = function(path,mimeType,callback,error,retry) { + * @param retry true if we've already tried refresh token flow once + */ + forcetk.Client.prototype.getChatterFile = function(path, mimeType, callback, error, retry) { var that = this; var url = this.instanceUrl + path; @@ -258,8 +258,8 @@ if (forcetk.Client === undefined) { * @param [error=null] function to which jqXHR will be passed in case of error * @param [method="GET"] HTTP method for call * @param [payload=null] payload for POST/PATCH etc - * @param [paramMap={}] parameters to send as header values for POST/PATCH etc - * @param [retry] specifies whether to retry on error + * @param [paramMap={}] parameters to send as header values for POST/PATCH etc + * @param [retry] specifies whether to retry on error */ forcetk.Client.prototype.apexrest = function(path, callback, error, method, payload, paramMap, retry) { var that = this; @@ -388,7 +388,7 @@ if (forcetk.Client === undefined) { fieldlist = null; } var fields = fieldlist ? '?fields=' + fieldlist : ''; - this.ajax('/' + this.apiVersion + '/sobjects/' + objtype + '/' + id + return this.ajax('/' + this.apiVersion + '/sobjects/' + objtype + '/' + id + fields, callback, error); } @@ -484,4 +484,4 @@ if (forcetk.Client === undefined) { return this.ajax('/' + this.apiVersion + '/search?q=' + escape(sosl) , callback, error); } -} \ No newline at end of file +} From 3ceda4cdfa2f3816bf07d05a382eeefcaaa57932 Mon Sep 17 00:00:00 2001 From: Pat Patterson Date: Thu, 11 Dec 2014 12:26:10 -0800 Subject: [PATCH 37/60] Remove RemoteTK, don't use proxy with REST API in Visualforce, add createBlob, updateBlob --- README.markdown | 95 +++++------ RemoteTK.component | 201 ----------------------- RemoteTKController.cls | 315 ------------------------------------- RemoteTKExample.page | 150 ------------------ RemoteTKMobile.page | 144 ----------------- TestRemoteTKController.cls | 306 ----------------------------------- app.js | 62 ++++---- example.html | 16 +- example.page | 9 +- forcetk.js | 186 +++++++++++++++++----- mobile.html | 16 +- mobile.page | 9 +- mobileapp.js | 82 +++++----- phonegap.html | 22 +-- 14 files changed, 299 insertions(+), 1314 deletions(-) delete mode 100644 RemoteTK.component delete mode 100644 RemoteTKController.cls delete mode 100644 RemoteTKExample.page delete mode 100644 RemoteTKMobile.page delete mode 100644 TestRemoteTKController.cls diff --git a/README.markdown b/README.markdown index 92877d2..b10229f 100644 --- a/README.markdown +++ b/README.markdown @@ -6,16 +6,51 @@ This minimal toolkit allows JavaScript in web pages to call the Force.com REST A Background ---------- -Due to the [same origin policy](http://en.wikipedia.org/wiki/Same_origin_policy), JavaScript running in Visualforce pages may not use [XmlHttpRequest](http://en.wikipedia.org/wiki/XMLHttpRequest) to directly invoke the REST API, since Visualforce pages have hostnames of the form abc.na1.visual.force.com, and the REST API endpoints are of the form na1.salesforce.com. - -The RemoteTK Visualforce Custom Component (comprising RemoteTK.component and RemoteTKController.cls) provides an abstraction very similar to the REST API, implemented via `@RemoteAction` methods in the component's controller. The advantage of this mechanism is that no API calls are consumed. - -Alternatively, the ForceTK JavaScript library works around the same origin restriction by using the [AJAX Proxy](http://www.salesforce.com/us/developer/docs/ajax/Content/sforce_api_ajax_queryresultiterator.htm#ajax_proxy) to give full access to the REST API. Since the AJAX proxy is present on all -Visualforce hosts with an endpoint of the form https://abc.na1.visual.force.com/services/proxy, our Visualforce-hosted JavaScript can invoke it, passing the desired resource URL in an HTTP header. A drawback here is that using the REST API, even from a Visualforce page, consumes API calls. - -To host JavaScript *outside* the Force.com platform, we can deploy a simple PHP proxy to perform the same function as the AJAX proxy. - -[PhoneGap](http://www.phonegap.com/) provides a way for HTML5/JavaScript apps to run as native applications; in this configuration a proxy is not required - the toolkit simply provides a convenient abstraction of the REST API. +ForceTK provides a convenient, thin JavaScript abstraction of the [Force.com REST API](https://developer.salesforce.com/page/REST_API), making the API more accessible to JavaScript code running in Visualforce, in hybrid mobile apps, and elsewhere. + +Due to the [same origin policy](http://en.wikipedia.org/wiki/Same_origin_policy), JavaScript running outside the Force.com Platform may not use [XMLHttpRequest](http://en.wikipedia.org/wiki/XMLHttpRequest) to directly invoke the REST API, so a minimal PHP proxy is provided. + +Recent Updates +-------------- + +* [Visualforce Remote Objects](https://www.salesforce.com/us/developer/docs/pages/index_Left.htm#CSHID=pages_remote_objects.htm|StartTopic=Content%2Fpages_remote_objects.htm|SkinName=webhelp) are proxy objects that enable basic DML operations on sObjects directly from JavaScript. Behind the scenes, the Remote Objects controller handles sharing rules, field level security, and other data accessibility concerns. Pages that use Remote Objects are subject to all the standard Visualforce limits, but like JavaScript remoting, Remote Objects calls don’t count toward API request limits. + + + Since Remote Objects are more secure than RemoteTK (which does not respect sharing rules, FLS etc since system-level access is proxied via the RemoteTK controller), and similarly do not consume API calls (the main motivation for RemoteTK), RemoteTK has been removed from the toolkit. + +* Since the Summer '13 release, the `/services/data` endpoint has been exposed on Visualforce hosts, so no proxy is now required for REST API calls in JavaScript served via Visualforce (although the proxy **is** still required for calls to `/services/apexrest`). `forcetk.js` has been updated to reflect this. + +* Inserting or updating blob data using the `create` or `update` functions (passing base64-encoded binary data in JSON) is limited by the REST API to 50 MB of text data or 37.5 MB of base64–encoded data. New functions, `createBlob` and `updateBlob`, allow creation and update of ContentVersion and Document records with binary ('blob') content with a size of up to 500 MB. Here is a minimal sample that shows how to upload a file to Chatter Files: + + + +

+ Select a file to upload as a new Chatter File. +

+ +

+ +
+ + Under the covers, `createBlob` sends a multipart message. See the REST API doc page [Insert or Update Blob Data](https://www.salesforce.com/us/developer/docs/api_rest/Content/dome_sobject_insert_update_blob.htm) for more details. Dependencies ------------ @@ -25,37 +60,8 @@ The toolkit uses [jQuery](http://jquery.com/). It has been tested on jQuery 1.4. Configuration ------------- -RemoteTK requires no configuration. - ForceTK requires that you add the correct REST endpoint hostname for your instance (i.e. https://na1.salesforce.com/ or similar) as a remote site in *Your Name > Administration Setup > Security Controls > Remote Site Settings*. -Using RemoteTK in a Visualforce page ------------------------------------- - -Add RemoteTKController.cls and RemoteTK.component to your org by creating an Apex Class and a Component and pasting in the respective content, pasting the files into a [Force.com IDE](http://wiki.developerforce.com/page/Force.com_IDE) project, or by using the [Force.com Migration Tool](http://wiki.developerforce.com/page/Migration_Tool_Guide). - -Your Visualforce page will need to include the component and create a client object. An absolutely minimal sample is: - - - - - - -

The first account I see is .

-
- -More fully featured samples are provided in [RemoteTKExample.page](Force.com-JavaScript-REST-Toolkit/blob/master/RemoteTKExample.page) and [RemoteTKMobile.page](Force.com-JavaScript-REST-Toolkit/blob/master/RemoteTKMobile.page). - Using ForceTK in a Visualforce page ----------------------------------- @@ -67,15 +73,12 @@ Your Visualforce page will need to include jQuery and the toolkit, then create a

The first account I see is .

@@ -130,14 +133,14 @@ Your HTML page will need to include jQuery and the toolkit, then create a client function sessionCallback(oauthResponse) { if (typeof oauthResponse === 'undefined' || typeof oauthResponse['access_token'] === 'undefined') { - $('#message').html('Error - unauthorized!'); + $('#message').text('Error - unauthorized!'); } else { client.setSessionToken(oauthResponse.access_token, null, oauthResponse.instance_url); client.query("SELECT Name FROM Account LIMIT 1", function(response){ - $('#message').html('The first account I see is ' + $('#message').text('The first account I see is ' +response.records[0].Name); }); } @@ -215,7 +218,7 @@ An absolutely minimal sample using OAuth to obtain a session ID is: client.query("SELECT Name FROM Account LIMIT 1", function(response){ - $('#message').html('The first account I see is ' + $('#message').text('The first account I see is ' +response.records[0].Name); } ); diff --git a/RemoteTK.component b/RemoteTK.component deleted file mode 100644 index 071114a..0000000 --- a/RemoteTK.component +++ /dev/null @@ -1,201 +0,0 @@ - - - - \ No newline at end of file diff --git a/RemoteTKController.cls b/RemoteTKController.cls deleted file mode 100644 index 7e3419e..0000000 --- a/RemoteTKController.cls +++ /dev/null @@ -1,315 +0,0 @@ -/* - * Copyright (c) 2012, salesforce.com, inc. - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without modification, are permitted provided - * that the following conditions are met: - * - * Redistributions of source code must retain the above copyright notice, this list of conditions and the - * following disclaimer. - * - * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and - * the following disclaimer in the documentation and/or other materials provided with the distribution. - * - * Neither the name of salesforce.com, inc. nor the names of its contributors may be used to endorse or - * promote products derived from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED - * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A - * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR - * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED - * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) - * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - */ - -public class RemoteTKController { - private static String makeError(String message, String errorCode) { - JSONGenerator gen = JSON.createGenerator(false); - gen.writeStartArray(); - gen.writeStartObject(); - gen.writeStringField('message', message); - gen.writeStringField('errorCode', errorCode); - gen.writeEndObject(); - gen.writeEndArray(); - - return gen.getAsString(); - } - - private static String writeFields(String objtype, SObject obj, String fields) { - Map fieldMap = null; - try { - fieldMap = (Map)JSON.deserializeUntyped(fields); - } catch (JSONException je) { - return makeError(je.getMessage(), 'JSON_PARSER_ERROR'); - } - - Schema.SObjectType targetType = Schema.getGlobalDescribe().get(objtype); - - Map targetFields = targetType.getDescribe().fields.getMap(); - - try { - for (String key : fieldMap.keySet()) { - if (targetFields.get(key) == null) { - return '[{"message":"Field '+key+' does not exist on object type '+objtype+'","errorCode":"INVALID_FIELD"}]'; - } - - Object value = fieldMap.get(key); - Schema.DisplayType valueType = targetFields.get(key).getDescribe().getType(); - - if (value instanceof String && valueType != Schema.DisplayType.String) { - // Coerce an incoming String to the correct type - String svalue = (String)value; - - if (valueType == Schema.DisplayType.Date) { - obj.put(key, Date.valueOf(svalue)); - } else if (valueType == Schema.DisplayType.Percent || - valueType == Schema.DisplayType.Currency) { - obj.put(key, svalue == '' ? null : Decimal.valueOf(svalue)); - } else if (valueType == Schema.DisplayType.Double) { - obj.put(key, svalue == '' ? null : Double.valueOf(svalue)); - } else if (valueType == Schema.DisplayType.Integer) { - obj.put(key, Integer.valueOf(svalue)); - } else { - obj.put(key, svalue); - } - } else { - // Just try putting the incoming value on the object - obj.put(key, value); - } - } - } catch (SObjectException soe) { - return makeError(soe.getMessage(), 'INVALID_FIELD'); - } - - return null; - } - - private static List picklistOptions(Schema.DescribeFieldResult field) { - List picklistOptions = new List(); - Schema.DisplayType fieldType = field.getType(); - if (fieldType != Schema.DisplayType.Picklist && - fieldType != Schema.DisplayType.MultiPicklist && - fieldType != Schema.DisplayType.Combobox) { - return picklistOptions; - } - List picklistValues = field.getPicklistValues(); - for (Schema.PicklistEntry picklistValue: picklistValues) { - Map picklistOption = new Map(); - picklistOption.put('value', picklistValue.getValue()); - picklistOption.put('label', picklistValue.getValue()); - picklistOption.put('active', picklistValue.isActive()); - picklistOption.put('defaultValue', picklistValue.isDefaultValue()); - picklistOptions.add(picklistOption); - } - return picklistOptions; - } - - @remoteAction - public static String describe(String objtype) { - // Just enough to make the sample app work! - Schema.SObjectType targetType = Schema.getGlobalDescribe().get(objtype); - if (targetType == null) { - return makeError('The requested resource does not exist', 'NOT_FOUND'); - } - - Schema.DescribeSObjectResult sobjResult = targetType.getDescribe(); - - Map fieldMap = sobjResult.fields.getMap(); - - List fields = new List(); - for (String key : fieldMap.keySet()) { - Schema.DescribeFieldResult descField = fieldMap.get(key).getDescribe(); - Map field = new Map(); - - field.put('type', descField.getType().name().toLowerCase()); - field.put('name', descField.getName()); - field.put('label', descField.getLabel()); - List references = new List(); - for (Schema.sObjectType t: descField.getReferenceTo()) { - references.add(t.getDescribe().getName()); - } - if (!references.isEmpty()) { - field.put('referenceTo', references); - } - field.put('picklistValues', picklistOptions(descField)); - - fields.add(field); - } - - Map result = new Map(); - result.put('fields', fields); - - return JSON.serialize(result); - } - - @remoteAction - public static String create(String objtype, String fields) { - Schema.SObjectType targetType = Schema.getGlobalDescribe().get(objtype); - if (targetType == null) { - return makeError('The requested resource does not exist', 'NOT_FOUND'); - } - - SObject obj = targetType.newSObject(); - - String error = writeFields(objType, obj, fields); - if (error != null) { - return error; - } - - try { - insert obj; - } catch (DMLException dmle) { - String fieldNames = ''; - for (String field : dmle.getDmlFieldNames(0)) { - if (fieldNames.length() > 0) { - fieldNames += ','; - } - fieldNames += '"'+field+'"'; - } - return '[{"fields":['+fieldNames+'],"message":"'+dmle.getDmlMessage(0)+'","errorCode":"'+dmle.getDmlType(0).name()+'"}]'; - } - - Map result = new Map(); - result.put('id', obj.id); - result.put('errors', new List()); - result.put('success', true); - - return JSON.serialize(result); - } - - @remoteAction - public static String retrieve(String objtype, String id, String fieldlist) { - // TODO - handle null fieldlist - retrieve all fields - Boolean containsId = false; - for (String field : fieldlist.split(',')) { - if (field.equalsIgnoreCase('id')){ - containsId = true; - break; - } - } - - if (!containsId) { - fieldlist = 'Id,'+fieldlist; - } - - String soql = 'SELECT '+fieldlist+' FROM '+objtype+' WHERE Id = \''+id+'\''; - List records; - try { - records = Database.query(soql); - } catch (QueryException qe) { - return makeError(qe.getMessage(), 'INVALID_QUERY'); - } - - return JSON.serialize(records[0]); - } - - @remoteAction - public static String upser(String objtype, String externalIdField, String externalId, String fields) { - Schema.SObjectType targetType = Schema.getGlobalDescribe().get(objtype); - if (targetType == null) { - return makeError('The requested resource does not exist', 'NOT_FOUND'); - } - - SObject obj = targetType.newSObject(); - obj.put(externalIdField, externalId); - - String error = writeFields(objType, obj, fields); - if (error != null) { - return error; - } - - Schema.SObjectField sobjField = targetType.getDescribe().fields.getMap().get(externalIdField); - - Database.Upsert(obj, sobjField); - - return null; - } - - @remoteAction - public static String updat(String objtype, String id, String fields) { - Schema.SObjectType targetType = Schema.getGlobalDescribe().get(objtype); - if (targetType == null) { - return makeError('The requested resource does not exist', 'NOT_FOUND'); - } - - SObject obj = targetType.newSObject(id); - - String error = writeFields(objType, obj, fields); - if (error != null) { - return error; - } - - try { - update obj; - } catch (DMLException dmle) { - String fieldNames = ''; - for (String field : dmle.getDmlFieldNames(0)) { - if (fieldNames.length() > 0) { - fieldNames += ','; - } - fieldNames += '"'+field+'"'; - } - return '[{"fields":['+fieldNames+'],"message":"'+dmle.getDmlMessage(0)+'","errorCode":"'+dmle.getDmlType(0).name()+'"}]'; - } - - return null; - } - - @remoteAction - public static String del(String objtype, String id) { - Schema.SObjectType targetType = Schema.getGlobalDescribe().get(objtype); - if (targetType == null) { - return makeError('The requested resource does not exist', 'NOT_FOUND'); - } - - SObject obj = targetType.newSObject(id); - - try { - delete obj; - } catch (DMLException dmle) { - String fieldNames = ''; - for (String field : dmle.getDmlFieldNames(0)) { - if (fieldNames.length() > 0) { - fieldNames += ','; - } - fieldNames += '"'+field+'"'; - } - return '[{"fields":['+fieldNames+'],"message":"'+dmle.getDmlMessage(0)+'","errorCode":"'+dmle.getDmlType(0).name()+'"}]'; - } - - return null; - } - - @remoteAction - public static String query(String soql) { - List records; - try { - records = Database.query(soql); - } catch (QueryException qe) { - return makeError(qe.getMessage(), 'INVALID_QUERY'); - } - - Map result = new Map(); - result.put('records', records); - result.put('totalSize', records.size()); - result.put('done', true); - - return JSON.serialize(result); - } - - @remoteAction - public static String search(String sosl) { - List> result; - try { - result = Search.query(sosl); - } catch (QueryException qe) { - return makeError(qe.getMessage(), 'INVALID_SEARCH'); - } catch (SearchException se) { - return makeError(se.getMessage(), 'INVALID_SEARCH'); - } - - return JSON.serialize(result); - } -} \ No newline at end of file diff --git a/RemoteTKExample.page b/RemoteTKExample.page deleted file mode 100644 index 2b89192..0000000 --- a/RemoteTKExample.page +++ /dev/null @@ -1,150 +0,0 @@ - - - - - - - - Force.com JavaScript REST Toolkit - - - - - - - - - - - -
-
-
-
-
-
- - - - - - - - - -
\ No newline at end of file diff --git a/RemoteTKMobile.page b/RemoteTKMobile.page deleted file mode 100644 index 25e9673..0000000 --- a/RemoteTKMobile.page +++ /dev/null @@ -1,144 +0,0 @@ - - - - -"}"/> - - - - -Accounts - - - - - - - - - - - -
- -
-

Account List

-
-
-
- -
-
    -
-
-
-

Some Text

-
-
-
-
-

Account Detail

-
-
- - - - -
Account Name:
Industry:
Ticker Symbol:
-
- - - -
-
-
-

Some Text

-
-
-
-
-

New Account

-
-
-
- - - - - - - - - - - - - - -
Account Name:
Industry:
Ticker Symbol:
- -
-
-
-

Some Text

-
-
- - -
\ No newline at end of file diff --git a/TestRemoteTKController.cls b/TestRemoteTKController.cls deleted file mode 100644 index daade25..0000000 --- a/TestRemoteTKController.cls +++ /dev/null @@ -1,306 +0,0 @@ -@isTest -public class TestRemoteTKController{ - private static String tooLongAccName = 'LOTS OF '+ - 'CHARACTERS XXXXXXXXXXXXXXXXXXXXXXXX'+ - 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'+ - 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'+ - 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'+ - 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'+ - 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'+ - 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'+ - 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'+ - 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'+ - 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'+ - 'XXXXXXXXXXXXXXXX'; - - static private void assertError(String jsonResult, String expectedError, String method) { - List errorArray = (List)JSON.deserializeUntyped(jsonResult); - - System.assertNotEquals(null, errorArray, - 'error array missing from '+method+' result'); - System.assertNotEquals(0, errorArray.size(), - 'error array is empty in '+method+' result'); - - Map error = (Map)errorArray[0]; - String errorCode = (String)error.get('errorCode'); - System.assertNotEquals(null, errorCode, - 'errorCode property missing from '+method+' result'); - System.assertEquals(expectedError, errorCode, - 'errorCode should be '+expectedError+' in '+method+' result'); - } - - static testMethod void testDescribe() { - // Assume we have accounts - String jsonResult = RemoteTKController.describe('Account'); - - System.assertNotEquals(null, jsonResult, - 'RemoteTKController.describe returned null'); - - Map result = (Map)JSON.deserializeUntyped(jsonResult); - - System.assertNotEquals(null, result.get('fields'), - 'fields property missing from RemoteTKController.describe result'); - - // TODO - more assertions on describe results - - // Invalid object type - // Hope there isn't a QXZXQZXZQXZQ object type! - jsonResult = RemoteTKController.describe('QXZXQZXZQXZQ'); - assertError(jsonResult, 'NOT_FOUND', 'RemoteTKController.describe'); - } - - static private void assertRecord(Map record, String accName, String accNumber, String method) { - Map attributes = (Map)record.get('attributes'); - System.assertNotEquals(null, attributes, - 'attributes property missing from '+method+' result'); - System.assertNotEquals(0, attributes.keySet().size(), - 'empty attributes object in '+method+' result'); - - String type = (String)attributes.get('type'); - System.assertNotEquals(null, type, - 'type property missing from '+method+' result'); - System.assertEquals('Account', type, - 'Wrong type in '+method+' result'); - - String url = (String)attributes.get('url'); - System.assertNotEquals(null, url, - 'url property missing from '+method+' result'); - - Id id = (Id)record.get('Id'); - System.assertNotEquals(null, id, - 'Id property missing from '+method+' result'); - Account account = [SELECT Id, Name FROM Account WHERE Id = :id LIMIT 1]; - System.assertNotEquals(null, account, - 'Couldn\'t find account record identified by '+method+' result'); - System.assertEquals(accName, account.Name, - 'Account name doesn\'t match in '+method+' result'); - - String name = (String)record.get('Name'); - System.assertNotEquals(null, name, - 'Name property missing from '+method+' result'); - System.assertEquals(accName, name, - 'Wrong account name in '+method+' result'); - - String accountNumber = (String)record.get('AccountNumber'); - System.assertNotEquals(null, name, - 'AccountNumber property missing from '+method+' result'); - System.assertEquals(accNumber, accountNumber, - 'Wrong account number in '+method+' result'); - } - - static private Id testCreate(String accName, String accNumber, String fields) { - // Assume we can create an account - - // Try with data in correct types - String jsonResult = RemoteTKController.create('Account', - '{"Name": "'+accName+'", '+ - '"AccountNumber" : "'+accNumber+'",'+ - fields+'}'); - - System.assertNotEquals(null, jsonResult, - 'RemoteTKController.create returned null'); - - Map result = (Map)JSON.deserializeUntyped(jsonResult); - - Boolean success = (Boolean)result.get('success'); - System.assertNotEquals(null, success, - 'success property missing from RemoteTKController.create result'); - System.assertNotEquals(false, success, - 'success is false in RemoteTKController.create result'); - - List errors = (List)result.get('errors'); - System.assertNotEquals(null, errors, - 'errors property missing from RemoteTKController.create result'); - System.assertEquals(0, errors.size(), - 'errors array is not empty in RemoteTKController.create result'); - - Id id = (Id)result.get('id'); - System.assertNotEquals(null, id, - 'id property missing from RemoteTKController.create result'); - Account account = [SELECT Id, Name, AccountNumber FROM Account LIMIT 1]; - System.assertNotEquals(null, account, - 'Couldn\'t find account record created by RemoteTKController.create result'); - System.assertEquals(accName, account.Name, - 'Account name doesn\'t match in RemoteTKController.create result'); - System.assertEquals(accNumber, account.AccountNumber, - 'Account number doesn\'t match in RemoteTKController.create result'); - - jsonResult = RemoteTKController.create('QXZXQZXZQXZQ', '{"Name": "'+accName+'"}'); - assertError(jsonResult, 'NOT_FOUND', 'RemoteTKController.create'); - - jsonResult = RemoteTKController.create('Account', '{"Name" "'+accName+'"}'); - assertError(jsonResult, 'JSON_PARSER_ERROR', 'RemoteTKController.create'); - - jsonResult = RemoteTKController.create('Account', '{"XQZXQZXQZXQZ" : "'+accName+'"}'); - assertError(jsonResult, 'INVALID_FIELD', 'RemoteTKController.create'); - - jsonResult = RemoteTKController.create('Account', '{"Name" : "'+tooLongAccName+'"}'); - assertError(jsonResult, 'STRING_TOO_LONG', 'RemoteTKController.create'); - - return id; - } - - static private void testRetrieve(String accName, String accNumber, Id id) { - String jsonResult = RemoteTKController.retrieve('Account', id, 'Name, AccountNumber'); - - System.assertNotEquals(null, jsonResult, - 'RemoteTKController.retrieve returned null'); - - Map result = (Map)JSON.deserializeUntyped(jsonResult); - - assertRecord(result, accName, accNumber, 'RemoteTKController.retrieve'); - - // TODO - test negative paths for retrieve - } - - static private void testQuery(String accName, String accNumber) { - String jsonResult = RemoteTKController.query('SELECT Id, Name, AccountNumber FROM Account WHERE Name = \''+accName+'\''); - - System.assertNotEquals(null, jsonResult, - 'RemoteTKController.query returned null'); - - Map result = (Map)JSON.deserializeUntyped(jsonResult); - - List records = (List)result.get('records'); - System.assertNotEquals(null, records, - 'records property missing from RemoteTKController.query result'); - System.assertEquals(1, records.size(), - 'records array should have single record in RemoteTKController.query result'); - - Map record = (Map)records[0]; - - assertRecord(record, accName, accNumber, 'RemoteTKController.query'); - - Integer totalSize = (Integer)result.get('totalSize'); - System.assertNotEquals(null, totalSize, - 'totalSize property missing from RemoteTKController.query result'); - System.assertEquals(1, totalSize, - 'totalSize should be 1 in RemoteTKController.query result'); - - Boolean done = (Boolean)result.get('done'); - System.assertNotEquals(null, done, - 'done property missing from RemoteTKController.query result'); - System.assertEquals(true, done, - 'done should be true in RemoteTKController.query result'); - - jsonResult = RemoteTKController.query('SSSSSS Id, Name FROM Account WHERE Name = \''+accName+'\''); - assertError(jsonResult, 'INVALID_QUERY', 'RemoteTKController.query'); - } - - static private void testSearch(String accName, String accNumber, Id id) { - Id [] fixedSearchResults= new Id[1]; - fixedSearchResults[0] = id; - Test.setFixedSearchResults(fixedSearchResults); - String jsonResult = RemoteTKController.search('FIND {'+accName+'} IN ALL FIELDS RETURNING Account (Id, Name, AccountNumber)'); - - System.assertNotEquals(null, jsonResult, - 'RemoteTKController.search returned null'); - - List result = (List)JSON.deserializeUntyped(jsonResult); - - List records = (List)result[0]; - - Map record = (Map)records[0]; - - assertRecord(record, accName, accNumber, 'RemoteTKController.search'); - - jsonResult = RemoteTKController.search('FFFF {'+accName+'} IN ALL FIELDS RETURNING Account (Id, Name)'); - assertError(jsonResult, 'INVALID_SEARCH', 'RemoteTKController.search'); - } - - static private void testUpdate(String accName, String accNumber, Id id, String fields) { - String jsonResult = RemoteTKController.updat('Account', id, '{"Name":"'+accName+'", "AccountNumber":"'+accNumber+'"}'); - System.assertEquals(null, jsonResult, - 'Non-null result from RemoteTKController.updat'); - Account account = [SELECT Id, Name, AccountNumber FROM Account WHERE Id = :id LIMIT 1]; - System.assertNotEquals(null, account, - 'Couldn\'t find account record after RemoteTKController.updat'); - System.assertEquals(accName, account.Name, - 'Account name doesn\'t match after RemoteTKController.updat'); - System.assertEquals(accNumber, account.AccountNumber, - 'Account number doesn\'t match after RemoteTKController.updat'); - - jsonResult = RemoteTKController.updat('QXZXQZXZQXZQ', id, '{"Name":"'+accName+'"}'); - assertError(jsonResult, 'NOT_FOUND', 'RemoteTKController.updat'); - - jsonResult = RemoteTKController.updat('Account', id, '{"XQZXQZXQZXQZ" : "'+accName+'"}'); - assertError(jsonResult, 'INVALID_FIELD', 'RemoteTKController.updat'); - - jsonResult = RemoteTKController.updat('Account', id, '{"Name" "'+accName+'"}'); - assertError(jsonResult, 'JSON_PARSER_ERROR', 'RemoteTKController.updat'); - - jsonResult = RemoteTKController.updat('Account', id, '{"Name" : "'+tooLongAccName+'"}'); - assertError(jsonResult, 'STRING_TOO_LONG', 'RemoteTKController.updat'); - } - - static private void testUpsert(String accName, String accNumber, Id id, String fields) { - String jsonResult = RemoteTKController.upser('Account', - 'Id', - (String)id, - '{"Name":"'+accName+'", '+ - '"AccountNumber":"'+accNumber+'",'+ - fields+'}'); - System.assertEquals(null, jsonResult, - 'Non-null result from RemoteTKController.upser'); - Account account = [SELECT Id, Name, AccountNumber FROM Account WHERE Id = :id LIMIT 1]; - System.assertNotEquals(null, account, - 'Couldn\'t find account record after RemoteTKController.upser'); - System.assertEquals(accName, account.Name, - 'Account name doesn\'t match after RemoteTKController.upser'); - System.assertEquals(accNumber, account.AccountNumber, - 'Account number doesn\'t match after RemoteTKController.upser'); - - jsonResult = RemoteTKController.upser('QXZXQZXZQXZQ', 'Id', (String)id, '{"Name":"'+accName+'"}'); - assertError(jsonResult, 'NOT_FOUND', 'RemoteTKController.upser'); - - jsonResult = RemoteTKController.upser('Account', 'Id', (String)id, '{"XQZXQZXQZXQZ" : "'+accName+'"}'); - assertError(jsonResult, 'INVALID_FIELD', 'RemoteTKController.upser'); - } - - static private void testDelete(Id id) { - String jsonResult = RemoteTKController.del('QXZXQZXZQXZQ', id); - assertError(jsonResult, 'NOT_FOUND', 'RemoteTKController.del'); - - jsonResult = RemoteTKController.del('Account', id); - System.assertEquals(null, jsonResult, - 'Non-null result from RemoteTKController.del'); - List accounts = [SELECT Id, Name FROM Account WHERE Id = :id]; - System.assertEquals(0, accounts.size(), - 'Account record was not deleted by RemoteTKController.del'); - - jsonResult = RemoteTKController.del('Account', id); - assertError(jsonResult, 'ENTITY_IS_DELETED', 'RemoteTKController.del'); - } - - static testMethod void testCRUD() { - String accName = 'Test1'; - String accNumber = '1234'; - - // String field values - Id id = testCreate(accName, accNumber, '"AnnualRevenue" : "1000000",'+ - '"NumberOfEmployees" : "1000",'+ - '"Phone" : "(111) 222-3333"'); - testDelete(id); - - // Integer field values - id = testCreate(accName, accNumber, '"AnnualRevenue" : 1000000,'+ - '"NumberOfEmployees" : 1000,'+ - '"Phone" : "(111) 222-3333"'); - testRetrieve(accName, accNumber, id); - testQuery(accName, accNumber); - testSearch(accName, accNumber, id); - testUpdate(accName+'1', accNumber+'1', id, '"AnnualRevenue" : "1100000",'+ - '"NumberOfEmployees" : "1100",'+ - '"Phone" : "(112) 222-3333"'); - testUpdate(accName+'2', accNumber+'2', id, '"AnnualRevenue" : "2000000",'+ - '"NumberOfEmployees" : "2000",'+ - '"Phone" : "(222) 222-3333"'); - testUpsert(accName+'3', accNumber+'3', id, '"AnnualRevenue" : 3000000,'+ - '"NumberOfEmployees" : 3000,'+ - '"Phone" : "(333) 222-3333"'); - testUpsert(accName+'4', accNumber+'4', id, '"AnnualRevenue" : 4000000,'+ - '"NumberOfEmployees" : 4000,'+ - '"Phone" : "(444) 222-3333"'); - testDelete(id); - } -} \ No newline at end of file diff --git a/app.js b/app.js index 10b7064..7ce5297 100644 --- a/app.js +++ b/app.js @@ -51,18 +51,18 @@ function metadataCallback(response){ // Using TrimPath Template for now - may switch to jQuery Template at some // point - $j('#prompt').html(TrimPath.processDOMTemplate("prompt_jst" + $('#prompt').html(TrimPath.processDOMTemplate("prompt_jst" , response)); // Set up autocomplete - $j( "#value" ).autocomplete({ + $( "#value" ).autocomplete({ source: function( request, response ) { var query = "SELECT Id, Name FROM Account "+ - "WHERE "+$j("#field").val()+" LIKE '%"+request.term+"%' "+ + "WHERE "+$("#field").val()+" LIKE '%"+request.term+"%' "+ "ORDER BY Name LIMIT 20"; client.query(query, function( data ) { - response( $j.map( data.records, function( record ) { + response( $.map( data.records, function( record ) { return { label: record.Name, value: record.Id @@ -76,22 +76,22 @@ if ( ui.item != null ) { showAccountDetail(ui.item.value); } else { - filterAccounts($j("#field").val(),this.value); + filterAccounts($("#field").val(),this.value); } return false; }, }); - $j('#go').click(function(e) { - var field = $j("#field").val(); - var value = $j("#value").val(); + $('#go').click(function(e) { + var field = $("#field").val(); + var value = $("#value").val(); e.preventDefault(); filterAccounts(field,value); }); - $j('#new').click(function(e) { + $('#new').click(function(e) { e.preventDefault(); // Just make Trimpath happy @@ -101,19 +101,19 @@ dummy[response.fields[i].name] = ''; } $dialog.html(TrimPath.processDOMTemplate("edit_jst", dummy)); - $dialog.find('#action').html('Create').click(function(e) { + $dialog.find('#action').text('Create').click(function(e) { e.preventDefault(); $dialog.dialog('close'); var fields = {}; $dialog.find('input').each(function() { - var child = $j(this); + var child = $(this); if ( child.val().length > 0 ) { fields[child.attr("name")] = child.val(); } }); - $j('#list').html(ajaxgif+" creating account..."); + $('#list').html(ajaxgif+" creating account..."); client.create('Account', fields, createCallback, errorCallback); }); @@ -125,21 +125,21 @@ } function queryCallback(response) { - $j('#list').html(TrimPath.processDOMTemplate("accounts_jst" + $('#list').html(TrimPath.processDOMTemplate("accounts_jst" , response)); - $j('#version').html($j.fn.jquery); - $j('#uiversion').html($j.ui.version); + $('#version').text($.fn.jquery); + $('#uiversion').text($.ui.version); - $j("#list tr:nth-child(odd)").addClass("odd"); + $("#list tr:nth-child(odd)").addClass("odd"); - $j('#logout').click(logout); + $('#logout').click(logout); - $j('#accounts').find('.id') + $('#accounts').find('.id') .hover(function() { - $j(this).addClass("highlighted"); + $(this).addClass("highlighted"); },function(){ - $j(this).removeClass("highlighted"); + $(this).removeClass("highlighted"); }) .click(function(){ showAccountDetail(this.id); @@ -156,36 +156,36 @@ && !response.Website.startsWith('http://')) { response.Website = 'http://'+response.Website; } - $dialog.html(TrimPath.processDOMTemplate("detail_jst" + $dialog.TrimPath.processDOMTemplate("detail_jst" ,response)); $dialog.find('#industry').click(function(e) { e.preventDefault(); $dialog.dialog('close'); - filterIndustry($j(this).html()); + filterIndustry($(this).text()); }); $dialog.find('#delete').click(function(e) { e.preventDefault(); $dialog.dialog('close'); - $j('#list').html(ajaxgif+" deleting account..."); + $('#list').html(ajaxgif+" deleting account..."); client.del('Account', $dialog.find('#id').val(), deleteCallback, errorCallback); }); $dialog.find('#edit').click(function(e) { e.preventDefault(); $dialog.html(TrimPath.processDOMTemplate("edit_jst" ,response)); - $dialog.find('#action').html('Update').click(function(e) { + $dialog.find('#action').text('Update').click(function(e) { e.preventDefault(); $dialog.dialog('close'); var fields = {}; $dialog.find('input').each(function() { - var child = $j(this); + var child = $(this); if ( child.val().length > 0 && child.attr("name") != 'id') { fields[child.attr("name")] = child.val(); } }); - $j('#list').html(ajaxgif+" updating account..."); + $('#list').html(ajaxgif+" updating account..."); client.update('Account', $dialog.find('#id').val(), fields, updateCallback, errorCallback); }); @@ -193,19 +193,19 @@ } function createCallback(response) { - $j('#list').html('Created '+response.id); + $('#list').text('Created '+response.id); setTimeout("filterAccounts()",1000); } function updateCallback(response) { - $j('#list').html('Updated'); + $('#list').text('Updated'); setTimeout("filterAccounts()",1000); } function deleteCallback(response) { - $j('#list').html('Deleted'); + $('#list').text('Deleted'); setTimeout("filterAccounts()",1000); } @@ -222,7 +222,7 @@ } function filterIndustry(industry) { - $j('#list').html(ajaxgif+" loading data..."); + $('#list').html(ajaxgif+" loading data..."); var query = "SELECT Id, Name FROM Account WHERE Industry = '"+industry +"' ORDER BY Name LIMIT 20"; @@ -231,7 +231,7 @@ } function filterAccounts(field, value) { - $j('#list').html(ajaxgif+" loading data..."); + $('#list').html(ajaxgif+" loading data..."); var query = ( typeof value !== 'undefined' && value.length > 0 ) ? "SELECT Id, Name FROM Account WHERE "+field+" LIKE '%"+value diff --git a/example.html b/example.html index 1af86b9..f5439d4 100644 --- a/example.html +++ b/example.html @@ -76,13 +76,8 @@ var $dialog = null; - // We use $j rather than $ for jQuery - if (window.$j === undefined) { - $j = $; - } - - $j(document).ready(function() { - $j('#login').popupWindow({ + $(document).ready(function() { + $('#login').popupWindow({ windowURL: getAuthorizeUrl(loginUrl, clientId, redirectUri), windowName: 'Connect', centerBrowser: 1, @@ -90,7 +85,7 @@ width:675 }); - $dialog = $j('
') + $dialog = $('
') .dialog({ autoOpen: false, width: 450 @@ -104,13 +99,12 @@ } function hideButton(){ - $j('#connect').html(ajaxgif+" connecting..."); + $('#connect').text(ajaxgif+" connecting..."); } function sessionCallback(oauthResponse) { if (typeof oauthResponse === 'undefined' || typeof oauthResponse['access_token'] === 'undefined') { - //$j('#prompt').html('Error - unauthorized!'); errorCallback({ status: 0, statusText: 'Unauthorized', @@ -121,7 +115,7 @@ oauthResponse.instance_url); // Kick things off by doing a describe on Account... - $j('#prompt').html(ajaxgif+" loading metadata..."); + $('#prompt').text(ajaxgif+" loading metadata..."); client.describe('Account',metadataCallback, errorCallback); } } diff --git a/example.page b/example.page index e18b827..7ce51a7 100644 --- a/example.page +++ b/example.page @@ -48,9 +48,6 @@ Sample Visualforce page for Force.com JavaScript REST Toolkit * It must go in the VF page so that merge variables are processed. */ - // Get a reference to jQuery that we can work with - $j = jQuery.noConflict(); - // Get an instance of the REST API client and set the session ID var client = new forcetk.Client(); client.setSessionToken('{!$Api.Session_ID}'); @@ -59,16 +56,16 @@ Sample Visualforce page for Force.com JavaScript REST Toolkit var $dialog = null; - $j(document).ready(function() { + $(document).ready(function() { // Set up the dialog - $dialog = $j('
') + $dialog = $('
') .dialog({ autoOpen: false, width: 450 }); // Kick things off by doing a describe on Account... - $j('#prompt').html(ajaxgif+" loading metadata..."); + $('#prompt').html(ajaxgif+" loading metadata..."); client.describe('Account', metadataCallback); }); diff --git a/forcetk.js b/forcetk.js index 3b94914..57d19a2 100644 --- a/forcetk.js +++ b/forcetk.js @@ -40,11 +40,6 @@ if (forcetk === undefined) { if (forcetk.Client === undefined) { - // We use $j rather than $ for jQuery so it works in Visualforce - if (window.$j === undefined) { - $j = $; - } - /** * The Client provides a convenient wrapper for the Force.com REST API, * allowing JavaScript in Visualforce pages to use the API via the Ajax @@ -63,7 +58,7 @@ if (forcetk.Client === undefined) { // In PhoneGap this.proxyUrl = null; } else { - // In Visualforce + // In Visualforce - still need proxyUrl for Apex REST methods this.proxyUrl = location.protocol + "//" + location.hostname + "/services/proxy"; } @@ -76,6 +71,7 @@ if (forcetk.Client === undefined) { this.refreshToken = null; this.sessionId = null; this.apiVersion = null; + this.visualforce = false; this.instanceUrl = null; this.asyncAjax = true; } @@ -96,9 +92,9 @@ if (forcetk.Client === undefined) { forcetk.Client.prototype.refreshAccessToken = function(callback, error) { var that = this; var url = this.loginUrl + '/services/oauth2/token'; - return $j.ajax({ + return $.ajax({ type: 'POST', - url: (this.proxyUrl !== null) ? this.proxyUrl: url, + url: (this.proxyUrl !== null && ! this.visualforce) ? this.proxyUrl: url, cache: false, processData: false, data: 'grant_type=refresh_token&client_id=' + this.clientId + '&refresh_token=' + this.refreshToken, @@ -106,7 +102,7 @@ if (forcetk.Client === undefined) { error: error, dataType: "json", beforeSend: function(xhr) { - if (that.proxyUrl !== null) { + if (that.proxyUrl !== null && ! this.visualforce) { xhr.setRequestHeader('SalesforceProxy-Endpoint', url); } } @@ -117,15 +113,17 @@ if (forcetk.Client === undefined) { * Set a session token and the associated metadata in the client. * @param sessionId a salesforce.com session ID. In a Visualforce page, * use '{!$Api.sessionId}' to obtain a session ID. - * @param [apiVersion="21.0"] Force.com API version + * @param [apiVersion="v29.0"] Force.com API version * @param [instanceUrl] Omit this if running on Visualforce; otherwise * use the value from the OAuth token. */ forcetk.Client.prototype.setSessionToken = function(sessionId, apiVersion, instanceUrl) { this.sessionId = sessionId; this.apiVersion = (typeof apiVersion === 'undefined' || apiVersion === null) - ? 'v27.0': apiVersion; + ? 'v29.0': apiVersion; if (typeof instanceUrl === 'undefined' || instanceUrl == null) { + this.visualforce = true; + // location.hostname can be of the form 'abc.na1.visual.force.com', // 'na1.salesforce.com' or 'abc.my.salesforce.com' (custom domains). // Split on '.', and take the [1] or [0] element as appropriate @@ -156,12 +154,12 @@ if (forcetk.Client === undefined) { */ forcetk.Client.prototype.ajax = function(path, callback, error, method, payload, retry) { var that = this; - var url = this.instanceUrl + '/services/data' + path; + var url = (this.visualforce ? '' : this.instanceUrl) + '/services/data' + path; - return $j.ajax({ + return $.ajax({ type: method || "GET", async: this.asyncAjax, - url: (this.proxyUrl !== null) ? this.proxyUrl: url, + url: (this.proxyUrl !== null && ! this.visualforce) ? this.proxyUrl: url, contentType: method == "DELETE" ? null : 'application/json', cache: false, processData: false, @@ -181,10 +179,10 @@ if (forcetk.Client === undefined) { }, dataType: "json", beforeSend: function(xhr) { - if (that.proxyUrl !== null) { + if (that.proxyUrl !== null && ! that.visualforce) { xhr.setRequestHeader('SalesforceProxy-Endpoint', url); } - xhr.setRequestHeader(that.authzHeader, "OAuth " + that.sessionId); + xhr.setRequestHeader(that.authzHeader, "Bearer " + that.sessionId); xhr.setRequestHeader('X-User-Agent', 'salesforce-toolkit-rest-javascript/' + that.apiVersion); } }); @@ -200,20 +198,20 @@ if (forcetk.Client === undefined) { * @param mimetype of the file * @param callback function to which response will be passed * @param [error=null] function to which request will be passed in case of error - * @param rety true if we've already tried refresh token flow once + * @param retry true if we've already tried refresh token flow once **/ forcetk.Client.prototype.getChatterFile = function(path,mimeType,callback,error,retry) { var that = this; - var url = this.instanceUrl + path; + var url = (this.visualforce ? '' : this.instanceUrl) + path; var request = new XMLHttpRequest(); - request.open("GET", (this.proxyUrl !== null) ? this.proxyUrl: url, true); + request.open("GET", (this.proxyUrl !== null && ! this.visualforce) ? this.proxyUrl: url, true); request.responseType = "arraybuffer"; - request.setRequestHeader(that.authzHeader, "OAuth " + that.sessionId); - request.setRequestHeader('X-User-Agent', 'salesforce-toolkit-rest-javascript/' + that.apiVersion); - if (this.proxyUrl !== null) { + request.setRequestHeader(this.authzHeader, "Bearer " + this.sessionId); + request.setRequestHeader('X-User-Agent', 'salesforce-toolkit-rest-javascript/' + this.apiVersion); + if (this.proxyUrl !== null && ! this.visualforce) { request.setRequestHeader('SalesforceProxy-Endpoint', url); } @@ -250,6 +248,124 @@ if (forcetk.Client === undefined) { request.send(); } + + // Local utility to create a random string for multipart boundary + function randomString() { + var str = ''; + for (var i = 0; i < 4; i++) { + str += (Math.random().toString(16)+"000000000").substr(2,8); + } + return str; + } + + /* Low level function to create/update records with blob data + * @param path resource path relative to /services/data + * @param fields an object containing initial field names and values for + * the record, e.g. {ContentDocumentId: "069D00000000so2", + * PathOnClient: "Q1 Sales Brochure.pdf"} + * @param filename filename for blob data; e.g. "Q1 Sales Brochure.pdf" + * @param payloadField 'VersionData' for ContentVersion, 'Body' for Document + * @param payload Blob, File, ArrayBuffer (Typed Array), or String payload + * @param callback function to which response will be passed + * @param [error=null] function to which response will be passed in case of error + * @param retry true if we've already tried refresh token flow once + */ + forcetk.Client.prototype.blob = function(path, fields, filename, payloadField, payload, callback, error, retry) { + var that = this; + var url = (this.visualforce ? '' : this.instanceUrl) + '/services/data' + path; + var boundary = randomString(); + + var blob = new Blob([ + "--boundary_" + boundary + '\n' + + "Content-Disposition: form-data; name=\"entity_content\";" + "\n" + + "Content-Type: application/json" + "\n\n" + + JSON.stringify(fields) + + "\n\n" + + "--boundary_" + boundary + "\n" + + "Content-Type: application/octet-stream" + "\n" + + "Content-Disposition: form-data; name=\"" + payloadField + + "\"; filename=\"" + filename + "\"\n\n", + payload, + "\n\n" + + "--boundary_" + boundary + "--" + ], {type : 'multipart/form-data; boundary=\"boundary_' + boundary + '\"'}); + + var request = new XMLHttpRequest(); + request.open("POST", (this.proxyUrl !== null && ! this.visualforce) ? this.proxyUrl: url, this.asyncAjax); + + request.setRequestHeader(this.authzHeader, "Bearer " + this.sessionId); + request.setRequestHeader('X-User-Agent', 'salesforce-toolkit-rest-javascript/' + this.apiVersion); + if (this.proxyUrl !== null && ! this.visualforce) { + request.setRequestHeader('SalesforceProxy-Endpoint', url); + } + + if (this.asyncAjax) { + request.onreadystatechange = function() { + // continue if the process is completed + if (request.readyState == 4) { + // continue only if HTTP status is good + if (request.status >= 200 && request.status < 300) { + // retrieve the response + callback(request.response ? JSON.parse(request.response) : null); + } else if(request.status == 401 && !retry) { + that.refreshAccessToken(function(oauthResponse) { + that.setSessionToken(oauthResponse.access_token, null,oauthResponse.instance_url); + that.blob(path, fields, fileName, file, callback, error, true); + }, + error); + } else { + // return status message + error(request, request.statusText, request.response); + } + } + } + } + + request.send(blob); + + return this.asyncAjax ? JSON.parse(request.response) : null; + } + + /* + * Create a record with blob data + * @param objtype object type; e.g. "ContentVersion" + * @param fields an object containing initial field names and values for + * the record, e.g. {ContentDocumentId: "069D00000000so2", + * PathOnClient: "Q1 Sales Brochure.pdf"} + * @param filename filename for blob data; e.g. "Q1 Sales Brochure.pdf" + * @param payloadField 'VersionData' for ContentVersion, 'Body' for Document + * @param payload Blob, File, ArrayBuffer (Typed Array), or String payload + * @param callback function to which response will be passed + * @param [error=null] function to which response will be passed in case of error + * @param retry true if we've already tried refresh token flow once + */ + forcetk.Client.prototype.createBlob = function(objtype, fields, filename, + payloadField, payload, callback, + error, retry) { + return this.blob('/' + this.apiVersion + '/sobjects/' + objtype + '/', + fields, filename, payloadField, payload, callback, error); + } + + /* + * Update a record with blob data + * @param objtype object type; e.g. "ContentVersion" + * @param id the record's object ID + * @param fields an object containing initial field names and values for + * the record, e.g. {ContentDocumentId: "069D00000000so2", + * PathOnClient: "Q1 Sales Brochure.pdf"} + * @param filename filename for blob data; e.g. "Q1 Sales Brochure.pdf" + * @param payloadField 'VersionData' for ContentVersion, 'Body' for Document + * @param payload Blob, File, ArrayBuffer (Typed Array), or String payload + * @param callback function to which response will be passed + * @param [error=null] function to which response will be passed in case of error + * @param retry true if we've already tried refresh token flow once + */ + forcetk.Client.prototype.updateBlob = function(objtype, id, fields, filename, + payloadField, payload, callback, + error, retry) { + return this.blob('/' + this.apiVersion + '/sobjects/' + objtype + '/' + id + + '?_HttpMethod=PATCH', fields, filename, payloadField, payload, callback, error); + } /* * Low level utility function to call the Salesforce endpoint specific for Apex REST API. @@ -258,14 +374,14 @@ if (forcetk.Client === undefined) { * @param [error=null] function to which jqXHR will be passed in case of error * @param [method="GET"] HTTP method for call * @param [payload=null] payload for POST/PATCH etc - * @param [paramMap={}] parameters to send as header values for POST/PATCH etc - * @param [retry] specifies whether to retry on error + * @param [paramMap={}] parameters to send as header values for POST/PATCH etc + * @param [retry] specifies whether to retry on error */ forcetk.Client.prototype.apexrest = function(path, callback, error, method, payload, paramMap, retry) { var that = this; var url = this.instanceUrl + '/services/apexrest' + path; - return $j.ajax({ + return $.ajax({ type: method || "GET", async: this.asyncAjax, url: (this.proxyUrl !== null) ? this.proxyUrl: url, @@ -291,14 +407,14 @@ if (forcetk.Client === undefined) { if (that.proxyUrl !== null) { xhr.setRequestHeader('SalesforceProxy-Endpoint', url); } - //Add any custom headers - if (paramMap === null) { - paramMap = {}; - } - for (paramName in paramMap) { - xhr.setRequestHeader(paramName, paramMap[paramName]); - } - xhr.setRequestHeader(that.authzHeader, "OAuth " + that.sessionId); + //Add any custom headers + if (paramMap === null) { + paramMap = {}; + } + for (paramName in paramMap) { + xhr.setRequestHeader(paramName, paramMap[paramName]); + } + xhr.setRequestHeader(that.authzHeader, "Bearer " + that.sessionId); xhr.setRequestHeader('X-User-Agent', 'salesforce-toolkit-rest-javascript/' + that.apiVersion); } }); @@ -465,9 +581,9 @@ if (forcetk.Client === undefined) { var index = url.indexOf( serviceData ); if( index > -1 ){ - url = url.substr( index + serviceData.length ); + url = url.substr( index + serviceData.length ); } else { - //-- leave alone + //-- leave alone } return this.ajax( url, callback, error ); diff --git a/mobile.html b/mobile.html index c1a14eb..9c07cad 100644 --- a/mobile.html +++ b/mobile.html @@ -55,13 +55,8 @@ // OAuth var client = new forcetk.Client(clientId, loginUrl, proxyUrl);; -// We use $j rather than $ for jQuery -if (window.$j === undefined) { - $j = $; -} - -$j(document).ready(function() { - $j('#login').popupWindow({ +$(document).ready(function() { + $('#login').popupWindow({ windowURL: getAuthorizeUrl(loginUrl, clientId, redirectUri), windowName: 'Connect', centerBrowser: 1, @@ -79,7 +74,6 @@ function sessionCallback(oauthResponse) { if (typeof oauthResponse === 'undefined' || typeof oauthResponse['access_token'] === 'undefined') { - //$j('#prompt').html('Error - unauthorized!'); errorCallback({ status: 0, statusText: 'Unauthorized', @@ -91,10 +85,10 @@ addClickListeners(); - $j.mobile.changePage('#mainpage',"slide",false,true); - $j.mobile.pageLoading(); + $.mobile.changePage('#mainpage',"slide",false,true); + $.mobile.pageLoading(); getAccounts(function(){ - $j.mobile.pageLoading(true); + $.mobile.pageLoading(true); }); } } diff --git a/mobile.page b/mobile.page index 40105bf..c3f54e8 100644 --- a/mobile.page +++ b/mobile.page @@ -50,20 +50,17 @@ an HTML5 mobile app using jQuery Mobile diff --git a/mobileapp.js b/mobileapp.js index 8d7d1b6..f2e8de7 100644 --- a/mobileapp.js +++ b/mobileapp.js @@ -35,85 +35,85 @@ function errorCallback(jqXHR){ } function addClickListeners() { - $j('#newbtn').click(function(e) { + $('#newbtn').click(function(e) { // Show the 'New Account' form e.preventDefault(); - $j('#accountform')[0].reset(); - $j('#accformheader').html('New Account'); + $('#accountform')[0].reset(); + $('#accformheader').text('New Account'); setButtonText('#actionbtn', 'Create'); - $j('#actionbtn').unbind('click.btn').bind('click.btn', createHandler); - $j.mobile.changePage('#editpage', "slide", false, true); + $('#actionbtn').unbind('click.btn').bind('click.btn', createHandler); + $.mobile.changePage('#editpage', "slide", false, true); }); - $j('#deletebtn').click(function(e) { + $('#deletebtn').click(function(e) { // Delete the account e.preventDefault(); - $j.mobile.pageLoading(); - client.del('Account', $j('#accountdetail').find('#Id').val() + $.mobile.pageLoading(); + client.del('Account', $('#accountdetail').find('#Id').val() , function(response) { getAccounts(function() { - $j.mobile.pageLoading(true); - $j.mobile.changePage('#mainpage', "slide", true, true); + $.mobile.pageLoading(true); + $.mobile.changePage('#mainpage', "slide", true, true); }); }, errorCallback); }); - $j('#editbtn').click(function(e) { + $('#editbtn').click(function(e) { // Get account fields and show the 'Edit Account' form e.preventDefault(); - $j.mobile.pageLoading(); - client.retrieve("Account", $j('#accountdetail').find('#Id').val() + $.mobile.pageLoading(); + client.retrieve("Account", $('#accountdetail').find('#Id').val() , "Name,Id,Industry,TickerSymbol", function(response) { - $j('#accountform').find('input').each(function() { - $j(this).val(response[$j(this).attr("name")]); + $('#accountform').find('input').each(function() { + $(this).val(response[$(this).attr("name")]); }); - $j('#accformheader').html('Edit Account'); + $('#accformheader').text('Edit Account'); setButtonText('#actionbtn', 'Update'); - $j('#actionbtn') + $('#actionbtn') .unbind('click.btn') .bind('click.btn', updateHandler); - $j.mobile.pageLoading(true); - $j.mobile.changePage('#editpage', "slide", false, true); + $.mobile.pageLoading(true); + $.mobile.changePage('#editpage', "slide", false, true); }, errorCallback); }); } // Populate the account list and set up click handling function getAccounts(callback) { - $j('#accountlist').empty(); + $('#accountlist').empty(); client.query("SELECT Id, Name FROM Account ORDER BY Name LIMIT 20" , function(response) { - $j.each(response.records, + $.each(response.records, function() { var id = this.Id; - $j('
  • ') + $('
  • ') .hide() .append('

    ' + this.Name + '

    ') .click(function(e) { e.preventDefault(); - $j.mobile.pageLoading(); + $.mobile.pageLoading(); // We could do this more efficiently by adding Industry and // TickerSymbol to the fields in the SELECT, but we want to // show dynamic use of the retrieve function... client.retrieve("Account", id, "Name,Id,Industry,TickerSymbol" , function(response) { - $j('#Name').html(response.Name); - $j('#Industry').html(response.Industry); - $j('#TickerSymbol').html(response.TickerSymbol); - $j('#Id').val(response.Id); - $j.mobile.pageLoading(true); - $j.mobile.changePage('#detailpage', "slide", false, true); + $('#Name').text(response.Name); + $('#Industry').text(response.Industry); + $('#TickerSymbol').text(response.TickerSymbol); + $('#Id').val(response.Id); + $.mobile.pageLoading(true); + $.mobile.changePage('#detailpage', "slide", false, true); }, errorCallback); }) .appendTo('#accountlist') .show(); }); - $j('#accountlist').listview('refresh'); + $('#accountlist').listview('refresh'); if (typeof callback != 'undefined' && callback != null) { callback(); @@ -124,20 +124,20 @@ function getAccounts(callback) { // Gather fields from the account form and create a record function createHandler(e) { e.preventDefault(); - var accountform = $j('#accountform'); + var accountform = $('#accountform'); var fields = {}; accountform.find('input').each(function() { - var child = $j(this); + var child = $(this); if (child.val().length > 0 && child.attr("name") != 'Id') { fields[child.attr("name")] = child.val(); } }); - $j.mobile.pageLoading(); + $.mobile.pageLoading(); client.create('Account', fields, function(response) { getAccounts(function() { - $j.mobile.pageLoading(true); - $j.mobile.changePage('#mainpage', "slide", true, true); + $.mobile.pageLoading(true); + $.mobile.changePage('#mainpage', "slide", true, true); }); }, errorCallback); } @@ -145,21 +145,21 @@ function createHandler(e) { // Gather fields from the account form and update a record function updateHandler(e) { e.preventDefault(); - var accountform = $j('#accountform'); + var accountform = $('#accountform'); var fields = {}; accountform.find('input').each(function() { - var child = $j(this); + var child = $(this); if (child.val().length > 0 && child.attr("name") != 'Id') { fields[child.attr("name")] = child.val(); } }); - $j.mobile.pageLoading(); + $.mobile.pageLoading(); client.update('Account', accountform.find('#Id').val(), fields , function(response) { getAccounts(function() { - $j.mobile.pageLoading(true); - $j.mobile.changePage('#mainpage', "slide", true, true); + $.mobile.pageLoading(true); + $.mobile.changePage('#mainpage', "slide", true, true); }); }, errorCallback); } @@ -167,5 +167,5 @@ function updateHandler(e) { // Ugh - this is required to change text on a jQuery Mobile button // due to the way it futzes with things at runtime function setButtonText(id, str) { - $j(id).html(str).parent().find('.ui-btn-text').text(str); + $(id).text(str).parent().find('.ui-btn-text').text(str); } diff --git a/phonegap.html b/phonegap.html index 1e80547..2f89475 100644 --- a/phonegap.html +++ b/phonegap.html @@ -74,7 +74,7 @@ addClickListeners(); - $j('#logoutbtn').click(function(e) { + $('#logoutbtn').click(function(e) { // Delete the saved refresh token window.plugins.keychain.removeForKey('refresh_token', 'forcetk', @@ -82,8 +82,8 @@ var cb = ChildBrowser.install(); client.setRefreshToken(null); - $j.mobile.changePage('#loginpage', "slide", false, true); - $j.mobile.pageLoading(); + $.mobile.changePage('#loginpage', "slide", false, true); + $.mobile.pageLoading(); cb.onLocationChange = function(loc) { if (loc.startsWith(redirectUri)) { cb.close(); @@ -95,10 +95,10 @@ ); }); - $j.mobile.changePage('#mainpage', "slide", false, true); - $j.mobile.pageLoading(); + $.mobile.changePage('#mainpage', "slide", false, true); + $.mobile.pageLoading(); getAccounts(function() { - $j.mobile.pageLoading(true); + $.mobile.pageLoading(true); }); } @@ -136,18 +136,18 @@ } } - // We use $j rather than $ for jQuery - if (window.$j === undefined) { - $j = $; + // We use $ rather than $ for jQuery + if (window.$ === undefined) { + $ = $; } - $j(document).ready(function() { + $(document).ready(function() { var cb = ChildBrowser.install(); SAiOSKeychainPlugin.install(); window.plugins.keychain.getForKey('refresh_token', 'forcetk', function(key, value) { - $j.mobile.pageLoading(); + $.mobile.pageLoading(); client.setRefreshToken(value); client.refreshAccessToken(sessionCallback, function(jqXHR, textStatus, errorThrown) { From e53010604d7bdf50c55e05949015e7c7b9396d7e Mon Sep 17 00:00:00 2001 From: Daniel Date: Fri, 9 Jan 2015 13:23:45 -0800 Subject: [PATCH 38/60] Update forcetk.js to support Windows8 in phonegap Protocol in Windows8 app is ms-appx: not file: --- forcetk.js | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/forcetk.js b/forcetk.js index 3b94914..b6d37fe 100644 --- a/forcetk.js +++ b/forcetk.js @@ -59,7 +59,7 @@ if (forcetk.Client === undefined) { this.clientId = clientId; this.loginUrl = loginUrl || 'https://login.salesforce.com/'; if (typeof proxyUrl === 'undefined' || proxyUrl === null) { - if (location.protocol === 'file:') { + if (location.protocol === 'file:' || location.protocol === 'ms-appx:') { // In PhoneGap this.proxyUrl = null; } else { @@ -484,4 +484,4 @@ if (forcetk.Client === undefined) { return this.ajax('/' + this.apiVersion + '/search?q=' + escape(sosl) , callback, error); } -} \ No newline at end of file +} From 728e6aa29565b856d5b7cd58c63f6dd5330690af Mon Sep 17 00:00:00 2001 From: Pat Patterson Date: Thu, 15 Jan 2015 21:47:04 -0800 Subject: [PATCH 39/60] jQuery-ized blob sample --- README.markdown | 54 ++++++++++++++++++++++++------------------------- 1 file changed, 27 insertions(+), 27 deletions(-) diff --git a/README.markdown b/README.markdown index b10229f..c29671c 100644 --- a/README.markdown +++ b/README.markdown @@ -22,35 +22,35 @@ Recent Updates * Inserting or updating blob data using the `create` or `update` functions (passing base64-encoded binary data in JSON) is limited by the REST API to 50 MB of text data or 37.5 MB of base64–encoded data. New functions, `createBlob` and `updateBlob`, allow creation and update of ContentVersion and Document records with binary ('blob') content with a size of up to 500 MB. Here is a minimal sample that shows how to upload a file to Chatter Files: - - -

    - Select a file to upload as a new Chatter File. -

    - -

    - + +

    + Select a file to upload as a new Chatter File. +

    + +

    + + +
    - Under the covers, `createBlob` sends a multipart message. See the REST API doc page [Insert or Update Blob Data](https://www.salesforce.com/us/developer/docs/api_rest/Content/dome_sobject_insert_update_blob.htm) for more details. + Under the covers, `createBlob` sends a multipart message. See the REST API doc page [Insert or Update Blob Data](https://www.salesforce.com/us/developer/docs/api_rest/Content/dome_sobject_insert_update_blob.htm) for more details. Dependencies ------------ From 58969932785c2f363d2aa3cb074a3197bd413658 Mon Sep 17 00:00:00 2001 From: Pat Patterson Date: Sun, 8 Mar 2015 21:49:42 -0700 Subject: [PATCH 40/60] First cut of BulkTK --- BulkAPISampleFiles/delete.csv | 5 + BulkAPISampleFiles/delete.xml | 16 +++ BulkAPISampleFiles/insert.csv | 3 + BulkAPISampleFiles/insert.xml | 17 +++ BulkAPISampleFiles/update.csv | 2 + BulkAPISampleFiles/update.xml | 8 ++ BulkAPISampleFiles/upsert.csv | 2 + BulkAPISampleFiles/upsert.xml | 8 ++ BulkTK.md | 121 ++++++++++++++++ bulk.page | 254 ++++++++++++++++++++++++++++++++++ bulktk.js | 239 ++++++++++++++++++++++++++++++++ 11 files changed, 675 insertions(+) create mode 100644 BulkAPISampleFiles/delete.csv create mode 100644 BulkAPISampleFiles/delete.xml create mode 100644 BulkAPISampleFiles/insert.csv create mode 100644 BulkAPISampleFiles/insert.xml create mode 100644 BulkAPISampleFiles/update.csv create mode 100644 BulkAPISampleFiles/update.xml create mode 100644 BulkAPISampleFiles/upsert.csv create mode 100644 BulkAPISampleFiles/upsert.xml create mode 100644 BulkTK.md create mode 100644 bulk.page create mode 100644 bulktk.js diff --git a/BulkAPISampleFiles/delete.csv b/BulkAPISampleFiles/delete.csv new file mode 100644 index 0000000..9535358 --- /dev/null +++ b/BulkAPISampleFiles/delete.csv @@ -0,0 +1,5 @@ +Id +003E000001DJOfxIAH +003E000001DJOfyIAH +003E000001DJOV4IAP +003E000001DJOV5IAP \ No newline at end of file diff --git a/BulkAPISampleFiles/delete.xml b/BulkAPISampleFiles/delete.xml new file mode 100644 index 0000000..e644728 --- /dev/null +++ b/BulkAPISampleFiles/delete.xml @@ -0,0 +1,16 @@ + + + + + 003E000001DJOfxIAH + + + 003E000001DJOfyIAH + + + 003E000001DJOV4IAP + + + 003E000001DJOV5IAP + + \ No newline at end of file diff --git a/BulkAPISampleFiles/insert.csv b/BulkAPISampleFiles/insert.csv new file mode 100644 index 0000000..31cb26a --- /dev/null +++ b/BulkAPISampleFiles/insert.csv @@ -0,0 +1,3 @@ +FirstName,LastName,Department,Birthdate,Description +Tom,Jones,Marketing,1940-06-07Z,"Self-described as ""the top"" branding guru on the West Coast" +Ian,Dury,R&D,,"World-renowned expert in fuzzy logic design. Influential in technology purchases." \ No newline at end of file diff --git a/BulkAPISampleFiles/insert.xml b/BulkAPISampleFiles/insert.xml new file mode 100644 index 0000000..686ed5a --- /dev/null +++ b/BulkAPISampleFiles/insert.xml @@ -0,0 +1,17 @@ + + + + + Tom + Jones + Marketing + 1940-06-07Z + Self-described as "the top" branding guru on the West Coast + + + Ian + Dury + R&D + World-renowned expert in fuzzy logic design. Influential in technology purchases. + + \ No newline at end of file diff --git a/BulkAPISampleFiles/update.csv b/BulkAPISampleFiles/update.csv new file mode 100644 index 0000000..230ef1a --- /dev/null +++ b/BulkAPISampleFiles/update.csv @@ -0,0 +1,2 @@ +Id,Title +003E000001CbzBi,Ninja \ No newline at end of file diff --git a/BulkAPISampleFiles/update.xml b/BulkAPISampleFiles/update.xml new file mode 100644 index 0000000..8574c72 --- /dev/null +++ b/BulkAPISampleFiles/update.xml @@ -0,0 +1,8 @@ + + + + + 003E000001CbzBi + Pirate + + \ No newline at end of file diff --git a/BulkAPISampleFiles/upsert.csv b/BulkAPISampleFiles/upsert.csv new file mode 100644 index 0000000..5841c32 --- /dev/null +++ b/BulkAPISampleFiles/upsert.csv @@ -0,0 +1,2 @@ +Twitter_Handle__c,Title +pattest7,Guru \ No newline at end of file diff --git a/BulkAPISampleFiles/upsert.xml b/BulkAPISampleFiles/upsert.xml new file mode 100644 index 0000000..b942d57 --- /dev/null +++ b/BulkAPISampleFiles/upsert.xml @@ -0,0 +1,8 @@ + + + + + pattest7 + Pirate + + \ No newline at end of file diff --git a/BulkTK.md b/BulkTK.md new file mode 100644 index 0000000..74217e4 --- /dev/null +++ b/BulkTK.md @@ -0,0 +1,121 @@ +BulkTK: Force.com Bulk API JavaScript Toolkit +============================================= + +This minimal toolkit extends ForceTK to allow JavaScript in web pages to call the [Force.com Bulk API](https://www.salesforce.com/us/developer/docs/api_asynch/). + +Background +========== + +The Force.com Bulk API allows asynchronous data access. BulkTK extends ForceTK with methods to create Bulk API jobs, add batches to them, monitor job status and retrieve job results. Control plane XML is parsed to JavaScript objects for ease of use, while data is returned verbatim. + +You should familiarize yourself with the [Force.com Bulk API documentation](https://www.salesforce.com/us/developer/docs/api_asynch/), since BulkTK is a relatively thin layer on the raw XML Bulk API. + +bulk.page is a simple Visualforce single page application to demonstrate BulkTK. Try it out in a sandbox or developer edition. + +Note that, just like ForceTK, BulkTK is unsupported and supplied as is. It is also currently in a very early stage of development. It appears to work well, but bugs cannot be ruled out, and the interface should not be considered stable. + +Example Usage +============= + +You must create a ForceTK client first. On a Visualforce page, you would do: + + var client = new forcetk.Client(); + client.setSessionToken('{!$Api.Session_ID}'); + +See the ForceTK documentation for authenticating from an external website, such as a Heroku app, or PhoneGap/Cordova. + +Create a job +------------ + + // See https://www.salesforce.com/us/developer/docs/api_asynch/Content/asynch_api_reference_jobinfo.htm + // for details of the JobInfo structure + + // Insert Contact records in CSV format + var job = { + operation : 'insert', + object : 'Contact', + contentType : 'CSV' + }; + + client.createJob(job, function(response) { + jobId = response.jobInfo.id; + console.log('Job created with id '+jobId+'\n'); + }, function(jqXHR, textStatus, errorThrown) { + console.log('Error creating job', jqXHR.responseText); + }); + +Add a batch of records to the job +--------------------------------- + +You can add multiple batches to the job; each batch can contain up to 10,000 records. See [batch size and limits](https://www.salesforce.com/us/developer/docs/api_asynch/Content/asynch_api_concepts_limits.htm#batch_size_title) for more details. + + var csvData = "FirstName,LastName,Department,Birthdate,Description\n"+ + "Tom,Jones,Marketing,1940-06-07Z,"Self-described as ""the top"" branding guru on the West Coast\n"+ + "Ian,Dury,R&D,,"World-renowned expert in fuzzy logic design. Influential in technology purchases."\n"; + + client.addBatch(jobId, "text/csv; charset=UTF-8", csvData, + function(response){ + console.log('Added batch '+response.batchInfo.id+'. State: '+response.batchInfo.state+'\n'); + }, function(jqXHR, textStatus, errorThrown) { + console.log('Error adding batch', jqXHR.responseText); + }); + +See BulkAPISampleFiles for sample CSV and XML data for different operations. + +Close the job +------------- + +You must close the job to inform Salesforce that no more batches will be submitted for the job. + + client.closeJob(jobId, function(response){ + console.log('Job closed. State: '+response.jobInfo.state+'\n'); + }, function(jqXHR, textStatus, errorThrown) { + console.log('Error closing job', jqXHR.responseText); + }); + +Check batch status +------------------ + + client.getBatchDetails(jobId, batchId, function(response){ + console.log('Batch state: '+response.batchInfo.state+'\n'); + }, function(jqXHR, textStatus, errorThrown) { + console.log('Error getting batch details', jqXHR.responseText); + }); + +Get batch results +----------------- + +Pass `true` as the `parseXML` parameter to get batch results for a query, false otherwise. + + client.getBatchResult(jobId, batchId, false, function(response){ + console.log('Batch result: '+response); + }, function(jqXHR, textStatus, errorThrown) { + console.log('Error getting batch result', jqXHR.responseText); + }); + +Bulk query +---------- + +When adding a batch to a bulk query job, the `contentType` for the request must be either `text/csv` or `application/xml`, depending on the content type specified when the job was created. The actual SOQL statement supplied for the batch will be in plain text format. + + var soql = 'SELECT Id, FirstName, LastName, Email FROM Contact'; + + client.addBatch(jobId, 'text/csv', soql, function(response){ + console.log('Batch state: '+response.batchInfo.state+'\n'); + }, function(jqXHR, textStatus, errorThrown) { + console.log('Error getting batch result', jqXHR.responseText); + }); + +Getting bulk query results is a two step process. Call `getBatchResult()` with `parseXML` set to `true` to get a set of result IDs, then call `getBulkQueryResult()` to get the actual records for each result + + client.getBatchResult(jobId, batchId, true, function(response){ + response['result-list'].result.forEach(function(resultId){ + client.getBulkQueryResult(jobId, batchId, resultId, function(response){ + console.log('Batch result: '+response); + }, function(jqXHR, textStatus, errorThrown) { + console.log('Error getting bulk query results', jqXHR.responseText); + }); + }); + }, function(jqXHR, textStatus, errorThrown) { + console.log('Error getting batch result', jqXHR.responseText); + }); diff --git a/bulk.page b/bulk.page new file mode 100644 index 0000000..ded3603 --- /dev/null +++ b/bulk.page @@ -0,0 +1,254 @@ + + + + +
    +

    1. Create a Bulk API job


    + + +
    + + +
    + + + +
    +
    +
    
    +    
    + + + + + + + +
    \ No newline at end of file diff --git a/bulktk.js b/bulktk.js new file mode 100644 index 0000000..44c8447 --- /dev/null +++ b/bulktk.js @@ -0,0 +1,239 @@ +/* + * Copyright (c) 2015, salesforce.com, inc. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, are permitted provided + * that the following conditions are met: + * + * Redistributions of source code must retain the above copyright notice, this list of conditions and the + * following disclaimer. + * + * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and + * the following disclaimer in the documentation and/or other materials provided with the distribution. + * + * Neither the name of salesforce.com, inc. nor the names of its contributors may be used to endorse or + * promote products derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A + * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR + * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED + * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ + +/* + * BulkTK: JavaScript library to wrap Force.com Bulk API. Extends ForceTK. + * Dependencies: + * jquery - http://jquery.com/ + * ForceTK - https://github.com/developerforce/Force.com-JavaScript-REST-Toolkit + * jxon - https://github.com/wireload/Ratatosk/blob/master/jxon.js + */ + +forcetk.Client.prototype.xmlHeader = "\n"; + +/* + * Low level utility function to call the Bulk API. + * @param path resource path + * @param parseXML set to true to parse XML response + * @param callback function to which response will be passed + * @param [error=null] function to which jqXHR will be passed in case of error + * @param [method="GET"] HTTP method for call + * @param [contentType=null] Content type of payload - e.g. 'application/xml; charset=UTF-8' + * @param [payload=null] payload for POST + * @param [parseXML=false] set to true to parse XML response + */ +forcetk.Client.prototype.bulkAjax = function(path, parseXML, callback, error, method, contentType, payload, retry) { + var that = this; + var url = this.instanceUrl + path; + + if (this.debug) { + console.log('bulkAjax sending: ', payload); + } + + return $.ajax({ + type: method || "GET", + async: this.asyncAjax, + url: (this.proxyUrl !== null) ? this.proxyUrl: url, + contentType: method == "DELETE" ? null : contentType, + cache: false, + processData: false, + data: payload, + success: function(data, textStatus, jqXHR) { + var respContentType = jqXHR.getResponseHeader('Content-Type'); + // Naughty Bulk API doesn't always set Content-Type! + if (parseXML && + ((respContentType && respContentType.indexOf('application/xml') === 0) || + data.indexOf(' Date: Sun, 8 Mar 2015 21:56:51 -0700 Subject: [PATCH 41/60] More detail in BulkTK readme --- BulkTK.md | 22 +++++++++++++++++++--- 1 file changed, 19 insertions(+), 3 deletions(-) diff --git a/BulkTK.md b/BulkTK.md index 74217e4..cd07b63 100644 --- a/BulkTK.md +++ b/BulkTK.md @@ -10,19 +10,35 @@ The Force.com Bulk API allows asynchronous data access. BulkTK extends ForceTK w You should familiarize yourself with the [Force.com Bulk API documentation](https://www.salesforce.com/us/developer/docs/api_asynch/), since BulkTK is a relatively thin layer on the raw XML Bulk API. -bulk.page is a simple Visualforce single page application to demonstrate BulkTK. Try it out in a sandbox or developer edition. +[bulk.page](https://github.com/developerforce/Force.com-JavaScript-REST-Toolkit/blob/master/bulk.page) is a simple Visualforce single page application to demonstrate BulkTK. Try it out in a sandbox or developer edition. Note that, just like ForceTK, BulkTK is unsupported and supplied as is. It is also currently in a very early stage of development. It appears to work well, but bugs cannot be ruled out, and the interface should not be considered stable. +Dependencies +============ + + * [jquery](http://jquery.com/) + * [ForceTK](https://github.com/developerforce/Force.com-JavaScript-REST-Toolkit) + * [jxon](https://github.com/wireload/Ratatosk/blob/master/jxon.js) + Example Usage ============= -You must create a ForceTK client first. On a Visualforce page, you would do: +This example focuses on Visualforce. See the [ForceTK documentation](https://github.com/developerforce/Force.com-JavaScript-REST-Toolkit) for details on authenticating from an external website, such as a Heroku app, or PhoneGap/Cordova. + +First, include BulkTK and its dependencies: + + + + + + +Now create a ForceTK client: var client = new forcetk.Client(); client.setSessionToken('{!$Api.Session_ID}'); -See the ForceTK documentation for authenticating from an external website, such as a Heroku app, or PhoneGap/Cordova. +See the [ForceTK documentation](https://github.com/developerforce/Force.com-JavaScript-REST-Toolkit) for details on authenticating from an external website, such as a Heroku app, or PhoneGap/Cordova. Create a job ------------ From 2349e0ae5b5882b511393c82225c5e0c7b218dd6 Mon Sep 17 00:00:00 2001 From: Pat Patterson Date: Mon, 9 Mar 2015 07:11:50 -0700 Subject: [PATCH 42/60] Added jxon.js --- BulkTK.md | 2 +- jxon.js | 140 ++++++++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 141 insertions(+), 1 deletion(-) create mode 100644 jxon.js diff --git a/BulkTK.md b/BulkTK.md index cd07b63..a5eb38f 100644 --- a/BulkTK.md +++ b/BulkTK.md @@ -19,7 +19,7 @@ Dependencies * [jquery](http://jquery.com/) * [ForceTK](https://github.com/developerforce/Force.com-JavaScript-REST-Toolkit) - * [jxon](https://github.com/wireload/Ratatosk/blob/master/jxon.js) + * [jxon](https://github.com/developerforce/Force.com-JavaScript-REST-Toolkit/blob/master/jxon.js) (originally from the [Ratatosk](https://github.com/wireload/Ratatosk) project; this version preserves case in element and attribute names) Example Usage ============= diff --git a/jxon.js b/jxon.js new file mode 100644 index 0000000..192694d --- /dev/null +++ b/jxon.js @@ -0,0 +1,140 @@ +/* + * JXON.js + * Ratatosk + * + * Created by Alexander Ljungberg on March 15th, 2012. + * + * Public domain JXON implementation from algorithm #3 of: + * https://developer.mozilla.org/en/Parsing_and_serializing_XML + * + * Any copyright is dedicated to the Public Domain. + * + * Modified by Andrew (Pat) Patterson, 2015 from original at + * https://github.com/wireload/Ratatosk/blob/master/jxon.js + * to preserve case of element and attribute names + */ + +JXON = function() +{ + +}; + +JXON.buildValue = function(sValue) +{ + if (/^\s*$/.test(sValue)) + return null; + if (/^(true|false)$/i.test(sValue)) + return sValue.toLowerCase() === "true"; + if (isFinite(sValue)) + return parseFloat(sValue); + // Don't do this - it'll parse anything that looks like a date and get the timezone wrong. + // https://bugzilla.mozilla.org/show_bug.cgi?id=693077 + //if (isFinite(Date.parse(sValue))) + // return new Date(sValue); + return sValue; +}; + +JXON.fromXML = function(xmlString) +{ + return JXON.getJXONData((new DOMParser()).parseFromString(xmlString, "text/xml")); +}; + +JXON.getJXONData = function(oXMLParent) +{ + var vResult = /* put here the default value for empty nodes! */ null, + nLength = 0, + sCollectedTxt = ""; + if (oXMLParent.hasAttributes && oXMLParent.hasAttributes()) + { + vResult = {}; + for (nLength; nLength < oXMLParent.attributes.length; nLength++) + { + oItAttr = oXMLParent.attributes.item(nLength); + vResult["@" + oItAttr.nodeName] = JXON.buildValue(oItAttr.value.replace(/^\s+|\s+$/g, "")); + } + } + if (oXMLParent.hasChildNodes()) + { + for (var oItChild, sItKey, sItVal, nChildId = 0; nChildId < oXMLParent.childNodes.length; nChildId++) + { + oItChild = oXMLParent.childNodes.item(nChildId); + if (oItChild.nodeType === 4) + { + sCollectedTxt += oItChild.nodeValue; + } /* nodeType is "CDATASection" (4) */ + else if (oItChild.nodeType === 3) + { + sCollectedTxt += oItChild.nodeValue.replace(/^\s+|\s+$/g, ""); + } /* nodeType is "Text" (3) */ + else if (oItChild.nodeType === 1 && !oItChild.prefix) + { /* nodeType is "Element" (1) */ + if (nLength === 0) + vResult = {}; + sItKey = oItChild.nodeName; + sItVal = JXON.getJXONData(oItChild); + if (vResult.hasOwnProperty(sItKey)) + { + if (vResult[sItKey].constructor !== Array) + vResult[sItKey] = [vResult[sItKey]]; + vResult[sItKey].push(sItVal); + } + else + { + vResult[sItKey] = sItVal; + nLength++; + } + } + } + } + if (sCollectedTxt) + nLength > 0 ? vResult.keyValue = JXON.buildValue(sCollectedTxt) : vResult = JXON.buildValue(sCollectedTxt); + /* if (nLength > 0) { Object.freeze(vResult); } */ + return vResult; +}; + +JXON.loadObj = function(oParentObj, oParentEl, oNewDoc) +{ + var nSameIdx, + vValue, + oChild; + for (var sName in oParentObj) + { + vValue = oParentObj[sName]; + if (sName === "keyValue") + { + if (vValue !== null && vValue !== true) + oParentEl.appendChild(oNewDoc.createTextNode(String(vValue))); + } + else if (sName.charAt(0) === "@") + oParentEl.setAttribute(sName.slice(1), vValue); + else + { + oChild = oNewDoc.createElement(sName); + if (vValue && vValue.constructor === Date) + oChild.appendChild(oNewDoc.createTextNode(vValue.toGMTString())); + else if (vValue && vValue.constructor === Array) + { + for (nSameIdx = 0; nSameIdx < vValue.length; nSameIdx++) + JXON.loadObj(vValue[nSameIdx], oChild); + } + else if (vValue && vValue instanceof Object) + { + JXON.loadObj(vValue, oChild, oNewDoc); + } + else if (vValue !== null && vValue !== true) + oChild.appendChild(oNewDoc.createTextNode(vValue.toString())); + + oParentEl.appendChild(oChild); + // CPLog.error("Document: " + (new XMLSerializer()).serializeToString(oNewDoc)); + } + } +}; + +JXON.toXML = function(oJXONObj, rootName) +{ + var oNewDoc = document.implementation.createDocument("", "", null), + rootNode = oNewDoc.createElement(rootName || 'xml'); + oNewDoc.appendChild(rootNode); + JXON.loadObj(oJXONObj, rootNode, oNewDoc); + return (new XMLSerializer()).serializeToString(oNewDoc); +}; From c3edd29d3395064db8fc9b402a943f38c3d0333e Mon Sep 17 00:00:00 2001 From: Pat Patterson Date: Mon, 9 Mar 2015 08:26:29 -0700 Subject: [PATCH 43/60] Dependencies, fix proxying in Visualforce --- bulk.page | 1 + bulktk.js | 10 ++++++---- 2 files changed, 7 insertions(+), 4 deletions(-) diff --git a/bulk.page b/bulk.page index ded3603..e9e7504 100644 --- a/bulk.page +++ b/bulk.page @@ -92,6 +92,7 @@ Sample Visualforce page for Force.com Bulk API JavaScript Toolkit + - - - - - - + + + + + + From 42abd3d633d82b4fc0f97cf5082457cc125422c9 Mon Sep 17 00:00:00 2001 From: Pat Patterson Date: Wed, 1 Apr 2015 08:29:53 -0700 Subject: [PATCH 45/60] Updated jQuery Mobile to latest --- mobileapp.js | 20 ++++++++++---------- phonegap.html | 41 +++++++++++++++++++---------------------- 2 files changed, 29 insertions(+), 32 deletions(-) diff --git a/mobileapp.js b/mobileapp.js index f2e8de7..eeb9242 100644 --- a/mobileapp.js +++ b/mobileapp.js @@ -48,12 +48,12 @@ function addClickListeners() { $('#deletebtn').click(function(e) { // Delete the account e.preventDefault(); - $.mobile.pageLoading(); + $.mobile.loading('show'); client.del('Account', $('#accountdetail').find('#Id').val() , function(response) { getAccounts(function() { - $.mobile.pageLoading(true); + $.mobile.loading('hide'); $.mobile.changePage('#mainpage', "slide", true, true); }); }, errorCallback); @@ -62,7 +62,7 @@ function addClickListeners() { $('#editbtn').click(function(e) { // Get account fields and show the 'Edit Account' form e.preventDefault(); - $.mobile.pageLoading(); + $.mobile.loading('show'); client.retrieve("Account", $('#accountdetail').find('#Id').val() , "Name,Id,Industry,TickerSymbol", function(response) { @@ -74,7 +74,7 @@ function addClickListeners() { $('#actionbtn') .unbind('click.btn') .bind('click.btn', updateHandler); - $.mobile.pageLoading(true); + $.mobile.loading('hide'); $.mobile.changePage('#editpage', "slide", false, true); }, errorCallback); }); @@ -94,7 +94,7 @@ function getAccounts(callback) { .append('

    ' + this.Name + '

    ') .click(function(e) { e.preventDefault(); - $.mobile.pageLoading(); + $.mobile.loading('show'); // We could do this more efficiently by adding Industry and // TickerSymbol to the fields in the SELECT, but we want to // show dynamic use of the retrieve function... @@ -105,7 +105,7 @@ function getAccounts(callback) { $('#Industry').text(response.Industry); $('#TickerSymbol').text(response.TickerSymbol); $('#Id').val(response.Id); - $.mobile.pageLoading(true); + $.mobile.loading('hide'); $.mobile.changePage('#detailpage', "slide", false, true); }, errorCallback); }) @@ -132,11 +132,11 @@ function createHandler(e) { fields[child.attr("name")] = child.val(); } }); - $.mobile.pageLoading(); + $.mobile.loading('show'); client.create('Account', fields, function(response) { getAccounts(function() { - $.mobile.pageLoading(true); + $.mobile.loading('hide'); $.mobile.changePage('#mainpage', "slide", true, true); }); }, errorCallback); @@ -153,12 +153,12 @@ function updateHandler(e) { fields[child.attr("name")] = child.val(); } }); - $.mobile.pageLoading(); + $.mobile.loading('show'); client.update('Account', accountform.find('#Id').val(), fields , function(response) { getAccounts(function() { - $.mobile.pageLoading(true); + $.mobile.loading('hide'); $.mobile.changePage('#mainpage', "slide", true, true); }); }, errorCallback); diff --git a/phonegap.html b/phonegap.html index be7c71f..818d1cd 100644 --- a/phonegap.html +++ b/phonegap.html @@ -48,9 +48,9 @@ from the CDN, but then the device needs to be online for the app to be functional. --> - - - + + + @@ -90,7 +90,7 @@ function() { client.setRefreshToken(null); $.mobile.changePage('#loginpage', "slide", false, true); - $.mobile.pageLoading(); + $.mobile.loading('show'); var ref = window.open(getAuthorizeUrl(loginUrl, clientId, redirectUri), '_blank', 'location=no,toolbar=no'); ref.addEventListener('loadstop', function(evt) { if (evt.url.startsWith(redirectUri)) { @@ -105,9 +105,9 @@ }); $.mobile.changePage('#mainpage', "slide", false, true); - $.mobile.pageLoading(); + $.mobile.loading('show'); getAccounts(function() { - $.mobile.pageLoading(true); + $.mobile.loading('hide'); }); } @@ -152,7 +152,7 @@ keychain = new Keychain(); keychain.getForKey( function(value) { - $.mobile.pageLoading(); + $.mobile.loading('show'); client.setRefreshToken(value); client.refreshAccessToken(sessionCallback, function(jqXHR, textStatus, errorThrown) { @@ -173,7 +173,7 @@ -
    +

    Login

    @@ -184,16 +184,15 @@

    Login

    Force.com

    -
    -
    +
    +

    Account List

    -
      +
      @@ -203,8 +202,8 @@

      Account List

      Force.com

    -
    -
    +
    +

    Account Detail

    @@ -217,15 +216,15 @@

    Account Detail

    + data-theme="b">Delete

    Force.com

    -
    -
    +
    +

    New Account

    @@ -234,17 +233,15 @@

    New Account

    - + - + - +
    Account Name:
    Industry:
    Ticker Symbol:
    From 224c054db9a2c720dbc1c2b800a8fe61ef94776d Mon Sep 17 00:00:00 2001 From: Pat Patterson Date: Wed, 1 Apr 2015 09:52:03 -0700 Subject: [PATCH 46/60] Updated README for Cordova 4.3.0, made sample filename more explicit. --- README.markdown | 109 +++++++++++++++++------------- phonegap.html => cordova-ios.html | 0 2 files changed, 61 insertions(+), 48 deletions(-) rename phonegap.html => cordova-ios.html (100%) diff --git a/README.markdown b/README.markdown index c29671c..2e25be7 100644 --- a/README.markdown +++ b/README.markdown @@ -151,39 +151,50 @@ Your HTML page will need to include jQuery and the toolkit, then create a client More fully featured samples are provided in [example.html](Force.com-JavaScript-REST-Toolkit/blob/master/example.html) and [mobile.html](Force.com-JavaScript-REST-Toolkit/blob/master/mobile.html). -Using the Toolkit in a PhoneGap app ------------------------------------ +Using the Toolkit in a Cordova app +---------------------------------- -Your HTML page will need to include jQuery, the toolkit, PhoneGap and the ChildBrowser plugin, then create a client object, passing a session ID to the constructor. You can use __https://login.salesforce.com/services/oauth2/success__ as the redirect URI and catch the page load in ChildBrowser. +Your HTML page will need to include jQuery, the toolkit and Cordova. You will also need to install the [InAppBrowser](http://plugins.cordova.io/#/package/org.apache.cordova.inappbrowser) plugin to be able to pop up a browser window for authentication. Create a client object, passing a session ID to the constructor. You can use __https://login.salesforce.com/services/oauth2/success__ as the redirect URI and catch the page load in InAppBrowser. An absolutely minimal sample using OAuth to obtain a session ID is: + - - - - - + + + -

    Click here.

    + + + +

    + -A fully featured sample (including persistence of the OAuth refresh token to the iOS Keychain) is provided in [phonegap.html](Force.com-JavaScript-REST-Toolkit/blob/master/phonegap.html). +A fully featured sample (including persistence of the OAuth refresh token to the iOS Keychain) is provided in [cordova-ios.html](Force.com-JavaScript-REST-Toolkit/blob/master/cordova-ios.html). The sample uses Cordova 4.3.0 and the InAppBrowser and iOS Keychain plugins. Install these with + cordova plugin add org.apache.cordova.inappbrowser + cordova plugin add com.shazron.cordova.plugin.keychainutil diff --git a/phonegap.html b/cordova-ios.html similarity index 100% rename from phonegap.html rename to cordova-ios.html From 54e92659d205a7aad41e193be25b22c059995aa2 Mon Sep 17 00:00:00 2001 From: Pat Patterson Date: Wed, 1 Apr 2015 09:58:31 -0700 Subject: [PATCH 47/60] Fixed path to cordova-ios.html --- README.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.markdown b/README.markdown index 2e25be7..e3c0368 100644 --- a/README.markdown +++ b/README.markdown @@ -239,7 +239,7 @@ An absolutely minimal sample using OAuth to obtain a session ID is: -A fully featured sample (including persistence of the OAuth refresh token to the iOS Keychain) is provided in [cordova-ios.html](Force.com-JavaScript-REST-Toolkit/blob/master/cordova-ios.html). The sample uses Cordova 4.3.0 and the InAppBrowser and iOS Keychain plugins. Install these with +A fully featured sample (including persistence of the OAuth refresh token to the iOS Keychain) for iOS is provided in [cordova-ios.html](https://github.com/developerforce/Force.com-JavaScript-REST-Toolkit/blob/master/cordova-ios.html). The sample uses Cordova 4.3.0 and the InAppBrowser and iOS Keychain plugins. Install these with cordova plugin add org.apache.cordova.inappbrowser cordova plugin add com.shazron.cordova.plugin.keychainutil From 0dcaf13e92f3e1bb7f184d81026358f8d8d6cf55 Mon Sep 17 00:00:00 2001 From: Pat Patterson Date: Tue, 26 May 2015 11:25:09 -0700 Subject: [PATCH 48/60] Return null from blob() for async calls - fixes #65 --- forcetk.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/forcetk.js b/forcetk.js index d965d2a..702692e 100644 --- a/forcetk.js +++ b/forcetk.js @@ -323,7 +323,7 @@ if (forcetk.Client === undefined) { request.send(blob); - return this.asyncAjax ? JSON.parse(request.response) : null; + return this.asyncAjax ? null : JSON.parse(request.response); } /* From f177720cc6e67abdbfc9e31ec7c7e05903c881c2 Mon Sep 17 00:00:00 2001 From: Pat Patterson Date: Thu, 28 May 2015 12:06:07 -0700 Subject: [PATCH 49/60] Accept JSON from API --- forcetk.js | 1 + 1 file changed, 1 insertion(+) diff --git a/forcetk.js b/forcetk.js index 702692e..b4deb3e 100644 --- a/forcetk.js +++ b/forcetk.js @@ -293,6 +293,7 @@ if (forcetk.Client === undefined) { var request = new XMLHttpRequest(); request.open("POST", (this.proxyUrl !== null && ! this.visualforce) ? this.proxyUrl: url, this.asyncAjax); + request.setRequestHeader('Accept', 'application/json'); request.setRequestHeader(this.authzHeader, "Bearer " + this.sessionId); request.setRequestHeader('X-User-Agent', 'salesforce-toolkit-rest-javascript/' + this.apiVersion); if (this.proxyUrl !== null && ! this.visualforce) { From b8c759e4a1f43e7fa873efb9a6ac68c4a11d6050 Mon Sep 17 00:00:00 2001 From: Pat Patterson Date: Thu, 28 May 2015 12:07:43 -0700 Subject: [PATCH 50/60] Revert "Accept JSON from API" This reverts commit f177720cc6e67abdbfc9e31ec7c7e05903c881c2. --- forcetk.js | 1 - 1 file changed, 1 deletion(-) diff --git a/forcetk.js b/forcetk.js index b4deb3e..702692e 100644 --- a/forcetk.js +++ b/forcetk.js @@ -293,7 +293,6 @@ if (forcetk.Client === undefined) { var request = new XMLHttpRequest(); request.open("POST", (this.proxyUrl !== null && ! this.visualforce) ? this.proxyUrl: url, this.asyncAjax); - request.setRequestHeader('Accept', 'application/json'); request.setRequestHeader(this.authzHeader, "Bearer " + this.sessionId); request.setRequestHeader('X-User-Agent', 'salesforce-toolkit-rest-javascript/' + this.apiVersion); if (this.proxyUrl !== null && ! this.visualforce) { From fcbb8a784533fa67836d5d8de3298c2e7e06b8ae Mon Sep 17 00:00:00 2001 From: Pat Patterson Date: Thu, 28 May 2015 12:13:26 -0700 Subject: [PATCH 51/60] Accept JSON from API. Fixes #65 --- forcetk.js | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/forcetk.js b/forcetk.js index 702692e..eef5ac7 100644 --- a/forcetk.js +++ b/forcetk.js @@ -292,7 +292,8 @@ if (forcetk.Client === undefined) { var request = new XMLHttpRequest(); request.open("POST", (this.proxyUrl !== null && ! this.visualforce) ? this.proxyUrl: url, this.asyncAjax); - + + request.setRequestHeader('Accept', 'application/json'); request.setRequestHeader(this.authzHeader, "Bearer " + this.sessionId); request.setRequestHeader('X-User-Agent', 'salesforce-toolkit-rest-javascript/' + this.apiVersion); if (this.proxyUrl !== null && ! this.visualforce) { From 21e7ab9ed0b3ced69316c7ef60e6dac769b2fb9a Mon Sep 17 00:00:00 2001 From: Menno Vanderlist Date: Fri, 10 Jul 2015 09:27:11 -0600 Subject: [PATCH 52/60] Replaced escape(soql) and escape(sosl) Fix to support umlaut and other European charaters Replaced with encodeURIComponent(soql) and encodeURIComponent(sosl) --- forcetk.js | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/forcetk.js b/forcetk.js index eef5ac7..eb1d7f2 100644 --- a/forcetk.js +++ b/forcetk.js @@ -562,7 +562,7 @@ if (forcetk.Client === undefined) { * @param [error=null] function to which jqXHR will be passed in case of error */ forcetk.Client.prototype.query = function(soql, callback, error) { - return this.ajax('/' + this.apiVersion + '/query?q=' + escape(soql) + return this.ajax('/' + this.apiVersion + '/query?q=' + encodeURIComponent(soql) , callback, error); } @@ -598,7 +598,7 @@ if (forcetk.Client === undefined) { * @param [error=null] function to which jqXHR will be passed in case of error */ forcetk.Client.prototype.search = function(sosl, callback, error) { - return this.ajax('/' + this.apiVersion + '/search?q=' + escape(sosl) + return this.ajax('/' + this.apiVersion + '/search?q=' + encodeURIComponent(sosl) , callback, error); } } From f13596c8aedef867d5aef4978ccf05f275ef948d Mon Sep 17 00:00:00 2001 From: Sean Cuevo Date: Fri, 2 Oct 2015 14:55:29 -0600 Subject: [PATCH 53/60] removing extra new line that would corrupt ms office file attachments --- forcetk.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/forcetk.js b/forcetk.js index eb1d7f2..cc640d7 100644 --- a/forcetk.js +++ b/forcetk.js @@ -286,7 +286,7 @@ if (forcetk.Client === undefined) { + "Content-Disposition: form-data; name=\"" + payloadField + "\"; filename=\"" + filename + "\"\n\n", payload, - "\n\n" + "\n" + "--boundary_" + boundary + "--" ], {type : 'multipart/form-data; boundary=\"boundary_' + boundary + '\"'}); From f05d17c402be989436e42bce16aa5dbaf075f72b Mon Sep 17 00:00:00 2001 From: Sean Cuevo Date: Fri, 2 Oct 2015 14:57:02 -0600 Subject: [PATCH 54/60] adding content type for attachments for IE 11 support --- forcetk.js | 1 + 1 file changed, 1 insertion(+) diff --git a/forcetk.js b/forcetk.js index eb1d7f2..e1865b2 100644 --- a/forcetk.js +++ b/forcetk.js @@ -296,6 +296,7 @@ if (forcetk.Client === undefined) { request.setRequestHeader('Accept', 'application/json'); request.setRequestHeader(this.authzHeader, "Bearer " + this.sessionId); request.setRequestHeader('X-User-Agent', 'salesforce-toolkit-rest-javascript/' + this.apiVersion); + request.setRequestHeader('Content-Type', 'multipart/form-data; boundary=\"boundary_' + boundary + '\"'); if (this.proxyUrl !== null && ! this.visualforce) { request.setRequestHeader('SalesforceProxy-Endpoint', url); } From fb347412c12b482a66e6bccf68a9bf8caad9729c Mon Sep 17 00:00:00 2001 From: Pat Patterson Date: Tue, 6 Oct 2015 11:02:30 -0700 Subject: [PATCH 55/60] Fixed typo in filename parameter. Fixes #74 --- forcetk.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/forcetk.js b/forcetk.js index eef5ac7..ebd6059 100644 --- a/forcetk.js +++ b/forcetk.js @@ -311,7 +311,7 @@ if (forcetk.Client === undefined) { } else if(request.status == 401 && !retry) { that.refreshAccessToken(function(oauthResponse) { that.setSessionToken(oauthResponse.access_token, null,oauthResponse.instance_url); - that.blob(path, fields, fileName, file, callback, error, true); + that.blob(path, fields, filename, file, callback, error, true); }, error); } else { From e12fc025215b5f146f7e5677a2f058c63eeecd61 Mon Sep 17 00:00:00 2001 From: Pat Patterson Date: Wed, 14 Oct 2015 11:25:32 -0700 Subject: [PATCH 56/60] Fixed all JSLint errors/warnings. Fixes #75 --- forcetk.js | 391 ++++++++++++++++++++++++++++------------------------- 1 file changed, 205 insertions(+), 186 deletions(-) diff --git a/forcetk.js b/forcetk.js index 0013562..d568e42 100644 --- a/forcetk.js +++ b/forcetk.js @@ -32,6 +32,9 @@ * console, go to Your Name | Setup | Security Controls | Remote Site Settings */ +/*jslint browser: true*/ +/*global alert, Blob, $, jQuery*/ + var forcetk = window.forcetk; if (forcetk === undefined) { @@ -50,10 +53,11 @@ if (forcetk.Client === undefined) { * PhoneGap etc * @constructor */ - forcetk.Client = function(clientId, loginUrl, proxyUrl) { + forcetk.Client = function (clientId, loginUrl, proxyUrl) { + 'use strict'; this.clientId = clientId; this.loginUrl = loginUrl || 'https://login.salesforce.com/'; - if (typeof proxyUrl === 'undefined' || proxyUrl === null) { + if (proxyUrl === undefined || proxyUrl === null) { if (location.protocol === 'file:' || location.protocol === 'ms-appx:') { // In PhoneGap this.proxyUrl = null; @@ -74,40 +78,42 @@ if (forcetk.Client === undefined) { this.visualforce = false; this.instanceUrl = null; this.asyncAjax = true; - } + }; /** * Set a refresh token in the client. * @param refreshToken an OAuth refresh token */ - forcetk.Client.prototype.setRefreshToken = function(refreshToken) { + forcetk.Client.prototype.setRefreshToken = function (refreshToken) { + 'use strict'; this.refreshToken = refreshToken; - } + }; /** * Refresh the access token. * @param callback function to call on success * @param error function to call on failure */ - forcetk.Client.prototype.refreshAccessToken = function(callback, error) { - var that = this; - var url = this.loginUrl + '/services/oauth2/token'; + forcetk.Client.prototype.refreshAccessToken = function (callback, error) { + 'use strict'; + var that = this, + url = this.loginUrl + '/services/oauth2/token'; return $.ajax({ type: 'POST', - url: (this.proxyUrl !== null && ! this.visualforce) ? this.proxyUrl: url, + url: (this.proxyUrl !== null && !this.visualforce) ? this.proxyUrl : url, cache: false, processData: false, data: 'grant_type=refresh_token&client_id=' + this.clientId + '&refresh_token=' + this.refreshToken, success: callback, error: error, dataType: "json", - beforeSend: function(xhr) { - if (that.proxyUrl !== null && ! this.visualforce) { + beforeSend: function (xhr) { + if (that.proxyUrl !== null && !this.visualforce) { xhr.setRequestHeader('SalesforceProxy-Endpoint', url); } } }); - } + }; /** * Set a session token and the associated metadata in the client. @@ -117,32 +123,32 @@ if (forcetk.Client === undefined) { * @param [instanceUrl] Omit this if running on Visualforce; otherwise * use the value from the OAuth token. */ - forcetk.Client.prototype.setSessionToken = function(sessionId, apiVersion, instanceUrl) { + forcetk.Client.prototype.setSessionToken = function (sessionId, apiVersion, instanceUrl) { + 'use strict'; this.sessionId = sessionId; - this.apiVersion = (typeof apiVersion === 'undefined' || apiVersion === null) - ? 'v29.0': apiVersion; - if (typeof instanceUrl === 'undefined' || instanceUrl == null) { + this.apiVersion = (apiVersion === undefined || apiVersion === null) + ? 'v29.0' : apiVersion; + if (instanceUrl === undefined || instanceUrl === null) { this.visualforce = true; // location.hostname can be of the form 'abc.na1.visual.force.com', // 'na1.salesforce.com' or 'abc.my.salesforce.com' (custom domains). // Split on '.', and take the [1] or [0] element as appropriate - var elements = location.hostname.split("."); - - var instance = null; - if(elements.length == 4 && elements[1] === 'my') { + var elements = location.hostname.split("."), + instance = null; + if (elements.length === 4 && elements[1] === 'my') { instance = elements[0] + '.' + elements[1]; - } else if(elements.length == 3){ + } else if (elements.length === 3) { instance = elements[0]; } else { instance = elements[1]; } - + this.instanceUrl = "https://" + instance + ".salesforce.com"; } else { this.instanceUrl = instanceUrl; } - } + }; /* * Low level utility function to call the Salesforce endpoint. @@ -152,41 +158,42 @@ if (forcetk.Client === undefined) { * @param [method="GET"] HTTP method for call * @param [payload=null] payload for POST/PATCH etc */ - forcetk.Client.prototype.ajax = function(path, callback, error, method, payload, retry) { - var that = this; - var url = (this.visualforce ? '' : this.instanceUrl) + '/services/data' + path; + forcetk.Client.prototype.ajax = function (path, callback, error, method, payload, retry) { + 'use strict'; + var that = this, + url = (this.visualforce ? '' : this.instanceUrl) + '/services/data' + path; return $.ajax({ type: method || "GET", async: this.asyncAjax, - url: (this.proxyUrl !== null && ! this.visualforce) ? this.proxyUrl: url, - contentType: method == "DELETE" ? null : 'application/json', + url: (this.proxyUrl !== null && !this.visualforce) ? this.proxyUrl : url, + contentType: method === "DELETE" ? null : 'application/json', cache: false, processData: false, data: payload, success: callback, - error: (!this.refreshToken || retry ) ? error : function(jqXHR, textStatus, errorThrown) { + error: (!this.refreshToken || retry) ? error : function (jqXHR, textStatus, errorThrown) { if (jqXHR.status === 401) { - that.refreshAccessToken(function(oauthResponse) { + that.refreshAccessToken(function (oauthResponse) { that.setSessionToken(oauthResponse.access_token, null, - oauthResponse.instance_url); + oauthResponse.instance_url); that.ajax(path, callback, error, method, payload, true); }, - error); + error); } else { error(jqXHR, textStatus, errorThrown); } }, dataType: "json", - beforeSend: function(xhr) { - if (that.proxyUrl !== null && ! that.visualforce) { + beforeSend: function (xhr) { + if (that.proxyUrl !== null && !that.visualforce) { xhr.setRequestHeader('SalesforceProxy-Endpoint', url); } xhr.setRequestHeader(that.authzHeader, "Bearer " + that.sessionId); xhr.setRequestHeader('X-User-Agent', 'salesforce-toolkit-rest-javascript/' + that.apiVersion); } }); - } + }; /** * Utility function to query the Chatter API and download a file @@ -200,64 +207,61 @@ if (forcetk.Client === undefined) { * @param [error=null] function to which request will be passed in case of error * @param retry true if we've already tried refresh token flow once */ - forcetk.Client.prototype.getChatterFile = function(path, mimeType, callback, error, retry) { - var that = this; - var url = (this.visualforce ? '' : this.instanceUrl) + path; + forcetk.Client.prototype.getChatterFile = function (path, mimeType, callback, error, retry) { + 'use strict'; + var that = this, + url = (this.visualforce ? '' : this.instanceUrl) + path, + request = new XMLHttpRequest(); - var request = new XMLHttpRequest(); - - request.open("GET", (this.proxyUrl !== null && ! this.visualforce) ? this.proxyUrl: url, true); + request.open("GET", (this.proxyUrl !== null && !this.visualforce) ? this.proxyUrl : url, true); request.responseType = "arraybuffer"; - + request.setRequestHeader(this.authzHeader, "Bearer " + this.sessionId); request.setRequestHeader('X-User-Agent', 'salesforce-toolkit-rest-javascript/' + this.apiVersion); - if (this.proxyUrl !== null && ! this.visualforce) { + if (this.proxyUrl !== null && !this.visualforce) { request.setRequestHeader('SalesforceProxy-Endpoint', url); } - - request.onreadystatechange = function() { + + request.onreadystatechange = function () { // continue if the process is completed - if (request.readyState == 4) { + if (request.readyState === 4) { // continue only if HTTP status is "OK" - if (request.status == 200) { + if (request.status === 200) { try { // retrieve the response callback(request.response); - } - catch(e) { + } catch (e) { // display error message alert("Error reading the response: " + e.toString()); } - } - //refresh token in 401 - else if(request.status == 401 && !retry) { - that.refreshAccessToken(function(oauthResponse) { - that.setSessionToken(oauthResponse.access_token, null,oauthResponse.instance_url); + } else if (request.status === 401 && !retry) { + //refresh token in 401 + that.refreshAccessToken(function (oauthResponse) { + that.setSessionToken(oauthResponse.access_token, null, oauthResponse.instance_url); that.getChatterFile(path, mimeType, callback, error, true); - }, - error); - } - else { + }, error); + } else { // display status message - error(request,request.statusText,request.response); + error(request, request.statusText, request.response); } - } - - } + } + }; request.send(); - - } - + + }; + // Local utility to create a random string for multipart boundary - function randomString() { - var str = ''; - for (var i = 0; i < 4; i++) { - str += (Math.random().toString(16)+"000000000").substr(2,8); + var randomString = function () { + 'use strict'; + var str = '', + i; + for (i = 0; i < 4; i += 1) { + str += (Math.random().toString(16) + "000000000").substr(2, 8); } return str; - } - + }; + /* Low level function to create/update records with blob data * @param path resource path relative to /services/data * @param fields an object containing initial field names and values for @@ -270,63 +274,62 @@ if (forcetk.Client === undefined) { * @param [error=null] function to which response will be passed in case of error * @param retry true if we've already tried refresh token flow once */ - forcetk.Client.prototype.blob = function(path, fields, filename, payloadField, payload, callback, error, retry) { - var that = this; - var url = (this.visualforce ? '' : this.instanceUrl) + '/services/data' + path; - var boundary = randomString(); - - var blob = new Blob([ - "--boundary_" + boundary + '\n' - + "Content-Disposition: form-data; name=\"entity_content\";" + "\n" - + "Content-Type: application/json" + "\n\n" - + JSON.stringify(fields) - + "\n\n" - + "--boundary_" + boundary + "\n" - + "Content-Type: application/octet-stream" + "\n" - + "Content-Disposition: form-data; name=\"" + payloadField - + "\"; filename=\"" + filename + "\"\n\n", - payload, - "\n\n" - + "--boundary_" + boundary + "--" - ], {type : 'multipart/form-data; boundary=\"boundary_' + boundary + '\"'}); - - var request = new XMLHttpRequest(); - request.open("POST", (this.proxyUrl !== null && ! this.visualforce) ? this.proxyUrl: url, this.asyncAjax); + forcetk.Client.prototype.blob = function (path, fields, filename, payloadField, payload, callback, error, retry) { + 'use strict'; + var that = this, + url = (this.visualforce ? '' : this.instanceUrl) + '/services/data' + path, + boundary = randomString(), + blob = new Blob([ + "--boundary_" + boundary + '\n' + + "Content-Disposition: form-data; name=\"entity_content\";" + "\n" + + "Content-Type: application/json" + "\n\n" + + JSON.stringify(fields) + + "\n\n" + + "--boundary_" + boundary + "\n" + + "Content-Type: application/octet-stream" + "\n" + + "Content-Disposition: form-data; name=\"" + payloadField + + "\"; filename=\"" + filename + "\"\n\n", + payload, + "\n\n" + + "--boundary_" + boundary + "--" + ], {type : 'multipart/form-data; boundary=\"boundary_' + boundary + '\"'}), + request = new XMLHttpRequest(); + + request.open("POST", (this.proxyUrl !== null && !this.visualforce) ? this.proxyUrl : url, this.asyncAjax); request.setRequestHeader('Accept', 'application/json'); request.setRequestHeader(this.authzHeader, "Bearer " + this.sessionId); request.setRequestHeader('X-User-Agent', 'salesforce-toolkit-rest-javascript/' + this.apiVersion); - if (this.proxyUrl !== null && ! this.visualforce) { + if (this.proxyUrl !== null && !this.visualforce) { request.setRequestHeader('SalesforceProxy-Endpoint', url); } - + if (this.asyncAjax) { - request.onreadystatechange = function() { + request.onreadystatechange = function () { // continue if the process is completed - if (request.readyState == 4) { + if (request.readyState === 4) { // continue only if HTTP status is good if (request.status >= 200 && request.status < 300) { // retrieve the response callback(request.response ? JSON.parse(request.response) : null); - } else if(request.status == 401 && !retry) { - that.refreshAccessToken(function(oauthResponse) { - that.setSessionToken(oauthResponse.access_token, null,oauthResponse.instance_url); - that.blob(path, fields, filename, file, callback, error, true); - }, - error); + } else if (request.status === 401 && !retry) { + that.refreshAccessToken(function (oauthResponse) { + that.setSessionToken(oauthResponse.access_token, null, oauthResponse.instance_url); + that.blob(path, fields, filename, payloadField, payload, callback, error, true); + }, error); } else { // return status message error(request, request.statusText, request.response); } - } - } + } + }; } - + request.send(blob); - + return this.asyncAjax ? null : JSON.parse(request.response); - } - + }; + /* * Create a record with blob data * @param objtype object type; e.g. "ContentVersion" @@ -340,12 +343,13 @@ if (forcetk.Client === undefined) { * @param [error=null] function to which response will be passed in case of error * @param retry true if we've already tried refresh token flow once */ - forcetk.Client.prototype.createBlob = function(objtype, fields, filename, - payloadField, payload, callback, - error, retry) { - return this.blob('/' + this.apiVersion + '/sobjects/' + objtype + '/', - fields, filename, payloadField, payload, callback, error); - } + forcetk.Client.prototype.createBlob = function (objtype, fields, filename, + payloadField, payload, callback, + error, retry) { + 'use strict'; + return this.blob('/' + this.apiVersion + '/sobjects/' + objtype + '/', + fields, filename, payloadField, payload, callback, error, retry); + }; /* * Update a record with blob data @@ -361,12 +365,13 @@ if (forcetk.Client === undefined) { * @param [error=null] function to which response will be passed in case of error * @param retry true if we've already tried refresh token flow once */ - forcetk.Client.prototype.updateBlob = function(objtype, id, fields, filename, - payloadField, payload, callback, - error, retry) { - return this.blob('/' + this.apiVersion + '/sobjects/' + objtype + '/' + id + - '?_HttpMethod=PATCH', fields, filename, payloadField, payload, callback, error); - } + forcetk.Client.prototype.updateBlob = function (objtype, id, fields, filename, + payloadField, payload, callback, + error, retry) { + 'use strict'; + return this.blob('/' + this.apiVersion + '/sobjects/' + objtype + '/' + id + + '?_HttpMethod=PATCH', fields, filename, payloadField, payload, callback, error, retry); + }; /* * Low level utility function to call the Salesforce endpoint specific for Apex REST API. @@ -378,33 +383,34 @@ if (forcetk.Client === undefined) { * @param [paramMap={}] parameters to send as header values for POST/PATCH etc * @param [retry] specifies whether to retry on error */ - forcetk.Client.prototype.apexrest = function(path, callback, error, method, payload, paramMap, retry) { - var that = this; - var url = this.instanceUrl + '/services/apexrest' + path; + forcetk.Client.prototype.apexrest = function (path, callback, error, method, payload, paramMap, retry) { + 'use strict'; + var that = this, + url = this.instanceUrl + '/services/apexrest' + path; return $.ajax({ type: method || "GET", async: this.asyncAjax, - url: (this.proxyUrl !== null) ? this.proxyUrl: url, + url: (this.proxyUrl !== null) ? this.proxyUrl : url, contentType: 'application/json', cache: false, processData: false, data: payload, success: callback, - error: (!this.refreshToken || retry ) ? error : function(jqXHR, textStatus, errorThrown) { + error: (!this.refreshToken || retry) ? error : function (jqXHR, textStatus, errorThrown) { if (jqXHR.status === 401) { - that.refreshAccessToken(function(oauthResponse) { + that.refreshAccessToken(function (oauthResponse) { that.setSessionToken(oauthResponse.access_token, null, - oauthResponse.instance_url); + oauthResponse.instance_url); that.apexrest(path, callback, error, method, payload, paramMap, true); - }, - error); + }, error); } else { error(jqXHR, textStatus, errorThrown); } }, dataType: "json", - beforeSend: function(xhr) { + beforeSend: function (xhr) { + var paramName; if (that.proxyUrl !== null) { xhr.setRequestHeader('SalesforceProxy-Endpoint', url); } @@ -413,13 +419,15 @@ if (forcetk.Client === undefined) { paramMap = {}; } for (paramName in paramMap) { - xhr.setRequestHeader(paramName, paramMap[paramName]); + if (paramMap.hasOwnProperty(paramName)) { + xhr.setRequestHeader(paramName, paramMap[paramName]); + } } xhr.setRequestHeader(that.authzHeader, "Bearer " + that.sessionId); xhr.setRequestHeader('X-User-Agent', 'salesforce-toolkit-rest-javascript/' + that.apiVersion); } }); - } + }; /* * Lists summary information about each Salesforce.com version currently @@ -428,9 +436,10 @@ if (forcetk.Client === undefined) { * @param callback function to which response will be passed * @param [error=null] function to which jqXHR will be passed in case of error */ - forcetk.Client.prototype.versions = function(callback, error) { + forcetk.Client.prototype.versions = function (callback, error) { + 'use strict'; return this.ajax('/', callback, error); - } + }; /* * Lists available resources for the client's API version, including @@ -438,9 +447,10 @@ if (forcetk.Client === undefined) { * @param callback function to which response will be passed * @param [error=null] function to which jqXHR will be passed in case of error */ - forcetk.Client.prototype.resources = function(callback, error) { + forcetk.Client.prototype.resources = function (callback, error) { + 'use strict'; return this.ajax('/' + this.apiVersion + '/', callback, error); - } + }; /* * Lists the available objects and their metadata for your organization's @@ -448,9 +458,10 @@ if (forcetk.Client === undefined) { * @param callback function to which response will be passed * @param [error=null] function to which jqXHR will be passed in case of error */ - forcetk.Client.prototype.describeGlobal = function(callback, error) { + forcetk.Client.prototype.describeGlobal = function (callback, error) { + 'use strict'; return this.ajax('/' + this.apiVersion + '/sobjects/', callback, error); - } + }; /* * Describes the individual metadata for the specified object. @@ -458,10 +469,11 @@ if (forcetk.Client === undefined) { * @param callback function to which response will be passed * @param [error=null] function to which jqXHR will be passed in case of error */ - forcetk.Client.prototype.metadata = function(objtype, callback, error) { - return this.ajax('/' + this.apiVersion + '/sobjects/' + objtype + '/' - , callback, error); - } + forcetk.Client.prototype.metadata = function (objtype, callback, error) { + 'use strict'; + return this.ajax('/' + this.apiVersion + '/sobjects/' + objtype + '/', + callback, error); + }; /* * Completely describes the individual metadata at all levels for the @@ -470,10 +482,11 @@ if (forcetk.Client === undefined) { * @param callback function to which response will be passed * @param [error=null] function to which jqXHR will be passed in case of error */ - forcetk.Client.prototype.describe = function(objtype, callback, error) { + forcetk.Client.prototype.describe = function (objtype, callback, error) { + 'use strict'; return this.ajax('/' + this.apiVersion + '/sobjects/' + objtype - + '/describe/', callback, error); - } + + '/describe/', callback, error); + }; /* * Creates a new record of the given type. @@ -484,10 +497,11 @@ if (forcetk.Client === undefined) { * @param callback function to which response will be passed * @param [error=null] function to which jqXHR will be passed in case of error */ - forcetk.Client.prototype.create = function(objtype, fields, callback, error) { - return this.ajax('/' + this.apiVersion + '/sobjects/' + objtype + '/' - , callback, error, "POST", JSON.stringify(fields)); - } + forcetk.Client.prototype.create = function (objtype, fields, callback, error) { + 'use strict'; + return this.ajax('/' + this.apiVersion + '/sobjects/' + objtype + '/', + callback, error, "POST", JSON.stringify(fields)); + }; /* * Retrieves field values for a record of the given type. @@ -498,16 +512,17 @@ if (forcetk.Client === undefined) { * @param callback function to which response will be passed * @param [error=null] function to which jqXHR will be passed in case of error */ - forcetk.Client.prototype.retrieve = function(objtype, id, fieldlist, callback, error) { - if (arguments.length == 4) { + forcetk.Client.prototype.retrieve = function (objtype, id, fieldlist, callback, error) { + 'use strict'; + if (arguments.length === 4) { error = callback; callback = fieldlist; fieldlist = null; } var fields = fieldlist ? '?fields=' + fieldlist : ''; return this.ajax('/' + this.apiVersion + '/sobjects/' + objtype + '/' + id - + fields, callback, error); - } + + fields, callback, error); + }; /* * Upsert - creates or updates record of the given type, based on the @@ -521,10 +536,11 @@ if (forcetk.Client === undefined) { * @param callback function to which response will be passed * @param [error=null] function to which jqXHR will be passed in case of error */ - forcetk.Client.prototype.upsert = function(objtype, externalIdField, externalId, fields, callback, error) { - return this.ajax('/' + this.apiVersion + '/sobjects/' + objtype + '/' + externalIdField + '/' + externalId - + '?_HttpMethod=PATCH', callback, error, "POST", JSON.stringify(fields)); - } + forcetk.Client.prototype.upsert = function (objtype, externalIdField, externalId, fields, callback, error) { + 'use strict'; + return this.ajax('/' + this.apiVersion + '/sobjects/' + objtype + '/' + externalIdField + '/' + externalId + + '?_HttpMethod=PATCH', callback, error, "POST", JSON.stringify(fields)); + }; /* * Updates field values on a record of the given type. @@ -536,10 +552,11 @@ if (forcetk.Client === undefined) { * @param callback function to which response will be passed * @param [error=null] function to which jqXHR will be passed in case of error */ - forcetk.Client.prototype.update = function(objtype, id, fields, callback, error) { - return this.ajax('/' + this.apiVersion + '/sobjects/' + objtype + '/' + id - + '?_HttpMethod=PATCH', callback, error, "POST", JSON.stringify(fields)); - } + forcetk.Client.prototype.update = function (objtype, id, fields, callback, error) { + 'use strict'; + return this.ajax('/' + this.apiVersion + '/sobjects/' + objtype + '/' + id + + '?_HttpMethod=PATCH', callback, error, "POST", JSON.stringify(fields)); + }; /* * Deletes a record of the given type. Unfortunately, 'delete' is a @@ -549,10 +566,11 @@ if (forcetk.Client === undefined) { * @param callback function to which response will be passed * @param [error=null] function to which jqXHR will be passed in case of error */ - forcetk.Client.prototype.del = function(objtype, id, callback, error) { - return this.ajax('/' + this.apiVersion + '/sobjects/' + objtype + '/' + id - , callback, error, "DELETE"); - } + forcetk.Client.prototype.del = function (objtype, id, callback, error) { + 'use strict'; + return this.ajax('/' + this.apiVersion + '/sobjects/' + objtype + '/' + id, + callback, error, "DELETE"); + }; /* * Executes the specified SOQL query. @@ -561,11 +579,12 @@ if (forcetk.Client === undefined) { * @param callback function to which response will be passed * @param [error=null] function to which jqXHR will be passed in case of error */ - forcetk.Client.prototype.query = function(soql, callback, error) { - return this.ajax('/' + this.apiVersion + '/query?q=' + encodeURIComponent(soql) - , callback, error); - } - + forcetk.Client.prototype.query = function (soql, callback, error) { + 'use strict'; + return this.ajax('/' + this.apiVersion + '/query?q=' + encodeURIComponent(soql), + callback, error); + }; + /* * Queries the next set of records based on pagination. *

    This should be used if performing a query that retrieves more than can be returned @@ -576,19 +595,18 @@ if (forcetk.Client === undefined) { * @param callback function to which response will be passed * @param [error=null] function to which jqXHR will be passed in case of error */ - forcetk.Client.prototype.queryMore = function( url, callback, error ){ + forcetk.Client.prototype.queryMore = function (url, callback, error) { + 'use strict'; //-- ajax call adds on services/data to the url call, so only send the url after - var serviceData = "services/data"; - var index = url.indexOf( serviceData ); - - if( index > -1 ){ - url = url.substr( index + serviceData.length ); - } else { - //-- leave alone + var serviceData = "services/data", + index = url.indexOf(serviceData); + + if (index > -1) { + url = url.substr(index + serviceData.length); } - - return this.ajax( url, callback, error ); - } + + return this.ajax(url, callback, error); + }; /* * Executes the specified SOSL search. @@ -597,8 +615,9 @@ if (forcetk.Client === undefined) { * @param callback function to which response will be passed * @param [error=null] function to which jqXHR will be passed in case of error */ - forcetk.Client.prototype.search = function(sosl, callback, error) { - return this.ajax('/' + this.apiVersion + '/search?q=' + encodeURIComponent(sosl) - , callback, error); - } + forcetk.Client.prototype.search = function (sosl, callback, error) { + 'use strict'; + return this.ajax('/' + this.apiVersion + '/search?q=' + encodeURIComponent(sosl), + callback, error); + }; } From 0c736367d2c7569e421df306d7690249214bfdec Mon Sep 17 00:00:00 2001 From: Pat Patterson Date: Mon, 26 Oct 2015 15:29:41 -0700 Subject: [PATCH 57/60] Handle apexrest payloads correctly. Fixes #49 --- forcetk.js | 24 +++++++++++++++++++++--- 1 file changed, 21 insertions(+), 3 deletions(-) diff --git a/forcetk.js b/forcetk.js index 8964464..7fd2918 100644 --- a/forcetk.js +++ b/forcetk.js @@ -380,7 +380,7 @@ if (forcetk.Client === undefined) { * @param callback function to which response will be passed * @param [error=null] function to which jqXHR will be passed in case of error * @param [method="GET"] HTTP method for call - * @param [payload=null] payload for POST/PATCH etc + * @param [payload=null] string or object with payload for POST/PATCH etc or params for GET * @param [paramMap={}] parameters to send as header values for POST/PATCH etc * @param [retry] specifies whether to retry on error */ @@ -389,10 +389,28 @@ if (forcetk.Client === undefined) { var that = this, url = this.instanceUrl + '/services/apexrest' + path; + method = method || "GET"; + + if (method === "GET") { + // Handle proxied query params correctly + if (this.proxyUrl && payload) { + if (typeof payload !== 'string') { + payload = $.param(payload); + } + url += "?" + payload; + payload = null; + } + } else { + // Allow object payload for POST etc + if (payload && typeof payload !== 'string') { + payload = JSON.stringify(payload); + } + } + return $.ajax({ - type: method || "GET", + type: method, async: this.asyncAjax, - url: (this.proxyUrl !== null) ? this.proxyUrl : url, + url: this.proxyUrl || url, contentType: 'application/json', cache: false, processData: false, From cf2e4e4e33d50a295205d76112b9bbb61b255363 Mon Sep 17 00:00:00 2001 From: svc-scm <48930134+svc-scm@users.noreply.github.com> Date: Tue, 12 Oct 2021 04:05:28 -0700 Subject: [PATCH 58/60] Updated/Added CODEOWNERS with ECCN --- CODEOWNERS | 2 ++ 1 file changed, 2 insertions(+) create mode 100644 CODEOWNERS diff --git a/CODEOWNERS b/CODEOWNERS new file mode 100644 index 0000000..522fa4a --- /dev/null +++ b/CODEOWNERS @@ -0,0 +1,2 @@ +# Comment line immediately above ownership line is reserved for related gus information. Please be careful while editing. +#ECCN:Open Source From 52ab8a54c620a4f5b46257e6ce1a3f6cb6b93efa Mon Sep 17 00:00:00 2001 From: Peter Chittum Date: Fri, 14 Oct 2022 21:06:17 +0100 Subject: [PATCH 59/60] adding oss info files --- CODE_OF_CONDUCT.md | 105 +++++++++++++++++++++++++++++++++++++++++++++ LICENSE.txt | 14 ++++++ SECURITY.md | 7 +++ 3 files changed, 126 insertions(+) create mode 100644 CODE_OF_CONDUCT.md create mode 100644 LICENSE.txt create mode 100644 SECURITY.md diff --git a/CODE_OF_CONDUCT.md b/CODE_OF_CONDUCT.md new file mode 100644 index 0000000..b4612a7 --- /dev/null +++ b/CODE_OF_CONDUCT.md @@ -0,0 +1,105 @@ +# Salesforce Open Source Community Code of Conduct + +## About the Code of Conduct + +Equality is a core value at Salesforce. We believe a diverse and inclusive +community fosters innovation and creativity, and are committed to building a +culture where everyone feels included. + +Salesforce open-source projects are committed to providing a friendly, safe, and +welcoming environment for all, regardless of gender identity and expression, +sexual orientation, disability, physical appearance, body size, ethnicity, nationality, +race, age, religion, level of experience, education, socioeconomic status, or +other similar personal characteristics. + +The goal of this code of conduct is to specify a baseline standard of behavior so +that people with different social values and communication styles can work +together effectively, productively, and respectfully in our open source community. +It also establishes a mechanism for reporting issues and resolving conflicts. + +All questions and reports of abusive, harassing, or otherwise unacceptable behavior +in a Salesforce open-source project may be reported by contacting the Salesforce +Open Source Conduct Committee at ossconduct@salesforce.com. + +## Our Pledge + +In the interest of fostering an open and welcoming environment, we as +contributors and maintainers pledge to making participation in our project and +our community a harassment-free experience for everyone, regardless of gender +identity and expression, sexual orientation, disability, physical appearance, +body size, ethnicity, nationality, race, age, religion, level of experience, education, +socioeconomic status, or other similar personal characteristics. + +## Our Standards + +Examples of behavior that contributes to creating a positive environment +include: + +* Using welcoming and inclusive language +* Being respectful of differing viewpoints and experiences +* Gracefully accepting constructive criticism +* Focusing on what is best for the community +* Showing empathy toward other community members + +Examples of unacceptable behavior by participants include: + +* The use of sexualized language or imagery and unwelcome sexual attention or +advances +* Personal attacks, insulting/derogatory comments, or trolling +* Public or private harassment +* Publishing, or threatening to publish, others' private information—such as +a physical or electronic address—without explicit permission +* Other conduct which could reasonably be considered inappropriate in a +professional setting +* Advocating for or encouraging any of the above behaviors + +## Our Responsibilities + +Project maintainers are responsible for clarifying the standards of acceptable +behavior and are expected to take appropriate and fair corrective action in +response to any instances of unacceptable behavior. + +Project maintainers have the right and responsibility to remove, edit, or +reject comments, commits, code, wiki edits, issues, and other contributions +that are not aligned with this Code of Conduct, or to ban temporarily or +permanently any contributor for other behaviors that they deem inappropriate, +threatening, offensive, or harmful. + +## Scope + +This Code of Conduct applies both within project spaces and in public spaces +when an individual is representing the project or its community. Examples of +representing a project or community include using an official project email +address, posting via an official social media account, or acting as an appointed +representative at an online or offline event. Representation of a project may be +further defined and clarified by project maintainers. + +## Enforcement + +Instances of abusive, harassing, or otherwise unacceptable behavior may be +reported by contacting the Salesforce Open Source Conduct Committee +at ossconduct@salesforce.com. All complaints will be reviewed and investigated +and will result in a response that is deemed necessary and appropriate to the +circumstances. The committee is obligated to maintain confidentiality with +regard to the reporter of an incident. Further details of specific enforcement +policies may be posted separately. + +Project maintainers who do not follow or enforce the Code of Conduct in good +faith may face temporary or permanent repercussions as determined by other +members of the project's leadership and the Salesforce Open Source Conduct +Committee. + +## Attribution + +This Code of Conduct is adapted from the [Contributor Covenant][contributor-covenant-home], +version 1.4, available at https://www.contributor-covenant.org/version/1/4/code-of-conduct.html. +It includes adaptions and additions from [Go Community Code of Conduct][golang-coc], +[CNCF Code of Conduct][cncf-coc], and [Microsoft Open Source Code of Conduct][microsoft-coc]. + +This Code of Conduct is licensed under the [Creative Commons Attribution 3.0 License][cc-by-3-us]. + +[contributor-covenant-home]: https://www.contributor-covenant.org (https://www.contributor-covenant.org/) +[golang-coc]: https://golang.org/conduct +[cncf-coc]: https://github.com/cncf/foundation/blob/master/code-of-conduct.md +[microsoft-coc]: https://opensource.microsoft.com/codeofconduct/ +[cc-by-3-us]: https://creativecommons.org/licenses/by/3.0/us/ \ No newline at end of file diff --git a/LICENSE.txt b/LICENSE.txt new file mode 100644 index 0000000..9ba9791 --- /dev/null +++ b/LICENSE.txt @@ -0,0 +1,14 @@ +BSD 3-Clause License + +Copyright (c) 2022 Salesforce, Inc. +All rights reserved. + +Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + +1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. + +2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. + +3. Neither the name of Salesforce.com nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/SECURITY.md b/SECURITY.md new file mode 100644 index 0000000..e31774d --- /dev/null +++ b/SECURITY.md @@ -0,0 +1,7 @@ +## Security + +Please report any security issue to [security@salesforce.com](mailto:security@salesforce.com) +as soon as it is discovered. This library limits its runtime dependencies in +order to reduce the total cost of ownership as much as can be, but all consumers +should remain vigilant and have their security stakeholders review all third-party +products (3PP) like this one and their dependencies. \ No newline at end of file From 01974a1415e6546eb35a7aca9e157b0522d20724 Mon Sep 17 00:00:00 2001 From: Philippe Ozil Date: Wed, 10 Jan 2024 14:10:31 +0100 Subject: [PATCH 60/60] Update README.markdown --- README.markdown | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/README.markdown b/README.markdown index e3c0368..b72c733 100644 --- a/README.markdown +++ b/README.markdown @@ -1,3 +1,7 @@ +> [!WARNING] +> This project is deprecated, use [JSforce](https://jsforce.github.io/) instead. + + Force.com JavaScript REST Toolkit =================================