Saturday 27 April 2013

Contract-first Spring Web Services (Example - 2)

Contract-first Spring Web Services

string-changecase sample code

Here I am presenting another example for developing Contract-first Spring Web-Service.
Please follow the primary steps mentioned in the below link in order to develop code for second example of Contract-first Spring web-service.

STEPS:-
1) Create a dynamic web project using Eclipse and name it as string-changecase.



2)  Create 3 packages with the names springws.stringchangecase, springws.stringchangecase.client and springws.stringchangecase.endpoint in the src folder.

3) Place the below available codes in their corresponding directories as shown in the project structure image above:-

changecaseService.xsd

<?xml version="1.0" encoding="UTF-8"?>
<schema xmlns="http://www.w3.org/2001/XMLSchema"
    elementFormDefault="qualified" attributeFormDefault="qualified"
    targetNamespace="http://localhost:7075/springws/stringchangecase/changecase-service"
    xmlns:tns="http://localhost:7075/springws/stringchangecase/changecase-service">

    <element name="stringChangeCaseRequest" type="string" />
    <element name="stringChangeCaseResponse" type="string" />

</schema>

StringChangeCaseService.java

package springws.stringchangecase;

public interface StringChangeCaseService {

    String changeCase(String inputString);

}

StringChangeCaseServiceImpl.java

package springws.stringchangecase;

public class StringChangeCaseServiceImpl implements StringChangeCaseService {

    public String changeCase(String inputString) {

        if (inputString == null || inputString.trim().length() == 0) {
            return "";
        } else {
            StringBuilder sb = new StringBuilder();
            char ch[] = inputString.toCharArray();
            for (int i = 0; i < ch.length; i++) {
                if (ch[i] == ' ') {
                    sb.append(" ");
                }
                if (Character.isLowerCase(ch[i])) {
                    char cha = Character.toUpperCase(ch[i]);
                    sb.append(Character.toString(cha));
                } else if (Character.isUpperCase(ch[i])) {
                    char cha = Character.toLowerCase(ch[i]);
                    sb.append(Character.toString(cha));
                }
            }

            return sb.toString();
        }
    }
}
 StringChangeCaseClient.java

package springws.stringchangecase.client;

import java.io.StringReader;

import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;

import org.springframework.ws.client.core.WebServiceTemplate;

public class StringChangeCaseClient {

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

        String xmlRequestForLowerCase = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>"
                + "<stringChangeCaseRequest xmlns=\"http://localhost:7075/springws/stringchangecase/changecase-service\">KUMAR GAURAV</stringChangeCaseRequest>";

        String wsdlUrl = "http://localhost:7075/string-changecase/stringChangeCase.wsdl";

        StreamSource requestMessage = new StreamSource(new StringReader(
                xmlRequestForLowerCase));
       
        System.out.println("\n");
        System.out.println("Example for String Upper to Lower Case Conversion");
        System.out.println("\n");
        StreamResult responseMessage = new StreamResult(System.out);

        WebServiceTemplate template = new WebServiceTemplate();
        template.sendSourceAndReceiveToResult(wsdlUrl, requestMessage,
                responseMessage);
       

        String xmlRequestForUpperCase = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>"
                + "<stringChangeCaseRequest xmlns=\"http://localhost:7075/springws/stringchangecase/changecase-service\">kumar gaurav</stringChangeCaseRequest>";

        requestMessage = new StreamSource(new StringReader(
                xmlRequestForUpperCase));
        System.out.println("\n");
        System.out.println("Example for String Lower to Upper Case Conversion");
        System.out.println("\n");
        responseMessage = new StreamResult(System.out);

        template = new WebServiceTemplate();
        template.sendSourceAndReceiveToResult(wsdlUrl, requestMessage,
                responseMessage);
       
        String xmlRequestForInitCase = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>"
            + "<stringChangeCaseRequest xmlns=\"http://localhost:7075/springws/stringchangecase/changecase-service\">Kumar Gaurav</stringChangeCaseRequest>";

        requestMessage = new StreamSource(new StringReader(
                xmlRequestForInitCase));
        System.out.println("\n");
        System.out.println("Example for String Init Case Conversion");
        System.out.println("\n");
        responseMessage = new StreamResult(System.out);

        template = new WebServiceTemplate();
        template.sendSourceAndReceiveToResult(wsdlUrl, requestMessage,
            responseMessage);
    }
}

StringChangeCaseServiceEndpoint.java

package springws.stringchangecase.endpoint;

import org.springframework.ws.server.endpoint.AbstractDomPayloadEndpoint;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.w3c.dom.Text;

import springws.stringchangecase.StringChangeCaseService;

public class StringChangeCaseServiceEndpoint extends AbstractDomPayloadEndpoint {

    public static final String NAMESPACE = "http://localhost:7075/springws/stringchangecase/changecase-service";

    public StringChangeCaseService stringChangeCaseService;

    public void setStringChangeCaseService(
            StringChangeCaseService stringChangeCaseService) {
        this.stringChangeCaseService = stringChangeCaseService;
    }

    protected Element invokeInternal(Element requestElement, Document document)
            throws Exception {

        String requestString = findRequestString(requestElement);
        String changedCaseString = invokeServiceAndReturnResponse(requestString);
        Element responseXml = prepareResponseXml(document, changedCaseString);
        return responseXml;
    }

