Friday, May 23, 2014

JVM: Java Heap & Stack

When does Heap gets created?
 Heap gets create on the startup of JVM. 
What is Heap structure (young space/nursery and old space) 
When an object created it is first stored and placed on young space or nursery and if it lives there for longer time it is moved to old space. The design goal behind young space and old space is that newly created objects are short lived and since they are placed on young space their access is faster. 
How memory is allocated to Objects? 
While assigning memory on Heap, Objects are first identified whether they are small or large? Small objects are allocated in Thread Local Areas (TLA). TLA are free chunk of space reserved from Heap and is given to thread for exclusive use. Thread can then allocate objects in its TLA without synchronizing with other threads. When the TLA becomes full, the thread simply requests a new TLA. The TLAs are reserved from the nursery if such exists; otherwise they are reserved anywhere in the heap. Large objects that don’t fit inside a TLA are allocated directly on the heap. 
What are Shallow and retained sizes? 
Shallow size of an object is the amount of memory allocated to store the object itself, not taking into account the referenced objects. Shallow size of a regular (non-array) object depends on the number and types of its fields. Shallow size of an array depends on the array length and the type of its elements (objects, primitive types). Shallow size of a set of objects represents the sum of shallow sizes of all objects in the set. 
Retained size of an object is its shallow size plus the shallow sizes of the objects that are accessible, directly or indirectly, only from this object. In other words, the retained size represents the amount of memory that will be freed by the garbage collector when this object is collected. 
What is allocated on stack and heap? 
'Local variables' like function arguments or variables inside a function are only 'allocated' on the stack (primitive value or reference). Object Instance and static variables are stored on the heap.

Thursday, May 22, 2014

Scala: Another way of handling exceptions using Scala Try

A nicer way to handle a scenario where you are expecting an operation to return a value or an exception and based on result you want to perform some action.

Let’s consider a very simple example/function below:

def divide(x:Integer, y:Integer) = x/y

   
All we are doing here accepting 2 numbers as parameter to divide function and dividing them to return a result. When the parameter value of “y” is “0” we’ll get an error (divide by zero) and we want to handle that error.

There are various ways in which this can be done:
1)    Using try catch block Or,
2)    Using Try class

In this example we’ll use second method. Before look at the example, “Try” class in Scala provides a function where you can wrap a result in “Try” and it provides two methods to explicitly check whether the operation was success and “Try” has valid result or not.

Let’s have a look at the example:
val tryWrapper = Try(divide(1, 2));

tryWrapper.isSuccess match {

 case true => println("Success: " + tryWrapper.get)

 case _ => println("Error")

}


Here we are wrapping divide() function call in a Try and we are explicitly check whether the operation was successful or not using isSuccess function of Try. When the operation is successful we also want to extract the result from Try, this can be done using get()  or getOrElse() function (similar to get or getOrElse operation on Option[]).

Sunday, May 18, 2014

Create an AEM (CQ) project using Maven


This article is mainly focused on setting up only project structure for CQ/AEM project using maven and guides you through how you can do your day to day development of AEM/CQ project with eclipse. In next article we’ll see how to develop templates, components and other things in details.

Before you go through this article it highly recommended that you have fair knowledge of Maven and at least folder structure of an AEM/CQ project. If you are in hurry, I’ll try to provide a very high level explanation of these two things but, I’ll recommend you to explore that in detail.

1) Typical AEM/CQ project: any web application is mainly composed of view (HTML, JSP etc.), CSS, JavaScript and some server side code. An AEM application is nothing different than this. A typical AEM application will have following folder structure:
  • /apps (Top level folder that is parent for all the code that you’ll develop)
  • /apps/[YOUR_APP_NAME]/components/[CQ templates and components] (contains mostly JSP or other scripts responsible for rendering) 
  • /apps/[YOUR_APP_NAME]/config (contais configuration for a project)
  • /apps/[YOUR_APP_NAME]/install (contains bundles/jar for server side logic) /etc/design/[design assets for your site] (Typically all CSS, JavaScript etc. are stored here and access using CQ Client lib. More information about ClientLibs can be found here: http://suryakand-shinde.blogspot.in/2012/01/clientlib-cq-static-resource-management.html) 
  • /content/dam/[images, docs, any other digital assets] 
  • /content/[YOUR_SITE_ROOT]
2) Maven is a tool for managing project dependences, build management and automation framework. There are many maven plugin available in market to automate various tasks. In this article also we’ll use few maven plug-ins to automate the task of CQ package creation & installation etc.

Before we go into details, let’s see few benefits of configuring CQ project with maven and doing development in eclipse:
  1. You can break your project in to smaller modules that can be managed individually. 
  2. You can do build automation for maven projects easily using Jenkins etc. 
  3. Unit testing becomes easier. Writing test cases becomes easier when you have broken down your project in separate modules (components, templates in one module and you java code for bundles in another module)
