Tuesday, May 5, 2020

Spring Rest Services and Microservices

Q Why should we handle response time out while calling Rest End point?
  • When we connect to server those connections are made with the help of threads. If a connection has not been established so thread will be blocked. So we will be having multiple blocked threads for each request since server is not responding. To avoid this situation and to release the threads we have to do a time out.
  • All these threads are available in thread pool in a server.
Q What is the difference between read time out and server time out?
  • Server timeout is when we are unable to establish a connection to the server.
  • Read time out happens when we are able to connect to server but unable to read the data that is we are not getting response back.
Q What is versioning in Rest?
  • When we update functionality in Rest and want user to use new one instead of old obsolete one.
  • We use versioning to mark these two different versions of functionality.
  • Versioning can be defined using.
    • Request parameters
      • @GetMapping(value="/courses", params="ver=2")
    • Headers
      • @GetMapping(value="/courses", headers="api-version=2")
    • Produces
      • @GetMapping(value="/courses", produces="application/version2+json")
    • URI
      • @GetMapping(value="/courses/v2")
Q How does basic authentication work in rest API?
  • We do it using SecurityConfiguration class in the API which extends to WebSecurityConfigurationAdapter.
  • When we hit the request it goes to AuthenticationFilter. The filter gives us an authentication object. This object is passed to AuthenticationManagerBuilder which will find the AuthenticationProvider. This provider will validate an authentication object.
  • There are various authentication providers like
    • DaoAuthenticationProvider
    • We can have our own custom authentication object provider.
  • This AuthenticationProvider will pass object to AuthenticationManagerBuilder. The builder will further pass the object to the SecurityContextHolder.
  • So SecurityContextHolder holds the SecurityContext object so when user signs in next time it won't ask for security credentials. It will check authentication credentials from the SecurityContextHolder itself. It will allow user to sign in without any credentials.
  • For authentication we can pass jwt authentication token in the headers which is used for authentication whenever we are giving call to the micro service.
    • This token is authenticated by the server.
    • This is called as token based authentication.
Q Which is better jwt based authentication or session based authentication?
  • Token based authentication should be followed in rest API's because those are stateless.
    • The server does not stores state of client side. Client sends all the information in the header so that server is able to process that request.
    • The client will give us a jwt token in every server we will have our public key or private key using which we will verify signature of the token and we will validate the token.
    • When we use basic token based authorization in the "Authorization Header" of the request we send "basic encoded_token_value".
      • Basic is the key word for basic authentication.
    • When we use jwt authentication we are writing bearar in place of basic which implies that we don't have any responsibility as a provider as we are using clients token. There is no further authentication needed once we have that token we are the owner of the token. The token has been generated after authentication with server.
      • jwt token is used for authorization of user and not authentication. Because the user who has jwt token is already authenticated.
  • Session based authentication is restricted to the particular session only. So if we hit a request do another system then that system won't recognize our session.
    • We may have many servers/instances running in microservices environment as we scale up our application.
    • Since session is limited to a server we can't use such an authentication in such a architecture.
Q What is content negotiation?
  • Content negotiation is what kind of requests should the API accept and what kind of response should API provide.
  • It is achieved by media type class in produces or consumes parameter of @Getmapping annotation as follows.
    • @GetMapping(value="/courses", consumes={MediaType.Application_XML_value}, produces={MediaType.Application_Json_Value})
Q What is the difference between @EnableDiscoveryClient and @EnableEurekaClient?

Ans
@EnableDiscoveryClient
  • This annotation is based onspring-cloud-commonsDependent and implemented in the classpath
  • If it is another registration center like (consul, zookeeper) then Eureka, @EnableDiscoveryClient is recommended

@EnableEurekaClient
  • The annotation is based onspring-cloud-netflixDependence can only be used for eureka;
  • if the registered center is eureka, then @EnableEurekaClient is recommended
Q Give some Examples of the different Rest Clients?
  • RestTemplate
  • OpenFin
Q How are rest templates used in a Project?
  • Rest Templates act as a client for consuming our Rest Data by hitting a url.
  • The url may send response in xml or json.
  • Example of Rest Template is
    • ProductDto productDto=restTemplate.getForObject(url,ProductDto.class,id);
  • Here ProductDto will be class with data members as same as what response is returned from url.
Q What is the difference between getForEntity() and getForObject()
  • Both methods belong to Rest Template
    • getForObject will only return an object i.e. response Object.
    • getForEntity will return a response Entity.
  • In getForEntity we also get values like statusCode(),getBody(),getHeaders().
  • We also have exchange() method to get Rest values.
Q What are the uses of Response Entity?
  • Using response Entity we can send the appropriate http status, response body, response headers.
  • For Example
    • return ResponseEntity.status(HTTPStatus.Accepted).body(restObject)
Q When an object is deleted and access is made what status code should we return?
  • Content not Found i.e. 204 we can return 200 too.


Friday, July 19, 2019

Spring IOC

What are the 2 types of Spring IOC containers?
  • Bean Factory
  • Application Context
What is the difference between bean factory and application context?
  • The spring framework comes with two IOC containers, bean factory and application context.
  • Bean factory is the most basic version of IOC container, and the application context extends the bean factory.
  • The application context comes with Advance features, including several that a gear towards enterprise applications while the bean factory comes with only basic features. Therefore, it is generally recommended to use application context and we should use bean factory only when memory consumption is critical.
  • Application context is an interface we can use its Implementation for creating objects in spring.
  • We can configure beans using XML,annotation and Java configuration file.

Sunday, June 9, 2019

Creating Custom Error Page in Spring MVC

Its always a good Practice to create a custom Error Page which can be shown to client to handle errors such as "Page Not Found" or even "Internal Server Error"

We have created a controller which does the exactly same work.We have not created any views here which you can create in your views location with name "error.jsp" or "error.html" or as you have configured your view resolver.

Here is the file you can add to your Controllers.

ExceptionHandling.java
 package com.springimplant.mvc.controllers;  
 import javax.servlet.http.HttpServletRequest;  
 import javax.servlet.http.HttpServletResponse;  
 import org.springframework.core.annotation.AnnotationUtils;  
 import org.springframework.http.HttpStatus;  
 import org.springframework.stereotype.Controller;  
 import org.springframework.web.bind.annotation.ControllerAdvice;  
 import org.springframework.web.bind.annotation.ExceptionHandler;  
 import org.springframework.web.bind.annotation.RequestMapping;  
 import org.springframework.web.bind.annotation.ResponseStatus;  
 import org.springframework.web.servlet.ModelAndView;  
 @Controller  
 @ControllerAdvice  
 public class ExceptionHandling {  
      @ExceptionHandler(Exception.class)  
      public ModelAndView exceptionHandler(final HttpServletRequest request,final HttpServletResponse response,final Exception ex)  
      {  
           // If exception has a ResponseStatus annotation then use its response code  
           ResponseStatus responseStatusAnnotation = AnnotationUtils.findAnnotation(ex.getClass(), ResponseStatus.class);  
           return buildModelAndViewErrorPage(request, response, ex,responseStatusAnnotation != null ? responseStatusAnnotation.value() : HttpStatus.INTERNAL_SERVER_ERROR);  
      }  
      @RequestMapping("*")  
      public ModelAndView fallbackHandler(final HttpServletRequest request, final HttpServletResponse response) throws Exception {  
           return buildModelAndViewErrorPage(request, response, null, HttpStatus.NOT_FOUND);  
      }  
      private ModelAndView buildModelAndViewErrorPage(final HttpServletRequest request,final HttpServletResponse response,final Exception ex,final HttpStatus httpStatus) {  
           response.setStatus(httpStatus.value());  
           ModelAndView mav=new ModelAndView("error");  
           if(ex!=null)  
           {  
                mav.addObject("title",ex);  
           }  
           mav.addObject("content",request.getRequestURL());  
           return mav;  
      }  
 }  

Thursday, June 6, 2019

Generating War file from Eclipse

  • In pom.xml from overview tab select packaging as war.
  • Next we need to add plugin to POM.xml
    • Right click on Pom.xml or Project =>select Maven=>select Add Plugin
    • Search for "maven-war-plugin" and add that plugin to pom.xml
  • Next if you don't have a web.xml file in your project to deploy i.e. it has been bootstrapped via java base classes add the following configuration
    •      <configuration>  
                 <failOnMissingWebXml>false</failOnMissingWebXml>  
           </configuration>
  • Right click on project and select Run as Maven Install.
Code to be added to Pom.xml
  <packaging>war</packaging>  
  <name>SpringMVCRestful</name>  
  <build>  
       <plugins>  
            <plugin>  
                 <groupId>org.apache.maven.plugins</groupId>  
                 <artifactId>maven-war-plugin</artifactId>  
                 <version>3.2.3</version>  
                  <configuration>  
                       <failOnMissingWebXml>false</failOnMissingWebXml>  
                  </configuration>  
            </plugin>  
       </plugins>  
  </build>  

*remove configuration from code if you are using web.xml for Bootstrapping

