Tuesday, June 11, 2013

Write Spring Web service

As you know that Spring support only contract first web service , i am giving you complete example how to write Web service.

IDE : Any Eclipse or Spring suit
Server : Tomcat 6 or 7

1) Create Dynamic web project  with "ws-tutorial" you can use any other name but then you need to take care web.xml and -servlet.xml


2) Inside of lib folder following jar required .
 You can directly copy it or cretae pom file with dependency .


  1. activation-1.1.1.jar
  2. aopalliance-1.0.jar
  3. commons-logging-1.1.1.jar
  4. easymock-1.2_Java1.3.jar
  5. jaxb-api-2.1.jar
  6. jaxb-impl-2.1.5.jar
  7. jaxen-1.1.1.jar
  8. jdom-1.0.jar
  9. junit-3.8.2.jar
  10. log4j-1.2.15.jar
  11. mail-1.4.1.jar
  12. saaj-api-1.3.jar
  13. saaj-impl-1.3.jar
  14. spring-aop-2.5.1.jar
  15. spring-beans-2.5.1.jar
  16. spring-context-2.5.1.jar
  17. spring-context-support-2.5.1.jar
  18. spring-core-2.5.1.jar
  19. spring-jdbc-2.5.1.jar
  20. spring-jms-2.5.1.jar
  21. spring-orm-2.5.1.jar
  22. spring-oxm-1.5.0-m2.jar
  23. spring-tx-2.5.1.jar
  24. spring-web-2.5.1.jar
  25. spring-webmvc-2.5.1.jar
  26. spring-ws-core-1.5.0-m2.jar
  27. spring-xml-1.5.0-m2.jar
  28. stax-api-1.0.1.jar
  29.  wsdl4j-1.6.1.jar
  30. xalan-2.7.0.jar
  31. xercesImpl-2.8.1.jar
  32. xml-apis-1.3.04.jar

     
Now your project is created 

3)Create any XML request message you required  example :


<QuickViewRequest xmlns="http://mycompany.com/hr/schemas">
    <QuickView>
        <Plan>2006-07-03</Plan>
    </QuickView>
</QuickViewRequest>

4)Now using XML tools create XSD file  "quickview.xsd" will discuss each mapping in details   copy  xsd inside of web inf folder /WEB-INF/quickview.xsd"

<?xml version="1.0" encoding="UTF-8"?>

<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
           xmlns:hr="http://mycompany.com/hr/schemas"
           elementFormDefault="qualified"
           targetNamespace="http://mycompany.com/hr/schemas">

<xs:element name="QuickViewRequest">
<xs:complexType>
<xs:all>
<xs:element name="QuickView" type="hr:QuickViewType" />
</xs:all>
</xs:complexType>
     </xs:element>
     
<xs:complexType name="QuickViewType">
<xs:sequence>
<xs:element name="Plan" type="xs:string" />
</xs:sequence>
</xs:complexType>
</xs:schema>


Now you are ready to create web service 

Add inside of web.xml following configuration 


