Showing posts with label Interview. Show all posts
Showing posts with label Interview. Show all posts

Wednesday 27 May 2020

Spring Interview Questions part-1


1.      Difference between spring and spring boot.

Spring Framework
Spring is one of the most widely used Java EE Frameworks for building applications. For the Java platform, the Spring framework provides an elaborate programming and configuration model. It aims to simplify Java EE development and helps developers be more productive at work. It can be used at any kind of deployment platform. It takes into account the rising needs of today’s businesses and strives to fulfill them.
 Unlike other frameworks, Spring focuses on several areas of an application and provides a wide range of features.
 One of the major features of the Spring framework is dependency injection. It helps make things simpler by allowing us to develop loosely coupled applications.
 Spring Boot
While the Spring framework focuses on providing flexibility to you, Spring Boot aims to shorten the code length and provide you with the easiest way to develop a web application. With annotation configuration and default codes, Spring Boot shortens the time involved in developing an application. It helps create a stand-alone application with less or almost zero-configuration.
 Autoconfiguration is a special feature in Spring Boot. It automatically configures a class based on that requirement.
2.      Benefits of Spring framework.
The Spring Framework can be used for all layers of implementation in the development of an application.
·       Considering its POJO model, it is a very lightweight framework.
·       It allows loose coupling and easy testability.
·       It supports declarative programming.
·       It is capable of eliminating the formation of singleton and factory classes.
·       It supports both XML and annotation configurations.
·       It provides middleware services.
 
3.      Despite having several in the Spring framework, what led to the emergence of Spring Boot?
Spring Boot helps in the easy usage of the Spring Framework by simplifying it to a great extent. Spring provides a loosely coupled application — this is a great feature. However, when there are several loosely coupled blocks, keeping track of them becomes a tedious and messy task. This is where Spring Block comes into the picture and helps simplify things by offering no configuration feature. It helps you get started with minimal effort and even provides externalized configuration.
 
4.Difference between Spring and Spring boot.
Spring Boot is a Spring-based production-ready project initializer. With features like auto-configuration, it saves you from writing lengthy code and helps you avoid unnecessary configuration.
While the Spring The framework offers you features like dependency injection or IOC and handles transactions, it also acts as a foundation for other Spring frameworks. The best example for this is Spring boot. Spring Boot uses the Spring Framework as a foundation and improvises on it. It simplifies Spring dependencies and runs applications straight from a command line. It also doesn’t require an application container. Spring Boot mostly helps in monitoring several components and configures them externally.
All in all, the Spring framework has made a significant contribution and continues to do so. With the many features mentioned above, the Spring framework is always a great choice for developers. However, it is highly beneficial when used alongside Spring Boot. The added advantages that come with Spring Boot are of great value to the developers as they offer completion of projects with minimal efforts. To all the problems that arise from the Spring framework, Spring Boot is the solution.
 
5.Benifits of Spring boot.
• Spring Boot doesn’t require you to deploy WAR files.
• It creates stand-alone applications.
• It helps embed Tomcat, Jetty, or Undertow directly.
• It doesn’t require XML configuration.
• It aims to reduce the LOC.
• It offers production ready features.
• It is easier to launch.
• Easier customization and management.
6. What is Inversion of Control (IOC)?
IoC is a design pattern that describes inverting the flow of control in a system, so execution flow is not controlled by a central piece of code. This means that components should only depend on abstractions of other components and are not be responsible for handling the creation of dependent objects. Instead, object instances are supplied at runtime by an IoC container through Dependency Injection (DI).
IoC enables better software design that facilitates reuse, loose coupling, and easy testing of software components.
 
7.What is Dependency Injection?
DI is a technique for passing dependencies into an object’s constructor. If the object has been loaded from the container, then its dependencies will be automatically supplied by the container. This allows you to consume a dependency without having to manually create an instance. This reduces coupling and gives you greater control over the lifetime of object instances.
8. Different @annotaions at spring and spring boot.
@Required: It applies to the bean setter method. It indicates that the annotated bean must be populated at configuration time with the required property, else it throws an exception BeanInitilizationException.
@Autowired: Spring provides annotation-based auto-wiring by providing @Autowired annotation. It is used to autowire spring bean on setter methods, instance variable, and constructor. When we use @Autowired annotation, the spring container auto-wires the bean by matching data-type.
@Configuration: It is a class-level annotation. The class annotated with @Configuration used by Spring Containers as a source of bean definitions.
@ComponentScan: It is used when we want to scan a package for beans. It is used with the annotation @Configuration. We can also specify the base packages to scan for Spring Components.
@Bean: It is a method-level annotation. It is an alternative of XML <bean> tag. It tells the method to produce a bean to be managed by Spring Container.
@Component: It is a class-level annotation. It is used to mark a Java class as a bean. A Java class annotated with @Component is found during the classpath. The Spring Framework pick it up and configure it in the application context as a Spring Bean.
@Controller: The @Controller is a class-level annotation. It is a specialization of @Component. It marks a class as a web request handler. It is often used to serve web pages. By default, it returns a string that indicates which route to redirect. It is mostly used with @RequestMapping annotation. 
@Service: It is also used at class level. It tells the Spring that class contains the business logic.
@Repository: It is a class-level annotation. The repository is a DAOs (Data Access Object) that access the database directly. The repository does all the operations related to the database.
@EnableAutoConfiguration: It auto-configures the bean that is present in the classpath and configures it to run the methods. The use of this annotation is reduced in Spring Boot 1.2.0 release because developers provided an alternative of the annotation, i.e. @SpringBootApplication.
@SpringBootApplication: It is a combination of three annotations @EnableAutoConfiguration, @ComponentScan, and @Configuration.
@RequestMapping: It is used to map the web requests. It has many optional elements like consumes, header, method, name, params, path, produces, and value. We use it with the class as well as the method.
@GetMapping: It maps the HTTP GET requests on the specific handler method. It is used to create a web service endpoint that fetches It is used instead of using: @RequestMapping(method = RequestMethod.GET)
@PostMapping: It maps the HTTP POST requests on the specific handler method. It is used to create a web service endpoint that creates It is used instead of using: @RequestMapping(method = RequestMethod.POST)
@PutMapping: It maps the HTTP PUT requests on the specific handler method. It is used to create a web service endpoint that creates or updates It is used instead of using: @RequestMapping(method = RequestMethod.PUT)
@DeleteMapping: It maps the HTTP DELETE requests on the specific handler method. It is used to create a web service endpoint that deletes a resource. It is used instead of using: @RequestMapping(method = RequestMethod.DELETE)
@PatchMapping: It maps the HTTP PATCH requests on the specific handler method. It is used instead of using: @RequestMapping(method = RequestMethod.PATCH)
@RequestBody: It is used to bind HTTP request with an object in a method parameter. Internally it uses HTTP MessageConverters to convert the body of the request. When we annotate a method parameter with @RequestBody, the Spring framework binds the incoming HTTP request body to that parameter.
@ResponseBody: It binds the method return value to the response body. It tells the Spring Boot Framework to serialize a return an object into JSON and XML format.
@PathVariable: It is used to extract the values from the URI. It is most suitable for the RESTful web service, where the URL contains a path variable. We can define multiple @PathVariable in a method.
@RequestParam: It is used to extract the query parameters form the URL. It is also known as a query parameter. It is most suitable for web applications. It can specify default values if the query parameter is not present in the URL.
@RequestHeader: It is used to get the details about the HTTP request headers. We use this annotation as a method parameter. The optional elements of the annotation are name, required, value, defaultValue. For each detail in the header, we should specify separate annotations. We can use it multiple time in a method
@RestController: It can be considered as a combination of @Controller and @ResponseBody annotations. The @RestController annotation is itself annotated with the @ResponseBody annotation. It eliminates the need for annotating each method with @ResponseBody.
@RequestAttribute: It binds a method parameter to request attribute. It provides convenient access to the request attributes from a controller method. With the help of @RequestAttribute annotation, we can access objects that are populated on the server-side.
9. What is JPA how you used it in your spring boot application.
When you implement a new application, you should focus on the business logic instead of technical complexity and boilerplate code. That’s why the Java Persistence API (JPA) specification and Spring Data JPA are extremely popular. JPA handles most of the complexity of JDBC-based database access and object-relational mappings. On top of that, Spring Data JPA reduces the amount of boilerplate code required by JPA. That makes the implementation of your persistence layer easier and faster.
JPA is a specification that defines an API for object-relational mappings and for managing persistent objects. Hibernate and EclipseLink are 2 popular implementations of this specification. You can learn more about the difference in What’s the difference between JPA, Hibernate and EclipseLink
Spring Data JPA adds a layer on top of JPA. That means it uses all features defined by the JPA specification, especially the entity and association mappings, the entity lifecycle management, and JPA’s query capabilities. On top of that, Spring Data JPA adds its own features like a no-code implementation of the repository pattern and the creation of database queries from method names.
10. How you are handling Client-side session in spring application.
We can control exactly when our session gets created and how Spring Security will interact with it:
· always – a session will always be created if one doesn’t already exist
· ifRequired – a session will be created only if required (default)
· never – the framework will never create a session itself but it will use one if it already exists
· stateless – no session will be created or used by Spring Security
<http create-session="ifRequired">...</http>
or
@Override
protected void configure(HttpSecurity http) throws Exception {
    http.sessionManagement()
        .sessionCreationPolicy(SessionCreationPolicy.IF_REQUIRED)
}
By default, Spring Security will create a session when it needs one – this is “ifRequired“.
For a more stateless application, the “never” option will ensure that Spring Security itself will not create any session; however, if the application creates one, then Spring Security will make use of it.
Finally, the strictest session creation option – “stateless” – is a guarantee that the application will not create any session at all.
A bean can be defined with session scope simply by using the @Scope annotation on beans declared in the web-Context:
@Component
@Scope("session")
public class Foo { .. }
Or with XML:
<bean id="foo" scope="session"/>
Then, the bean can simply be injected into another bean:
@Autowired
private Foo theFoo;
11. What is actuators in spring boot.
Spring Boot Actuator is a sub-project of Spring Boot. It provides several production-grade services to your application out of the box. Once Actuator is configured in your Spring Boot application, you can interact and monitor your application by invoking different HTTP endpoints exposed by Spring Boot Actuator such as application health, bean details, version details, configurations, logger details, etc.
Spring Boot includes a number of built-in endpoints, and you can also add your own or even configure existing endpoints to be exposed on any custom endpoints of your choice. It is obvious that all the endpoints cannot be exposed publicly, considering that there are many sensitive endpoints like beans, env, etc. Hence, Spring Boot also sets sensitive defaults to true for many endpoints that require a username/password when they are accessed over HTTP (or simply disabled if web security is not enabled). Health and info are not sensitive by default.
12. How do you write userCreation service in spring boot.
13.Different HTTP methods used in Spring Boot(i.e: @GetMapping,@DeleteMapping,@PostMapping,@PatchMapping,@PutMapping)
Below is the list of method that used while creating your RESTful API.
1. GET
2. POST
3. PUT
4. DELETE
5. PATCH
1. GET Method
HTTP GET method used to retrieve information from the REST API.We should not use this method to change any information or the resource.GET should be idempotent, meaning regardless of how many times it repeats with the same parameters, the results are the same.
2. POST Method
This method in the REST API should only be used to create a new resource.In some cases, POST method is used to update entity but this operation is not very frequent.POST API call is not idempotent nor safe and should be used with care.
3. PUT Method
If we want to update an existing resource, PUT method should be used for this operation.PUT method has some features as compare to the POST method and we should keep those in mind
· PUT method is idempotent.This means the client can send the same request multiple time and as per HTTP spec, this has exactly the same effect as sending once. (This is for us to make sure PUT behaves correctly every time)
4. DELETE Method
DELETE method should be used to remove a given resource.Similiar to PUT method, DELETE operation is idempotent.If a resource is deleted any later request will change anything in the system and it should return 404 response.DELETE can be a long-running or asynchronous request.
5. PATCH Method
Partial update to a resource should happen through PATCH method.To differentiate between PATCH and PUT method, PATCH request used to partially change a given resource while PUT used to replace existing resource.There are few things to keep in mind while using PATCH method.
· Support for PATCH in browsers, servers and web applications are not universal, this can post some challenges.
· Request payload for Patch is not simple and a client is required to send information to differentiate between the new and original documents.
 
