Tag: WebService

UserName Token In JAXWS WebService

Hi,

Jay SenSharma

Jay SenSharma

Here is a Simple demonstration of using the UserName Token in WebLogic JAXWS WebServices.

Step1). Create a Directory  “F:DELETEAuthXML_UserName_Token” where we can place all our application sources…

Step2). Now we need to create our own UserNameToken.xml file. In order to do that Please create a Directory “policies” in the current directory “F:DELETEAuthXML_UserName_Token” and place the following “UsernameToken.xml

<?xml version="1.0"?>
<wsp:Policy xmlns:wsp="http://schemas.xmlsoap.org/ws/2004/09/policy" xmlns:sp="http://docs.oasis-open.org/ws-sx/ws-securitypolicy/200512">
<sp:SupportingTokens>
<wsp:Policy>
<sp:UsernameToken sp:IncludeToken="http://docs.oasis-open.org/ws-sx/ws-securitypolicy/200512/IncludeToken/AlwaysToRecipient">
<wsp:Policy>
<sp:WssUsernameToken10/>
</wsp:Policy>
</sp:UsernameToken>
</wsp:Policy>
</sp:SupportingTokens>
</wsp:Policy>
Step3). Now In the “F:DELETEAuthXML_UserName_Token” Directory Write your WebService “SecureHelloWorldImpl.java
package examples.webservices.security_jws;
import weblogic.jws.Policies;
import weblogic.jws.Policy;
import javax.jws.WebService;
import javax.jws.WebMethod;
import javax.jws.soap.SOAPBinding;

@SOAPBinding(style=SOAPBinding.Style.DOCUMENT,use=SOAPBinding.Use.LITERAL, parameterStyle=SOAPBinding.ParameterStyle.WRAPPED)
@Policies({@Policy(uri="policy:UsernameToken.xml")})
@WebService(name="SecureHelloWorldPortType",serviceName="SecureHelloWorldService")
public class SecureHelloWorldImpl
{
@WebMethod()
public String sayHello(String s) {
return "JAXWS Service Says ... Hello " + s;
}
}
Step4). Now write the WebService Client in “F:DELETEAuthXML_UserName_Token” the Client name is “SecureHelloWorldClient.java
package client;
import examples.webservices.security_jws.client.*;
import java.util.*;
import javax.xml.ws.BindingProvider;
import weblogic.wsee.security.unt.ClientUNTCredentialProvider;
import weblogic.xml.crypto.wss.provider.CredentialProvider;
import weblogic.xml.crypto.wss.WSSecurityContext;
public class SecureHelloWorldClient {
public static void main(String[] args) throws Throwable {
String USERNAME = "weblogic";
String PASSWORD = "weblogic";
SecureHelloWorldService service=new SecureHelloWorldService();
SecureHelloWorldPortType port=service.getSecureHelloWorldPortTypePort();

//////////NOT TRY TO COMMENT OUT THE BELOW 8 Lines....Client Will Fail With Security Header Missing Exception
System.out.println("nnt-----1 Port: "+port);
BindingProvider bindingProvider = (BindingProvider) port;
Map<String,Object> rc = (Map<String,Object>)bindingProvider.getRequestContext();
List<CredentialProvider> credProviders = new ArrayList<CredentialProvider>();
credProviders.add(new ClientUNTCredentialProvider(USERNAME.getBytes(),PASSWORD.getBytes()));
rc.put(WSSecurityContext.CREDENTIAL_PROVIDER_LIST, credProviders);
rc.put(BindingProvider.USERNAME_PROPERTY, USERNAME);
rc.put(BindingProvider.PASSWORD_PROPERTY, PASSWORD);;
/////////////////////////////////////////////////////////////
String response = port.sayHello("World");
System.out.println("response = " + response);
}
}
Step 5). Now we need to write the “build.xml” so build the Service and the Client…
<project name="webservices-security_jws" default="all" basedir=".">
<!-- set global properties for this build -->
<property name="ws.file" value="SecureHelloWorldImpl" />
<property name="ear.dir" value="${basedir}/webservicesSecurityeEar" />
<property name="client.dir" value="${basedir}/webservicesSecurity_client" />
<property name="cert-dir" value="C:replicationcerts" />
<property name="wls.username" value="weblogic" />
<property name="wls.password" value="weblogic" />
<property name="wls.hostname" value="localhost" />
<property name="wls.port" value="7001" />
<property name="wls.server.name" value="AdminServer" />

<path id="client.class.path">
<pathelement path="${client.dir}"/>
<pathelement path="${java.class.path}"/>
</path>

