Categories
Community Learning XPages XPages

Tim explains JSON-RPC #codefortim

First I want to highlight OpenNTF’s recent post regarding Tim’s projects.  Let me simply say that I think the #codefortim idea is brilliant. Pure genius and so appropriate.  Tim shared.  Period. I just read that post like 5 minutes ago so I’m going to let it sink in before I talk any more about it.

Which brings us to the topic of today.  This email exchange I’m going to post was forwarded to me by my friend Dan.  He asked Tim a question and as usual got a great response back.  I’m so very thankful he sent this to me.  What make this really special is just how recent it is.  It was only a couple of days before Tim passed.  This is the last email I have to publish.  If anyone has any similar emails that they’d be willing to share I’d be very happy to publish them as well. Next up is some videos.

Dan asks:

On May 7, 2014 at 4:30:20 PM, Daniel wrote:

Hi Tim,

I was looking at an answer you gave Naveen on Stack Overflow on the use of the JSON-RPC control.

http://stackoverflow.com/questions/11356227/how-to-use-xejsonrpcservice

From how you describe the control, it sounds like an AJAX operation. Is my understanding correct?

I’m thinking of an application for it and I wonder if you could tell me if it’s the right tool.

I have an Xpage I’m building that accepts input from a proximity scanner. When an ID is scanned (badgeNo), I’d like to be able to query and SQL db to get the person’s EmpID number and use that to display his image on the screen. Would the JSON-RPC control be appropriate for that kind of operation?

Thanks,

Dan

Tim responds:

From:        Tim Tripcony

To:        Daniel

Date:        05/08/2014 02:15 AM

Subject:        Re: JSON-RPC control


In my opinion, that use case is almost definitely a good fit for JSON-RPC.

RPC stands for “remote procedure call”. Simply put, you’re telling the server to run a method — and how to run that method (in other words, passing method arguments) — and send back a result. So yes, this is AJAX, but it’s slightly different from partial refresh events in XPages.

Partial refresh events execute server-side code, of course, but upon completion they send back a specific visual representation of a portion of the page (namely, HTML) because that portion of the page might need to look different afterward as a result of the execution of that code. The archetypal example of this is an onChange event in a combo box that alters which select values are now valid for an additional combo box further down the page. As you’ve no doubt already seen in action, the platform automatically generates the JavaScript for you that causes the AJAX call to tell the server what code to run, but also handles taking the HTML that is returned and updating the affected portion of the page.

Similarly, submission of any data the user has entered is also automatic. While there are ways to override exactly how much data is sent for each specific event, the default is to just post the entire form to the server. This facilitates the “statefulness” of XPages — with each event, the server state of the page is essentially synchronized with what the client state now is, so both the browser and the server have some level of awareness of the user’s behavior, and both can account for that current state.

JSON-RPC, by comparison, might appear rather manual at first glance. Adding one of these components to your page and defining one or more methods is essentially defining an API that you can then call… but you still need to then add client-side code to actually call it, and also to respond to whatever data the server sends back to the browser. There are a few bits of good news in this regard, however:

– The platform still auto-generates some client-side JavaScript for you. To be precise, a global JavaScript object is created client-side and populated with methods that map to whatever server-side methods you defined for the RPC. These methods are even aware of what arguments you defined for each.

– The performance of this type of service is incredibly lean for two reasons. One reason is that it sends the absolute minimum amount of data in both directions. To be precise, it sends only identifiers for which service is being called and which method it should run, as well as the value of any arguments; in return, it sends back only whatever value you explicitly return from whichever method is called. So instead of posting the values of potentially dozens or even hundreds of fields and getting back a big blob of HTML, it might send only a single number (e.g. badge ID) to the server and get back a single string (e.g. employee ID)… although the response object can be as simple or complex as you want.

The other reason it’s faster is because the default behavior is to not save the component tree after an RPC method runs. It’s assuming that you’re doing something very similar to the use case you described, so there’s no need to re-serialize the entire page state, because you’re not sending a bunch of form data that should update a backing model bean, etc.; rather, you’re just sending it a badge ID and asking it to send back a corresponding employee ID, so there shouldn’t be a need for it to “remember” that it did once it has.

For both of these reasons, JSON-RPC tends to be lightning fast when compared to most partial refresh events, even under low-bandwidth / high latency conditions.

Here’s some pseudo-code to give you a feel for what this might look like if you decide to take the JSON-RPC approach. Somewhere in your XPage you’d have component markup that looks similar to the following:

<xe:jsonRpcService id=”scannerRpc” pathInfo=”scanner”>

<xe:this.methods>

<xe:remoteMethod name=”getEmployeeId” script=”return getEmployeeIDFromSQL(badgeId);”>

<xe:this.arguments>

<xe:remoteMethodArg type=”number” name=”badgeId” />

</xe:this.arguments>

</xe:remoteMethod>

</xe:this.methods>

</xe:jsonRpcService>

The assumption, of course, is that the getEmployeeIDFromSQL() function is already defined somewhere — presumably, in a SSJS library. So for what you’re describing, all that might really need to change in the above example is to alter the type of the badgeId argument (if, for instance, that should be a string, not a number) or to change the getEmployeeIDFromSQL reference to whatever code will be responsible for actually performing the SQL query, whether that be SSJS or perhaps a method of some Java bean.

The other half of this, then, is defining client-side code to call the remote method defined above. If that’s triggered by a “Search” button, for instance, you might end up with something like this:

<xp:button value=”Search” id=”button1″>

<xp:eventHandler event=”onclick” submit=”false”>

<xp:this.script><![CDATA[var badgeId = someCodeToGetIdFromScanner();

scanner.getEmployeeId(badgeId).addCallback(function(employeeId){

dojo.byId(“#{id:employeeId}”).attr(“value”, employeeId);

});]]></xp:this.script>

</xp:eventHandler>

</xp:button>

You might, of course, be setting the innerHTML of a div instead of the value of an input, but hopefully the above example illustrates the basic premise:

– Because the JSON-RPC service lists “scanner” as the value of its “pathInfo” attribute, the browser will automatically be aware of a global JavaScript object called “scanner”.

– Because the RPC service defines a remote method named “getEmployeeId” that accepts a single argument named “badgeId”, the global client-side object has a function called “getEmployeeId” that is also expecting a single argument.

– Calling that client-side function does not immediately send the AJAX request; rather, it returns an object that has a .addCallback method. Calling this method does immediately trigger the AJAX call… and passing a function to addCallback() defines what code will run when the AJAX call returns. Since we’re just expecting to get back a single string value, we specify that the function that we pass to addCallback() accepts a single argument, which we can then use inside the function to somehow update the page or otherwise inform the user that we now know what the scanned employee’s ID is.

No doubt there’s a myriad of valid approaches for your specific use case, but I’ve become rather fond of JSON-RPC for this type of functionality, both because of the relative ease of implementation and because of the comparative performance. Hopefully this overly verbose explanation gives you an indication of whether or not the JSON-RPC approach would, in fact, be a good fit for what you’re trying to do. 🙂


For anyone reading this information that’s interested in the JSON-RPC stuff.  I believe it’s come up on NotesIn9 a couple times as well. So there should be some examples available.

#codefortim