Article summary

Summary

Discusses how to develop an AEM Service that uses the Jasper Reports API.  By following this article, you will learn about these AEM concepts

  • How to use Jasper Reports API within AEM to develop PDF reports (this article shows you how to generate a PDF report from a standalone Eclipse project and then how to integrate Jasper Report API in an AEM service).
  • How to write a custom Urber OSGi that contains third-party APIs.
  • How to upload the Urber OSGi to the Maven repository so you can build AEM services that use classes in the Urber JAR.
  • How to deal with multipe dependencies when building complex Java logic.
  • How to write PDF reports to the AEM DAM by using the AssetManager API.
Digital Marketing Solution(s) Adobe Experience Manager (Adobe CQ)
Audience
Developer (Advanced)
Required Skills
JCR nodes, JavaScript, HTML
Tested On Adobe Experience Manager 6.1
Video N/A

Note:

This article has a prerequisite on a DataSourcePool. Before following along with this article, ensure that you perform these tasks:

1 - setup the MySQL database as specified in this article

2 - setup a DataSourcePool configuration; otherwise, the code will not work

3  - deploy the MySQL data drive file to AEM  

For information about performing these tasks, see this AEM HELPX Artilce: Injecting a DataSourcePool Service into an Adobe Experience Manager OSGi bundle.

Introduction

You can create a custom Jasper Reports service for Adobe Experience Manager (AEM) that builds dynamic reports. A benefit of creating a custom service is you can develop it to meet your business requirements and integrate the reporting service to use data queried from an AEM service. For example, you can create an AEM reporting solution that queries enterprise data from a database (mySQL is used in this article as an example) that a digital marketer is interested in viewing and produces a PDF report, as shown in the following illustration.

Client
A HTL Component Dialog

The custom AEM Service invokes the operation of the OSGi bundle that uses the Jasper Reports API. Then the service persists the Jasper Report in the AEM DAM by using the AssetManager API, as shown in this illustration. 

DAM
A report stored in the AEM DAM

MySQL Database

To follow along with this development article, you need to setup a local instance of MySQL. Create a datasource named cq and place a table named Customer in that datasource.

The following describes the fields in the Customer table: 

  • custId  - An integer that specifies the customer identifier value (PK)
  • custFirst -  A string value that specifies the customer’s first name. 
  • custLast - A string value that specifies the customer’s last name. 
  • custDesc - A string value that specifies the customer’s description.
  • custAddress - A string value that specifies the customer’s address or phone number.

Note:

Ensure you use the same field names; otherwise, the code in this article will not work. For this article, the user name and password for both values is root.  For more information about MySQL, including how to install it, see https://www.mysql.com/

Jasper Reports API

To build an AEM component that is able to produce PDF reports using Jasper Reports, you need to use the Jasper Reports API. For information, see http://jasperreports.sourceforge.net/api/.

For information about Jasper Reports, see http://community.jaspersoft.com/project/jasperreports-library

Create a custom Urber Jasper Reports OSGi bundle

The first step is to create a custom Jasper Report Urber OSGi bundle that contains the required JAR files required to use Jasper Reports. This section is broken into these sections:

  1. Retrieve all JAR files. 
  2. Create a JAR file that contains a Java class that produces the PDF report. The Java class has a method named CreateReport that accepts a String value that represents the report name and returns an InputStream instance that represents the PDF report. The InputStream is used by an AEM service to write to the AEM DAM (this is covered later in this development article). 
  3. Build custom Jasper Report Urber OSGi bundle that contains this class and all of the required JAR files required to use the Jasper Reports API (there are 14 JAR files that are included in this OSGi bundle). 
  4. Upload the Jasper Report Urber OSGi bundle to your local Maven repository. THis is required to build an AEM Service that uses the custom Java class that builds a Jasper Reports PDF report. 

Retrieve all Jasper Reports JAR files

To successfully build the PDF report using the Jasper Reports API, you need to download the following JAR files: 

  • commons-beanutils-1.9.0.jar
  • commons-codec-1.5.jar
  • commons-collections-3.0.jar
  • commons-digester-1.7.jar
  • commons-lang3-3.4.jar
  • commons-logging-1.2.jar
  • dynamicreports-core-4.1.1.jar
  • itext-2.1.7.jar
  • jackson-annotations-2.1.4.jar
  • jackson-core-2.1.4.jar
  • jackson-databind-2.1.4.jar
  • jasper-compiler-jdt-5.5.23.jar
  • jasperreports-6.3.0.jar
  • jasperreports-javaflow-6.3.0.jar
  • jaxb-api-2.1.jar
  • jcommon-1.0.23.jar
  • jfreechart-1.0.19.jar
  • log4j-1.2.14.jar
  • poi-2.5.1-final-20040804.jar
  • velocity-1.7.jar
  • xml-apis-2.0.2.jar
  • xml-apis-ext-1.3.04.jar

You can download jasperreports-6.3.0.jarjasperreports-fonts-6.3.0.jar, and jasperreports-javaflow-6.3.0.jar from this URL:

https://sourceforge.net/projects/jasperreports/

These three files are located in the jasperreports-6.3.0\dist folder (at the time of this article, version 6.3.0 was available). You can download the remaining JAR files using Maven download page. For example you can download the dynamicreports-core-3.1.6.jar file from this URL:

https://mvnrepository.com/artifact/net.sourceforge.dynamicreports/dynamicreports-core/3.1.6

Add all of these JAR files to your Eclipse project's class path. Next, create a Java class named CreateReports that uses the Jasper Reports API.  The following Java class represents this class. 

Test the Application logic in an Eclipse Java project

Create a Java standalone project that tests the Jasper Reports API and all of the dependency JAR files. It is very important to ensure that this application logic runs outside of AEM before you attempt to run the application logic as an AEM service. 

Create a Java Eclipse project. Add all of the dependencies specified in the previous section to this project's class path. In addition, add the MySQL driver file such as mysql-connector-java-5.1.22.jar to the project's class path. (In the standalone application, a connection is manually created while within AEM, a DataSourcePool is used).

In your Java project, add a class named CreateReport and then add a method named BuildReport. Add the following Java code to the CreateReport.java file. In this example, notice that the PDF report is written to the root of the C drive. 

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

import net.sf.dynamicreports.jasper.builder.JasperReportBuilder;
import net.sf.dynamicreports.report.builder.DynamicReports;
import net.sf.dynamicreports.report.builder.column.Columns;
import net.sf.dynamicreports.report.builder.component.Components;
import net.sf.dynamicreports.report.builder.datatype.DataTypes;
import net.sf.dynamicreports.report.constant.HorizontalAlignment;
import net.sf.dynamicreports.report.exception.DRException;

public class CreateReport {

    
	
	//This creates a Jasper Report
	public String BuildPDFReport(String reportName) {
       
		
		  Connection connection = null;
	        try {
	            Class.forName("com.mysql.jdbc.Driver");
	            connection = DriverManager.getConnection(
	                    "jdbc:mysql://localhost:3306/cq", "root", "root");
	        } catch (Exception e) {
	            e.printStackTrace();
	            return "Error with Connection";
	        } 
	        JasperReportBuilder report = DynamicReports.report();//a new report
	        report
	                .columns(
	                        Columns.column("Customer Id", "custId", DataTypes.integerType()),
	                        Columns.column("First Name", "custFirst", DataTypes.stringType()),
	                        Columns.column("Last Name", "custLast", DataTypes.stringType()),
	                        Columns.column("Description", "custDesc", DataTypes.stringType()))
	                .title(//title of the report
	                        Components.text("SimpleReportExample")
	                                .setHorizontalAlignment(HorizontalAlignment.CENTER))
	                .pageFooter(Components.pageXofY())//show page number on the page footer
	                .setDataSource("SELECT custId, custFirst, custLast, custDesc FROM customer",
	                        connection);

	        try {
	         
	            //export the report to a pdf file
	            report.toPdf(new FileOutputStream("C:\\report.pdf"));

	           return ("Report is done") ; 
	        }
	        catch (Exception e) {
	            
	            return "Report failed "+e.getMessage() ;
	            
	        } 
         
	    }
 }

Note:

Make sure that this Java application logic successfully pulls data from the Customer MySQL table and creates a report. This is simply an example of using the Jasper Reports API to generate a report. Consult the Jasper Reports page for more samples on using this API to create other report types.

For this example, ensure that you see the report written to the C:\ root as shown in this illustration. 

Report
A PDF Report generated by Jasper Reports API

Note:

Make sure that you get this Application Logic working before proceeding with this development article. It is important to get Java logic working outside of AEM before attempting to integrate the logic within AEM.  

Build custom Jasper Report Urber OSGi bundle

To create a  Jasper Reports Urber OSGi bundle, you use another Eclipse project (the Eclipse version indigo works best) that creates an OSGi bundle. An OSGi bundle is essentially a collection of JAR files and a MANIFEST.MF file. In this use case, include all of the JAR files listed in this section. All of these JAR files must be located in the OSGi bundle in order for the Jasper Reports API to work within AEM. 

Create an OSGi bundle that contains the JDBC application logic:

1. Start Eclipse (Indigo). The steps below have been tested on Eclipse Java EE IDE for Web Developers version Indigo Service Release 1.

2. Select File, New, Other.

3. Under the Plug-in Development folder, choose Plug-in from Existing JAR Archives. Name your project JasperAEMUrber.

4. In the JAR selection dialog, click the Add external button, and browse to the JAR files. Add them all.

5. Click Next.

6. In the Plug-in Project properties dialog, ensure that you check the checkbox for Analyze library contents and add dependencies.

7. Make sure that the Target Platform is the standard OSGi framework.

8. Ensure the checkboxes for Unzip the JAR archives into the project and Update references to the JAR files are both checked.

9. Click Next, and then Finish.

10. Click the Runtime tab.

11. Make sure that the Exported Packages list is populated.

12. Make sure these packages have been added under the Export-Package header in MANIFEST.MF. Remove the version information in the MANIFEST.MF file. Version numbers can cause conflicts when you upload the OSGi bundle.

13. Also make sure that the Import-Package header in MANIFEST.MF is also populated, as shown below. Copy the import and export section below to your MF file. 

14. Save the project.

15. Build the OSGi bundle by right-clicking the project in the left pane, choose Export, Plug-in Development, Deployable plug-ins and fragments, and click Next.

16. Select a location for the export (C:\TEMP) and click Finish. Name your bundle JasperAEMUrber (Ignore any error messages).

17. In C:\TEMP\plugins, you should now find the OSGi bundle.

18. Login to Apache Felix Web Console at http://server:port/system/console/bundles (default admin user = admin with password= admin).

19. Sort the bundle list by Id and note the Id of the last bundle.

20. Click the Install/Update button.

21. Check the Start Bundle checkbox.

22. Browse to the bundle JAR file you just built. (C:\TEMP\plugins).

23. Click Install.

24. Click the Refresh Packages button.

25. Check the bundle with the highest Id.

26. Your new bundle should now be listed with the status Active.

27. If the status is not Active, check the error.log for exceptions. If you get “org.osgi.framework.BundleException: Unresolved constraint” errors, check the MANIFEST.MF for strict version requirements which might follow: javax.xml.namespace; version=”3.1.0”

28. If the version requirement causes problems, remove it so that the entry looks like this: javax.xml.namespace.

29. If the entry is not required, remove it entirely.

30. Rebuild the bundle.

31. Delete the previous bundle and deploy the new one.

MF File

The following represents the MF file you can use. 

Manifest-Version: 1.0
Bundle-ManifestVersion: 2
Bundle-Name: JasperAEMUrber
Bundle-SymbolicName: JasperAEMUrber
Bundle-Version: 1.0.0
Bundle-ClassPath: .
Export-Package: com.foo.reports,
 com.lowagie.text,
 com.lowagie.text.exceptions,
 com.lowagie.text.factories,
 com.lowagie.text.html,
 com.lowagie.text.html.simpleparser,
 com.lowagie.text.pdf,
 com.lowagie.text.pdf.codec,
 com.lowagie.text.pdf.codec.wmf,
 com.lowagie.text.pdf.collection,
 com.lowagie.text.pdf.crypto,
 com.lowagie.text.pdf.draw,
 com.lowagie.text.pdf.events,
 com.lowagie.text.pdf.fonts,
 com.lowagie.text.pdf.fonts.cmaps,
 com.lowagie.text.pdf.hyphenation,
 com.lowagie.text.pdf.interfaces,
 com.lowagie.text.pdf.internal,
 com.lowagie.text.pdf.parser,
 com.lowagie.text.xml,
 com.lowagie.text.xml.simpleparser,
 com.lowagie.text.xml.xmp,
 com.lowagie.tools,
 com.mysql.jdbc,
 com.mysql.jdbc.authentication,
 com.mysql.jdbc.exceptions,
 com.mysql.jdbc.exceptions.jdbc4,
 com.mysql.jdbc.integration.c3p0,
 com.mysql.jdbc.integration.jboss,
 com.mysql.jdbc.interceptors,
 com.mysql.jdbc.jdbc2.optional,
 com.mysql.jdbc.jmx,
 com.mysql.jdbc.log,
 com.mysql.jdbc.profiler,
 com.mysql.jdbc.util,
 net.sf.dynamicreports.design.base,
 net.sf.dynamicreports.design.base.barcode,
 net.sf.dynamicreports.design.base.chart,
 net.sf.dynamicreports.design.base.chart.dataset,
 net.sf.dynamicreports.design.base.chart.plot,
 net.sf.dynamicreports.design.base.component,
 net.sf.dynamicreports.design.base.crosstab,
 net.sf.dynamicreports.design.base.expression,
 net.sf.dynamicreports.design.base.style,
 net.sf.dynamicreports.design.constant,
 net.sf.dynamicreports.design.definition,
 net.sf.dynamicreports.design.definition.barcode,
 net.sf.dynamicreports.design.definition.chart,
 net.sf.dynamicreports.design.definition.chart.dataset,
 net.sf.dynamicreports.design.definition.chart.plot,
 net.sf.dynamicreports.design.definition.component,
 net.sf.dynamicreports.design.definition.crosstab,
 net.sf.dynamicreports.design.definition.expression,
 net.sf.dynamicreports.design.definition.style,
 net.sf.dynamicreports.design.exception,
 net.sf.dynamicreports.design.transformation,
 net.sf.dynamicreports.design.transformation.chartcustomizer,
 net.sf.dynamicreports.jasper.base,
 net.sf.dynamicreports.jasper.base.export,
 net.sf.dynamicreports.jasper.base.reporthandler,
 net.sf.dynamicreports.jasper.base.tableofcontents,
 net.sf.dynamicreports.jasper.base.templatedesign,
 net.sf.dynamicreports.jasper.builder,
 net.sf.dynamicreports.jasper.builder.export,
 net.sf.dynamicreports.jasper.constant,
 net.sf.dynamicreports.jasper.definition,
 net.sf.dynamicreports.jasper.definition.export,
 net.sf.dynamicreports.jasper.exception,
 net.sf.dynamicreports.jasper.transformation,
 net.sf.dynamicreports.report,
 net.sf.dynamicreports.report.base,
 net.sf.dynamicreports.report.base.barcode,
 net.sf.dynamicreports.report.base.chart,
 net.sf.dynamicreports.report.base.chart.dataset,
 net.sf.dynamicreports.report.base.chart.plot,
 net.sf.dynamicreports.report.base.column,
 net.sf.dynamicreports.report.base.component,
 net.sf.dynamicreports.report.base.crosstab,
 net.sf.dynamicreports.report.base.datatype,
 net.sf.dynamicreports.report.base.expression,
 net.sf.dynamicreports.report.base.grid,
 net.sf.dynamicreports.report.base.style,
 net.sf.dynamicreports.report.builder,
 net.sf.dynamicreports.report.builder.barcode,
 net.sf.dynamicreports.report.builder.chart,
 net.sf.dynamicreports.report.builder.column,
 net.sf.dynamicreports.report.builder.component,
 net.sf.dynamicreports.report.builder.condition,
 net.sf.dynamicreports.report.builder.crosstab,
 net.sf.dynamicreports.report.builder.datatype,
 net.sf.dynamicreports.report.builder.expression,
 net.sf.dynamicreports.report.builder.grid,
 net.sf.dynamicreports.report.builder.group,
 net.sf.dynamicreports.report.builder.style,
 net.sf.dynamicreports.report.builder.subtotal,
 net.sf.dynamicreports.report.builder.tableofcontents,
 net.sf.dynamicreports.report.component,
 net.sf.dynamicreports.report.constant,
 net.sf.dynamicreports.report.datasource,
 net.sf.dynamicreports.report.defaults,
 net.sf.dynamicreports.report.defaults.xml,
 net.sf.dynamicreports.report.definition,
 net.sf.dynamicreports.report.definition.barcode,
 net.sf.dynamicreports.report.definition.chart,
 net.sf.dynamicreports.report.definition.chart.dataset,
 net.sf.dynamicreports.report.definition.chart.plot,
 net.sf.dynamicreports.report.definition.column,
 net.sf.dynamicreports.report.definition.component,
 net.sf.dynamicreports.report.definition.crosstab,
 net.sf.dynamicreports.report.definition.datatype,
 net.sf.dynamicreports.report.definition.expression,
 net.sf.dynamicreports.report.definition.grid,
 net.sf.dynamicreports.report.definition.style,
 net.sf.dynamicreports.report.exception,
 net.sf.jasperreports.ant,
 net.sf.jasperreports.charts,
 net.sf.jasperreports.charts.base,
 net.sf.jasperreports.charts.design,
 net.sf.jasperreports.charts.fill,
 net.sf.jasperreports.charts.type,
 net.sf.jasperreports.charts.util,
 net.sf.jasperreports.charts.xml,
 net.sf.jasperreports.compilers,
 net.sf.jasperreports.components,
 net.sf.jasperreports.components.barbecue,
 net.sf.jasperreports.components.barcode4j,
 net.sf.jasperreports.components.charts,
 net.sf.jasperreports.components.headertoolbar,
 net.sf.jasperreports.components.headertoolbar.actions,
 net.sf.jasperreports.components.headertoolbar.json,
 net.sf.jasperreports.components.iconlabel,
 net.sf.jasperreports.components.items,
 net.sf.jasperreports.components.items.fill,
 net.sf.jasperreports.components.list,
 net.sf.jasperreports.components.map,
 net.sf.jasperreports.components.map.fill,
 net.sf.jasperreports.components.map.type,
 net.sf.jasperreports.components.sort,
 net.sf.jasperreports.components.sort.actions,
 net.sf.jasperreports.components.spiderchart,
 net.sf.jasperreports.components.spiderchart.type,
 net.sf.jasperreports.components.table,
 net.sf.jasperreports.components.table.fill,
 net.sf.jasperreports.components.table.util,
 net.sf.jasperreports.crosstabs,
 net.sf.jasperreports.crosstabs.base,
 net.sf.jasperreports.crosstabs.design,
 net.sf.jasperreports.crosstabs.fill,
 net.sf.jasperreports.crosstabs.fill.calculation,
 net.sf.jasperreports.crosstabs.interactive,
 net.sf.jasperreports.crosstabs.type,
 net.sf.jasperreports.crosstabs.xml,
 net.sf.jasperreports.data,
 net.sf.jasperreports.data.bean,
 net.sf.jasperreports.data.cache,
 net.sf.jasperreports.data.csv,
 net.sf.jasperreports.data.ds,
 net.sf.jasperreports.data.ejbql,
 net.sf.jasperreports.data.empty,
 net.sf.jasperreports.data.excel,
 net.sf.jasperreports.data.hibernate,
 net.sf.jasperreports.data.hibernate.spring,
 net.sf.jasperreports.data.http,
 net.sf.jasperreports.data.jdbc,
 net.sf.jasperreports.data.jndi,
 net.sf.jasperreports.data.json,
 net.sf.jasperreports.data.mondrian,
 net.sf.jasperreports.data.provider,
 net.sf.jasperreports.data.qe,
 net.sf.jasperreports.data.xls,
 net.sf.jasperreports.data.xlsx,
 net.sf.jasperreports.data.xml,
 net.sf.jasperreports.data.xmla,
 net.sf.jasperreports.engine,
 net.sf.jasperreports.engine.analytics.data,
 net.sf.jasperreports.engine.analytics.dataset,
 net.sf.jasperreports.engine.base,
 net.sf.jasperreports.engine.component,
 net.sf.jasperreports.engine.convert,
 net.sf.jasperreports.engine.data,
 net.sf.jasperreports.engine.design,
 net.sf.jasperreports.engine.design.events,
 net.sf.jasperreports.engine.export,
 net.sf.jasperreports.engine.export.data,
 net.sf.jasperreports.engine.export.draw,
 net.sf.jasperreports.engine.export.oasis,
 net.sf.jasperreports.engine.export.ooxml,
 net.sf.jasperreports.engine.export.ooxml.type,
 net.sf.jasperreports.engine.export.tabulator,
 net.sf.jasperreports.engine.export.type,
 net.sf.jasperreports.engine.export.zip,
 net.sf.jasperreports.engine.fill,
 net.sf.jasperreports.engine.fonts,
 net.sf.jasperreports.engine.part,
 net.sf.jasperreports.engine.print,
 net.sf.jasperreports.engine.query,
 net.sf.jasperreports.engine.scriptlets,
 net.sf.jasperreports.engine.style,
 net.sf.jasperreports.engine.type,
 net.sf.jasperreports.engine.util,
 net.sf.jasperreports.engine.util.xml,
 net.sf.jasperreports.engine.virtualization,
 net.sf.jasperreports.engine.xml,
 net.sf.jasperreports.export,
 net.sf.jasperreports.export.annotations,
 net.sf.jasperreports.export.parameters,
 net.sf.jasperreports.export.type,
 net.sf.jasperreports.expressions,
 net.sf.jasperreports.extensions,
 net.sf.jasperreports.functions,
 net.sf.jasperreports.functions.annotations,
 net.sf.jasperreports.governors,
 net.sf.jasperreports.j2ee.servlets,
 net.sf.jasperreports.olap,
 net.sf.jasperreports.olap.mapping,
 net.sf.jasperreports.olap.mondrian,
 net.sf.jasperreports.olap.olap4j,
 net.sf.jasperreports.olap.result,
 net.sf.jasperreports.olap.xmla,
 net.sf.jasperreports.parts,
 net.sf.jasperreports.parts.subreport,
 net.sf.jasperreports.renderers,
 net.sf.jasperreports.renderers.util,
 net.sf.jasperreports.repo,
 net.sf.jasperreports.search,
 net.sf.jasperreports.swing,
 net.sf.jasperreports.types.date,
 net.sf.jasperreports.util,
 net.sf.jasperreports.view,
 net.sf.jasperreports.view.save,
 net.sf.jasperreports.web,
 net.sf.jasperreports.web.actions,
 net.sf.jasperreports.web.commands,
 net.sf.jasperreports.web.listeners,
 net.sf.jasperreports.web.servlets,
 net.sf.jasperreports.web.util,
 org.apache.commons.collections,
 org.apache.commons.collections.bag,
 org.apache.commons.collections.bidimap,
 org.apache.commons.collections.buffer,
 org.apache.commons.collections.collection,
 org.apache.commons.collections.comparators,
 org.apache.commons.collections.functors,
 org.apache.commons.collections.iterators,
 org.apache.commons.collections.keyvalue,
 org.apache.commons.collections.list,
 org.apache.commons.collections.map,
 org.apache.commons.collections.set,
 org.apache.commons.digester,
 org.apache.commons.digester.parser,
 org.apache.commons.digester.plugins,
 org.apache.commons.digester.plugins.strategies,
 org.apache.commons.digester.substitution,
 org.apache.commons.digester.xmlrules,
 org.apache.commons.lang,
 org.apache.commons.lang.builder,
 org.apache.commons.lang.enums,
 org.apache.commons.lang.exception,
 org.apache.commons.lang.math,
 org.apache.commons.lang.mutable,
 org.apache.commons.lang.reflect,
 org.apache.commons.lang.text,
 org.apache.commons.lang.time,
 org.apache.commons.lang3,
 org.apache.commons.lang3.builder,
 org.apache.commons.lang3.concurrent,
 org.apache.commons.lang3.event,
 org.apache.commons.lang3.exception,
 org.apache.commons.lang3.math,
 org.apache.commons.lang3.mutable,
 org.apache.commons.lang3.reflect,
 org.apache.commons.lang3.text,
 org.apache.commons.lang3.text.translate,
 org.apache.commons.lang3.time,
 org.apache.commons.lang3.tuple,
 org.apache.commons.logging,
 org.apache.commons.logging.impl,
 org.apache.poi.ddf,
 org.apache.poi.dev,
 org.apache.poi.hpsf,
 org.apache.poi.hpsf.wellknown,
 org.apache.poi.hssf.dev,
 org.apache.poi.hssf.eventmodel,
 org.apache.poi.hssf.eventusermodel,
 org.apache.poi.hssf.model,
 org.apache.poi.hssf.record,
 org.apache.poi.hssf.record.aggregates,
 org.apache.poi.hssf.record.formula,
 org.apache.poi.hssf.usermodel,
 org.apache.poi.hssf.util,
 org.apache.poi.poifs.common,
 org.apache.poi.poifs.dev,
 org.apache.poi.poifs.eventfilesystem,
 org.apache.poi.poifs.filesystem,
 org.apache.poi.poifs.property,
 org.apache.poi.poifs.storage,
 org.apache.poi.util,
 org.eclipse.jdt.core.compiler,
 org.eclipse.jdt.internal.compiler,
 org.eclipse.jdt.internal.compiler.ast,
 org.eclipse.jdt.internal.compiler.batch,
 org.eclipse.jdt.internal.compiler.classfmt,
 org.eclipse.jdt.internal.compiler.codegen,
 org.eclipse.jdt.internal.compiler.env,
 org.eclipse.jdt.internal.compiler.flow,
 org.eclipse.jdt.internal.compiler.impl,
 org.eclipse.jdt.internal.compiler.lookup,
 org.eclipse.jdt.internal.compiler.parser,
 org.eclipse.jdt.internal.compiler.parser.diagnose,
 org.eclipse.jdt.internal.compiler.problem,
 org.eclipse.jdt.internal.compiler.util,
 org.eclipse.jdt.internal.core.util,
 org.gjt.mm.mysql,
 org.w3c.tools.codec
Bundle-RequiredExecutionEnvironment: JavaSE-1.7
Import-Package: org.xml.sax.helpers,
 org.mozilla.javascript,
 javax.sql.rowset,
 javax.net.ssl,
 org.apache.lucene.search,
 javax.persistence,
 javax.swing.text,
 javax.xml.stream,
  javax.xml.soap,
 org.apache.log4j,
 org.apache.lucene.document,
 org.w3c.dom.traversal,
 org.apache.xalan.xslt,
 javax.management,
 org.apache.lucene.analysis,
 javax.naming,
 javax.naming.spi,
 javax.xml.transform.dom,
 org.apache.lucene.analysis.tokenattributes,
 org.apache.lucene.store,
 javax.crypto,
  org.eclipse.jdt.core,
  javax.swing.border,
 org.apache.xpath.objects,
 org.apache.xpath,
 javax.print.attribute,
 org.xml.sax,
 javax.sql,
 org.w3c.dom,
 org.apache.lucene.search.spans,
 javax.net,
 org.apache.lucene.util,
 javax.xml.namespace,
 javax.swing.table,
 org.apache.lucene.index,
 javax.print.attribute.standard,
 javax.swing.event,
 javax.imageio.metadata,
 javax.transaction.xa,
 javax.imageio,
 javax.swing,
 javax.xml.transform.stream,
 javax.servlet,
 javax.servlet.http,
  javax.xml.xpath,
 org.apache.lucene.analysis.miscellaneous,
 javax.swing.filechooser,
 javax.xml.transform.stax,
 javax.swing.text.html,
 javax.xml.bind,
 javax.xml.parsers,
 javax.imageio.stream,
 javax.print,
 javax.imageio.plugins.jpeg,
 javax.xml.transform,
 javax.xml.transform.sax

Note:

Getting the MF file correct all depends on what OSGi files you have in your AEM instance. This MF file is a starting point. You may have to modify the import and export sections to get this bundle into an Active state. 

Upload the Jasper Urber OSGi bundle to your local Maven repository

You need to upload the Jasper Urber OSGi bundle to your local Maven repository. The reason is because the AEM custom service that is built uses the Jasper Reports API exposed in this OSGi bundle. 

As a result, when the AEM Service is build with a Maven 10 Archetype, Maven must be able to resolve all import statements (and Java logic) that use the Jasper Reports API such as these.

import net.sf.dynamicreports.report.builder.DynamicReports;
import net.sf.dynamicreports.report.builder.column.Columns;

In order to resolve the Jasper Reports API within an AEM service, the Urber JasperReports JAR file must be located in the Maven repository. You can upload the Urber JAR to Maven by using this Maven command: 

mvn install:install-file -Dfile=C:/JasperReports/plugins/JasperAEMUrber_1.0.0.jar -DgroupId=com.foo.reports -DartifactId=jrurbersrt1.0 -Dversion=1.0 -Dpackaging=jar -DgeneratePom=true

Notice that you must specify the location of the Urber JAR file in the -Dfile argument. Also notice that you specify the Dgroup and DartifactID values. Once you upload the JAR to Maven using this command, you can reference this JAR file using this Dependency.

<groupId>com.foo.reports</groupId>
<artifactId>jrurbersrt1.0</artifactId>
<version>1.0</version>
<scope>system</scope>
<systemPath>C:\Users\scottm\.m2\repository\com\foo\reports\jrurbersrt1.0\1.0\jrurbersrt1.0-1.0.jar</systemPath>
</dependency>

Notice that scope element is system and systemPath references the location of the JAR file in the repository. (This dependency is used later in this article to build the AEM service) 

Setup Maven in your development environment

You can use Maven to build an OSGi bundle that contains a Sling Servlet. 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:

Default locale: en_US, platform encoding: Cp1252
OS name: "windows 7", version: "6.1", arch: "amd64", family: "windows"

Note:

It is recommended that you use Maven 3.0.3 or greater. 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>

Note:

The Adobe repository URL is now made secured. Change http://repo.adobe.com/nexus/content/groups/public/ to https://repo.adobe.com/nexus/content/groups/public/.

Create an AEM Maven 10 archetype project

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

files
Maven Archetype 10 generated 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 AEM 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 - jasperHTL
  • artifactId - jasperHTL
  • version - 1.0-SNAPSHOT
  • package - com.jasper.community
  • appsFolderName - jasperHTL
  • artifactName - jasperHTL
  • componentGroupName - jasperHTL
  • contentFolderName - jasperHTL
  • cssId - jasperHTL
  • packageGroup -jasperHTL
  • siteName - jasperHTL

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 jasperHTL 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 Import Project Dialog