Before we start creating actual project, following installations should be there on your machine:
  1. Maven 
  2. CQ/AEM author environment 
  3. Eclipse with Vault Plug-in (VLT Plug-in for eclipse can be downloaded from http://sourceforge.net/projects/vaultclipse) 

Create AEM/CQ Maven Project

Source code for this project can be found here: https://suryakand.googlecode.com/svn/aem/simple-aem-maven-project

We have seen some benefits of maven for CQ projects and have basic knowledge of CQ project structure by now. Typically, a CQ/AEM maven project will be a modular maven project with multiple modules. For this article we’ll create a top level project that contains two modules “bundles” and “content”.

Follow these steps to create a maven project:
Step 1: create a maven project using adobe aem's maven archetype. When you run the command it’ll as for project information on command prompt that you’ll need to provide:
mvn archetype:generate -DarchetypeGroupId=com.day.jcr.vault -DarchetypeArtifactId=multimodule-content-package-archetype -DarchetypeVersion=1.0.2 -DarchetypeRepository=adobe-public-releases

This will create a maven project with two modules one for bundle and another one for content as shown in Fig: AEM eclipse project. a) content: this is where you'll put your templates, components etc. b) bundle: all java code that is responsible for creating bundle will go here.

Step 2: Verify project After the project is created, run the following command just to make sure that everything generated as expected. The build should complete without any error:
mvn clean install

Step 3: Import project into eclipse Once the build is successful, import the project in to eclipse using File-> Import -> Existing Maven Projects -> browse to the directory where you have parent pom.xml file -> Finish


 Fig. 1: Typical AEM/CQ project structure

Step 4: Import project into CQ Now that we have a project ready, next thing that we’ll do is try to install the project (content and bundle) in local author (http://localhost:4502). Execute following command from the directory where we have parent project’s pom.xml file:
mvn clean install –PautoInstallPackage

NOTE: “autoInstallPackage” is a maven profile that is defined in “content” project’s pom.xml file. Go to the CRXDLite and check whether the apps folder contains your project or not?

Most of the stuff has been done for us by maven plug-in but, it is important to understand what is going on behind the scene before we start our day to day development so, let’s see what maven did for us. As evident from the screen shot above maven created a parent project with 2 module projects (bundle and content) for us. “bundle” and “content” are also maven project and they have their own pom.xml file. Let’s look at each pom.xml carefully:

1) pom.xml of parent project: See the comments/NOTE in below XML file for more information about various sections and their usage. I have omitted some part of XML to keep it short so that we can focus on important sections:

<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://maven.apache.org/POM/4.0.0" xsi:schemalocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
 <modelversion>4.0.0</modelversion>
 <groupid>com.surya.aem</groupid>
 <artifactid>blog-sample</artifactid>
 <version>1.0-SNAPSHOT</version>
 
 <packaging>pom</packaging>

 <name>Blog Sample - Reactor Project</name>
 <description>Maven Multimodule project for Blog Sample.</description>

 <prerequisites>
  <maven>3.0.2</maven>
 </prerequisites>

 
 <properties>
  <crx .host="">localhost</crx>
  <crx .port="">4502</crx>
  <crx .username="">admin</crx>
  <crx .password="">admin</crx>
  <publish .crx.host="">localhost</publish>
  <publish .crx.port="">4503</publish>
  <publish .crx.username="">admin</publish>
  <publish .crx.password="">admin</publish>
  <project .build.sourceencoding="">UTF-8</project>
  <project .reporting.outputencoding="">UTF-8</project>
 </properties>

 <dependencymanagement>
  <dependencies>
   
  </dependencies>
 </dependencymanagement>

 <repositories>
  <repository>
   <id>adobe</id>
   <name>Adobe Public Repository</name>
   <url>http://repo.adobe.com/nexus/content/groups/public/</url>
   <layout>default</layout>
  </repository>
 </repositories>
 <pluginrepositories>
  <pluginrepository>
   <id>adobe</id>
   <name>Adobe Public Repository</name>
   <url>http://repo.adobe.com/nexus/content/groups/public/</url>
   <layout>default</layout>
  </pluginrepository>
 </pluginrepositories>

 <build>
  <pluginmanagement>
   <plugins>
    
        
    <plugin>
     <groupid>org.apache.sling</groupid>
     <artifactid>maven-sling-plugin</artifactid>
     <version>2.1.0</version>
     <configuration>
      <username>${crx.username}</username>
      <password>${crx.password}</password>
     </configuration>
    </plugin>
         
    <plugin>
     <groupid>com.day.jcr.vault</groupid>
     <artifactid>content-package-maven-plugin</artifactid>
     <version>0.0.20</version>
     <extensions>true</extensions>
     <configuration>
      <failonerror>true</failonerror>
      <username>${crx.username}</username>
      <password>${crx.password}</password>
     </configuration>
    </plugin>
    <plugin>
     <groupid>org.eclipse.m2e</groupid>
     <artifactid>lifecycle-mapping</artifactid>
     <version>1.0.0</version>
     <configuration>
      
      
     </configuration>
    </plugin>
   </plugins>
  </pluginmanagement>
 </build>

 <profiles>
   
  <profile>
   <id>autoInstallBundle</id>
   <build>
    <plugins>
     <plugin>
      <groupid>org.apache.sling</groupid>
      <artifactid>maven-sling-plugin</artifactid>
      <executions>
       <execution>
        <id>install-bundle</id>
        <goals>
         <goal>install</goal>
        </goals>
       </execution>
      </executions>
     </plugin>
    </plugins>
   </build>
  </profile>
 </profiles>
 
 
 <modules>
  <module>bundle</module>
  <module>content</module>
 </modules>
