Version 23.

0: Winter '12

Force.com Streaming API Developer's Guide

Last updated: November 18, 2011
© Copyright 2000–2011 salesforce.com, inc. All rights reserved. Salesforce.com is a registered trademark of salesforce.com, inc., as are other

names and marks. Other marks appearing herein may be trademarks of their respective owners.

Table of Contents

Table of Contents
Getting Started with Force.com Streaming API.....................................................................................3 Chapter 1: Introducing the Force.com Streaming API..................................................................3
Concepts: Bayeux Protocol, CometD, and Long Polling..............................................................................................4 HTTPS Recommended................................................................................................................................................4 Supported Browsers.......................................................................................................................................................4 Debugging Streaming API Applications.......................................................................................................................5

Chapter 2: Quick Start Using Workbench....................................................................................6
Prerequisites..................................................................................................................................................................6 Step 1: Create an Object................................................................................................................................................7 Step 2: Create a PushTopic...........................................................................................................................................7 Step 3: Subscribe to the PushTopic Channel................................................................................................................8 Step 4: Test the PushTopic Channel.............................................................................................................................8

Chapter 3: Quick Start...............................................................................................................10
Prerequisites.................................................................................................................................................................10 Step One: Obtain a Developer Edition and Streaming API Access............................................................................11 Step Two: Set Up Authentication...............................................................................................................................11 Step Three: Create a Streaming API PushTopic........................................................................................................13 Step Four: Set Up a Bayeux Client..............................................................................................................................14 Step Five: Walk Through the Sample Code...............................................................................................................15

Using Streaming API..........................................................................................................................26 Chapter 4: Streaming API Features............................................................................................26
Clients and Timeouts..................................................................................................................................................27 Clients and Cookies for Streaming API......................................................................................................................27 Message Reliability......................................................................................................................................................28 Bulk Subscriptions.......................................................................................................................................................28 ID Fields in WHERE Clauses....................................................................................................................................29

Reference...........................................................................................................................................30 Chapter 5: PushTopic................................................................................................................30 Chapter 6: Streaming API Limits...............................................................................................35 Index.................................................................................................................................................36

i

Table of Contents ii .

after two minutes the client should reconnect immediately. in a secure and scalable way. This enables you to reduce the number of API calls and improve performance. The client must start over with a handshake and subscribe again. The Streaming API uses the HTTP/1. If the reconnection doesn't happen within 40 seconds. 3 .1 request-response model and the Bayeux protocol (CometD implementation). Connects using long polling. see Concepts: Bayeux Protocol. 2. it should reconnect immediately to receive the next set of events.com. Sends a handshake request. • • If no events are generated and the client is waiting and the server closes the connection. The client receives events while it maintains a long-lived connection. These events can be received by: • • • Pages in the Salesforce application. To enable the Streaming API for your organization. contact salesforce. Applications servers outside of Salesforce. 3.com Streaming API Use the Streaming API to receive events for changes to Salesforce data that match a SOQL query you define. and Long Polling on page 4. Clients outside the Salesforce application. the server expires the subscription and the connection closes. CometD. would benefit from the Streaming API which reduces the number of requests that return no data. Note: The Streaming API is part of a pilot program. consuming unnecessary API calls and processing time. Consider the following applications for the Streaming API: Applications with a high polling frequency Applications that have constant polling action against the Salesforce infrastructure. Sends a subscription request to a channel. General notification You can use the Streaming API for applications that require general notification of data changes in an organization. For details about these steps. A Bayeux client connects to the Streaming API in three stages: 1.GETTING STARTED WITH FORCE. If the client receives events.COM STREAMING API Chapter 1 Introducing the Force.

instead of sending an empty response if information isn't available.Introducing the Force. allows emulation of an information push from a server to a client. we recommend you use HTTPS. Bayeux. See Also: Introducing the Force. Long polling. or CometD. CometD. and Long Polling Concepts: Bayeux Protocol. the client requests a new connection and starts over. CometD is a scalable HTTP-based event routing bus that uses an Ajax Push technology pattern known as Comet. In the case of server timeouts. If you are not familiar with long polling.com Streaming API 4 . the client requests information from the server. primarily over HTTP. See Also: Introducing the Force.com Streaming API Supported Browsers The Streaming API has been tested with Internet Explorer 8 and Firefox 4. By default this is HTTPS. Other browsers are not supported. Similar to a normal poll. The server sends a complete response to the client. • • • Bayeux is a protocol for transporting asynchronous messages. we strongly recommend you review the following documents before trying the Quick Start sample: • • • CometD documentation: http://cometd. CometD. Thus the server almost always has an available waiting request to deliver data in response to an event.org/documentation Bayeux protocol documentation: http://cometd.org/documentation/bayeux/spec See Also: Introducing the Force. It implements Bayeux Protocol Specification 1. also called Comet programming.0. the server holds the request and waits until information is available.com Streaming API Concepts: Bayeux Protocol. and Long Polling The Bayeux protocol and CometD use long polling. To protect the security of your data. It's helpful to understand the basic concepts before using the Quick Start samples. The client then immediately re-requests information. However.0.org/documentation/bayeux Bayeux protocol specification: http://cometd.com Streaming API HTTPS Recommended The Streaming API follows the preference set by your administrator for your organization.

or Firebug. Use a tool that can report the contents of all requests and results.Introducing the Force. Because Streaming API applications are stateful. and results. See Also: Introducing the Force. body of the post.com Streaming API 5 . If you must contact us for help. The next step is to use your debug tool to help isolate the symptoms and cause of any problems. such as Burp Proxy. The first step for any debugging process is to follow the instructions in the Quick Start on page 10 and verify that you can implement the samples provided. Fiddler.com Streaming API Debugging Streaming API Applications Debugging Streaming API Applications You must be able to see all of the requests and responses in order to debug Streaming API applications. you need to use a proxy tool to debug your application. The most common errors include: • • • • • Browser and JavaScript issues Sending requests out of sequence Malformed requests that don't follow the Bayeux protocol Authorization issues Network or firewall issues with long-lived connections Using these tools. be sure to copy and save these elements to assist in troubleshooting. you can look at the requests. headers.

