Showing posts with label web service. Show all posts
Showing posts with label web service. Show all posts

Tuesday, November 11, 2014

How to trigger a web service from stand alone java

/*
Class EndPoint
*/

package better.faster.smarter.development;

public class EndPoint {
private String hostName="";
public void setHostName(String hostName){
this.hostName=hostName;
}
public String getHostName(){
return this.hostName;
}
}

------------------------------------------------------------------------------------------
/*
Class ExecuteWebService
*/

package better.faster.smarter.development;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.net.URL;
import java.net.URLConnection;

public class ExecuteWebService {
//soapRequest is a string which is used for executing the web service
@SuppressWarnings("deprecation")
protected static String executeWebService(String soapRequest,EndPoint endPt,String signature)
{
String responseString="";
String hostName="";
URL url=null;
URLConnection urlC=null;
DataOutputStream out =null;
DataInputStream in = null;
String str="";
try{
//Validate the endPoint
if(null==endPt)
throw new RuntimeException("Cannot proceed with executing the web service as the end point is null");
//Get the hostName
hostName=endPt.getHostName();
//Validate the endPoint here as well
if("".equalsIgnoreCase(hostName))
throw new RuntimeException("Cannot proceed with executing the web service as the end point is empty");
//Validate the soap Request
if("".equalsIgnoreCase(soapRequest))
throw new RuntimeException("Cannot proceed with executing the web service as the soap request is invalid");
//Get the header value if header is present then add SOAPHeader else trigger direct soap request
if(signature==null)
signature="";
if(!"".equalsIgnoreCase(signature))
{
soapRequest = "<SOAP:Envelope xmlns:SOAP=\"http://schemas.xmlsoap.org/soap/envelope/\">" +
"<SOAP:Header><wsse:Security xmlns:wsse=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd\">" +
                   signature + "</wsse:Security></SOAP:Header><SOAP:Body>" + soapRequest + "</SOAP:Body></SOAP:Envelope>";
}
//Both soap request and end point are valid if the control comes here
//Initialize url and also urlConnection and all the related parameters. Hard coded few of them as 
//they are rarely used in our application
url = new URL(hostName);
urlC = url.openConnection();
urlC.setRequestProperty("Content-Type", "text/xml");
urlC.setDoInput(true);
urlC.setDoOutput(true);
urlC.setUseCaches(false);
out = new DataOutputStream(urlC.getOutputStream());
out.writeBytes(soapRequest);
in = new DataInputStream(urlC.getInputStream());
responseString="";
while(null!=((str=in.readLine())))
responseString+= str+"\n";
}
catch(Exception e)
{
CustomLogger.logEntry("Exception while executing the soap request with details "+e.getMessage());
}
finally{
hostName=null;
url=null;
urlC=null;
}
return responseString;
}
}
------------------------------------------------------------------------------------
/*
Class TriggerAssertion
*/

package better.faster.smarter.development;

public class TriggerAssertion {

public static void main(String[] args) {
// TODO Auto-generated method stub
EndPoint endPt = new EndPoint();
endPt.setHostName("http://192.168.1.10/cordys/com.eibus.web.soap.Gateway.wcp?");
String userName="icici";
String userPass="icici";
String requestString =
               "<SOAP:Envelope xmlns:SOAP=\"http://schemas.xmlsoap.org/soap/envelope/\">" +
               "<SOAP:Header>" +
               "<wsse:Security xmlns:wsse=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd\">" +
               "<wsse:UsernameToken xmlns:wsse=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd\">" +
               "<wsse:Username>" + userName + "</wsse:Username>" +
               "<wsse:Password>" + userPass + "</wsse:Password>" +
               "</wsse:UsernameToken>" +
               "</wsse:Security>" +
               "</SOAP:Header>" +
               "<SOAP:Body>" +
               "<samlp:Request xmlns:samlp=\"urn:oasis:names:tc:SAML:1.0:protocol\" MajorVersion=\"1\" MinorVersion=\"1\">" +
               "<samlp:AuthenticationQuery>" +
               "<saml:Subject xmlns:saml=\"urn:oasis:names:tc:SAML:1.0:assertion\">" +
               "<saml:NameIdentifier Format=\"urn:oasis:names:tc:SAML:1.1:nameid-format:unspecified\">" + userName + "</saml:NameIdentifier>" +
               "</saml:Subject>" +
               "</samlp:AuthenticationQuery>" +
               "</samlp:Request>" +
               "</SOAP:Body>" +
               "</SOAP:Envelope>";
String responseString = ExecuteWebService.executeWebService(requestString,endPt,"");
String getUserDetails="<GetUserDetails xmlns=\"http://schemas.cordys.com/notification/workflow/1.0\"></GetUserDetails>";
String sos= "<SOAP:Envelope xmlns:SOAP=\"http://schemas.xmlsoap.org/soap/envelope/\">" +
                "<SOAP:Body>" + getUserDetails + "</SOAP:Body></SOAP:Envelope>";
int ssss = responseString.indexOf("<Signature");
        int k = responseString.indexOf("</samlp:AssertionArtifact>");
        String sigresponse = responseString.substring(ssss, k+26);
responseString=ExecuteWebService.executeWebService(getUserDetails,endPt,sigresponse);
System.out.println(responseString);
}

}