14. What is GetMapping,DeleteMapping,PostMapping,PatchMapping,PutMapping
@GetMapping is specialized version of @RequestMapping annotation that acts as a shortcut for @RequestMapping(method = RequestMethod.GET). @GetMapping annotated methods handle the HTTP GETrequests matched with given URI expression
 
@DeleteMapping is a composed annotation that acts as a shortcut for @RequestMapping(method = RequestMethod.DELETE).
 
@PostMapping is specialized version of @RequestMapping annotation that acts as a shortcut for @RequestMapping(method = RequestMethod.POST). @PostMapping annotated methods handle the HTTP POST requests matched with given URI expression
 
@PatchMapping is a composed annotation that acts as a shortcut for @RequestMapping(method = RequestMethod.PATCH).
 
@PutMapping is a composed annotation that acts as a shortcut for @RequestMapping(method = RequestMethod.PUT).
 
15. Difference between Put and Post methods
PUT implies putting a resource - completely replacing whatever is available at the given URL with a different thing. By definition, a PUT is idempotent. Do it as many times as you like, and the result is the same. x=5 is idempotent. You can PUT a resource whether it previously exists, or not (eg, to Create, or to Update)!
POST updates a resource, adds a subsidiary resource, or causes a change. A POST is not idempotent, in the way that x++ is not idempotent.
16. Difference between Post, Put and Patch methods
POST
You use POST to create a resource and instruct the server to make a Uniform Resource Identifier (URI) for it. For example, when you want to create a new article you would POST to /articles to make the file and get the URI, so you end up with /articles/1234/.
PUT
PUT also creates resources, but it does so for a known URI. So, you can PUT to /articles/1234/. If the article doesn't exist, PUT creates it. If it does exist, this HTTP verb updates it. While PUT seems nearly identical to POST, the difference between the two comes down to idempotence.
 Idempotence is a property that creates identical side effects whether you have one or many results. PUT has this characteristic, while POST creates new resources infinitely. In general, POST works best for resource creation, while PUT handles updates. 
 
 PATCH
So, where does PATCH come into the picture? This HTTP verb partially updates resources without sending the complete representation of it. When you're working with complicated objects and resources, it's a big deal to update more than you need to. 
16. What is the use of @Configuration in spring.
Annotating a class with the @Configuration indicates that the class can be used by the Spring IoC container as a source of bean definitions.
@Configuration is meta-annotated with @Component, therefore @Configuration classes are candidates for component scanning (typically using Spring XML's <context:component-scan/> element) and therefore may also take advantage of @Autowired/@Inject like any regular @Component. In particular, if a single constructor is present autowiring semantics will be applied transparently for that constructor:
17. Different annotations in Spring Boot, like @repository, @service, @RestController, @RequestMapping.
@Repository Annotation
Although above use of @Component is good enough but we can use more suitable annotation that provides additional benefits specifically for DAOs i.e. @Repository annotation. The @Repository annotation is a specialization of the @Component annotation with similar use and functionality. In addition to importing the DAOs into the DI container, it also makes the unchecked exceptions (thrown from DAO methods) eligible for translation into Spring DataAccessException.
@Service Annotation
The @Service annotation is also a specialization of the component annotation. It doesn’t currently provide any additional behavior over the @Component annotation, but it’s a good idea to use @Service over @Component in service-layer classes because it specifies intent better. Additionally, tool support and additional behavior might rely on it in the future.
@RestController
This annotation was introduced in Spring 4.0 to simplify the creation of RESTful web services. It’s a convenience annotation that combines @Controller and @ResponseBody – which eliminates the need to annotate every request handling method of the controller class with the @ResponseBody annotation.
@RequestMapping
This is one of the most common annotations used in Spring Web applications. This annotation maps HTTP requests to handler methods of MVC and REST controllers.
 
 18. What is OAUTH?
OAuth is an open standard authorization protocol or framework that describes how unrelated servers and services can safely allow authenticated access to their assets without actually sharing the initial, related, single logon credential. In authentication parlance, this is known as secure, third-party, user-agent, delegated authorization.
19What is Restful API - stateless and state-full services?
A RESTful API is an application program interface (API) that uses HTTP requests to GET, PUT, POST and DELETE data.
A RESTful API -- also referred to as a RESTful web service -- is based on representational state transfer (REST) technology, an architectural style and approach to communications often used in web services development.
A stateless system can be seen as a box  where at any point in time the value of the output(s) depends only on the value of the input(s)
A stateful system instead can be seen as a box where at any point in time the value of the output(s) depends on the value of the input(s) and of an internal state, so basicaly a stateful system is like a state machine with "memory" as the same set of input(s) value can generate different output(s) depending on the previous input(s) received by the system.
From the parallel programming point of view, a stateless system, if properly implemented, can be executed by multiple threads/tasks at the same time without any concurrency issue A stateful system will requires that multiple threads of execution access and update the internal state of the system in an exclusive way, hence there will be a need for a serialization [synchronization] point.
20. What is two factor authentications?
Two-factor authentication (2FA), sometimes referred to as two-step verification or dual factor authentication, is a security process in which the user provides two different authentication factors to verify themselves to better protect both the user's credentials and the resources the user can access. Two-factor authentication provides a higher level of assurance than authentication methods that depend on single-factor authentication (SFA), in which the user provides only one factor -- typically a password or passcode. Two-factor authentication methods rely on users providing a password as well as a second factor, usually either a security token or a biometric factor like a fingerprint or facial scan.
Two-factor authentication adds an additional layer of security to the authentication process by making it harder for attackers to gain access to a person's devices or online accounts, because knowing the victim's password alone is not enough to pass the authentication check. Two-factor authentication has long been used to control access to sensitive systems and data, and online service providers are increasingly using 2FA to protect their users' credentials from being used by hackers who have stolen a password database or used phishing campaigns to obtain user passwords.

 


Friday 22 May 2020

Apache Solr Interview Questions

Q1. What do you understand by the term Apache Lucene?
Apache Solr is a standalone full-text search platform to perform searches on multiple websites and index documents using XML and HTTP. Built on a Java Library called Lucence, Solr supports a rich schema specification for a wide range and offers flexibility in dealing with different document fields. It also consists of an extensive search plugin API for developing custom search behavior.
Supported by Apache Software Foundation, Apache Lucene is a free, open-source, high-performance text search engine library written in Java by Doug Cutting. Lucence facilitates full-featured searching, highlighting, indexing and spellchecking of documents in various formats like MS Office docs, HTML, PDF, text docs and others. Solr is built on top of lucene.
Advantages
Disadvantages
Has a powerful language structure
Learning the syntax consumes a lot of time
empowers clients to perform precise scans for every one of the
questions either it may be simple or complex
There is a requirement of expert programmers
who can write codes.
SolrJ is an API that makes it easy for Java applications to talk to Solr. SolrJ hides a lot of the details of connecting to Solr and allows your application to interact with Solr with simple high-level methods.
Both Solr and Elasticsearch are popular open source search engines built on top of Lucene. Both have vibrant communities and are well documented. The difference is in the way each builds a wrapper and implements features on top of Lucene.



Q2. Describe the term Request Handler.
A Request Handler is basically a plugin, which handles approaching solicitations with a specific goal in mind. At the point when a client runs a search in Solr, a request handler prepares the inquiry question. SolrRequestHandler is the Solr Plugin that represents the logic to be performed at any request.

Q3. List the different type of information that can be retrieved from a field type.
The different type of information that can be retrieved from a field type include the following:
·       Name of the field
·       Field properties
·       A usable class names
·       Description of the field investigation for the field type, in case the field type is that of a Text Field

Q4. What do you understand by the term Field Analyzer?
Working with literary information in Solr, Field Analyzer audits and checks the documented content and produces a token stream. The pre-procedure of examining any input content is performed during the time of inquiring or classifying and at inquiry time. Many of the Solr applications utilize Custom Analyzers characterized by clients. However, it is essential to keep in mind that every Analyzer has just a single Tokenizer.
Field analyzers are used both during ingestion, when a document is indexed, and at query time. An analyzer examines the text of fields and generates a token stream. Analyzers may be a single class or they may be composed of a series of tokenizer and filter classes.
Tokenizers break field data into lexical units, or tokens.
Filters examine a stream of tokens and keep them, transform or discard them, or create new ones. Tokenizers and filters may be combined to form pipelines, or chains, where the output of one is input to the next. Such a sequence of tokenizers and filters is called an analyzer and the resulting output of an analyzer is used to match query results or build indices.

Q5. List the various categories of highlighters.
Different categories of highlighters available in Apache Solr include the following:
Standard Highlighter: gives exact matches even to innovative query parsers.
FastVector Highlighter: Though less progressed in comparison to Standard Highlighter, it works better for more dialects and promotes Unicode break iterators.
Postings Highlighter: One of the most precise, compact and effective highlighter categories in comparison to other vectors. However, inappropriate for a progressive number of question terms.

Q6. What does the term Highlighting refer?
Highlighting is only the fragmentation of records relating to the client's question that is incorporated into the Query reaction. A short time later, these parts are shown and set in the unique portion, that is utilized by the clients and customers to exhibit the pieces. The Solr contains various featuring utilities and has power overdifferent fields. The featuring utilities can be called by Handlers of Request and can be reused with the standard question parsers.

Q7. How can one utilize Apache Solr for achieving maximum potential for performance?
Solr can accomplish quick inquiry reactions in light of the fact that, rather than looking through the content legitimately, it looks through a record. This resembles recovering pages in a book identified with a catchphrase by checking the file at the back of a book, rather than looking through each expression of each page of the book.

Q8. List and describe the various building blocks of Apache Solr.
The chief building blocks associated with Apache Solr include the following:
Request Handler: A request handler is used in order to process various queries that might be related to updating or other features. Based on the requirement of the user, from a variety of request handlers, themost appropriate one can be picked to do the job.
Search Component: Search Component is a special feature that allows searching for different facilities within Apache Solr. These facilities might include spell checks, faceting, highlighting, etc. that might be particularly required by the user.
Query Parser: This building block of Apache Solr helps in the verification of different queries for specific syntactical errors. Once the error has been resolved then it is modified to a format that is acceptable by Lucene
Response Writer: Response Writer in Apache Solr generates various outputs of different formats for each query place by the user. Numerous formats supported by Apache Solr include JSON, XML, CSV, and so on. Each type of response has a different response writer assigned to it.
Analyzer/Tokenizer: Data is recognized by data in the format of tokens. These token that is analyzed and segregated to different contents by Apache Solr is then passed onto Lucene. The role of the Tokenizer is to then break the stream of tokens that is organized by the analyzer as tokens.
Update Request Processor: When an update is sent as an appeal to Apache Solr, then this particular request is run via a range of different plugins that are jointly named as update request processor.

Q9. List the different types of Fields that are used in Apache Solr.
The different type of Fields used in Apache Solr include the following:
·       date
·       double
·       float
·       long
·       Text

Q10. What do you infer by the term Dynamic Fields with respect to Apache Solr?
During times when a user neglected to characterize some important field then dynamic fields are only the ideal decision to consider. One can make different dynamic fields together and they are profoundly adaptable in ordering fields that are not uniquely characterized in the pattern.

Q11. Explain the term SolrCloud.
Apache Solr incorporates the capacity to set up a group of Solr servers that consolidates adaptation to noncritical failure and high accessibility is Called SolrCloud. These abilities give circulated ordering and hunt capacities and the accompanying highlights:
·       Central arrangement for the whole group
·       Automatic burden adjusting and flop over for inquiries
·       ZooKeeper combination for group coordination and setup.
In other terms, SolrCloud is adaptable circulated pursuit and order, without an ace hub to assign hubs, shards,and reproductions. Rather, Solr utilizes ZooKeeper to deal with these areas, contingent upon setup records and diagrams. Archives can be sent to any server and ZooKeeper will make sense of it.

Q12. List the various categories of query parameters used in Apache Solr.
The various categories of query parameters used in Apache Solr include the following:
fl: stipulates the list of various fields that are required to be returned to each document within the result
fq: represents a set of filter queries that are filled by Apache Solr within strict bounds for the best result to be obtained for various documents
rows: represents the exact number of various documents that need to be recovered per page; the default number is 10
start: represents the initial offset for a particular page, the default number is 0
sort: indicates the rundown of fields isolated by commas, in light of which the aftereffects of the question is to be arranged
q: this is the fundamental inquiry parameter of Apache Solr, the archives are scored by their closeness to terms in this parameter
wt: represents the kind of the reaction the user needs to see the outcome

Q13. List the various configuration files used by Apache Solr.
The various configuration files used by Apache Solr include the following:
Solr.xml - This record is in $SOLR_HOME index and is composed of Solr Cloud related data.
Schema.xml - It constitutes the entire schema.
Solrconfig.xml - It incorporates the definitions and center explicit setups identified with solicitation taking care of and reaction organizing.
Core.properties - This record contains the arrangements explicit profoundly.

Q14. What do you understand by the term Apache Solr core?
Apache Solr Core is a functioning occurrence of a Lucene list that is composed of all the Solr arrangement records. Solr core should be made to perform activities like analyzing and recording. Solr application may contain one or different centers. On the off chance that core might require two centers in a Solr application have the leverage to communicate with one another.

Q15. Features of Apache Solr
1. Permits Scalable, superior ordering Near ongoing ordering
2. Standard levels provide open interfaces such as XML, HTTP, and JSON
3. Adaptable and versatile faceting
4. Progressed and precise full – content exploration
5. Directly adaptable, auto list replication, auto failover, and recuperation
6. Permits simultaneous examination and refreshing.
7. Complete HTML organization interfaces
8. Gives cross – stage arrangements that are compatible with different files

Q16. Pros of Apache Solr
1. Easy access Apache Solr: Regardless of whether it is handling a setup issue or attempting to become familiar with a portion of the further developed highlights, there are a lot of assets to enable you to go out and make you go.
2. Excellent performance: Apache Solr takes into consideration a ton of custom tuning (if necessary) and gives extraordinary out of the crate execution for seeking on expansive informational collections.
3. Maintenance: Subsequent to setting up Solr in a generation domain there are a lot of devices given to enable you to keep up and update your application. Apache Solr accompanies extraordinary adaptation to non-critical failure worked in and has turned out to be entirely solid.

Q17. Cons of Apache Solr
1. An ordering of information can once in a while be a trudge, which means it can here and there require a significant stretch of time to get a huge accumulation fully operational in the event that you have numerous fields that should be recorded.

Q18. What is SolrJ?

Q19.Can you compare the features of Apache Solr vs Elasticsearch?

Typical MicroServices Interview

1. Explain briefly about your project experience ​ .

2. Explain about oops concept and how you implemented in your project.  

3. I have a class A having main method, also I have another class B extends A when compiling B will it be executed or not?.

Yes, It will get executed. 
public class Test2 {         

public static void main(String[] args) {  
System.out.println("Called Test 2");         }   } 

public class Test4 extends Test2  {  } 

output: Called Test 2 

4. What will happen when a method is called inside the same method. Who Checks and stop the program termination. 

eg:  public class Test2  { 

public void greet(){ 
greet(); 
}         
public static void main(String[] args) {
  Test2 test2 = new Test2();
  test2.greet();  
       } 
  } 

The above Code throws Exception in thread "main" java.lang.StackOverflowError. Which means The StackOverflowError extends the VirtualMachineError class, which indicates that the JVM is broken, or it has run out of resources and cannot operate. Furthermore, the the VirtualMachineError extends the Error class, which is used to indicate those serious problems that an application should not catch. A method may not declare such errors in its throw clause, because these errors are abnormal conditions that shall never occur. 

When a function call is invoked by a Java application, a stack frame is allocated on the call stack. The stack frame contains the parameters of the invoked method, its local parameters, and the return address of the method. The return address denotes the execution point from which, the program execution shall continue after the invoked method returns. If there is no 
space for a new stack frame then, the StackOverflowError is thrown by the Java Virtual Machine (JVM). 

The most common case that can possibly exhaust a Java application’s stack is recursion. In recursion, a method invokes itself during its execution. Recursion is considered as a powerful general-purpose programming technique, but must be used with caution, in order for the StackOverflowError to be avoided. 

5. If I have a static method in both parent class and extended class and while creating the object reference for the child method which method will be invoked.? 

private, final and static methods and variables use static binding and bonded by the compiler while overridden methods are bonded during runtime based upon the type of runtime object 

Hence the method in the parent class is called also the compiler throws the warnings."The static method greet() from the type Test2 should be accessed in a static way" 

6. How many objects are created when (Parent)Test2 test2 = new (child)Test4(); 

In inheritance, subclass acquires super class properties. An important point to note is, when subclass object is created, a separate object of super class object will not be created. Only a subclass object object is created that has super class variables. 

7. Explain static binding? 

Static Binding: The binding which can be resolved at compile time by compiler is known as static or early binding. Binding of all the static, private and final methods is done at compile-time . 

Why binding of static, final and private methods is always a static binding?  Static binding is better performance wise (no extra overhead is required). Compiler knows that all such methods cannot be overridden and will always be accessed by object of local class. Hence compiler doesn’t have any difficulty to determine object of class (local class for sure). That’s the reason binding for such methods is static. 

8. I have two class and methods with different argument how do you call this during the runtime. 

public class ReflectionDemo1 {


    public static void main(String[] args) {

        System.out.println(greet("Syed Ghouse Habib", 1));
    }
    public static String greet(String string, long log) {
        return string + log;
    }
}

public class ReflectionDemo2 {
    public static void main(String[] args) {

        System.out.println(greet("Syed Ghouse Habib"));
    }
    public static String greet(String string) {
        return string;
    }
}

It can be called using the reflection.

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Arrays;

public class InvokeMain {
    public static void main(String...args) {
        try {
            for (String arg: args) {
                Class << ? > c = Class.forName(arg);
                Class[] argTypes = new Class[1];
                argTypes[0] = String[].class;
                Method main = c.getDeclaredMethod("main", argTypes);
                String[] mainArgs = Arrays.copyOfRange(args, 1, args.length);
                System.out.format("invoking %s.main()%n", c.getName());
                main.invoke(null, (Object) mainArgs);
            }

            // production code should handle these exceptions more gracefully } catch (ClassNotFoundException x) {     x.printStackTrace(); } catch (NoSuchMethodException x) {     x.printStackTrace(); } catch (IllegalAccessException x) {     x.printStackTrace(); 
        } catch (InvocationTargetException x) {
            x.printStackTrace();
        }
    }
}

9. What will happen when the Employee object with the same value is added to the set

Having only the equals method. It will have two objects created. When we have only the hashcode method. It will have two objects created. It will have only one entry when both the methods are available. 

10. Write a program to sum the value from the given alphanumeric string. 

sampleString = "pq12s56"

import java.util.stream.Collectors;

public class StringSummer {

    public static void main(String args[]) {
        String sampleString = "pq12s56";
        int sum8 = 0; //using java8 
        sum8 = sampleString.chars().filter(val - > Character.isDigit((char) val)).mapToObj(num - > Character.getNumericValue(num)).collect(Collectors.summingInt(Integer::intValue));
        System.out.println(sum8);

        int sum = 0; //using java 7
        char[] charVal = sampleString.toCharArray();
        for (char c: charVal) {
            if (Character.isDigit(c)) {
                sum = sum + Character.getNumericValue(c);
            }

        }
        System.out.println(sum);
    }
}

11. Explain memory management in java?.

Runtime data area in JVM can be divided as below, 

Method Area: Storage area for compiled class files. (One per JVM instance) 

Heap: Storage area for Objects. (One per JVM instance) 

Java stack: Storage area for local variables, results of intermediate operations. (One per thread) 

PC Register: Stores the address of the next instruction to be executed if the next instruction is native method then the value in pc register will be undefined. (One per thread) 

Native method stacks : Helps in executing native methods (methods written in languages other than Java). (One per thread) 

Following are points you need to consider about memory allocation in java. 

Note: Object and Object references are different things. 

1)There is new keyword in java used very often to create a new objects. But what new does is allocate memory for the object of class you are making and returns a reference. 

