Article summary

Summary

This AEM development community article discusses the Quiz component. This was the winning submission for the 2015 AEM code contest. This also addresses community questions on the community on how to create an AEM quiz component.  Also discusses how to use the Experience Manager Urber 6.3 JAR. (This component is still based on Classic UI)

A special thank you to Praveen Dubey, a top AEM community member, for contributing AEM code that is used in this article. 

This article covers many AEM concepts that are important to understand as an AEM developer. 

  • How to use nested multifields in an AEM dialog to collect unknown amount of data from an author.
  • How to write a complex xtype that contains a multifield.
  • How to set dialog data in the JCR.
  • How to use a PathField widget to pass data to an OSGi service.
  • How to convert JCR data to a Resource object in an OSGi bundle.
  • How to work with a Resource Object's ValueMap to read back node properties the corresponding values. 
  • How to convert ValueMap data into JSON data.
  • How to hook into a third party SlickQuiz plugin.

This article uses an Adobe Maven Archetype project to build an OSGi bundle. If you are not familiar with an Adobe Maven Archetype project, it is recommended that you read the following article: Creating your first AEM Service using an Adobe Maven Archetype project.

Digital Marketing Solution(s) Adobe Experience Manager (Adobe CQ)
Audience
Developer (Advanced)
Required Skills
Java, JQuery, JSON, HTML
AEM Version(s)

AEM 6.3

To read 6.2 version, click https://helpx.adobe.com/experience-manager/using/quiz62.html.

To read 6.1 version, click https://helpx.adobe.com/experience-manager/using/quiz.html.

Note:

You can download an AEM package that contains the Quiz component. Install the package by using AEM package manager. 

 

* aem-quiz-component63-v6.3.zip
An AEM 6.3 package that contain the custom quiz component

Note:

To run the Quiz page, enter the following URL into a web browser:

http://localhost:4502/content/aemquiz/en/saved-quiz/aem-quiz.html

Also, you have to WhiteList the aemQuiz63.core bundle. For information, see https://forums.adobe.com/thread/2355506. If you do not whitelist the bundle, then the Quiz component does not successfully work.

Introduction

You can develop a custom Adobe Experience Manager Quiz component that lets your web site visitors perform an on-line quiz and view the results. There are business requirements that require web visitors to perform an online quiz and then track the results. Building an AEM custom quiz component satisfies this business requirement. 

Assume that another requirement for the quiz component is the questions and corresponding answers are configurable. That is, an AEM author can set them without updating the component's application logic.

Note:

Using AEM adaptive forms or other forms is not a recommended way to develop a custom AEM quiz component. Instead, its better to develop a custom component as discussed in this article.

The Quiz application is made up of two parts:

  • Quiz component -  allows web visitors to answer displayed questions and view the results
  • Quiz configuration - allows AEM authors to set questions and answers

The following illustration shows the logic flow for the Quiz component. 

QuizWF
The Quiz component logic flow

  1. The AEM Quiz configuration component lets an author set data values used in the quiz component.

  2. The quiz configuration data is stored in the AEM JCR.

  3. An AEM Service reads the JCR data.

  4. The OSGi Service converts the JCR data to JSON data.

  5. The Quiz component uses the JSON data to render the quiz.

Quiz component

The Quiz component uses JSON data that contains JCR data set by the Quiz Configuration component. The following illustration shows the quiz component.
 

QuizIntro
The AEM Quiz component

Once started, the quiz component steps the user through the questions.

QuizQ1
The Quiz component displaying a question

Once the user completes the quiz, the custom AEM component displays the user's results.

completequiz
The Quiz component displaying results

Quiz configuration

The Quiz configuration component lets an AEM author dynamically define questions during edit mode. There is no need to recompile the quiz component when you want to update the questions that make up the quiz. To enter questions and the corresponding answer, a multifield widget is used (each question has its own multifield), as shown in the following illustration. 

 

EditMode
A dialog that lets authors specify questions displayed by the Quiz component

Quiz component data

When an author fills out the Quiz configuration component, the quiz data is persisted in a JCR node such as:

/content/aemquiz/en/configurations/aem-config/jcr:content/par/quiz_config 

The following illustration shows quiz data being persisted as node properties. 

JCRData
JCR Quiz component data stored in the AEM JCR

Notice that the questionData property is a String array that stores all of the questions for the quiz.

SlickQuiz Plugin

The AEM Quiz component uses the JQuery SlickQuiz plugin. You pass this plugin JSON data that contains the questions, answers, and other required data. An AEM service (located in an OSGi bundle) reads the JCR node that contains the data and formats the data as JSON (the Java application logic that builds the following JSON data is shown later in this development article). 

The following JSON was created by the AEM service and used by this plugin. Notice that this JSON contains data located in the JCR node. 

{  
   "info":{  
      "name":"Simple Mobile Quiz",
      "main":"<p>Welcome to Quiz,<\/p>\n<p>Lets get started and see what's your knowledge about AEM...<\/p>\n",
      "results":"Simple Mobile Quiz",
      "level1":"<p>Excellect Performance<\/p>\n",
      "level2":"<p>Very Good&nbsp; Performance<\/p>\n",
      "level3":"<p>Good Performance<\/p>\n",
      "level4":"<p>Bad Performance<\/p>\n",
      "level5":"<p>Poor Performance<\/p>\n"
   },
   "questions":[  
      {  
         "q":"AEM Stands for ",
         "a":[  
            {  
               "option":"Adobe Experience Manager",
               "correct":true
            },
            {  
               "option":"Advance Engineering Mathematics",
               "correct":false
            }
         ],
         "correct":"<p><span>Good...<\/span>AEM is a Adobe Product<\/p>",
         "incorrect":"<p><span>Wrong..<\/span>AEM is a Adobe Product<\/p>"
      },
      {  
         "q":"What can be created in AEM?",
         "a":[  
            {  
               "option":"Websites",
               "correct":true
            },
            {  
               "option":"Car",
               "correct":false
            },
            {  
               "option":"Books",
               "correct":false
            }
         ],
         "correct":"<p><span>Excellent<\/span>AEM is WCM tool<\/p>",
         "incorrect":"<p><span>Sorry<\/span>AEM is WCM tool<\/p>"
      },
      {  
         "q":"WCM stands for?",
         "a":[  
            {  
               "option":"Web Content Management",
               "correct":true
            },
            {  
               "option":"Web Content Maker",
               "correct":false
            },
            {  
               "option":"World Conference Management",
               "correct":false
            }
         ],
         "correct":"<p><span>Good<\/span>WCM stands for Web Content Management<\/p>",
         "incorrect":"<p><span>Nopes<\/span>WCM stands for Web Content Management<\/p>"
      }
   ]
}data ={  
   "checkAnswerText":"Check My Answer",
   "preventUnansweredText":"You must select at least one answer.",
   "questionCountText":"Question %current of %total",
   "perQuestionResponseMessaging":true,
   "displayQuestionCount":true,
   "randomSortAnswers":false,
   "completionResponseMessaging":false,
   "preventUnanswered":false,
   "randomSortQuestions":false
}

