Thursday, 27 July 2023

Comparable vs Comparator

Comparable

  • It present in Java.lang Package.
  • It Contains only one Method.
  • Comparable can be used for natural or default sorting ordering.
        compareTo()

Method
  • public int compareTo(Object obj1,obj2)
obj1.compareTo(obj2)
  • Return(-ve), iff obj1 has to come before obj2.
  • Return(+ve), iff obj1 has to come after obj2.
  • Return(0),  iff obj1 & obj2 are equal.
foreg:
  • System.out.println("A".compareTo("z")); 
Return value is Negative/(-ve).
  • System.out.println("z".compareTo("k")); 
Return value is positivetive/(+ve)
  • System.out.println("A".compareTo("A")); 
Return value is Zero/(0)
  • System.out.println("A".compareTo("null"));
Return value is Null Pointer Exception.

Object1:-The Object, which is to be Inserted.
Object2:-The Object, which is already Inserted. 

If We are Depending on Default Natural Sorting Order while adding object in to the TreeSet JVM will call (compareTo) method.

Note:
  • If Default Natural Sorting Order not available or if we are not satisfied with Default Natural Sorting Order, than we can go for Customizer Sorting by using Comparator.
Comparator
  • It present in java.util.Package.
  • Comparator can be used for custom ordering.
    • It defines Two Methods. 
    1. compare() 
    2. equals()
Method
  1. public int compare(object obj1, obj2)
obj1.compareTo(obj2)
  • Return(-ve), iff obj1 has to come before obj2.
  • Return(+ve), iff obj1 has to come after obj2.
  • Return(0),  iff obj1 & obj2 are equal.
  2.public boolean equals(obj)
  • Whenever we are implementing Comparator interface compulsory we should provide implementation only for compare method.
  • we are not required to provide implementation for equals method .Because it is already available to our class from object class through Inheritance. 
For eg of Comparator
  • Write a program To Insert Objects into the TreeSet, Where the Sorting order is Descending Order


Output is


  • If we are not Passing comparator Object than internally JVM will call comparatorTo method, which is meant for Default Natural Sorting Order, In this case the output is 
  • [0,5,10,15,20]
  • If we are passing compare object than, JVM will call compare method which meant for Customizer Sorting in this case output is 
  • [20,15,10.5,0]
Various implementation of compare method
for eg:    Main class
       






result is Ascending Order

  • when you return I1(-ve) & I2(+ve)



Result is Descending 

  • when you return I2(-ve) & I1(+ve
Result is Ascending 



  • when you return -1

Result is [Rverse of Inversion Order]
  • when you return +1
Result is [Insertion Order]


  • when you return 0


Result is[Only First element will be insertion order all remaining consider as Duplicates]



Difference B/w Comparable & Comparator


Wednesday, 19 July 2023

Unit Test for Sling Model using JUnit

What is JUnit?

Java-specific unit testing framework JUnit was developed as an open-source project. It is used to create and execute repeated automated tests that assist programmers in finding and swiftly fixing flaws in their code.

Why do we need JUnit Framework?

  • The Java programming language has an open-source unit testing framework called JUnit.
  • It helps in ensuring that the code is error-free and that every component of the codebase is operating as intended.
  • JUnit integrates with other development tools such as Eclipse and Maven.
  • JUnit provides a structure for writing tests, including annotations to specify test methods, assertions for checking expected results, and rules for organizing and running tests.
  • It gives Code Coverage to complete class/lines.
Which Api we will be using in Sling Model unit Test Case?
  • io.wcm.testing.mock.aem.junit5.*
  • org.mockito.junit.jupiter.*
  • org.junit.jupiter.api.*
How to Write Junit Test case for Sling Model
  • Folded Structure which is important while writing Unit TestCase


  • Inside Core Module you will get src under src you will find two folder one is main and another is test.
Now let's see how to generate test case:
  • I am using Eclipse Ide (integrated development environment) editor to write java code
 

  • Inside test we have models folder, than click right click, than select New, than select other option. 
  • Click on Other Option than search Junit and Select JunitTestCase.



  • Write Name of class and add Test.java.
  • Now, you have a Skeleton of Test class.
  • Now you have to Add Aem Specific Libraries.
  • You have a annotation is
@ExtendWith({ AemContextExtension.class, MockitoExtension.class })
  • This Annotation allow you to use your own Api.
  • Now I have to use Aem related Api
AemContext aemContext = new AemContext();
What is the meaning of @BeforeEach?
  • This method will execute Before each method.
  • used when different test cases share the same logic. The method with the @BeforeEach annotation always runs before the execution of each test case.
  • This annotation is commonly used to develop necessary preconditions for each @Test method.

aemContext.addModelsForClasses(rotationImpl.class);
  • There is a method add Classes add Model for classes now, you have to mention your SlingModel.
  • For this aemContext this is our Model.
  • It means we will be Testing this Model.
Now we talked about resource or Component let's see how to create resource.
  • As I have already discussed we should have json which contain all those properties and from this we will convert that json to resource.
Now we can see how to create json
  • You can get it from Aem itself.
  • Go to that page where it is and copy this path and go to Sling Exporter than paste copy path and Add .infinity.json.



  • Whatever you will save in your Node all data are present in the form of json.







  • Inside test folder resource folder is present than click right button select New and than select File and give name whatever you want and Add .json.
  •  In created folder you copy the whole json here.


 

  • I save properties as the value of a key.

  • Now Load this Json 
aemContext.load().json("/rotation.json", "/component")
  • aemContext.load().json present in "/component" path.

aemContext.currentResource("/component/rotation");
  • It means the current resource means the component than what is the current resource /component.
  • Our Run case is passed.

The Coverage is 100%.
Note:-The Coverage should be more than 50%.





Friday, 7 July 2023

Cursors in Java

What is Cursor?

  • If We want to get Objects One by One from the Collection, than we should go for Cursor.
  • 3 Types of Cursor Available in Java.
  1. Enumeration
  2. Iterator
  3. ListIterator
Enumeration
  • We can Use Enumeration to get Objects One By One From Legacy Classes.
  • We can create Enumeration Object By Using Elements Method of Vector Classes.
        public Enumeration elements();
 for eg:   
        Enumeration e = v.elements();
Methods
  1. public boolean hasMoreElements();
  2. public object nextElement();
Limitations of Enumeration(1.0v)

  • We can apply Enumeration concept only for Legacy Classes and it is not Universal Cursor.
  • By using Enumeration we can get only Read Access & We can't perform Remove Operation.
To Overcome Enumeration Limitations, we should go for Iterator.

Iterator(Interface)
  • We can apply Iterator Concept for any Collection Object.
  • It is Universal Cursor.
  • By using, Iterator We can Perform Both Read & Remove Operations.
  • We can create Iterator Object by using, Iterator Method of Collection Interface. 
         public Iterator iterator()
for eg:
           Iterator itr = c iterator();
Here, c is Any Collection Object.

Methods of Iterator
  • public boolean hasNext();
  • public Object next();
  • public void remove();
Limitations of Iterator
  • By using, Enumeration & Iterator we can always move only towards  Forward Direction & we can't move towards Backward direction these are Single direction cursor.
  • By Using, Iterator we can perform only Read & Remove Operations we can't perform Replacement & Addition of new Object.
To Overcome Iterator Limitations we should go for ListIterator.

ListIterator(Interface)

  • By Using, ListIterator we can move either to the Forward & Backward Direction.
  • It is Bidirectional Cursor.
  • By using ListIterator we can perform, Replacement an addition of new Object in addition to Read & Remove Operations.
  • We can create ListIterator By using, ListIterator method for ListIterator Interface.
          public  ListIterator listIterator();
for eg:
        ListIterator itr = l.listIterator();

Here, l is Any List Object.

Methods Of ListIterator

  • ListIterator is Child Interface of Iterator Hence, All methods present in Iterator By default, available to the ListInterface.
Forward Direction Method
  • public boolean hasNext()
  • public Object next()
  • public int nextIndex()
Backward Direction Method
  • public boolean previousNext()
  • public Object previous()
  • public int previousIndex()
Extra Method
  • public void move()
  • public void add(object o)
  • public void set(object o)
Limitations of ListIterator
  • The Most Powerful Cursor is ListIterator But, it is applicable only for List Objects.




Thursday, 6 July 2023

Set (Interface) & Child Classes of Set Interface

Set

  • Set is Child Interface of Collection.
  • If we want to represent a group of Individual Object as a Single entity, Where Duplicates are not allowed & Insertion Order Not Preserved.
  • Set Interface doesn't have Contain any New Method and we have to use Only Collection Interface Method.



HashSet(Interface)

  • The Underlying Data Structure is HashTable.
  • Duplicates objects are not allowed.
  • Insertion Order is not Preserved & It is based on Hash Code of Objects.
  • Null Insertion is Possible.
  • Heterogeneous Objects are allowed.
  • Implements Serializable & Cloneable but Not Random Access Interface.
  • Hash Set is the Best choice If Our Frequent Operation is Search Operation.
Note:
  • In HashSet Duplicates are Not allowed, If we are trying to Insert Duplicates than we won't get any Compile/Run Time errors & add Method Simply Returns False.
Constructor
  1. HashSet h = new HashSet();
  • Creates an Empty HashSet Objects with Default Intial Capacity is 16 & Default Fill Ratio 0.75.
  2.HashSet h = new HashSet(int intialCapacity);
  • Creates an Empty HashSet Objects with Specified Intial Capacity & Default Fill Ratio 0.75.
  3.HashSet h = new HashSet(int intialCapacity,float fillRatio);
  4.HashSet h = new HashSet(Collection c);
  • Creates an Equivalent HashSet for the given Collection.
  • This Constructor meant for Inter Conversion B/W Collection Objects.
LinkedHashSet
  • It is Child Class of HashSet.
  • It is Exactly Same as HashSet {Including Constructor & Method}.
 Except Some Differences B/W HashSet & LinkedHashSet.


SortedSet
  • It is a Child Interface of Set.
  • If we want to Represent A group of Individual Objects according to Some Sorting Order without Duplication than we should go for SorteSet.
Methods of SortedSet
  • first()-> (1oo)[Return First element].
  • last()->   (110)[Return Last element].
  • headSet()->(100,101,102)[Return less than object].
  • tailSet()-> (106,108,110)[Return greater than object].
  • subSet()-> [Return greater & equal(>=) than object & less than & equal(<=) than object].
  • comparator()-> Returns Describe underlying Sorting Technique. if we are using Default Natural Sorting Order than we will get Null. 
  • for eg:
100
101
102
104
106
108
110
Note:-
  • Numbers-> Default Natural Sortiong Order [Ascending Order]
  • String ->Default Natural Sorting Order [Ascending Order]

NavigableSet
  • NavigableSet is Child class of Sorted Interface.
  • Duplication are Not allowed.
  • Insertion Order Not Preserved.
  • Heterogeneous Objects are allowed.
  • Null Insertion is Possible.
  • NavigableSet implements Serializable & Cloneable but not Random Access Interface.
  • NavigableSet interface provides navigation methods and descending iterator that allows the elements in the set can be traversed in descending order.

TreeSet
  • The Underlying Data Structure is Balanced Tree.
  • Duplication are Not allowed.
  • Insertion Order Not Preserved.
  • Heterogeneous Objects are Not allowed.
  • Null Insertion is Possible.
  • TreeSet implements Serializable & Cloneable but Not Random Access Interface.
  • All Objects will be Inserted based On some Sorting Order.
  • It may be Default Natural Sorting Order .
Constructor
  1. TreeSet t = new TreeSet();
  • Create an Empty TreeSet Object where, the elements will be Inserted according to Default Natural Sorting Order.
  2.TreeSet t = new TreeSet(Comparable c);
  • Create an Empty TreeSet Objects where, the elements will be Inserted according to Customizer Sorting Order Specified by Comparator Object.
  3.TreeSet t = new TreeSet (Collection c);
  4.TreeSet t = new TreeSet (SortedSet s);




Tuesday, 4 July 2023

List(Interface) & Child classes of List Interface

List Interface 



  • We can preserve Insertion order via Indexed.
  • We can differentiate Duplicate order via Indexed.
  • Index will play very important role in List.
  • List Interface defines the following Specific Methods.
8 Methods are present in List 
  • void add(int index, Object o).
  • boolean addAll(int index, Collection c).
  • object get(int index).
  • object remove(int index)
  • object set(int index, Object new)[To replace the element present at specified index with provided Object & returns Old objects]
  • int indexOf (Object O)[Returns index of first occurrence of 'o']
  • int lastIndexOf(Object o)
  • ListIterator listIterator()
  1. ArrayList

  • The underlying data structure is Resizable Array & Growable Array.
  • Duplicates are allowed.
  • Insertion Order Preserved.
  • Heterogeneous Objects are allowed[It means Different type of Objects].
  • Null Insertion is Possible.
Constructor

In ArrayList 3 types of Constructor are available
  a).ArrayList l = new ArrayList();
  • It means Create empty ArrayList object with default intial Capacity.
  • for eg:- The capacity is 10.
  • One's ArrayList reaches Max Capacity than a new ArrayList object will be created
   new Capacity = (current Capacity*3/2)+1


      b. ArrayList l = new ArrayList(int intialCapacity);
  • Creates an empty ArrayList Objects with Specified Intial Capacity.
  c.ArrayList l = new ArrayList(Collection c);
  • Creates an equivalent ArrayList object for the given Collection.