That means whenever you create an object as static or local, it gets stored in HEAP. 

2) All the class variable primitive or object references (which is just a pointer to location where object is stored i.e. heap) are also stored in heap. 

3) Classes loaded by classloader and static variables and static object references are stored in a special location in heap which permanent generation. 

4) Local primitive variables, local object references and method parameters are stored in Stack. 

5) Local Functions (methods) are stored in stack but Static functions(methods) goes in permanent storage. 

6) All the information related to a class like the name of the class, Object arrays associated with the class, internal objects used by JVM (like java/lang/Object), and optimization information goes into the Permanent Generation area. 

7) To understand stack, heap, data you should read about Processes and Process Control Block in Operating Systems. 


12. Explain the initial capacity of ArrayList?. How would you force to create an array of capacity 8? 

In java 8 default capacity of ArrayList is 0 until we add at least one object into the ArrayList object (You can call it lazy initialization). 

Now question is why this change has been done in JAVA 8? 

The answer is to save memory consumption. Millions of array list objects are created in real-time java applications. Default size of 10 objects means that we allocate 10 pointers (40 or 80 bytes) for the underlying array at creation and fill them in with nulls. An empty array (filled with nulls) occupy lot of memory . 

Lazy initialization postpones this memory consumption till moment you will actually use the array list. 

