Amazon

Sunday, May 18, 2014

AXIS 2 - Client and Password Call Back Handler - For a secured (using Rampart) webservice


Password Call Back Handler - This class is invoked by container when the webservice receives a secured  request.

package crishantha.rampart;

import java.io.IOException;

import javax.security.auth.callback.Callback;
import javax.security.auth.callback.CallbackHandler;
import javax.security.auth.callback.UnsupportedCallbackException;

import org.apache.ws.security.WSPasswordCallback;

public class PWCBHandler implements CallbackHandler {

public void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException {
System.out.println("handle->(Callback[]:"+ callbacks);
for (int i = 0; i < callbacks.length; i++) {
System.out.println("(Callback["+i+"]:"+ callbacks[i]);
//When the server side need to authenticate the user
WSPasswordCallback pwcb = (WSPasswordCallback)callbacks[i];

System.out.println("pwcb.getIdentifier()->"+pwcb.getIdentifier());
System.out.println("pwcb.getPassword()->"+pwcb.getPassword());


if(pwcb.getIdentifier().equals("apache") /*&& pwcb.getPassword().equals("password")*/) {
//If authentication successful, simply return
pwcb.setPassword("password"); // this value should be same as password supplied in SOAP Envelop.
//See the client program below for password
System.out.println("user authenticated->"+pwcb.getIdentifier());

return;
} else {
throw new UnsupportedCallbackException(callbacks[i], "check failed");
}
}
}
}

