Tuesday, 7 March 2017

SOAP Web Service Basic Example And Configuration

Soap:
SOAP stands for Simple Object Access Protocol. 

SOAP provides a way to communicate between applications running on different operating systems, with different technologies and programming languages.

The best way to communicate between applications is over HTTP, because HTTP is supported by all Internet browsers and servers. SOAP was created to accomplish this

Notice: Soap uses only XML data format for request and response.

Basic Requirements:
1. Eclipse
2. Jboss Server
3. Jdk 1.6 or +
4. Following Lib:
              axis.jar
              commons-discovery-0.2.jar
              commons-logging.jar
              jaxrpc.jar
              saaj.jar
              wsdl4j.jar
Put these jars in your lib folder.

Project Structure in Eclipse:
Let me discuss about above files.
1. RequestXML.java : This is request pojo class which takes one parameter  which has XML format.

package com.soap.test;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlType;

@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "RequestXMl", propOrder = { "id"})
public class RequestXMl {

@XmlElement(name = "Id")
private int id;

public int getId() {
return id;
}

public void setId(int id) {
this.id = id;
}


}

2. ResponseXML.java: This is response pojo class which return name and age  which has XML format.

package com.soap.test;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlType;

@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "ResponseXML", propOrder = { "name", "age"})
public class ResponseXML {

@XmlElement(name = "Name")
private String name;
@XmlElement(name = "Age")
private int age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}


}

3. SoapDAO.java: This is the DAO(Data Access Object) class as we all java developer know how to write DAO, handler, controller class, So here i am directly calling dao class from service class you can have multiple layer based on your company's project structure.

package com.soap.test;

public class SoapDAO {

public ResponseXML getRecord(RequestXMl req )
{
ResponseXML res=new ResponseXML();

System.out.println("Request ID: "+req.getId());
res.setAge(27);
res.setName("Lokesh Sahu");

return res;

}


}

4. SoapService.java: This is main class for soap service you can have any name of the class in my case name of the service is SaopService.

In this class as of now we have only one service public ResponseXML getDetails(RequestXMl req ) in this class

You can have multiple methods in same service class. 

In below Class if you see two line of code just above class name which has red text that is the only code which define its a soap service, only first class or we can say the entry class of the request is soap service.

Some keyword which is used in soap services are following:

targetNamespace: this is just reverse of your package name
serviceName: This is the class name which will be published  as service name
portName: portname should be services name + SOAP keyword as we follow standards


package com.soap.test;

import javax.jws.soap.SOAPBinding;
import org.xml.sax.XMLReader;

@javax.jws.WebService(targetNamespace = "http://test.soap.com/", serviceName = "SoapService", portName = "SoapServiceSOAP")
@SOAPBinding(style = SOAPBinding.Style.DOCUMENT, use = SOAPBinding.Use.LITERAL, parameterStyle = SOAPBinding.ParameterStyle.WRAPPED)

public class SoapService {

public ResponseXML getDetails(RequestXMl req )

{

return new SoapDAO().getRecord(req);
}

}

Now all setup its time to build project and create war file,
Right click on project and export war and save it on any location.

Now start the Jboss Server and Deploy this war.

While deploying Jboss will give you service url as given below image





In Image you can see Red circle which has service url with 
http://localhost:4000/SoapTest/SoapService

in my case the url which has machine name but it will be depends on machine 

Now copy the URL and paste in google chrome and add ?wsdl in last with url and press enter like this :
http://localhost:4000/SoapTest/SoapService?wsdl

So it will give you wsdl file, you can give this wsdl file to anyone who want to consume your services.

For local testing you should have SOAPUI 4.0+ software to test

In my SOPA ui how it look like see the below image





You can configure the service url in soap ui to test in local you can also search in google how to import or create new project in soap ui for testing.

Thanks A Lot for reading my Blog, Happy Learning.

You can also visit my REST and Spring MVC blog on same url.






Friday, 31 July 2015

RESTful Web services configuration in eclipse

Introduction:


Restful web services is used for client server communication over the HTTP protocol.

For client server communication it uses many data format like Json, Xml, Html etc.

Now, How to create simple hello world example using restful web services in eclipse
please follow the given steps.

It Works on HTTP protocols.

      1. GET for reading resources
      2. PUT for creating resources
      3. POST for updating resources
      4. DELETE for deleting resources

We can define the paths to access particular resource by Annotations. Here some importanant annotations are there

      1. @PATH - to define path
      2. @POST - to handle HTTP POST request
      3. @GET - to handle HTTP GET request
      4. @PUT - to handle HTTP PUT request
      5. @DELETE - to handle HTTP DELETE request
      6. @Produces - to define output type
      7. @Consumes - to define input
      8. @PathParam - to get parameter values in post request.
      9. @QueryParam - to get parameter values in get request (in url)

Requirements:


1. Eclipse or netbeans
2. Tomcat
3. jdk 1.5 or above
4. Following libraries for rest:
         jersey-client-1.17.jar 
         jersey-core-1.17.jar
         jersey-server-1.17.jar
         jersey-servlet-1.17.jar
         xstream-1.17.jar
  Download these jar from here

Step1:


Open Eclipse > File > New > Dynamic Web Project > 'enter project name'

Step2:


 Configure all libraries into the build path Or right click on project select 'properties' and click on
 'java build path' then click on 'Add External Jar' then locate your libraries folder and select all  above mentioned jars and finally click on OK.

Step3:


Now create index.html file inside web content  with following  contents:

<!DOCTYPE html >
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">

<title>Rest Examples</title>


</head>
<body>
<a href="http://localhost:8080/RestWebservices/rs/test/hello>Click Here</a>

