Upload New File

parent 35d191db
package ibase.webitm.utility;
import java.awt.Color;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.image.BufferedImage;
import java.awt.image.DataBufferByte;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.rmi.RemoteException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.TimeZone;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import ibase.ejb.CommonDBAccessEJB;
import ibase.utility.BaseLogger;
import ibase.utility.UserInfoBean;
import ibase.webitm.ejb.AuditTrailExtEJB;
import ibase.webitm.ejb.DBAccessEJB;
import ibase.webitm.ejb.DocumentHandlerEJB;
import ibase.webitm.ejb.DocumentHandlerWrapperEJB;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.rendering.ImageType;
import org.apache.pdfbox.rendering.PDFRenderer;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.jcodec.api.FrameGrab;
import org.jcodec.api.JCodecException;
import org.jcodec.common.DemuxerTrack;
import org.jcodec.common.FileChannelWrapper;
import org.jcodec.common.NIOUtils;
import org.jcodec.common.model.ColorSpace;
import org.jcodec.common.model.Picture;
import org.jcodec.containers.mp4.demuxer.MP4Demuxer;
import org.jcodec.scale.ColorUtil;
import org.jcodec.scale.Transform;
import org.json.JSONException;
import org.json.JSONObject;
import com.itextpdf.text.pdf.PdfReader;
import com.reader.DocumentMetaDataReader;
import ibase.utility.CommonConstants;
import ibase.utility.E12GenericUtility;
public class DoumentHandlerUtility extends RestAPIServiceUtility {
private UserInfoBean userInfo = null;
private static String dirName = null;
//change the method name
public byte[] getAttachConfigData(String objName, String refser, String refId, String checkObjName, HttpServletRequest request,String tokenIDfromHeader)
{
BaseLogger.log( "3", null, null, "Insidet the getAttachConfigData() :" );
String returnData = null;
RestAPIServiceUtility utility = new RestAPIServiceUtility();
if (userInfo == null) {
APIUtility apiUtility = new APIUtility();
userInfo = apiUtility.createUserInfoFromJWTToken(tokenIDfromHeader);
BaseLogger.log( "3", null, null, "USER_INFO created from TOKEN: [" + userInfo + "]" );
}
BaseLogger.log( "3", null, null, "objName :: : ["+ objName +"]" );
try {
if (!"".equals(utility.checkNull(objName))) {
DocumentHandlerWrapperEJB docWrapperHandler = new DocumentHandlerWrapperEJB();
docWrapperHandler.setUserInfo(userInfo);
returnData = docWrapperHandler.getAttachmentsMetaData(objName, refId, userInfo, checkObjName);
BaseLogger.log( "3", null, null, "returnData :: : ["+ returnData +"]" );
} else {
JSONObject jsonObject = new JSONObject();
jsonObject.put("EXCEPTION", "ObjName is invalid [" + objName + "].");
returnData = jsonObject.toString();
}
} catch (Exception ex) {
BaseLogger.log("3", userInfo, null, "Exception in DocumentHandlerServlet :: handleDocument() : " + ex);
JSONObject jsonObject = new JSONObject();
try {
jsonObject.put("EXCEPTION", ex);
} catch (JSONException e) {
e.printStackTrace();
}
returnData = jsonObject.toString();
}
return returnData.getBytes();
}
//for getFileConfigurationData
public String getFileConfigurationData(String objName,HttpServletRequest request,String tokenIDfromHeader) {
String returnData = null;
if (userInfo == null) {
APIUtility apiUtility = new APIUtility();
userInfo = apiUtility.createUserInfoFromJWTToken(tokenIDfromHeader);
BaseLogger.log( "3", null, null, "USER_INFO created from TOKEN: [" + userInfo + "]" );
}
try {
if (!"".equals(checkNull(objName))) {
DocumentHandlerWrapperEJB docWrapperHandler = new DocumentHandlerWrapperEJB();
docWrapperHandler.setUserInfo(userInfo);
returnData = docWrapperHandler.getFileConfigurationsMetadata(objName, userInfo.getTransDB());
} else {
BaseLogger.log("3", userInfo, null, "DocumentHandlerServlet :: handleDocument() : Invalid objName[" + objName + "]");
JSONObject jsonObject = new JSONObject();
jsonObject.put("EXCEPTION", "ObjName is invalid [" + objName + "].");
returnData = jsonObject.toString();
}
} catch (Exception ex) {
BaseLogger.log("3", userInfo, null, "Exception in DocumentHandlerServlet :: handleDocument() : " + ex);
JSONObject jsonObject = new JSONObject();
try {
jsonObject.put("EXCEPTION", ex.toString());
} catch (JSONException e) {
e.printStackTrace();
}
returnData = jsonObject.toString();
}
return returnData;
}
public String getUploadDocument(boolean captureImage, boolean imgExist, String fileName, String refSer, String refId, String objName, String documentType, String fileType, String docLinkOpt, String fileMetadata, String docMetaData, String refDescr, String expDate, int cacheOpt, HttpServletRequest request, String tokenIDfromHeader) {
String uploadedFilePath = request.getParameter("UPLOADED_FILE_PATH");
String croppedImg = checkNull(request.getParameter("CROPPED_IMAGE"));
String croppedImgName = checkNull(request.getParameter("CROPPED_IMAGE_NAME"));
int rotateAngle = checkNull(request.getParameter("ROTATE_ANGLE")).length() > 0 ? Integer.parseInt(request.getParameter("ROTATE_ANGLE")) : 0;
BaseLogger.log("3", userInfo, null, " ************* croppedImg - [" + croppedImg + "] : croppedImgName - [" + croppedImgName + "]");
String userId = "";
UserInfoBean userInfo = null;
DBAccessEJB dbAccess = new DBAccessEJB();
DocumentHandlerEJB docHandler = null;
docHandler = new DocumentHandlerEJB();
if (userInfo == null) {
APIUtility apiUtility = new APIUtility();
userInfo = apiUtility.createUserInfoFromJWTToken(tokenIDfromHeader);
}
if (fileName.length() == 0) {
fileName = userId + ".png";
}
dirName = ( new File( CommonConstants.JBOSSHOME ) ) + File.separator + "dump";
BaseLogger.log("3", userInfo, null, "***** documentHandler servlet fileName[" + fileName + "]");
String filePath = dirName + File.separator + fileName;
BaseLogger.log("3", userInfo, null, " New filePath is :: [" + filePath + "]");
if (uploadedFilePath != null && uploadedFilePath.length() > 0) {
filePath = uploadedFilePath;
}
if ("true".equalsIgnoreCase(croppedImg)) {
filePath = CommonConstants.APPLICATION_CONTEXT + File.separator + "dump" + File.separator + "croppedImg" + File.separator + fileName;
}
BaseLogger.log("3", userInfo, null, "fileName - [" + fileName + "] : filePath - [" + filePath + "]");
BaseLogger.log("3", userInfo, null, "CommonConstants.APPLICATION_CONTEXT value :--> [" + CommonConstants.APPLICATION_CONTEXT + "]");
if (rotateAngle > 0 && "false".equalsIgnoreCase(croppedImg)) {
rotateImage(fileName, filePath, rotateAngle);
}
String retStr = null;
try {
retStr = addDocument(request, filePath, refSer, docHandler, userInfo);
if (checkNull(objName).length() == 0) {
String condition = " REF_SER = '" + refSer + "' ";
String tranWindow = dbAccess.getDBColumnValue("TRANSETUP", "TRAN_WINDOW", condition, userInfo.getTransDB());
if (checkNull(tranWindow).length() > 0) {
objName = tranWindow.replace("w_", "");
}
}
String auditStaus = "Error";
if (retStr != null && retStr.indexOf("<Document>") != -1) {
auditStaus = "Success";
if ("true".equalsIgnoreCase(croppedImg)) {
try {
File file = new File(filePath);
if (file.delete()) {
BaseLogger.log("3", userInfo, null, file.getName() + " is deleted!");
} else {
BaseLogger.log("3", userInfo, null, "Delete operation is failed.");
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
String chgTerm = userInfo.getRemoteHostName();
if (chgTerm != null && chgTerm.length() > 15) {
chgTerm = chgTerm.substring(0, 15);
} else if (chgTerm == null || chgTerm.length() == 0) {
chgTerm = userInfo.getRemoteHost();
}
AuditTrailExtEJB auditTrailExt = new AuditTrailExtEJB();
String auditTranId = auditTrailExt.saveActionPerformedInAudit(objName, refId, "UPLOAD_ATTACHMENT", "UPLOAD_ATTACHMENT", userInfo.getLoginCode(), chgTerm, userInfo);
auditTrailExt.updateAuditResponse(auditTranId, auditStaus, retStr, userInfo);
byte[] byteArray = retStr.getBytes();
removeTempFile((dirName + File.separator + fileName));
} catch (Exception e) {
// Handle any exceptions that occur during the document addition process or audit trail update
e.printStackTrace(); // Or log the exception
}
return retStr;
}
private void rotateImage( String imgName, String filePath, int rotateAngle )
{
try
{
if ( rotateAngle > 0 )
{
BufferedImage originalImage = ImageIO.read( new File( filePath ) );
BaseLogger.log("3", null, null,"Original image dimension: "+originalImage.getWidth()+" x "+originalImage.getHeight());
int type = originalImage.getType() == 0 ? BufferedImage.TYPE_INT_ARGB : originalImage.getType();
int imgWidth = originalImage.getWidth();
int imgHeight = originalImage.getHeight();
BufferedImage rotateImage = new BufferedImage( imgWidth, imgHeight, type );
Graphics2D g = rotateImage.createGraphics();
g.rotate( Math.toRadians(rotateAngle), rotateImage.getWidth() / 2, rotateImage.getHeight() / 2 );
g.drawImage( originalImage, 0, 0, imgWidth, imgHeight, null );
g.dispose();
BaseLogger.log("3", null, null,"Cropped image dimension: "+rotateImage.getWidth()+" x "+rotateImage.getHeight());
if ( E12GenericUtility.checkNull(imgName).length() > 0 )
{
File outputfile = new File( filePath );
ImageIO.write( rotateImage, "jpg", outputfile );
BaseLogger.log("3", null, null,"Image rotated successfully: "+outputfile.getPath());
}
else
{
BaseLogger.log("3", null, null,"Image Name is empty.");
}
}
}
catch (Exception e)
{
e.printStackTrace();
}
}
private void removeTempFile( String filePath )
{
try
{
File file = new File(filePath);
if ( file.exists() )
{
if( file.delete() )
{
BaseLogger.log( "3", null, null, "File deleted successfully" );
}
else
{
BaseLogger.log( "3", null, null, "Failed to delete the file" );
}
}
else
{
BaseLogger.log( "3", null, null, "file not exist in temp location" );
}
}
catch (Exception e)
{
e.printStackTrace();
BaseLogger.log( "0", null, null, "Exception in remove temp attachment file" );
}
}
private String addDocument( HttpServletRequest request, String filePath, String refSer, DocumentHandlerEJB docHandler, UserInfoBean userInfo )throws Exception //Manish 12/1/2006
{
String retString = null;
BufferedInputStream bfr = null;
ByteArrayOutputStream bout = null;
try
{
String objName = request.getParameter( "OBJ_NAME" );
String refId = request.getParameter( "REF_ID" );
//Added by Jatin M on 30-Jan-2022 [To check if the Ref_id contains special character at the end and if yes than remove it] - START
if(refId.endsWith(":"))
{
refId = refId.substring(0,refId.length() - 1);
}
//Added by Jatin M on 30-Jan-2022 [To check if the Ref_id contains special character at the end and if yes than remove it] - END
//Changed by Prasad on 18/02/2021 [get refSer from method argument]
//String refSer = getRefSer( request, userInfo );
String refCol = checkNull( request.getParameter( "REF_COL" ) );
if( refCol.length() == 0 )
{
refCol = " ";
}
String strGrabFrame = checkNull( request.getParameter( "GRAB_FRAME" ) );
String documentType = checkNull( request.getParameter( "DOCUMENT_TYPE" ) );
if( "".equalsIgnoreCase(documentType) )
{
documentType = checkNull((String)request.getAttribute("DOCUMENT_TYPE"));
}
String attachFileType = checkNull( request.getParameter( "FILE_TYPE" ) );
String module = checkNull( request.getParameter( "MODULE" ) );
//Added by Pankaj R on 03/05/2021 [get doc_meta_data] START
String docMetaData = checkNull( request.getParameter( "DOC_META_DATA" ) );
File file = new File( filePath );
String fileName = file.getName();
String fileType = filePath.substring( filePath.lastIndexOf(".") + 1 );
//Added by Abhishek T on 03-Aug-18 [For getting number of pages of PDF document] START
int noOfPages = 0;
if ( "pdf".equalsIgnoreCase( attachFileType ) )
{
//Create new FileInputStream as PdfReader closed the input stream.
InputStream pdfFileStream = new FileInputStream(file);
noOfPages = getPDFNumberOfPages(pdfFileStream);
pdfFileStream.close();
}
//Added by Abhishek T on 03-Aug-18 [For getting number of pages of PDF document] END
//Added by Pravin K for store doc link in table on 21-DEC-17 START
String docLinkOptn = request.getParameter("DOC_LINK_OPT");
//Added by Pravin K for store doc link in table on 21-DEC-17 END
//Added by Pravin K on 10-SEP-18 for S18FBAS001 [for invoice details from pdf] START
String extractedData = "";
// FIXME Hard coded document type
//Added by Pravin K on 22-APR-21 [TO make data extraction configyrable] START
DocumentHandlerWrapperEJB documentHandlerWrapperEJB = new DocumentHandlerWrapperEJB();
String templatePath = documentHandlerWrapperEJB.getExtractionTemplatePath(objName,documentType, userInfo);
BaseLogger.log("3",userInfo,null, "Extracted_data :templatePath[" + templatePath+"]");
//Added by nikhil on 31-01-2022 for xls to csv conversion[Start]
CommonDBAccessEJB commonDBAccessEJB = new CommonDBAccessEJB();
String extractPrc = E12GenericUtility.checkNull(commonDBAccessEJB.getDBColumnValue("OBJ_ATTACH_CONFIG", "EXTRACT_PRC", "WHERE OBJ_NAME='"+objName+"' AND DOC_TYPE='"+documentType+"'", userInfo.getTransDB()));
String extractTempl = E12GenericUtility.checkNull(commonDBAccessEJB.getDBColumnValue("OBJ_ATTACH_CONFIG", "EXTRACT_TEMPL", "WHERE OBJ_NAME='"+objName+"' AND DOC_TYPE='"+documentType+"'", userInfo.getTransDB()));
String procStatus = "I";
String docProcessTrail = "";
String docOcrData = "";//Added by Tejas s on 30-May-2023 [After upload train document using pine code library agianst the enterprise]
String entityType ="";
String docOverviewData = "";//Added by Tejas s on 9-june-2023...[to store overviewData and extractedData saperately]
if(extractPrc.equals("EXCELINMEM") && !"".equals(extractTempl))
{
BaseLogger.log("3",userInfo,null, "Inside if condition line no 2101 extractTempl : ["+extractTempl+"]");
String responseString = "";
ExcelToCSV excelToCSV = new ExcelToCSV();
responseString = excelToCSV.excelToCSV(file, userInfo, extractTempl);
BaseLogger.log("0", null, null, "Print responseString line no 2997---- :" +responseString);
}
//Added by nikhil on 31-01-2022 for xls to csv conversion[End]
//Added by Pravin K on 22-APR-21 [TO make data extraction configyrable] END
//if ("Invoice".equalsIgnoreCase(documentType) || "Orders".equalsIgnoreCase(documentType) )
//Added by nikhil on 31-01-2022 for xls to csv conversion[Start]
else if(templatePath != null && templatePath.length() > 1)
{
InvoiceReader invoiceReader = new InvoiceReader(file);
// Added By Tejas s on 22-FEB-2023..[To Pass Processing method & instruction and APIKEY as request parameters to python Api]
//extractedData = invoiceReader.readInvoice(userInfo, templatePath);//Aded By pravin k Oon 28-APR-21
//Added by vaishali P [To pass entity type if present against selected doc_type][start]
DocumentHandlerWrapperEJB documentHandlerEjb = new DocumentHandlerWrapperEJB();
entityType = documentHandlerEjb.getEntityType(userInfo, documentType);
extractedData = invoiceReader.readInvoice(userInfo, templatePath, true ,documentType,entityType,"", objName);
//Added by vaishali P [To pass entity type if present against selected doc_type][END]
procStatus = invoiceReader.getProcStatus();
BaseLogger.log("3",userInfo,null, "Print procStatus : " + procStatus);
BaseLogger.log("3",userInfo,null, "Extracted_data : " + extractedData);
// Added by Pravin on 12-NOV-18 [to process extracted data] START
if (extractedData.length() > 1)
{
InvoiceDataPreprocessor preProcess = new InvoiceDataPreprocessor();
extractedData = preProcess.processData(extractedData);
BaseLogger.log("0", null, null, "extracted_data after process ---- :" +extractedData);
//Added by Tejas s on 30-May-2023 [After upload train document using pine code library agianst the enterprise]
docOcrData = invoiceReader.getOcrData();
}
// Added by Pravin on 12-NOV-18 [to process extracted data] END
docProcessTrail = invoiceReader.getDocProcTrailData();
//Added by Tejas s on 9-june-2023...[to store overviewData and extractedData saperately]..
docOverviewData = invoiceReader.getOverViewData();
}
//Added by Pravin K on 10-SEP-18 for S18FBAS001 [for invoice details from pdf] END
String refDescr = checkNull(request.getParameter("REF_DESCR"));
// Added by Pravin K on 22-JAN-19 [To store last modify date] START
//Added by Saitej D on [14-Mar-2019] [To get expiry date & allow download of document for content library] START
String expDate = request.getParameter( "EXP_DATE");
String cacheOpt = request.getParameter( "CACHE_OPT");
//Added by Saitej D on [14-Mar-2019] [To get expiry date & allow download of document for content library] END
String fileMetadata = checkNull(request.getParameter("FILE_METADATA"));
// Added by Pravin K on 22-JAN-19 [To store last modify date] END
fileMetadata = getFileMetaData(filePath, userInfo);
//Added by Prasad R on 11/10/2021 [check in related implementation] START
String docId = checkNull(request.getParameter("DOC_ID"));
if( docId.equalsIgnoreCase("") )
{
docId = checkNull((String)request.getAttribute("DOC_ID"));
}
boolean isMajorVersion = false;
try
{
String majorVersion = checkNull(request.getParameter("IS_MAJOR_VERSION"));
if ( majorVersion.length() > 0 )
{
isMajorVersion = Boolean.parseBoolean( majorVersion );
}
}
catch (Exception e)
{
isMajorVersion = false;
e.printStackTrace();
}
String checkinComment = checkNull(request.getParameter("CHECKIN_COMMENT"));
//Added by Prasad R on 11/10/2021 [check in related implementation] END
String userId = userInfo.getLoginCode();
StringBuffer retXMLStringBuff = new StringBuffer();
retXMLStringBuff.append("<?xml version=\"1.0\" encoding=\""+CommonConstants.ENCODING+"\"?>");
retXMLStringBuff.append("<DocumentRoot>");
retXMLStringBuff.append("<description>Datawindow Root</description>");
retXMLStringBuff.append("<group0>");
retXMLStringBuff.append("<description>Group0 description</description>");
retXMLStringBuff.append("<Header0>");
retXMLStringBuff.append("<description>Header0 members</description>");
retXMLStringBuff.append("<header>");
retXMLStringBuff.append("<ref_id><![CDATA[").append(refId).append("]]></ref_id>");
retXMLStringBuff.append("<ref_col><![CDATA[").append(refCol).append("]]></ref_col>");
retXMLStringBuff.append("<obj_name><![CDATA[").append(objName).append("]]></obj_name>");
retXMLStringBuff.append("<ref_ser><![CDATA[").append(refSer).append("]]></ref_ser>");
retXMLStringBuff.append("<doc_name><![CDATA[").append(fileName).append("]]></doc_name>");
retXMLStringBuff.append("<doc_type><![CDATA[").append(fileType).append("]]></doc_type>");
retXMLStringBuff.append("<document_type><![CDATA[").append(documentType).append("]]></document_type>");
retXMLStringBuff.append("<file_type><![CDATA[").append(attachFileType).append("]]></file_type>");
retXMLStringBuff.append("<created_by><![CDATA[").append(userId).append("]]></created_by>");
retXMLStringBuff.append("<doc_link_optn><![CDATA[" + docLinkOptn + "]]></doc_link_optn>");
retXMLStringBuff.append("<ref_descr><![CDATA[" + refDescr + "]]></ref_descr>");
retXMLStringBuff.append("<doc_pages><![CDATA[" + noOfPages + "]]></doc_pages>");
retXMLStringBuff.append("<extracted_data><![CDATA[" + extractedData + "]]></extracted_data>");
// Changed by Pravin K on 25-JAN-19 [ Added fileMetadata To store last modify date]
retXMLStringBuff.append("<file_metadata><![CDATA[" + fileMetadata + "]]></file_metadata>");// pa // 25-JAN
//Added by Saitej D on [14-Mar-2019] [To get expiry date & allow download of document for content library] START
retXMLStringBuff.append("<exp_date><![CDATA[" + expDate + "]]></exp_date>");
retXMLStringBuff.append("<cache_opt><![CDATA[" + cacheOpt + "]]></cache_opt>");
//Added by Saitej D on [14-Mar-2019] [To get expiry date & allow download of document for content library] END
retXMLStringBuff.append("<module><![CDATA[" + module + "]]></module>");
//Added by Pankaj R on 03/05/2021 [get doc_meta_data] START
retXMLStringBuff.append("<doc_meta_data><![CDATA[").append(docMetaData).append("]]></doc_meta_data>");
//Added by Prasad R on 11/10/2021 [check in related implementation] START
retXMLStringBuff.append("<doc_id><![CDATA["+docId+"]]></doc_id>");
retXMLStringBuff.append("<is_major_version><![CDATA["+ isMajorVersion +"]]></is_major_version>");
retXMLStringBuff.append("<checkin_comment><![CDATA["+ checkinComment +"]]></checkin_comment>");
retXMLStringBuff.append("<proc_status><![CDATA["+ procStatus +"]]></proc_status>");
//Added by Prasad R on 11/10/2021 [check in related implementation] END
//Added by Jatin M on 23-03-2023 [To insert/update document process trail in DOC_PROCESS_TRAIL] - START
retXMLStringBuff.append("<doc_proc_trail><![CDATA["+URLEncoder.encode(docProcessTrail, "UTF-8")+"]]></doc_proc_trail>");
//Added by Jatin M on 23-03-2023 [To insert/update document process trail in DOC_PROCESS_TRAIL] - END
//Added by Tejas s on 30-May-2023 [After upload train document using pine code library agianst the enterprise]...Start
retXMLStringBuff.append("<ocr_data><![CDATA["+URLEncoder.encode(docOcrData, "UTF-8")+"]]></ocr_data>");
//Added by Tejas s on 30-May-2023 [After upload train document using pine code library agianst the enterprise]...End
//Added by Tejas s on 9-june-2023...[to store overviewData and extractedData saperately]..start
retXMLStringBuff.append("<overview_data><![CDATA[" + docOverviewData + "]]></overview_data>");
//Added by Tejas s on 9-june-2023...[to store overviewData and extractedData saperately]..End
retXMLStringBuff.append("</header>");
retXMLStringBuff.append("</Header0>");
retXMLStringBuff.append("</group0>");
retXMLStringBuff.append("</DocumentRoot>");
BaseLogger.log("3", userInfo, null, "getAttachmentDetailStr [" + retXMLStringBuff + "]");
FileInputStream input = new FileInputStream( file );
bfr = new BufferedInputStream( input );
bout = new ByteArrayOutputStream();
int i=-1;
while((i=bfr.read()) != -1)
{
bout.write(i);
}
byte[] byteArray = bout.toByteArray();
// Added By Vikas L on 06-Feb-2019 [To get preview of the uploading file] START
byte[] previewImage = {};
if ("pdf".equalsIgnoreCase(fileType))
{
previewImage = getPdfPreviewImage(filePath);
}
else if ("zip".equalsIgnoreCase(fileType))
{
// Changed by Abhishek T on 06-June-2019 [Send zip file to python service for getting preview image] START
String htmlPreviewCaptureService = E12GenericUtility.getPythonServiceURL("HTML_CAPTURE");
if (htmlPreviewCaptureService != null) {
try {
File zipFile = new File(filePath);
previewImage = E12GenericUtility.makeMultipartRequest(htmlPreviewCaptureService, zipFile);
} catch (Exception ex) {
BaseLogger.log("3", null, "DocumentHandlerWrapperEJB", "Exception while getting ZIP file preview : " + ex);
}
}
// Changed by Abhishek T on 06-June-2019 [Send zip file to python service for getting preview image] END
}
else if("txt".equalsIgnoreCase(fileType))
{
previewImage = getTextToImage(filePath);
}
else if("csv".equalsIgnoreCase(fileType))
{
previewImage = getCsvToImage(filePath);
}
else if("docx".equalsIgnoreCase(fileType))
{
previewImage = getDocxToImage(filePath);
}
else
{
previewImage = getVideoPreviewImage(strGrabFrame, filePath, userInfo);
}
// Added By Vikas L on 06-Feb-2019 [To get preview of the uploading file] END
//Changed by Pravin K on 25-JAN-19 [ Added fileMetadata To store last modify date]
//retString = docHandler.addDocument( objName, refId, refSer, refCol, strGrabFrame, documentType, attachFileType, filePath, docLinkOptn, refDescr, noOfPages, extractedData, module, userInfo, fileMetadata);
retString = docHandler.addDocument( retXMLStringBuff.toString(), byteArray, previewImage, userInfo );
}
catch (ITMException itme)
{
throw itme;
}
catch (Exception e)
{
throw new ITMException(e);
}
finally
{
try
{
if( bfr != null )
{
bfr.close();
bfr = null;
}
if( bout != null )
{
bout.close();
bout = null;
}
}
catch ( Exception e )
{
BaseLogger.log("0",userInfo,null,"Exception in releasing file resource :" );
e.printStackTrace();
}
}
return retString;
}
private int getPDFNumberOfPages(InputStream pdfFileStream)
{
int noOfPages = 0;
try
{
PdfReader pdfReader = new PdfReader(pdfFileStream);
noOfPages = pdfReader.getNumberOfPages();
}
catch (IOException ex)
{
BaseLogger.log("0", null, null,"IOException in DocumentHandlerServlet :: getPDFNumberOfPages() : " + ex);
}
catch (Throwable throwable)
{
// Changed by Abhishek T on 04-OCT-18 START
/*
* Error (not Exception) throws,
* if PDF document is password protected,
* locked for printing, modifying, copying etc.
* in this 0 return as no of pages
*/
BaseLogger.log("0", null, null,"Exception or Error in DocumentHandlerServlet :: getPDFNumberOfPages() : " + throwable);
BaseLogger.log("0", null, null,
"The PDF file may be password protected or locked from copying, printing and modifying etc.\n" +
"For error detailing, refer below stack trace"
);
String stackTrace = buildStackTrace(throwable);
BaseLogger.log("0", null, null,stackTrace);
// Changed by Abhishek T on 04-OCT-18 END
}
BaseLogger.log("2", null, null,"DocumentHandlerServlet :: getPDFPageCount() : noOfPages [" + noOfPages + "]");
return noOfPages;
}
private String getFileMetaData( String filePath, UserInfoBean userInfo ) throws JSONException, ParseException
{
JSONObject fileMetadataJsonObj = new JSONObject();
String fileMetadata = "";
DocumentMetaDataReader dataReader = new DocumentMetaDataReader();
HashMap<String, String> metadataMap = dataReader.getDocumentMetaData(filePath);
BaseLogger.log("3",userInfo,null," metadataMap : [" + metadataMap + "]" );
if(metadataMap.containsKey("Date/Time") ||metadataMap.containsKey("Date/Time Original"))
{
String dateStr = "";
if(metadataMap.containsKey("Date/Time Original"))
{
dateStr = metadataMap.get("Date/Time Original");//dd MMM yyyy HH:mm a
BaseLogger.log("3",userInfo,null,"Date/Time Original : [" + dateStr + "]" );
}
else
{
dateStr = metadataMap.get("Date/Time");//dd MMM yyyy HH:mm a
BaseLogger.log("3",userInfo,null,"Date/Time : [" + dateStr + "]" );
}
//SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy:MM:dd HH:mm:ss");//2019:01:29 15:25:50
//Changed By Pankaj T. on 10-11-2022 As suggested by KB Sir changed date format
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
Date dateDt = dateFormat.parse(dateStr);
fileMetadata = dateDt.getTime()+"";
BaseLogger.log("3",userInfo,null,"fileMetadata : [" + fileMetadata + "]" );
//Changes by Prajyot on 26-Mar-2019 [Created JsonObject outside if block]
//JSONObject fileMetadeta = new JSONObject();
//fileMetadeta.put("lastModifiedDate", fileMetadata);
//fileMetadata = fileMetadeta.toString();
fileMetadataJsonObj.put("lastModifiedDate", fileMetadata);
fileMetadata = fileMetadataJsonObj.toString();
BaseLogger.log("3",userInfo,null," JSONObject fileMetadata : [" + fileMetadata + "]" );
}
/*
else
{
fileMetadata = "";
}
*/
//Added by Prajyot on 26-Mar-2019 [To add duration in fileMetadataJsonObj] Start
if(metadataMap.containsKey("Duration"))
{
String duration = metadataMap.get("Duration");//HH:mm:ss
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
Date date = sdf.parse("1970-01-01 " + duration);
BaseLogger.log("3",null,null,"in milliseconds: " + date.getTime());
duration = date.getTime() + "";
fileMetadataJsonObj.put("duration", duration);
fileMetadata = fileMetadataJsonObj.toString();
BaseLogger.log("3",userInfo,null," JSONObject fileMetadata : [" + fileMetadata + "]" );
}
//Added by Prajyot on 26-Mar-2019 [To add duration in fileMetadataJsonObj] End
return fileMetadata;
}
private String buildStackTrace(Throwable ex)
{
StringBuilder sb = new StringBuilder();
StackTraceElement[] elements = ex.getStackTrace();
sb.append(String.format("%s : %s\n", ex.getClass().getSimpleName(), ex.getMessage()));
for (StackTraceElement element : elements) {
sb.append(String.format("\tat %s\n", element.toString()));
}
return sb.toString();
}
private byte[] getPdfPreviewImage(String filepath)
{
byte[] bytes = { 0 };
File file = new File(filepath);
try (PDDocument document = PDDocument.load(file))
{
PDFRenderer pdfRenderer = new PDFRenderer(document);
BufferedImage bufferedImage = pdfRenderer.renderImageWithDPI(0, 50, ImageType.RGB);
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
ImageIO.write(bufferedImage, "png", outputStream);
bytes = outputStream.toByteArray();
document.close();
}
catch (IOException ex)
{
BaseLogger.log("0", null, "DocumentHandlerWrapperEJB", "IOException while trying to create pdf document - " + ex);
return bytes;
}
// Added by Pravin K on 03-DEC-19[ For the exception while uploading pdf invoice] START
catch (Exception ex)
{
BaseLogger.log("0", null, "DocumentHandlerWrapperEJB", "Other exception while trying to create pdf document - " + ex);
return bytes;
}
// Added by Pravin K on 03-DEC-19[ For the exception while uploading pdf invoice] END
return bytes;
}
private byte[] getTextToImage(String filepath)
{
byte[] bytes = { 0 };
File file = new File(filepath);
try
{
BufferedReader br = new BufferedReader(new FileReader(file));
StringBuilder sb = new StringBuilder();
String line;
while((line = br.readLine())!=null){
sb.append(line).append("\n");
}
bytes = convert(sb.toString(),filepath+"_img");
}
catch (IOException ex)
{
BaseLogger.log("0", null, "DocumentHandlerWrapperEJB", "IOException while trying to create txt document - " + ex);
return bytes;
}
catch (Exception ex)
{
BaseLogger.log("0", null, "DocumentHandlerWrapperEJB", "Other exception while trying to create txt document - " + ex);
return bytes;
}
return bytes;
}
private byte[] convert(String text, String img_name)
{
String[] text_array = text.split("[\n]");
BufferedImage img = new BufferedImage(1, 1, BufferedImage.TYPE_INT_ARGB);
Graphics2D g2d = img.createGraphics();
Font font = new Font("Consolas", Font.BOLD, 12);
g2d.setFont(font);
FontMetrics fm = g2d.getFontMetrics();
int width = fm.stringWidth(getLongestLine(text_array));
int lines = getLineCount(text);
int height = fm.getHeight() * (lines + 4);
g2d.dispose();
img = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
g2d = img.createGraphics();
g2d.setRenderingHint(RenderingHints.KEY_ALPHA_INTERPOLATION, RenderingHints.VALUE_ALPHA_INTERPOLATION_QUALITY);
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g2d.setRenderingHint(RenderingHints.KEY_COLOR_RENDERING, RenderingHints.VALUE_COLOR_RENDER_QUALITY);
g2d.setRenderingHint(RenderingHints.KEY_DITHERING, RenderingHints.VALUE_DITHER_ENABLE);
g2d.setRenderingHint(RenderingHints.KEY_FRACTIONALMETRICS, RenderingHints.VALUE_FRACTIONALMETRICS_ON);
g2d.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
g2d.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
g2d.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, RenderingHints.VALUE_STROKE_PURE);
g2d.setFont(font);
fm = g2d.getFontMetrics();
g2d.setColor(Color.BLACK);
for (int i = 1; i <= lines; ++i) {
g2d.drawString(text_array[i - 1], 0, fm.getAscent() * i);
}
g2d.dispose();
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
try {
// String img_path = System.getProperty("user.dir") + "/" + img_name + ".png";
// ImageIO.write(img, "png", new File(img_path));
ImageIO.write(img, "png",outputStream);
BaseLogger.log("0", null, null,"Print inside convert outputStream::::::: " + outputStream);
// bytes = outputStream.toByteArray();
} catch (IOException ex) {
ex.printStackTrace();
}
return outputStream.toByteArray();
}
public static int getLineCount(String text) {
return text.split("[\n]").length;
}
private static String getLongestLine(String[] arr) {
String max = arr[0];
for (int i = 1; i < arr.length; i++) {
if (max.length() < arr[i].length()) {
max = arr[i];
}
}
return max;
}
private byte[] getCsvToImage(String filepath)
{
byte[] bytes = { 0 };
File file = new File(filepath);
StringBuffer data = new StringBuffer();
try
{
FileReader fr = new FileReader(file);
BufferedReader br = new BufferedReader(fr);
String line = "";
String[] tempArr;
while ((line = br.readLine()) != null) {
tempArr = line.split(",");
for (String str : tempArr) {
data.append(str + " ");
}
data.append("\n");
}
bytes = convert(data.toString(),filepath+"_img");
}
catch (Exception ex)
{
BaseLogger.log("0", null, "DocumentHandlerWrapperEJB", "Other exception while trying to create csv document - " + ex);
return bytes;
}
return bytes;
}
private byte[] getDocxToImage(String filepath)
{
byte[] bytes = { 0 };
try
{
FileInputStream fis = new FileInputStream(filepath);
XWPFDocument doc = new XWPFDocument(fis);
StringBuilder strBuild = new StringBuilder();
List<XWPFParagraph> paragraphs = doc.getParagraphs();
for (XWPFParagraph para : paragraphs)
{
strBuild.append(para.getText()).append("\n");
}
bytes = convert(strBuild.toString(),filepath+"_img");
fis.close();
}
catch (Exception ex)
{
BaseLogger.log("0", null, "DocumentHandlerWrapperEJB", "Other exception while trying to create docx document - " + ex);
return bytes;
}
return bytes;
}
private byte[] getVideoPreviewImage( String strGrabFrame, String filePath, UserInfoBean userInfo )
{
byte[] videoFrameByteArray = {0};
try
{
boolean grabFrame = new Boolean(strGrabFrame).booleanValue();
if (grabFrame)
{
File videoFile = new File(filePath);
if (videoFile.exists())
{
BaseLogger.log("3", userInfo, null,"@@@@@ DocumentHandlerServlet :: addDocument() : Video file found at [" + videoFile.toString() + "]");
try
{
//Added by Sonam K on 5-Jul-19 [To grab video frame] START
int totalFrames = 0 ;
int frameNumber = 10;
try
{
FileChannelWrapper ch = NIOUtils.readableFileChannel(videoFile);
MP4Demuxer demuxer = new MP4Demuxer(ch);
DemuxerTrack video_track = demuxer.getVideoTrack();
totalFrames = video_track.getMeta().getTotalFrames();
frameNumber = (totalFrames * 10) / 100;
}
catch( Exception e )
{
BaseLogger.log("0", userInfo, null,"Exception in DocumentHandlerServlet :: getVideoPreviewImage() : " + e);
}
//Added by Sonam K on 5-Jul-19 [To grab video frame] END
Picture picFrame = FrameGrab.getNativeFrame(videoFile, frameNumber);
int height = picFrame.getHeight(), width = picFrame.getWidth();
ColorSpace picColorSpace = picFrame.getColor();
// If ColorSpace of grabbed frame is not RGB convert it to RGB.
if (picColorSpace != ColorSpace.RGB)
{
Transform transform = ColorUtil.getTransform(picFrame.getColor(), ColorSpace.RGB);
Picture newPic = Picture.create(width, height, ColorSpace.RGB);
transform.transform(picFrame, newPic);
picFrame = newPic;
}
BufferedImage bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_3BYTE_BGR);
// write picture data to buffered image
byte[] bufferedImageData = ((DataBufferByte) bufferedImage.getRaster().getDataBuffer()).getData();
int[] picData = picFrame.getPlaneData(0);
for (int i = 0, len = bufferedImageData.length; i < len; i++)
bufferedImageData[i] = (byte) picData[i];
// write BufferedImage to byte array
ByteArrayOutputStream arrayOutputStream = new ByteArrayOutputStream();
ImageIO.write(bufferedImage, "png", arrayOutputStream);
videoFrameByteArray = arrayOutputStream.toByteArray();
}
catch (IOException ex)
{
BaseLogger.log("0", userInfo, null,"Exception in DocumentHandlerServlet :: addDocument() : " + ex);
}
catch (JCodecException ex)
{
BaseLogger.log("0", userInfo, null,"Exception in DocumentHandlerServlet :: addDocument() : " + ex);
}
catch (Exception ex)
{
BaseLogger.log("0", userInfo, null,"Exception in DocumentHandlerServlet :: addDocument() : " + ex);
}
}
else
{
BaseLogger.log("3", userInfo, null,"@@@@@ DocumentHandlerServlet :: addDocument() : Video file NOT found at [" + videoFile.toString() + "]");
}
}
}
catch (Exception e)
{
e.printStackTrace();
}
return videoFrameByteArray;
}
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment