Parts of OpenAPI 3.0 Specification
Info and Components are important parts of API Definition

  1. Info – Provides Name, Description and Developers information of API
  2. Servers – Provides server information and various environment URL of API
  3. Security – Provides details about how API is secured, API keys, Authorization information
  4. Paths – Details about API Endpoints
  5. Tags and extenaldocs – Tags that could be grouped for API operations
  6. Components – Set of reusable objects which could be used during API definition

Swagger Consist of Three Parts

  1. swagger-editor– Helps in editing yml file as per Open API Specification
  2. swagger-ui– dist folder helps in circulating API documentation
  3. swagger-codegen

Installing Swagger in Local
Swagger needs http-server. We would use node http-server. We should navigate to the swagger editor folder and start the http-server.

>>npm install -g http-server
>>npm install
>>http-server swagger-editor -a 127.0.0.1 -p 8090
>>http-server swagger-ui -a 127.0.0.1 -p 8091

For the API Documentation we can copy and ship the dist folder in swagger-ui folder. We would have already placed the yaml file which we have created in swagger-editor in swagger-ui folder. Now we should edit the index.html file in swagger-ui folder as below to point to out yml file

index.html

.
.
window.onload = function() {
  // Begin Swagger UI call region
  const ui = SwaggerUIBundle({
  url: "EmpMgmt.yaml",
  dom_id: '#swagger-ui',
   deepLinking: true,
.
.

Presuming the project has Documentation in api-docs folder we can now start the server as below

>>D:\Projects\workspace\EmpMgmt> http-server api-docs -a 127.0.0.1 -p 8091

Refernce for OpenAPI Specification
https://github.com/OAI/OpenAPI-Specification/tree/main/versions

Spring MVC uses HttpMessageConverter to convert the Http request to an object representation and back.Spring Framework then uses one of the Jackson message converters to marshall and unmarshall Java Objects to and from JSON over HTTP.Spring will use the “Accept” header to determine the media type that it needs to respond with and uses the “Content-Type” header to determine the media type of the request body.

Default Message Converters in Spring MVC
StringHttpMessageConverter: it converts Strings from the HTTP request and response.
FormHttpMessageConverter: it converts form data to/from a MultiValueMap.
ByteArrayHttpMessageConverter: it converts byte arrays from the HTTP request and response.
MappingJackson2HttpMessageConverter: it converts JSON from the HTTP request and response.
Jaxb2RootElementHttpMessageConverter: it converts Java objects to/from XML.
SourceHttpMessageConverter: it converts javax.xml.transform.Source from the HTTP request and response.
AtomFeedHttpMessageConverter: it converts Atom feeds.
RssChannelHttpMessageConverter: it converts RSS feeds.

Customizing HttpMessageConverters with Spring MVC

Annotation Usage
@RequestMapping
@RequestMapping(value = "/{name}", 
                method = RequestMethod.GET, 
                consumes="application/json"
                produces ="application/json",
                headers={"name=pankaj", "id=1"})
path (or) (or) name (or) and value: which URL the method is mapped to
method: compatible HTTP methods
params: filters requests based on presence, absence, or value of HTTP parameters
headers: filters requests based on presence, absence, or value of HTTP headers
consumes: which media types the method can consume in the HTTP request body
produces: which media types the method can produce in the HTTP response body
@RequestBody
@RequestMapping(method = RequestMethod.POST)
@ResponseBody
public HttpStatus something(@RequestBody MyModel myModel) 
{
    return HttpStatus.OK;
}
with @RequestBody, Spring will bind the incoming HTTP request body(for the URL mentioned in @RequestMapping for that method) to that parameter. While doing that, Spring will [behind the scenes] use HTTP Message converters to convert the HTTP request body into domain object [deserialize request body to domain object], based on Accept header present in request.
@ResponseBody
@RequestMapping(value = "/user/all", method = RequestMethod.GET)
public @ResponseBody List<User> listAllUsers() {
    return userService.findAllUsers();
}
with @ResponseBody, Spring will bind the return value to outgoing HTTP response body. While doing that, Spring will [behind the scenes] use HTTP Message converters to convert the return value to HTTP response body [serialize the object to response body], based on Content-Type present in request HTTP header
@RequestParam
http://localhost:8080/springmvc/hello/101?param1=10¶m2=20

public String getDetails(
    @RequestParam(value="param1", required=true) String param1,
        @RequestParam(value="param2", required=false) String param2){
...
}
@RequestParam is to obtain an parameter from the URI as well.@RequestParam annotation used for accessing the query parameter values from the request
defaultValue – This is the default value as a fallback mechanism if request is not having the value or it is empty.
name – Name of the parameter to bind
required – Whether the parameter is mandatory or not. If it is true, failing to send that parameter will fail.
value – This is an alias for the name attribute
@PathVariable
'http://localhost:8080/springmvc/hello/101?param1=10&param2=20

@RequestMapping("/hello/{id}")    public String getDetails(@PathVariable(value="id") String id,
    @RequestParam(value="param1", required=true) String param1,
    @RequestParam(value="param2", required=false) String param2){
.......
}

@GetMapping("/user/{firstName}/{lastName}")
   @ResponseBody
   public String handler(@MatrixVariable("firstName") String firstName,
         @MatrixVariable("lastName") String lastName
         ) {

      return "<br>Matxrix variable <br> "
            + "firstName =" + firstName +"<br>"
            + "lastName =" + lastName;
   }
@PathVariable is to obtain some placeholder from the URI
@MatrixVariable – a name-value pair within a path segment is referred as matrix variable. Matrix variables can appear in any path segment, each variable separated with a semicolon (;) and multiple values are separated by comma (,)
i.e.
http://www.example.com/employee/Mike;salary=45000;dept=HR
http://www.example.com/car/Audi;color=RED,BLACK,WHITE

@RequestHeader
@Controller
public class HelloController {
 @RequestMapping(value = "/hello.htm")
 public String hello(
   @RequestHeader(value="Accept") String accept,
   @RequestHeader(value="Accept-Language") String acceptLanguage,
   @RequestHeader(value="User-Agent", defaultValue="foo") String userAgent,
   HttpServletResponse response) {

  System.out.println("accept: " + accept);
  System.out.println("acceptLanguage: " + acceptLanguage);
  System.out.println("userAgent: " + userAgent);
  
  return null;
 }
}
Reading http requestheader is written in HelloController
The advantage of using Spring @RequestHeader is that it will automatically throw an exception like HTTP Status 400 – Missing request header ‘X’ for method parameter of type, if the header is NOT sent in the input request (by setting required=true)

@RequestHeader for facilitating use to get the header details easily in our controller class

GET

  1. GET is idempotent and can be requested any number of times
  2. GET requests can be cached, can be distributed & shared
  3. GET request is less secured compared to POST.

POST

  1. Used to Create a resource
  2. Post is not idempotent.x++ is not idempotent
  3. POST is NOT idempotent. So if you retry the request N times, you will end up having N resources with N different URIs created on server.

PUT

  1. Used to Create or Modify a resource
  2. PUT is idempotent, so if you PUT an object twice, it has no effect.
  3. x=5 is idempotent.You can PUT a resource whether it previously exists, or not (eg, to Create, or to Update)!

When to use Put and Post
You can use both PUT or POST for creating the resource until the client decides the resource location in the Server.But if the server decides the resource location using

POST /questions/ HTTP/1.1
Host: www.example.com/

Note that the following is an error:

POST /questions/ HTTP/1.1
Host: www.example.com/

If the URL is not yet created, you should not be using POST to create it while specifying the name. This should result in a ‘resource not found’ error because does not exist yet. You should PUT the resource on the server first.

You could though do something like this to create a resources using POST:

POST /questions HTTP/1.1
Host: www.example.com/

Note that in this case the resource name is not specified, the new objects URL path would be returned to you.

PUT is Used to create a resource, or overwrite it. While you specify the resources new URL.

PUT /questions/ HTTP/1.1
Host: www.example.com/

To overwrite an existing resource:

PUT /questions/ HTTP/1.1
Host: www.example.com/

PATCH
Patch request says that we would only send the data that we need to modify without modifying or effecting other parts of the data. Ex: if we need to update only the first name, we pass only the first name.PATCH – HTTP.PATCH can be used when the client is sending one or more changes to be applied by the server. The PATCH method requests that a set of changes described in the request entity be applied to the resource identified by the Request-URI. The set of changes is represented in a format called a patch document.

In PUT request, the enclosed entity would be considered as the modified version of a resource which residing on server and it would be replaced by this modified entity.

In PATCH request, enclosed entity contains the set of instructions that how the entity which residing on server, would be modified to produce a newer version.

DELETE

DELETE is pretty easy to understand. It is used to delete a resource identified by a URI.On successful deletion, return HTTP status 200 (OK) along with a response body, perhaps the representation of the deleted item (often demands too much bandwidth), or a wrapped response (see Return Values below). Either that or return HTTP status 204 (NO CONTENT) with no response body. In other words, a 204 status with no body, or the JSEND-style response and HTTP status 200 are the recommended responses.

  1. Caching is the ability to store copies of frequently accessed data in several places along the request-response path. When a consumer requests a resource representation, the request goes through a cache or a series of caches (local cache, proxy cache or reverse proxy) toward the service hosting the resource.
  2. If any of the caches along the request path has a fresh copy of the requested representation, it uses that copy to satisfy the request. If none of the caches can satisfy the request, the request travels all the way to the service (or origin server as it is formally known).
  3. Using HTTP headers, an origin server indicates whether a response can be cached and if so, by whom, and for how long. Caches along the response path can take a copy of a response, but only if the caching metadata allows them to do so.
  4. Few are the advantages of Caching
    • Reduce bandwidth
    • Reduce latency
    • Reduce load on servers
    • Hide network failures
  5. GET requests are cachable by default – until special condition arises. Usually, browsers treat all GET requests cacheable.
  6. POST requests are not cacheable by default but can be made cacheable if either an Expires header or a Cache-Control header with a directive, to explicitly allows caching, is added to the response. Responses to PUT and DELETE requests are not cacheable at all.

There are two main HTTP response headers that we can use to control caching behavior:
Expires : The Expires HTTP header specifies an absolute expiry time for a cached representation. Beyond that time, a cached representation is considered stale and must be re-validated with the origin server. To indicate that a representation never expires, a service can include a time up to one year in the future.

Expires: Wed, 6 March 2019 15:09:49 IST

Cache-Control:
The header value comprises one or more comma-separated directives. These directives determine whether a response is cacheable, and if so, by whom, and for how long e.g. max-age or s-maxage directives.

Cache-Control: max-age=3600
ETag: "abcd1234567n34jv"
(or)
Last-Modified: Fri, 10 May 2016 09:17:49 IST

Cacheable responses (whether to a GET or to a POST request) should also include a validator — either an ETag or a Last-Modified header.

ETag
An ETag value is an opaque string token that a server associates with a resource to uniquely identify the state of the resource over its lifetime. When the resource changes, the ETag changes accordingly.

Last-Modified
Whereas a response’s Date header indicates when the response was generated, the Last-Modified header indicates when the associated resource last changed. The Last-Modified value cannot be later than the Date value.

@RequestBody, spring will try to convert the content of the incoming request body to your parameter object on the fly.@ResponseBody, spring will try to convert its return value and write it to the http response automatically

@Controller
@RequestMapping(value = "/bookcase")
public class BookCaseController 
{ 
    private BookCase bookCase;
 
    @RequestMapping(method = RequestMethod.GET)
    @ResponseBody
    public BookCase getBookCase() {
        return this.bookCase;
    }
 
    @RequestMapping(method = RequestMethod.PUT)
    @ResponseStatus(HttpStatus.NO_CONTENT)
    public void setBookCase(@RequestBody BookCase bookCase) {
        this.bookCase = bookCase;
    } 
}

Depending on your configuration, spring has a list of HttpMessageConverters registered in the background. A HttpMessageConverters responsibility is to convert the request body to a specific class and back to the response body again, depending on a predefined mime type. Every time an issued request is hitting a @RequestBody or @ResponseBody annotation spring loops through all registered HttpMessageConverters seeking for the first that fits the given mime type and class and then uses it for the actual conversion.

Refer here

Q: What is the Contract First and Service First Approach?
Contract-first is where you create the WSDL, and then you can create the implementation from this, and since the WSDL is your contract, this would be contract-first.
Service First or Contract-last or Code-First is where the WSDL is created from the source code, or implementation, so it will most likely be generated by a tool rather than created by the developer.

Q: Which is the better approach to web services – contract first or contract last?
Contract-first is the generally accepted ‘best practice.’.Both the producer and consumer of the service exactly what is needed and what is expected. It empowers the developer to use the full capabilities of XML (restrictions, patterns, …) and from there it is fairly easy to generate code for any programming language. One other reason is that the schema in the is the contract between the two systems talking to each other. If the developer creates the WSDL from code, technical dependencies on the specific programming language might be introduced (datatypes, …)

WSDL should be manually composed without using third party tool. Many now adays are not doing so since they find code first approach and generating WSDL is easy for them.

Below is simple code which generates WSDL using @WebService annotation

@WebService
public class TestService {
	@WebMethod
	public String sayHello(String msg){
		return "Hello "+msg;
	}	
}

Q: What JAXB does?
JAXB helps in converting Java Class to XML and Vice Versa. We always code our business logic in Java but the web service communication always happens by XML. So in order for this to happen we use third party tools like JAXB or JAXB2 plugins.

Q: What is the structure of SOAP Envelope?
A SOAP based web service message is a hierarchical XML packet, consisting of up to four parts.

  1. Envelope
  2. Header
  3. Body(Contains either Request or Response)
  4. Fault(Found only in Response)
<?xml version = "1.0"?>
<SOAP-ENV:Envelope xmlns:SOAP-ENV = "http://www.w3.org/2001/12/soap-envelope" 
   SOAP-ENV:encodingStyle = "http://www.w3.org/2001/12/soap-encoding">
 
   <SOAP-ENV:Header>
      ...
      ...
   </SOAP-ENV:Header>
   <SOAP-ENV:Body>
      ...
      ...
      <SOAP-ENV:Fault>
         ...
         ...
      </SOAP-ENV:Fault>
      ...
   </SOAP-ENV:Body>
</SOAP_ENV:Envelope>

Q: What are different part of WSDL Denote?
wsdl:types – Datatypes used in Request and Response. It contains the copy of entire XSD.
wsdl:message – Request and Response structure composed from various datatypes defined above.
wsdl:portType – PortType is like Interface. It tells about methods, their input and output.
wsdl:binding – Binding is like implementation of PortType. Defines how the SOAP service could be accessed over http,https or MQ.
wsdl:service – Contains the port which defines the Endpoint URL, port number

Q: What does REST Webservice follow? Contract First or Service First?
Unlike SOAP that exposes methods and method signatures, REST exposes resources. An understanding of the media types used in the exchange of those resources is all a REST client needs in order to communicate with a REST web service. There is no need for a separate document to describe the resources. Hence REST follows Service First Approach though Contract First Approach could be implemented.

Q: What are the Key Components in Webservices
All the web services has a Service Definition. Service Definition contains the following

  1. Request and Response Format
  2. Request Structure
  3. Response Structure
  4. API Endpoints

Q: what is the difference between XSD and WSDL?
WSDL (Web Services Description Language) describes your service and its operations – what is the service called, which methods does it offer, what kind of in parameters and return values do these methods have?

It’s a description of the behavior of the service – its functionality.

XSD (XML Schema Definition) describes the static structure of the complex data types being exchanged by those service methods. It describes the types, their fields, any restriction on those fields (like max length or a regex pattern), and so forth.

WSDL documents have an associated XSD that shows what is valid to put in a WSDL document.

Q:Short Descriptions on Tags below

<definitions name = "HelloService"
   targetNamespace = "http://www.examples.com/wsdl/HelloService.wsdl"
   xmlns:tns = "http://www.examples.com/wsdl/HelloService.wsdl"
   xmlns = "http://schemas.xmlsoap.org/wsdl/"
   xmlns:soap = "http://schemas.xmlsoap.org/wsdl/soap/"
   xmlns:xsd = "http://www.w3.org/2001/XMLSchema">
.
.
</definitions>
  • targetNamespace – is a convention of XML Schema that enables the WSDL document to refer to itself
  • xmlns:tns – When a complex object type is defined the targetnamespace could be used for deriving the way the object should be interpreted
    Refer Here
  • xmlns – Unique Identifier for xml elements
  • xmlns:soap – It should always have the value of: “http://www.w3.org/2003/05/soap-envelope/”.The namespace defines the Envelope as a SOAP Envelope.
    If a different namespace is used, the application generates an error and discards the message.
  • xmlns:xsd – XSD is XML Schema Definition Language. XSD files are used to validate that XML files conform to a certain format.Without XML Schema (XSD file) an XML file is a relatively free set of elements and attributes. The XSD file defines which elements and attributes are permitted and in which order. In SOAP, XSD tells how the Structure of Request and Response should be

What is use of xsi:schemalocation?
While developing Webservice XSD is the first file that is created. XSD contains data types that would be used in requests and responses. Once XSD is created Request and Response would be developed based on XSD. xsi:schemalocation is a tag used in response and request which helps in validating the datatype used conforms to one is XSD. In other words, it helps the IDE to keep a check by cross-checking elements defined in request and response are the same as one defined in XSD.

Q1:Difference between concrete wsdl and abstract wsdl
Typically a wsdl contains – types, Messages, porttype, Binding and service
Using Types ,messages and porttype we can’t do anything with that.. which is abstract part. Binding and service has more info about the webservices. So it’s concrete.abstract wsdl is enough to consume a soap service … If we use an abstract wsdl and if we try to generate classes we will not be able to see the java files and only class files can be obtained …
Concrete wsdl can provide complete details about the service…

It is not safe to provide the concrete wsdl to the consumer if he is not to be trusted ..
Please Refer Here

Q2:What is the Difference between SOAP and REST
Refer Here

Q3:What do you mean by Stateless in terms of RESTAPI?
The state of the client application is never stored on the server and is passed on. In this process, the client send all the information that is required for the server to fulfill the HTTP request and the server responds make with HTTP Response.The following are the advantages of Statelessness
HTTP protocol and REST web service, both shares the feature of statelessness. Every method required for communication is identified as an independent method i.e. there are no dependencies to other methods.Any previous communication with the client and server is not maintained and thus the whole process is very much simplified.If any information or metadata used earlier in required in another method, then the client sends again that information with HTTP request.

Q4:What is Resource in RESTApi? What is Resource Representation? Why its important?
‘Resource’ is defined as an object of a type which can be an image, HTML file, text data, and any type of dynamic data.JSON
YAML,XML,HTML are some of the Resource Types.Representation of Resource is important because it determines the easy identification of resources. With proper representations of resource in the proper format, allows the client to easily understand the format.

Q5:What is Caching?Use of Cache Control Header?
Caching is the process in which server response is stored so that a cached copy can be used when required and there is no need of generating the same response again. This process not only reduces the server load but in turn increase the scalability and performance of the server. Only the client is able to cache the response and that too for a limited period of time.

Cache control header can help in attaining cache ability.
Public: Resources that are marked as the public can be cached by any intermediate components(gateways) between the client and server.
Private: Resources that are marked as private can only be cached by the client.
No cache means that particular resource cannot be cached and thus the whole process is stopped.

Q6:What is Payload?
Request data which is present in the body part of every HTTP message is referred as ‘Payload’. In Restful web service, the payload can only be passed to the recipient through POST method.

Q7:Different HTTP methods
GET: This is a read only operation which fetches the list of users on the server.
PUT: This operation is used for the creation of any new resource on the server.
POST: This operation is used for updating an old resource or for creating a new resource.
DELETE: As the name suggests, this operation is used for deleting any resource on the server.
OPTIONS: This operation fetches the list of any supported options of resources that are available on the server.

Q8:What is the difference between PUT method and POST method?
PUT is idempotent, so if you PUT an object twice, it has no effect. You can update or create a resource with PUT with the same object URL.POST is to create new resource.If you are depending on server to create new resource using POST will result in multiple resource creation since server is the one which decides where to place the object. refer here

Q9:What is JAX-RS and what are its implementations?
JAX-RS is defined as the Java API for RESTful web service. Few of its implementations include Jersey,RESTEasy,Apache CFXPlay

Q10:What is use of OPTIONS and HEAD?
OPTIONS tells you things such as “What methods are allowed for this resource”.OPTIONS Identifying which HTTP methods a resource supports, e.g. can we DELETE it or update it via a PUT?OPTIONS method returns info about API (methods/content type)

HTTP/1.1 200 OK
Allow: GET,HEAD,POST,OPTIONS,TRACE
Content-Type: text/html; charset=UTF-8
Date: Wed, 08 May 2013 10:24:43 GMT
Content-Length: 0

HEAD Checking whether a resource has changed. This is useful when maintaining a cached version of a resource.Retrieving metadata about the resource, e.g. its media type or its size, before making a possibly costly retrieval.HEAD gets the HTTP header you would get if you made a GET request, but without the body. This lets the client determine caching information, what content-type would be returned, what status code would be returned.

HTTP/1.1 200 OK
Accept-Ranges: bytes
Content-Type: text/html; charset=UTF-8
Date: Wed, 08 May 2013 10:12:29 GMT
ETag: "780602-4f6-4db31b2978ec0"
Last-Modified: Thu, 25 Apr 2013 16:13:23 GMT
Content-Length: 1270

Q11.Maximum length of HTTP GET request?
The limit is dependent on both the server and the client.As already mentioned, HTTP itself doesn’t impose any hard-coded limit on request length; but browsers have limits ranging on the 2kb – 8kb .If the limit is exceeded in either the browser or the server, most will just truncate the characters outside the limit without any warning

HTTP 1.1 defines Status Code 414 Request-URI Too Long for the cases where a server-defined limit is reached which is usually configureable somewhere in the server configuration.For the case of client-defined limits, there is no sense on the server returning something, because the server won’t receive the request at all.

Q12.What is need for HttpMessageConverter?
Spring MVC uses HttpMessageConverter to convert the Http request to an object representation and back.Spring Framework then uses one of the Jackson message converters to marshall and unmarshall Java Objects to and from JSON over HTTP.Spring will use the “Accept” header to determine the media type that it needs to respond with and uses the “Content-Type” header to determine the media type of the request body.

Default Message Converters in Spring MVC
StringHttpMessageConverter: it converts Strings from the HTTP request and response.
FormHttpMessageConverter: it converts form data to/from a MultiValueMap.
ByteArrayHttpMessageConverter: it converts byte arrays from the HTTP request and response.
MappingJackson2HttpMessageConverter: it converts JSON from the HTTP request and response.
Jaxb2RootElementHttpMessageConverter: it converts Java objects to/from XML.
SourceHttpMessageConverter: it converts javax.xml.transform.Source from the HTTP request and response.
AtomFeedHttpMessageConverter: it converts Atom feeds.
RssChannelHttpMessageConverter: it converts RSS feeds.

@EnableWebMvc annotation, it automatically registered default Http message converters with application as listed above according to available library in the class path.

Q13.What is WS-Addressing?
WS-Addressing is useful in situations where the SOAP response can’t be served immediately. Either the resources to form the response are not available right away or the result itself takes a long time to be generated. There are times where your business takes time.something which needs manually intervention, something to be approved, whatever, but it takes days to do it. keeping the connection opened all that time and waiting for the response would be inefficient.notification process comes to rescue in these kind of scenarios.The client makes a requests but does not wait for the response. It instead instructs the server where to send the response by use of a “reply to” address. Once the response is available, the server connects to that address and sends the response.Instead of relying on network-level transport to convey routing information, a message utilizing WS-Addressing may contain its own dispatch metadata in a standardized SOAP header.WS-Addressing you are not tied to that. You can demand the response on another type of channel. Request comes on HTTP for example, but you can instruct the server to send the response back over SMTP, for example.

Q14.What is SOAP handler or handler Resolver ?
The handler framework in the Java API for XML Web Services (JAX-WS) allows applications to address cross-cutting and/or system-level concerns by opening the service and client runtimes for applications to plug in modular components. SOAP handler is a SOAP message interceptor, which is able to intercept incoming or outgoing SOAP message and manipulate its values. For example, attach a SOAP handler in client side, which will inject client’s computer MAC address into the SOAP header block for every outgoing SOAP message that is send by the client. In server side, attach another SOAP handler, to retrieve back the client’s MAC address in SOAP header block from every incoming SOAP message.This mechanism also allows the separation of the most fundamental concerns of application software in Web services development, effectively abstracting the system service into handlers and leaving the clients and services to focus on business logic.

JAX-WS specifies two types of handlers:

  1. Protocol handlers are specific to a protocol and may access or change the protocol-specific aspects of a message
  2. Logical handlers are protocol-agnostic and act only on the payload of a message

How XML Namespaces work?
Every element (or attribute) in XML belongs to a namespace, a way of “qualifying” the name of the element.Imagine you and I both invent our own XML. You invent XML to describe people, I invent mine to describe cities. Both of us include an element called name. Yours refers to the person’s name, and mine to the city name

<person>
    <name>Rob</name>
    <age>37</age>
    <homecity>
        <name>London</name>
        <lat>123.000</lat>
        <long>0.00</long>
    </homecity>
</person>

If our two XMLs were combined into a single document, how would we tell the two names apart? As you can see above, there are two name elements, but they both have different meanings.The answer is that you and I would both assign a namespace to our XML, which we would make unique:

<personxml:person xmlns:personxml="http://www.your.example.com/xml/person"
                  xmlns:cityxml="http://www.my.example.com/xml/cities">
    <personxml:name>Rob</personxml:name>
    <personxml:age>37</personxml:age>
    <cityxml:homecity>
        <cityxml:name>London</cityxml:name>
        <cityxml:lat>123.000</cityxml:lat>
        <cityxml:long>0.00</cityxml:long>
    </cityxml:homecity>
</personxml:person>

All of the tags that start with personxml: are tags belonging to your XML, all the ones that start with cityxml: are mine.

If you declare a namespace without the identifier, that is, xmlns=”http://somenamespace”, rather than xmlns:rob=”somenamespace”, it specifies the default namespace for the document.

SOAP(Simple Object Access Protocol) – SOAP is an XML-based protocol that lets you exchange info over a particular protocol (can be HTTP or SMTP, for example) between applications. It stands for Simple Object Access Protocol and uses XML for its messaging format to relay the information.

WSDL(Web Services Definition Language) – A WSDL is an XML document that describes a web service. WSDL tells about the functions that you can implement or exposed to the client. For example: add, delete, subtract, and so on. what is the service called, which methods does it offer, what kind of in parameters and return values do these methods have?

XSD(XML Schema Definition) – describes the static structure of the complex data types being exchanged by those service methods. It describes the types, their fields, any restriction on those fields (like max length or a regex pattern), and so forth.It’s a description of datatypes and thus static properties of the service – it’s about data.

XSD definitions are part of WSDL in the tag

UDDI(Universal Description, Discovery, and Integration)– It is directly that is used to publish and discover public web services. UDDI is an obsolete failure that is almost never used in practice.UDDI works just like a telephone directory where a business can be registered as per its name, geography and the web services it publishes.UDDI registers the WSDL address URL of a web service. A client of the web service searches and finds the WSDL in the UDDI registry. Once received the WSDL can be invoked by using the URL.

WSDL: When we go to a restaurant we see the Menu Items, those are the WSDL’s.
Proxy Classes: Now after seeing the Menu Items we make up our Mind (Process our mind on what to order): So, basically we make Proxy classes based on WSDL Document.
SOAP: Then when we actually order the food based on the Menu’s: Meaning we use proxy classes to call upon the service methods which is done using SOAP

SEI(service endpoint interface): The endpoint is a connection point where HTML files or active server pages are exposed. A web service endpoint is a URL that another program would use to communicate with your program. To see the WSDL, you add WSDL to the web service endpoint URL.

Parts of WSDL
Definitions – variables – ex: myVar, x, y, etc.

Types – data types – ex: int, double, String, myObjectType

Operations – methods/functions – ex: myMethod(), myFunction(), etc.

Messages – method/function input parameters & return types

ex: public myObjectType myMethod(String myVar)
Porttypes – classes (i.e. they are a container for operations) – ex: MyClass{}, etc.

Example of a Endpoint URL

protocol://host:port/partOfThePath

where

host=someIp
port=8080
partOfThePath=/some/service/path

serviceAEndpoint=http://host:port/some/service/path?dynamicParam=

Simple SOAP Request and Response

 package com.mugil.org;

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

import javax.jws.WebService;

@WebService
public class Products 
{
  List<String> arrProducts = new ArrayList<String>();
	
  public Products()
  {
	arrProducts.add("Books");
	arrProducts.add("EReader");
	arrProducts.add("PDF");	
  }
  
  public String getProduct(int index)
  {
	return arrProducts.get(index);  
  }
}

SOAP Request

<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:org="http://org.mugil.com/">
   <soapenv:Header/>
   <soapenv:Body>
 
      <org:getProduct>
         <arg0>0</arg0>
      </org:getProduct>
   </soapenv:Body>
</soapenv:Envelope>

SOAP Request

<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
   <soap:Body>
      <ns2:getProductResponse xmlns:ns2="http://org.mugil.com/">
         <return>Books</return>
      </ns2:getProductResponse>
   </soap:Body>
</soap:Envelope>

Part of WSDL
Typical WSDL document contains the following tags

  1. service – Contains the port which defines the Endpoint URL, port number
  2. portType – Contains input and output for an operation.Though there are multiple input and output arguments they would be bundled together as one message
  3. binding – Defines how the SOAP service could be accessed like over http,https
  4. types – Type defined as complex type defines the Input and output
  5. message – Kind of input and output taken as argument, mostly represented as Message

Service

 <wsdl:service name="ProductsService">
  <wsdl:port binding="tns:ProductsServiceSoapBinding" name="ProductsPort">
   <soap:address location="http://localhost:8096/WebService1/Products"/>
  </wsdl:port>
  </wsdl:service>

Porttype

 <wsdl:portType name="Products">
   <wsdl:operation name="getProduct">
    <wsdl:input message="tns:getProduct" name="getProduct"></wsdl:input>
    <wsdl:output message="tns:getProductResponse" name="getProductResponse"></wsdl:output>
   </wsdl:operation>
  </wsdl:portType>

Binding

<wsdl:binding name="ProductsServiceSoapBinding" type="tns:Products">
      <soap:binding style="document" transport="http://schemas.xmlsoap.org/soap/http" />
      <wsdl:operation name="getProduct">
         <soap:operation soapAction="" style="document" />
         <wsdl:input name="getProduct">
            <soap:body use="literal" />
         </wsdl:input>
         <wsdl:output name="getProductResponse">
            <soap:body use="literal" />
         </wsdl:output>
      </wsdl:operation>
   </wsdl:binding>

Types

 <wsdl:types>
      <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" elementFormDefault="unqualified" targetNamespace="http://org.mugil.com/" version="1.0">
         <xs:element name="getProduct" type="tns:getProduct" />
         <xs:element name="getProductResponse" type="tns:getProductResponse" />
         <xs:complexType name="getProduct">
            <xs:sequence>
               <xs:element name="arg0" type="xs:int" />
            </xs:sequence>
         </xs:complexType>
         <xs:complexType name="getProductResponse">
            <xs:sequence>
               <xs:element minOccurs="0" name="return" type="xs:string" />
            </xs:sequence>
         </xs:complexType>
      </xs:schema>

Message

 <wsdl:message name="getProduct">
      <wsdl:part element="tns:getProduct" name="parameters" />
   </wsdl:message>
   <wsdl:message name="getProductResponse">
      <wsdl:part element="tns:getProductResponse" name="parameters" />
   </wsdl:message>

Service(Class name with @WebService Annotation) 
                | 
Port(has Binding which defines portType)
                | 
    PortType(defines Operations)
                | 
Operations(defines input and output Type)

Annotations for WebService

@Webservice(name="MartCatalogue", portName="MartCataloguePort", serviceName="ProductsService", targetNamespace="MartProducts.com")
.
.
@WebMethod(action="fetch_products", operationName="fetchProducts")
.

name

<wsdl:portType name="MartCatalogue">
.
.

portName and serviceName

wsdl:port binding="tns:productServiceSoapBinding" name="productPort">
  <soap:address location="http://localhost:8096/WebService1/productService"/>
</wsdl:port>
.
.

targetNamespace
Defines unique set of operations under namespace.Defaults to package name in java in reverse order
targetNamespace=”MartProducts.com”

targetNamespace

<wsdl:operation name="fetchProducts">
.
.
 <wsdl:operation name="fetchProducts">
      <soap:operation soapAction="fetch_products" style="document" />
  .
  .