</project>

2) pom.xml of bundle module:

<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://maven.apache.org/POM/4.0.0" xsi:schemalocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd ">
    <modelversion>4.0.0</modelversion>
    <parent>
        <groupid>com.surya.aem</groupid>
        <artifactid>blog-sample</artifactid>
        <version>1.0-SNAPSHOT</version>
    </parent>

    <artifactid>blog-sample-bundle</artifactid>
    <packaging>bundle</packaging>
    <name>Blog Sample Bundle</name>

    <dependencies>
  
    </dependencies> 

    <build>
        <plugins>
   
            <plugin>
                <groupid>org.apache.felix</groupid>
                <artifactid>maven-scr-plugin</artifactid>
                <executions>
                    <execution>
                        <id>generate-scr-descriptor</id>
                        <goals>
                            <goal>scr</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
            <plugin>
                <groupid>org.apache.felix</groupid>
                <artifactid>maven-bundle-plugin</artifactid>
                <extensions>true</extensions>
                <configuration>
                    <instructions>
                        <bundle-symbolicname>com.surya.aem.blog-sample-bundle</bundle-symbolicname>
                    </instructions>
                </configuration>
            </plugin>
      
            <plugin>
                <groupid>org.apache.sling</groupid>
                <artifactid>maven-sling-plugin</artifactid>
                <configuration>
     
                    <slingurl>http://${crx.host}:${crx.port}/apps/blog/install</slingurl>
                    <useput>true</useput>
                </configuration>
            </plugin>
            
        </plugins>
    </build>
</project>

3) pom.xml of content project:
<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://maven.apache.org/POM/4.0.0" xsi:schemalocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
    <modelversion>4.0.0</modelversion>
    <parent>
        <groupid>com.surya.aem</groupid>
        <artifactid>blog-sample</artifactid>
        <version>1.0-SNAPSHOT</version>
    </parent>

    <artifactid>blog-sample-content</artifactid>
    <packaging>content-package</packaging>
    <name>Blog Sample Package</name>

    <dependencies>
        <dependency>
            <groupid>${project.groupId}</groupid>
            <artifactid>blog-sample-bundle</artifactid>
            <version>${project.version}</version>
        </dependency>
    </dependencies>
    <build>
        <resources>
            <resource>
                <directory>src/main/content/jcr_root</directory>
                <filtering>false</filtering>
                <excludes>
                    <exclude>**/.vlt</exclude>
                    <exclude>**/.vltignore</exclude>
                </excludes>
            </resource>
        </resources>

        <plugins>
            <plugin>
                <groupid>org.apache.maven.plugins</groupid>
                <artifactid>maven-resources-plugin</artifactid>
                <configuration>
                    <includeemptydirs>true</includeemptydirs>
                </configuration>
            </plugin>
  
            <plugin>
                <groupid>com.day.jcr.vault</groupid>
                <artifactid>content-package-maven-plugin</artifactid>
                <extensions>true</extensions>
                <configuration>
                    <group>Blog Sample</group>
                    <filtersource>src/main/content/META-INF/vault/filter.xml</filtersource>
                    <embeddeds>
      
                        <embedded>
                            <groupid>${project.groupId}</groupid>
                            <artifactid>blog-sample-bundle</artifactid>
                            <target>/apps/blog/install</target>
                        </embedded>
                    </embeddeds>
                    <targeturl>http://${crx.host}:${crx.port}/crx/packmgr/service.jsp</targeturl>
                </configuration>
            </plugin>
        </plugins>
    </build>
    <profiles>
  

        <profile>
            <id>autoInstallPackage</id>
            <build>
                <plugins>
                    <plugin>
                        <groupid>com.day.jcr.vault</groupid>
                        <artifactid>content-package-maven-plugin</artifactid>
                        <executions>
                            <execution>
                                <id>install-content-package</id>
                                <phase>install</phase>
                                <goals>
                                    <goal>install</goal>
                                </goals>
                            </execution>
                        </executions>
                    </plugin>
                </plugins>
            </build>
        </profile>
    
        <profile>
            <id>autoInstallPackagePublish</id>
            <build>
                <plugins>
                    <plugin>
                        <groupid>com.day.jcr.vault</groupid>
                        <artifactid>content-package-maven-plugin</artifactid>
                        <executions>
                            <execution>
                                <id>install-content-package-publish</id>
                                <phase>install</phase>
                                <goals>
                                    <goal>install</goal>
                                </goals>
                                <configuration>
                                    <targeturl>http://${publish.crx.host}:${publish.crx.port}/crx/packmgr/service.jsp</targeturl>
                                    <username>${publish.crx.username}</username>
                                    <password>${publish.crx.password}</password>
                                </configuration>
                            </execution>
                        </executions>
                    </plugin>
                </plugins>
            </build>
        </profile>
    </profiles>
