Tuesday, August 16, 2011

JAX-WS send custom SOAP headers and Set endpoint

String endPointURL=”<ws_service_endpoint_url>”;
String userName=”uname”; //custom header for ws security
String password=”password”; //custom header for ws security
String systemId=”system_id”; //custom header to call WS
String correlationId=”corr_id”; //custom header to call ws
                 
//adding handler to add custom soap header
RetailAccountService serviceLocator=new RetailAccountService();
HeaderHandlerResolver handlerResolver = new HeaderHandlerResolver(userName,password,systemId,correlationId);
serviceLocator.setHandlerResolver(handlerResolver);
                 
//setting webservice endpoint
PncEnterpriseOffersV1RetailInterfacesPortType oppService=serviceLocator.getPncEnterpriseOffersV1RetailInterfacesPort();
BindingProvider bp = (BindingProvider)oppService;          bp.getRequestContext().put(BindingProvider.ENDPOINT_ADDRESS_PROPERTY, endPointURL);
GetOpportunitiesByUserType oppUser=new GetOpportunitiesByUserType();
oppUser.setUser(userId);
GetOpportunitiesByUserResponseType oppRes=oppService.getOpportunitiesByUser(oppUser);






import java.util.ArrayList;
import java.util.List;

import javax.xml.ws.handler.Handler;
import javax.xml.ws.handler.HandlerResolver;
import javax.xml.ws.handler.PortInfo;

public class HeaderHandlerResolver implements HandlerResolver {
      private String userName;
      private String password;
      private String systemId;
      private String correlationId;

      public HeaderHandlerResolver(String userName, String password,
                  String systemId, String correlationId) {
            super();
            this.userName = userName;
            this.password = password;
            this.systemId = systemId;
            this.correlationId = correlationId;
      }

      public List<Handler> getHandlerChain(PortInfo portInfo) {
            List<Handler> handlerChain = new ArrayList<Handler>();
            HeaderHandler hh = new HeaderHandler(userName, password, systemId,
                        correlationId);
            handlerChain.add(hh);
            return handlerChain;
      }
}



import java.io.ByteArrayOutputStream;
import java.util.Set;

import javax.xml.soap.SOAPElement;
import javax.xml.soap.SOAPEnvelope;
import javax.xml.soap.SOAPHeader;
import javax.xml.soap.SOAPMessage;
import javax.xml.ws.handler.MessageContext;
import javax.xml.ws.handler.soap.SOAPHandler;
import javax.xml.ws.handler.soap.SOAPMessageContext;

import org.apache.log4j.Logger;

public class HeaderHandler implements SOAPHandler<SOAPMessageContext> {
      private static Logger log = Logger.getLogger(HeaderHandler.class);
      private String userName;
      private String password;
      private String systemId;
      private String correlationId;

      public HeaderHandler(String userName, String password, String systemId, String correlationId) {
            super();
            this.userName = userName;
            this.password = password;
            this.systemId = systemId;
            this.correlationId = correlationId;
      }

      public boolean handleMessage(SOAPMessageContext smc) {
            // constructing custom soap header
            Boolean outboundProperty = (Boolean) smc.get(MessageContext.MESSAGE_OUTBOUND_PROPERTY);

            if (outboundProperty.booleanValue()) {
                  SOAPMessage message = smc.getMessage();
                  try {
                        SOAPEnvelope envelope = smc.getMessage().getSOAPPart().getEnvelope();
                        SOAPHeader header = envelope.addHeader();

                        SOAPElement securityEle = header.addChildElement("Security", "wsse", "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd");
                        SOAPElement usernameTokenEle = securityEle.addChildElement("UsernameToken", "wsse");
                        SOAPElement usernameEle = usernameTokenEle.addChildElement("Username", "wsse");
                        usernameEle.addTextNode(userName);
                        SOAPElement passwordEle = usernameTokenEle.addChildElement("Password", "wsse");
                        passwordEle.setAttribute("Type", "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordText");
                        passwordEle.addTextNode(password);

                        SOAPElement systemContextEle = header.addChildElement("systemContext", "urn", "urn:pnc.common.utils.v1.context");
                        SOAPElement systemIdEle = systemContextEle.addChildElement("systemId");
                        systemIdEle.addTextNode(systemId);
                        SOAPElement correlationIdEle = systemContextEle.addChildElement("correlationId");
                        correlationIdEle.addTextNode(correlationId);

                        // Print out the outbound SOAP message to log
                        ByteArrayOutputStream soapReq = new ByteArrayOutputStream();
                        message.writeTo(soapReq);
                        log.debug("SOAP Request for Operation getOpportunitiesByUser " + new String(soapReq.toByteArray()));
                        soapReq.close();
                  } catch (Exception e) {
                        log.error(e.getMessage(), e);
                  }
            } else {
                  try {
                        // This handler does nothing with the response from the Web
                        // Service so we just log the SOAP message.
                        SOAPMessage message = smc.getMessage();
                        ByteArrayOutputStream soapRes = new ByteArrayOutputStream();
                        message.writeTo(soapRes);
                        log.debug("SOAP Response for Operation getOpportunitiesByUser " + new String(soapRes.toByteArray()));
                        soapRes.close();
                  } catch (Exception e) {
                        log.error(e.getMessage(), e);
                  }
            }

            return outboundProperty;
      }

