SpringBoot Annotations

Posted on

1)Actuator :

Spring Boot actuator provides restful web services to access the current state of running an application in the production environment. With the help of actuator, you can check various metrics and monitor your application. and

Spring Boot Annotations

 

 

@Interceptor in SpringBoot

Posted on

You can use the Interceptor in Spring Boot to perform operations under the following situations −

  • Before sending the request to the controller
  • Before sending the response to the client

For example, you can use an interceptor to add the request header before sending the request to the controller and add the response header before sending the response to the client.

To work with interceptor, you need to create @Component class that supports it and it should implement the HandlerInterceptor interface.

The following are the three methods you should know about while working on Interceptors −

  • preHandle() method − This is used to perform operations before sending the request to the controller. This method should return true to return the response to the client.
  • postHandle() method − This is used to perform operations before sending the response to the client.
  • afterCompletion() method − This is used to perform operations after completing the request and response.

HTTP REQUESTS AND RESPONSE CODES

Posted on

HTTP Method   Operation  Comment
GET(IDEMPOTENT)  Read Operation only  Uses only for the read operation.GET should be idempotent
POST Create new resource  Should only be used to create a new resource
PUT(IDEMPOTENT) Update / Replace Resource Update an existing resource.Think of PUT method as putting a resource
DELETE Delete Resource To remove a given resource.DELETE operation is idempotent
PATCH Partial Update / Modify  Partial update to a resource should happen through PATCH

All these status codes grouped into 5 different categories

Status Code Category Description Example
1XX – Informational Informational indicates a provisional response 100 (Continue ) , 101
2XX – Successful This class of status code indicates that the client’s request was successfully received, understood, and accepted. 200 (OK), 201(Created), 202 (Accepted)
3XX – Redirection This class of status code indicates that further action required by the user agent to fulfill the request 301 (Moved Permanently), 302, 304
4XX – Client Error The 4xx class of status code is intended for cases where the client seems to have erred  400 ( Bad Request), 401, 403, 404, 405
5XX – Server Error Response status codes beginning with the digit “5” tell cases where the server is aware that it has erred or is incapable of performing the request  500 (Internal Server Error), 502, 503, 505

 

difference between pull and fetch in GIT

Posted on

git fetch just “downloads” the changes from the remote to your local repository. git pull downloads the changes and merges them into your current branch. “In its default mode, git pull is shorthand for git fetch followed by git merge FETCH_HEAD .”

 

GIT PULL= GIT FETCH+ GIT MERGE

JVM Architecture

Posted on Updated on

JVMThe JVM is divided into three main subsystems:

  1. ClassLoader Subsystem
  2. Runtime Data Area
  3. Execution Engine

1. ClassLoader Subsystem
Java’s dynamic class loading functionality is handled by the ClassLoader subsystem. It loads, links. and initializes the class file when it refers to a class for the first time at runtime, not compile time.

1.1 Loading
Classes will be loaded by this component. BootStrap ClassLoader, Extension ClassLoader, and Application ClassLoader are the three ClassLoaders that will help in achieving it.

BootStrap ClassLoader – Responsible for loading classes from the bootstrap classpath, nothing but rt.jar. Highest priority will be given to this loader.
Extension ClassLoader – Responsible for loading classes which are inside the ext folder (jre\lib).
Application ClassLoader –Responsible for loading Application Level Classpath, path mentioned Environment Variable, etc.
The above ClassLoaders will follow Delegation Hierarchy Algorithm while loading the class files.

1.2 Linking
Verify – Bytecode verifier will verify whether the generated bytecode is proper or not if verification fails we will get the verification error.
Prepare – For all static variables memory will be allocated and assigned with default values.
Resolve – All symbolic memory references are replaced with the original references from Method Area.
1.3 Initialization
This is the final phase of ClassLoading; here, all static variables will be assigned with the original values, and the static block will be executed.

2. Runtime Data Area
The Runtime Data Area is divided into five major components:

Method Area – All the class-level data will be stored here, including static variables. There is only one method area per JVM, and it is a shared resource.
Heap Area – All the Objects and their corresponding instance variables and arrays will be stored here. There is also one Heap Area per JVM. Since the Method and Heap areas share memory for multiple threads, the data stored is not thread-safe.
Stack Area – For every thread, a separate runtime stack will be created. For every method call, one entry will be made in the stack memory which is called Stack Frame. All local variables will be created in the stack memory. The stack area is thread-safe since it is not a shared resource. The Stack Frame is divided into three subentities:
Local Variable Array – Related to the method how many local variables are involved and the corresponding values will be stored here.
Operand stack – If any intermediate operation is required to perform, operand stack acts as runtime workspace to perform the operation.
Frame data – All symbols corresponding to the method is stored here. In the case of any exception, the catch block information will be maintained in the frame data.
PC Registers – Each thread will have separate PC Registers, to hold the address of current executing instruction once the instruction is executed the PC register will be updated with the next instruction.
Native Method stacks – Native Method Stack holds native method information. For every thread, a separate native method stack will be created.
3. Execution Engine
The bytecode, which is assigned to the Runtime Data Area, will be executed by the Execution Engine. The Execution Engine reads the bytecode and executes it piece by piece.

Interpreter – The interpreter interprets the bytecode faster but executes slowly. The disadvantage of the interpreter is that when one method is called multiple times, every time a new interpretation is required.
JIT Compiler – The JIT Compiler neutralizes the disadvantage of the interpreter. The Execution Engine will be using the help of the interpreter in converting byte code, but when it finds repeated code it uses the JIT compiler, which compiles the entire bytecode and changes it to native code. This native code will be used directly for repeated method calls, which improve the performance of the system.
Intermediate Code Generator – Produces intermediate code
Code Optimizer – Responsible for optimizing the intermediate code generated above
Target Code Generator – Responsible for Generating Machine Code or Native Code
Profiler – A special component, responsible for finding hotspots, i.e. whether the method is called multiple times or not.
Garbage Collector: Collects and removes unreferenced objects. Garbage Collection can be triggered by calling System.gc(), but the execution is not guaranteed. Garbage collection of the JVM collects the objects that are created.

Advantages of SpringBoot

Posted on Updated on

Advantages of SpringBoot:

  • No need of creating boilerplate configuration
  • Plenty of SpringBoot Starter to quickly get up and running
  • DevTools to autorestart server on code/config updates
  • Embedded Tomcat/Jetty/Undertow support
  • Easier customization of application properties
  • Easy management of profile specific properties
  • Easier dependency management using platform-bom

Remove Duplicates from String

Posted on Updated on

Using LinkedHashSet ,as it provides insertion order and time complexity of basic method is O(1).

import java.util.*;

class RemoveDuplicates
{
    /* Function removes duplicate characters from the string
    This function work in-place */
    void removeDuplicates(String str)
    {
        LinkedHashSet lhs = new LinkedHashSet();
        for(int i=0;i<str.length();i++)
lhs.add(str.charAt(i));

// print string after deleting duplicate elements
for(Character ch : lhs)
System.out.print(ch);
}

/* Driver program to test removeDuplicates */
public static void main(String args[])
{
String str = “tejureddy”;
RemoveDuplicates r = new RemoveDuplicates();
r.removeDuplicates(str);
}
}

Map with multiple values for same key

Posted on Updated on

APPROACH 1:

Map<String, List> map = new HashMap<>();
List list = new ArrayList<>();
map.put(“key1”, list);
map.get(“key1”).add(“value1”);
map.get(“key1”).add(“value2”);

assertThat(map.get(“key1”).get(0)).isEqualTo(“value1”);
assertThat(map.get(“key1”).get(1)).isEqualTo(“value2”);

APPROACH 2:

MultiMap<String, String> map = new MultiValueMap<>();
map.put(“key1”, “value1”);
map.put(“key1”, “value2”);
assertThat((Collection) map.get(“key1”))
.contains(“value1”, “value2”);

APPROACH 3: Java 8 Approach

Map<String, List> map = new HashMap<>();
map.computeIfAbsent(“key1”, k -> new ArrayList<>()).add(“value1”);
map.computeIfAbsent(“key1”, k -> new ArrayList<>()).add(“value2”);

assertThat(map.get(“key1”).get(0)).isEqualTo(“value1”);
assertThat(map.get(“key1”).get(1)).isEqualTo(“value2”);

Filter in Java8

Posted on Updated on

public class FilterStreams {

public static void main(String[] args) {

java.util.List<Integer> num = Arrays.asList(1,2,3,4,5,6);
List<Integer> greater = num.stream()
.filter(n -> n >2).collect(Collectors.toList());
System.out.println(greater);

}
}

Filter in Java8

Posted on

public class FilterStreams {

public static void main(String[] args) {

java.util.List<Integer> num = Arrays.asList(1,2,3,4,5,6);
List<Integer> greater = num.stream()
.filter(n -> n >2)
.collect(Collectors.toList());
System.out.println(greater);

}
}