</project>

At this point you have a working AEM/CQ maven project in eclipse. With this maven project you can do lot of things like build automation, better unit testing and deployment management. One aspect that we have not covered so far is how to use this project for everyday development.

Let’s consider a very common use case. You have an AEM project for which you maintain your source code in SVN (or any other SCM) and you are using eclipse & CRXDELite for development. The reason I mentioned CRXDELite along with eclipse is that, there are certain tasks that are easy to perform with CRXDELite e.g. creating new component or template with a wizard. When you create anything in CRXDELite, you need a way to pull content created in CQ repository out in maven project (or file system) so that it can be source controlled in SVN so, how to do that? There are two ways to do this and both these ways uses “vlt” tool provided by AEM/CQ. Here are two ways:

  1. Eclipse Vault (vlt) plug-in OR, 
  2. Maven Vault plug-in
I’ll try to provide some information on how to use both these methods in my other blog posts as soon as possible.

Check out source code for this project: https://suryakand.googlecode.com/svn/aem/simple-aem-maven-project
Thank you for reading, if you have any question or find any error please feel free to leave a comment.

Saturday, May 17, 2014

CQ/AEM Dialog v/s Design Dialog

A component is CQ is a smallest unit that can dropped on a page and content author can fill in any content in it. Content can be of two types:
  1. Page specific (in this case component dialog is used)
  2. Design/Global (in this case design_dialog is used)
The way a dialog or design_dialog is defined is exactly same, there are only two differences:
  1. The obvious difference is in their name i.e. “dialog” and “design_dialog”
  2. The way properties (stored content/values) are access:
  • Retrieve values from dialog (widget) to jsp: String var= properties.get("","");
  • Retrieve values from design_dialog to jsp: String var= currentStyle.get("","");
Content/values stored via get stored at page level under component’s node. On the other hand, content/value stored via a design dialog is store at design path of your teamplate (see cq:designPath property of root node of your application/page), usually this location is under /etc/design/

Adobe CQ/AEM Useful Links

  1. /crx/explorer/index.jsp  - CRX Explorer
  2. /crx/de/index.jsp – CRXDE Lit
  3. /damadmin     - DAMAdmin
  4. /libs/cq/search/content/querydebug.html – Query debug tool
  5. /libs/granite/security/content/admin.html – New user manager standalone ui  [5.6 only?]
  6. /libs/cq/contentsync/content/console.html – Content sync console
  7. /system/console/bundles – Felix web admin console
  8. /system/console/jmx/com.adobe.granite.workflow%3Atype%3DMaintenance - Felix web admin console JMX / Workflow maintenance tasks
  9. /system/console/jmx/com.adobe.granite%3Atype%3DRepository - Felix web admin console JMX / Repository maintenance tasks
  10. /system/console/depfinder – This new 5.6 tool will help you figure out what package exports a class and also prints a Maven Dependency for the class.
  11. /libs/granite/ui/content/dumplibs.rebuild.html?rebuild=true – Helpful link for debugging caching problems. Wipes the clientlibs and designs and forces it to rebuild it. Thanks to Mark Ellis for this link.
  12. /system/console/adapters – This link shows you the Adapters are registered in the system. This helps you figure out what you can adaptTo() from resource to resource.
Params
  1. wcmmode=DISABLED - This handy publisher parameter turns off CQ authoring features so you can preview a page cleanly

Strapi CMS Plugin - Generate Content using Gen AI

An AI Strapi Plugin (@genai/gemini-content-generator) to generate content using Gen AI in Strapi Introduction The @genai/gemini-content-ge...