Thursday, 10 May 2018

Java Interview Quetions on Web Services


What is an XML Schema?
An XML Schema describes the structure of an XML document. The purpose of an XML Schema is to define the legal building blocks of an XML document:
  • the elements and attributes that can appear in a document
  • the number of (and order of) child elements
  • data types for elements and attributes
  • default and fixed values for elements and attributes
WSDL
WSDL stands for Web Services Description Language. It is the standard format for describing a web service. WSDL was developed jointly by Microsoft and IBM.

Features of WSDL

·   WSDL is an XML-based protocol for information exchange in decentralized and distributed environments.
·     WSDL definitions describe how to access a web service and what operations it will perform.
·        WSDL is a language for describing how to interface with XML-based services.
·      WSDL is an integral part of Universal Description, Discovery, and Integration (UDDI), an XML-based worldwide business registry.
·        WSDL is the language that UDDI uses.

WSDL Elements

A WSDL document contains the following elements −
·     Definition − It is the root element of all WSDL documents. It defines the name of the web service, declares multiple namespaces used throughout the remainder of the document, and contains all the service elements described here.
·     Data types − The data types to be used in the messages are in the form of XML schemas.
·    Message − It is an abstract definition of the data, in the form of a message presented either as an entire document or as arguments to be mapped to a method invocation.
·        Operation − It is the abstract definition of the operation for a message, such as naming a method, message queue, or business process, that will accept and process the message.
·        Port type − It is an abstract set of operations mapped to one or more end-points, defining the collection of operations for a binding; the collection of operations, as it is abstract, can be mapped to multiple transports through various bindings.
·     Binding − It is the concrete protocol and data formats for the operations and messages defined for a particular port type.
·        Port − It is a combination of a binding and a network address, providing the target address of the service communication.
·     Service − It is a collection of related end-points encompassing the service definitions in the file; the services map the binding to the port and include any extensibility definitions.
In addition to these major elements, the WSDL specification also defines the following utility elements −
·        Documentation − This element is used to provide human-readable documentation and can be included inside any other WSDL element.
·        Import − This element is used to import other WSDL documents or XML Schemas.

The <portType> Element
The <portType> element defines a web service, the operations that can be performed, and the messages that are involved.The request-response type is the most common operation type, but WSDL defines four types:
Type Definition
One-way    The operation can receive a message but will not return a response
Request-response        The operation can receive a request and will return a response
Solicit-response  The operation can send a request and will wait for a response
Notification         The operation can send a message but will not wait for a response



A web service needs to define its inputs and outputs and how they are mapped into and out of the services. WSDL <types> element takes care of defining the data types that are used by the web service. Types are XML documents, or document parts.
·        The types element describes all the data types used between the client and the server.
·        WSDL is not tied exclusively to a specific typing system.
·        WSDL uses the W3C XML Schema specification as its default choice to define data types.
·        If the service uses only XML Schema built-in simple types, such as strings and integers, then types element is not required.
·        WSDL allows the types to be defined in separate elements so that the types are reusable with multiple web services.

The <message> element describes the data being exchanged between the web service providers and the consumers.
·        Each Web Service has two messages: input and output.
·        The input describes the parameters for the web service and the output describes the return data from the web service.
·        Each message contains zero or more <part> parameters, one for each parameter of the web service function.
·        Each <part> parameter associates with a concrete type defined in the <types> container element.
The <binding> element provides specific details on how a portType operation will actually be transmitted over the wire.
·        The bindings can be made available via multiple transports including HTTP GET, HTTP POST, or SOAP.
·        The bindings provide concrete information on what protocol is being used to transfer portType operations.
·        The bindings provide information where the service is located.
·        For SOAP protocol, the binding is <soap:binding>, and the transport is SOAP messages on top of HTTP protocol.
·        You can specify multiple bindings for a single portType.
The binding element has two attributes : name and type attribute.
<binding name = "Hello_Binding" type = "tns:Hello_PortType">
The name attribute defines the name of the binding, and the type attribute points to the port for the binding, in this case the "tns:Hello_PortType" port.
·        The port element has two attributes: name and binding .
·        The name attribute provides a unique name among all ports defined within the enclosing WSDL document.
·        The binding attribute refers to the binding using the linking rules defined by WSDL.
·        Binding extensibility elements are used to specify the address information for the port.
·        A port MUST NOT specify more than one address.
·        A port MUST NOT specify any binding information other than address information.
The <service> element defines the ports supported by the web service. For each of the supported protocols, there is one port element. The service element is a collection of ports.
·        Web service clients can learn the following from the service element −
    • where to access the service,
    • through which port to access the web service, and
    • how the communication messages are defined.