</body>
</html> 

Step4:


Now create HelloWorldRest.java for testing with following contents:

import javax.ws.rs.DefaultValue;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;

@Path("/test")
public class HelloWorldRest {

@GET
@Path("/hello")


public String hello()
{

String hello="Welcome To Restfull Web Services";
System.out.println(hello);

return hello;
}

}


Here we are using some annotation like 
@Path-this annotation is used for identify the path of class
@GET- this is http GET method for calling web services.

Step5:

Now create the web.xml file inside WEB-INF folder with following contents

<?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>CaseStudyREST</display-name>
  <welcome-file-list>
    
    <welcome-file>index.html</welcome-file>
    
  </welcome-file-list>
  <servlet>
    <servlet-name>ServletAdaptor</servlet-name>
    <servlet-class>com.sun.jersey.server.impl.container.servlet.ServletAdaptor</servlet-class>
    
    <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>ServletAdaptor</servlet-name>
    <url-pattern>/rs/*</url-pattern>
  </servlet-mapping>
</web-app>

Here we are using ServletAdaptor for handling web services

Step6: RUN APPLICATION

Now start server and right click on project goto run>run as server

Now you will be able to see output in browser  click on 'CLICK HERE' 

Thanks for reading this tutorial hope it will help you.


Thursday, 30 July 2015

Spring MVC configuration in eclipse

Introduction:

Spring is an open source light weight framework for developing Java Application.
Spring provide many modules like, Beans, context, application, Core, Data access, Spring MVC etc.

For creating simple Java web application we use Spring MVC(Model View Controller) module.

Here we will see how to configure spring hello world application using eclipse.

Requirements:

1. Eclipse
2. Tomcat server
3. JDK_1.5.0 or later version
4. Spring jars(these are spring 3 jars you can have spring 4 jars also)

    slf4j-api-1.1.0-beta0.jar
    spring-asm-3.0.1.RELEASE.jar
    spring-context-3.0.1.RELEASE.jar
    spring-beans-3.0.1.RELEASE.jar
    spring-core-3.0.1.RELEASE.jar
    spring-expression-3.0.1.RELEASE.jar
    spring-instrument-3.0.1.RELEASE.jar
    spring-oxm-3.0.1.RELEASE.jar
    spring-web-3.0.1.RELEASE.jar
    spring-webmvc-3.0.1.RELEASE.jar

You can download these here

Project structure will be like this image in eclipse



Follow the given steps for creating simple application in Eclipse.

Step1:

Open Eclipse>File>New>Dynamic web project>'enter name of project'
click on 'Finish' button

Here my project name is FirstSpring

Step2:

Now create index.html file inside WebContent like this

<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<a href="hello.html">Click Here</a> |   
</body>
</html>

Step3:


Now create web.xml file inside WEB-INF folder like this


<?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" 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>FirstSpring</display-name>
  <welcome-file-list>
    
    <welcome-file>index.jsp</welcome-file>

  </welcome-file-list>
  <servlet>
<servlet-name>spring</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>spring</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
<context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/spring-servlet.xml</param-value>
    </context-param>
</web-app>

If you noticed we are using DispatcherServlet in web.xml, this is the front end controller of the spring
which is responsible for handling coming request and displaying response in UI, This controller provided by spring only.

Step4:


Create one spring-servlet.xml file inside WEB-INF folder for view resolver and spring basic configuration like this.  

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
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">

<context:component-scan base-package="com.tcs.controller" />
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">  
        <property name="prefix" value="/WEB-INF/jsp/" />  
        <property name="suffix" value=".jsp" />  
    </bean>
    
</beans> 

here we are using InternalResourceViewResolver class for view resolver or in other word we can say DispatcherServlet try to find
output .jsp file or .html to display response.
prefix and suffix is the getter setter of InternalResourceViewResolver class, here prefix is used to resolved folder name and
suffix is used to resolved file extension.

Step5:


Now create jsp folder inside WEB-INF folder and create hellopage.jsp file inside jsp folder for displaying response like this.


<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
message is: ${message}
</body>
</html>


here $ work like getAttribute in servlet which set by controller in java file
and 'message' is the output string which is set by the controller once we create controller class then you will see.

Step6:


Now finally we are creating 'HelloWorldController.java' for testing something like this



import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

@Controller
public class HelloWorldController {

@RequestMapping(value="/hello", method=RequestMethod.GET)
public ModelAndView helloWorld()
{
String message="Hello you are  in spring" ;
return new ModelAndView("hellopage", "message", message);
}
}
Here we are using some annotation like

'@controller' when you use this annotation with class, That class will treat as as controller class in spring.
DispatcherServlet will map your request into this class.

'@RequestMapping' this is use for request mapping which will come from client in our case request is coming from index.html.
if you noticed that in index.html when you click on 'hello spring' internally request will go as 'hello' in controller class.

'RequestMethod.GET' this indicate your coming request is using http GET method 
'ModelAndView' this a class which we are returning as a response, This class provide a constructor which has three parameters.

first parameters is your output jsp page which will be inside jsp folder as I discussed in step5
second parameter is output string where you are setting your output which will be retrieve 'hellopage.jsp' 
Third parameter is your actual output which is what you want to return.
Here I am returning String message="Hey you are in spring application";

Step7: RUN APPLICATION


Now we have done all configuration its time to start server and right click in your project and select run as> run on server

Output will like this

you will able to see hello.html page with 'Hello Spring' link now click on this link you will get output like this 


This was very basic spring MVC application which can give you basic idea about spring configuration.

Thanks for reading this tutorial.