How do we Bootstrap via Java base classes not using web.xml

  • Create a class that extends "AbstractAnnotationConfigDispatcherServletInitializer".
    • This class will be instantiated when tomcat starts.
  • There are three abstract methods in this class
    • getRootConfigClasses()
      • Used to create Root Application Context such as Dispatcher Servlet
    • getServletConfigClasses()
      • Used to create Servlet Application Context.
    • getServletMappings()
      • Used to create URL Mappings for a servlet.
SimpleWebAppInitializer
 package com.springimplant.mvc.config;  
 import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;  
 public class SimpleWebAppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {  
      @Override  
      protected Class<?>[] getRootConfigClasses() {  
           return new Class[]{SimpleWebConfiguration.class};  
      }  
      @Override  
      protected Class<?>[] getServletConfigClasses() {  
           return null;  
      }  
      @Override  
      protected String[] getServletMappings() {  
           return new String[] {"/entry/*"};  
      }  
 }  

SimpleWebContext(Dispatcher Servlet Class)
 package com.springimplant.mvc.config;  
 import org.springframework.context.annotation.ComponentScan;  
 import org.springframework.context.annotation.Configuration;  
 import org.springframework.web.servlet.config.annotation.EnableWebMvc;  
 @Configuration  
 @EnableWebMvc  
 @ComponentScan(basePackages="com.springimplant.mvc.controllers")  
 public class SimpleWebConfiguration {  
 }  


Thursday, July 5, 2018

Spring Bean

How can we handle multiple beans of same type?
  • We can use @Qualifier annotations, which lets us specify, which bean to inject When there are multiple beans available based on their name.
  • We can also use @primary Annotation On one of the beans, which will mark as a default choice for injecting type.
Explain the helper class that initializes end destroys web application context?
  • Class ContextLoaderListener using methods contextInitialized() and contextDestroyed()
Q What is AnnotationConfigApplicationContext ?
  • Annotation Config application context is a standalone application context which accepts annotated classes as input. For instance @configuration or @component. Beans can be looked up with scan() or registered with register().
What will happen if using @service,@component over @Repository in DAO layer?
  • If we use @Repository in DAO it gives the user a readable view, he is able to guess that this class contains DAO logic. If we use @Component its generic It’s hard to understand what logic is written there.
  • @Repository Helps you to handle persistent related exceptions that spring provides.
  • The generic class which handles all the DAO exceptions is called as DataAccessException class.
  • Any exception thrown by our persistence layer, irrespective Of the JDBC we are using like hibernate, Spring JDBC or myBatis JDBC will be wrapped by spring exception called as DataAccessException. 
What is a controller in spring mvc?
Controller is the class that takes care of all the client requests and send them to the configured resources to handle it.We can create a controller class by using @Controller annotation.

What is a front controller? What is its purpose?
org.springframework.web.servlet.DispatcherServlet is the front controller class that initializes the context based on the spring beans configurations.

What is the difference between @RequestMapping and @ResponseBody annotations?
@RequestMapping maps the request to a specific view file as specified in view resolver.
@ResponseBody treats the response returned from function as the final response and no viewresolver is required in this case.


What’s the difference between @Component, @Controller, @Repository & @Service annotations in Spring?
  • These classes are used to give authority to spring to define objects for us.
  • @Component is used to indicate that a class is a component. These classes are used for auto detection and configured as bean, when annotation based configurations are used.
  • @Controller is a specific type of component, used in MVC applications and mostly used with RequestMapping annotation.
  • @Repository annotation is used to indicate that a component is used as repository and a mechanism to store/retrieve/search data. We can apply this annotation with DAO pattern implementation classes.
    • For DAO layer which interacts with database we define annotation @Repository.
    • We add queries in this with respect to the database.
  • @Service is used to indicate that a class is a Service. Usually the business facade classes that provide some services are annotated with this.
    • For service classes where we define business logic we define @Service annotation

What is DispatcherServlet and ContextLoaderListener?
DispatcherServlet is the front controller in the Spring MVC application and it loads the spring bean configuration file and initialize all the beans that are configured.
If annotations are enabled, it also scans the packages and configure any bean annotated with @Component@Controller@Repository or @Service annotations.
ContextLoaderListener is the listener to start up and shut down Spring’s root WebApplicationContext
It’s important functions are to tie up the lifecycle of ApplicationContext to the lifecycle of the ServletContext and to automate the creation of ApplicationContext.
What is ViewResolver in Spring?
ViewResolver implementations are used to resolve the view pages by name. Usually we configure it in the spring bean configuration file.
 <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">  
           <property name="prefix" value="/WEB-INF/views/"></property>  
           <property name="suffix" value=".jsp"></property>  
      </bean>  

