Menu

Void elements in HTML

There are six categories of HTML elements. Void element is one among the six categories that have the following HTML elements. Void elements or tags do not need the closing tag and always be closed in the same opening tag, that's why we also refer to these elements as self-closing elements. Void elements can't have child elements or content.

  1. area
  2. base
  3. br
  4. col
  5. embed
  6. hr
  7. img
  8. input
  9. link
  10. meta
  11. param
  12. source
  13. track
  14. wbr

How to iterate on a JSON objects using Java

Today we are going to see how to iterate on a JSON object or read a JSON file and fetch key and value from that JSON file using Java.

Below is the example code snippet.



 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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
package rashidjorvee;

import java.io.FileReader;

import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
public class JsonReader {
 /* JSON data file
  * [
    {
      "componentName": "comp1""compKey": [
        {
          "keyname": "json_key1",
          "props": [
            {
              "fieldLabel": "Jorvee",
              "name": "./productProperty",
              "id": "productID",
              "sling:resourceType": "granite/ui/components/foundation/form/textfield"
            }
          ]
        }
      ]
    },
    {
      "componentName": "comp2""compKey": [
        {
          "keyname": "json_key2",
          "props": [
            {
              "fieldLabel": "Rashid",
              "name": "./productProperty",
              "id": "productID",
              "sling:resourceType": "foundation/components/parsys"
            }
          ]
        }
      ]
    }
  ]
  */
 public static void main(String[] args) {
  try{
   JSONParser parser=new JSONParser();
   JSONArray a = (JSONArray) parser.parse(new FileReader("D:\\json/jsonFile.json"));
   for (Object comp:a) {
    JSONObject key1 = (JSONObject) comp;
    String componentName = (String) key1.get("componentName");
    System.out.println("componentName: "+componentName);
    JSONArray compkeys = (JSONArray) key1.get("compKey");
    for (Object o : compkeys)
    {
     JSONObject key = (JSONObject) o;
     String keyName = (String) key.get("keyname");
     System.out.println("KeyName: "+keyName);
     
     JSONArray keys = (JSONArray) key.get("props");
     for (Object prop : keys) {
      JSONObject properties = (JSONObject) prop;
      
      String name = (String) properties.get("name");
      System.out.println("Name: " +name);
      
      String fieldLabel = (String) properties.get("fieldLabel");
      System.out.println("City: "+fieldLabel);
      
      String job = (String) properties.get("sling:resourceType");
      System.out.println("resourceType: "+job);
      
      String id = (String) properties.get("id");
      System.out.println("ID: "+id);
      
     }
     System.out.println("\n");
    }
   }
  } catch(Exception e) {}

 }

}

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;
}


Public provident fund (PPF)

Public provident fund(PPF) is the safest investment available in the market for long time investment at least more than 7 years. Actual maturity of PPF is for 15 years and a person cannot withdraw his/her money completely before 15 years, but they can withdraw some amount partially after seven years from the opening of the account.
PPF gives the highest rate of interest in any investment, and RoI is always same with PF and VPF account, as these all are the investment plan from the government of India.

Why you should invest in PPF?

  • Your money will safe in hand of Govt.
  • PPF account is actually managed by India post(post office).
  • A high rate of interest.
  • Tax exemption under 80 C.
  • Interest earned on PPF amount in non-taxable
  • You can open your account at any time with minimum/subscription amount of 500 rupees.
  • Within a financial year you maximum you could submit 150,000 rupees.
  • Funds can be deposited to PPF account, only 12 times in a Financial Year.
  • Premature closure is not allowed before 15 years, but you could partially withdraw after seven years.
  • You can take a loan on this account after the 3rd financial year.

Where to open a PPF account?

PPF is a saving and tax saving scheme of GoI and managed by the post office of India. You could open PPF account with any post office or with any public or private banks.

for more details and current benefits of scheme you could visit Post-Office-Saving-Schemes | indiapost.gov.in

Eclipse shortcuts for Java programming

When you are working with Eclipse IDE to write the java programs, we have too many shortcuts to write the statements in java which Eclipse supports. using these shortcuts you could write your program easy and fast. 
Here I am writing few shortcuts to write java program in Eclipse IDE. Go and try these shortcuts and let us know you have other shortcuts to write and make efficient programming.