Note:-
  • Usually we use Collection to hold underlying objects from One Location to another Location[Container]. To provide Support for this requirement every collection class by default implements Serializable and the Cloneable Interface.
  • ArrayList & Vector class implements Random Access Interface so, that any Random element with the access with same speed.
  • Random Access Interface present in Java.util Package. Doesn't contain any Methods. It is Marker Interface Required ability will be provided by JVM.
 When ArrayList is Worst Choice?
  • If our Frequent Operation is Insertion & Deletion in a middle. 
 When ArrayList is Best Choice and Why?
  • If Our Frequent Operation is Retrieval Operation.
  • Because ArrayList implements Random Access Interface
How to get Synchronized Version of ArrayList Object?
  • By default ArrayList is Non-Synchronized but we can get Synchronized version of ArrayList object.
  • By using SynchronizedList Method of Collection Class.
  • For eg:
     ArrayList l = new ArrayList();
     List l1 = collections.synchronizedList(l);

2.LinkedList
  • The Underline data structure(Double/Doubly LinkedList).
  • Insertion Order is Preserved.
  • Duplicates are allowed.
  • Heterogeneous Objects allowed.
  • Null Insertion is Possible.
  • LinkedList implements Searlizable & Cloneable Interfaces.
  • Not Implements Random Access Interface.