For information about this plugin, see https://github.com/jewlofthelotus/SlickQuiz.

The SlickQuiz plugin is located in a client library located at: 

/etc/designs/aemquiz/clientlib-site/script.js

Because of the size of the component, it is recommended that you install the package as opposed to creating the AEM files from scratch. This article explains the main pieces of code so you understand how it works and the AEM concepts used to create it.

Install the AEM Quiz Component package

Install the AEM package that is shown at the start of this community article.  For information, see INSTALLING PACKAGES.

Once you install the package you can view the following project files. 

ProjectFiles
Quiz component project files

The following list explains the project files:

A - The location where the Quiz component is defined.

B - The location where the Quix configuration is defined. 

C - The location where application configuration information is located. For example, notice this node: org.apache.sling.commons.log.file. The value is logs/project-aemquiz.log. This means that log information is written to project-aemquiq.log. So when looking for log information, be sure to check this log file.

D - AEM templates used by this application. 

In addition to these AEM files, the package also installs AEM ClientLibs files in this location. 

/etc/designs/aemquiz

The following illustration shows the ClientLibs files. 

ClientLib files
AEM Quiz component ClientLib files

Note:

The package contains all of the files that are required to run the Quiz component. The rest of this article explains the code, including how to build the OSGi bundle in case you want to change the logic. 

Setup Maven in your development environment

You can use Maven to build an OSGi bundle that the Quiz component uses. It is not required to build and deploy the OSGi bundle as it is deployed when you install the AEM package. However, in case you want to modify the OSGi bundle, the article discusses how to build it. 

Maven manages required JAR files that a Java project needs in its class path. Instead of searching the Internet trying to find and download third-party JAR files to include in your project’s class path, Maven manages these dependencies for you.

You can download Maven 3 from the following URL:

http://maven.apache.org/download.html

After you download and extract Maven, create an environment variable named M3_HOME. Assign the Maven install location to this environment variable. For example:

C:\Programs\Apache\apache-maven-3.0.4

Set up a system environment variable to reference Maven. To test whether you properly setup Maven, enter the following Maven command into a command prompt:

%M3_HOME%\bin\mvn -version

This command provides Maven and Java install details and resembles the following message:

OS name: "windows 7", version: "6.1", arch: "amd64", family: "windows"

 

Note:

For more information about setting up Maven and the Home variable, see: Maven in 5 Minutes.

Next, copy the Maven configuration file named settings.xml from [install location]\apache-maven-3.0.4\conf\ to your user profile. For example, C:\Users\scottm\.m2\.

You have to configure your settings.xml file to use Adobe’s public repository. For information, see Adobe Public Maven Repository at http://repo.adobe.com/.

The following XML code represents a settings.xml file that you can use.

<?xml version="1.0" encoding="UTF-8"?>

<!--
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements.  See the NOTICE file
distributed with this work for additional information
regarding copyright ownership.  The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License.  You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied.  See the License for the
specific language governing permissions and limitations
under the License.
-->

<!--
 | This is the configuration file for Maven. It can be specified at two levels:
 |
 |  1. User Level. This settings.xml file provides configuration for a single user, 
 |                 and is normally provided in ${user.home}/.m2/settings.xml.
 |
 |                 NOTE: This location can be overridden with the CLI option:
 |
 |                 -s /path/to/user/settings.xml
 |
 |  2. Global Level. This settings.xml file provides configuration for all Maven
 |                 users on a machine (assuming they're all using the same Maven
 |                 installation). It's normally provided in 
 |                 ${maven.home}/conf/settings.xml.
 |
 |                 NOTE: This location can be overridden with the CLI option:
 |
 |                 -gs /path/to/global/settings.xml
 |
 | The sections in this sample file are intended to give you a running start at
 | getting the most out of your Maven installation. Where appropriate, the default
 | values (values used when the setting is not specified) are provided.
 |
 |-->