Monday, July 21, 2014

Call a web service from html using JQuery

Adding to the earlier post of mine http://learnings.joshikiran.com/2014/05/call-web-service-from-html.html I wanted to show a way to call a web service using JQuery in this post.

So the pre-requisites remains same i.e., you must know which web service you want to call (Method + Namespace) and also a gateway URL (URL to which you want to POST/GET).

The example I am trying here is executing the below SOAP request

<SOAP:Envelope xmlns:SOAP="http://schemas.xmlsoap.org/soap/envelope/">
<SOAP:Body>
<GetXMLObject xmlns="http://schemas.cordys.com/1.0/xmlstore">
<key version="">/OAuthIntegration/RedirectorContent.xml</key>
</GetXMLObject>
</SOAP:Body>
</SOAP:Envelope>

Gateway URL which I am using is : /cordys/com.eibus.web.soap.Gateway.wcp? 

(For Ppl who understand the architecture of cordys : This is a SOAP request intended to be executed under system organization context. If you want a service to be executed under any organization context you need to append the Organization dn also to the gateway)

By taking references from cordys API, I have created a wrapper on $.ajax call to call a webservice. The wrapper which i have created is something like $.joshi.ajax which is on similar lines with $.cordys.ajax

This works exactly similar way what I have explained in the similar post (request as string and posting to the gateway URL) but this using ajax calls of JQuery.

A utility js file should be as mentioned below, this utility file then be imported where ever you want to use,

<<NameOfJSFile : joshiJQuery which you can view it html page while importing>>