<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>MyCompany HR Holiday Service</display-name>

    <servlet>
        <servlet-name>spring-ws</servlet-name>
        <servlet-class>org.springframework.ws.transport.http.MessageDispatcherServlet</servlet-class>
    </servlet>

    <servlet-mapping>
        <servlet-name>spring-ws</servlet-name>
        <url-pattern>/services/*</url-pattern>
    </servlet-mapping>

</web-app>

now create "spring-ws-servlet.xml"  with following configuration


<beans xmlns="http://www.springframework.org/schema/beans"
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-2.0.xsd">

<bean
class="org.springframework.ws.server.endpoint.mapping.PayloadRootQNameEndpointMapping">
<property name="mappings">
<props>
<prop key="{http://mycompany.com/hr/schemas}QuickViewRequest">QuickViewEndpoint</prop>
</props>
</property>
<property name="interceptors">
<bean
class="org.springframework.ws.server.endpoint.interceptor.PayloadLoggingInterceptor" />
</property>
</bean>


<bean id="QuickViewEndpoint" class="com.mycompany.hr.ws.QuickViewEndpoint">
<constructor-arg ref="iQuickViewResourceService" />
</bean>

<bean id="iQuickViewResourceService" class="com.mycompany.hr.service.QuickViewResourceService" />

<!-- 
<bean
class="org.springframework.ws.server.endpoint.mapping.PayloadRootQNameEndpointMapping">
<property name="mappings">

<props>
   <prop key="{http://mycompany.com/hr/schemas}QuickViewRequest">QuickViewEndpoint</prop>
</props>
</property>
<property name="interceptors">
<bean
class="org.springframework.ws.server.endpoint.interceptor.PayloadLoggingInterceptor" />
</property>
</bean>
-->
<bean id="quickview"
class="org.springframework.ws.wsdl.wsdl11.DynamicWsdl11Definition">
<property name="builder">
<bean
class="org.springframework.ws.wsdl.wsdl11.builder.XsdBasedSoap11Wsdl4jDefinitionBuilder">
<property name="schema" value="/WEB-INF/quickview.xsd" />
<property name="portTypeName" value="QuickViewResource" />
<property name="locationUri" value="http://localhost:8080/ws-tutorial/services" />
<property name="targetNamespace" value="http://mycompany.com/hr/definitions" />
</bean>
</property>
</bean>
</beans>

5) Create interface and give its implementation in class

public interface IQuickViewResourceService {

public String getQuickView(String url,String Plan);


}

public class QuickViewResourceService implements IQuickViewResourceService {

    private static final Log logger = LogFactory.getLog(StubHumanResourceService.class);

    public String getQuickView(String URL ,String plan) {
        logger.info("Inside Service-->."+plan);
        return "Vaquar";
    }

}

6) Create End point 

import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.Namespace;
import org.jdom.xpath.XPath;
import org.springframework.ws.server.endpoint.AbstractJDomPayloadEndpoint;

import com.mycompany.hr.service.HumanResourceService;
import com.mycompany.hr.service.IQuickViewResourceService;


public class QuickViewEndpoint extends AbstractJDomPayloadEndpoint {

    private XPath Plan;


    private IQuickViewResourceService iQuickViewResourceService;

    public QuickViewEndpoint(IQuickViewResourceService iQuickViewResourceService) throws JDOMException {
        this.iQuickViewResourceService = iQuickViewResourceService;
        Namespace namespace = Namespace.getNamespace("hr", "http://mycompany.com/hr/schemas");
        Plan = XPath.newInstance("//hr:Plan");
        Plan.addNamespace(namespace);
        
    }

    protected Element invokeInternal(Element holidayRequest) throws Exception {
        String name = "Vaquar Khan";
        iQuickViewResourceService.getQuickView("",name);
        System.out.println("QuickViewEndpoint ..........................");
        return null;
    }


}

Now you are done with Web service code .
7)We are going to write client for web service 

public class QuickViewMain {

public static void main(String[] args) throws Exception {
try{
QuickViewRequestClient iQuickViewResourceService = new QuickViewRequestClient();

String url = "http://localhost:8080/ws-tutorial/services";

String Plan="Vaquar";
iQuickViewResourceService.getQuickView(Plan,url);

}catch(Exception e){
e.printStackTrace();

}
System.exit(0);
}


}



import java.text.SimpleDateFormat;
import java.util.Date;

import org.jdom.Document;
import org.jdom.Element;
import org.jdom.Namespace;
import org.jdom.transform.JDOMResult;
import org.jdom.transform.JDOMSource;
import org.springframework.ws.client.core.WebServiceTemplate;

/**
 * Example client code using Spring-WS.
 */
public class QuickViewRequestClient {
private Namespace hrNs;
private WebServiceTemplate wsTemplate;
/**
* Default class constructor
*/
public QuickViewRequestClient() {
hrNs = Namespace.getNamespace("hr", "http://mycompany.com/hr/schemas");
wsTemplate = new WebServiceTemplate();
}

public void getQuickView(String plan,String url) {
Document document = 
createQuickViewRequest(plan);

        wsTemplate.sendSourceAndReceiveToResult(url, new JDOMSource(document.getRootElement()), new JDOMResult());
}

/**
* Creates a JDOM element representing a holiday request.
*/
private Document createQuickViewRequest(String Plan) {
Document document= new Document(new Element("QuickViewRequest", hrNs));
document.getRootElement()
.addContent(new Element("QuickView", hrNs).addContent(new Element("Plan", hrNs).setText("100")));
return document;
}
}

Add your war into tomcat server and run server  and run java class "QuickViewMain " :)

Thursday, June 6, 2013

Remove Trailing Zero in String

Remove Trailing Zero in String

Example 10000000 should be 1
and  1000001 should be 1000001

public class Test {

/**
* @param args
*/
public static void main(String[] args) {
Test test = new Test();
System.out.println("" + test.removeTrailingZero("1000000001"));

}

public String removeTrailingZero(String inputValue) {
String inputOrignal = "";
if (inputValue != null) {

StringBuilder sb = new StringBuilder(inputValue);
String input = sb.reverse().toString();

int len = input.length();
int counter = 0;
char[] tempCharArray = new char[len];

// put original string in an array of chars
for (int i = 0; i < len; i++) {
tempCharArray[i] = input.charAt(i);
if (input.charAt(i) == '0') {
counter++;
} else {
break;
}
}
inputOrignal = inputValue.substring(0, (len - counter));
}
return inputOrignal;
}

}