I am developing a web application which communicates to/from a server using JSON. I use
var jsonStr = '{ name: "Rob", time: "2pm" }';
jQuery("#name").jqGrid({
type : "POST",
url:'ControllerServlet?jsonData='+jsonStr,
datatype: "json",
to pass data to server as JSON string, parse it in server, process it and send a JSON back which is displayed in the jqGrid.
This works for me, but I wonder what is the role of JSON-RPC; I read that it is used for remote calls. Is there any advantage in using JSON-RPC instead of using the above way to invoke servlet? How can I use JSON-RPC to do the same action?
As the website states, JSON-RPC is a remote procedure call protocol specification using JSON. It is therefore a specification to call remote methods/procedures on a server similar to XML-RPC or Java's RMI. Both JSON-RPC and XML-RPC can use HTTP as the underlying transport protocol but can also work with others.
On the other hand jqGrid and in general Ajax usually uses HTTP (ideally RESTful) requests to fetch or transfer direct representations of e.g. JSON or XML encoded data. By now this is the preferred way in JavaScript development (comparison of REST vs XML-RPC is a nice read and applies to JSON-RPC as well).
Related
I am developing a library for working with various types of cloud based queue services.
One of those services is the Azure Queue Storage REST API.
For the Amazon SQS service I can send an Accept: application/json header and the response is in JSON format.
Since JSON is a format that is supported by many APIs and XML is not fun to work with, I would prefer the Azure Storage REST API to also return a response in JSON format.
I have tried to set the Accept: application/json header to no avail. The responses are all in XML format with Content-Type: application/xml, which is obviously not what I was asking for.
Currently all code is in C with dependencies on a couple of libraries, including cURL and jansson, although for this question that doesn't really matter. It's just that I would like the library to be as simple and lightweight as possible.
I have a hard time digging through all kinds of documentation. Most topics I can find are about sending JSON within a message. But that's not what I'm going for.
Is it even possible to receive the actual responses in JSON? I would really like to drop my libxml2 dependency.
As pointed by #Tom Because the documentation is stating that it only return XML, I would personally write an azure function who becomes an adaptor which basically takes your request, sends it to azure queue storage, retrieves the xml response and then converts the xml response to json and return the json to the caller (which will be your C code).
A sample python code to convert xml to json is shown below:
import xmltodict
import json
text = ''
xpars = xmltodict.parse(text)
json = json.dumps(xpars)
print(json)
A sample xml message
text = '<QueueMessagesList>
<QueueMessage>
<MessageId>string-message-id</MessageId>
<InsertionTime>insertion-time</InsertionTime>
<ExpirationTime>expiration-time</ExpirationTime>
<PopReceipt>opaque-string-receipt-data</PopReceipt>
<TimeNextVisible>time-next-visible</TimeNextVisible>
<DequeueCount>integer</DequeueCount>
<MessageText>message-body</MessageText>
</QueueMessage>
</QueueMessagesList>'
And the response will be :
{
"QueueMessagesList": {
"QueueMessage": {
"MessageId": "string-message-id",
"InsertionTime": "insertion-time",
"ExpirationTime": "expiration-time",
"PopReceipt": "opaque-string-receipt-data",
"TimeNextVisible": "time-next-visible",
"DequeueCount": "integer",
"MessageText": "message-body"
}
}
}
Please Note: This whole thing can also be done using a Logic App in azure.
I have only shown the XML to JSON converter part here, but it is really straightforward to write an HTTP Trigger Azure Function to do the same. Or you can even write this converter into your C code as well.
Hope this helps you in moving on with your library development.
Protocol: A standard to define a method of exchanging data over a network.
If a browser wants to communicate with a server, it has to create an HTTP request and send that HTTP request to the server to convey its request of resources and options. The server receives the request and process it and do the needful and create an HTTP response to send to the browser. The browser has to follow the HTTP specification in creating the HTTP request. The server also has to follow the HTTP specification in creating the HTTP response. This is how the communication between the browser and the server happens in a standard way to avoid conflicts by following the HTTP protocol.
Json Wire Protocol: A client has an object that has to be sent to a server. The client converts this object into a JSON object and sends it to the server. The server parses the JSON object and converts it back to object for use. The server converts the response object into a JSON object and sends it back to the client. The client then converts the JSON object to object for use.
Why the later is called as Json Wire Protocol?
You are pretty correct both about Protocol and JsonWireProtocol. At this point it is worth to mention that, earlier all implementations of WebDriver that communicated with the browser, or a RemoteWebDriver server shall use a common wire protocol. This wire protocol defines a RESTful web service using JSON over HTTP.
JSON Wire Protocol is an abstract specification of how automation behavior like clicking or typing or whatever you actually want to do with your automation script is mapped to selenium or appium or HTTP requests and response. The protocol will assume that the WebDriver API has been "flattened", but there is an expectation that client implementations will take a more Object-Oriented approach, as demonstrated in the existing Java API. The wire protocol is implemented in request/response pairs of "commands" and "responses".
What is JSON Wire protocol?
JSON (JavaScript Object Notation) is a lightweight format for data exchange between client and server. Applications use JSON objects to send and receive data between each other in the web world. JSON data structure is industry standard and can be used for sending and receiving data as Key & Value pair. Some people say its a very nice alternative for XML. We can save JSON files as .json extension.
How JSON looks like?
A simple json file looks like below and there are many online editors which can be used to edit and verify JSON structure.
{
"Student":{
"FirstName":"Pawan",
"LastName":"Garia",
"IdNumber":"12345",
"City" : "New Delhi",
"EmailID" : "email#gmail.com" }
}
Why JSON Wire Protocol was used in first place?
To implement a client-server architecture which can give us the following benefits.
You write test in any programming language.
You can perform or run test on cloud services like SauceLabs, BrowserStack or Selenium Grid setup.
You are not bound to run test only on the local machine.
Different Drivers(FirefoxDriver, ChromeDriver) can be crated for browsers and separate implementation by using the same standards.
So client-server implementation requires a standard set of the specification beforehand so that Server and Client should be in sync with each other in term of what is coming and going on request and response. It’s something like a language of communication with each other. So we need some common specification to solve this kind of requirement and the solution was HTTP.
Why HTTP is the solution?
HTTP is a standard for web and can be a good base for the specification. Every programming language has a good HTTP libraries which can be used for creating client and server for request and response calls.
How JSON Wire protocol worked with HTTP?
HTTP request and response are generally made of GET and POST requests which is out of scope for this discussion.
Current status
From Selenium perspective, JSON Wire Protocol is obsolete now and the WebDriver W3C Living Document is the new implementation.
WebDriver Communication
The WebDriver protocol is organised into commands. Each HTTP request with a method and template defined in the specification represents a single command and hence each command produces a single HTTP response. In response to a command, the remote end will run a series of actions known as remote end steps. These provide the sequences of actions that a remote end takes when it receives a particular command.
Command Processing
The remote end is an HTTP server reading requests from the client and writing responses typically over a TCP socket. In the specification the communication is modeled as the data transmission between a particular local end and remote end with a connection to which the remote end may write bytes and read bytes. The exact details of how this connection works and how it is established is a bigger topic and out of scope for this question. After a connection has been established, the remote end must read bytes from the connection until a complete HTTP request can be constructed from the data. If it is not possible to construct a complete HTTP request, the remote end must either close the connection, return an HTTP response with status code 500, or return an error with error code unknown error.
Outro
Difference between JsonWireProtocol mechanisms and the new standards in W3C Living Document when using Selenium
When making an AJAX request to a server (may be Java, PHP, etc), is it necessary to pass data as JSON string ?
Can we not pass the object directly ? Are there issues de-serializing OR can that be handled at the backend ? Any examples of handling JS object (if it is possible to send an obj directly) at the backend would be great ?
Object literal makes sense only in the JavaScript runtime environment. Since AJAX body is simply a string, you can pass {a:3} to a server. But what should server side do with it? It ertainly can store it in a database and return to you back when requested. But what if it wanted to extract some data from it? You' have to have JS runtime and evaluate the object using eval. Which would be awkward, but possible. However, not all servers have JS runtime environment. Whereas there are libraries for many languages that support parsing JSON into the representation specific to the language on the server.
An AJAX request passes data to the server in the same way any other HTTP request does. Most commonly, AJAX requests use POST and pass data to the server as POST data, but query strings are often used, and there are other ways to pass data to a server using HTTP and AJAX.
In essence all HTTP data is octets (bytes), and HTTP has no special support for serialization of JavaScript objects, so you or the libraries and/or frameworks you use must handle the serialization.
I was checking the files in the controllers of web module in both OpenERP-7.0 and OpenERP-6.1. Then I found that 6.1 uses jsonrequest (#openerpweb.jsonrequest) 7.0 uses httprequest (#openerpweb.httprequest). What is the difference between the two ?
I didn't look at OpenERP v7 but OpenERP v6.1 uses both - HttpRequest and JsonRequest. I suppose it's the same for OpenERP v7...
Both of them are about communication between client and server. HttpRequest communicates trough the well known GET and POST methods. That means the following:
The client send a request encoded in the url (GET method) or in the http body (POST method)
The server returns an object corresponding to the request. Could be an html page, PNG image, CSS file, JavaScript, XML encoded data or whatever.
JsonRequest is an implementation of another protocol for client/server communication - JSON-RPC 2.0. You may want lo look here for more information. It's a remote procedure call (RPC) protocol which means that it allows the client to initiate the execution of some method on the server passing some arguments to this method. In response the client gets some data as a result of the method invocation.
EDIT - some more words about the decorators #openerpweb.jsonrequest and #openerpweb.httprequest
Some methods are decorated with the #openerpweb.jsonrequest decorator, other methods - with the #openerpweb.httprequest. This means nothing else but that the first group of methods will be available for execution trough the JSON RPC protocol and the second group will be accessible trough the pure HTTP protocol.
Now, what is the difference? And do we need both jsonrequest and httprequest? Let simplify it like this: JSON is more suitable for executing methods on the server and obtain results. HTTP is simpler and easier to use when all we what is to access some resource on the server.
Let's 'decorate' this with some examples for clarity. Take a look at the following method of the web.controllers.main.Export class:
#openerpweb.jsonrequest
def formats(self, req):
""" Returns all valid export formats
:returns: for each export format, a pair of identifier and printable name
:rtype: [(str, str)]
"""
...
This method accepts some arguments and returns a list (Python list object) containing all known export formats. It will be called in a programmatic way in some python code on the client side.
On the other side are the 'http' methods - like the method css() of the web.controllers.main.Web class:
#openerpweb.httprequest
def css(self, req, mods=None):
....
All this method does is to return a CSS file to the client. It's a simple action like accessing an image, a HTML web page or whatever other resource on the server. The resource we are returning here is nothing complicated as a Python list as in the previous example. We don't need a special format to encode it additionally. So we don't need additional data encoding format as JSON and remote procedure call protocol as JSON RPC.
We use org.json api to parse json on server side and GWT JsonParser to parse JSON on client side. Is there a api that we can use that can be used on both the client side and server side?
You are looking for GWT AutoBean: http://code.google.com/p/google-web-toolkit/wiki/AutoBean
With AutoBeans you juset define the structure of your JSON and the GWT Compiler handles the rest.
I am writing this in comparison to using autobeans or GWT-RCP - if you are using Java on the server. Especially so, if you are not.
The cleanest way is REST-RPC/JPA, where you can share a single set of POJOS between client, server and persistence db. Let me brag on behalf of this technology mix - one single set of POJOs, instead of three, without any (or minimal) transformation between the three fronts.
You should not have to write any data transformation routines. Or at least, only minimal amount of data transformation due to serialization constraints or because you are trying to interface GWT and REST with an existing schema which presents a high degree of non-serializability.
As well as, similar to GWT-RPC, sharing a single set of Java RPC methods on both client-server sides. Well, nearly the same set of methods. Except that the return type on the server-side becomes the callback generic parameter on the client-side.
The mix of technology is:
JAX-RS (either Resteasy or Jersey on the server side)
JAX-RS + GWT = RestyGWT on the client-side
JPA on the server-side
JAXB over JAX-RS on both GWT client and server-side.
Jackson JSON processor on server-side.
Compelling reasons for REST-RPC is
you could pretend you writing client-server conversations as GWT-RPC. The service interface and callback attitude is the same.
The data interchange between client and server is in JSON.
Which means you could use a browser instead of your GWT client to converse with the server after you have successfully set up your app. Or jQuery. Or PHP, or Python as the server.
no need to muck around with the JSON or XML encode/decode yourself - deal in POJO and only in POJO.
you could use the browser to debug your web service independent of the GWT client.
The attitude of REST is (besides state independent requests) is the concept called a Web API. An API like a javadoc, perhaps - but stated in terms of JSON or XML. The wonderful thing about this API is - you do not have to generate the documentation. Like a javadoc, you could run Enunciate over the service interface.
You could follow my discussion in the following (3+ part) blog post:
http://h2g2java.blessedgeek.com/2012/07/gwt-with-jax-rs-and-jpa-part-3.html.