$.joshi = function(){
$.joshi={};
}
$.joshi.ajax = function(options){
var opts = $.extend({}, $.joshi.ajax.defaults);
opts = ajaxExtend(opts, options);
opts.url = configureGatewayUrl(opts.url, opts);
if (!opts.url) return null;
if (typeof (opts.data) === "undefined" && opts.method && opts.namespace) {
var dataStrings = [];
dataStrings.push("<SOAP:Envelope xmlns:SOAP='http://schemas.xmlsoap.org/soap/envelope/'><SOAP:Body><");
dataStrings.push(opts.method);
dataStrings.push(" xmlns='");
dataStrings.push(opts.namespace);
dataStrings.push("'>");
if (opts.parameters) {
dataStrings.push(getParameterString(opts.parameters, opts));
}
dataStrings.push("</" + opts.method + ">");
dataStrings.push("</SOAP:Body></SOAP:Envelope>");
opts.data = dataStrings.join("");
}
debugger;
return $.ajax(opts);
}
function getParameterString(parameters, settings) {
var pStrings = [];
if ($.isArray(parameters)) {
for (var i = 0, len = parameters.length; i < len; i++) {
var par = parameters[i];
pStrings.push("<" + par.name + ">");
pStrings.push((typeof (par.value) === "function" ? par.value() : par.value));
pStrings.push("</" + par.name + ">");
}
} else if (typeof (parameters) === "object") {
if ($.cordys.json) pStrings.push($.cordys.json.js2xmlstring(parameters));
else {
for (var par in parameters) {
pStrings.push("<" + par + ">");
pStrings.push((typeof (parameters[par]) === "function" ? parameters[par]() : parameters[par]));
pStrings.push("</" + par + ">");
}
}
} else if (typeof (parameters) === "function") {
if (typeof (settings.context) === "object") {
pStrings.push(parameters.call(settings.context, settings));
} else {
pStrings.push(parameters(settings));
}
} else if (typeof (parameters) === "string") {
pStrings.push(parameters);
}
return pStrings.join("");
}
function configureGatewayUrl(url, options) {
return url ? url.replace(/^http:\//, window.location.protocol + "/").replace(/\/localhost\//, "/" + window.location.host + "/") : "com.eibus.web.soap.Gateway.wcp";
}
function ajaxExtend(target, src) {
var key, deep, flatOptions = jQuery.ajaxSettings.flatOptions || {};
for (key in src) {
if (src[key] !== undefined) {
(flatOptions[key] ? target : (deep || (deep = {})))[key] = src[key];
}
}
if (deep) {
jQuery.extend(true, target, deep);
}
return target;
}
$.joshi.ajax.defaults = {
url: "",
async: true,
isMock: false,
type: "POST",
contentType: "text/xml; charset=\"utf-8\"",
dataType: "json"
} 

And finally the html which you have to write should be something similar to below

<!DOCTYPE html>
<html lang="en">
<head>
<script type="text/javascript" src="jquery-1.11.0.min.js"></script>
<script type="text/javascript" src="joshiJQuery.js"></script>
<script type="text/javascript">
function callWebService()
{
debugger;
var xmlKey="";
var xmlKey=$('#key').val();
$.joshi.ajax({
 url : "http://dhl-hyd1024/cordys/com.eibus.web.soap.Gateway.wcp",
 method :"GetXMLObject",
 namespace: "http://schemas.cordys.com/1.0/xmlstore",
 parameters : "<key version=''>"+xmlKey+"</key>",
 complete : function(data){
debugger;
$('#responseOfService').html(data.responseText.replace(/</g,"&lt;").replace(/>/g,'&gt;'));
 }
});
}
</script>
</head>
<body class='default'>
<input type="input" id="key" style="width:400px;" value="/bFOIntFrameWork/RedirectorContent.xml"/>
<input type="button" value="Fire Web Service" style="width:200px;" onclick="callWebService()"></input>
<br/><br/>
<div id="responseOfService" style="
font-family: Trebuchet ms;
font-size: 0.9em;
width: 700px;
border: 1px solid red;
">
</div>
</body>

</html>


Wednesday, May 28, 2014

Call a web service from HTML

Goal :
The goal for this post is to know how exactly we call a web service in html page (Service and HTML should be hosted in the same server).

Pre-Requisites :

  • There should be a web service which is hosted in the server. 
  • One should have knowledge on what are the parameters to be sent to call a web service or at least know how to use a SOAP UI to call a web service.
  • Basic html knowledge.
Explanation :
  • Know the web service to be called
You have to know the parameters of the web service to be called. Below are the parameters which are to be known (Assuming the web service is in the same server where the html file is being developed),
1. End point
2. SOAP Request
3. Content Type

If the above parameters are not known these can be taken from soap UI or from Fiddler as shown below

Below picture gives a brief idea on how to get End Point and SOAP Request from SOAP UI



Below picture gives information on how to get End Point, SOAP Request and Content Type from Fiddler.


There are other ways of getting these information like network tab of chrome's developer tools etc., These are just few ways of getting these information. However the goal here is to get the parameters not how do we get. Once we have this information we go ahead by writing simple html page.
  • Write a simple HTML Page
Below is the sample page how do we write it.

  • Write a function which calls a web service and display it on the browser

function soap() {
            var xmlhttp = new XMLHttpRequest();
            xmlhttp.open('POST', 'http://dhl-hyd1024/cordys/com.eibus.web.soap.Gateway.wcp?', true);
            // build SOAP request
            var sr =             
                '<SOAP:Envelope xmlns:SOAP="http://schemas.xmlsoap.org/soap/envelope/">'+
'<SOAP:Body>'+
                        '<sty:GetXMLObject xmlns:sty="http://schemas.cordys.com/1.0/xmlstore">' +
                            '<sty:key version="isv">/OAuthIntegration/RedirectorContent.xml</sty:key>' +
                        '</sty:GetXMLObject>' +
' </SOAP:Body>'+
'</SOAP:Envelope>';
xmlhttp.setRequestHeader('Content-Type', 'text/xml');
            xmlhttp.send(sr);
            xmlhttp.onreadystatechange = function () {
                if (xmlhttp.readyState == 4) {
                    if (xmlhttp.status == 200) {
document.getElementById('responseXML').innerHTML = xml_to_string(xmlhttp.responseXML);
                        alert('done use firebug to see response');
                    }
                }
            }
        }

Note : xml_to_string here is a function which is irrelevant here.

Highlighted sections are variable parameters (important variable parameters). These parameters should be replaced by the parameters what we have collected in the previous sections.

However this way of communication is not JQuery based which I would suggest to use in order to be in recent industrial terms.

Monday, February 10, 2014

One Problem of having CWS and ISVP in a single Environment

Scenario:

 This post is about the problem I have faced by having the CWS content and ISVP content only in one single environment. I have one project's CWS content and ISVP content in my local environment. Now what I did was, I have uninstalled the isvp from my local machine. The UnInstallation was successful but however both the CWS content and ISVP content in the same environment will be sharing common cordys database, while uninstalling the ISVP it removed certain content from the cordys database (Assumable its xsd related content). The process of uninstallation was successful. But now I am facing a problem from my development content. When i publish any of the newly created web service it doesn't succeed throwing the exception which is shown below,

<![CDATA[ApplicationTransaction 'com.cordys.cap.applicationconnector.Transaction' threw an exception during abort.]]></log4j:message>
<log4j:NDC><![CDATA[Running Publishing document(s)
 Publishing HealthMonitoringTool/Web Services/HealthMonitor/ESB-App/Composite/HealthMonitor.ESBApp.Composite.ESBAppCompositeWS
 Publishing HealthMonitoringTool/Web Services/HealthMonitor/ESB-App/Composite/HealthMonitor.ESBApp.Composite.ESBAppCompositeWS/ESBAppCompositeWSI
 Publishing HealthMonitoringTool/Web Services/HealthMonitor/ESB-App/Composite/HealthMonitor.ESBApp.Composite.ESBAppCompositeWS/ESBAppCompositeWSI/GetDistintOrgsFromConfiguration
 Publishing HealthMonitoringTool/Web Services/HealthMonitor/ESB-App/Composite/HealthMonitor.ESBApp.Composite.ESBAppCompositeWS/ESBAppCompositeWSI/GetDistintOrgsFromConfiguration/GetDistintOrgsFromConfigurationRealization
 Publishing HealthMonitoringTool/Ws-App Packages/HealthMonitor/HealthMonitorAppR1
 Publishing HealthMonitoringTool/Ws-App Packages/HealthMonitor/HealthMonitorAppR1/COMM_JOBRUN_WORKITEM_DETAILS.xsd
 Publishing HealthMonitoringTool/Ws-App Packages/HealthMonitor/HealthMonitorAppR1/COMM_JOBRUN_WORKITEM_DETAILS.xsd/Reference_to_00505687-00BD-11E3-E8EE-2679912CB788
 Publishing HealthMonitoringTool/Ws-App Packages/HealthMonitor/HealthMonitorAppR1/XMLSchema_Binary_Reference_WSAppServerSchema.xsd
]]

I have understood that I created a mess first by having both cws and ISVP content in one single environment and second by unInstalling isvp. I have installed the isvp again in the environment and tried publishing the newly created web service. But NO LUCK :( still I have the same issue. This issue got resolved when I restarted the cordys monitor and then tried publishing the service. 

The situation is same for any newly created web service in this scenario. Whenever I create a new web service in my local development server, in order to publish it successfully I have to restart cordys monitor and then try publishing.

Note : I could able to find the resolution, but I wasn't able to understand what exactly went wrong. People can put their thoughts on this and let me know if they have found the reason behind this by giving a clear explanation.