<taskdef name="jwsc" classname="weblogic.wsee.tools.anttasks.JwscTask" />
<taskdef name="clientgen" classname="weblogic.wsee.tools.anttasks.ClientGenTask" />
<target name="all" depends="clean,server,zip,deploy,client,run" />

<!-- Cleaning the WorkSpace -->
<target name="build" depends="clean,server,client" />
<target name="clean">
<delete dir="${ear.dir}"/>
<delete dir="${client.dir}"/>
</target>

<!-- To Build the WebService -->
<target name="server">
<mkdir dir="${ear.dir}"/>
<jwsc  srcdir="${basedir}"
       destdir="${ear.dir}"
       classpath="${java.class.path}"
       fork="true"
       keepGenerated="true"
       deprecation="${deprecation}"
       debug="true">
      <jws file="${ws.file}.java"  type="JAXWS"/>
</jwsc>
</target>

<!-- To add the Policy File Inside the WebService WAR file -->
<target name="zip">
<zip destfile="${ear.dir}/${ws.file}.war" update="true">
<zipfileset dir="." prefix="WEB-INF">
<include name="policies/*.xml"/>
</zipfileset>
</zip>
</target>

<!-- Deploy Application -->
<target name="deploy">
<wldeploy action="deploy"
          source="${ear.dir}"
          user="${wls.username}"
          password="${wls.password}"
          verbose="true"
          adminurl="t3://${wls.hostname}:${wls.port}" targets="${wls.server.name}" />
</target>

<!-- Redeploy Application -->
<target name="redeploy">
<wldeploy action="redeploy"
          source="${ear.dir}"
          user="${wls.username}"
          password="${wls.password}"
          verbose="true"
          failonerror="${failondeploy}"
          adminurl="t3://${wls.hostname}:${wls.port}" targets="${wls.server.name}" />
</target>

<!-- To Generate the Client Side Artifacts -->
<target name="client">
<mkdir dir="${client.dir}"/>
<clientgen type="JAXWS"
           wsdl="http://localhost:7001/SecureHelloWorldImpl/SecureHelloWorldService?WSDL"
           destDir="${client.dir}"
           classpath="${java.class.path}"
           packageName="examples.webservices.security_jws.client"/>
<javac  srcdir="${client.dir}" destdir="${client.dir}" classpath="${java.class.path}" includes="examples/webservices/security_jws/client/**/*.java"/>
<javac srcdir="${basedir}" destdir="${client.dir}" classpath="${java.class.path};${client.dir}" includes="SecureHelloWorldClient.java"/>
</target>

<!-- To Run the Client Program -->
<target name="run" >
<java fork="true" classname="client.SecureHelloWorldClient" failonerror="false" >
     <classpath refid="client.class.path"/>
     <arg line="weblogic weblogic" />
</java>
</target>
</project>

Step6). Now open a Command prompt and then run “setWLSEnv.cmd” or “setWLSEnv.sh”  and then just enter “ant” in the command prompt…
.
.
Thanks
Jay SenSharma


How to build a WebService from a WSDL

Hi,

Jay SenSharma

Jay SenSharma

How to build a WebService from a WSDL ? Especially when it uses some Externally Located Schema.

Step 1). DownLoad the WSDL and paste it in the Current Directory. And If the WSDL is using some External XSDs then Explicitly download those XSDs in the Current Directory.

Step 2). In the downloaded WSDL Please Modify the “XSDLocation” Attribute in the Downloaded WSDL Like below….
SimpleService.WSDL

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<!-- Generated by JAX-WS RI at http://jax-ws.dev.java.net. RI's version is Oracle JAX-WS 2.1.3-07/10/2008 08:41 PM(bt). -->
<definitions targetNamespace="http://test.webservicefromWSDL/" name="SimpleService" xmlns="http://schemas.xmlsoap.org/wsdl/" xmlns:tns="http://test.webservicefromWSDL/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/">
<types>
<xsd:schema>
<xsd:import namespace="http://test.webservicefromWSDL/" schemaLocation="SimpleService_schema1.xsd"/>
</xsd:schema>
</types>
<message name="hello">
<part name="parameters" element="tns:hello"/>
</message>
<message name="helloResponse">
<part name="parameters" element="tns:helloResponse"/>
</message>
<portType name="Simple">
<operation name="hello">
<input message="tns:hello"/>
<output message="tns:helloResponse"/>
</operation>
</portType>
<binding name="SimplePortBinding" type="tns:Simple">
<soap:binding transport="http://schemas.xmlsoap.org/soap/http" style="document"/>
<operation name="hello">
<soap:operation soapAction=""/>
<input>
<soap:body use="literal"/>
</input>
<output>
<soap:body use="literal"/>
</output>
</operation>
</binding>
<service name="SimpleService">
<port name="SimplePort" binding="tns:SimplePortBinding">
<soap:address location="http://s906648/SimpleService/SimpleService"/>
</port>
</service>
</definitions>