<settings xmlns="http://maven.apache.org/SETTINGS/1.0.0" 
          xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
          xsi:schemaLocation="http://maven.apache.org/SETTINGS/1.0.0 http://maven.apache.org/xsd/settings-1.0.0.xsd">
  <!-- localRepository
   | The path to the local repository maven will use to store artifacts.
   |
   | Default: ~/.m2/repository
  <localRepository>/path/to/local/repo</localRepository>
  -->

  <!-- interactiveMode
   | This will determine whether maven prompts you when it needs input. If set to false,
   | maven will use a sensible default value, perhaps based on some other setting, for
   | the parameter in question.
   |
   | Default: true
  <interactiveMode>true</interactiveMode>
  -->

  <!-- offline
   | Determines whether maven should attempt to connect to the network when executing a build.
   | This will have an effect on artifact downloads, artifact deployment, and others.
   |
   | Default: false
  <offline>false</offline>
  -->

  <!-- pluginGroups
   | This is a list of additional group identifiers that will be searched when resolving plugins by their prefix, i.e.
   | when invoking a command line like "mvn prefix:goal". Maven will automatically add the group identifiers
   | "org.apache.maven.plugins" and "org.codehaus.mojo" if these are not already contained in the list.
   |-->
  <pluginGroups>
    <!-- pluginGroup
     | Specifies a further group identifier to use for plugin lookup.
    <pluginGroup>com.your.plugins</pluginGroup>
    -->
  </pluginGroups>

  <!-- proxies
   | This is a list of proxies which can be used on this machine to connect to the network.
   | Unless otherwise specified (by system property or command-line switch), the first proxy
   | specification in this list marked as active will be used.
   |-->
  <proxies>
    <!-- proxy
     | Specification for one proxy, to be used in connecting to the network.
     |
    <proxy>
      <id>optional</id>
      <active>true</active>
      <protocol>http</protocol>
      <username>proxyuser</username>
      <password>proxypass</password>
      <host>proxy.host.net</host>
      <port>80</port>
      <nonProxyHosts>local.net|some.host.com</nonProxyHosts>
    </proxy>
    -->
  </proxies>

  <!-- servers
   | This is a list of authentication profiles, keyed by the server-id used within the system.
   | Authentication profiles can be used whenever maven must make a connection to a remote server.
   |-->
  <servers>
    <!-- server
     | Specifies the authentication information to use when connecting to a particular server, identified by
     | a unique name within the system (referred to by the 'id' attribute below).
     | 
     | NOTE: You should either specify username/password OR privateKey/passphrase, since these pairings are 
     |       used together.
     |
    <server>
      <id>deploymentRepo</id>
      <username>repouser</username>
      <password>repopwd</password>
    </server>
    -->
    
    <!-- Another sample, using keys to authenticate.
    <server>
      <id>siteServer</id>
      <privateKey>/path/to/private/key</privateKey>
      <passphrase>optional; leave empty if not used.</passphrase>
    </server>
    -->
  </servers>

  <!-- mirrors
   | This is a list of mirrors to be used in downloading artifacts from remote repositories.
   | 
   | It works like this: a POM may declare a repository to use in resolving certain artifacts.
   | However, this repository may have problems with heavy traffic at times, so people have mirrored
   | it to several places.
   |
   | That repository definition will have a unique id, so we can create a mirror reference for that
   | repository, to be used as an alternate download site. The mirror site will be the preferred 
   | server for that repository.
   |-->
  <mirrors>
    <!-- mirror
     | Specifies a repository mirror site to use instead of a given repository. The repository that
     | this mirror serves has an ID that matches the mirrorOf element of this mirror. IDs are used
     | for inheritance and direct lookup purposes, and must be unique across the set of mirrors.
     |
    <mirror>
      <id>mirrorId</id>
      <mirrorOf>repositoryId</mirrorOf>
      <name>Human Readable Name for this Mirror.</name>
      <url>http://my.repository.com/repo/path</url>
    </mirror>
     -->
  </mirrors>
  
  <!-- profiles
   | This is a list of profiles which can be activated in a variety of ways, and which can modify
   | the build process. Profiles provided in the settings.xml are intended to provide local machine-
   | specific paths and repository locations which allow the build to work in the local environment.
   |
   | For example, if you have an integration testing plugin - like cactus - that needs to know where
   | your Tomcat instance is installed, you can provide a variable here such that the variable is 
   | dereferenced during the build process to configure the cactus plugin.
   |
   | As noted above, profiles can be activated in a variety of ways. One way - the activeProfiles
   | section of this document (settings.xml) - will be discussed later. Another way essentially
   | relies on the detection of a system property, either matching a particular value for the property,
   | or merely testing its existence. Profiles can also be activated by JDK version prefix, where a 
   | value of '1.4' might activate a profile when the build is executed on a JDK version of '1.4.2_07'.
   | Finally, the list of active profiles can be specified directly from the command line.
   |
   | NOTE: For profiles defined in the settings.xml, you are restricted to specifying only artifact
   |       repositories, plugin repositories, and free-form properties to be used as configuration
   |       variables for plugins in the POM.
   |
   |-->
  <profiles>
    <!-- profile
     | Specifies a set of introductions to the build process, to be activated using one or more of the
     | mechanisms described above. For inheritance purposes, and to activate profiles via <activatedProfiles/>
     | or the command line, profiles have to have an ID that is unique.
     |
     | An encouraged best practice for profile identification is to use a consistent naming convention
     | for profiles, such as 'env-dev', 'env-test', 'env-production', 'user-jdcasey', 'user-brett', etc.
     | This will make it more intuitive to understand what the set of introduced profiles is attempting
     | to accomplish, particularly when you only have a list of profile id's for debug.
     |
     | This profile example uses the JDK version to trigger activation, and provides a JDK-specific repo.
    <profile>
      <id>jdk-1.4</id>

      <activation>
        <jdk>1.4</jdk>
      </activation>

      <repositories>
        <repository>
          <id>jdk14</id>
          <name>Repository for JDK 1.4 builds</name>
          <url>http://www.myhost.com/maven/jdk14</url>
          <layout>default</layout>
          <snapshotPolicy>always</snapshotPolicy>
        </repository>
      </repositories>
    </profile>
    -->

    <!--
     | Here is another profile, activated by the system property 'target-env' with a value of 'dev',
     | which provides a specific path to the Tomcat instance. To use this, your plugin configuration
     | might hypothetically look like:
     |
     | ...
     | <plugin>
     |   <groupId>org.myco.myplugins</groupId>
     |   <artifactId>myplugin</artifactId>
     |   
     |   <configuration>
     |     <tomcatLocation>${tomcatPath}</tomcatLocation>
     |   </configuration>
     | </plugin>
     | ...
     |
     | NOTE: If you just wanted to inject this configuration whenever someone set 'target-env' to
     |       anything, you could just leave off the <value/> inside the activation-property.
     |
    <profile>
      <id>env-dev</id>

      <activation>
        <property>
          <name>target-env</name>
          <value>dev</value>
        </property>
      </activation>

      <properties>
        <tomcatPath>/path/to/tomcat/instance</tomcatPath>
      </properties>
    </profile>
    -->
  

