@Component -- for DAO layer works fine but readability/visibility wise its bad
@Service -- Service layer
@Controller -- Business Logic
@Repository -- we use this annotation to DAO layer -- Benifits this helps to handle persistance level exceptions that spring provides
DataAccessException is the root class which spring provides for handling exceptions
@PostConstruct
Called first during initialisation(Creating data base connections)
@Predestroy
called B4 the container is destroyed and bean is out of container(Close all the DB connections/clean up work)
Rest client
---------------------
Rest template --- Client to consume the data (make a call to get , put,post)
getForEntity and getForObject -- methods belong to resttemplate
getForObject -- returns object
getForEntity -- returns header,body , what ever we want
Exchange method - same purpose belongs to rest template
While wrting an API , what are the advantages of returning entity??
We can send http status and body and headers
For delete API, what kinld of status code you will return
204 /200
Time out when ever we are going for rest template?
Basically when connecting to server connections are made with threads.
Thread is blocked if the connection is not establised and then another user tries and another thread is blocked .
So just to avoid that time out is needed so that thread is released
Can we have many threads inside the server?
yes
Server time out -- connection not established
Read time out -- connection established but not able to read some data
Versioning in rest
---------------------------
Adding a new functionality to the API and user should use the new one
Can be defined using request parameters and can be mentioned in headers
URi also it can be defined
How authentication in rest web services and how we make rest web servives secure?
Security configuration class which will be extending securityconfigurationAdapter class
Hitting a request goes to authentication filter which will give us authentication object and this object is paased to authentication builder which will provide proper authentication provider which will validate this object.
Some of the authentication providers are DAO Authentication Provider, we can define even our own
Authentication provider internally passes back to builder which will pass to security holder So next time when user logs in object will be checked by the security holder and user will be allowed to sign in
Header we pass the tokens , like jwt tokens which will be used for authentication and server will validate it.These are stateless i.e server wont store any inf and client will alwyas send relavant information via header.
Bearer is written in jwt token??Means syou are the owner .JWT used for authorisation .Once we give uname and pwd we get authorisation token which weill again be sending to the server which will in turn verify the token
In basic authentication where we give username and pwd where we can use base64 encoded
Content Negotiation?
What kinld of content API should accept/produce.It can be achieved using MediaType
Cross Cutting Concerns in spring?And do you implement that?
Belongs to spring AOP used for logging purpose .We want to log after the particular method or so..
Monitoring , secutity.after one method we have to perform security then it can be done
In micro services suppose we want to implement logging,tracing??Where will be implementing these?
At gateway level we ill be doing
Custom validators in spring can be created by implementing validator class
There is a method over ride and write the logic
Core Java
------------------
We have define ArrayList as Size 2 and then add 3 elements ..Will third elemt be added?
Yes it will be added as the arraylist dynamicallu grows in size
1 million string objects to array list added with out specifying size and in a for loop you are adding then it takes total og 613 ms to complete else if you specify size then it will run in 193 ms.
Internally it regrows and calls Arrays.Copyof which will create a new Array and then copy all the elements, so suppose if we have lot of elements and if its size is specified then it allocates so much and then no copy of array or new array creation is needed
Fail fast and fail safe collections
----------------------------------------
Iterators
fail fast used by arraylist/ linked list --During itration if we try to add /modify it gives concurrent modification exception
Fail safe : Thread safe ..CopyOnWriteArrayList , Concurrent hash map ...Modification during iteration it works perfectly fine
Fail safe is going to consume more memory , modification operations will be perfomred on a copy of collections not on the orinal collections
Arrays.asList will give us an unmodifyable list , which we cannoot alter
SingleTon Design pattern
--------------------------
Object for the class can be created only one(For the entire run time)
Scope Single ton in spring means one bean per container(one per application context)
1)Since a priority queue needs to compare its elements and order them accordingly, the user defined class must implement the Comparable interface, or you must provide a Comparator while creating the priority queue. Otherwise, the priority queue will throw a ClassCastException when you add new objects to it.(https://www.callicoder.com/java-priority-queue/)
2)By default all wrapper class implement comparable interface
Leet Code problem 347. Top K Frequent Elements
Example 1:
Input: nums = [1,1,1,2,2,3], k = 2
Output: [1,2]
Example 2:
Input: nums = [1], k = 1
Output: [1]
Solution we are going to use HashMap , Priority queue and Array
package LeetCode;
import java.util.HashMap;
import java.util.PriorityQueue;
import java.util.Queue;
public class TopKElements {
public int[] topKEmements(int[] nums, int k) {
HashMap<Integer, Integer> cache = new HashMap<>();
for (int num : nums) {
cache.put(num, cache.getOrDefault(num, 0) + 1);
}
Queue<Integer> minHeap = new PriorityQueue<>((a, b) -> cache.get(a) - cache.get(b));// Comparator so that it
// gets stored in the order
// where least occured
// element is stored in the
// top
for (int num : cache.keySet()) {
minHeap.add(num);
if (minHeap.size() > k) {
minHeap.poll();
}
}
int[] arr = new int[k];
int index = 0;
while (minHeap.size() != 0) {
int val = minHeap.poll();
arr[index++] = val;
}
return arr;
}
public static void main(String[] args) {
TopKElements elements = new TopKElements();
int[] nums = { 1, 1, 1, 2, 2, 3 };
int[] result = elements.topKEmements(nums, 2);
for (int number : result) {
System.out.println("Result is " + number);
}
}
}
Kth larets element in an array
Formula could be (length of array - k) this will give the index of the kth largest element
For example [ 2 1 3 8 9] is the array k =2 that means finf 2nd largest
Step 1: Sort the array [1 2 3 8 9]
step 2:length of array - k --> (5 -2) which is 3 i.e at 3rd index we have 2nd largets element
Similarlly 3rd largets means
5-3 which is 2 i.e at 2nd index we have 3rd largest element in the array
Using priority queue approach
----------------------------------------
1)Insert elements in to priority queue which will be inserted in to default ordering i.e least element will be removed first when we poll
2)We poll from queue when size becomes grater than k
that where we get result
Following is the code
package LeetCode;
import java.util.Arrays;
import java.util.PriorityQueue;
public class KthLargetsElement {
public int findkthLatgestUsingBruteForce(int[] numbers, int k) {
Arrays.sort(numbers);
int kthIndex = numbers.length - k;
return numbers[kthIndex];
}
public int findkthLargestUsingPriorityQueue(int[] numbers, int k) {
PriorityQueue<Integer> pq = new PriorityQueue<>();
for (int num : numbers) {
pq.offer(num);
if (pq.size() > k) {
pq.poll();
}
}
return pq.peek();
}
public static void main(String[] args) {
KthLargetsElement element = new KthLargetsElement();
int[] numbers = { 102 ,6,100,500,78 };
int k = 2;
int result = element.findkthLatgestUsingBruteForce(numbers, k);
System.out.println(k + "th largest element is " + result);
int resultUsingPriorityQueue = element.findkthLargestUsingPriorityQueue(numbers, k);
System.out.println("Result using priority queue " + resultUsingPriorityQueue);
HashMap allows null as a key and so hashcode for this will always be zero , even empty string can be given as a key and it also hols the hash code zero but internally they are stored in different indexes
Concurrent hashmap does not allow null as a key , Hash table also does not allow null key
Some sample example below
Oct 06, 2020 12:39:06 PM MapContainsGet logMapInfo
INFO: HashMap: {NEVADA=Carson City, WASHINGTON=Olympia, NORTH_DAKOTA=Bismark, MONTANA=null, ARIZONA=Phoenix, UTAH=Salt Lake City, OREGON=Salem, COLORADO=Denver, SOUTH_DAKOTA=Pierre, IDAHO=Boise, NEW_MEXICO=Sante Fe, CALIFORNIA=Sacramento, WYOMING=Cheyenne}
Oct 06, 2020 12:39:06 PM MapContainsGet demonstrateGetAndContains
INFO:
Map of type java.util.HashMap returns null for Map.get() using Montana
Map of type java.util.HashMap returns true for Map.containsKey() using Montana
Map of type java.util.HashMap returns null for Map.get() using Kansas
Map of type java.util.HashMap returns false for Map.containsKey() using Kansas
Oct 06, 2020 12:39:06 PM MapContainsGet logMapInfo
INFO: LinkedHashMap: {ARIZONA=Phoenix, CALIFORNIA=Sacramento, COLORADO=Denver, IDAHO=Boise, NEVADA=Carson City, NEW_MEXICO=Sante Fe, NORTH_DAKOTA=Bismark, OREGON=Salem, SOUTH_DAKOTA=Pierre, UTAH=Salt Lake City, WASHINGTON=Olympia, WYOMING=Cheyenne, MONTANA=null}
Oct 06, 2020 12:39:06 PM MapContainsGet demonstrateGetAndContains
INFO:
Map of type java.util.LinkedHashMap returns null for Map.get() using Montana
Map of type java.util.LinkedHashMap returns true for Map.containsKey() using Montana
Map of type java.util.LinkedHashMap returns null for Map.get() using Kansas
Map of type java.util.LinkedHashMap returns false for Map.containsKey() using Kansas
Oct 06, 2020 12:39:06 PM MapContainsGet generateStatesMap
SEVERE: java.util.concurrent.ConcurrentHashMap does not allow for null values - java.lang.NullPointerException
Oct 06, 2020 12:39:06 PM MapContainsGet logMapInfo
INFO: ConcurrentHashMap: {NEVADA=Carson City, WASHINGTON=Olympia, NORTH_DAKOTA=Bismark, ARIZONA=Phoenix, UTAH=Salt Lake City, OREGON=Salem, COLORADO=Denver, SOUTH_DAKOTA=Pierre, IDAHO=Boise, NEW_MEXICO=Sante Fe, CALIFORNIA=Sacramento, WYOMING=Cheyenne}
Oct 06, 2020 12:39:06 PM MapContainsGet demonstrateGetAndContains
INFO:
Map of type java.util.concurrent.ConcurrentHashMap returns null for Map.get() using Montana
Map of type java.util.concurrent.ConcurrentHashMap returns false for Map.containsKey() using Montana
Map of type java.util.concurrent.ConcurrentHashMap returns null for Map.get() using Kansas
Map of type java.util.concurrent.ConcurrentHashMap returns false for Map.containsKey() using Kansas
Oct 06, 2020 12:39:06 PM MapContainsGet logMapInfo
INFO: EnumMap: {ARIZONA=Phoenix, CALIFORNIA=Sacramento, COLORADO=Denver, IDAHO=Boise, MONTANA=null, NEVADA=Carson City, NEW_MEXICO=Sante Fe, NORTH_DAKOTA=Bismark, OREGON=Salem, SOUTH_DAKOTA=Pierre, UTAH=Salt Lake City, WASHINGTON=Olympia, WYOMING=Cheyenne}
Oct 06, 2020 12:39:06 PM MapContainsGet demonstrateGetAndContains
INFO:
Map of type java.util.EnumMap returns null for Map.get() using Montana
Map of type java.util.EnumMap returns true for Map.containsKey() using Montana
Map of type java.util.EnumMap returns null for Map.get() using Kansas
Map of type java.util.EnumMap returns false for Map.containsKey() using Kansas
Immutable objects are a very important element of application building, which makes applications more legible and consistent, as well as more error-proof. Every developer should know how to use immutable objects and what benefits are associated with their use.
Writing this post I didn’t think about the disadvantages of creating immutable classes. Fortunately, a user potracheno informed about it in the comment. Thanks!
Immutable objects have far more advantages than disadvantages. The only thing that comes to my mind is the cost of memory. With immutability, any time you need to modify data, you need to create a new object. This can be expensive. If you are sure that you will not need immutability (e.g. you are creating a simple single-threaded application) - do not create immutable code.
Advantages of immutable objects
These objects make us avoid accidental changes, often in very inappropriate places. If an object is changeable, there will definitely be someone who wants to change it where it should not.
A good example of such a situation is the object that we pass as a parameter of the method. Such an object can be passed between multiple application layers, between multiple method calls. It can be passed on very deep in the call hierarchy. This makes it very difficult to identify where it was changed. This can lead to many strange and difficult to solve problems.
Using immutable objects we do not have such problems and the design of our application improves.
Invariant objects are also safe for multithreaded use. If an object is not changed, it can be safely transferred between threads without synchronization.
Another advantage is that such objects are ideal as key objects in maps. In a situation where keys are variable, after changing the key object its hashcode changes, making it impossible to find the stored value in HashMap.
How to create immutable objects?
Such objects can be created in three ways. Through the constructor and that is the easiest way. But it has a fundamental disadvantage. The more fields to initiate, the more parameters in the constructor. That’s why you shouldn’t create objects that have more than 2-3 fields.
Another way is the factory method. As with the constructor, the more fields, the more parameters. But this approach has such an advantage that we can create several such methods with a different names, with different set of parameters, which improves readability.
A third way to create immutable objects is to use the builder pattern. In order to use the builder, it must be implemented inside the class so that it has access to private class fields.
We can write such a builder manually or use some kind of IDE plugin to generate it for us. Another option is to use Lombok and @Builder annotation.
What is an immutable object?
An immutable object is one which, after being created and initialized, remains unchanged and, importantly, cannot be changed (in a conventional way, of course). This means that such an object does not provide methods that allow changing its state. And all its fields are private (or public final).
This changeability is a little apparent, because, using reflection, you can change the field values in each class. However, this does not mean that for this reason, we should give up immutable objects.
How to ensure the object’s immutability?
Apart from the fact that all fields should be private, they should be final. And the class itself should be marked as final so that it cannot be inherited. Such an object should not provide methods to modify its internal state, e.g. setters.
But private, final fields are not everything. It is important what types of data we store in these fields. It should also be unchangeable! If the fields in your object are primitives, primitive wrappers or Strings then there is no problem. All these types are immutable. But if you use your own objects, you must ensure that they are unchangeable.
Strategy defines a family of interchangeable algorithms (in the form of classes) that are used to solve the same problem in several different ways.
Number converter with the strategy pattern
Imagine that you want to create a system to convert numbers into different Numeral Systems . As in the previous example, we will start with the interface:
Time for implementation. We will add support to convert number to octal, binary and hex system:
According to the diagram at the beginning of the post - we will create a class Context that will use our strategies: