Menu

How to store multiple values for a key into Map using JAVA

Today we will practice a program to assign or set multiple values or list of values or ArrayList for a key in Map. And also how to iterate on that map and find the value from the list of values.

Declare a Map, with a string or integer key and list or ArrayList type of value; as given in below code in line 10. In this Map, you can store a single value as a key and a list of values you could store into that key in form of a list or array list.
Line 10: Map<String, ArrayList<String>> map = new HashMap<String, ArrayList<String>>();
In line 12 we are creating an ArrayList in which we will store the list of values and we will put this list into Map.
Line 12: ArrayList<String> list = new ArrayList<String>();
Later in line 13 and 14, we are adding values in ArrayList.
Line 13 and 14: list.add("A"+i);
                          list.add("B"+i);
On top of this ArrayList we have created a for loop which will help us to create the pair of 10 unique values of key and value and mapped and put those values into the map.

Line 15 of the code is to put a pair of key and value into a map.
Line 15: map.put("index"+i, list);
We have completed the creation of map. Now we will see how to iterate through the map and pull a particular key or value. or how to find a value into map? or how to find a matching value from a list stored into a map?
To iterate on map first we have to create an object of Entry class with the help of Map and entrySet(). Below is the foreach loop using that we can iterate on all keys of the map.  
Line 19: for(Map.Entry<String, ArrayList<String>> entry : map.entrySet())
Now using the entry object we can pull the key and values of the current iteration index. Below are the codes to getKey() and getValue() from the map. Line 20 of the code will return the value stored as a key, and line 21 will return a list of values stored into the value of the map of the current index.
Line 20: String key = entry.getKey();Line 21: ArrayList<String> value = entry.getValue();
To find a value from map or the list of values stored into the map we will use the matches() method and using regex we could find the matching values at the specified index. In line 23 of the code, we are searching a value B5 which we have stored in the list of values. If we have a list of values then we have to specify the index number using get(index) in which method matches() will search for the requested value.
Line 23: if(entry.getValue().get(1).matches("B5")) 
To search a value from simple key-value pairs of map then we could simply write the above line without get() method. e.g. if(entry.getValue().matches("B5")) and in similar way you could find a key as well. e.g. if(entry.getKey().matches("index7"))

Below is the complete example code which you could directly copy and paste in your IDE and practice this exercise.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
package rashidjorvee;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

public class MultipleValuesInMap {

 public static void main(String[] args) {
  Map<String, ArrayList<String>> map = new HashMap<String, ArrayList<String>>();
  for(int i=1; i<=10; i++) {
   ArrayList<String> list = new ArrayList<String>();
   list.add("A"+i);
   list.add("B"+i);
   map.put("index"+i, list);
  }

  System.out.println(map);
  for(Map.Entry<String, ArrayList<String>> entry : map.entrySet()) {
   String key = entry.getKey();
   ArrayList<String> value = entry.getValue();
   //System.out.println(value.get(1).matches("(?i)b2|B3|B4"));
   if(entry.getValue().get(1).matches("B5")) {
    System.out.println(entry.getKey() +" " +entry.getValue().get(0) +" " +entry.getValue().get(1));
   }
  }
  System.out.println(map.size());

 }

}

metatype=true in AEM

Why we add parameter metatype=true in @Component annotation?


When we add parameter metatype=true then Apache felix generate a metatype.xml file for that component, if we don’t then there will no metaype.xml file.
Metatype.xml file contains an element <OCD> which have parameters name and description of the component. Under the <OCD> we have another ta <AD> which have detail information of property which we want to make visible and configurable on Apache felix console localhost:4502/system/console/configMgr.
So if we specified ten properties in our component then there will be ten <AD> elements under the <OCD>

Metatype.xml file also contains the element <Designate> with attribute PID and <Object> which has parameter OCDREF under the <Designate> element, which represent and store the configured values. Value for PID and OCDREF is always used to same and that is also the name of the file which you will find in the CRX.  

When we add metatype=true in the parameter of @component that means we have made the property of that component or service configurable and visible on Felix console, which is an easy and helpful way to configure properties of any component and service. Felix web console uses the meta type information to show user-friendly and easy the GUI configuration.

interface MetaTypeService helps to obtain the meta type information of any bundle and component. MetaType Service will examine the specified bundle for meta type documents to create the returned MetaTypeInformation object.
If the specified bundle does not contain any meta type documents, then a MetaTypeInformation object will be returned that wrappers any ManagedService or ManagedServiceFactory services registered by the specified bundle that implement MetaTypeProvider. Thus the MetaType Service can be used to retrieve meta type information for bundles which contain a meta-type document or which provide their own MetaTypeProvider objects.