<profile>

                <id>adobe-public</id>

                <activation>

                    <activeByDefault>true</activeByDefault>

                </activation>

                <repositories>

                  <repository>

                    <id>adobe</id>

                    <name>Nexus Proxy Repository</name>

                    <url>http://repo.adobe.com/nexus/content/groups/public/</url>

                    <layout>default</layout>

                  </repository>

                </repositories>

                <pluginRepositories>

                  <pluginRepository>

                    <id>adobe</id>

                    <name>Nexus Proxy Repository</name>

                    <url>http://repo.adobe.com/nexus/content/groups/public/</url>

                    <layout>default</layout>

                  </pluginRepository>

                </pluginRepositories>

            </profile>

</profiles>

  <!-- activeProfiles
   | List of profiles that are active for all builds.
   |
  <activeProfiles>
    <activeProfile>alwaysActiveProfile</activeProfile>
    <activeProfile>anotherAlwaysActiveProfile</activeProfile>
  </activeProfiles>
  -->
</settings>

Create an Experience Manager archetype project 

You can create an Experience Manager archetype project by using the Maven archetype plugin. In this example, assume that the working directory is C:\AdobeCQ.

files

The following list describes the Archetype 10 project arguments:

  • groupId - Base Maven groupId
  • artifactId - Base Maven ArtifactId
  • version - the version of your project
  • package - Java Source Package
  • appsFolderName - /apps folder name
  • artifactName - Maven Project Name
  • componentGroupName - AEM component group name
  • contentFolderName - /content folder name
  • cssId - prefix used in generated css
  • packageGroup - Content Package Group name
  • siteName - AEM site name

To create an Experience Manager archetype project, perform these steps:

  1. Open the command prompt and go to your working directory (for example, C:\AdobeCQ).

  2. Run the following Maven command:

    mvn archetype:generate -DarchetypeGroupId=com.adobe.granite.archetypes -DarchetypeArtifactId=aem-project-archetype -DarchetypeVersion=10 -DarchetypeRepository=https://repo.adobe.com/nexus/content/groups/public/

  3. When prompted, specify the following information:

    • groupId - aemQuiz63
    • artifactId - aemQuiz63
    • version - 1.0-SNAPSHOT
    • package - com.aem.aemquiz
    • appsFolderName - aemQuiz63
    • artifactName - aemQuiz63
    • componentGroupName - aemQuiz63
    • contentFolderName - aemQuiz63
    • cssId - aemQuiz63
    • packageGroup - aemQuiz63
    • siteName - aemQuiz63
  4. WHen prompted, specify Y.

  5. Once done, you will see a message like:
    [INFO] Finished at: Wed Mar 27 13:38:58 EDT 2013
    [INFO] Final Memory: 10M/184M

  6. Change the command prompt to the generated project. For example: C:\AdobeCQ\aemQuiz63. Run the following Maven command:

    mvn eclipse:eclipse

    After you run this command, you can import the project into Eclipse as discussed in the next section.

Add Java files to the Maven project using Eclipse 

To make it easier to work with the Maven generated project, import it into the Eclipse development environment, as shown in the following illustration.

project

Add the Java files discussed in this section to the com.aem.aemquiz.core package.  

QuizImpl

The QuizImpl interface defines two methods exposed by the AEM Quiz Service. These methods are named: 

  • getData - this method receives a path to the JCR node where configuration information is stored and returns JSON data that contains data required by the Quiz SlickQuiz plug-in. See the JSON at the start of this development article. 
  • getOptions - this method also reads the JCR configuration node and returns data in JSON format. The difference is this JSON data contains other data such as the text value that displayed for the next question (nextQuestionText). 

The following code represents the QuizImpl method. 

package com.aem.aemquiz.core;

public abstract interface QuizImpl
{
  public abstract String getData(String paramString);
   
  public abstract String getOptions(String paramString);
}

HelloService2

The following code represents the HelloService2 Java class. 

package com.aem.aemquiz.core;

import com.adobe.cq.sightly.WCMUsePojo;
import org.apache.sling.api.scripting.SlingScriptHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
  
public class HelloService2 extends WCMUsePojo
{
     private Logger logger = LoggerFactory.getLogger(this.getClass());
  protected FooImpl services;
    
  public void activate()
  {
    this.services = ((FooImpl)getSlingScriptHelper().getService(FooImpl.class));
    this.logger.info("**** THE QUIZ Activate method was invoked");
  }
    
  public String getMessage()
  {
    this.logger.info("The Data called");
    return this.services.getData("ss");
    //return "";
  }
}

FooImpl class

The FooImpl extends the QuizImpl interface and provides application logic for the getOptions and getData methods. The following Java code represents the FooImpl class. 

package com.aem.aemquiz.core;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map.Entry;
import javax.jcr.Node;
import javax.jcr.Property;
import javax.jcr.Value;
import org.apache.felix.scr.annotations.Component;
import org.apache.felix.scr.annotations.Reference;
import org.apache.felix.scr.annotations.Service;
import org.apache.sling.api.resource.Resource;
import org.apache.sling.api.resource.ResourceResolver;
import org.apache.sling.api.resource.ResourceResolverFactory;
import org.apache.sling.api.resource.ValueMap;
import org.apache.sling.commons.json.JSONArray;
import org.apache.sling.commons.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
  
@Component (immediate=true)
@Service
public class FooImpl implements QuizImpl
{
  @Reference
  private ResourceResolverFactory resolverFactory;
  String resourcePath = null;
  private Logger LOGGER = LoggerFactory.getLogger(this.getClass());
    
  public String getOptions(String url)
  {
    try
    {
      this.resourcePath = url;
      ResourceResolver resourceResolver = this.resolverFactory
        .getAdministrativeResourceResolver(null);
      Resource res = resourceResolver.getResource(this.resourcePath);
      ValueMap readMap = res.getValueMap();
      HashMap<String, Boolean> markFalse = new HashMap();
        
  
      String[] JSONDataValues = { "checkAnswerText", 
        "preventUnansweredText", "questionCountText", 
        "nextQuestionText", "numberOfQuestions", 
        "randomSortQuestions", "randomSortAnswers", 
        "preventUnanswered", "perQuestionResponseMessaging", 
        "completionResponseMessaging", "displayQuestionCount" };
        
  
      markFalse.put("randomSortQuestions", Boolean.valueOf(false));
      markFalse.put("randomSortAnswers", Boolean.valueOf(false));
      markFalse.put("preventUnanswered", Boolean.valueOf(false));
      markFalse.put("perQuestionResponseMessaging", Boolean.valueOf(true));
      markFalse.put("completionResponseMessaging", Boolean.valueOf(false));
      markFalse.put("displayQuestionCount", Boolean.valueOf(true));
        
      JSONObject options = new JSONObject();
      ArrayList<String> tempData = new ArrayList();
      LOGGER.info("Inside Option{}", JSONDataValues);
      String value;
      for (int i = 0; i < JSONDataValues.length; i++) {
        if (readMap.containsKey(JSONDataValues[i]))
        {
          tempData.add(JSONDataValues[i]);
          value = readMap.get(JSONDataValues[i]).toString();
          LOGGER.info("Value:" + value);
          if (!value.equals(null)) {
            if (value.equals("true")) {
              options.put(JSONDataValues[i], true);
            } else {
              options.put(JSONDataValues[i], value);
            }
          }
        }
      }
      LOGGER.info("Map:" + markFalse);
      LOGGER.info("ArrayList:" + tempData);
      for (java.util.Map.Entry<String, Boolean> entry : markFalse.entrySet())
      {
        LOGGER.info("Checking:+" + (String)entry.getKey());
        if (!tempData.contains(entry.getKey()))
        {
          LOGGER.info("Putting Key :" + (String)entry.getKey());
          if (!((Boolean)entry.getValue()).booleanValue()) {
            options.put((String)entry.getKey(), entry.getValue());
          } else {
            options.put((String)entry.getKey(), false);
          }
        }
      }
      LOGGER.info("Final Data Options" + options.toString());
        
      return options.toString();
    }
    catch (Exception e)
    {
      LOGGER.info("Exception " + e);
    }
    return null;
  }
    
  public String getData(String url)
  {
    LOGGER.info("Getting started");
    try
    {
      this.resourcePath = url;
      ResourceResolver resourceResolver = this.resolverFactory
        .getAdministrativeResourceResolver(null);
      Resource res = resourceResolver.getResource(this.resourcePath);
      ValueMap readMap = res.getValueMap();
      LOGGER.info("Data " + readMap.get("displayText"));
      JSONObject info = new JSONObject();
        
      JSONArray questionsArray = new JSONArray();
      JSONArray quesoptions = new JSONArray();
      JSONObject finalJson = new JSONObject();
      JSONObject ques = new JSONObject();
      JSONObject quesop1 = new JSONObject();
        
      info.put("name", readMap.get("nameofquiz"));
      info.put("main", readMap.get("displayText"));
      info.put("results", readMap.get("nameofquiz"));
      info.put("level1", readMap.get("level1"));
      info.put("level2", readMap.get("level2"));
      info.put("level3", readMap.get("level3"));
      info.put("level4", readMap.get("level4"));
      info.put("level5", readMap.get("level5"));
      LOGGER.info("Info Data: " + info);
        
      LOGGER.info("Q Data: " + readMap.get("questionData"));
        
  
      Node node = (Node)res.adaptTo(Node.class);
      ArrayList<String> list = new ArrayList();
      Property prop = node.getProperty("questionData");
      if (prop.isMultiple())
      {
        Value[] values = prop.getValues();
        for (Value value : values) {
          list.add(value.getString());
        }
      }
      else
      {
        list.add(prop.getString());
      }
      for (int i = 0; i < list.size(); i++)
      {
        ques = new JSONObject();
        quesoptions = new JSONArray();
        String text = (String)list.get(i);
        LOGGER.info("Text:" + text);
        String[] splitText = text.split("\\|");
          
        ques.put("q", splitText[0]);
        LOGGER.info("q:" + splitText[0]);
        String[] allOptions = splitText[1].split("\\,");
        for (int j = 0; j < allOptions.length; j++)
        {
          quesop1 = new JSONObject();
          String[] optionValue = allOptions[j].split("\\~");
          quesop1.put("option", optionValue[0]);
          if (optionValue[1].equals("true")) {
            quesop1.put("correct", true);
          } else {
            quesop1.put("correct", false);
          }
          quesoptions.put(quesop1);
        }
        LOGGER.info("Options: " + quesoptions);
        ques.put("a", quesoptions);
        String correct = "<p><span>" + splitText[2] + "</span>" + 
          splitText[3] + "</p>";
        String incorrect = "<p><span>" + splitText[4] + "</span>" + 
          splitText[5] + "</p>";
        ques.put("correct", correct);
        ques.put("incorrect", incorrect);
          
        questionsArray.put(ques);
      }
      finalJson.put("info", info);
        
      finalJson.put("questions", questionsArray);
        
        
      LOGGER.info("Final JSON: " + finalJson);
        
      return finalJson.toString();
    }
    catch (Exception e)
    {
      LOGGER.info("Exception :" + e.getMessage());
    }
    return null;
  }
    
  protected void bindResolverFactory(ResourceResolverFactory paramResourceResolverFactory)
  {
    this.resolverFactory = paramResourceResolverFactory;
  }
    
  protected void unbindResolverFactory(ResourceResolverFactory paramResourceResolverFactory)
  {
    if (this.resolverFactory == paramResourceResolverFactory) {
      this.resolverFactory = null;
    }
  }
}