InternalResourceViewResolver is one of the implementation of ViewResolver interface and we are providing the view pages directory and suffix location through the bean properties. So if a controller handler method returns “home”, view resolver will use view page located at /WEB-INF/views/home.jsp.


What is a MultipartResolver and when its used?
MultipartResolver interface is used for uploading files
CommonsMultipartResolver and StandardServletMultipartResolver are two implementations provided by spring framework for file uploading.
Once configured, any multipart request will be resolved by the configured MultipartResolver and pass on a wrapped HttpServletRequest.
What is the difference between Bean Factory and Application Context?

BeanFactory is also called basic IOC and ApplicationContext is called Advanced IOC.
BeanFactory uses lazy initialization approach whereas ApplicationContext uses eager initialization approach.
BeanFactory creates a singleton bean only when it is requested from it but ApplicationContext creates all singleton beans at the time of its own initialization.
What is a Bean cycle?
  • We have 2 annotations @Postconstruct and @Pre destroy
    • In @PostConstruct whenever our container is created our beans will be instantiated the Method annotated with @PostConstruct will be called first and then other logic will run.
    • The Method annotated with @PreDestroy will Run once our container is about to get Destroyed and bean is about to get out of the container.
    • We can use @PostConstruct while creating DB connection So that we don’t need to create it again and again.
    • We can use @PreDestroy to close our DB connection Like a cleanup work.
  • In spring we have couple of interfaces which do same work
    • Initializing Bean
    • DisposableBean
  • Spring internal classes implement or extend to these interfaces.
How will the @PreDestroy Method be called in this case of standalone application?
  • In a web Application when we use context.stop() it will be called but in a standalone application it won’t be called.
  • If we use context.close() then the @predestroy annotated method will be called in a standalone application.
  • It is always better to use context.registerShutDownHook() rather than context.close() as it asks JVM on exit to destroy Application context object.
What are different scopes of a bean?
  • Singleton
    • Spring container by default returns a Singleton bean for a class.
    • Same object of class is returned by Spring Container each time which can be identified from the hashcode of the object.
  • Prototype
    • Spring container returns a New object for a class.
    • We can change the scope of a been using annotation scope or by using scope property of been element in XML.
  • Request
    • Used for Web Applications
    • Used for Http Requests
  • Session
    • Used for Web Applications
  • Global session
    • Used for Web Applications
What are the different stages of bean or explain bean life cycle?
  • Spring provides two important methods to every bean
    • Public void init()
      • Initialization code loading config, connecting DB, web service etc.
    • Public void destroy()
      • Clean up code
  • We can change the name of these methods but signature must be same.
  • We give the Spring Bean And a configuration XML file to the spring container.
  • This Spring container initializes the Spring bean and sets the values of its properties.
    • It then calls the init() method.
    • Next we can read and use the Bean.
    • Next when the object is about to get destroyed it calls destroy() method to perform cleanup operation.
Q In how many ways we can configure a Spring Bean?
  • XML
  • Spring interface
  • Annotation
Q what is constructor injection ambiguity problem and how it can be resolved in spring beans?
  • Constructor injection ambiguity. Problem comes when we try to overload a constructor. Thus At runtime when we try to create a bean using constructor injection, the JVM may find ambiguous arguments for different constructors. The priority of which constructor will be used is as follows.
    • if we have a constructor with string arguments, then it is considered by default because all parameter types in constructor injection are treated as string by default.
    • If we don’t have string argument constructor, then it will look for first constructor to which string can type casted too and we will use it.
    • The direction of looking for first constructor depends on where your default constructor is, that is no argument Constructor is placed. If placed at the bottom, then it will look bottom up else it will look top down.
    • Try adding no argument constructor annotation from Lombok Library and it will take the last constructor first, since it adds a no argument constructor in the end of the class.
    • To Specifically tell JVM to use particular constructor use type property of constructor-arg tag as follows.
    • We can also define order of Arguments using index property as follows.
<bean class="com.springimplant.util.Calc" name="Call" >
<constructor-arg value="50" type="double" index="1"/>
<constructor-arg value="100" type="double" index="0"/>
</bean>
What is the concept of inner bean, and what are the disadvantages of inner bean?
  • An inner bean Is  a bean That is declared inside the scope of another bean.
  • An inner bean Can only be used through outer bean As it encapsulates the outer bean.
  • It cannot be injected in another bean.
  • It stops accessibility of a bean by other beans.
  • It is all about configuring one spring be inside another bean.

Spring Boot

What is circular/cyclic dependency in spring boot? When two services are interdependent on each other, that is to start one service, we requ...