+ Start a Discussion
Saravanan @CreationSaravanan @Creation 

Dynamically passing push topic to page and getting back the record id

Hi All

 

I created the page from followed the code from streaming API pdf example of visualforce page .But after created the record on the object i didn't get the value on the streaming visualforce page.can any one help me how to find out the error on code.

 

 

And also i have the requirement when one object field value is changed to some known value then i need to create one record on another object whether its possible on streaming API If you have code sample then is more helpful for me.

 

 

Best Answer chosen by Admin (Salesforce Developers) 
Saravanan @CreationSaravanan @Creation

Hi Friends,

 

Finally i got the way to bring the push topic dynamicaly  from the controller,And I passed the received message id to the controller.

 

for implementing the salesforce API Streaming guide(Second visualforc code example) and below link is helped me a lot 

 

http://wiki.developerforce.com/page/Getting_Started_with_the_Force.com_Streaming_API

 

http://boards.developerforce.com/t5/Streaming-API-Developer-Preview/Error-trying-to-do-the-Visualforce-sample-of-Streaming-Api/td-p/349157

 

after got the object record id in the controller we able to do any operation like insert,update etc..

 

my sample codes are as follow as.

 

<apex:page controller="StreamingAPI">

<apex:includeScript value="{!$Resource.cometd}"/>

<apex:includeScript value="{!$Resource.jquery}"/>

<apex:includeScript value="{!$Resource.json2}"/>

<apex:includeScript value="{!$Resource.jquery_cometd}"/>

<script type="text/javascript">

(function($){

$(document).ready(function() {

// Connect to the CometD endpoint

$.cometd.init({
url: window.location.protocol+'//'+window.location.hostname+'/cometd/23.0/',
requestHeaders: { Authorization: 'OAuth {!$Api.Session_ID}'}
});

// Subscribe to a topic. JSON-encoded update will be returned
// in the callback
$.cometd.subscribe('{!pushTopicName}', function(message) {
$('#content').append('<p>Notification: ' +

'Channel: ' + JSON.stringify(message.channel) + '<br>' +

'Record name: ' + JSON.stringify(message.data.sobject.Name) + '<br>' +

'ID: ' + JSON.stringify(message.data.sobject.Id) + '<br>' +

'Event type: ' + JSON.stringify(message.data.event.type) +'<br>' +
'Created: ' + JSON.stringify(message.data.event.createdDate) + '</p>');

StreamingAPI.JsonResult(JSON.stringify(message.data.sobject.Id),function(result, event){
},{escape:true});

});

});

})(jQuery)

</script>

<body>

<div id="content">

<p>Notifications should appear here...</p>

</div>

</body>
</apex:page>

 

 

controller code

 

 

public with sharing class StreamingAPI {

Public String pushTopicName;

public StreamingAPI(){

}

public string getpushTopicName(){
PushTopic pt=[select id, Name from pushTopic where isActive=true];
pushTopicName='/topic/'+pt.Name;
return pushTopicName;
}

@RemoteAction
public static void JsonResult(string json){

System.debug('*******JSON String**********:'+ json);
}

}

 

 

 

 

 

 

All Answers

greentruck55greentruck55

streaming is Notification only..  you have to use some other code to update or create other objects..  you would use the standard remote SF apis.

 

I had a problem with one of the samples, where the 'topic' was wrong in the example..

 

the topic name MUST be '/topic/' + your topic name

 

in the earlier samples '/topic/' was not required..

 

you can also trace the events on the salesforce system log..

 

Saravanan @CreationSaravanan @Creation

Thanks for your reply,

 

but based on my requirement, for example when field value is changing to  some know value i need to update some record only through API streaming.

 

the requirement like a monitoring field.

 

whether its possible to achieve by using API streaming, If its possible how can i achieve this.give me some example code

 

thanks in advance.

 

greentruck55greentruck55

Again, the Streaming api is outbound notifications ONLY, there is NO update or read capability.

 

Streaming will ONLY tell you WHICH record(s) matched your Topic configuration, AND supply the fields you requested.

 