Where I could find the metatype.xml file in my project? Or Where metatype.xml file exist?

[PROJECT NAME]\core\bin\target\classes\OSGI-INF\metatype

Example of a metafile.xml



 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
<?xml version="1.0" encoding="UTF-8"?><metatype:MetaData xmlns:metatype="http://www.osgi.org/xmlns/metatype/v1.0.0" localization="OSGI-INF/metatype/com.rashid.jorvee.aem.services.MetaTypeExample">

    <OCD id="com.rashid.jorvee.aem.services.MetaTypeExample" name="%com.rashid.jorvee.aem.services.MetaTypeExample.name" description="%com.rashid.jorvee.aem.services.MetaTypeExample.description">

        <AD id="MetaType.userID" type="String" name="%com.rashid.jorvee.aem.services.MetaTypeExample.MetaType.userID.name" description="%com.rashid.jorvee.aem.services.MetaTypeExample.MetaType.userID.description"/>

        <AD id="MetaType.contact" type=" Integer " name="%com.rashid.jorvee.aem.services.MetaTypeExample.MetaType. contact.name" description="%com.rashid.jorvee.aem.services.MetaTypeExample.MetaType.contact.description"/>

        <AD id="MetaType.address" type="String" default="Boston, united States" name="%com.rashid.jorvee.aem.services.MetaTypeExample.MetaType.address.name" description="%com.rashid.jorvee.aem.services.MetaTypeExample.MetaType.address.description"/>

    </OCD>

    <Designate pid="com.rashid.jorvee.aem.services.MetaTypeExample">

        <Object ocdref="com.rashid.jorvee.aem.services.MetaTypeExample"/>

    </Designate>

</metatype:MetaData>

In the above example, we have created a service class MetaTypeExample which have following configurable properties.
  1. userID
  2. contact
  3. address


Marriage of Alauddin Khilji and Padmavati

Finally, the day comes when Alauddin Khilji married with Padmavati. On this pious day, Alauddin Khilji most powerful King of 13th century Delhi Sultanate won the heart of prince Padmini as known as Padmavati(queen of Mewar present day in Rajasthan) propose her and bound life-death relation with her, this ceremony also makes an India's biggest myth into reality.

Malik Muhham Jaisi, a poet who was not in the court of Alauddin Khilji, not even he was born in the era of Alauddin Khilji wrote an epic poetry "Padmavat" an imaginative story of a queen which was not based on any real story but Bollywood actor and actress embrace his story and helps him to make it true in the 21st century.

Bollywood actor and actress who played the role of Sultan Alauddin Khilji(Ranbir Singh) and Queen Padmavati(Deepika Padukon) in Movie Padmavaat(directed by Sanjay Leela Bhansali) happily get married on November 14th, 2018.

Reference:

Alauddin Khalji - A powerful king of Delhi Sultanate
Malik Muhammad Jayasi | known for his epic poetry Padmavati
Poem Padmavat- imagination of Malik Muhammad Jayasi
Movie Padmaavat - Directed by Sanjay Leela Bhansali

Tu Reh Naward-e-Shauq Hai, Manzil Na Kar Qabool

تو  رہ  نوارد-ا-شوق  ہے منزل  نہ کر قبول

لیلیٰ  بھی  ہم -نشین  ہو  تو  محمل  نہ  کر  قبول
Tu Reh Naward-e-Shauq Hai, Manzil Na Kar Qabool

Laila Bhi Hum-Nasheen Ho To Mehmil Na Kar Qabool
If you traverse the road of love, Donʹt yearn to seek repose or rest,

If Layla be your companion close that litter shun with great contempt.

اے جوے اب بڑھ کے ہو دریا-ا-تند-و-تیز

ساحل تجھے اتا ہو تو ساحل نہ کر قبول
Ae Jooye Aab Barh Ke Ho Darya-e-Tund-o-Taiz

Sahil Tujhe Atta Ho To Sahil Na Kar Qabool
O streamlet, onward flow and get transformed to torrent strong and deep,

If bank is eʹer on you bestowed, Abstain, flow on with mighty sweep.
کھویا  نہ  جا  صنم  کدہ-و-کائنات میں