The Eclipse project that you work in to build the OSGi service is jasperHTL.core. You do not have to work in the other projects under jasperHTL. 

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. Also, delete all files in the project except for the   com.jasper.community.core package. Place the two Java files discussed in this article into this package. Delete all other Java files. 

BuildReport interface

The next step is to add Java interface named BuildReport to the com.jasper.community.core package. This interface defines the operations exposed by your custom AEM service. The following Java code represents the BuildReport Java interface.

package com.jasper.community.core;

public interface BuildReport {
	
	
	public String BuildReport(); 

}

BuildReportImpl class

The BuildReportImpl class is the AEM service that uses the Jasper Reports API to build a report. The Jasper Report is written to an InputStream and then the AEM AssetManager API to used to write the PDF report to the AEM Dam. (This is an example of how to use the Jasper Reports API within an AEM service). 

The following Java represents the BuildReportImpl class. 

 

package com.jasper.community.core;


import com.jasper.community.core.BuildReport;

import java.io.FileOutputStream;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;


import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
   

import javax.jcr.Node;
import javax.jcr.Session;

import java.io.InputStream ; 
import java.sql.Connection;
  

 import org.apache.sling.api.resource.Resource;
import org.apache.sling.api.resource.ResourceResolver;
import org.apache.sling.api.resource.ValueMap;
import org.apache.felix.scr.annotations.Reference;
import org.apache.felix.scr.annotations.Component;
import org.apache.felix.scr.annotations.Service;


import net.sf.dynamicreports.jasper.builder.JasperReportBuilder;
import net.sf.dynamicreports.report.builder.DynamicReports;
import net.sf.dynamicreports.report.builder.column.Columns;
import net.sf.dynamicreports.report.builder.component.Components;
import net.sf.dynamicreports.report.builder.datatype.DataTypes;
import net.sf.dynamicreports.report.constant.HorizontalAlignment;
import net.sf.dynamicreports.report.exception.DRException;


import com.day.commons.datasource.poolservice.DataSourcePool;


//AssetManager
import com.day.cq.dam.api.AssetManager; 
import com.foo.reports.CreateReport; //located in the Urder Jasper Reports OSGi bundle that we created

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


//Sling Imports
import org.apache.sling.api.resource.ResourceResolverFactory ;
import org.apache.sling.api.resource.ResourceResolver;
import org.apache.sling.api.resource.Resource;

import javax.sql.DataSource;


//This is a component so it can provide or consume services
@Component

@Service

public class BuildReportImpl implements BuildReport  {
	
	
    
  //Inject a Sling ResourceResolverFactory
    @Reference
    private ResourceResolverFactory resolverFactory;
    
    @Reference
    private DataSourcePool source;
	
    
    /** Default log. */
    protected final Logger log = LoggerFactory.getLogger(this.getClass());
	
	public String BuildReport()
	{
		
		
		DataSource dataSource = null;
		 Connection connection = null;
		
		try{
			
			 // Create a Connection object
			connection =  getConnection();
			
			//Use JasperReport app logic in an AEM Service 
			JasperReportBuilder report = DynamicReports.report();//a new report
	        report
	                .columns(
	                        Columns.column("Customer Id", "custId", DataTypes.integerType()),
	                        Columns.column("First Name", "custFirst", DataTypes.stringType()),
	                        Columns.column("Last Name", "custLast", DataTypes.stringType()),
	                        Columns.column("Description", "custDesc", DataTypes.stringType()))
	                .title(//title of the report
	                        Components.text("SimpleReportExample")
	                                .setHorizontalAlignment(HorizontalAlignment.CENTER))
	                .pageFooter(Components.pageXofY())//show page number on the page footer
	                .setDataSource("SELECT custId, custFirst, custLast, custDesc FROM customer",
	                        connection);

	                          
	            //Create an InputStream that represents the report. The InputSteam is used by an AEM service
	            //to write to the AEM DAM
	            ByteArrayOutputStream os = new ByteArrayOutputStream(); 
	                         
	            //export the report to a pdf file
	            report.toPdf(os);
	             
	           InputStream is =  new ByteArrayInputStream(os.toByteArray());; 

	           int length = is.available();
	             
	            log.info("IS IS THIS BIG " +length);
	             
	            //Persist the PDF Report in the AEM DAM
	            String reportDetails =  writeToDam(is, "JasperReport.pdf"); 
	             
	            log.info("Details is " +reportDetails);
	             
	            return "Report was successfully created";
	             
	        }
	        catch (Exception e)
	        {
	            log.info(e.getMessage());
	        }
	         
	        return "ERROR" ; 
	         
	        }
	    