Shortcuts commands:

  1. ALT + CTRL + A: to edit and write multiple lines simultaneously  
  2. ALT + Shift + J: Add code Definition
  3. Select a line then ALT + Arrow (Up/Down): to move the code up and down
  4. Shift + Alt + I: to align the code
  5. Shift + mouse hover: to see the method implementation code.
  6. CTRL + O: to see the list of all variables and methods.
  7. CTRL + K: to find matching text within the file.
  8. CTRL + Click on a method name to open the implementation of the method.
  9. Ctrl + space: to open the preference window or template proposal.
  10. You can directly copy and paste your complete code from notepad to eclipse SCR folder, and eclipse will automatically create package and class for that class and paste your code into it. Open notepad > Copy all code from pad > open eclipse > right click on src folder in case if you don't have src folder then right click on project name > select the paste option 
  11. Inline and split variables: select variable then CTRL + 1 and select the option
  12. CTRL + 2, L to assign the value into a local variable
  13. ALT + Shift + M: Select single or multiple lines and move those selected codes in a new method.
  14. Ctrl + Alt-J: to Join more than one lines in a single line
  15. syserr or sysout: to write the complete System.err.println() or  System.out.println() respectively.
  16. Type a string literal "rashid"; select the literal "rashid", then press Ctrl + space, now type sysout/syserr to to pass that string in the argument.


If you face any issue in using these shortcuts then please let us know, we will help you to understand these shorthands.

Java 11 release notes and new features for Java developers

Java 11, released in September 2018, introduced several new features and improvements. Here is a summary of the release notes and some of the key new features in bullet points along with examples:

1. Local-Variable Syntax for Lambda Parameters

   - Allows using `var` as the type of lambda parameters.

   - Example:

// Before Java 11

(String str) -> System.out.println(str);



// Java 11 and later

(var str) -> System.out.println(str);


2. HTTP Client (Standard)

   - The new `java.net.http.HttpClient` API provides a more modern and efficient way to send HTTP requests and receive responses.

   - Example:

HttpClient client = HttpClient.newHttpClient();

HttpRequest request = HttpRequest.newBuilder()

				   .uri(URI.create("https://api.jorvee-java.com/java-sample"))

				   .GET()

				   .build();

HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());

System.out.println(response.body());

3. Enhanced `java.util.stream` API

   - New methods like `takeWhile`, `dropWhile`, `ofNullable` for Stream and Optional.

   - Example:

List<Integer> numbers = List.of(1, 2, 3, 4, 5);
 
// takeWhile
List<Integer> result1 = numbers.stream()
			.takeWhile(n -> n < 4)
			.collect(Collectors.toList()); // Output: [1, 2, 3]


// dropWhile
List<Integer> result2 = numbers.stream()
			.dropWhile(n -> n < 4)
			.collect(Collectors.toList()); // Output: [4, 5]

// ofNullable
Optional<String> optionalValue = Optional.ofNullable(null);

     

4. `var` in Lambda Expression

   - Allows using `var` in lambda expressions, capturing the type from the context.

   - Example:    

     BiFunction<Integer, Integer, Integer> add = (var x, var y) -> x + y;

    

5. Epsilon: A No-Op Garbage Collector

   - Introduces a new garbage collector (`-XX:+UseEpsilonGC`) that does not reclaim memory but allows applications to run without GC overhead.

   - Useful for performance testing or short-lived applications with minimal memory allocation.

6. Nest-Based Access Control

   - Adds support for private interfaces, allowing nested classes to access private members of the enclosing class.

class Outer {

	 private interface InnerInterface {

		 void doSomething();

	 }



	 static class Nested implements InnerInterface {

		 public void doSomething() {

			 System.out.println("Doing something...");

		 }

	 }

}

     

7. Flight Recorder

   - Previously commercial feature, now available for free in OpenJDK.

   - Flight Recorder allows recording and analyzing application events for profiling and debugging purposes.


These are just a few of the new features and improvements introduced in Java 11. The release also includes performance enhancements, security updates, and other improvements. Always ensure to check the complete release notes and documentation for a comprehensive overview of all changes and updates.

Adobe Experience Manager for Content Author

Adobe Experience Manager (AEM) for Beginners

 Adobe Experience Manager(AEM) is a content management system(CMS) used to develop and design a website and web application.


1. What is CMS?

2. Adobe Experience Manager technology stack?

3. What is the component?

4. What is the template?



What is the meaning of Assalam-o-alaykum?

Muslims always greet people with these words; do you ever think, what does it means? and they say only instead of greeting with other words and message like people from other faith greet each other. e.g.
Hello, Hi, Hey, Namaste, Bonjour, yeoboseyo, مرحبا, হ্যালো, שלום, Zdravstvuyte, Hola, Kon'nichiwa, Nǐ hǎo, Hallo, Merhaba, Zdravstvuyte, Salom and many other words of greeting used in this world.
Lets understand the concept behind saying the As-salam-o-alaykum
.L

‏السلام عليكم | As-salam-o-alaykum 

Meaning: May peace be upon you! 