List<String> s = new ArrayList<>(8); 

This statement will create the array of inital capacity 8. 

13. What is the algorithm used in Java GC. 

Mark & sweep algoritm. 

14.what are the different types of method avaliable in  

1. GET Method HTTP GET method used to retrieve information from the REST API.We should not use this method to change any information or the resource.GET should be idempotent, meaning regardless of how many times it repeats with the same parameters, the results are the same. 

2. POST Method This method in the REST API should only be used to create a new resource.In some cases, POST method is used to update entity but this operation is not very frequent.POST API call is not idempotent nor safe and should be used with care. 

3. PUT Method If we want to update an existing resource, PUT method should be used for this operation.PUT method has some features as compare to the POST method and we should keep those in mind · PUT method is idempotent.This means the client can send the same request multiple time and as per HTTP spec, this has exactly the same effect as sending once. (This is for us to make sure PUT behaves correctly every time) 

4. DELETE Method DELETE method should be used to remove a given resource.Similiar to PUT method, DELETE operation is idempotent.If a resource is deleted any later request will change anything in the 
system and it should return 404 response.DELETE can be a long-running or asynchronous request.

 5. PATCH Method Partial update to a resource should happen through PATCH method.To differentiate between PATCH and PUT method, PATCH request used to partially change a given resource while PUT used to replace existing resource.There are few things to keep in mind while using PATCH method. · Support for PATCH in browsers, servers and web applications are not universal, this can post some challenges. · Request payload for Patch is not simple and a client is required to send information to differentiate between the new and original documents. 