any additional work must use the standard SF api sets.

 

In one of my applications using Streaming, I only return the record ID. I know that I need more fields, but they are not all in the specific record I was notified about (comments, attachments, and other related objects must be found uniquely thru related object links)..

and as we know we will chnage our minds over a long production period, this list of data is configured separately from the Push Topic.

 

the code receiving the notification then makes a SOQL call (using the Partner WSDL apis & the object ID) to get all the required data in ONE Soql stmt (built dynamically).

 

Sam

Saravanan @CreationSaravanan @Creation

Thank you very much,

 

Can you please tell me how you got  the object id when the particular record is changed in API streaming.and how did you pass the id into partner wsdl 

 

can you please post that API streaming page code and controller code,It will help me out to deal with this.

 

greentruck55greentruck55

In your pushtopic definition you tell the server what fields to send

 

for my test environment.

 

select name,id, description__c from problem__c where .....

 

and I get a streaming event message

 

Received Message: {"data":{"sobject":{"Name":"123461","Id":"a0O30000009JhdcEAC","Description__c":"this is a test problem of a synchronized problem"},"event":{"type":"updated","createdDate":"2012-07-02T13:42:56.000+0000"}},"channel":"/topic/updatedProblem","clientId":"vxfsf6gvp04bu133otjrsh4g3y"}
id found=a0O30000009JhdcEAC

 

and so you can use the id field to  make further soql calls just like normal

( this is a test system)

so my soql back is

select name from Problem__c q where id='a0O30000009JhdcEAC'

 

and then I get the SF select response, and have to parse that as always.,

 

my streaming code is all in Java,  there is nothing on the server side except the pushtopic creation.

 

here is my streaming event message handler.

I parse the JSON response into a hashmap

and then access the hashmap

 

