Wednesday, November 30, 2011

JSON-P an example

Say, you have an HTML page in 1 domain and a servlet running in another domain.
For cross domain communication from your HTML and Servlet you can take advantage of the JSONP.

HTML File in Server 1



<html>
  <head>
    <script type="text/javascript">
      function callTheJsonp() {
          // the url of the script where we send the asynchronous call
          //var url = "http://rws65594fwks.us.oracle.com:7001/GoogleAppInsideFireWall/osmservlet?callback=parseRequest";
          var currentPageURL = document.location.href;
          alert(currentPageURL);
          var url = "http://127.0.0.1:7101/GoogleAppInsideFireWall/osmservlet?callback=parseRequest&calledPageUrl="+currentPageURL;//For My JDev testing
          // create a new script element
          var script = document.createElement('script');
          // set the src attribute to that url
          script.setAttribute('src', url);
          // insert the script in out page
          document.getElementsByTagName('head')[0].appendChild(script);
      }

      // this function should parse responses.. you can do anything you need..
      // you can make it general so it would parse all the responses the page receives based on a response field
      function parseRequest(response) {
          try // try to output this to the javascript console
          {
              alert('in callback--Response from OSM ');
              //console.log(response);
              alert('product id ' + response.itemId + ': quantity = ' + response.quantity + ' & price = ' + response.price);
          }
          catch (an_exception)// alert for the users that don't have a javascript console
          {
              alert('product id ' + response.itemId + ': quantity = ' + response.quantity + ' & price = ' + response.price);
          }
      }
    </script>
  </head>
  <body>
    <form>
      <p>
        <b>AMulya Mishra Test-&gt;</b>
         is a simulation of Buzzient UI hosted in 
        <b>Google Apps</b>.Clicking this button will invoke Ravi's WLS ADF App
                          which is inside Oracle Firewall.
      </p>
      <p>Access this page without VPN or without Proxy.. Before clicking this
         button, set proxy or connect to VPN and click to access the ADF App
         running in Ravi's WLS.</p>
      <p>
        1)-See the java script code written in this HTML using view source.<br>
        2)-Clicking 'Create Service Request' button calls a JavaScript method called callTheJsonp().<br>
        3)-Here we add a dynamic script tag with attribute src pointing to a servlet in different WLS.<br>
        4)-The servlet has a method to generate a JSON object and send it back as response to This page.<br>
        5)-Then it invokes function parseRequest(response) which takes this JSON object and prints in javascript console.<br>
      </p>
      <input type="button" name="Create Fusion Apps Service Request"
             value="Create Fusion Apps Service Request"
             onclick="callTheJsonp();"/>
          </form>
  </body>
</html>



Servlet code in Server 2


package view.oracle.apps.atf.osm.hadoopTest;

import com.google.gson.Gson;

import java.io.IOException;
import java.io.PrintWriter;

import java.util.Map;

import java.util.Random;

import javax.servlet.*;
import javax.servlet.http.*;

import oracle.apps.OSMPojo;

public class OSMServlet extends HttpServlet {
    private static final String CONTENT_TYPE = "text/html; charset=UTF-8";

    public void init(ServletConfig config) throws ServletException {
        super.init(config);
    }

    public void doGet(HttpServletRequest request,
                      HttpServletResponse response) throws ServletException,
                                                           IOException {
        System.out.println("--->Here in GET");
        response.setContentType(CONTENT_TYPE);
        PrintWriter out = response.getWriter();
        Map params = request.getParameterMap(); 
        if(params != null && params.containsKey("callback")){
            String jsonData = this.getJSONData();
            String output = request.getParameter("callback") + "(" + jsonData + ");";
            out.println(output);
        }
        out.close();
    }

    private String getJSONData() {
        Gson gson = new Gson();
        OSMPojo pojo = new OSMPojo();
        pojo.setItemId(new Long(new Random().nextLong()).toString());
        pojo.setPrice(new Long(new Random().nextLong()).toString());
        pojo.setQuantity(new Long(new Random().nextLong()).toString());
        String json = gson.toJson(pojo);
        return json;
    }    
}

10 comments:

EMPORiO said...

Hi,

How will i call the servlet app, if this requires username/passoword(not basic Authentication).

Hyderabad Jobs said...

Nice post all the information of the place there in the blog but it should have also contains some pictures or images of the place which look more attractive

Anonymous said...

viagra achat viagra acheter comprar viagra precio viagra viagra viagra senza ricetta

Anonymous said...

Diversification [url=http://www.ddtshanghaiescort.com]shanghai escorts[/url] of occupation of the clod arm so that they be experiencing a comprehensive break down of uses. The Burrell Ku Kean and the organizers of

Anonymous said...

generic cialis generic cialis vente cialis prix cialis pharmacie acquistare cialis vendita cialis cialis cialis 10 mg precio

Anonymous said...

generic cialis 20 mg generic cialis online cialis generique cialis 10mg generique cialis prezzo cialis in farmacia cialis cialis venta

Anonymous said...

generic cialis generic cialis online cialis acheter cialis moins cher cialis cialis ricetta medica cialis cialis comprar espana

Anonymous said...

http://cialisnopreascriptionmg.net/ cialis no preascription
http://achatcialisgenerique20mg.net/ cialis prix
http://acquistocialisgenerico20mg.net/ cialis acquistare
http://comprarcialisgenerico20mg.net/ cialis

Anonymous said...

http://acheterviagragnerique1.net/ viagra
http://comprarviagragenerico1.net/ viagra sin receta
http://acquistareviagragenerico1.net/ costo viagra
http://kaufenvaigragenerika1.net/ bestellen viagra

Patrick Co Eban said...

Very much useful article. Kindly keep blogging

Java Training in Chennai

Java Online Training India