محفل گداز گرمی-و-محفل نہ کر قابول
Khoya Na Ja Sanamkada-e-Kainat Mein
Mehfil Gudaz! Garmi-e-Mehfil Na Kar Qabool
Donʹt lose your bearings in this world because with idols it is full,

The assemblage here can cast a spell,disdain, or strings of heart shall pull.
صبح ازل یہ مجھ  سے کہا جبریل نے

جو عقل کا غلام ہو, وہ دل نہ کر قبول
Subah-e-Azal Ye Mujh Se Kaha Jibreel Ne

Jo Aqal Ka Ghulam Ho, Woh Dil Na Kar Qabool
Gabriel on Creationʹs Early Morn, a piece of useful counsel gave,

He bade me not accept a heart enchained by mind of man like slave.
باطل دوویی پسند ہے, حق لا-شریک ہے

شرکت میانہ حق-و-باطل نہ کر قبول

Batil Dooyi Pasand Hai, Haq La-Shareek Hai

Shirkat Mayana-e-Haq-o-Batil Na Kar Qabool
Untruth conceals in various masks but Truth and God are both unique,

There canʹt be pool ʹtwixt good and bad—This fact is known from times antique.

Error: Could not find or load main class

If you are getting the error Error: Could not find or load main class when you try to run any java program in using eclipse then you could perform any of the following resolutions to fix the issue. If a single resolution doesn't work for you then perform the next solution which is given below.

1. Go to your project path for e.g. C:\Users\java\rashid\jorvee > open .classpath file and verify all the entries given in this file are actually exist in your system. Below is the sample file.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
<?xml version="1.0" encoding="UTF-8"?>

<classpath>

 <classpathentry exported="true" kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-1.8"/>

 <classpathentry kind="src" path="src"/>

 <classpathentry exported="true" kind="lib" path="C:/Users/java/rashid/java-json.jar/java-json.jar"/>

 <classpathentry kind="output" path="bin"/>

</classpath>

2. Go to run > run configuration > classpath> Select Project > Advance > select option add folder and select the bin folder where your .class file get stored.

3. There might be a possibility that there is no classpath set for java class files. Please go ahead and set classpath manually by executing the below command on cmd.
javac -cp . PackageName/*.java

4. In some cases we have found that Java build path is not set up for the project, or somehow it gets removed from the directory then go ahead and set your project classpath here. Add your project in the source tab and JRE in libraries tab.
Project > Properties > Java Build Path

AEM Sling Models

What is the Sling Models?

While working with Sling in Adobe Experience Manager[AEM]; we need to map our objects (Java backend object) with  Apache Sling resource. Many Sling projects want to be able to create model objects - POJOs which are automatically mapped from Sling objects, typically resources, but also request objects. With the help of sling models, we can define a model object "a Java class or interface" and map that object with sling resources. Before sling models, we are achieving these all using WCMUse and WCMUsePojo which are quite similar to sling models.

To use the Sling Models in your project first you need to add the following dependency in your pom.xml file.
<dependency>
   <groupId>org.apache.sling</groupId>
   <artifactId>org.apache.sling.model.api</artifactId>
   <version>1.3.0</version>
   <scope>provided</scope>
<dependency>

@Model annotation 

To map a java class or interface with sling resource we use @Model annotation and could pass an adaptables parameter into it to make a class adaptable by sling model.

@Model(adaptables = Resource.class)
public class RashidJorvee {
 //Write your code here
}  
 or
@Model(adaptables = SlingHttpServletRequest.class)
public class RashidJorvee {
 //Write your code here
} 

@Inject annotation

Using @Inject we can make a filed and method injectable. We can also inject a constructor using @Inject annotation. We also use @Inject with @Filter option to pass the reference to an available OSGi service, which works similarly as @Refernce.
@Inject
private String firstName;
@Inject
String getName();
There are many other options we have which makes injection make accurate and exact. like following

@Named

To match the name of the property with field name

@Via

Change the adaptable object instead of using the original adaptable object

@Default 

To assign a defult value to any field or property.

@Filter

Filter an OSGi service

@Optional

Mark filed and method injection optional.

@Source

To manage the ambiguity between injector, it helps us to tie the injected field or method to a particular injector. 

@PostConstruct annotation

Using PostConstruct annotation we can invoke any method which we want to execute when all injection has been completed for that class. This is act as similar to the activate() method which we use for WCMUsePojo or WCMUse.

@PostConstruct
public void letMeExecuteFirst() {
 //Write your code here;
}