package com.aem.community.core.servlets;
//import org.apache.felix.scr.annotations.Reference;
import org.apache.sling.api.SlingHttpServletRequest;
import org.apache.sling.api.SlingHttpServletResponse;
import org.apache.sling.api.resource.*;
import org.apache.sling.api.servlets.SlingAllMethodsServlet;
import org.apache.sling.commons.json.JSONArray;
import org.apache.sling.commons.json.JSONException;
import org.apache.sling.commons.json.JSONObject;
import org.osgi.framework.Constants;
import org.osgi.service.component.annotations.Component;
import org.osgi.service.component.annotations.Reference;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.jcr.RepositoryException;
import javax.jcr.Session;
import javax.servlet.Servlet;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import java.io.IOException;
import java.util.Iterator;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
// @SlingServlet(paths = "/bin/commentexcelreporting")
@Component(service= Servlet.class,
property={
Constants.SERVICE_DESCRIPTION + "=custom reporting servlet",
"sling.servlet.paths="+ "/bin/commentexcelreporting"
})
public class CommentReporting extends SlingAllMethodsServlet {
@Reference
ResourceResolverFactory resourceResolverFactory;
Logger logger = LoggerFactory.getLogger(CommentReporting.class);
//static int storecount=0;
int storecount=0;
@Override
public void doGet(final SlingHttpServletRequest request, final SlingHttpServletResponse response) throws ServletException, IOException {
//This is for admin session
ResourceResolver resourceResolver = null;
resourceResolver= request.getResourceResolver();
logger.info("Resolved user: " + resourceResolver.getUserID());
// this is for system user session............ creating session from resource resolver factory
// Map<String, Object> usermap = new HashMap<String, Object>();
// usermap.put(ResourceResolverFactory.SUBSERVICE, "customreporting");
// ResourceResolver resourceResolver = null;
// try {
// // resourceResolver = resourceResolverFactory.getResourceResolver(usermap);
// resourceResolver = resourceResolverFactory.getServiceResourceResolver(usermap);
// logger.info("Resolved user: " + resourceResolver.getUserID());
// } catch (LoginException e) {
// e.printStackTrace();
// }
String[] headerlist = {"Commenter Name / ID", "Commenter Title", "Commenter Email Address", " Comment Type", " Document Title / Version"};
//Uncomment below for hitting the servlet path directly and replace all
//String varWorkflowPathHardcoded = "http://localhost:4508/libs/fmdita/review/inlinereview.html?wId=/var/workflow/instances/server1/2019-10-21/ReviewDITAMAP_64&idx=0&filterData=%5B%5B0%5D%2C%5B0%5D%2C%5B0%5D%5D";
String varworkflowpathfromjs = request.getParameter("presenturl");
logger.info("this is value coming from js "+varworkflowpathfromjs);
if(varworkflowpathfromjs.contains("idx")) {
Session session = resourceResolver.adaptTo(Session.class);
JSONArray jsonArray = new JSONArray();
// int storecount = 0;
int storecount = this.storecount;
forParticularTopicsJson(varworkflowpathfromjs,resourceResolver,jsonArray, storecount,session);
//Apache poi started
Workbook workbook = new XSSFWorkbook();
// logger.info("after coming from method "+ CommentReporting.storecount);
logger.info("after coming from method "+this.storecount);
logger.info("withoutv this coming from method "+storecount);
// excelCreation(workbook,headerlist, CommentReporting.storecount,jsonArray);
excelCreation(workbook,headerlist,this.storecount,jsonArray);
//below code is for downloadable excel file on button click AJAX
responseConfig(response,workbook);
try {
session.save();
} catch (RepositoryException e) {
e.printStackTrace();
}
}//if url contains id
//else condition started for " url does not contain id" ---> this can happen when one topic only is there
// or if user is at parent page of map (havent selected any topic to edit)
else {
String commentInfopathRemoveWcmmode=null;
String commentInfopath=null;
Session session = resourceResolver.adaptTo(Session.class);
// String varworkflowpath = "/var/workflow/instances/server1/2019-10-23/ReviewDITAMAP_12";
//http://localhost:4508/libs/fmdita/review/inlinereview.html?wId=/var/workflow/instances/server1/2019-10-28/ReviewDITAMAP_11&wcmmode=disabled
boolean wcmmode = varworkflowpathfromjs.contains("wcmmode");
if(wcmmode) {
commentInfopathRemoveWcmmode = varworkflowpathfromjs.substring(varworkflowpathfromjs.indexOf("wId=") + 4, varworkflowpathfromjs.indexOf("&wcmmode"));
logger.info("path wich contains wcmmode,after substring the wcmmode from url"+commentInfopathRemoveWcmmode);
}
else {
commentInfopath = varworkflowpathfromjs.substring(varworkflowpathfromjs.indexOf("wId=") + 4);
logger.info("path which does not contain wcmmode,no need of substring the wcmmode from url"+commentInfopath);
}
Resource varwokflownode = resourceResolver.getResource(wcmmode?commentInfopathRemoveWcmmode:commentInfopath);
JSONArray jsonArray = new JSONArray();
Resource metaData = varwokflownode.getChild("metaData");
Resource events = metaData.getChild("events");
int eventsChildNodeCount = 0;
Iterator<Resource> eventsResourceIterator = events.listChildren();
int count = 0;
while (eventsResourceIterator.hasNext()) {
Resource eventChildResource = eventsResourceIterator.next();
logger.info("this is the node which needs to ftech" + eventChildResource.getName());
Resource respectiveTopicNode = events.getChild(eventChildResource.getName());
// int count = 0;
logger.info("0 1 2 3 topics nodesssss name " + eventChildResource.getName());
Iterator<Resource> resourceIterator = respectiveTopicNode.listChildren();
// while (resourceIterator.hasNext()) {
// Resource zero = events.getChild("0");
// int count = 0;
// Iterator<Resource> resourceIterator = zero.listChildren();
while (resourceIterator.hasNext()) {
JSONObject jsonObject = new JSONObject();
try {
Resource eventRes = resourceIterator.next();
ValueMap valueMap = eventRes.adaptTo(ValueMap.class);
String comment = valueMap.get("comment", String.class);
jsonObject.put("comment", comment);
String commentId = valueMap.get("commentId", String.class);
jsonObject.put("commentId", commentId);
String user = valueMap.get("user", String.class);
jsonObject.put("user", user);
String version = valueMap.get("version", String.class);
jsonObject.put("version", version);
} catch (JSONException e) {
e.printStackTrace();
}
jsonArray.put(jsonObject);
count++;
}//while loop ended
logger.info("count is " + count);
//response.getWriter().print("anything");
// response.getWriter().print(jsonArray);
}//parent while loop ended
//apache poi started
Workbook workbook = new XSSFWorkbook();
excelCreation(workbook,headerlist,count,jsonArray);
//below code is for downloadable excel file on button click AJAX
responseConfig(response,workbook);
// String reportName = "customisedCommentReport.xlsx";
// response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
// response.setHeader("Content-Disposition", "attachment; filename=" + reportName);
// ServletOutputStream outputStream = response.getOutputStream();
// workbook.write(outputStream);
// workbook.close();
try {
session.save();
} catch (RepositoryException e) {
e.printStackTrace();
}
}//else ended
}//doget ends
//different methods...
private void forParticularTopicsJson(String varworkflowpathfromjs, ResourceResolver resourceResolver, JSONArray jsonArray, int storecount, Session session) {
logger.info("id is contained in url or not" + varworkflowpathfromjs.contains("idx"));
int n = varworkflowpathfromjs.indexOf("idx");
String id = varworkflowpathfromjs.substring(n + 4, n + 5);
logger.info("trying to fetcch the id " + id);
// Session session = resourceResolver.adaptTo(Session.class);
//write the code to get this ---->varwokflownode==/var/workflow/instances/server0/2019-10-10_1/ReviewDITAMAP_37
String commentInfopath = varworkflowpathfromjs.substring(varworkflowpathfromjs.indexOf("wId=") + 4, varworkflowpathfromjs.indexOf("&idx"));
logger.info("this is actual path node of var" + commentInfopath);
Resource varwokflownode = resourceResolver.getResource(commentInfopath);
// JSONArray jsonArray = new JSONArray();
Resource metaData = varwokflownode.getChild("metaData");
Resource events = metaData.getChild("events");
int eventsChildNodeCount = 0;
Iterator<Resource> eventsResourceIterator = events.listChildren();
int count = 0;
while (eventsResourceIterator.hasNext()) {
Resource eventChildResource = eventsResourceIterator.next();
logger.info("this is the node which needs to ftech" + eventChildResource.getName());
if (eventChildResource.getName().equals(id)) {
logger.info("this is the node which needs to ftech" + eventChildResource.getName().equals(id));
// }
//}
Resource respectiveTopicNode = events.getChild(id);
// int count = 0;
logger.info("0 1 2 3 topics nodesssss name " + eventChildResource.getName());
Iterator<Resource> resourceIterator = respectiveTopicNode.listChildren();
while (resourceIterator.hasNext()) {
JSONObject jsonObject = new JSONObject();
try {
Resource eventRes = resourceIterator.next();
logger.info("0 1 2 3 topics nodesssss name " + eventRes.getName());
ValueMap valueMap = eventRes.adaptTo(ValueMap.class);
String comment = valueMap.get("comment", String.class);
logger.info("comment is this ---> " + comment);
jsonObject.put("comment", comment);
String commentId = valueMap.get("commentId", String.class);
jsonObject.put("commentId", commentId);
String user = valueMap.get("user", String.class);
jsonObject.put("user", user);
String version = valueMap.get("version", String.class);
jsonObject.put("version", version);
logger.info("jsonobject----> " + jsonObject);
} catch (JSONException e) {
e.printStackTrace();
}
jsonArray.put(jsonObject);
logger.info("jsonarray---> " + jsonArray);
count++;
}//while loop ended
logger.info("count is " + count);
this.storecount=count;
//below give actual number
logger.info("storecountcount is " +this.storecount);
}
}//while and if loop parent one ended
logger.info("storecountcount is " + storecount);
//return storecount;
}
private void responseConfig(SlingHttpServletResponse response, Workbook workbook) throws IOException {
String reportName = "customisedCommentReport.xlsx";
response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
response.setHeader("Content-Disposition", "attachment; filename=" + reportName);
ServletOutputStream outputStream = null;
try {
outputStream = response.getOutputStream();
} catch (IOException e) {
e.printStackTrace();
}
workbook.write(outputStream);
workbook.close();
}
private void excelCreation(Workbook workbook, String[] headerlist, int count, JSONArray jsonArray) {
// Workbook workbook = new XSSFWorkbook();
Sheet planetsheet = workbook.createSheet("commentreport");
Row headerrow = planetsheet.createRow(0);
for (int i = 0; i < headerlist.length; i++) {
Cell cell = headerrow.createCell(i);
cell.setCellValue(headerlist[i]);
}
for (int m = 0; m < count + 1; m++) {
Row otherRows = planetsheet.createRow(m + 1);
Cell cellOne = otherRows.createCell(0);
try {
cellOne.setCellValue(jsonArray.getJSONObject(m).get("comment").toString());
Cell cellTwo = otherRows.createCell(1);
cellTwo.setCellValue(jsonArray.getJSONObject(m).get("commentId").toString());
Cell cellThree = otherRows.createCell(2);
cellThree.setCellValue(jsonArray.getJSONObject(m).get("comment").toString());
Cell cellfourth = otherRows.createCell(3);
cellfourth.setCellValue(jsonArray.getJSONObject(m).get("user").toString());
Cell cellfifth = otherRows.createCell(4);
cellfifth.setCellValue(jsonArray.getJSONObject(m).get("version").toString());
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}//class ends