package com.viewer.servlets;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.locks.ReentrantLock;
import javax.servlet.ServletException;
import org.apache.commons.io.IOUtils;
import org.apache.felix.scr.annotations.Component;
import org.apache.felix.scr.annotations.Properties;
import org.apache.felix.scr.annotations.Property;
import org.apache.felix.scr.annotations.Reference;
import org.apache.felix.scr.annotations.Service;
import org.apache.sling.api.SlingHttpServletRequest;
import org.apache.sling.api.SlingHttpServletResponse;
import org.apache.sling.api.resource.LoginException;
import org.apache.sling.api.resource.Resource;
import org.apache.sling.api.resource.ResourceResolver;
import org.apache.sling.api.resource.ResourceResolverFactory;
import org.apache.sling.api.servlets.SlingAllMethodsServlet;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.day.cq.dam.api.Asset;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.groupdocs.viewer.converter.options.ConvertImageFileType;
import com.groupdocs.viewer.converter.options.FileDataOptions;
import com.groupdocs.viewer.converter.options.HtmlOptions;
import com.groupdocs.viewer.domain.FileData;
import com.groupdocs.viewer.domain.PageData;
import com.groupdocs.viewer.domain.containers.DocumentInfoContainer;
import com.groupdocs.viewer.domain.html.HtmlResource;
import com.groupdocs.viewer.domain.html.HtmlResourceType;
import com.groupdocs.viewer.domain.html.PageHtml;
import com.groupdocs.viewer.domain.options.DocumentInfoOptions;
import com.viewer.model.FileDataJsonSerializer;
import com.viewer.model.Utils;
import com.viewer.model.ViewDocumentParameters;
import com.viewer.model.ViewDocumentResponse;
import com.viewer.model.WatermarkPosition;
import com.viewer.model.helper.DotNetToJavaStringHelper;
import com.viewer.model.helper.ImageUrlHelper;
import com.viewer.model.helper.RefObject;
import com.viewer.utils.ViewerUtils;
//@WebServlet("/ViewDocument")
@Component(immediate = true, description = "Doc viewer servlet")
@Service(value = javax.servlet.Servlet.class)
@Properties(value = {
@Property(name = "sling.servlet.extensions", value = {"html", "json"}),
@Property(name = "sling.servlet.methods", value = {"GET", "POST"}),
@Property(name = "sling.servlet.paths", value = {"/services/ViewDocument"})
})
public class ViewDocument extends SlingAllMethodsServlet {
private static final long serialVersionUID = 1L;
private static final Logger LOG = LoggerFactory.getLogger(ViewDocument.class);
//private static String _locales = (System.getProperty("user.dir") + "\\src\\main\\webapp\\storage\\temp\\").replace("\\", "/");
final ReentrantLock lock = new ReentrantLock();
private final ConvertImageFileType _convertImageFileType = ConvertImageFileType.JPG;
public String _licensePath = "D:\\GroupDocs.Total.Java.lic";
List temp_cssList;
@Reference
private ResourceResolverFactory resolverFactory;
@Override
protected void doPost(SlingHttpServletRequest request, SlingHttpServletResponse response)
throws ServletException, IOException {
response.addHeader("Content-Type", "application/json");
ViewDocumentParameters params = new ObjectMapper().readValue(request.getInputStream(), ViewDocumentParameters.class);
ViewDocumentResponse result = new ViewDocumentResponse();
/*InputStream stream = this.getClass().getClassLoader()
.getResourceAsStream(params.getPath());
Path temp =Files.createTempFile("tmp","."+getFileExtension(params.getPath()));
Files.copy(stream, temp, StandardCopyOption.REPLACE_EXISTING);*/
ResourceResolver rr;
try {
rr = resolverFactory.getAdministrativeResourceResolver(null);
} catch (LoginException x) {
throw new ServletException(x);
}
Resource resource = rr.getResource("/content/dam/docviewerassets/"+params.getPath());
Asset asset = resource.adaptTo(Asset.class);
Path temp = null;
try {
temp = Files.createTempFile("tmp","."+getFileExtension(params.getPath()));
Files.copy(asset.getOriginal().getStream(), temp, StandardCopyOption.REPLACE_EXISTING);
} catch (Exception x) {
throw new ServletException(x);
}
FileData fileData = ViewerUtils.factoryFileData(temp.toAbsolutePath().toString());
LOG.error("Check pageCount"+fileData.getPageCount());
//FileData fileData = ViewerUtils.factoryFileData(asset.getOriginal().getStream());
DocumentInfoContainer docInfo = null;
try {
result.setDocumentDescription((new FileDataJsonSerializer(fileData, new FileDataOptions())).Serialize(false));
} catch (ParseException x) {
throw new ServletException(x);
}
if (params.getUseHtmlBasedEngine()) {
try {
//DocumentInfoOptions options = new DocumentInfoOptions();
//docInfo = ViewerUtils.getViewerHtmlHandler().getDocumentInfo(asset.getOriginal().getStream());
docInfo = ViewerUtils.getViewerHtmlHandler().getDocumentInfo(new DocumentInfoOptions(temp.toAbsolutePath().toString()));
LOG.error("Check2 documentType=="+docInfo.getDocumentType()+"docinfo" +docInfo.getName());
//Files.deleteIfExists(temp);
//stream.close();
} catch (Exception x) {
throw new ServletException(x);
}
result.setPageCss(new String[0]);
result.setLic(true);
result.setPdfDownloadUrl(GetPdfDownloadUrl(params));
result.setPdfPrintUrl(GetPdfPrintUrl(params));
result.setUrl(GetFileUrl(params));
result.setPath(params.getPath());
result.setName(params.getPath());
result.setDocType(docInfo.getDocumentType());
result.setFileType(docInfo.getFileType());
HtmlOptions htmlOptions = new HtmlOptions();
htmlOptions.setResourcesEmbedded(true);
htmlOptions.setHtmlResourcePrefix("/GetResourceForHtml?documentPath=" + params.getPath() + "&pageNumber={page-number}&resourceName=");
if (!DotNetToJavaStringHelper.isNullOrEmpty(params.getPreloadPagesCount().toString())
&& params.getPreloadPagesCount().intValue() > 0) {
htmlOptions.setPageNumber(1);
htmlOptions.setCountPagesToConvert(params.getPreloadPagesCount().intValue());
} else {
htmlOptions.setPageNumber(1);
htmlOptions.setCountPagesToConvert(1);
}
String[] cssList = null;
RefObject<ArrayList> tempRef_cssList = new RefObject<ArrayList>(cssList);
//List htmlPages = GetHtmlPages(params.getPath(), htmlOptions);
//-------------
/* InputStream streamin = this.getClass().getClassLoader()
.getResourceAsStream("TestViewer.pdf");*/
List htmlPages = GetHtmlPages(temp.toAbsolutePath().toString(),params.getPath(), htmlOptions);
//streamin.close();
//-------------
cssList = tempRef_cssList.argValue;
ArrayList pagesContent = new ArrayList();
for (PageHtml page : htmlPages) {
pagesContent.add(page.getHtmlContent());
}
String[] htmlContent = pagesContent.toArray(new String[0]);
LOG.error("Check3 htmlContent=="+htmlContent);
result.setPageHtml(htmlContent);
result.setPageCss(new String[]{String.join(" ", temp_cssList)});
LOG.error("Check5 setPageHtml=="+result.getPageHtml().length);
for (int i = 0; i < result.getPageHtml().length; i++) {
String html = result.getPageHtml()[i];
LOG.error("Check6 result.getPageHtml()[i]=="+result.getPageHtml()[i]);
int indexOfScript = html.indexOf("script");
if (indexOfScript > 0) {
result.getPageHtml()[i] = html.substring(0, indexOfScript);
LOG.error("Check7 html.substring(0, indexOfScript)=="+html.substring(0, indexOfScript));
}
}
} else {
try {
docInfo = ViewerUtils.getViewerImageHandler().getDocumentInfo(new DocumentInfoOptions(params.getPath()));
} catch (Exception x) {
throw new ServletException(x);
}
int maxWidth = 0;
int maxHeight = 0;
for (PageData pageData : docInfo.getPages()) {
if (pageData.getHeight() > maxHeight) {
maxHeight = pageData.getHeight();
maxWidth = pageData.getWidth();
}
}
/*fileData.setDateCreated(new Date());
fileData.setDateModified(docInfo.getLastModificationDate());
fileData.setPageCount(docInfo.getPages().size());
fileData.setPages(docInfo.getPages());
fileData.setMaxWidth(maxWidth);
fileData.setMaxHeight(maxHeight);*/
result.setPageCss(new String[0]);
result.setLic(true);
result.setPdfDownloadUrl(GetPdfDownloadUrl(params));
result.setPdfPrintUrl(GetPdfPrintUrl(params));
result.setUrl(GetFileUrl(params.getPath(), true, false, params.getFileDisplayName(),
params.getWatermarkText(), params.getWatermarkColor(), params.getWatermarkPostion(),
params.getWatermarkWidth(), params.getIgnoreDocumentAbsence(), params.getUseHtmlBasedEngine(),
params.getSupportPageRotation()));
result.setPath(params.getPath());
result.setName(params.getPath());
result.setDocType(docInfo.getDocumentType());
result.setFileType(docInfo.getFileType());
int[] pageNumbers = new int[docInfo.getPages().size()];
int count = 0;
for (PageData page : docInfo.getPages()) {
pageNumbers[count] = page.getNumber();
count++;
}
String applicationHost = request.getScheme() + "://" + request.getServerName() + ":"
+ request.getServerPort();
String[] imageUrls = ImageUrlHelper.GetImageUrls(applicationHost, pageNumbers, params);
LOG.error("Check4 imageUrls=="+imageUrls);
result.setImageUrls(imageUrls);
}
new ObjectMapper().writeValue(response.getOutputStream(), result);
}
private String getFileNameWithoutExtension(String fileName) {
try {
return fileName.replaceFirst("[.][^.]+$", "");
} catch (Exception exp) {
System.out.println("Exception: " + exp.getMessage());
exp.printStackTrace();
return null;
}
}
private String getFileExtension(String name) {
try {
return name.substring(name.lastIndexOf(".") + 1);
} catch (Exception e) {
return "";
}
}
////////////////////////////////////////////////////////////////////////////////////////////////////
public final String GetFileUrl(String path, boolean getPdf, boolean isPrintable, String fileDisplayName,
String watermarkText, Integer watermarkColor, WatermarkPosition watermarkPosition, Float watermarkWidth,
boolean ignoreDocumentAbsence, boolean useHtmlBasedEngine, boolean supportPageRotation) {
Map queryString = new LinkedHashMap();
String myUrl = "path=" + path;
queryString.put("path", path);
if (!isPrintable) {
queryString.put("getPdf", String.valueOf(getPdf).toLowerCase());
myUrl = myUrl + "&getPdf=" + String.valueOf(getPdf).toLowerCase();
if (fileDisplayName != null) {
queryString.put("displayName", fileDisplayName);
}
}
if (watermarkText != null) {
queryString.put("watermarkText", watermarkText);
queryString.put("watermarkColor", watermarkColor.toString());
if (watermarkPosition != null) {
queryString.put("watermarkPosition", watermarkPosition.toString());
}
if (watermarkWidth != null) {
queryString.put("watermarkWidth", (new Float((float) watermarkWidth)).toString());
}
}
if (ignoreDocumentAbsence) {
queryString.put("ignoreDocumentAbsence", String.valueOf(ignoreDocumentAbsence).toLowerCase());
}
queryString.put("useHtmlBasedEngine", String.valueOf(useHtmlBasedEngine).toLowerCase());
myUrl = myUrl + "&useHtmlBasedEngine=" + String.valueOf(useHtmlBasedEngine).toLowerCase();
queryString.put("supportPageRotation", String.valueOf(supportPageRotation).toLowerCase());
myUrl = myUrl + "&supportPageRotation=" + String.valueOf(supportPageRotation).toLowerCase();
String handlerName = isPrintable ? "GetPdfWithPrintDialog" : "GetFile";
String baseUrl = "http://localhost:4502/services/" + handlerName + "?" + myUrl;
String fileUrl = baseUrl + handlerName + queryString;
return baseUrl;
}
public String GetPdfDownloadUrl(ViewDocumentParameters parameters) {
return GetFileUrl(parameters.getPath(), true, false, parameters.getFileDisplayName(),
parameters.getWatermarkText(), parameters.getWatermarkColor(), parameters.getWatermarkPostion(),
parameters.getWatermarkWidth(), parameters.getIgnoreDocumentAbsence(),
parameters.getUseHtmlBasedEngine(), parameters.getSupportPageRotation());
}
private String GetPdfPrintUrl(ViewDocumentParameters request) {
return GetFileUrl(request.getPath(), true, true, request.getFileDisplayName(), request.getWatermarkText(),
request.getWatermarkColor(), request.getWatermarkPostion(), request.getWatermarkWidth(),
request.getIgnoreDocumentAbsence(), request.getUseHtmlBasedEngine(), request.getSupportPageRotation());
}
private String GetFileUrl(ViewDocumentParameters request) {
return GetFileUrl(request.getPath(), false, false, request.getFileDisplayName(), null, null, null, null, false,
false, false);
}
private List GetHtmlPages(String absolutePath, String filePath,HtmlOptions htmlOptions) throws ServletException, IOException {
List htmlPages = null;
try {
ResourceResolver rr = resolverFactory.getAdministrativeResourceResolver(null);
Resource resource = rr.getResource("/content/dam/docviewerassets/"+filePath);
Asset asset = resource.adaptTo(Asset.class);
//String url="http://localhost:4502/content/dam/docviewerassets/TestViewer.pdf";
//URI uri = new URI(url);
htmlPages = ViewerUtils.getViewerHtmlHandler().getPages(asset.getOriginal().getStream(), htmlOptions);
/*FileInputStream stream = new FileInputStream(absolutePath);
htmlPages = ViewerUtils.getViewerHtmlHandler().getPages(stream, htmlOptions);
stream.close();*/
} catch (Exception x) {
throw new ServletException(x);
}
temp_cssList = new ArrayList();
for (PageHtml page : htmlPages) {
int indexOfBodyOpenTag = page.getHtmlContent().indexOf("");
if (indexOfBodyOpenTag > 0) {
page.setHtmlContent(page.getHtmlContent().substring(indexOfBodyOpenTag + "".length()));
}
int indexOfBodyCloseTag = page.getHtmlContent().indexOf("");
if (indexOfBodyCloseTag > 0) {
page.setHtmlContent(page.getHtmlContent().substring(0, indexOfBodyCloseTag));
}
/////////////////////////
List test = page.getHtmlResources();
for (HtmlResource resource : page.getHtmlResources()) {
if (resource.getResourceType() == HtmlResourceType.Style) {
InputStream cssStream = null;
try {
cssStream = ViewerUtils.getViewerHtmlHandler().getResource(filePath, resource);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String text = IOUtils.toString(cssStream, "UTF-8");
boolean needResave = false;
if (text.indexOf("url(\"") >= 0 && text.indexOf("url(\"/GetResourceForHtml?documentPath=") < 0) {
needResave = true;
text = text.replace("url(\"", "url(\"/GetResourceForHtml?documentPath=" + filePath
+ "&pageNumber=" + resource.getDocumentPageNumber() + "&resourceName=");
}
if (text.indexOf("url('") >= 0 && text.indexOf("url('/GetResourceForHtml?documentPath=") < 0) {
needResave = true;
text = text.replace("url('", String.format("url(\'/GetResourceForHtml?documentPath=" + filePath
+ "&pageNumber=" + resource.getDocumentPageNumber() + "&resourceName="));
}
temp_cssList.add(text);
if (needResave) {
String fullPath = ViewerUtils.TEMP_PATH + filePath + "/" + "html" + "/" + "resources" + "/" + "page"
+ page.getPageNumber() + "/" + resource.getResourceName();
File file = new File(fullPath);
// if file doesnt exists, then create it
if (!file.exists()) {
file.getParentFile().mkdirs();
file.createNewFile();
}
FileWriter fw = new FileWriter(file.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
bw.write(text);
bw.close();
}
}
/////////////////////////
}
ArrayList cssClasses = Utils.GetCssClasses(page.getHtmlContent());
for (String cssClass : cssClasses) {
String newCssClass = "page-" + page.getPageNumber() + "-" + cssClass;
page.setHtmlContent(page.getHtmlContent().replace(cssClass, newCssClass));
for (int i = 0; i < temp_cssList.size(); i++) {
temp_cssList.set(i, temp_cssList.get(i).replace(cssClass, newCssClass));
}
}
}
return htmlPages;
}
/*private List GetHtmlPages(String filePath, HtmlOptions htmlOptions) throws ServletException, IOException {
List htmlPages = null;
try {
htmlPages = ViewerUtils.getViewerHtmlHandler().getPages(filePath, htmlOptions);
} catch (Exception x) {
throw new ServletException(x);
}
temp_cssList = new ArrayList();
for (PageHtml page : htmlPages) {
int indexOfBodyOpenTag = page.getHtmlContent().indexOf("");
if (indexOfBodyOpenTag > 0) {
page.setHtmlContent(page.getHtmlContent().substring(indexOfBodyOpenTag + "".length()));
}
int indexOfBodyCloseTag = page.getHtmlContent().indexOf("");
if (indexOfBodyCloseTag > 0) {
page.setHtmlContent(page.getHtmlContent().substring(0, indexOfBodyCloseTag));
}
/////////////////////////
List test = page.getHtmlResources();
for (HtmlResource resource : page.getHtmlResources()) {
if (resource.getResourceType() == HtmlResourceType.Style) {
InputStream cssStream = ViewerUtils.getViewerHtmlHandler().getResource(filePath, resource);
String text = IOUtils.toString(cssStream, "UTF-8");
boolean needResave = false;
if (text.indexOf("url(\"") >= 0 && text.indexOf("url(\"/GetResourceForHtml?documentPath=") < 0) {
needResave = true;
text = text.replace("url(\"", "url(\"/GetResourceForHtml?documentPath=" + filePath
+ "&pageNumber=" + resource.getDocumentPageNumber() + "&resourceName=");
}
if (text.indexOf("url('") >= 0 && text.indexOf("url('/GetResourceForHtml?documentPath=") < 0) {
needResave = true;
text = text.replace("url('", String.format("url(\'/GetResourceForHtml?documentPath=" + filePath
+ "&pageNumber=" + resource.getDocumentPageNumber() + "&resourceName="));
}
temp_cssList.add(text);
if (needResave) {
String fullPath = ViewerUtils.TEMP_PATH + filePath + "/" + "html" + "/" + "resources" + "/" + "page"
+ page.getPageNumber() + "/" + resource.getResourceName();
File file = new File(fullPath);
// if file doesnt exists, then create it
if (!file.exists()) {
file.getParentFile().mkdirs();
file.createNewFile();
}
FileWriter fw = new FileWriter(file.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
bw.write(text);
bw.close();
}
}
/////////////////////////
}
ArrayList cssClasses = Utils.GetCssClasses(page.getHtmlContent());
for (String cssClass : cssClasses) {
String newCssClass = "page-" + page.getPageNumber() + "-" + cssClass;
page.setHtmlContent(page.getHtmlContent().replace(cssClass, newCssClass));
for (int i = 0; i < temp_cssList.size(); i++) {
temp_cssList.set(i, temp_cssList.get(i).replace(cssClass, newCssClass));
}
}
}
return htmlPages;
}*/
}