or delete data (as opposed to simply reading data). • • • • • Prerequisites Step 1: Create an Object Step 2: Create a PushTopic Step 3: Subscribe to the PushTopic Channel Step 4: Test the PushTopic Channel Prerequisites You need access and appropriate permissions to complete the quick start steps. This quick start takes you step-by-step through the process of using the Streaming API to receive notification when a record is updated. but may have been changed by an administrator. • Access to a Developer Edition organization. While the Streaming API is in pilot. staging.developerforce.com/join and follow the instructions for signing up for a Developer Edition organization. This permission is enabled by default. • • • The “API Enabled” permission enabled for your Developer Edition organization. update. 6 .force. go to http://developer. register at http://www.com/events/streaming_api_upgrade/registration. Your username must have “Read” permission on the PushTopic standard object so you can receive notifications. Note: To verify that the “API Enabled” and “Streaming API” permissions are enabled in your organization. use Developer Edition for developing. The “Streaming API” permission enabled. Even if you already have Enterprise Edition or Unlimited Edition. go to My Name > Setup > Customize > User Interface. For a new developer organization. you must register for access to it. and testing your solutions against sample data to protect your organization’s live data. • • Your username must have “Create” permission on the PushTopic standard object so you can create and manage PushTopic records. This is especially true for applications that insert.com developer community.php. If you are not already a member of the Force. Access to the Streaming API.Chapter 2 Quick Start Using Workbench This quick start shows you how to get started with the Streaming API by using Workbench.

In the Data Type field . f. In the Starting Number field. enter Description. Your InvoiceStatement object should now have two custom fields. You’ll create the object using Salesforce. Click New Custom Object and fill in the custom object definition. d. c. with each entry on its own line. For Data Type. Click Next. type INV-{0000}. type Status. Alternatively. 2. type Invoice Statements. In the Field Label field. 1. and click Next again. Type the following picklist values in the box provided. Select Starts with vowel sound. Events notifications are generated for updates that match the query. a. In the Display Format field. Click Save to go the detail page for the Invoice Statement object. Add a Status field.Quick Start Using Workbench Step 1: Create an Object Step 1: Create an Object The first step in the quick start using Workbench is to create an InvoiceStatement object. Select Your Name > System Log. Click Next. In the Field Label and Field Name fields. In the Plural Label field. g. type Invoice Number. In the Record Name field . select Read Only and then click Next. d. Click Your Name > Setup > Create > Objects. 7 . you’ll get notifications when an InvoiceStatement record is created or updated. After you create a PushTopic and subscribe to it. 3. accept the defaults. select Text Area and click Next. For field-level security. Click Save. In the Data Type field. a. type Invoice Statement. 5. • • • • • • • In the Label field . 4. Open Closed Negotiating Pending e. c. Scroll down to the Custom Fields & Relationships related list and click New. type 1. you can also use Workbench to create a PushTopic. 1. b. select Picklist and click Next. Now create an optional Description field. select Auto Number. b. Select the checkbox for Use first value as default value. Step 2: Create a PushTopic Use the System Log to create the PushTopic record that contains a SOQL query.

Once you successfully establish a connection to your database. you land on the Select page.google. For Environment select Production. In the Push Topic field. open an instance of Workbench and log in by following the steps in Step 3: Subscribe to the PushTopic Channel. Click data > Insert. On the Logs tab." Keep this browser window open and make sure the connection doesn’t time out. 7.com recommends that you do not use this hosted instance of Workbench to access data in a production database. Click queries > Streaming Push Topics. Accept the terms of service and click Login with Salesforce. 5. host. you can download. 1. Status__c FROM Invoice_Statement__c'. 2. If you want to use Workbench for your production database. PushTopic pushTopic = new PushTopic(). 1. Step 4: Test the PushTopic Channel Make sure the browser that you used in Step 3: Subscribe to the PushTopic Channel stays open and the connection doesn’t time out. The final step is to test the PushTopic channel by creating a new InvoiceStatement record in Workbench and viewing the event notification. 6. Step 3: Subscribe to the PushTopic Channel In this step.0.Name = 'InvoiceStatementUpdates'. insert pushTopic. pushTopic. open source. 4. navigate to http://workbench. pushtopic. Salesforce.com provides a hosted instance of Workbench for demonstration purposes only—salesforce. In your browser. 8 . Click Subscribe.Quick Start Using Workbench Step 3: Subscribe to the PushTopic Channel 2. click Execute. For Object Type. In a new browser window. 3.com/p/forceworkbench/downloads/list. You’ll be able to see the event notifications triggered by the InvoiceStatement record you create in the next step. 4. and click Execute. Important: Workbench is a free. paste in the following Apex code. 3. Type in a value for the Description__c field. Ensure that the Single Record field is selected. you’ll subscribe to the channel you created with the PushTopic record in the previous step.com. community-supported tool (see the Help page in Workbench). Click Confirm Insert. 2. In the Enter Apex Code window. select Invoice_Statement__c. You’ll view event notifications in this browser.Query = 'SELECT Id. 3. You can download Workbench from http://code. 5.developerforce. and configure it using your own resources. You’ll see the connection and response information and a response like "Subscribed to /topic/InvoiceStatementUpdates. select InvoiceStatementUpdates. pushTopic.ApiVersion = 23. and click Next.