    private static String findRequestString(Element requestElement) {

        NodeList childNodes = requestElement.getChildNodes();
        String requestString = null;
        for (int i = 0; i < childNodes.getLength(); i++) {
            if (childNodes.item(i).getNodeType() == Node.TEXT_NODE) {
                Text tempText = (Text) childNodes.item(i);
                requestString = tempText.getNodeValue();
                break;
            }
        }
        return requestString;
    }

    private String invokeServiceAndReturnResponse(String requestString) {

        String changedCaseString = stringChangeCaseService
                .changeCase(requestString);
        return changedCaseString;
    }

    private static Element prepareResponseXml(Document document,
            String responseString) {

        Element responseElement = document.createElementNS(NAMESPACE,
                "stringChangeCaseResponse");
        Text responseText = document.createTextNode(responseString);
        responseElement.appendChild(responseText);
        return responseElement;
    }
}

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
    id="WebApp_ID" version="2.5">
    <display-name>string-changecase</display-name>
    <servlet>
        <servlet-name>spring-webservice</servlet-name>
        <servlet-class>org.springframework.ws.transport.http.MessageDispatcherServlet</servlet-class>
        <init-param>
            <param-name>transformWsdlLocations</param-name>
            <param-value>true</param-value>
        </init-param>
    </servlet>

    <servlet-mapping>
        <servlet-name>spring-webservice</servlet-name>
        <url-pattern>/*</url-pattern>
    </servlet-mapping>
</web-app>

spring-webservice-servlet.xml

<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="
        http://www.springframework.org/schema/beans    
        http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context-3.0.xsd
        http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">

    <bean id="stringChangeCaseService" class="springws.stringchangecase.StringChangeCaseServiceImpl">
    </bean>

    <bean id="stringChangeCaseServiceEndpoint"
        class="springws.stringchangecase.endpoint.StringChangeCaseServiceEndpoint">
        <property name="stringChangeCaseService" ref="stringChangeCaseService" />
    </bean>
    <bean id="payloadMapping"
        class="org.springframework.ws.server.endpoint.mapping.PayloadRootQNameEndpointMapping">
        <property name="defaultEndpoint" ref="stringChangeCaseServiceEndpoint" />
    </bean>
    <bean id="stringChangeCaseSchema" class="org.springframework.xml.xsd.SimpleXsdSchema">
        <property name="xsd" value="/WEB-INF/changecaseService.xsd" />
    </bean>

    <bean id="stringChangeCase"
        class="org.springframework.ws.wsdl.wsdl11.DefaultWsdl11Definition">
        <property name="schema" ref="stringChangeCaseSchema" />
        <property name="portTypeName" value="stringChangeCase" />
        <property name="locationUri"
            value="http://localhost:7075/string-changecase/services" />
    </bean>
</beans>

* After running the server, hit the below URL:
       http://localhost:7075/string-changecase/stringChangeCase.wsdl

In this URL, we will get the WSDL file for the above string-changecase project

*The WSDL file will look like as follow:-

 <?xml version="1.0" encoding="UTF-8" standalone="no" ?>
<wsdl:definitions xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/"
    xmlns:sch="http://localhost:7075/springws/stringchangecase/changecase-service"
    xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/"
    xmlns:tns="http://localhost:7075/springws/stringchangecase/changecase-service"
    targetNamespace="http://localhost:7075/springws/stringchangecase/changecase-service">
    <wsdl:types>
        <schema xmlns="http://www.w3.org/2001/XMLSchema"
            attributeFormDefault="qualified" elementFormDefault="qualified"
            targetNamespace="http://localhost:7075/springws/stringchangecase/changecase-service">
            <element name="stringChangeCaseRequest" type="string" />
            <element name="stringChangeCaseResponse" type="string" />
        </schema>
    </wsdl:types>
    <wsdl:message name="stringChangeCaseResponse">
        <wsdl:part element="tns:stringChangeCaseResponse" name="stringChangeCaseResponse" />
    </wsdl:message>
    <wsdl:message name="stringChangeCaseRequest">
        <wsdl:part element="tns:stringChangeCaseRequest" name="stringChangeCaseRequest" />
    </wsdl:message>
    <wsdl:portType name="stringChangeCase">
        <wsdl:operation name="stringChangeCase">
            <wsdl:input message="tns:stringChangeCaseRequest" name="stringChangeCaseRequest" />
            <wsdl:output message="tns:stringChangeCaseResponse" name="stringChangeCaseResponse" />
        </wsdl:operation>
    </wsdl:portType>
    <wsdl:binding name="stringChangeCaseSoap11" type="tns:stringChangeCase">
        <soap:binding style="document"
            transport="http://schemas.xmlsoap.org/soap/http" />
        <wsdl:operation name="stringChangeCase">
            <soap:operation soapAction="" />
            <wsdl:input name="stringChangeCaseRequest">
                <soap:body use="literal" />
            </wsdl:input>
            <wsdl:output name="stringChangeCaseResponse">
                <soap:body use="literal" />
            </wsdl:output>
        </wsdl:operation>
    </wsdl:binding>
    <wsdl:service name="stringChangeCaseService">
        <wsdl:port binding="tns:stringChangeCaseSoap11" name="stringChangeCaseSoap11">
            <soap:address location="http://localhost:7075/string-changecase/services" />
        </wsdl:port>
    </wsdl:service>
</wsdl:definitions>

Result:-


Note:- Same library is needed which i used in the development of
find-factorial-using-contractfirst example in the below URL.


No comments:

Post a Comment