      public Set getHeaders() {
            // throw new UnsupportedOperationException("Not supported yet.");
            return null;
      }

      public boolean handleFault(SOAPMessageContext context) {
            // throw new UnsupportedOperationException("Not supported yet.");
            return true;
      }

      public void close(MessageContext context) {
            // throw new UnsupportedOperationException("Not supported yet.");
      }
}

Saturday, August 6, 2011

JAX-RPC properties to send, receive SOAP headers and Consume web service in Portlet


To consume webservice in Portlet :

1)      Create a separate java project and paste wsdl file src folder
2)      Right click on wsdl file and select “web service” then “generate client” option
3)      Select “Client type” as “Java Proxy”. Select “Web service runtime” as “Jax-rpc”
4)      Set level of client generation to “Deploy Client” so that ServiceLocator and ProxyType will get generated automatically
5)      Once client code is generated, set this java project in build path of portlet project to resolve the ws generated classes at compile time also make this project available in runtime. In rad upto 7.5 use “j2ee module dependency” for radv8.0 use “Deployment Assembly” option.
6)      Use the Servicelocator or PortTypeProxy generated class to call webservice operations

Sample code to send and receive SOAP headers using JAX-RPS :
ServiceLocator serviceLocator=new ServiceLocator();
PortType oppService=serviceLocator.getRetailPort();
javax.xml.rpc.Stub oppServiceStub=(javax.xml.rpc.Stub)oppService;

//setting webservice endpoint
String retailEndPointURL=”<ws_url>”;
oppServiceStub._setProperty("javax.xml.rpc.service.endpoint.address",retailEndPointURL);


1 //Create the request and response hashmaps.
2 HashMap requestHeaders=new HashMap();
3 HashMap responseHeaders=new HashMap();
4
5 //Add "AtmUuid1" and "AtmUuid2" to the request hashmap.
6 requestHeaders.put(new QName("com.rotbank.security", "AtmUuid1"),
7   "<AtmUuid1 xmlns=\"><uuid>ROTB-0A01254385FCA09</uuid></AtmUuid1>");
8 requestHeaders.put(new QName("com.rotbank.security", "AtmUuid2"),
9  ((IBMSOAPFactory)SOAPFactory.newInstance()).createElementFromXMLString(
10   "x:AtmUuid2 xmlns:x=\"com.rotbank.security\"><x:uuid>ROTB-0A01254385FCA09
     </x:uuid><x:AtmUuid2>"));
11
12 //Add "ServerUuid" to the response hashmap.
13 //If "responseHeaders" is empty, all the SOAP headers are
14 //extracted from the response message.
15 responseHeaders.put(new QName("com.rotbank.security","ServerUuid"), null);
16
17 //Set the properties on the Stub object.
18 stub.setProperty(com.ibm.websphere.webservices.Constants.REQUEST_SOAP_HEADERS.requestHeaders);
19 stub.setProperty(com.ibm.websphere.webservices.Constants.RESPONSE_SOAP_HEADERS.responseHeaders);
20
21 //Call the operationon the Stub.
22 stub.foo(parm2, parm2);
23
24 //Retrieve "ServerUuid" from the response hashmap.
25 SOAPElement serverUuid =
26   (SOAPElement) responseHeaders.get(new QName("com.rotbank.security","ServerUuid"));
27
28 //Note: "serverUuid" now equals a SOAPElement object that represents the
29 //following code:
30//"<y:ServerUuid xmlns:y=\"com.rotbank.security\"><:uuid>ROTB-0A03519322FSA01
   </y:uuid></y:ServerUuid.");


On lines 2-3, new HashMaps are created that are used for the request and response SOAP headers.

On lines 6-10, the AtmUuid1 and AtmUuid2 headers elements are added to the request HashMap.

On line 15, the ServerUuid header element name, along with a null value, is added to the response HashMap.

On line 18, the request HashMap is set as a property on the Stub object. This causes the AtmUuid1 and AtmUuid2 headers to be added to each request message that is associated with an operation that is invoked on the Stub object.

On line 19, the response HashMap is set as a property on the Stub object. This causes the ServerUuid header to be extracted from each response message that is associated with an operation that is invoked on the Stub object.

On line 22, the Web service operation is invoked on the Stub object.

On lines 25-26, the ServerUuid header is retrieved from the response HashMap. The header was extracted from the response message and inserted into the HashMap by the Web services engine.

Some part of sample code is taken from link: http://publib.boulder.ibm.com/infocenter/wasinfo/v7r0/index.jsp?topic=/com.ibm.websphere.express.doc/info/exp/ae/rwbs_impsoapheadexmp.html