Switch over to your Streaming Push Topics browser window. "createdDate": "2011-10-04T19:16:31.Quick Start Using Workbench Step 4: Test the PushTopic Channel 6.000+0000" }. The message looks something like this: { "channel": "/topic/InvoiceStatementUpdates". "sobject": { "Id": "a05D0000002jKF1IAM". "Status__c": "Open" } } } 9 . The notification returns the Id and Status__c fields that you defined in the SELECT statement of your PushTopic query. You’ll see a notification that the invoice statement was created. "data": { "event": { "type": "created".

try to access the PushTopic object via Apex or an API call. ◊ OAuth 2.Chapter 3 Quick Start Create a sample streaming application in your development environment to see the power and flexibility of the Streaming API. verify that you have the “API Enabled” permission. This permission is enabled by default. which requires some setup. For more information. verify whether you already have access. • • For a new developer organization. We provide the steps. select My Name > Setup > Customize > User Interface.developerforce. PushTopic is not available and your organization does not yet have Streaming API enabled.com/events/streaming_api_upgrade/registration. you are ready to start working with the Streaming API. If the call fails. register at http://www. If it succeeds. your organization does not have access. but may have been changed by an administrator. • Become familiar with: ◊ The Bayeux protocol in order to build a client to receive messages on a streaming channel.php. If you don't see the checkbox. If you see the Enable Streaming API checkbox. • Need: ◊ “Create” permission on the PushTopic standard object to create and administer PushTopic records ◊ “Read” permission on the PushTopic standard object to receive notifications If you already have a Developer Edition organization.0. You must also enable the Streaming API. make sure it is enabled. • • • • • • Prerequisites Step One: Obtain a Developer Edition and Streaming API Access Step Two: Set Up Authentication Step Three: Create a Streaming API PushTopic Step Four: Set Up a Bayeux Client Step Five: Walk Through the Sample Code Prerequisites Completing the prerequisites makes it easier to build and use the Quick Start sample. To verify. but it will help if you are familiar with the basic concepts and workflow. Tip: If you already have a client application set up. see the help in the Salesforce user interface. 10 . For an existing organization.

11 .com/join and follow the instructions for signing up for a Developer Edition organization.0. and testing your solutions against sample data to protect your organization’s live data. It must be secure: http:// does not work. Setting Up Authorization with OAuth 2.com developer community. plus any additional cookies set by the Salesforce server. Even if you already have Enterprise Edition or Unlimited Edition. and click New to create a new remote access application if you have not already done so. and a Consumer Secret is created (click the link to reveal it). only https://. navigate to My Name > Setup > Develop > Remote Access.0 documentation. the callback URL is similar to https://my-website/_callback. This is especially true for applications that insert.0 specification uses “client” instead of “consumer.Quick Start Step One: Obtain a Developer Edition and Streaming API Access Step One: Obtain a Developer Edition and Streaming API Access If you are not already a member of the Force. When you click Save. 1. For more details. Note: The OAuth 2. update. Step Two: Set Up Authentication You can set up a simple authentication scheme for developer testing. use Developer Edition for developing.0. the Consumer Key is created and displayed. or delete data (as opposed to simply reading data). see the Streaming Client Sample in Java on page 16. staging.force. The values here correspond to the following values in the sample code in the rest of this procedure: • • • client_id is the Consumer Key client_secret is the Consumer Secret redirect_uri is the Callback URL. For development environments.” Salesforce supports OAuth 2. For production systems.0 Setting up OAuth 2. Set up the HTTP authorization header using this session ID: Authorization: OAuth sessionId The CometD endpoint requires a session ID on all requests.apache. go to http://developer. The sample Java code in this chapter uses the Apache HttpClient library which may be downloaded from http://hc. Usually it is a servlet if you work with Java.x/. The Callback URL you supply here is the same as your Web application's callback URL. Setting Up Authentication for Developer Testing To set up authorization for developer testing: 1. If any of the steps are unfamiliar. 2. use robust authorization. In Salesforce.0 requires that you take some steps within the Salesforce application and in other locations. you can consult the Salesforce online help or OAuth 2.org/httpclient-3. such as OAuth 2. Log in using the Web service SOAP API login() and get the session ID.

"auser@example. post. the value is authorization_code as shown in the sample. "password"). secret).addParameter("client_secret".getParams(). parametersBody[1] = new NameValuePair("username".setConnectionTimeout(30000).out. This sample gets both the session ID and then follows a discovery resource link.addParameter("password". oauthPost.com/id/00Dxxxxxxxxxxxx/005xxxxxxxxxxxx) contained in the first response to get more information about the user.salesforce. String clientId. and password .getParams().out. If the value of client_id (or consumer key) and client_secret (or consumer secret) are valid. Salesforce sends a callback to the URI specified in redirect_uri that contains a value for access_token.println("Logging in as " + username + " in environment " + loginHost).addParameter("client_id". client.println("POST " + baseUrl). clientSecret). This completes the authentication. parametersBody[2] = new NameValuePair("password".getHttpConnectionManager(). String secret) throws HttpException. String baseUrl = "https://" + loginHost + "/services/oauth2/token". String password. clientId). You can pass the access token rather than the session ID to authenticate on calls to the Streaming API. make a request to the authentication URL that passes in grant_type.setCookiePolicy(CookiePolicy. PostMethod post = new PostMethod(environment).getResponseBodyAsString(). client_id. username.out.Quick Start Step Two: Set Up Authentication There is one additional value you must specify: the grant_type. post. 3. parametersBody[0] = new NameValuePair("grant_type". username).com").executeMethod(oauthPost). } 12 . int code = client. Important: This method of authentication should only be used in development environments and not for production code.RFC_2109). From your Java or other client application.0 callbacks. For OAuth 2.valueOf(code) + ": " + jsonResponse).setRequestBody(parametersBody). post. IOException { // set up an http client that will make a connection to the REST API HttpClient client = new HttpClient(). 2. https://instance_name. String jsonResponse = oauthPost. client_secret. String username. post. clientId). parametersBody[3] = new NameValuePair("client_id". parametersBody[4] = new NameValuePair("client_secret". public static void oAuthSessionProvider(String loginHost.println("HTTP " + String. // execute the request System. // we're going to send a post request to the OAuth URL PostMethod oauthPost = new PostMethod(baseUrl). For example: HttpClient httpclient = new HttpClient(). // set the SID System. client. "swordfish"). password).addParameter("username". System. post. "password").addParameter("grant_type". // the request body must contain these 5 values NameValuePair[] parametersBody = new NameValuePair[5].

the opportunity ID. Amount FROM Opportunity WHERE Amount > 1000 A notification sent as a result of record creation where the record meets the query criteria: { "channel": "/topic/BigOpportunities". Sample queries and results: • Whenever an opportunity is above $1000 on a new or updated record. To create a PushTopic record. for example. name.000+0000" }. SELECT Id. As soon as a PushTopic record is created. A Bayeux client can receive streamed events on this channel. a subscription is created.Quick Start Step Three: Create a Streaming API PushTopic Step Three: Create a Streaming API PushTopic Before a stream of data can flow. There are limits on subscriptions for each organization. Valid values are 20.0 or later. Execute an anonymous Apex call. the system starts evaluating records. Name. "data": { "event": { "type": "created". These fields are required in a PushTopic record: • • • ApiVersion: version of the API your client uses to connect. Each PushTopic record that you create corresponds to a channel in cometD. Query: the SOQL query that filters the data to be returned. The channel name is the name of the PushTopic prefixed with “/topic/”. "createdDate": "2011-09-12T17:35:33. you must create a PushTopic in the organization where your Salesforce data resides. "Amount": 20000. When a client registers with a channel. Note that no record is reported unless the Amount value changes (create or update). use any of the following techniques: • • • Use the create() call from a SOAP API client. "Id": "006D000000CrUkDIAV" } } } 13 . /topic/MyPushTopic. Tip: Field names should be unique and descriptive. "sobject": { "Name": "GenePoint". and amount are pushed to the stream. Each PushTopic record contains a SOQL query that specifies the type of records to be pushed when created or updated. Execute an HTTP POST method from a REST API client. Name: a descriptive name for the data to be delivered in the stream.

"Id": "006x0000002JSofAAG" } } } • If you need to report on a particular record. 14 . or Python. For a sample Java client. "Id": "001x0000002JSofAAG" } } } Step Four: Set Up a Bayeux Client Download a Bayeux client with a binding for your desired programming language. No record is reported unless either the Amount or FiscalQuarter values change (create or update). Name. "Amount": 2000. and the fiscal quarter is three or changes to three. put the ID field in the WHERE clause. see the next step. JavaScript. "sobject": { "Name": "Grand Hotels & Resorts Ltd. See ID Fields in WHERE Clauses. "createdDate": "2011-04-12T17:35:33. "data": { "event": { "type": "updated".000 in the third fiscal quarter: { "channel": "/topic/Q3BigOpportunities". SELECT Id. for example Java.000+0000" }. Amount FROM Opportunity WHERE Amount > 1000 AND FiscalQuarter = "3" Sample notification when a record is updated with a value of more than $1. Name FROM Account WHERE Id="001x0000002JSofAAG" AND NumberOfEmployees > 10 Sample notification when the record is updated to have more than 10 employees: { "channel": "/topic/ExpressLogisticsNumEmployees". "sobject": { "Name": "Express Logistics and Transport".000+0000" }.Quick Start Step Four: Set Up a Bayeux Client • By adding an AND clause. SELECT Id. "data": { "event": { "type": "updated". "createdDate": "2011-09-12T17:35:33. the same values are pushed to the stream if the amount changes and is above $1000. to push a particular account's information to the stream whenever a field changes.". For example.

0. Download the compressed archive file from the CometD website: http://download.com/p/cookies/downloads/detail?name=jquery.0.zip 5.ApiVersion = 23. use the Streaming Client Sample in Java.0/cometd-javascript/common/src/main/webapp/org/cometd.0/cometd-javascript/jquery/src/main/webapp/jquery/jquery-cometd.tgz 3. Extract the file jquery.2. Create a page named StreamingPage from Your Name > Setup > Develop > Pages. Create a Visualforce page in your organization: a. For a desktop client that works with Salesforce data.0.2.0.js from jquery. Visualforce Sample Use this sample to receive notifications of updates to all accounts in an organization. Create a PushTopic that sends the ID and name for any account that is created or updated.js 4.org/cometd-1.0. Name FROM Account'.tgz: • • cometd-1. 8. use the Visualforce sample to a page in your Salesforce organization.tgz 2. pushtopic.cookies. Extract the following JavaScript files from cometd-1. Download the compressed archive file from the following URL: http://code.cookies. 6.zip.2.0.Name = 'AccountTopic'.js. b. pushTopic.2. The updates are continuously streamed to a page in your organization.js: cookies_js jquery-cometd.cookies. For example.0.js.cometd.js: cometd_js jquery.cookies.Query = 'SELECT Id. 1. select Your Name > System Log and execute the following Apex code: PushTopic pushTopic = new PushTopic().0. insert pushTopic. Replace the code in the page with the following code: <apex:page > <head> <apex:includeScript 15 .2. Select Your Name > Setup > Develop > Static Resources to add the extracted files with the following names: • • • cometd.0.js cometd-1. Download the compressed archive file from the following URL: http://download.0.2.org/cometd-1. pushTopic.cometd.google.Quick Start Step Five: Walk Through the Sample Code Step Five: Walk Through the Sample Code Streaming API samples: • • For a Web page.0. and you'll see dynamic updates as records are created or updated.js: jquery_cometd 7.0.2.2.0.

com/ajax/libs/jquery/1.jquery_cometd}"/> <script type="text/javascript"> $ = jQuery. Create or modify an Account in a different browser.4.java contains the sample client logic. subscribes to the sample topic and handles the stream of data.cometd. var auth = 'OAuth {!$Api.Quick Start Step Five: Walk Through the Sample Code value="http://ajax.cometd_js}"/> <apex:includeScript value="{!$Resource.ready(function() { var cometdUrl = 'https://' + window.subscribe('/topic/AccountTopic'.event.event.jar jetty-client-7.stringify(message.1. }).init({ url: cometdUrl.stringify(message.data.jar cometd-java-common-2.3. To simulate a real-world situation.salesforce.5/jquery.4.cometd.createdDate)). }). </script> </head> <body> <div id="content"> <p>Notifications should appear here.hostname + '/cometd/23.channel) + '\n' + 'Account name: ' + JSON.sobject.4.stringify(message.4.</p> </div> </body> </apex:page> 9.data.stringify(message. function(message) { alert('Notification from the channel/topic you subscribed to!').jar jetty-io-7.jar jetty-util-7.sobject.v20110707.cookies_js}"/> <apex:includeScript value="{!$Resource.js"/> <apex:includeScript value="{!$Resource.stringify(message.1.jar jetty-http-7.Session_ID}'. alert('Name of the channel: ' + JSON.com/apex/StreamingPage 10.jar The following Java classes: ◊ StreamingClientExample. $(document).min.googleapis. requestHeaders: { Authorization: auth} }).4.3..Name) + '\n' + 'Account ID: ' + JSON. log in as a different user.4.4.1.location.Id) + '\n' + 'Event type: ' + JSON.v20110707.v20110707.4.v20110707. $.data.data. Load the Visualforce page in a Web browser by using the following URL: https://my_instance. $.jar cometd-java-client-2.noConflict(). 16 .3..0/'. Streaming Client Sample in Java The Java sample client contains: • JAR files needed for the client to work: ◊ ◊ ◊ ◊ ◊ ◊ ◊ • bayeux-api-2.type) + '\n' + 'Event date: ' + JSON.

4.java gets a session ID using SOAP.1. Every client must retrieve a session ID and pass it in the HTTP request header: 1.4.1. Edit StreamingClientExample.tar.cometd.3. Download the compressed archive file from the following URL: http://download.3.java 7. Compile the source files and ensure that the JAR files mentioned above are in your build path. Name FROM Account'.3.jar 3.3.tar.ApiVersion= 23. Log in using the Web service SOAP API login() and get the session ID.jar jetty-hightide-7.4.codehaus.4. pushtopic. 8.4.4.4.jar jetty-hightide-7.v20110707.java SoapLoginUtil.jar 5.jar cometd-2.v20110707. Copy the following classes into a text editor and save them to their respective Java source files: • • StreamingClientExample.v20110707/lib/jetty-util-7.Name = 'AllAccounts'.v20110707. insert pushTopic.4.4.4.4.gz 2.1-distribution.tar.v20110707/lib/jetty-client-7. Create a new PushTopic with the name AllAccounts. pushTopic.tar. by selecting Your Name > System Log and by executing the following Apex code: PushTopic pushTopic = new PushTopic().4.v20110707/lib/jetty-io-7. Set up the HTTP authorization header using this session ID: Authorization: OAuth sessionId To use this sample: 1.org/jetty/jetty-hightide-7.4.4.3.Query = 'SELECT Id.4. For more information. Extract the following JAR files from jetty-hightide-7.3.v20110707.0-distribution.v20110707/lib/jetty-http-7.4. 2.v20110707. 6.3.1/cometd-java/cometd-java-common/target/cometd-java-common-2.4. Download the following file from: http://dist.4. Extract the following JAR files from cometd-2.0.gz Jetty Hightide is a distribution of the Jetty open source web container.1.1/cometd-java/cometd-java-client/target/cometd-java-client-2.gz: • • • cometd-2.jar jetty-hightide-7.0.jar cometd-2.4.v20110707.gz: • • • • jetty-hightide-7. see Jetty Hightide documentation 4.4.4/jetty-hightide-7.java and modify these values: USER_NAME Salesforce username 17 . pushTopic.Quick Start Step Five: Walk Through the Sample Code ◊ SoapLoginUtil.1/cometd-java/bayeux-api/target/bayeux-api-2.org/cometd-2.4.

"successful":true. "version":"1.com (Only if you are using a sandbox.. "successful":true.. "supportedConnectionTypes":["long-polling"]. StreamingClientExample. [CHANNEL:META_SUBSCRIBE]: { "id":"4"..0" } [CHANNEL:META_CONNECT]: { "id":"2". 9."timeout":110000}.salesforce.. Waiting for handshake [CHANNEL:META_HANDSHAKE]: { "id":"1". "channel":"/meta/subscribe"} [CHANNEL:META_CONNECT]: {"id":"3"."successful":true.) Danger: To protect your information.Quick Start Step Five: Walk Through the Sample Code PASSWORD Password for the specified Salesforce username CHANNEL /topic/AllAccounts LOGIN_ENDPOINT https://test.java subscribes to a PushTopic and handles the streaming information."channel":"/meta/connect"} 10. never include passwords in your code in a production environment. "successful":true. "clientId":"21rynpzn2am2v01uxo4va4eiu7x". "subscription":"/topic/AllAccounts". "minimumVersion":"1. "channel":"/meta/connect"} Subscribing for channel: /topic/AllAccounts Waiting for streamed data from your organization .StreamingClientExample. You should see output similar to the following: Running streaming client example.salesforce.p5fXbjYlqCgx7They_zFjmP5n9HxvfUA6xGSGtC1Nb6P4S. If you are in a production organization. "advice":{"interval":0. To simulate a real-world situation. log in as a different user. Run java demo."reconnect":"retry".com Sessionid=00DD0000000FSp9!AQIAQIVjGYijFhiAROTc455T6kEVeJ GXuW5VCnpLANCMawS7. Login successful! Endpoint: https://www. 18 . "channel":"/meta/handshake". no change is required for LOGIN_ENDPOINT. Create or modify an Account in a different browser..0".

final boolean VERSION_22 = false.Message.eclipse. delegate the login to OAuth. org.println("Running streaming client example.eclipse.bayeux.salesforce. org.addListener (new ClientSessionChannel.net. java. java. // milliseconds private static final int READ_TIMEOUT = 120 * 1000. // The long poll duration. client.Map.cometd. // Be sure to create this topic before running this sample.client. private static final int CONNECTION_TIMEOUT = 20 * 1000. import import import import java. private static final String STREAMING_ENDPOINT_URI = VERSION_22 ? "/cometd" : "/cometd/23.out.URL. Same as the name of the PushTopic.client.MessageListener.ClientTransport. import org.bayeux. org. // The channel to subscribe to..0".").Quick Start Step Five: Walk Through the Sample Code Important: Never handle the usernames and passwords of others.cometd.MessageListener() { public void onMessage(ClientSessionChannel channel.cometd. final boolean USE_COOKIES = VERSION_22.cometd. static final String LOGIN_ENDPOINT = "https://login. // milliseconds public static void main(String[] args) throws Exception { System.bayeux.com".transport.net.ContentExchange.client. /** * This example demonstrates how a streaming client works * against the Salesforce Streaming API.ClientSessionChannel. Message message) { 19 . private static final String USER_NAME = "change_this_to_your_testuser@yourcompany. Before using in a production environment.util. org. // NOTE: Putting passwords in code is not a good practice and not recommended. package demo.client.client. final BayeuxClient client = makeClient().META_HANDSHAKE).HttpClient.ClientSessionChannel.cometd.Channel. org.getChannel(Channel.cometd.. // Set this to // against the private static private static true only when using this client Summer'11 release (API version=22.com".. private static final String PASSWORD = "change_this_to_your_testpassword".transport. import import import import import import import org.MalformedURLException.LongPollingTransport.cometd.BayeuxClient. The serverUrl points to the endpoint where your organization is hosted. java.0). **/ public class StreamingClientExample { // // // // This URL is used only for logging in.bayeux.util. import org.jetty. private static final String CHANNEL = VERSION_22 ? "/AllAccounts" : "/topic/AllAccounts". org.jetty.client. The LoginResult returns a serverUrl which is then used for constructing the streaming URL.HashMap.client.

getChannel(Channel. System.isSuccessful().println("[CHANNEL:META_CONNECT]: " + message). client.println("[CHANNEL:META_HANDSHAKE]: " + message).isSuccessful(). boolean success = message. if (!success) { String error = (String) message. System.println("Waiting for handshake")."). System.println("Exiting.Quick Start Step Five: Walk Through the Sample Code System. System.handshake(). Message message) { System..get("error"). client.addListener( new ClientSessionChannel. if (!success) { String error = (String) message.addListener( new ClientSessionChannel.out.out. if (error != null) { System. System.out. } } } })..println("Exiting.println("Exiting. client.out. System.exit(1).MessageListener() { public void onMessage(ClientSessionChannel channel. System.println("Exception during HANDSHAKE: ").out.printStackTrace().. } } } }).println("Error during CONNECT: " + error).println("Exiting.exit(1). if (exception != null) { System.out. } Exception exception = (Exception) message."). System.getChannel(Channel.exit(1).get("error"). } } } }).META_CONNECT). System. if (!success) { String error = (String) message.")..out.exit(1). Message message) { System. exception.out.get("error").META_SUBSCRIBE).println("[CHANNEL:META_SUBSCRIBE]: " + message).").out..get("exception"). if (error != null) { System. 20 ..out.MessageListener() { public void onMessage(ClientSessionChannel channel..println("Error during HANDSHAKE: " + error).isSuccessful(). if (error != null) { System.out.out.. boolean success = message.println("Error during SUBSCRIBE: " + error). boolean success = message.

httpClient. String endpoint = pair[1].login(httpClient. httpClient) { @Override protected void customize(ContentExchange exchange) { super. sessionid).println("Waiting for streamed data from your organization . } assert pair. } System. if (pair == null) { System.exit(1). httpClient.State.out.println("Failed to handshake: " + client). System. // to receive streamed events on the // specified topic from your organization.println("Subscribing for channel: " + CHANNEL).println("Login successful!\nEndpoint: " + endpoint + "\nSessionid=" + sessionid).Quick Start Step Five: Walk Through the Sample Code boolean handshaken = client. client. } }). if (!handshaken) { System.println("Received Message: " + message). httpClient. final String sessionid = pair[0]. Map<String. String[] pair = SoapLoginUtil. } 21 . BayeuxClient client = new BayeuxClient(salesforceStreamingEndpoint( endpoint).out. LongPollingTransport transport = new LongPollingTransport( options.subscribe(new MessageListener() { @Override public void onMessage(ClientSessionChannel channel. Object> options = new HashMap<String.put(ClientTransport.addRequestHeader("Authorization".out. if (USE_COOKIES) establishCookies(client. USER_NAME... "OAuth " + sessionid).out.exit(1). options. } }.").toExternalForm(). READ_TIMEOUT). exchange. BayeuxClient.customize(exchange). Object>().out.CONNECTED). Message message) { System. transport).setTimeout(READ_TIMEOUT).length == 2.waitFor(10 * 1000.TIMEOUT_OPTION.getChannel(CHANNEL). PASSWORD). USER_NAME. System. System. return client. } } private static BayeuxClient makeClient() throws Exception { HttpClient httpClient = new HttpClient(). } private static String salesforceStreamingEndpoint(String endpoint) throws MalformedURLException { return new URL(endpoint + STREAMING_ENDPOINT_URI).start().setConnectTimeout(CONNECTION_TIMEOUT). while (true) { // This infinite loop is for demo only.

"us". 24 * 60 * 60 * 1000). client. "channel":"/meta/connect"} Subscribing for channel: /topic/AllAccounts Waiting for streamed data from your organization .. "subscription":"/topic/AllAccounts". "channel":"/meta/handshake".Quick Start Step Five: Walk Through the Sample Code private static void establishCookies(BayeuxClient client.. String user. "supportedConnectionTypes":["long-polling"]. "en_US". Login successful! Endpoint: https://www. "successful":true. 24 * 60 * 60 * 1000).setCookie("language". "Id":"001D000000J3fTHIAZ"}. "channel":"/meta/subscribe" } [CHANNEL:META_CONNECT]: { "id":"3". "advice":{"interval":0..setCookie("login". Waiting for handshake [CHANNEL:META_HANDSHAKE]: { "id":"1". 24 * 60 * 60 * 1000). "successful":true. [CHANNEL:META_SUBSCRIBE]: { "id":"4".setCookie("sid".setCookie("com. "createdDate":"2011-09-06T18:51:08.LocaleInfo". 24 * 60 * 60 * 1000). "successful":true. "event":{"type":"updated".salesforce. "channel":"/meta/connect" } Received Message: { "data": { "sobject": { "Name":"Wingo Ducks".000+0000" 22 . sid."reconnect":"retry". user..p5fXbjYlqCgx7They_zFjmP5n9HxvfUA6xGSGtC1Nb6P4S.0"..0" } [CHANNEL:META_CONNECT]: { "id":"2". String sid) { client. client.salesforce."timeout":110000}. client. "version":"1.com Sessionid=00DD0000000FSp9!AQIAQIVjGYijFhiAROTc455T6kEVeJGXuW5VCnp LANCMawS7. "clientId":"31t0cjzfbgnfqn1rggumba0k98u". } } After you change data that corresponds to the query in your push topic. the output from running StreamingClientExample will look something like this: Running streaming client example. "minimumVersion":"1. "successful":true.

import javax. java.SAXException.UnsupportedEncodingException.xml.getBytes("UTF-8").xml. InterruptedException.sax.xml. private static final String ENV_START = "<soapenv:Envelope xmlns:soapenv='http://schemas.xmlsoap.xml. org.sax. String password) throws UnsupportedEncodingException { return (ENV_START + " <urn:login>" + " <urn:username>" + username + "</urn:username>" + " <urn:password>" + password + "</urn:password>" + " </urn:login>" + ENV_END). "successful":true.ContentExchange. public final class SoapLoginUtil { // The enterprise SOAP API endpoint used for the login call in this example. java.io.parsers. "channel":"/topic/AllAccounts" } [CHANNEL:META_CONNECT]: { "id":"5".net. Important: Never handle the usernames and passwords of others.sax.sforce.soap. org.xml. import javax.setURL(getSoapURL()). Before using in a production environment.io. String username.client.Attributes. import import import import import import import import import import java.eclipse. org.net. String password) throws IOException.MalformedURLException.java sends a username and password to the server and receives the session ID. private static final String ENV_END = "</soapenv:Body></soapenv:Envelope>".org/soap/envelope/' " + "xmlns:xsi='http://www.w3. exchange. exchange. private static final String SERVICES_SOAP_PARTNER_ENDPOINT = "/services/Soap/u/22. delegate the login to OAuth. java.DefaultHandler.Quick Start Step Five: Walk Through the Sample Code } }. java.ByteArrayInputStream.parsers. ParserConfigurationException { ContentExchange exchange = new ContentExchange().ParserConfigurationException.jetty.SAXParserFactory.parsers.jetty.helpers.org/2001/XMLSchema-instance' " + "xmlns:urn='urn:partner. org. private static byte[] soapXmlForLogin(String username.setMethod("POST"). "channel":"/meta/connect" } SoapLoginUtil.URL.xml.client.eclipse.HttpClient. 23 . package demo.io. SAXException. import javax.IOException.0/".com'><soapenv:Body>".SAXParser. } public static String[] login(HttpClient client. org.

saxParser.setRequestHeader("SOAPAction". return new String[] {parser.setRequestHeader("Content-Type". private String sessionId. } private static class LoginResponseParser extends DefaultHandler { private boolean inSessionId.setNamespaceAware(true).serverUrl == null) { System.LOGIN_ENDPOINT + getSoapUri()).waitForDone(). SAXParser saxParser = spf. String localName. } @Override public void endElement(String uri.getResponseContent().append(":") .toString()}. length). client.serverUrl). password))). "text/xml").Quick Start Step Five: Walk Through the Sample Code exchange. exchange.append(soapEndpoint. if (parser. } if (localName. String qName) { if (localName != null) { if (localName. @Override public void characters(char[] ch.newSAXParser(). return null. "''"). int length) { if (inSessionId) sessionId = new String(ch. start.out.getProtocol()) . length). private boolean inServerUrl.getPort() > 0) endpoint. start. } private static String getSoapURL() throws MalformedURLException { return new URL(StreamingClientExample.send(exchange).setRequestHeader("PrettyPrint". if (soapEndpoint.getBytes("UTF-8")).println("Login Failed!\n" + response). "Yes"). SAXParserFactory spf = SAXParserFactory. int start. } 24 .equals("serverUrl")) { inServerUrl = false. LoginResponseParser parser = new LoginResponseParser().toExternalForm(). if (inServerUrl) serverUrl = new String(ch.equals("sessionId")) { inSessionId = false.sessionId == null || parser. String response = exchange.getHost()). spf. } URL soapEndpoint = new URL(parser. private String serverUrl.parse(new ByteArrayInputStream( response.setRequestContentSource(new ByteArrayInputStream(soapXmlForLogin( username. exchange.getPort()). parser). exchange. endpoint.append("://") .append(soapEndpoint. } private static String getSoapUri() { return SERVICES_SOAP_PARTNER_ENDPOINT.sessionId. exchange. StringBuilder endpoint = new StringBuilder() .newInstance().append(soapEndpoint.

equals("sessionId")) { inSessionId = true.x/cometd-java/client http://cometd.Quick Start Step Five: Walk Through the Sample Code } } @Override public void startElement(String uri. Attributes attributes) { if (localName != null) { if (localName. String localName.org/documentation/2.x/cometd-java/concepts 25 . String qName.org/documentation/2.equals("serverUrl")) { inServerUrl = true. } if (localName.org/documentation/2. } } } } } CometD Java support documentation: • • • http://cometd.x/cometd-java http://cometd.

. 26 . • • • • • Clients and Timeouts Clients and Cookies for Streaming API Message Reliability Bulk Subscriptions ID Fields in WHERE Clauses Streaming API helps you create near real-time update notifications of your Salesforce data. In this chapter you will learn the API features that your client can take advantage of..USING STREAMING API Chapter 4 Streaming API Features In this chapter .

then the organization timeout goes into effect and closes the session. therefore the client must handshake. Streaming API requirements on clients: • • • • The "Content-Type: application/json" header is required on all calls to the cometd servlet if the content of the post is JSON. See Also: Streaming API Features Clients and Cookies for Streaming API The client you create to work with the Streaming API must obey the standard cookie protocol with the server. for example https://instance_name. the session timeout is restarted. irrespective of activity on the connection. a client needs to reconnect to receive the next set of events. Authorization: OAuth sessionId. Clients must obey the standard cookie protocol with the server. A header containing the Salesforce session ID or OAuth token is required. Each Streaming API client logs into an instance and maintains a session. connects. For example. 27 . the client must start again and handshake. If the reconnection doesn't happen within 40 seconds.Streaming API Features Clients and Timeouts Clients and Timeouts The Streaming API imposes three timeouts. the connection times out after two minutes and the server closes the connection. and connect before the session is timed out on the server side. subscribe. the server expires the subscription and the connection is closed. maximum CometD session: 3600 seconds A client subscription is valid for a maximum of 3600 seconds. If this happens. Clients should reconnect before two minutes to avoid the connection timeout. The client must accept and send back all appropriate cookies for the domain and URI path. ◊ EventType contains either created or updated. Reconnect timeout: 40 seconds After receiving the events.com/cometd. subscribe. and connect. If there's no activity on that session. Socket timeout: 110 seconds A client receives events (JSON-formatted HTTP responses) while it waits on a connection. as supported in the Bayeux protocol. A new subscription creates a new server session: the server timeout clock restarts again. The client must accept and send the appropriate cookies for the domain and URI path. If no events are generated and the client is still waiting. When the client handshakes. The subscribe response and other responses might contain the following fields. or subscribes.salesforce. These fields aren't contained in the CometD specification.

If a client disconnects and starts a new handshake. it doesn't get messages that were processed while it was not subscribed to the channel. it may be working with a different application server.Streaming API Features Message Reliability ◊ CreatedDate contains the event's creation date. See Also: Streaming API Features Message Reliability This streaming system doesn't guarantee durability and reliable delivery of notifications. "subscription": "/topic/foo" }. For example this code subscribes to three topics: [ { "channel": "/meta/subscribe". { "channel": "/meta/subscribe". Streaming servers don't keep any client state and don't keep track of what's delivered. "subscription": "/topic/bar" }. "clientId": "Un1q31d3nt1f13r". If an application server is stopped. To do so. "clientId": "Un1q31d3nt1f13r". send a JSON array of subscribe messages instead of a single subscribe message. all the messages being processed but not yet sent are lost. "subscription": "/topic/baz" } ] 28 . so it receives only new messages from that point on. Messages may be lost for a variety of reasons. Some events may be dropped if the system is being heavily used. See Also: Streaming API Features Bulk Subscriptions You can subscribe to multiple topics at the same time. including: • • • • When a client first subscribes or reconnects. "clientId": "Un1q31d3nt1f13r". { "channel": "/meta/subscribe".

' See Also: Streaming API Features 29 . SELECT Id. See Also: Streaming API Features ID Fields in WHERE Clauses You can use an Id field in the WHERE clause of a SOQL query to receive updates about a record whenever it changes.Streaming API Features ID Fields in WHERE Clauses For more information. For example: SELECT Name__c. Ordinarily. Address__c FROM MyCustomer__c WHERE ID = 'id_value' This query in a PushTopic record reports the Name and Address of the specified record whenever the record changes. but ID fields provide this special behavior to make reporting on specific records easy. Inc. Queries such as the following will not usually return any results. Address FROM MyCustomer__c WHERE Name='Rachel Green. the value in the WHERE clause must change to trigger a Streaming API update. since the field in the WHERE clause does not usually change. see the Bayeux Specification.

Sort.0. It must be an API version greater than 20. Field Properties: Create. Field Properties: Default on create. Example value: 23.0 Field Properties: Create. Sort. update(). PATCH. Filter. Users with “View All Data” can view PushTopic records and see streaming messages. API version to use for executing the query specified in Query. Only users with “Create” permission can create this record.REFERENCE Chapter 5 PushTopic Represents a query that is the basis for notifying listeners of changes to records in an organization. If your query applies to a custom object from a package. Limit: 400 characters Field Properties: Create. Update Description string Description of what kinds of records are returned by the query. This is available from API version 21. Update CreatedById ID System field: ID of the User who created this record. Filter. Supported Calls REST: DELETE. GET.0 or later. delete(). Sort CreatedDate dateTime System field: Date and time when this record was created. Special Access Rules • • This object is only available if the Streaming API is enabled for your organization. Group. describeSObjects(). Filter. this value must match the package's ApiVersion. retrieve(). Update 30 . Sort. Filter. Fields Field ApiVersion Field Type Description double Required. describe(). query(). POST (query requests are specified in the URI) SOAP: create().

the system starts evaluating records. Group. If you change a PushTopic Name. Filter. Security and the SOQL Query Subscribers receive notifications about any create or update to a record if: 31 . Descriptive name of the PushTopic. Field Properties: Default on create. /topic/MyPushTopic. Sort Usage As soon as a PushTopic record is created. Group. Sort. Update Query string Required. New subscriptions must use the new channel name.PushTopic Field ID Field Type Description ID System field: Globally unique string that identifies a record. Sort isActive boolean Indicates whether the record currently counts towards the organization's limit. The SOQL query statement that determines which record changes trigger events to be sent to the channel. Sort. Field Properties: Default on create. Filter. Each PushTopic record that you create corresponds to a channel in cometD. A client receives events only if they match the new SOQL query. Update SystemModstamp dateTime System field: Date and time when this record was last modified by a user or by a workflow process (such as a trigger). Filter. Sort. Group. Filter. Group. Sort Name string Required. live subscriptions are not affected. Filter. Note: Updates performed by the Bulk API are not included in results. Default on create. Changes If you change a PushTopic record's query. Field Properties: Default on create. Limit: 1300 characters Field Properties: Create. Filter. Filter. Sort LastModifiedById ID System field: Date and time when this record was last modified by a user. Limit: 25 characters. idLookup. Field Properties: Default on create. Field Properties: Default on create. This value identifies the channel. changes take effect immediately on the server side. Field Properties: Create. Field Properties: Create. A Bayeux client can receive streamed events on this channel. such as MyNewCases or TeamUpdatedContacts. The channel name is the name of the PushTopic prefixed with “/topic/”. Filter. for example. Group. Sort LastModifiedDate dateTime System field: Date and time when this record was last modified by a user. Update IsDeleted boolean System field: Indicates whether the record has been moved to the Recycle Bin (true) or not (false). since such updates could flood a channel.

PushTopic • • • All custom objects and a subset of standard objects (that is. the subscription fails. For example. Opportunity) are supported. If the subscriber has already successfully subscribed to the PushTopic. Restrictions To ensure that notifications are sent in a timely manner. resulting in the user no longer having access to one of the fields. Case. by setting the isActive field to false. but the field-level security then changes. Name FROM.Id = pushTopicId. you execute the following Apex code to deactivate a PushTopic by Id: String pushTopicId = '0IFD0000000008jOAA'. assume a user tries to subscribe to a PushTopic with the following Query value: SELECT Id. Deactivating PushTopics You can temporarily deactivate a PushTopic. Here are examples of queries: ◊ Custom object SELECT Id. Name FROM Employee__c WHERE bonus_received__c = true AND bonus_amount__c > 20000 If the subscriber doesn't have access to bonus_received__c or bonus_amount__c. pt. Name FROM Account WHERE NumberOfEmployees > 1000 32 . the following restrictions apply to SOQL queries in the Query field: Requirements and Example Queries • • • Query must include Id in the root of the SELECT statement. no streamed events are sent.. Lead. Contact. For example.. update(pt). PushTopic pt = new PushTopic(). pt. rather than deleting it. Account... The record meets the WHERE clause criteria. For example: SELECT Id. Campaign. the select field is omitted from the output.IsActive = false. Only one entity per query. and The subscriber must have: ◊ Field-level security access to the fields specified in the WHERE clause ◊ Read access on the SObject in the query ◊ Visibility of the record based on sharing rules Note: If there are field-level security restrictions. MyCustomField__c FROM MyCustomObject__c ◊ One of the following standard objects (may include custom fields) Account SELECT Id.

AVG(AnnualRevenue) FROM Account ◊ Error message: INVALID_FIELD.Account. Name.Name FROM Contact ◊ Error message: INVALID_FIELD.PushTopic - Campaign SELECT Id. MAX. Count(Name) FROM Account ◊ Error message: INVALID_FIELD. and SUM) ◊ Example query: SELECT Id. Contact. Subject FROM Case WHERE Status = 'Working' AND IsEscalated = TRUE - Contact SELECT Id. Name FROM Campaign WHERE Status = 'Planned' - Case SELECT Id. Name FROM Account WHERE Id IN (SELECT AccountId FROM Contact WHERE Title = ‘CEO’) ◊ Error message: INVALID_FIELD. Name FROM Contact LIMIT 10 ◊ Error message: INVALID_FIELD. 'LIMIT' is not allowed • Relationships are not supported. semi/anti join sub-selects are not supported • Aggregate queries (that is. Unsupported for Developer Preview The following are not supported: • Semi-joins and anti-joins ◊ Example query: SELECT Id. ORDER BY 33 . AVG. but you can reference an ID: ◊ Example query: SELECT Id. Amount FROM Opportunity WHERE CloseDate < 2011-06-14 • As with any SOQL query. MIN. Email FROM Contact - Lead SELECT Id. the object must be valid for the specified API version. Company FROM Lead WHERE Industry = 'Computer Services' - Opportunity SELECT Id. Name. relationships are not supported • • Searching for values in Text Area fields. Industry. Aggregate queries are not supported • COUNT ◊ Example query: SELECT Id. Aggregate queries are not supported • LIMIT ◊ Example query: SELECT Id.

AccountId FROM Contact GROUP BY AccountId ◊ Error message: INVALID_FIELD. Name FROM Account ORDER BY Name ◊ Error message: INVALID_FIELD. 'Aggregate queries are not supported' • • Formula fields NOT ◊ Example query: SELECT Id FROM Account WHERE NOT name = 'Salesforce. 'ORDER BY' clause is not allowed • GROUP BY ◊ Example query: SELECT Id.com' ◊ Error message: INVALID_FIELD. 34 .PushTopic ◊ Example query: SELECT Id. 'NOT' is not supported • Queries without ID in the selected fields lis Client Limits See Streaming API Limits on page 35.

35 .000 for free organizations.com. regardless of activity (maximum CometD session) Maximum length of the SOQL query in the Query field of a PushTopic record Maximum length for PushTopic name Limit 20 10 10 1. please contact salesforce.Chapter 6 Streaming API Limits Description Maximum number of topics Maximum number of clients (subscribers) per topic Maximum number of concurrent clients (subscribers) across all topics Maximum number of events per day Socket timeout during connection (CometD session) Timeout to reconnect after successful connection (keepalive) Timeout for session. 100.000 for all other organizations 110 seconds 40 seconds 3600 seconds 1300 characters 25 characters Note: To increase the number of clients per topic or the number of concurrent clients across all topics.

27 client 27 getting started 3 J JSON 10 JSON array for bulk subscriptions 28 T Timeouts 27 L Limits 35 Long polling 4 U Using the Streaming API 26 M Message loss 28 W WHERE clause 29 36 .Index Index B Bayeux protocol 4. 13 access token 11 Developer Edition 11. 10 Browsers 4 Bulk subscriptions 28 O OAuth 10 access token 10 C Client 27 timeout 27 Clients for Streaming API 27 CometD 4 P PushTopic 30 Streaming API object 30 Q Quick Start 6–8 create an object 7 creating a push topic 7 prerequisites 6 subscribe to a channel 8 testing the PushTopic 8 using workbench 6 Quickstart 10–11. 13 OAuth 11 prerequisites 10 D Debugging the Streaming API 5 G Getting started 3 H HTTPS 4 I ID Fields 29 S Stateless 28 Streaming API 3.

Sign up to vote on this title
UsefulNot useful