Article summary

Summary

Discusses how to develop an AEM 6.4 HTML Template Language component that displays YouTube videos.

HTL is the AEM template language that can be used to replace use of JSP when developing an AEM component. HTL helps you to separate your design from your application logic. For more information, see Introduction to the HTML Template Language.

A special thank you to Ratna Kumar Kotla, a  top AEM community member, for testing this article to ensure it works.

Digital Marketing Solution(s) Adobe Experience Manager 6.4
Audience Developer
Required Skills Java, HTML, JavaScript
Version 6.4

Download

Note:

You can download an AEM package that contains the code used in this article. Download the package and deploy using package manager. The purpose of this code is to show the community these concepts in action. That is, it's to illustrate how to write a HTL component that displays a YouTube video. This community code is for teaching purposes only and not meant to go into production as is.

You can view the sample community application by using the following URL:

http://localhost:4502/editor.html/content/YouTubeAEM64/en.html (assuming you deploy on author).

Introduction

Displaying video content within a web site is a typical requirement for Experience Manager 6.4 authors. Furthermore, the video may not be located within the AEM DAM, but rather a YouTube video. To address this requirement, you can create a custom component that can display a YouTube video. 

In addition, you can develop the component to retrieve information about the video and display the information within the component, as shown in the following illustration. The component developed in this article is built using HTL, which helps you to separate your design from your application logic. For more information, see Introduction to the HTML Template Language.

Intro
An AEM 6.4 YouTube component displaying a video

To select the YouTube video, an AEM author provides the Video ID in a component dialog.

dialog
A YouTube video ID is specified in the component dialog

This development article covers the following tasks:

  1. Performs a Restful call to a YouTube service and retrieves the JSON response by using JSONObject instance.
  2. Plays the video within an Experience Manager page without the need to use an Iframe.
  3. Video title and channel name are shown using an accordion widget.

This development article steps you through how to build an AEM HTL component by using an AEM Maven Archetype 13 project. This HTL uses a Java class that extends com.adobe.cq.sightly.WCMUsePojo. For information, see com.adobe.cq.sightly.WCMUsePojo.

Note:

The Java class com.adobe.cq.sightly.WCMUse is deprecated.

Create an AEM Maven 13 archetype project

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

maven
Maven Archetype 13 generated files

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 org.apache.maven.plugins:maven-archetype-plugin:2.4:generate -DarchetypeGroupId=com.adobe.granite.archetypes -DarchetypeArtifactId=aem-project-archetype -DarchetypeVersion=13 -DarchetypeCatalog=https://repo.adobe.com/nexus/content/groups/public/

3. When prompted, specify the following information:

  • groupId - YouTubeAEM64
  • artifactId - YouTubeAEM64
  • version - 1.0-SNAPSHOT
  • package - com.adobe.community
  • appsFolderName - YouTubeAEM64
  • artifactName - YouTubeAEM64
  • componentGroupName - YouTubeAEM64
  • contentFolderName - YouTubeAEM64
  • cssId - YouTubeAEM64
  • packageGroup -YouTubeAEM64
  • siteName - YouTubeAEM64

4. When prompted, specify Y.

5. Once done, you will see a message like:

[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 01:42 min
[INFO] Finished at: 2016-04-25T14:34:19-04:00
[INFO] Final Memory: 16M/463M
[INFO] ------------------------------------------------------------------------

6. Change the working directory to YouTubeAEM64 and then enter the following 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
Eclipse project dialog

The Eclipse project that you work in to build the OSGi bundle that uses HTL API is YouTubeAEM64.core. You do not have to work in the other projects under YouTubeAEM64.  

Note:

Do not worry about the errors reported in Eclipse. It does not read the POM file where the APIs are resolved. You build the bundle with Maven. Eclipse is used to edit the Java files and the POM file.

The next step is to add Java files to the com.adobe.community.core package. The Java classes are named YoutubeComponentC and YoutubePojo

YoutubePojo class

The YoutubePojo is a Java bean that has class members to store details about the given YouTube video. The information is obtained by using a Restful call and the information is returned in JSON format.

The YoutubePojo class has these string class members:

  • videohtml 
  • videoid 
  • videotitle
    • video_author_name

The following Java code represents the YoutubePojo class.

package com.adobe.community.core;

public class YoutubePojo
{
  private String videohtml;
  private String videoid;
  private String videotitle;
  private String video_author_name;
   
  public String getVideoid()
  {
    return this.videoid;
  }
   
  public void setVideoid(String videoid)
  {
    this.videoid = videoid;
  }
   
  public String getVideotitle()
  {
    return this.videotitle;
  }
   
  public void setVideotitle(String videotitle)
  {
    this.videotitle = videotitle;
  }
   
  public String getVideo_author_name()
  {
    return this.video_author_name;
  }
   
  public void setVideo_author_name(String video_author_name)
  {
    this.video_author_name = video_author_name;
  }
   
  public String getVideohtml()
  {
    return this.videohtml;
  }
   
  public void setVideohtml(String videohtml)
  {
    this.videohtml = videohtml;
  }
}

YoutubeComponentC class


	




The YoutubeComponentC class is the Java side of the HTL component and extends WCMUsePojo, which is an abstract class that implements the Use interface. A HTL component's Java class must implement this abstract class. 


The activate method gets the value of the video id that an author specifies in the component dialog.

//Get the value that the author entered into the AEM dialog
videoid = getProperties().get("videoid", "");

This value is used in a Restful call to a YouTube service to obtain information about the video that corresponds to the video. Information is returned within JSON format.

DefaultHttpClient httpClient = new DefaultHttpClient();

HttpGet getRequest = new HttpGet("https://www.youtube.com/oembed?url=http://www.youtube.com/watch?v=" + videoid + "&format=json");
getRequest.addHeader("accept", "application/json");

HttpResponse response = httpClient.execute(getRequest);
if (response.getStatusLine().getStatusCode() != 200)
{
log.info("exception");

throw new RuntimeException("Failed : HTTP error code : " + response.getStatusLine().getStatusCode());
}
BufferedReader br = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));

String myJSON = "";
String output;
while ((output = br.readLine()) != null) {
myJSON = myJSON + output;
}

Then the JSON values are stored in the YoutubePojo data members. Once they are stored in the data members, the HTL logic can display them (this is shown later in this development article).


The following Java code represents the YoutubeComponentC class.

package com.adobe.community.core;

import com.adobe.cq.sightly.WCMUsePojo;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import javax.jcr.Node;
import javax.jcr.Property;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.sling.api.resource.Resource;
import org.apache.sling.commons.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
 
public class YoutubeComponentC
  extends WCMUsePojo
{
  private YoutubePojo youtubepojo = null;
  protected static final Logger log = LoggerFactory.getLogger(YoutubeComponentC.class.getClass());
   
  public void activate()
    throws Exception
  {
    Node currentNode = (Node)getResource().adaptTo(Node.class);
    this.youtubepojo = new YoutubePojo();
     
    String videoid = "oeO6zwjxyQw";
    
    //Get the value that the author entered into the AEM dialog
    videoid = getProperties().get("videoid", "");
    
    log.info("**** Video ID " + videoid);
     
    String jsonstr = getJSON(videoid);
    JSONObject youtubeJson = new JSONObject(jsonstr);
    this.youtubepojo.setVideotitle(youtubeJson.get("title").toString());
    this.youtubepojo.setVideo_author_name(youtubeJson.get("author_name").toString());
    this.youtubepojo.setVideohtml(youtubeJson.getString("html").toString());
  }
   
  public YoutubePojo getYoutubepojo()
  {
    return this.youtubepojo;
  }
   
  public static String getJSON(String videoid)
  {
    try
    {
      DefaultHttpClient httpClient = new DefaultHttpClient();
       
      HttpGet getRequest = new HttpGet("https://www.youtube.com/oembed?url=http://www.youtube.com/watch?v=" + videoid + "&format=json");
      getRequest.addHeader("accept", "application/json");
       
      HttpResponse response = httpClient.execute(getRequest);
      if (response.getStatusLine().getStatusCode() != 200)
      {
        log.info("exception");
         
        throw new RuntimeException("Failed : HTTP error code : " + response.getStatusLine().getStatusCode());
      }
      BufferedReader br = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
       
      String myJSON = "";
      String output;
      while ((output = br.readLine()) != null) {
        myJSON = myJSON + output;
      }
      log.info("**** Myjson: " + myJSON);
      httpClient.getConnectionManager().shutdown();
       
      return myJSON;
    }
    catch (Exception e)
    {
      e.printStackTrace();
    }
    return null;
  }
}

Modify the Maven POM file

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

<dependency>
    <groupId>com.adobe.aem</groupId>
    <artifactId>uber-jar</artifactId>
    <version>6.4.0</version>
    <classifier>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>

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

PPom
Parent POM

Add the dependency shown above to the Parent POM file. Next, modify the POM file located at C:\AdobeCQ\YouTubeAEM64\core. The following code represents this POM file.

<?xml version="1.0" encoding="UTF-8"?>
<!--
 |  Copyright 2017 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>YouTubeAEM64</groupId>
        <artifactId>YouTubeAEM64</artifactId>
        <version>1.0-SNAPSHOT</version>
        <relativePath>../pom.xml</relativePath>
    </parent>
    <artifactId>YouTubeAEM64.core</artifactId>
    <packaging>bundle</packaging>
    <name>YouTubeAEM64 - Core</name>
    <description>Core bundle for YouTubeAEM64</description>
    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.sling</groupId>
                <artifactId>maven-sling-plugin</artifactId>
            </plugin>
            <plugin>
                <groupId>org.apache.felix</groupId>
                <artifactId>maven-bundle-plugin</artifactId>
                <extensions>true</extensions>
                <configuration>
                    <instructions>
                        <!-- Import any version of javax.inject, to allow running on multiple versions of AEM -->
                        <Import-Package>javax.inject;version=0.0.0,*</Import-Package>
                        <Sling-Model-Packages>
                            com.adobe.community.core
                        </Sling-Model-Packages>
                    </instructions>
                </configuration>
            </plugin>
        </plugins>
    </build>

    <dependencies>
        <!-- OSGi Dependencies -->
        <dependency>
            <groupId>com.adobe.aem</groupId>
            <artifactId>uber-jar</artifactId>
            <classifier>apis</classifier>
        </dependency>
    
        <dependency>
            <groupId>org.apache.geronimo.specs</groupId>
            <artifactId>geronimo-atinject_1.0_spec</artifactId>
        </dependency>
        <dependency>
            <groupId>org.osgi</groupId>
            <artifactId>osgi.core</artifactId>
        </dependency>
        <dependency>
            <groupId>org.osgi</groupId>
            <artifactId>osgi.cmpn</artifactId>
        </dependency>
        <dependency>
            <groupId>org.osgi</groupId>
            <artifactId>osgi.annotation</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>uber-jar</artifactId>
            <classifier>apis</classifier>
        </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-core</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\YouTubeAEM64.
  2. Run the following maven command: mvn -PautoInstallPackage install.
  3. The OSGi component can be found in the following folder: C:\AdobeCQ\YouTubeAEM64\core\target. The file name of the OSGi component is YouTubeAEM64.core-1.0-SNAPSHOT.jar.

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

Create an Experience Manager Touch UI component

Create the YouTube component by performing these tasks using CRXDE Lite:

1. Right click on /apps/YouTubeAEM64/components/content and then select New, Component.

2. Enter the following information into the Create Component dialog box:

  • Label: The name of the component to create. Enter youtube-component.
  • Title: The title that is assigned to the component. Enter youtube-component.
  • Description: The description that is assigned to the template. Enter: A YouTube component.
    Super Resource Type: Enter foundation/components/parbase.
    Group: The group in the side kick where the component appears. Enter YouTubeAEM64.

4. Click Ok.

Build the Touch UI dialog

A dialog lets an author click on the component in the Touch UI view during design time and enter values that are used by the component. The component created in this development article lets the AEM author enter a YouTube video ID. (See the illustration shown at the beginning of this development article.)

A dialog that is built for the Touch UI is defined by using nodes of type un:structured. You define the type of control on the Touch UI dialog by setting the node's sling:resourceType property. For example, to define a text field on a Touch UI dialog, set the sling:resourceType property to granite/ui/components/foundation/form/textfield.

To make creating a dialog easier for this component, copy the dialog under the HelloWorld component and paste it under the youtube-component at /apps/YouTubeAEM64/components/content/youtube-component

Change the name property under /apps/YouTubeAEM64/components/content/youtube-component/cq:dialog/content/items/column/items/text to ./videoid

dialog2
Change the name property

Add the HTL Code

For the purpose of this article, the HTL code is written within a Maven Archetype default component located here:

/apps/YouTubeAEM64/components/content/youtube-component/youtube-component.html

Change the file extention to .html and add the following code.

<html>
<head>
 
<style>
button.accordion {
    background-color: #eee;
    color: #444;
    cursor: pointer;
    padding: 18px;
    width: 480px;
    border: none;
    text-align: left;
    outline: none;
    font-size: 15px;
    transition: 0.4s;
    font-family:  "Times New Roman", Times, serif;
     font-size: 20px;
}
 
button.accordion.active, button.accordion:hover {
    background-color: #ddd;
}
 
button.accordion:after {
    content: '\002B';
    color: #777;
    font-weight: bold;
    float: right;
    margin-left: 5px;
}
 
button.accordion.active:after {
    content: "\2212";
}
 
div.panel {
    padding: 0px 18px;
    margin:6px;
    background-color: white;
    max-height: 0;
    overflow: hidden;
    transition: max-height 0.2s ease-out;
    font-family:  "Times New Roman", Times, serif;
     font-size: 20px;
     width:480px;
}
</style>
</head>
<body>
 
<!-- /* YouTube Component */ -->
 
<h1> Youtube Video </h1>
<sly data-sly-use.hello="com.adobe.community.core.YoutubeComponentC" />
 
${hello.Youtubepojo.videohtml @ context='html'}


<div>
<button class="accordion">Video title:</button>
<div class="panel">
<p> ${hello.Youtubepojo.videotitle}</p></div>

<button class="accordion">Video Author:</button>
<div class="panel">
<p> ${hello.Youtubepojo.video_author_name}</p></div>
</div> 
<script>
var acc = document.getElementsByClassName("accordion");
var i;
 
for (i = 0; i < acc.length; i++) {
  acc[i].onclick = function() {
    this.classList.toggle("active");
    var panel = this.nextElementSibling;
    if (panel.style.maxHeight){
      panel.style.maxHeight = null;
    } else {
      panel.style.maxHeight = panel.scrollHeight + "px";
    } 
  }
}
</script>
 
<!-- /* Checkbox code to check if link needs to open in new tab. */ -->
<hr>
<div><a target='${properties.isChecked ? "_blank" : "_self"}' href="${properties.path @ extension = 'html'}">${properties.name}</a>
</div>
<hr>
<!-- /* Code to check if link entered in path in Dialog */ -->
 
<div data-sly-test.socialshare="${properties.social1}">
<A HREF="${properties.social1}"  title="Facebook" width="50px" target="_blank"><img src="/content/dam/YouTubeComponent/png-facebook-icon-194.jpg"  alt="Facebook" ></A>
</div>
 
<!-- /* Code if link is not given in dialog then hide it from front end */ -->
 
<div data-sly-test="${!socialshare}">
<A data-sly-test="${''}" HREF="${properties.social1}"  title="Facebook" target="_blank"><img src="/content/dam/YouTubeComponent/png-facebook-icon-194.jpg"  alt="Facebook" ></A> 
</div>
</body>
</html>

View the output of the HTL component

The final task is to drag and drop the YouTube component from the Side Rail to the AEM web page located at:

http://localhost:4502/editor.html/content/YouTubeAEM64/en.html

Click on the component and specify the video id of a YouTube video, as shown in the following video.


Note:

A video ID can be obtained from the URL of the video. For example, given this URL: https://www.youtube.com/watch?v=oeO6zwjxyQw, the ID is oeO6zwjxyQw

Note:

Be sure to set the values in the component dialog. 

See also

Join the AEM community at: Adobe Experience Manager Community

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