We can see the meaning; the person who is greeting is not only greeting you but s/he is actually making Du'a for you and s/he wants peace upon you from God.
Muslims in their prayer either it is their daily prayers (which is five times in a day), our prayers performed on occasion of Eids and other festivals, Muslims always conclude prayer by saying: As-salmualaykumwarahmatullah — (Means: May peace and blessings of God be upon you!). When they utter these blessings, they turn their heads to the right and the left side and put their gaze on their shoulder respectively. In doing so, they convey the message of peace to all mankind throughout the world.

Here in these videos you could see how a person uttering As-salmualaykumwarahmatullah and concluding his prayer.





لڑکیوں کا ختنہ کروانا | Ladkiyon ka Khtana karwana

Question ID : 155853

Fatwa:176-197/M=3/1439 | Darul Uloom Deoband

:سوال
کیا لڑکیوں کا ختنہ کروانا ضروری ہے؟ یا کہیں سے ثابت ہے کہ ان کا ختنہ کیا جائے؟ بالتفصیل بتائیں۔ اور اگر قرآن و حدیث سے ثابت ہو تو اس کا حوالہ بھی دیں۔

:جواب
لڑکیوں کا ختنہ کروانا ضروری نہیں ہے اور لڑکوں کی طرح سنت بھی نہیں ہے۔


از: وقار علی غفرلہ، نائب مفتی 16/2/1439
الجواب صحیح: حبیب الرحمن عفا اللہ عنہ، محمود حسن بلند شہری غفرلہ
مفتیانِ دارالافتاء، دارالعلوم دیوبند

Purchase of Alaska region

Alaska was earlier part of the Russian Empire. Russia sold Alaska to the United States for 7.2 million US dollars in the year 1867. The Senate approved the treaty of purchase on April 9; President Andrew Johnson signed the treaty on May 28, and Alaska was formally transferred to the United States on October 18, 1867.


Reference

Alaska Map
Alaska part of United States | Picture @ Al Jazeera News

How to create a node or drop component in AEM using java program?

A simple and easy java code to create/add a node or drop a component in AEM.

In this tutorial, we are dropping an AEM component on AEM page (in a parsys or under a specific node) programmatically. To complete this requirement, we have to write code as follows:

First, we have to create an object of ResourceResolver either using ResourceResolverFactory or using session. In this example, we use ResourceResolverFactory interface service API to create the object of ResourceResolver to get the resource from AEM. (code snippet line # 6)
Now we will get the resource using ResourceResolver and adapt that resource in a JCR Node type, so we can deal with that resource and perform manipulation. ResourceResolver has a method getResource resource which makes AME resource available for manipulation. getResource() method required a relative to as parameter to get that resource. (code snippet line # 7)
Then using JCR API we will add a node under that resource/Node with its name(component name) and type(component type). (code snippet line # 8)
After that, we will set all the required property for that component. (code snippet line # 9-13)

Below is the complete code to drop a component in AEM using java. If you have any doubt please comment your doubt and questions in the comment section.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
@Reference
private ResourceResolverFactory resolverFactory;
ResourceResolver resolver;
private void addNodeOrComponentInAEM() {
 try {
  resolver = resolverFactory.getServiceResourceResolver(null);
  Node jcrContent=resolver.getResource("/content/we-retail/ca/en/men/jcr:content").adaptTo(Node.class);
  Node nextbuttonNode=jcrContent.addNode("nextButton","nt:unstructured");
  nextbuttonNode.setProperty("buttonType", "submit");
  nextbuttonNode.setProperty("componentName", "coralButton");
  nextbuttonNode.setProperty("fieldId", "submit");
  nextbuttonNode.setProperty("fieldLabel", "Next");
  nextbuttonNode.setProperty("sling:resourceType", "granite/ui/components/coral/foundation/button");
  
 } catch (Exception e) {
  
 } 
}

Pass by reference and pass by value in Java

Today in this tutorial of Java program we will see how to work with pass by value and pass by reference. 

Below is code snippet.

 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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56

package com.rashid.jorvee;


public class ValueRef {

 public static void main(String[] args) {

  Employee emp=new Employee();

  ValueRef valref=new ValueRef();

  emp.setSalary(12000.00);

  System.out.println("Employee emp salary: " +emp.getSalary());

  valref.salary(emp);

 }

 public void salary(Employee em){

  em.setSalary(14000.00);

  em=new Employee();

  em.setSalary(15000.0);

  System.out.println("Employee em salary: " +em.getSalary());

 }

}



class Employee{

 double salary;

 public double getSalary() {

  return salary;

 }


 public void setSalary(double salary) {

  this.salary = salary;

 }
}

Output:
Employee emp salary: 12000.0
Employee em salary: 15000.0