Constructor 

     a. LinkedList l = new LinkedList();
  • Creates an Empty LinkedList Object.
  b. LinkedList l = new LinkedList(collection c);
  • Creates an Equivalent LinkedList object for the given Collection.
LinkedList Specific Methods

  • void addFirst(object o);
  • void addLast(object o);
  • Object getFirst();
  • Object getLat();
  • Object removeFirst();
  • Object removeLast();
Usually We can use LinkedList to implements Stack & Queue.

What is Difference B/w LinkedList & ArrayList?



3.Vector
  • The Underlying data Structure is Resizable Array & Growable Array.
  • Insertion Order Preserved.
  • Duplication are allowed.
  • Heterogeneous Objects are allowed.
  • Null Insertion is possible.
  • It Implements Serializable, cloneable & Random Access Interface.
  • Every Method present in the Vector is Synchronized and Vector Object is Thread-Safe.

Constructor

a. Vector v = new Vector();
  • Creates an empty vector Object with default initial Capacity 10.
  • Once, Vector reaches it's Max Capacity than, New Vector Object will be created with 
  •      New capacity=current capacity*2 

b. Vector v = new Vector(int initial capacity);
  • Creates an empty Vector Object with Specified initial Capacity.
c.  Vector v = new Vector(int initialcapacity , int                 incrementalcapacity).
  • for eg: Vector v = new v (1000, 5);

d. Vector v =new Vector(collection c);
  •   Creates an equivalent vector object for the given collection these constructor meant for interconversion B/w Collection Objects. 
  
What is Difference B/w ArrayList & Vector?


Methods
  • int Size();
  • int Capacity();
  • Enumeration element();
  • addElement(Object o);
  • removeElement(object o);
  • object get(int index); 



Stack
  • It is Child Class of Vector.
  • It is Specially Designed Class Last In First Out.(LIFO).
Constructor

Stack s = new Stack();

Methods

  • Object push(object o);
     To Insert an Object into Stack.
  • Object pop();
     To Remove & Return Top of the Stack.
  • Object peek();
     To return Top of the Stack without Removal.
  • Boolean empty();
     Returns true If the Stack is Empty.
  • int Search(object o);
     Return Offset if the element is available otherwise return -1.















Servlet in AEM/Sling Servlet

  What is Servlet? A servlet is a Java class that runs on the server side where the application resides. It acts as a middle layer between t...