SimpleService_schema1.xsd

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<xs:schema version="1.0" targetNamespace="http://test.webservicefromWSDL/" xmlns:tns="http://test.webservicefromWSDL/" xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xs:element name="hello" type="tns:hello"/>
<xs:element name="helloResponse" type="tns:helloResponse"/>
<xs:complexType name="hello">
<xs:sequence/>
</xs:complexType>
<xs:complexType name="helloResponse">
<xs:sequence>
<xs:element name="return" type="xs:string" minOccurs="0"/>
</xs:sequence>
</xs:complexType>
</xs:schema>

Step3). Develope the ANT “build.xml” like following:

<project name="GenerateWS" default="all">
<property name="build" value="output" />
<property name="adminurl" value="t3://localhost:7001" />
<property name="serverName" value="AdminServer" />
<property name="ear.dir" value="EJB_JAXWS_Ear" />

<taskdef name="jwsc"    classname="weblogic.wsee.tools.anttasks.JwscTask" />
<taskdef name="wsdlc" classname="weblogic.wsee.tools.anttasks.WsdlcTask"/>
<target name="all" depends="generate-from-wsdl"/>

<target name="generate-from-wsdl">
      <wsdlc  srcWsdl="SimpleService.wsdl"
              destJwsDir="jarJws"
              destImplDir="."
              packageName="ws"
              type="JAXWS"/>
</target>

<target name="build-service">
<jwsc srcdir="." destdir="output/EJB_WS_Ear">
    <jws file="ws/SimpleService_SimplePortImpl.java"
         compiledWsdl="jarJws/SimpleService_wsdl.jar" />
    </jwsc>
</target>

<target name="deploy" depends="build-service">
<wldeploy action="deploy" source="output/EJB_WS_Ear"
          user="weblogic" password="weblogic" verbose="true"
          failonerror="yes" adminurl="${adminurl}"
          targets="${serverName}" />
</target>

<target name="redeploy">
<wldeploy action="redeploy" source="output/EJB_WS_Ear"
          user="weblogic" password="weblogic" verbose="true"
          failonerror="true" adminurl="${adminurl}"
          targets="${serverName}" />
</target>
</project>

Step4). Run the Ant Task —“generate-from-wsdl”  (before this you need to run the setDomainEnv.sh or setWLSEnv.cmd).
C:DELETEWSDLC_TO_Service>ant generate-from-wsdl

Output:
Buildfile: build.xml

generate-from-wsdl:
[wsdlc] Download file [SimpleService_schema1.xsd] to C:DOCUME~1JAYKUM~1LOCALS~1Temp_ckr59b
[wsdlc] Download file [SimpleService.wsdl] to C:DOCUME~1JAYKUM~1LOCALS~1Temp_ckr59b
[wsdlc] srcWsdl is redefined as [ C:DOCUME~1JAYKUM~1LOCALS~1Temp_ckr59bSimpleService.wsdl ]
[wsdlc] Consider using <depends>/<produces> so that wsimport won’t do unnecessary compilation
[wsdlc] parsing WSDL…

[wsdlc] generating code…

[wsdlc] compiling code…

[wsdlc] Note: C:DELETEWSDLC_TO_ServicejarJwsgeneratedwsSimpleService.java uses unchecked or unsafe operations.

[wsdlc] Note: Recompile with -Xlint:unchecked for details.
[AntUtil.deleteDir] Deleting directory C:DOCUME~1JAYKUM~1LOCALS~1Temp_ckr59b

BUILD SUCCESSFUL
Total time: 2 seconds
C:DELETEWSDLC_TO_Service>
——————-

Step5). Above execution will generate two Directories in the Current Directory “ws” and “jarJws”.
You will find that a WebService class “SimpleService_SimplePortImpl.java” is generated inside the “ws” directory like following.