15. Difference between put and post method. 

PUT implies putting a resource - completely replacing whatever is available at the given URL with a different thing. By definition, a PUT is idempotent. Do it as many times as you like, and the result is the same. x=5 is idempotent. You can PUT a resource whether it previously exists, or not (eg, to Create, or to Update)! POST updates a resource, adds a subsidiary resource, or causes a change. A POST is not idempotent, in the way that x++ is not idempotent. 

16. How does the springboot works. 

From the run method, the main application context is kicked off which in turn searches for the classes annotated with @Configuration, initializes all the declared beans in those configuration classes, and based upon the scope of those beans, stores those beans in JVM, specifically in a space inside JVM which is known as IOC container. After the creation of all the beans, automatically configures the dispatcher servlet and registers the default handler mappings, messageConverts, and all other basic things. 

Basically, spring boot supports three embedded servers:- Tomcat (default), Jetty and Undertow. 

You can add cross filters in spring boot in one of the configuration files as 

@Configuration @EnableWebMvc public class WebConfig extends WebMvcConfigurerAdapter { 

    @Override     public void addCorsMappings(CorsRegistry registry) {         registry.addMapping("/api/**");     } } 

17.What are the Embeded servers in spring boot and which one is default. 

Tomcat (default), Jetty and Undertow. 