The FooImpl class exposes a method named getData that takes a string parameter, named url, that references the JCR node where the Quiz configuration data is persisted. For example: 

/content/aemquiz/en/configurations/aem-config/jcr:content/par/quiz_config

This value is set in the Quiz component dialog using a PathField (this is shown later in this article). 

An org.apache.sling.api.resource.Resource instance is created by using the url parameter value. Therefore, you can convert a String value that references an AEM JCR path into a Resource object.

this.resourcePath = url;     
ResourceResolver resourceResolver = this.resolverFactory        .getAdministrativeResourceResolver(null);     
Resource res = resourceResolver.getResource(this.resourcePath);

Next, a ValueMap object is created by invoking the Resource object's getValueMap method. The ValueMap object stores node properties and their corresponding values. 

ValueMap readMap = res.getValueMap();

 

Next a JSONObject instance is created. All properties values, except for questionData, is added to the JSONObject.  

 

 

info.put("name", readMap.get("nameofquiz"));
info.put("main", readMap.get("displayText"));
info.put("results", readMap.get("nameofquiz"));
info.put("level1", readMap.get("level1"));
info.put("level2", readMap.get("level2"));
info.put("level3", readMap.get("level3"));
info.put("level4", readMap.get("level4"));
info.put("level5", readMap.get("level5"));

Because questionData is a node property that stores string array data, an iteration is required to place all of the data into the JSONObject instance. Once the question data is added to the JSONObject, it is used as the return value of the getData method.

  Node node = (Node)res.adaptTo(Node.class);
      ArrayList<String> list = new ArrayList();
      Property prop = node.getProperty("questionData");
      if (prop.isMultiple())
      {
        Value[] values = prop.getValues();
        for (Value value : values) {
          list.add(value.getString());
        }
      }
      else
      {
        list.add(prop.getString());
      }
      for (int i = 0; i < list.size(); i++)
      {
        ques = new JSONObject();
        quesoptions = new JSONArray();
        String text = (String)list.get(i);
        LOGGER.info("Text:" + text);
        String[] splitText = text.split("\\|");
        
        ques.put("q", splitText[0]);
        LOGGER.info("q:" + splitText[0]);
        String[] allOptions = splitText[1].split("\\,");
        for (int j = 0; j < allOptions.length; j++)
        {
          quesop1 = new JSONObject();
          String[] optionValue = allOptions[j].split("\\~");
          quesop1.put("option", optionValue[0]);
          if (optionValue[1].equals("true")) {
            quesop1.put("correct", true);
          } else {
            quesop1.put("correct", false);
          }
          quesoptions.put(quesop1);
        }
        LOGGER.info("Options: " + quesoptions);
        ques.put("a", quesoptions);
        String correct = "<p><span>" + splitText[2] + "</span>" + 
          splitText[3] + "</p>";
        String incorrect = "<p><span>" + splitText[4] + "</span>" + 
          splitText[5] + "</p>";
        ques.put("correct", correct);
        ques.put("incorrect", incorrect);
        
        questionsArray.put(ques);
      }
      finalJson.put("info", info);
      
      finalJson.put("questions", questionsArray);
      
      
      LOGGER.info("Final JSON: " + finalJson);
      
      return finalJson.toString();

Modify the Maven POM file 

You need to modify two POM files. The first one is the parent POM file shown in this illustration

POMParent
Parent POM

Add the following POM dependency to the POM file located at C:\AdobeCQ\aemQuiz63.

<dependency>
               <groupId>com.adobe.aem</groupId>
               <artifactId>uber-jar</artifactId>
               <version>6.3</version>
               <!-- for AEM6.1 use this version     : <version>6.1.0</version> -->
               <!-- for AEM6.1 SP1 use this version : <version>6.1.0-SP1-B0001</version> -->
               <!-- for AEM6.1 SP2 use this version : <version>6.1.0-SP2</version> -->
               <!-- for AEM6.2 use this version     : <version>6.2.0</version> -->
               <classifier>obfuscated-apis</classifier>
               <scope>provided</scope>
           </dependency>
            
           <dependency>
               <groupId>org.apache.geronimo.specs</groupId>
               <artifactId>geronimo-atinject_1.0_spec</artifactId>
               <version>1.0</version>
               <scope>provided</scope>
           </dependency>

Next, modify the POM file to successfully build the OSGi bundle. In the POM file located at C:\AdobeCQ\aemQuiz62\bundle, add the following dependencies.

  • org.apache.felix.scr
  • org.apache.felix.scr.annotations
  • org.apache.jackrabbit
  • org.apache.sling

The following XML represents this POM file.

<?xml version="1.0" encoding="UTF-8"?>
<!--
 |  Copyright 2015 Adobe Systems Incorporated
 |
 |  Licensed under the Apache License, Version 2.0 (the "License");
 |  you may not use this file except in compliance with the License.
 |  You may obtain a copy of the License at
 |
 |      http://www.apache.org/licenses/LICENSE-2.0
 |
 |  Unless required by applicable law or agreed to in writing, software
 |  distributed under the License is distributed on an "AS IS" BASIS,
 |  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 |  See the License for the specific language governing permissions and
 |  limitations under the License.
-->
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>aemQuiz63</groupId>
        <artifactId>aemQuiz63</artifactId>
        <version>1.0-SNAPSHOT</version>
        <relativePath>../pom.xml</relativePath>
    </parent>
    <artifactId>aemQuiz63.core</artifactId>
    <packaging>bundle</packaging>
    <name>aemQuiz63 - Core</name>
    <description>Core bundle for aemQuiz63</description>
    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.felix</groupId>
                <artifactId>maven-scr-plugin</artifactId>
            </plugin>
            <plugin>
                <groupId>org.apache.felix</groupId>
                <artifactId>maven-bundle-plugin</artifactId>
                <extensions>true</extensions>
                <configuration>
                    <instructions>
                        <!--
                        <Embed-Dependency>
                            artifactId1,
                            artifactId2;inline=true
                        </Embed-Dependency>
                        -->
                        <Sling-Model-Packages>
                            com.aem.aemquiz.core
                        </Sling-Model-Packages>
                    </instructions>
                </configuration>
            </plugin>
        </plugins>
    </build>
    <profiles>
        <!-- Development profile: install only the bundle -->
        <profile>
            <id>autoInstallBundle</id>
            <activation>
                <activeByDefault>false</activeByDefault>
            </activation>
            <build>
                <plugins>
                    <plugin>
                        <groupId>org.apache.sling</groupId>
                        <artifactId>maven-sling-plugin</artifactId>
                        <configuration>
                            <!-- Note that this requires /apps/aemQuiz63/install to exist!!          -->
                            <!--    This is typically the case when ui.apps is deployed first                -->
                            <!--    Otherwise, create /apps/aemQuiz63/install manually (CRXDE|Lite)  -->
                            <slingUrlSuffix>/apps/aemQuiz63/install/</slingUrlSuffix>
                            <failOnError>true</failOnError>
                        </configuration>
                    </plugin>
                </plugins>
            </build>
        </profile>
    </profiles>
    <dependencies>
        <!-- OSGi Dependencies -->
             
        <dependency>
            <groupId>com.adobe.aem</groupId>
            <artifactId>uber-jar</artifactId>
            <classifier>obfuscated-apis</classifier>
        </dependency>
  
        <dependency>
            <groupId>org.apache.geronimo.specs</groupId>
            <artifactId>geronimo-atinject_1.0_spec</artifactId>
        </dependency>
       
        <dependency>
            <groupId>org.apache.felix</groupId>
            <artifactId>org.apache.felix.scr</artifactId>
        </dependency>
        <dependency>
            <groupId>org.apache.felix</groupId>
            <artifactId>org.apache.felix.scr.annotations</artifactId>
        </dependency>
        <dependency>
            <groupId>biz.aQute</groupId>
            <artifactId>bndlib</artifactId>
        </dependency>
        <dependency>
            <groupId>org.osgi</groupId>
            <artifactId>org.osgi.core</artifactId>
        </dependency>
        <dependency>
            <groupId>org.osgi</groupId>
            <artifactId>org.osgi.compendium</artifactId>
        </dependency>
        <!-- Other Dependencies -->
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
        </dependency>
        <dependency>
            <groupId>javax.jcr</groupId>
            <artifactId>jcr</artifactId>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>servlet-api</artifactId>
        </dependency>
        <dependency>
            <groupId>com.adobe.aem</groupId>
            <artifactId>aem-api</artifactId>
        </dependency>
        <dependency>
            <groupId>org.apache.sling</groupId>
            <artifactId>org.apache.sling.models.api</artifactId>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
        </dependency>
        <dependency>
            <groupId>org.mockito</groupId>
            <artifactId>mockito-all</artifactId>
        </dependency>
        <dependency>
            <groupId>junit-addons</groupId>
            <artifactId>junit-addons</artifactId>
        </dependency>
    </dependencies>
</project>

Build the OSGi bundle using Maven 

To build the OSGi bundle by using Maven, perform these steps:

  1. Open the command prompt and go to the C:\AdobeCQ\aemQuiz63 folder.

  2. Run the following maven command: mvn -PautoInstallPackage install.

  3. The OSGi component can be found in the following folder: C:\AdobeCQ\aemQuiz63\core\target. The file name of the OSGi component is aemQuiz63.core-1.0-SNAPSHOT.jar.

The command -PautoInstallPackage automatically deploys the OSGi bundle to AEM.

Quiz Configuration dialog

The Quiz Configuration component lets an author set questions, answers, and other data used by the Quiz component. The data is set by using a multifield widget located in the component's dialog. The following illustration shows the JCR nodes that represent the dialog. 

QuizConfigDialog
The dialog for the Quiz Configuration dialog

Questions node

Notice the dialog node located at: 

/apps/aemquiz/components/content/quiz-config/dialog/items/questions/items/question

This is a nested multifield as defined by the xtype. Under this node is:

/apps/aemquiz/components/content/quiz-config/dialog/items/questions/items/question/fieldConfig

The xtype of the fieldConfig node is pfquestions. This represents a custom xtype and defines this GUI located on the dialog.

customXType
A custom xtype used in the Quiz configuration component dialog

In this example, notice that there are two multifields. The inner Options multifield is for answers to the given question. When you click Add Item, a text field and a checkbox appears that lets an author enter possible answers, as shown in this illustration. 

AEMCOnfigMFs
A nested multifield control that lets authors enter possible answers to a quiz question

The value in the text field represents a possible answer. The checkbox represents the correct answer. So you only click a single checkbox for each question. 

The inner Options multifield is defined in the pfquestions xtype and is created by using JavaScript. This JavaScript is located in the AEM Custom Library located at this node: 

/etc/designs/aemquiz/componentJS/script.js

In this script.js file, you see the widgets that appear on Options multifield being defined using script. For example, the following code defined the checkbox (which is an instance of CQ.Ext.form.Checkbox). 

   this.optionText = new CQ.Ext.form.Checkbox ({
            fieldLabel : "is True?",
            width : 300,
            listeners : {
                change : {
                    scope : this,
                    fn : this.updateHidden
                }
            }
        });

Likewise, the options multifield (which is CQ.form.MultiField) is defined by script which is shown here. 

 this.optionData = new CQ.form.MultiField({
            fieldLabel : "Options ",
            fieldDescription: "Click '+' to add options",
            width : 500,
            fieldConfig: {
                "xtype" : "pfquestionsoptions"
            },
            listeners: {
                change: {
                    scope:this,
                    fn:this.updateHidden
                }
            }
        });

Note:

It is recommended that you look at the script.js file to understand how it works. 

Notice that these values entered into the dialog that uses the nested multifields are located in the JSON data used by the Quiz component. 

{  
         "q":"What can be created in AEM?",
         "a":[  
            {  
               "option":"Websites",
               "correct":true
            },
            {  
               "option":"Car",
               "correct":false
            },
            {  
               "option":"Books",
               "correct":false
            }
         ],

Config node

Notice the config node located at this JCR location: 

/apps/aemquiz/components/content/quiz-config/dialog/items/config

These JCR nodes let an author enter values used by the quiz component. For example, Level 1 represents the message that is displayed if the user answers all quiz questions correctly, Level 2 represents the message if the user missed onlu one question, and so on. 

The following illustration shows this part of the dialog.

Lvlquestions
The Quiz configuration component that lets an author enter level information

Notice that these values are used in the JSON data used by the Quiz component. 

"level1":"<p>Excellect Performance<\/p>\n",
"level2":"<p>Very Good&nbsp; Performance<\/p>\n",
"level3":"<p>Good Performance<\/p>\n",
"level4":"<p>Bad Performance<\/p>\n",
"level5":"<p>Poor Performance<\/p>\n

(See the fill JSON at the start of this article.)

Options node

The options nodes allow an author to define additional data such as the message that appears when the quiz is complete that shows the user how many questions they got right. For example: 

Question %current of %total

These nodes are defined at this JCR location: 

/apps/aemquiz/components/content/quiz-config/dialog/items/options

The following illustration shows the options part of the dialog. 

TestOptions
Text options used by the quiz component

Notice that these values are used in the JSON data used by the Quiz component (see the fill JSON at the start of this article.)

data ={  
   "checkAnswerText":"Check My Answer",
   "preventUnansweredText":"You must select at least one answer.",
   "questionCountText":"Question %current of %total",
   "perQuestionResponseMessaging":true,
   "displayQuestionCount":true,
   "randomSortAnswers":false,
   "completionResponseMessaging":false,
   "preventUnanswered":false,
   "randomSortQuestions":false

Quiz component

The Quiz component uses a dialog that lets an author specify the JCR location to where the configuration nodes are stored. This is performed by using a pathfield widget in the dialog, as shown in this illustration. 

QuizPathField
A PathField located in the Quiz component dialog

This is the JCR location that is passed to the methods, such as getData, that is defined in the OSGi bundle. In the component JSP file (located at /apps/aemquiz/components/content/quiz-component/quiz-component.jsp), the value of the PathField is retrieved: 

String url = properties.get("configurl", String.class);

Next, the Quiz component JSP creates an instance of QuizImpl, (the interface defined in the OSGi bundle), as shown here.

com.aemquiz.aemquiz.core.services.core.QuizImpl s = sling.getService(com.aemquiz.aemquiz.core.services.core.QuizImpl.class);;

A variable named quizJSON is used to store the JSON data returned by the getData method. 

var quizJSON = <%= s.getData(url) %> 

Now the SlickQuiz plugin uses the quizJSON data to render the quiz. The SlickQuiz plugin code is defined in an AEM ClientLibs folder at the following location:

/etc/designs/aemquiz/clientlib-site/script.js

Note:

The SlickQuiz plugin code is defined from lines 9613 to 10349 (defined in /etc/designs/aemquiz/clientlib-site/script.js). 

Note:

The AEM ClientLibs that contain the SlickQuiz plugin is referenced in a Sightly file that is part of the Quiz project files. See this file: /apps/aemquiz/components/structure/page/partials/footlibs.html. This line of code referenced the clientlibs: <sly data-sly-use.clientLib="/libs/granite/sightly/templates/clientlib.html" data-sly-call="${clientLib.js @ categories='aemquiz.all'}" data-sly-unwrap/>.

The following code represents the Quiz component located at /apps/aemquiz/components/content/quiz-component/quiz-component.jsp.

<%@include file="/libs/foundation/global.jsp"%>

<% 
	String url = properties.get("configurl", String.class);
if(url!=null && url.length()>0) {
    com.aem.aemquiz.core.QuizImpl s = sling.getService(com.aem.aemquiz.core.QuizImpl.class);
%> 

<body id="slickQuiz">
    <h1 class="quizName"></h1>
    <div class="quizArea">
        <div class="quizHeader">
            <a class="startQuiz" href="">Get Started!</a>
        </div>
    </div>
    <div class="quizResults">
        <h3 class="quizScore">You Scored: <span></span></h3>
        <h3 class="quizLevel"><strong>Ranking:</strong> <span></span></h3>
        <div class="quizResultsCopy"></div>
    </div>
    
    <script>

        var quizJSON = <%= s.getData(url) %> 
            data = <%= s.getOptions(url) %> 
            
    </script>
<%
} else { 
	out.print("Please Author the URL where configurations are saved");
}
%>

Running the Quiz component

You can run the Quiz component by going to the SiteAdmin view at: 

http://localhost:4502/siteadmin#/content/aemquiz/en/configurations/aem-config

as shown in this illustration. (Make sure that you installed the package shown at the start of this article.)

 

PAgeVIew
The AEM siteadmin

Next open the aem-config page in classic view at this location: 

http://localhost:4502/cf#/content/aemquiz/en/configurations/aem-config.html

You will see the Quiz configuration component. Click on the component and you will see the green border to open the dialog. 

QUizCOnfigA
The Quiz configuration component

After you open the dialog, you can explore the dialog. You will see the controls that are explained earlier in this development article. 

Once you set the Quiz configuration component's dialog, you can open the AEM Quiz page at the following URL: 

http://localhost:4502/content/aemquiz/en/saved-quiz/aem-quiz.html

You will see this Quiz component, as shown in this illustration. 

QuizIntro
The AEM custom Quiz component

Click Get Started to run the quiz. 

Note:

There are other supporting files that are part of /apps/aemquiz not covered in this article. For example, if you look at files under /apps/aemquiz/components/structure, you will see some boilerplate files that setup pages, footers, and so on. It is recommended that you look at this files so you understand how they all work together. 

See also

This work is licensed under a Creative Commons Attribution-Noncommercial-Share Alike 3.0 Unported License  Twitter™ and Facebook posts are not covered under the terms of Creative Commons.

Legal Notices   |   Online Privacy Policy