package ws;
import javax.jws.WebService;
import javax.xml.ws.BindingType;
/**
* This class was generated by the JAX-WS RI.
* Oracle JAX-WS 2.1.3-06/19/2008 07:03 PM(bt)
* Generated source version: 2.1
*
*/
@WebService(portName = "SimplePort", serviceName = "SimpleService", targetNamespace = "http://test.webservicefromWSDL/", wsdlLocation = "/wsdls/SimpleService.wsdl", endpointInterface = "ws.Simple")
@BindingType("http://schemas.xmlsoap.org/wsdl/soap/http")
public class SimpleService_SimplePortImpl
implements Simple
{
public SimpleService_SimplePortImpl() {
}

/**
*
* @return
*     returns java.lang.String
*/
public String hello() {
//replace with your impl here
return null;
}

}

Modify the "wsSimpleService_SimplePortImpl.java" and
Provide the implementation to the String hello() method according to your requirement...

Example:
public String hello() {
System.out.println("nnt Hello Mr...Jack..."+new java.util.Date());
return "nnt Hello Mr...Jack..."+new java.util.Date();
}

Step6). Now run the ANT task “deploy” it will build your WebService using JWSC and then It will deploy it:
OUTPUT:

C:DELETEWSDLC_TO_Service>ant deploy
Buildfile: build.xml

build-service:
[jwsc] JWS: processing module /ws/SimpleService_SimplePortImpl
[jwsc] Parsing source files
[jwsc] Parsing source files
[jwsc] 1 JWS files being processed for module /ws/SimpleService_SimplePortImpl
[jwsc] JWS: C:DELETEWSDLC_TO_ServicewsSimpleService_SimplePortImpl.java Validated.
[jwsc] <WSEE:1>URIs = []<TylarBindingsBuilderBase.getTylarUris:52>
[jwsc] Dependent class ws.Simple was not found in the classpath or sourcpath.
[jwsc] Compiling 8 source files to C:DOCUME~1JAYKUM~1LOCALS~1Temp_lt0r03
[jwsc] Note: C:Documents and SettingsjaykumarsLocal SettingsTemp_lt0r03wsSimpleService.java uses unchecked or unsafe operations.

[jwsc] Note: Recompile with -Xlint:unchecked for details.
[jwsc] Deleting existing module outputFile C:DELETEWSDLC_TO_ServiceoutputEJB_WS_EarwsSimpleService_SimplePortImpl.war
[jwsc] Unable to delete module outputFile C:DELETEWSDLC_TO_ServiceoutputEJB_WS_EarwsSimpleService_SimplePortImpl.war
[jwsc] Building jar: C:DELETEWSDLC_TO_ServiceoutputEJB_WS_EarwsSimpleService_SimplePortImpl.war
[jwsc] Created JWS deployment outputFile: C:DELETEWSDLC_TO_ServiceoutputEJB_WS_EarwsSimpleService_SimplePortImpl.war
[jwsc] [EarFile] Application File : C:DELETEWSDLC_TO_ServiceoutputEJB_WS_EarMETA-INFapplication.xml
[AntUtil.deleteDir] Deleting directory C:DOCUME~1JAYKUM~1LOCALS~1Temp_lt0r03

deploy:
[wldeploy] weblogic.Deployer -verbose -noexit -source C:DELETEWSDLC_TO_ServiceoutputEJB_WS_Ear -targets AdminServer -adminurl t3://loca
lhost:7001 -user weblogic -password ******** -deploy
[wldeploy] weblogic.Deployer invoked with options:  -verbose -noexit -source C:DELETEWSDLC_TO_ServiceoutputEJB_WS_Ear -targets AdminSer
ver -adminurl t3://localhost:7001 -user weblogic -deploy
[wldeploy] <Dec 18, 2009 4:32:49 PM IST> <Info> <J2EE Deployment SPI> <BEA-260121> <Initiating deploy operation for application, EJB_WS_Ear
[archive: C:DELETEWSDLC_TO_ServiceoutputEJB_WS_Ear], to AdminServer .>
[wldeploy] Task 1 initiated: [Deployer:149026]deploy application EJB_WS_Ear on AdminServer.
[wldeploy] Task 1 completed: [Deployer:149026]deploy application EJB_WS_Ear on AdminServer.
[wldeploy] Target state: deploy completed on Server AdminServer
[wldeploy]
[wldeploy] Target Assignments:
[wldeploy] + EJB_WS_Ear  AdminServer

BUILD SUCCESSFUL
Total time: 5 seconds
C:DELETEWSDLC_TO_Service>

Step 7). Test Your WebService using WebLogic TestClient through AdminConsole.
Thanks

Jay SenSharma


Fetching HttpHeaders inside JAXWS WebService

Hi,

Jay SenSharma