all of this is standard documented SF Partner WSDL apis. (and my creation of code using them)

 

			client.getChannel(CHANNEL).subscribe(new MessageListener() {
				public void onMessage(ClientSessionChannel channel, Message message) {
					System.out.println("Received Message: " + message);
					try
					{
					    JSONReader reader = new JSONReader();
					    Object result = reader.read(message.toString());
					    if(result.getClass().getName()=="java.util.HashMap")
					    {
					    	String id=getItem((HashMap)result,"data.sobject.Id");
					    	if(id!=null)
					    			System.out.println("id found="+id);
					    	String qs=f.replace(fakeid, id); // build the query string
					    	System.out.println("query string="+qs);
					    	QueryResult qr=connection.query(qs);  // call SF partner api to get more 
					    	System.out.println("there were "+qr.getSize()+" records returned");
					    	SObject[] recordinfo=qr.getRecords();  // get the select results
						    	// process the select results
						    	Iterator it=recordinfo[0].getChildren();
						    	while(it.hasNext())
						    	{
						    		processObject((XmlObject)it.next());
						    	}

						    	System.out.println("there are "+qr.getSize()+ " children");
					    }
					}
					catch (Exception e)
					{
						// TODO Auto-generated catch block
						e.printStackTrace();
					}

 

 

 

 

Saravanan @CreationSaravanan @Creation

Thanks,

 

I will try this on tommorow morning,If i am facing any issues can you help.













 

greentruck55greentruck55

I will try to help..

 

You should write a program that uses the partner wsdl first to get that right. separate from streaming

 

Saravanan @CreationSaravanan @Creation

Hi,

 

How did you got the API streaming received message on controller,below is my page code

 

<apex:page >
<apex:includeScript value="{!$Resource.json2_js}"/>
<apex:includeScript value="{!URLFOR($Resource.cometd, 'dojo/dojo.js')}"/>
<apex:includeScript value="{!$Resource.demo_js}"/>
<apex:stylesheet value="{!$Resource.demo_css}"/>
<script>var token = '{!$Api.Session_ID}';</script>
<div id="demo">
<div id="datastream"></div>
<div id="input">
<div id="join">
<table>
<tbody>
<tr>
<td>&nbsp;</td>
<td> Enter Topic Name </td>
<td>
<input id="topic" type="text" />
</td>
<td>
<button id="subscribeButton"
class="button">Subscribe</button>
</td>
</tr>
</tbody>
</table>
</div>
<div id="joined">
<table>
<tbody>
<tr>
<td>
<button id="leaveButton"
class="button">Unsubscribe</button>
</td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
</apex:page>
In this page how can i use controller instead of displaying the received msg on page i need get it on controller.

 

 

greentruck55greentruck55

see http://www.salesforce.com/us/developer/docs/pages/Content/pages_js_remoting.htm

 

I think.. I have only done this with OnClick., but not passed data in the request directly, but using form fields instead.

 

 

Saravanan @CreationSaravanan @Creation

Thanks dude,

 

I spend today,

 

i created pushtopic.

 

and i created the page given in salesforce,the first excrices page.

 

i am not able to get the responce message atomatically in controller 

 

 

whether second excrices will be good for this.

 

if you have time please have a look 

 

greentruck55greentruck55

Sorry, I don't know how to get the javascript detected event into a controller, unless you use the SF remoting apis I linked to before.

 

I think those questions should be asked over in the VisualForce board section. they have nothing to do with streaming.

Saravanan @CreationSaravanan @Creation

Hi Friends,

 

Finally i got the way to bring the push topic dynamicaly  from the controller,And I passed the received message id to the controller.

 

for implementing the salesforce API Streaming guide(Second visualforc code example) and below link is helped me a lot 

 

http://wiki.developerforce.com/page/Getting_Started_with_the_Force.com_Streaming_API

 

http://boards.developerforce.com/t5/Streaming-API-Developer-Preview/Error-trying-to-do-the-Visualforce-sample-of-Streaming-Api/td-p/349157

 

after got the object record id in the controller we able to do any operation like insert,update etc..

 

my sample codes are as follow as.

 

<apex:page controller="StreamingAPI">

<apex:includeScript value="{!$Resource.cometd}"/>

<apex:includeScript value="{!$Resource.jquery}"/>

<apex:includeScript value="{!$Resource.json2}"/>

<apex:includeScript value="{!$Resource.jquery_cometd}"/>

<script type="text/javascript">

(function($){

$(document).ready(function() {

// Connect to the CometD endpoint

$.cometd.init({
url: window.location.protocol+'//'+window.location.hostname+'/cometd/23.0/',
requestHeaders: { Authorization: 'OAuth {!$Api.Session_ID}'}
});

// Subscribe to a topic. JSON-encoded update will be returned
// in the callback
$.cometd.subscribe('{!pushTopicName}', function(message) {
$('#content').append('<p>Notification: ' +

'Channel: ' + JSON.stringify(message.channel) + '<br>' +

'Record name: ' + JSON.stringify(message.data.sobject.Name) + '<br>' +

'ID: ' + JSON.stringify(message.data.sobject.Id) + '<br>' +

'Event type: ' + JSON.stringify(message.data.event.type) +'<br>' +
'Created: ' + JSON.stringify(message.data.event.createdDate) + '</p>');

StreamingAPI.JsonResult(JSON.stringify(message.data.sobject.Id),function(result, event){
},{escape:true});

});

});

})(jQuery)

</script>

<body>

<div id="content">

<p>Notifications should appear here...</p>

</div>

</body>
</apex:page>

 

 

controller code

 

 

public with sharing class StreamingAPI {

Public String pushTopicName;

public StreamingAPI(){

}

public string getpushTopicName(){
PushTopic pt=[select id, Name from pushTopic where isActive=true];
pushTopicName='/topic/'+pt.Name;
return pushTopicName;
}

@RemoteAction
public static void JsonResult(string json){

System.debug('*******JSON String**********:'+ json);
}

}

 

 

 

 

 

 

This was selected as the best answer
vinti chittoravinti chittora
@Saravanan @Creation 
Can you please attach the files that you have used in static resources. It will be very helpful.
Thanks.