Solved
The email function not working on DEV environment
Hi
I am trying to setup an email function servlet on AEM, it grabs nodes info in AEM and save them is a excel file. The servlet works fine on local, but somehow it's not working on live environment, here's my code:
package com.fidelity.cms.aem.reports;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.TreeMap;
import javax.jcr.Node;
import javax.jcr.RepositoryException;
import javax.jcr.Session;
import javax.jcr.query.Query;
import javax.jcr.query.QueryManager;
import javax.jcr.query.QueryResult;
import javax.jcr.query.RowIterator;
import javax.mail.util.ByteArrayDataSource;
import javax.servlet.Servlet;
import org.apache.commons.mail.HtmlEmail;
import org.apache.felix.scr.annotations.Activate;
import org.apache.felix.scr.annotations.Property;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.sling.api.SlingHttpServletRequest;
import org.apache.sling.api.SlingHttpServletResponse;
import org.apache.sling.api.resource.Resource;
import org.apache.sling.api.resource.ResourceResolver;
import org.apache.sling.api.resource.ValueMap;
import org.apache.sling.api.servlets.SlingAllMethodsServlet;
import org.apache.sling.commons.osgi.PropertiesUtil;
import org.osgi.service.component.ComponentContext;
import org.osgi.service.component.annotations.Component;
import org.osgi.service.component.annotations.Reference;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.day.cq.mailer.MessageGateway;
import com.day.cq.mailer.MessageGatewayService;
import com.fidelity.cms.aem.api.ValidationService;
/**
*
*/
@Component(service = Servlet.class,
property = {
"sling.servlet.methods=" + "GET",
"sling.servlet.paths =" + "/bin/test/content-report",
"sling.servlet.paths =" + "/bin/test/email-content-report"})
public class ContentReportServlet extends SlingAllMethodsServlet {
private static final long serialVersionUID = 3207272768197646044L;
private final Logger log = LoggerFactory.getLogger(this.getClass());
MessageGatewayService messageGatewayService;
@Reference
ValidationService validationService;
public String emailList;
Set<String> recipients = new HashSet<>();
protected void doGet(SlingHttpServletRequest request, SlingHttpServletResponse response) {
try {
String queryString = "SELECT [jcr:path] FROM [cq:Page] AS s WHERE ISDESCENDANTNODE([/content])";
ResourceResolver resourceResolver = request.getResourceResolver();
String URI = validationService.getRequestURI(request);
Session session = resourceResolver.adaptTo(Session.class);
QueryManager queryManager = session.getWorkspace().getQueryManager();
Query query = queryManager.createQuery(queryString, Query.JCR_SQL2);
QueryResult queryResult = query.execute();
RowIterator rowIterator = queryResult.getRows();
Map < String, String > pathMap = new TreeMap < > ();
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
//testing
recipients.add("myemail@email.ca");
while (rowIterator.hasNext()) {
String path = rowIterator.nextRow().getPath();
Resource jcrContent = resourceResolver.getResource(path + "/jcr:content");
String title = " ";
String expiryString = " ";
String compID = " ";
String author = " ";
String type = " ";
String published = " ";
String URL = " ";
long linkedPage = 0;
String isExpired = " ";
String autoUnpublish = " ";
Node parentNode = session.getNode(path);
linkedPage = parentNode.getNodes().getSize() - 1;
ValueMap properties = jcrContent.getValueMap();
Date expiryDate = properties.get("expiry", Date.class);
expiryString = (expiryDate != null) ? formatter.format(expiryDate) : "No Expiry Date";
autoUnpublish = properties.get("autoUnpublishAtExpiry", String.class);
if (jcrContent != null) {
if(expiryDate == null) {
isExpired = "No Expiry Date";
}else {
Date currentDate = new Date();
long daysDifference = (expiryDate.getTime()-currentDate.getTime())/(24*60*60*1000);
if(daysDifference<0) {
isExpired = "Expired";
}else if(daysDifference<=30){
isExpired = "Less than 30 days to expiry";
}else if(daysDifference<=60) {
isExpired = "Less than 60 days to expiry";
}else {
isExpired = "More than 60 days to expiry";
}
}
title = properties.get("jcr:title", String.class);
compID = properties.get("contentWorkdayId", String.class);
author = properties.get("expiryEmail", String.class);
type = (path.contains("/dam/") ? "asset" : "page");
if(properties.containsKey("autoUnpublishAtExpiry") && properties.get("autoUnpublishAtExpiry", Boolean.class) && isExpired.equalsIgnoreCase("Expired")) {
published="Expired by system";
}else {
published = properties.get("cq:lastReplicationAction", String.class);
}
String jcrProperties = expiryString + "--div--" +
type + "--div--" +
title + "--div--" +
compID + "--div--" +
author + "--div--" +
published + "--div--" +
URL + "--div--" +
linkedPage + "--div--" +
isExpired + "--div--" +
autoUnpublish;
pathMap.put(path, jcrProperties);
}
}
writeDataToFile("ContentReport", pathMap, response, recipients, URI);
// response.getWriter().println("Content Report generated");
} catch (RepositoryException e) {
log.error("Error occurred while generating report: {}", e.getMessage(), e);
}
}
private void writeDataToFile(String reportName, Map < String, String > data, SlingHttpServletResponse response, Set<String> recipients, String URI) {
XSSFWorkbook workbook = new XSSFWorkbook();
XSSFSheet sheet = workbook.createSheet("Expiry Report");
org.apache.poi.ss.usermodel.Row row = sheet.createRow(0);
Cell pathHeader = row.createCell(0);
pathHeader.setCellValue("Content path");
Cell expiryHeader = row.createCell(1);
expiryHeader.setCellValue("Expiry Date");
Cell typeHeader = row.createCell(2);
typeHeader.setCellValue("Content Type");
Cell titleHeader = row.createCell(3);
titleHeader.setCellValue("Content Title");
Cell compIDHeader = row.createCell(4);
compIDHeader.setCellValue("Compliance ID");
Cell authorHeader = row.createCell(5);
authorHeader.setCellValue("Content Owner");
Cell publishHeader = row.createCell(6);
publishHeader.setCellValue("Published");
Cell siteURL = row.createCell(7);
siteURL.setCellValue("URL");
Cell totalLinkedPage = row.createCell(8);
totalLinkedPage.setCellValue("Total Linked Pages");
Cell isExpired = row.createCell(9);
isExpired.setCellValue("Is expired");
Cell autoUnpublish = row.createCell(10);
autoUnpublish.setCellValue("Auto Unpublish Pages");
int rowNum = 1;
List<Map.Entry<String, String>> sortedData = new ArrayList<>(data.entrySet());
sortedData.sort((entry1, entry2)->{
String owner1 = entry1.getValue().split("--div--")[4];
String owner2 = entry2.getValue().split("--div--")[4];
if(owner1 == null || "null".equals(owner1)) {
return(owner2 == null || "null".equals(owner2)) ? 0:1;
}else if (owner2 == null || "null".equals(owner2)) {
return -1;
}
int ownerComparsion = owner1.compareTo(owner2);
if(ownerComparsion == 0) {
String expiry1 = entry1.getValue().split("--div--")[0];
String expiry2 = entry2.getValue().split("--div--")[0];
LocalDate date1 = "No Expiry Date".equals(expiry1)? LocalDate.MAX:LocalDate.parse(expiry1);
LocalDate date2 = "No Expiry Date".equals(expiry2)? LocalDate.MAX:LocalDate.parse(expiry2);
return date1.compareTo(date2);
}
return ownerComparsion;
}
);
String currentOwner = null;
for(Map.Entry<String, String> entry: sortedData) {
String key = entry.getKey();
String value = entry.getValue();
String owner = value.split("--div--")[4];
if(!Objects.equals(owner, currentOwner)) {
currentOwner = owner;
}
row = sheet.createRow(rowNum++);
Cell pagePath = row.createCell(0);
pagePath.setCellValue(key);
Cell expiry = row.createCell(1);
expiry.setCellValue(value.split("--div--")[0]);
Cell type = row.createCell(2);
type.setCellValue(value.split("--div--")[1]);
Cell title = row.createCell(3);
title.setCellValue(value.split("--div--")[2]);
Cell compID = row.createCell(4);
compID.setCellValue(value.split("--div--")[3]);
Cell author = row.createCell(5);
author.setCellValue(value.split("--div--")[4]);
Cell published = row.createCell(6);
published.setCellValue(value.split("--div--")[5]);
Cell url = row.createCell(7);
url.setCellValue(value.split("--div--")[6]);
Cell linkedPage = row.createCell(8);
linkedPage.setCellValue(value.split("--div--")[7]);
Cell expired = row.createCell(9);
expired.setCellValue(value.split("--div--")[8]);
Cell autoPublishPage = row.createCell(10);
autoPublishPage.setCellValue(value.split("--div--")[9]);
}
try {
if(URI.startsWith("/bin/test/content-report")) {
response.setContentType("application/ms-excel");
response.setHeader("Content-Disposition", "attachment; filename=" + reportName + ".xlsx");
OutputStream out = response.getOutputStream();
workbook.write(out);
out.flush();
out.close();
workbook.close();
}else if (URI.startsWith("/bin/test/email-content-report")){
sendingEmail(workbook, recipients);
}
} catch (Exception e) {
log.error("Error occurred while generating excel file: {}", e.getMessage(), e);
}
}
private void sendingEmail (XSSFWorkbook workbook, Set<String> recipients){
try {
log.info("sending email function started");
ByteArrayOutputStream byteStream = new ByteArrayOutputStream();
workbook.write(byteStream);
MessageGateway<HtmlEmail> messageGateway = messageGatewayService.getGateway(HtmlEmail.class);
if(messageGateway != null) {
HtmlEmail email = new HtmlEmail();
email.setCharset("utf-8");
for(String recipient : recipients) {
email.addTo(recipient);
}
log.info("recipient added");
email.setFrom("noreply@test.ca");
email.setSubject("DEV Testing");
email.setHostName("hostname");
email.setSmtpPort(portNumber);
email.setSSLOnConnect(false);
log.info("email property added");
email.setHtmlMsg("<html><body><p>Hi all,</p></body></html>");
ByteArrayDataSource dataSource = new ByteArrayDataSource(byteStream.toByteArray(), "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
email.attach(dataSource, "filename.xlsx", "ContentReport", HtmlEmail.ATTACHMENTS);
log.info("email config added");
messageGateway.send(email);
log.info("email sent");
byteStream.close();
}
} catch (Exception e) {
log.error("Error occurred while sending report by email: {}", e.getMessage(), e);
}
}
}
This servlet has two functions,
hit
/bin/test/content-report will download the report directly
hit
/bin/fidelity/email-content-report will attach the report in the email and send it out.
I can't find any error message in the log the and only "sending email function started" message displayed.
I can't find any error message in the log the and only "sending email function started" message displayed.
Please give me some advises.
Thank you