Tag in services.xml (http://java-application-programming.blogspot.in/2014/05/axis2-servicesxml-engaging-rampart.html) need to be embed in services.xml for integrating Password Call Back Handler.


Client Program to call secured webservice


package ramp.client;

import org.apache.axis2.client.Options;
import org.apache.axis2.client.ServiceClient;
import org.apache.axis2.context.ConfigurationContext;
import org.apache.axis2.context.ConfigurationContextFactory;


public class Client {
public static void main(String[] args)throws Exception {

System.setProperty("javax.net.ssl.trustStore", "D:\\apache-tomcat-7.0.53\\bin\\sslkey\\sslkey.jks");
System.setProperty("javax.net.ssl.trustStorePassword", "password");


ConfigurationContext ctx = ConfigurationContextFactory.createConfigurationContextFromFileSystem("D:\\AXIS2_DUMP\\axis2-1.6.2\\repository", null);
System.out.println("0->"+ctx.getContextRoot());

TemperatureConversionServiceStub stub =  new TemperatureConversionServiceStub(ctx, "https://localhost:8443/ram/services/TemperatureConversionService");
System.out.println("1->"+stub);

ServiceClient sc = stub._getServiceClient();
System.out.println("1.1->"+sc);
sc.engageModule("rampart");
System.out.println("1.2->"+sc);
Options options = sc.getOptions();
System.out.println("1.3->"+options);
options.setUserName("apache");

options.setPassword("password");
System.out.println("1.4->"+options.getPassword());

TemperatureConversionServiceStub.Celcius2Farenhit celc = new TemperatureConversionServiceStub.Celcius2Farenhit();
System.out.println("2->"+celc);
celc.setCelcius(10f);
System.out.println("3->"+celc);
TemperatureConversionServiceStub.Celcius2FarenhitResponse cfr = stub.celcius2Farenhit(celc);
System.out.println("4->"+cfr);
float f = cfr.get_return();
System.out.println("5. result->"+f);

}

}


SOAP Envelop sent by client program:





<?xml version='1.0' encoding='utf-8'?>
<soapenv:Envelope xmlns:soapenv="http://www.w3.org/2003/05/soap-envelope">
<soapenv:Header>
<wsse:Security
xmlns:wsse="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd"
xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd"
soapenv:mustUnderstand="true">
<wsu:Timestamp wsu:Id="TS-1">
<wsu:Created>2014-05-18T12:13:15.063Z</wsu:Created>
<wsu:Expires>2014-05-18T12:18:15.063Z</wsu:Expires>
</wsu:Timestamp>
<wsse:UsernameToken wsu:Id="UsernameToken-2">
<wsse:Username>apache</wsse:Username>
<wsse:Password
Type="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordText">password</wsse:Password>
</wsse:UsernameToken>
</wsse:Security>
</soapenv:Header>
<soapenv:Body>
<ns1:celcius2farenhit xmlns:ns1="http://www.polarisft.com/iph/ws/portalService/">
<ns1:celcius>10.0</ns1:celcius>
</ns1:celcius2farenhit>
</soapenv:Body>
</soapenv:Envelope>

Saturday, May 17, 2014

AXIS 2 - SOAP Webservice - Adding Security layer to webservice using Rampart

Tools and Libraries used 

  1. apache-tomcat-7.0.53
  2. axis2-1.6.2
  3. rampart-1.6.2
  4. jdk 1.6
Exploring ram.war - The war file name is ram.war. The directory structure of the war file is below.

D:\APACHE-TOMCAT-7.0.53\WEBAPPS\RAM
├───META-INF
└───WEB-INF
    ├───classes
    │   ├───com
    │   │   └───polaris
    │   │       └───iph
    │   │           └───ws
    │   └───crishantha
    │       └───rampart
    ├───conf
    ├───lib
    ├───modules
    └───services
        └───TemperatureConversionService
            └───META-INF

Below folders contain classes for webservice.
- classes/com.polaris.iph.ws 
- classes/crishantha.rampart

Integrating rampart with Axis 2 webservice
WEB-INF/conf - contains axis2.xml
WEB-INF/lib - contains all jars from  Axis2_HOME/lib/ and RAMPART_HOME/lib directory. 

Very important Note 
- The version of Axis2 and Rampart should be same. I faced issues because previously I was using axis2-1.6.2 and rampart-1.3.2. Then I changed the version of rampart to rampart-1.6.2 and it worked. This is very important point.
- The axis2 libs should not be mixed with various versions of other libs of Rampart and other extensions. It creates compatibility issues.

WEB-INF/modules - copy rahas-1.6.2.mar and rampart-1.6.2.mar files from  rampart-1.6.2\modules folder  in  WEB-INF/modules folder.

Declare webservice and engaging Rampart 

Adding Webservice in WAR file  and engaging Rampart with Axis2. Follow this link to see the META-INF/services/TemperatureConversionService/META-INF/services.xml.
http://java-application-programming.blogspot.in/2014/05/axis2-servicesxml-engaging-rampart.html

Making server ready for HTTPS
Creating SSL Key to make tomcat server HTTPS /SSL Enabled. Execute below command from Tomcat_home\bin folder
keytool -genkey -alias tomcat -keyalg RSA -keystore  c:\sslkey\sslkey.jks

c:\sslkey\sslkey.jks will be created with the key. This key will be used to enable SSL.

Open the server.xml of tomcat from TOMCAT_HOME\conf\server.xml and enable /change/add below lines  around tags.

     <Connector port="8443" protocol="HTTP/1.1" SSLEnabled="true"
               maxThreads="150" scheme="https" secure="true"
               clientAuth="false" sslProtocol="TLS"
      keystoreFile="C:\sslkey\sslkey.jks"
      keystorePass="password" />
     
Note: keystorePass="password", "password" value is entered while creating sslkey.jks using keytool (see few lines above)

Open WEB-INF/conf/axis2.xml and add below lines below tag  <transportReceiver>
 
<transportReceiver name="https" class="org.apache.axis2.transport.http.AxisServletListener">

<parameter name="port">8443</parameter>
</transportReceiver>
Note : The port in axis2.xml and server.xml should be same, here its kept 8443.

Generating Client Code - Stub to call this service.

Save the WSDL  -TemperatureConversionService.xml
Execute below command


D:\AXIS2_DUMP\axis2-1.6.2\bin\clientcode>..\WSDL2Java.bat -uri D:\2010SANT\27_0_0\WS-POC\RAMPART\WebContent\WEB-INF\wsdl\TemperatureConversionService.xml -p ramp.client -d adb -s


NOTE: Get the jar from http://repo1.maven.org/maven2/org/apache/axis2/axis2-adb-codegen/1.6.2/axis2-adb-codegen-1.6.2.jar, before executing above command of WSDL2Java.bat. Issues will come without this jar.

Follow below link to develop Webservice Client for secured Webservice
 http://java-application-programming.blogspot.in/2014/05/axis-2-client-and-password-call-back.html

AXIS 2 - services.xml - engaging rampart


<serviceGroup>
<service name="TemperatureConversionService" targetNamespace="http://www.polarisft.com/iph/ws/">

<module ref="rampart" /> <!-- Engaging Rampart -->
<description>
This service is to get the running Axis version
</description>
<schema schemaNamespace="http://www.polarisft.com/iph/ws/portalService/" />
<parameter name="ServiceClass">crishantha.rampart.TemperatureConversionService
</parameter>
<operation name="celcius2farenhit">
<messageReceiver class="org.apache.axis2.rpc.receivers.RPCMessageReceiver" />
</operation>
<operation name="farenhit2celcius">
<messageReceiver class="org.apache.axis2.rpc.receivers.RPCMessageReceiver" />
</operation>

<!-- Rampart specific tags  - start -->
<wsp:Policy wsu:Id="UsernameTokenOverHTTPS"
xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd"
xmlns:wsp="http://schemas.xmlsoap.org/ws/2004/09/policy">
<wsp:ExactlyOne>
<wsp:All>
<sp:TransportBinding
xmlns:sp="http://schemas.xmlsoap.org/ws/2005/07/securitypolicy">
<wsp:Policy>
<sp:TransportToken>
<wsp:Policy>
<sp:HttpsToken RequireClientCertificate="false" />
</wsp:Policy>
</sp:TransportToken>
<sp:AlgorithmSuite>
<wsp:Policy>
<sp:Basic256 />
</wsp:Policy>
</sp:AlgorithmSuite>
<sp:Layout>
<wsp:Policy>
<sp:Lax />
</wsp:Policy>
</sp:Layout>
<sp:IncludeTimestamp />
</wsp:Policy>
</sp:TransportBinding>
<sp:SignedSupportingTokens
xmlns:sp="http://schemas.xmlsoap.org/ws/2005/07/securitypolicy">
<wsp:Policy>
<sp:UsernameToken
sp:IncludeToken="http://schemas.xmlsoap.org/ws/2005/07/securitypolicy/IncludeToken/AlwaysToRecipient" />
</wsp:Policy>
</sp:SignedSupportingTokens>
<ramp:RampartConfig xmlns:ramp="http://ws.apache.org/rampart/policy">
<ramp:passwordCallbackClass>crishantha.rampart.PWCBHandler</ramp:passwordCallbackClass> <!-- crishantha.rampart.PWCBHandler is user defined class to handle user name password -->
</ramp:RampartConfig>
</wsp:All>
</wsp:ExactlyOne>
</wsp:Policy>
<!-- Rampart specific tags  - End-->
</service>
</serviceGroup>

Thursday, May 1, 2014

SOAP Webservice - JAX-WS

Topics

  1. Create a sample SOAP Webservice using JAX-WS
  2. Deploy in Tomcat 7.0
  3. Invoke WSDL
  4. Create Client
  5. Use Client to invoke Webservice

  1. Create a sample SOAP Webservice using JAX-WS
    1. Create a dynamic Web Project in Eclipse
    2. Create Service Endpoint Interface (SEI) HelloWorld 
    3. Create Service Inplementation Bean (SIB), HelloWorldImpl which implement SEI.
    4. Change web.xml, add entries if Servlet giving service to Webservice HelloWorldImpl 
    5. Add sun-jaxws.xml in WEB-INF folder. This file will publish and start the webservice runtime in Tomcat.
  2. Deploy in Tomcat 7.0
    1. Add a new server in Eclipse, pointing to Tomcat 7 installation directory.
    2. Add below jars in WEB-INF/lib folder
      1. gmbal-api-only.jar
      2. ha-api.jar
      3. jaxb-api.jar
      4. jaxb-impl-2.2.6.jar
      5. jaxb-impl.jar
      6. jaxws-rt.jar
      7. management-api.jar
      8. policy.jar
      9. stax-ex.jar
      10. streambuffer.jar
    3. Add the webservice project (created in 1) in server.
    4. Start the server.
  3. Invoke WSDL
    1. http://localhost:8080/SOAP_JAX/hello?wsdl
  4. Create Client
    1. Create a new java project in eclipse.
    2. Go to src directory in doc command prompt.
    3. Invoke command "wsimport -keep -verbose http://localhost:8080/SOAP_JAX/hello?wsdl"
    4. Two classes will be created in src folder. These are stubs to invoke webservice. 
    5. Write the client file using the stubs created in 4 above.
  5. Invoke main method to access webservice.

HelloWorld.java (SEI)

package com.ws.soap.jaxws.sanjeev;

import javax.jws.WebMethod;
import javax.jws.WebResult;
import javax.jws.WebService;
import javax.jws.soap.SOAPBinding;

/**
 * This class was generated by the JAX-WS RI.
 * JAX-WS RI 2.2.4-b01
 * Generated source version: 2.2
 * 
 */
@WebService(name = "HelloWorld", targetNamespace = "http://com.soap.sanjeev/")
@SOAPBinding(style = SOAPBinding.Style.RPC)
public interface HelloWorld {

    /**
     * 
     * @return
     *     returns java.lang.String
     */
    @WebMethod
    @WebResult(partName = "return")
    public String getHelloWorldAsString();

}


HelloWorldImpl.java (SIB)

package com.ws.soap.jaxws.sanjeev;

import javax.jws.WebService;

@WebService(endpointInterface = "com.ws.soap.jaxws.sanjeev.HelloWorld")
public class HelloWorldImpl implements HelloWorld {
@Override
public String getHelloWorldAsString() {
// TODO Auto-generated method stub
return "hello world";
}
}

WEB-INF/sun-jaxws.xml  - will publish the webservice and start the webservice runtime

<?xml version="1.0" encoding="UTF-8"?>
<endpoints xmlns="http://java.sun.com/xml/ns/jax-ws/ri/runtime"
version="2.0">
<endpoint name="HelloWorld" implementation="com.ws.soap.jaxws.sanjeev.HelloWorldImpl"
url-pattern="/hello" />

</endpoints>

WEB-INF/web.xml - setup servlet and url for webservice
<?xml version="1.0" encoding="UTF-8"?>

<web-app
xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
   http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"
version="2.4">

<display-name>Archetype Created Web Application</display-name>

<listener>
<listener-class>
com.sun.xml.ws.transport.http.servlet.WSServletContextListener
</listener-class>
</listener>
<servlet>
<servlet-name>hello</servlet-name>
<servlet-class>
com.sun.xml.ws.transport.http.servlet.WSServlet
</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>hello</servlet-name>
<url-pattern>/hello</url-pattern>  <!-- service the webservice -->
</servlet-mapping>

</web-app>


WSDL File


<?xml version="1.0" encoding="UTF-8"?><!-- Published by JAX-WS RI at http://jax-ws.dev.java.net. RI's version is JAX-WS RI 2.2.8 svn-revision#13980. --><!-- Generated by JAX-WS RI at http://jax-ws.dev.java.net. RI's version is JAX-WS RI 2.2.8 svn-revision#13980. --><definitions xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd" xmlns:wsp="http://www.w3.org/ns/ws-policy" xmlns:wsp1_2="http://schemas.xmlsoap.org/ws/2004/09/policy" xmlns:wsam="http://www.w3.org/2007/05/addressing/metadata" xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/" xmlns:tns="http://sanjeev.jaxws.soap.ws.com/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="http://schemas.xmlsoap.org/wsdl/" targetNamespace="http://sanjeev.jaxws.soap.ws.com/" name="HelloWorldImplService">
<import namespace="http://com.soap.sanjeev/" location="http://localhost:8080/SOAP_JAX/hello?wsdl=1"></import>
<binding xmlns:ns1="http://com.soap.sanjeev/" name="HelloWorldImplPortBinding" type="ns1:HelloWorld">
<soap:binding transport="http://schemas.xmlsoap.org/soap/http" style="rpc"></soap:binding>
<operation name="getHelloWorldAsString">
<soap:operation soapAction=""></soap:operation>
<input>
<soap:body use="literal" namespace="http://com.soap.sanjeev/"></soap:body>
</input>
<output>
<soap:body use="literal" namespace="http://com.soap.sanjeev/"></soap:body>
</output>
</operation>
</binding>
<service name="HelloWorldImplService">
<port name="HelloWorldImplPort" binding="tns:HelloWorldImplPortBinding">
<soap:address location="http://localhost:8080/SOAP_JAX/hello"></soap:address>
</port>
</service>

</definitions>



HelloClient.java   -  Webservice Client 

package com.client.soap.jaxws.sanjeev;

import javax.xml.ws.WebServiceRef;

import com.ws.soap.jaxws.sanjeev.HelloWorld;
import com.ws.soap.jaxws.sanjeev.HelloWorldImplService;

public class HelloClient {
    @WebServiceRef(wsdlLocation="http://localhost:8080/SOAP_JAX/hello?wsdl")
    static HelloWorldImplService service;

    public static void main(String[] args) {
        try {
            HelloClient client = new HelloClient();
            client.doTest(args);
        } catch(Exception e) {
            e.printStackTrace();
        }
    }

    public void doTest(String[] args) {
        try {
   service = new HelloWorldImplService();        
       
            System.out.println("Retrieving the port from    the following service: " + service);
            HelloWorld port = service.getHelloWorldImplPort();
            System.out.println("Invoking the sayHello operation                 on the port.");

            String name;
            if (args.length > 0) {
                name = args[0];
            } else {
                name = "No Name";
            }

            String response = port.getHelloWorldAsString();
            System.out.println(response);
        } catch(Exception e) {
            e.printStackTrace();
        }
    }

}

Amazon Best Sellors

TOGAF 9.2 - STUDY [ The Open Group Architecture Framework ] - Chap 01 - Introduction

100 Feet View of TOGAF  What is Enterprise? Collection of Organization that has common set of Goals. Enterprise has People - organized by co...