	    //Write the Jasper Report to the DAM 
	  //Save the uploaded file into the AEM DAM using AssetManager APIs
	    private String writeToDam(InputStream is, String fileName)
	    {
	    try
	    {
	        //Inject a ResourceResolver
	        ResourceResolver resourceResolver = resolverFactory.getAdministrativeResourceResolver(null);
	         
	        //Use AssetManager to place the file into the AEM DAM
	        com.day.cq.dam.api.AssetManager assetMgr = resourceResolver.adaptTo(com.day.cq.dam.api.AssetManager.class);
	        
	        
	        String newFile = "/content/dam/reports/"+fileName ; 
	        
	        
	        assetMgr.createAsset(newFile, is,"application/pdf", true);
	             
	        // Return the path to the file was stored
	        return newFile;
	    }
	    catch(Exception e)
	    {
	        log.info("Error IS "+e.getMessage())  ;
	    }
	    return null;
	    }
	    
	    
	    
	  //Returns a connection using the configured DataSourcePool 
	    private Connection getConnection()
	    {
	             DataSource dataSource = null;
	             Connection con = null;
	             try
	             {
	                 //Inject the DataSourcePool right here! 
	                 dataSource = (DataSource) source.getDataSource("Customer");
	                 con = dataSource.getConnection();
	                 return con;
	                 
	               }
	             catch (Exception e)
	             {
	                 e.printStackTrace(); 
	             }
	                 return null; 
	    }

	}

Note:

This code injects a DataSourcePool object to get the data from MySQL. Ensure that you setup a DataSourcePool configuration; otherwise, the code will not work. Also, make sure you deploy the MySQL data drive file to AEM.  For information about performing these two tasks, see this AEM HELPX Artilce: Injecting a DataSourcePool Service into an Adobe Experience Manager OSGi bundle.

Modify the Maven POM file

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

<dependency>
<groupId>com.adobe.aem</groupId>
<artifactId>uber-jar</artifactId>
<version>6.1.0</version>
<scope>provided</scope>
<classifier>obfuscated-apis</classifier>
</dependency>

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

ParentPOM
Parent POM

Add the dependency shown above to the Parent POM file. Next, modify the POM file located at C:\AdobeCQ\jasperHTL\core.

 

In the following POM file, notice the dependency that references the custom Urber file.

<groupId>com.foo.reports</groupId>
<artifactId>jrurbersrt1.0</artifactId>
<version>1.0</version>
<scope>system</scope>
<systemPath>C:\Users\scottm\.m2\repository\com\foo\reports\jrurbersrt1.0\1.0\jrurbersrt1.0-1.0.jar</systemPath>
</dependency>

Make sure you change the system path to point to the location in your Maven repository where the Jasper Urber JAR file is located.

The following code 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>jasperHTL</groupId>
        <artifactId>jasperHTL</artifactId>
        <version>1.0-SNAPSHOT</version>
        <relativePath>../pom.xml</relativePath>
    </parent>
    <artifactId>jasperHTL.core</artifactId>
    <packaging>bundle</packaging>
    <name>jasperHTL - Core</name>
    <description>Core bundle for jasperHTL</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.jasper.community.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/jasperHTL/install to exist!!          -->
                            <!--    This is typically the case when ui.apps is deployed first                -->
                            <!--    Otherwise, create /apps/jasperHTL/install manually (CRXDE|Lite)  -->
                            <slingUrlSuffix>/apps/jasperHTL/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>com.foo.reports</groupId>
            <artifactId>jrurbersrt1.0</artifactId>
            <version>1.0</version>
            <scope>system</scope>
             <systemPath>C:\Users\scottm\.m2\repository\com\foo\reports\jrurbersrt1.0\1.0\jrurbersrt1.0-1.0.jar</systemPath>
        </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\jasperHTL.
  2. Run the following maven command: mvn -PautoInstallPackage install.
  3. The OSGi component can be found in the following folder: C:\AdobeCQ\jasperHTL\core\target. The file name of the OSGi component is jasperHTL.core-1.0-SNAPSHOT.jar.

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

Create the HTL Front End Component

When you use the Maven Archetype 10 archetype to create an AEM project, a default front end project is created, as shown in the following illustration.

CRXDE
Default files created by Adobe Maven 10 Archetype project

Change the file extension of helloworld from .html to .jsp. 

Note:

For information about the default files created by the Maven 10 Archetype project, see this community article: Creating your first AEM 6.2 Project using Adobe Maven Archetype 10.

Add JSP code

For the purpose of this article, add JSP code to the component located here:

/apps/myHTL62/components/content/helloworld

 

Add the following JSP code that invokes the  com.jasper.community.core.BuildReport that creates a custom report. 

<%@include file="/libs/foundation/global.jsp"%>
<h1><%= properties.get("title", currentPage.getTitle()) %></h1>
<%
  
com.jasper.community.core.BuildReport report = sling.getService(com.jasper.community.core.BuildReport.class);
String ff = report.BuildReport();
%>
  
<h2>Report Component</h2>
<h3>Report Details: <%=ff%></h3>

View the output of the HTL component

To access the component, enter the following URL: 

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

The following illustration shows the HTL component.

 

Client2
The HTL component created in this article

The AEM Service invokes the custom logic in the Jasper Urber OSGi that creates the report. The AEM service writes the report to the AEM DAM location /content/dam/reports, as shown in this illustration. 

 

DAM1
The Jasper Report located in the AEM DAM

See also

Congratulations, you have just created an AEM OSGi bundle that uses the uses the Jasper Reports API to dynamically create a PDF report. Please refer to the AEM community page for other articles that discuss how to build AEM services/applications.

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