Jay SenSharma

If we want to display the HttpHeaders (NOT SOAPHeaders) inside our JAXWS webservice then we need to use   “javax.xml.ws.WebServiceContext” class provided as part of JAXWS APIs. Here is a Sample on How to use this API.

Step 1). Create a “src” directory inside Some Folder like: “C:JavaTestJAXWS_ClientHttpHeaders_ClientIP”

Step 2). Develope the WebService class “HelloWorldImpl.java” inside the “C:JavaTestJAXWS_ClientHttpHeaders_ClientIPsrcexampleswebserviceshello_world” Directory.

package examples.webservices.hello_world;
import javax.jws.*;
import javax.xml.ws.WebServiceContext;
import javax.annotation.Resource;
import javax.xml.ws.handler.MessageContext;
import java.util.*;
import javax.servlet.http.*;
import javax.xml.ws.handler.soap.*;

@WebService
public class HelloWorldImpl
{
@Resource
WebServiceContext wsCtxt;
@WebMethod
public String getClientIP()
{
MessageContext msgCtxt = wsCtxt.getMessageContext();
HttpServletRequest req = (HttpServletRequest)msgCtxt.get(MessageContext.SERVLET_REQUEST);
String clientIP = req.getRemoteAddr();
System.out.println("nnttClient's IP Address is : "+clientIP);
return "nt Your IP Address is : "+clientIP;
}
@WebMethod
public String sayHelloWorld(String message)
{
System.out.println("sayHelloWorld:" + message);
return "Here is the message: '" + message + "'";
}

@WebMethod
public String getHttpHeaders()
{
MessageContext context=wsCtxt.getMessageContext();
System.out.println("nnt Got MessageContext context = "+context);
Map map = (Map)context.get(MessageContext.HTTP_REQUEST_HEADERS);
String str="";

Set entries = map.entrySet();
Iterator iterator = entries.iterator();
while (iterator.hasNext())
{
Map.Entry entry = (Map.Entry)iterator.next();
str=str+"nHeader:" + entry.getKey() + " tValue: " + entry.getValue();
System.out.println("ntHeader:" + entry.getKey() + " : " + entry.getValue());
}

System.out.println("nnttClient's HTTP Headers are : "+str);
return "nt Your HTTP Headers are : "+str;
}
}

Step3). Provide the ANT “build.xml” file inside the “C:JavaTestJAXWS_ClientHttpHeaders_ClientIP”. Step4). Open a Command/Shell window and run the “setDomainEnv.sh/cmd” or “setWLSEnv.sh/cmd”.

Step4). Run the ANT…

Step5). Login to AdminConsole and Click on Test Client Page of deployed WebService…Execute the Method “getHttpHeaders” you will find the following SOAPResoponse:

<S:Envelope xmlns:S="http://schemas.xmlsoap.org/soap/envelope/">
<S:Body>
<ns2:getHttpHeadersResponse xmlns:ns2="http://hello_world.webservices.examples/">
<return>Your HTTP Headers are :
Header:Cookie Value: [PreviousWsdl1261036687257=VHJhbnNhY3Rpb25hbEltcGxTZXJ2aWNlfGh0dHA6Ly9sb2NhbGhvc3Q6NzAwMS9UcmFuc2FjdGlvbmFsSW1wbC9UcmFuc2FjdGlvbmFsSW1wbD9XU0RM; PreviousWsdl1261038900211=SGVsbG9Xb3JsZEltcGxTZXJ2aWNlfGh0dHA6Ly9sb2NhbGhvc3Q6NzAwMS9IZWxsb1dvcmxkSW1wbC9IZWxsb1dvcmxkSW1wbFNlcnZpY2U/V1NETA==; ADMINCONSOLESESSION=lNnpLqLNtCsxKGJFQhN517hmQ6c81lDYPF2QryGdcVbPzJfBLqct!-1472209373; JSESSIONID=LyG0LqLL849T3f2k4vLy2XlXKb3yWCDvy1P0XpVQtTvgyyTfLv9v!-1472209373]
Header:Host Value: [localhost:7001]
Header:Content-type Value: 
Header:Content-length Value: [183]
Header:Connection Value: [Keep-Alive]
Header:User-agent Value: [BEA WebLogic Server 10.3.0.0]
Header:Accept Value: 
Header:Soapaction Value: [""]</return>
</ns2:getHttpHeadersResponse>
</S:Body>
</S:Envelope>

.

.

Thanks

Jay SenSharma


Copyright © 2010-2012 Middleware Magic. All rights reserved. |