·        The service element includes a documentation element to provide human-readable documentation.





Basic parts of WSDL


WSDL

Web Services

Web services are open standard (XML, SOAP, HTTP, etc.) Web applications that interact with other Web applications for the purpose of exchanging data.
To learn more about Web Services, visit Web Services Tutorial.

UDDI

UDDI is an XML-based standard for describing, publishing, and finding Web services.
To learn more about UDDI, visit UDDI Tutorial.

SOAP

SOAP is a simple XML-based protocol that allows applications to exchange information over HTTP.

What is JSON

JSON is an open standard for exchanging data on the web. It supports data structures like object and array. So it is easy to write and read data from JSON.

  • JSON stands for JavaScript Object Notation.
  • JSON is lightweight data-interchange format.
  • JSON is easy to read and write than XML.
  • JSON is language independent.
  • JSON supports array, object, string, number and values.
  • JSON supports data structures such as array and objects.

Features of JSON

  1. Simplicity
  2. Openness
  3. Self Describing
  4. Internationalization
  5. Extensibility
  6. Interoperability
No.
JSON
XML
1)
JSON stands for JavaScript Object Notation.
XML stands for eXtensible Markup Language.
2)
JSON is simple to read and write.
XML is less simple than JSON.
3)
JSON is easy to learn.
XML is less easy than JSON.
4)
JSON is data-oriented.
XML is document-oriented.
5)
JSON doesn't provide display capabilities.
XML provides the capability to display data because it is a markup language.
6)
JSON supports array.
XML doesn't support array.
7)
JSON is less secured than XML.
XML is more secured.
9)
JSON supports only text and number data type.
XML support many data types such as text, number, images, charts, graphs etc. Moreover, XML offeres options for transferring the format or structure of the data with actual data.


  enter image description here

REST(REpresentational State Transfer)
REST is an architectural style. It doesn’t define so many standards like SOAP. REST is for exposing Public APIs(i.e. Facebook API, Google Maps API) over the internet to handle CRUD operations on data. REST is focused on accessing named resources through a single consistent interface.

SOAP(Simple Object Access Protocol)
SOAP brings its own protocol and focuses on exposing pieces of application logic (not data) as services. SOAP exposes operations. SOAP is focused on accessing named operations, each operation implement some business logic. Though SOAP is commonly referred to as 
web servicesthis is misnomer. SOAP has a very little if anything to do with the Web. REST provides true Web services based on URIs and HTTP.

Why REST?
·         Since REST uses standard HTTP it is much simpler in just about ever way.
·         REST is easier to implement, requires less bandwidth and resources.
·         REST permits many different data formats where as SOAP only permits XML.
·         REST allows better support for browser clients due to its support for JSON.
·         REST has better performance and scalability. REST reads can be cached, SOAP based reads cannot be cached.
·         If security is not a major concern and we have limited resources. Or we want to create an API that will be easily used by other developers publicly then we should go with REST.
·         If we need Stateless CRUD operations then go with REST.
·         REST is commonly used in social media, web chat, mobile services and Public APIs like Google Maps.

Why SOAP?
·         SOAP is not very easy to implement and requires more bandwidth and resources.
·         SOAP message request is processed slower as compared to REST and it does not use web caching mechanism.
·         WS-Security: While SOAP supports SSL (just like REST) it also supports WS-Security which adds some enterprise security features.
·         WS-AtomicTransaction: Need ACID Transactions over a service, you’re going to need SOAP.
·         WS-ReliableMessaging: If your application needs Asynchronous processing and a guaranteed level of reliability and security. Rest doesn’t have a standard messaging system and expects clients to deal with communication failures by retrying.
·         If the security is a major concern and the resources are not limited then we should use SOAP web services. Like if we are creating a web service for payment gateways, financial and telecommunication related work then we should go with SOAP as here high security is needed.




Stateless meaning:
It does not keep track of configuration settings, transaction information or any other data for the next session. When a program "does not maintain state" (is stateless) or when the infrastructure of a system prevents a program from maintaining state, it cannot take information about the last session into the next, such as settings the user chose or conditions that arose during processing.
HTTP:
The HTTP protocol, which is the communications vehicle for Web transactions, is stateless. After a Web page is delivered to the user, the connection is closed. Counter measures, such as the use of cookies, have been developed to maintain the state of a user moving from page to page on a Web site.