18. Difference between spring mvc and spring boot, is dispatcher servlet not used in the springboot? 

Spring MVC is a complete HTTP oriented MVC framework managed by the Spring Framework and based in Servlets. It would be equivalent to JSF in the JavaEE stack. The most popular elements in it are classes annotated with @Controller, where you implement methods you can access using different HTTP requests. It has an equivalent @RestController to implement REST-based APIs. 

Spring boot is a utility for setting up applications quickly, offering an out of the box configuration in order to build Spring-powered applications. As you may know, Spring integrates a wide range of different modules under its umbrella, as spring-core, spring-data, spring-web (which includes Spring MVC, by the way) and so on. With this tool you can tell Spring how many of them to use and you'll get a fast setup for them (you are allowed to change it by yourself later on). So, Spring MVC is a framework to be used in web applications and Spring Boot is a Spring based production-ready project initializer. 


You understood it right. 

@Configuration @Configuration is an analog for xml file. Such classes are sources of bean definitions by defining methods with the @Bean annotation. 

@Configuration is: 

not required, if you already pass the annotated class in the sources parameter when calling the SpringApplication.run() method; required, when you don't pass the annotated class explicitly, but it's in the package that's specified in the @ComponentScan annotation of your main configuration class. For readability, classes that are even explicitly passed as sources may anyway be annotated with @Configuration - just to show the intentions more clearly. 

Your current class is not really source of bean definitions, because it doesn't have any, but if you had @Bean annotated methods, Spring would see them. 

@EnableAutoConfiguration Can be used with or without @Configuration. It tells Spring to setup some basic infrastructure judging by what you have in the classpath. It's done by invoking a so called import class that's 
derived from the value of the @Import annotation that @EnableAutoConfiguration includes. Only one class should be annotated with @EnableAutoConfiguration, duplicating it doesn't do anything. 

19.what is a stream in java 8 and what are its features?. 

Java provides a new additional package in Java 8 called java.util.stream. This package consists of classes, interfaces and enum to allows functional-style operations on the elements. You can use stream by importing java.util.stream package. 

Stream provides following features: 

Stream does not store elements. It simply conveys elements from a source such as a data structure, an array, or an I/O channel, through a pipeline of computational operations. Stream is functional in nature. Operations performed on a stream does not modify it's source. For example, filtering a Stream obtained from a collection produces a new Stream without the filtered elements, rather than removing elements from the source collection. Stream is lazy and evaluates code only when required. The elements of a stream are only visited once during the life of a stream. Like an Iterator, a new stream must be generated to revisit the same elements of the source. You can use stream to filter, collect, print, and convert from one data structure to other etc. In the following examples, we have apply various operations with the help of stream. 

20. Draw microservices componets. 


21. How to implement the retry mechanism for the microservices. 

@SpringBootApplication
@EnableRetry
public class So52193237Application {

    public static void main(String[] args) {
        SpringApplication.run(So52193237Application.class, args);
    }

    @Bean
    public ApplicationRunner runner(Foo foo) {
        return args - > {
            try {
                foo.exec();
            } catch (Exception e) {
                try {
                    foo.exec();
                } catch (Exception ee) {
                    Thread.sleep(11000);
                    try {
                        foo.exec();
                    } catch (Exception eee) {

                    }
                }
            }
        };
    }

    @Component
    public static class Foo {

        private static final Logger LOGGER = LoggerFactory.getLogger(Foo.class);

        private final Bar bar;

        public Foo(Bar bar) {
            this.bar = bar;
        }

        @CircuitBreaker(maxAttempts = 1, openTimeout = 10000, resetTimeout = 10000)
        public void exec() throws TypeOneException {
            LOGGER.info("Foo.circuit");
            this.bar.retryWhenException();
        }

        @Recover
        public void recover(Throwable t) throws Throwable {
            LOGGER.info("Foo.recover");
            throw t;
        }

    }

    @Component
    public static class Bar {

        private static final Logger LOGGER = LoggerFactory.getLogger(Bar.class);

        @Retryable(value = {
            TypeOneException.class
        }, maxAttempts = 3, backoff = @Backoff(2000)) public void retryWhenException() throws TypeOneException {
            LOGGER.info("Retrying");
            throw new TypeOneException();
        }

        @Recover
        public void recover(Throwable t) throws Throwable {
            LOGGER.info("Bar.recover");
            throw t;
        }

    }

}

22. What are the types of exceptions you have handled in your application? 

23. Do you like to work in a team or an individual contributor? 

24. Do you like to learn about new technologies?. 

25. Have you heard of cucumber?. 

26. What you will do in your free time?. 

27. If you have a conflict with one of your college how you will resolve it?. 

28. If the requirements are not clear what you will do first?. 

29. Any Questions for me? 

x