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;
    }    
}

Thursday, November 24, 2011

Creating your first J2EE Google App and Host in Google Apps Engine.

This is for people who just want to know how to build an app and upload to Google Apps Engine so that you dont have to worry about Server and Hosting mechanism.

If you have an J2EE WebApp and you want to host it in Google Apps Engine, here are the steps.
Assumption, you have a Google/GMAIL account.

Step 1: Go to https://appengine.google.com/ and create a new application.
If you have never used App Engine before, you might be asked to verify your mobile phone number before you can create a new app.

Step 2: Give your application a name – it should be unique and may only include lowercase alphabets and digits.
For this example, our app identifier is “amulsmmtest”. (http://amulsmmtest.appspot.com)
Application Title-> SMM Test For ATK -AMulya

Step3: http://code.google.com/appengine/downloads.html
Download appengine-java-sdk-1.6.0.zip
Unzip to a dir called D:\Downloads\appengine-java-sdk-1.6.0\appengine-java-sdk-1.6.0\

Step4:Create an J2EE WebApp having a servlet/jsp/HTML.
Step5:In the WebApp,under WEB-INF dir(where web.xml resides),create a new XML file called appengine-web.xml
<?xml version="1.0" encoding="utf-8"?>
<appengine-web-app xmlns="http://appengine.google.com/ns/1.0">
<application>amulsmmtest</application>
<version>1</version>
</appengine-web-app>


Step6:From JDeveloper, right click and deploy the War file to a directory, say D:\ATK\SMM\GoogleAppOutSideFireWall\deploy\webapp.war

Step7: Unzip this war to D:\ATK\SMM\GoogleAppOutSideFireWall\deploy\webapp

Step8:You are done now to upload the App to Google Apps Engine, to your own domain, you have created in Step2.

Step9: Go to your Command Prompt and make sure, your %JAVA_HOME%/bin is in classpath
Step10:
Execute the following Java command to upload the WebApp

D:\Downloads\appengine-java-sdk-1.6.0\appengine-java-sdk-1.6.0\bin\appcfg.cmd -p www-proxy.uk.oracle.com:80 update D:\ATK\SMM\GoogleAppOutSideFireWall\deploy\webapp


Thats it, now access the HTML page in your webapp using this URL
http://amulsmmtest.appspot.com/GoogleAppMainPage.html

Where amulsmmtest.appspot.com is your domain and GoogleAppMainPage.html is the HTML page inside your webapp's WEB-INF dir.

Thursday, November 17, 2011

Viewing SOAPMessage in console

Add -Dcom.sun.xml.ws.transport.http.client.HttpTransportPipe.dump=true

Saturday, November 12, 2011

Invoking Secured Webservice client proxy code

Few setups needed to be done in WLS domain, to enable GPA.
Securing a Webservice producer
Save the below file in name gpa.py under $MW_HOME/oracle_common/common/bin

connect('weblogic','weblogic1','t3://localhost:7101')
beginRepositorySession()
createPolicySet('default-domain-ws-DefaultDomain','ws-service','Domain("*")')
attachPolicySetPolicy('oracle/wss_saml_or_username_token_service_policy')
validatePolicySet()
commitRepositorySession()
beginRepositorySession()
createPolicySet('default-domain-ws-client-DefaultDomain','ws-client','Domain("*")')
attachPolicySetPolicy('oracle/wss10_saml_token_client_policy')
validatePolicySet()
commitRepositorySession()
beginRepositorySession()
createPolicySet('default-domain-ws-connection-DefaultDomain','ws-connection','Domain("*")')
attachPolicySetPolicy('oracle/wss10_saml_token_client_policy')
validatePolicySet()
commitRepositorySession()
beginRepositorySession()
createPolicySet('default-domain-ws-callback-DefaultDomain','ws-callback','Domain("*")')
attachPolicySetPolicy('oracle/wss10_saml_token_client_policy')
validatePolicySet()
commitRepositorySession()
beginRepositorySession()
createPolicySet('soa-domain-sca-reference-fusion_domain','sca-reference','Domain("*")')
attachPolicySetPolicy('oracle/wss10_saml_token_client_policy')
validatePolicySet()
commitRepositorySession()
beginRepositorySession()
createPolicySet('soa-domain-sca-service-fusion_domain','sca-service','Domain("*")')
attachPolicySetPolicy('oracle/wss_saml_or_username_token_service_policy')
validatePolicySet()
commitRepositorySession()


Execute this gpa.py

$MW_HOME/oracle_common/common/bin/wlst.sh gpa.py


$MW_HOME/oracle_common/common/bin/wlst.sh
connect('weblogic','weblogic1','t3://localhost:7101')
createCred(map="oracle.wsm.security", key="keystore-csf-key", user="owsm", password="welcome1", desc="Keystore key")
createCred(map="oracle.wsm.security", key="enc-csf-key", user="orakey", password="welcome1", desc="Encryption key")
createCred(map="oracle.wsm.security", key="sign-csf-key", user="orakey", password="welcome1", desc="Signing key")
createCred(map="oracle.wsm.security", key="basic.credentials", user="weblogic", password="weblogic1", desc="User")


Assumming the Webservice producer App name is "ProducerApp"

$MW_HOME/oracle_common/common/bin/wlst.sh
connect('weblogic','weblogic1','t3://localhost:7101')
grantPermission(codeBaseURL="file:${common.components.home}/modules/oracle.wsm.agent.common_11.1.1/wsm-agent-core.jar",permClass="oracle.wsm.security.WSIdentityPermission",permTarget="resource=ProducerApp",permActions="assert")


Configuration from Client Side
create the Webservice client.(OSMGateWayAMService_Service)
2)-Add the policy "policy:oracle/wss10_saml_token_client_policy" to this client.
3)-Then , they have to create the ProxyClient,i.e oSMGateWayProxy

ProducerService_Service producer_Service =
new ProducerService_Service(new URL(wsdlUrl),
new QName(producer
producer));
SecurityPolicyFeature[] securityFeature = new SecurityPolicyFeature[] { new SecurityPolicyFeature("policy:oracle/wss10_saml_token_client_policy")};
ProducerService producerServiceProxy = producer_Service.getProducerServiceHttpPort(securityFeature);

5)-If you WONT attach this Client Policy, then while invocation, you get "SAML Indentity Assertion Error".