Spring Annotations

Core Spring Framework Annotations

@Required

This annotation is applied on bean setter methods. Consider a scenario where you need to enforce a required property. The @Required annotation indicates that the affected bean must be populated at configuration time with the required property. Otherwise an exception of type BeanInitializationException is thrown.

@Autowired

This annotation is applied on fields, setter methods, and constructors. The @Autowired annotation injects object dependency implicitly.
When you use @Autowired on fields and pass the values for the fields using the property name, Spring will automatically assign the fields with the passed values.
When you use @Autowired on setter methods, Spring tries to perform the by Type autowiring on the method. You are instructing Spring that it should initiate this property using setter method where you can add your custom code, like initializing any other property with this property.

Consider a scenario where you need instance of class A, but you do not store A in the field of the class. You just use A to obtain instance of B, and you are storing B in this field. In this case setter method autowiring will better suite you. You will not have class level unused fields.
When you use @Autowired on a constructor, constructor injection happens at the time of object creation. It indicates the constructor to autowire when used as a bean. One thing to note here is that only one constructor of any bean class can carry the @Autowired annotation.

@Qualifier

This annotation is used along with @Autowired annotation. When you need more control of the dependency injection process, @Qualifier can be used. @Qualifier can be specified on individual constructor arguments or method parameters. This annotation is used to avoid confusion which occurs when you create more than one bean of the same type and want to wire only one of them with a property.

@Configuration

This annotation is used on classes which define beans. @Configuration is an analog for XML configuration file – it is configuration using Java class. Java class annotated with @Configuration is a configuration by itself and will have methods to instantiate and configure the dependencies.

@ComponentScan

This annotation is used with @Configuration annotation to allow Spring to know the packages to scan for annotated components. @ComponentScan is also used to specify base packages using basePackageClasses orbasePackage attributes to scan. If specific packages are not defined, scanning will occur from the package of the class that declares this annotation.
Checkout this post for an in depth look at the Component Scan annotation.

@Bean

This annotation is used at the method level. @Bean annotation works with @Configuration to create Spring beans. As mentioned earlier, @Configuration will have methods to instantiate and configure dependencies. Such methods will be annotated with @Bean. The method annotated with this annotation works as bean ID and it creates and returns the actual bean.
Here is an example:

@Lazy

This annotation is used on component classes. By default all autowired dependencies are created and configured at startup. But if you want to initialize a bean lazily, you can use @Lazy annotation over the class. This means that the bean will be created and initialized only when it is first requested for. You can also use this annotation on @Configuration classes. This indicates that all @Bean methods within that @Configuration should be lazily initialized.

@Value

This annotation is used at the field, constructor parameter, and method parameter level. The @Value annotation indicates a default value expression for the field or parameter to initialize the property with. As the @Autowiredannotation tells Spring to inject object into another when it loads your application context, you can also use@Value annotation to inject values from a property file into a bean’s attribute. It supports both #{...} and${...} placeholders.

Spring Framework Stereotype Annotations

@Component

This annotation is used on classes to indicate a Spring component. The @Component annotation marks the Java class as a bean or say component so that the component-scanning mechanism of Spring can add into the application context.

@Controller

The @Controller  annotation is used to indicate the class is a Spring controller. This annotation can be used to identify controllers for Spring MVC or Spring WebFlux.

@Service

This annotation is used on a class. The @Service marks a Java class that performs some service, such as execute business logic, perform calculations and call external APIs. This annotation is a specialized form of the@Component annotation intended to be used in the service layer.

@Repository

This annotation is used on Java classes which directly access the database. The @Repository annotation works as marker for any class that fulfills the role of repository or Data Access Object. This annotation has a automatic translation feature. For example, when an exception occurs in the @Repositorythere is a handler for that exception and there is no need to add a try catch block.

Spring MVC and REST Annotations

@Controller

This annotation is used on Java classes that play the role of controller in your application. The @Controllerannotation allows autodetection of component classes in the classpath and auto-registering bean definitions for them. To enable autodetection of such annotated controllers, you can add component scanning to your configuration. The Java class annotated with @Controller is capable of handling multiple request mappings.
This annotation can be used with Spring MVC and Spring WebFlux.

@RequestMapping

This annotation is used both at class and method level. The @RequestMapping annotation is used to map web requests onto specific handler classes and handler methods. When @RequestMapping is used on class level it creates a base URI for which the controller will be used. When this annotation is used on methods it will give you the URI on which the handler methods will be executed. From this you can infer that the class level request mapping will remain the same whereas each handler method will have their own request mapping.
Sometimes you may want to perform different operations based on the HTTP method used, even though the request URI may remain the same. In such situations, you can use the method attribute of @RequestMapping with an HTTP method value to narrow down the HTTP methods in order to invoke the methods of your class.
Here is a basic example on how a controller along with request mappings work:

@CookieValue

This annotation is used at method parameter level. @CookieValue is used as argument of request mapping method. The HTTP cookie is bound to the @CookieValue parameter for a given cookie name. This annotation is used in the method annotated with @RequestMapping.
Let us consider that the following cookie value is received with a http request:
JSESSIONID=418AB76CD83EF94U85YD34W
To get the value of the cookie, use @CookieValue like this:

@CrossOrigin

This annotation is used both at class and method level to enable cross origin requests. In many cases the host that serves JavaScript will be different from the host that serves the data. In such a case Cross Origin Resource Sharing (CORS) enables cross-domain communication. To enable this communication you just need to add the@CrossOrigin annotation.
By default the @CrossOrigin annotation allows all origin, all headers, the HTTP methods specified in the@RequestMapping annotation and maxAge of 30 min. You can customize the behavior by specifying the corresponding attribute values.
An example to use @CrossOrigin at both controller and handler method levels is this.

@GetMapping

This annotation is used for mapping HTTP GET requests onto specific handler methods. @GetMapping is a composed annotation that acts as a shortcut for @RequestMapping(method = RequestMethod.GET)

@PostMapping

This annotation is used for mapping HTTP POST requests onto specific handler methods. @PostMapping is a composed annotation that acts as a shortcut for @RequestMapping(method = RequestMethod.POST)

@PutMapping

This annotation is used for mapping HTTP PUT requests onto specific handler methods. @PutMapping is a composed annotation that acts as a shortcut for @RequestMapping(method = RequestMethod.PUT)

@PatchMapping

This annotation is used for mapping HTTP PATCH requests onto specific handler methods. @PatchMapping is a composed annotation that acts as a shortcut for @RequestMapping(method = RequestMethod.PATCH)

@DeleteMapping

This annotation is used for mapping HTTP DELETE requests onto specific handler methods. @DeleteMapping is a composed annotation that acts as a shortcut for @RequestMapping(method = RequestMethod.DELETE)

@ExceptionHandler

This annotation is used at method levels to handle exception at the controller level. The @ExceptionHandlerannotation is used to define the class of exception it will catch. You can use this annotation on methods that should be invoked to handle an exception. The @ExceptionHandler values can be set to an array of Exception types. If an exception is thrown that matches one of the types in the list, then the method annotated with matching @ExceptionHandler will be invoked.

@InitBinder

This annotation is a method level annotation that plays the role of identifying the methods which initialize theWebDataBinder - a DataBinder that binds the request parameter to JavaBean objects. To customise request parameter data binding , you can use @InitBinder annotated methods within our controller. The methods annotated with @InitBinder all argument types that handler methods support.
The 
@InitBinder annotated methods will get called for each HTTP request if you don’t specify the value element of this annotation. The value element can be a single or multiple form names or request parameters that the init binder method is applied to.

@Mappings and @Mapping

This annotation is used on fields. The @Mapping annotation is a meta annotation that indicates a web mapping annotation. When mapping different field names, you need to configure the source field to its target field and to do that you have to add the @Mappings annotation. This annotation accepts an array of @Mapping having the source and the target fields.

@MatrixVariable

This annotation is used to annotate request handler method arguments so that Spring can inject the relevant bits of matrix URI. Matrix variables can appear on any segment each separated by a semicolon. If a URL contains matrix variables, the request mapping pattern must represent them with a URI template. The@MatrixVariable annotation ensures that the request is matched with the correct matrix variables of the URI.

@PathVariable

This annotation is used to annotate request handler method arguments. The @RequestMapping annotation can be used to handle dynamic changes in the URI where certain URI value acts as a parameter. You can specify this parameter using a regular expression. The @PathVariable annotation can be used declare this parameter.

@RequestAttribute

This annotation is used to bind the request attribute to a handler method parameter. Spring retrieves the named attributes value to populate the parameter annotated with @RequestAttribute. While the @RequestParamannotation is used bind the parameter values from query string, the @RequestAttribute is used to access the objects which have been populated on the server side.

@RequestBody

This annotation is used to annotate request handler method arguments. The @RequestBody annotation indicates that a method parameter should be bound to the value of the HTTP request body. The HttpMessageConveter is responsible for converting from the HTTP request message to object.

@RequestHeader 02065414444

This annotation is used to annotate request handler method arguments. The @RequestHeader annotation is used to map controller parameter to request header value. When Spring maps the request, @RequestHeader checks the header with the name specified within the annotation and binds its value to the handler method parameter. This annotation helps you to get the header details within the controller class.

@RequestParam

This annotation is used to annotate request handler method arguments. Sometimes you get the parameters in the request URL, mostly in GET requests. In that case, along with the @RequestMapping annotation you can use the @RequestParam annotation to retrieve the URL parameter and map it to the method argument. The@RequestParam annotation is used to bind request parameters to a method parameter in your controller.

@RequestPart

This annotation is used to annotate request handler method arguments. The @RequestPart annotation can be used instead of @RequestParam to get the content of a specific multipart and bind to the method argument annotated with @RequestPart. This annotation takes into consideration the “Content-Type” header in the multipart(request part).

@ResponseBody

This annotation is used to annotate request handler methods. The @ResponseBody annotation is similar to the@RequestBody annotation. The @ResponseBody annotation indicates that the result type should be written straight in the response body in whatever format you specify like JSON or XML. Spring converts the returned object into a response body by using the HttpMessageConveter.

@ResponseStatus

This annotation is used on methods and exception classes. @ResponseStatus marks a method or exception class with a status code and a reason that must be returned. When the handler method is invoked the status code is set to the HTTP response which overrides the status information provided by any other means. A controller class can also be annotated with @ResponseStatus which is then inherited by all @RequestMapping methods.

@ControllerAdvice

This annotation is applied at the class level. As explained earlier, for each controller you can use@ExceptionHandler on a method that will be called when a given exception occurs. But this handles only those exception that occur within the controller in which it is defined. To overcome this problem you can now use the@ControllerAdvice annotation. This annotation is used to define @ExceptionHandler@InitBinder and@ModelAttribute methods that apply to all @RequestMapping methods. Thus if you define the @ExceptionHandlerannotation on a method in @ControllerAdvice class, it will be applied to all the controllers.

@RestController

This annotation is used at the class level. The @RestController annotation marks the class as a controller where every method returns a domain object instead of a view. By annotating a class with this annotation you no longer need to add @ResponseBody to all the RequestMapping method. It means that you no more use view-resolvers or send html in response. You just send the domain object as HTTP response in the format that is understood by the consumers like JSON.@RestController  is a convenience annotation which combines @Controller  and @ResponseBody .

@RestControllerAdvice

This annotation is applied on Java classes. @RestControllerAdvice is a convenience annotation which combines @ControllerAdvice and @ResponseBody. This annotation is used along with the @ExceptionHandler annotation to handle exceptions that occur within the controller.

@SessionAttribute

This annotation is used at method parameter level. The @SessionAttribute annotation is used to bind the method parameter to a session attribute. This annotation provides a convenient access to the existing or permanent session attributes.

@SessionAttributes

This annotation is applied at type level for a specific handler. The @SessionAtrributes annotation is used when you want to add a JavaBean object into a session. This is used when you want to keep the object in session for short lived. @SessionAttributes is used in conjunction with @ModelAttribute.
Consider this example. The 
@ModelAttribute name is assigned to the @SessionAttributes as value. The @SessionAttributes has two elements. The value element is the name of the session in the model and the types element is the type of session attributes in the model.

Spring Framework DataAccess Annotations

@Transactional

This annotation is placed before an interface definition, a method on an interface, a class definition, or a public method on a class. The mere presence of @Transactional is not enough to activate the transactional behaviour. The @Transactional is simply a metadata that can be consumed by some runtime infrastructure. This infrastructure uses the metadata to configure the appropriate beans with transactional behaviour.
The annotation further supports configuration like:
·         The Propagation type of the transaction
·         The Isolation level of the transaction
·         A timeout for the operation wrapped by the transaction
·         A read only flag - a hint for the persistence provider that the transaction must be read only
The rollback rules for the transaction

No comments:

Post a Comment