Guest User

FileUpload

a guest
Oct 5th, 2016
98
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 11.71 KB | None | 0 0
  1. package com.quantros.qsupport;
  2.  
  3. import java.io.File;
  4. import java.io.FileInputStream;
  5. import java.util.ArrayList;
  6. import java.util.Iterator;
  7. import java.util.List;
  8. import java.util.Map;
  9.  
  10. import javax.servlet.ServletContext;
  11. import javax.servlet.ServletException;
  12. import javax.servlet.ServletOutputStream;
  13. import javax.servlet.http.HttpServletRequest;
  14. import javax.servlet.http.HttpServletResponse;
  15. import javax.servlet.http.HttpSession;
  16.  
  17. import jxl.Cell;
  18.  
  19. import org.apache.commons.fileupload.DiskFileUpload;
  20. import org.apache.commons.fileupload.FileItem;
  21. import org.apache.commons.fileupload.servlet.ServletFileUpload;
  22. import org.apache.commons.lang.StringUtils;
  23. import org.json.JSONArray;
  24. import org.json.JSONObject;
  25.  
  26. import com.infoobjectsinc.util.QGlobals;
  27. import com.infoobjectsinc.util.QUser;
  28. import com.infoobjectsinc.util.QuantrosException;
  29. import com.quantros.AppModules.IOFunctions;
  30. import com.quantros.AppModules.ProcessDataHandler;
  31. import com.quantros.qsupport.DAO.BatchUploadDAO;
  32. import com.quantros.qxplore.Globals;
  33. import com.quantros.util.ServerUtil;
  34.  
  35. public class BatchUpload implements ProcessDataHandler{
  36.  
  37.     public void processData(HttpServletRequest req, HttpServletResponse res, ServletContext servctxt) throws ServletException, Exception {
  38.  
  39.         HttpSession session = req.getSession(true);
  40.         IOFunctions iof = new IOFunctions(QGlobals.debugger);
  41.         QUser qUser = (QUser) session.getAttribute("quser");
  42.         BatchUploadDAO dao = new BatchUploadDAO();
  43.        
  44.         if (qUser == null) {
  45.             iof.forwardTo(req, res, servctxt, "/qsupport/jsp/index.jsp");
  46.             return;
  47.         }
  48.        
  49.        
  50.         try {
  51.             String uploadUsersID = qUser.getIdAsString();
  52.             String action = iof.getParameter(req, "action", "");
  53.             String forEntitiesID = iof.getParameter(req, "ENTITIESID", "");
  54.             String uploadType = iof.getParameter(req, "uploadType", "");
  55.            
  56.             if (action.equalsIgnoreCase("uploadFile")) {
  57.                 JSONObject jsonResponse = new JSONObject();
  58.                 JSONObject uploadResult = uploadFile(qUser, uploadType, iof, req, res, servctxt);
  59.                 ParseExcel parser = null;
  60.                 String uploadID = "";
  61.                 if (uploadType.equalsIgnoreCase("Departments")) {
  62.                     parser = new ParseExcelDepartments();
  63.                     //parser.setIsDebug(true);
  64.                 } else if (uploadType.equalsIgnoreCase("Facilities")) {
  65.                     parser = new ParseExcelFacilities();
  66.                     //parser.setIsDebug(true);
  67.                 } else if (uploadType.equalsIgnoreCase("Users")) {
  68.                     parser = new ParseExcelUsers();
  69.                 } else if (uploadType.equalsIgnoreCase("SeverityAlertNotificationUserAssignment")){
  70.                     parser = new ParseExcelSeverityAlertUsers();
  71.                 } else {
  72.                     throw new Exception("upload type " + uploadType + " is not known.");
  73.                 }
  74.  
  75.                 uploadID = dao.insertFileIntoTable(uploadUsersID, forEntitiesID, uploadResult.getString("jobname"), uploadResult.getString("FILE_PATH"), uploadResult.getString("ORIGINAL_FILE_PATH"), uploadType);                
  76.                 jsonResponse.put("success", true);
  77.                
  78.                 res.setContentType("text/html");
  79.                 res.getWriter().print(jsonResponse);
  80.             } else if (action.equalsIgnoreCase("getUploadHistory")) {
  81.                 JSONObject jsonResponse = new JSONObject();
  82.                 jsonResponse.put("success", true);
  83.                 JSONArray ar = getUploadHistory(forEntitiesID,dao,uploadType);
  84.                 jsonResponse.put("uploadHistory", ar);
  85.                 res.setContentType("application/json");
  86.                 res.getWriter().print(jsonResponse);
  87.             } else if (action.equalsIgnoreCase("downloadOriginalFile")) {
  88.                 String uploadID = iof.getParameter(req, "uploadID", "");
  89.                 uploadType = iof.getParameter(req, "uploadType", "");
  90.  
  91.                 File of = ServerUtil.getFile(dao.getUploadedFile(uploadID));
  92.                 String fileName = dao.getClientSideFilePath(uploadID);
  93.                 String[] components = fileName.split("[\\/]");
  94.                 int len = components.length;
  95.                 fileName = components[len - 1];
  96.  
  97.                 res.setHeader("Expires", "0");
  98.                 res.setHeader("Cache-Control","private, must-revalidate, max-age=300, post-check=0, pre-check=0");
  99.                 res.setContentType("application/vnd.ms-excel");
  100.                 res.setHeader("Content-Disposition","attachment; filename=\"" + fileName + "\"");
  101.                 res.setHeader("Content-Length", String.valueOf(of.length()));
  102.                
  103.                 ServletOutputStream servletoutputstream = res.getOutputStream();
  104.                 int bufferSize = 10240; // 10KB
  105.                 FileInputStream fileinputstream = ServerUtil.getFileInputStream(of);
  106.                 try {
  107.                     int i = fileinputstream.available();
  108.                     byte numOfBytes[] = new byte[i];
  109.                     int j = fileinputstream.read(numOfBytes);
  110.                     fileinputstream.close();
  111.                     servletoutputstream.write(numOfBytes);
  112.                 } catch (Exception e) {
  113.                     fileinputstream.close();
  114.                     QGlobals.debugger.error("BatchUpload","processData",e);
  115.                     throw new QuantrosException(e);
  116.                 }
  117.                 servletoutputstream.flush();
  118.                
  119.             } else if (action.equalsIgnoreCase("downloadBadRecords")) {
  120.                 String uploadID = iof.getParameter(req, "uploadID", "");
  121.                 uploadType = iof.getParameter(req, "uploadType", "");
  122.                 ParseExcel parser = null;
  123.                 if (uploadType.equalsIgnoreCase("Departments")) {
  124.                     parser = new ParseExcelDepartments();
  125.                 } else if (uploadType.equalsIgnoreCase("Facilities")) {
  126.                     parser = new ParseExcelFacilities();
  127.                     //parser.setIsDebug(true);
  128.                 } else if (uploadType.equalsIgnoreCase("Users")) {
  129.                     parser = new ParseExcelUsers();
  130.                     parser.setIsDebug(true);
  131.                     // UploadFacilitiesParseExcel parser = new UploadFacilitiesParseExcel();
  132.                 } else if (uploadType.equalsIgnoreCase("SeverityAlertNotificationUserAssignment")) {
  133.                     parser = new ParseExcelSeverityAlertUsers();
  134.                     parser.setIsDebug(true);
  135.                 } else {
  136.                     throw new Exception("upload type " + uploadType + " is not known.");
  137.                 }
  138.                
  139.                 File badFile = ServerUtil.getFile(dao.getBadRecordFilePath(uploadID));
  140.                 String fileName = badFile.getName();
  141.                 QGlobals.debugger.log("BatchUpload","processData", "Bad record file name:" + fileName,  4);
  142.                
  143.                 res.setHeader("Expires", "0");
  144.                 res.setHeader("Cache-Control","private, must-revalidate, max-age=300, post-check=0, pre-check=0");
  145.                 res.setContentType("application/vnd.ms-excel");
  146.                 res.setHeader("Content-Disposition","attachment; filename=\"" + fileName + "\"");
  147.                 res.setHeader("Content-Length", String.valueOf(badFile.length()));
  148.  
  149.                 ServletOutputStream servletoutputstream = res.getOutputStream();
  150.                 int bufferSize = 10240; // 10KB
  151.                 FileInputStream fileinputstream = ServerUtil.getFileInputStream(badFile);
  152.                 QGlobals.debugger.log("BatchUpload","processData", "Before sending excel content",  4);
  153.                 try {
  154.                     int i = fileinputstream.available();
  155.                     byte numOfBytes[] = new byte[i];
  156.                     int j = fileinputstream.read(numOfBytes);
  157.                     fileinputstream.close();
  158.                     servletoutputstream.write(numOfBytes);
  159.                 } catch (Exception e) {
  160.                     fileinputstream.close();
  161.                     QGlobals.debugger.error("BatchUpload","processData",e);
  162.                     throw new QuantrosException(e);
  163.                 }
  164.                 servletoutputstream.flush();
  165.             }
  166.         } catch (Exception e) {
  167.             QGlobals.debugger.error("BatchUpload", "processData", e);
  168.             throw new QuantrosException(e);
  169.         }
  170.     }
  171.    
  172.     private JSONArray getUploadHistory(String entitiesID, BatchUploadDAO dao, String uploadType) throws Exception {
  173.  
  174.         List lst = dao.getUploadHistory(entitiesID, uploadType);
  175.         JSONArray ar = new JSONArray();
  176.         Iterator itr = lst.iterator();
  177.         Map m;
  178.         int badCount = 0;
  179.         int totalRecordCount = 0;
  180.  
  181.         String downloadLink = "";
  182.         while (itr.hasNext()) {
  183.             m = (Map) itr.next();
  184.             badCount = Integer.parseInt(m.get("BAD_RECORD_COUNT").toString());
  185.             totalRecordCount = Integer.parseInt(m.get("RECORD_COUNT").toString());
  186.  
  187.             if (badCount > 0) {
  188.                 downloadLink = "<a class='badRecordsDownloadLink' onclick='badRecordLinkClicked();' href='/qsupport/controller/QSupportController?ServName=BatchUpload&action=downloadBadRecords&uploadID=" +
  189.                         m.get("UPLOADID").toString() + "&uploadType=" + uploadType + "'>" + badCount + "</a>";
  190.                 m.put("BAD_RECORD_COUNT", downloadLink);
  191.             }
  192.            
  193.             downloadLink = "<a class='totalRecordsDownloadLink' onclick='totalRecordLinkClicked();' href='/qsupport/controller/QSupportController?ServName=BatchUpload&action=downloadOriginalFile&uploadID=" +
  194.                     m.get("UPLOADID").toString() + "&uploadType=" + uploadType + "'>" + totalRecordCount + "</a>";
  195.             m.put("RECORD_COUNT", downloadLink);
  196.  
  197.             ar.put(new JSONObject(m));
  198.         }
  199.         return ar;
  200.     }
  201.  
  202.     /*
  203.      * This method builds a JSONObject for the given record.
  204.      */
  205.     public JSONObject cellsToJSONObject(int index, String[] headerNames, Cell[] dataCells) throws QuantrosException {
  206.         JSONObject jsonRecord = new JSONObject();
  207.         try {
  208.             jsonRecord.put("s_no", index);
  209.             for(int i = 0; i < dataCells.length; i++) {
  210.                 jsonRecord.put(headerNames[i], dataCells[i].getContents());
  211.             }
  212.         } catch(Exception e) {
  213.             QGlobals.debugger.error("ExcelImport", "cellsToJSONObject", e);
  214.             throw new QuantrosException(e);
  215.         }
  216.         return jsonRecord;
  217.     }
  218.  
  219.     private JSONObject uploadFile(QUser qUser, String uploadType, IOFunctions iof, HttpServletRequest req, HttpServletResponse res, ServletContext servctxt) throws ServletException, Exception {
  220.  
  221.         String entitiesID = iof.getParameter(req,"ENTITIESID", "");
  222.         String jobName = iof.getParameter(req,"jobname", "");
  223.         boolean isMultipart = ServletFileUpload.isMultipartContent(req);
  224.         Globals.debugger.log("BatchUpload", "uploadFile", "isMultipart:" + isMultipart, 4);
  225.  
  226.         JSONObject result = new JSONObject();
  227.         File f = null;
  228.         DiskFileUpload upload = new DiskFileUpload();
  229.         List items = upload.parseRequest(req);
  230.         Iterator itr = items.iterator();
  231.         while(itr.hasNext()) {
  232.             FileItem item = (FileItem)itr.next();
  233.             if (! item.isFormField()) {
  234.                 String usersID = qUser.getIdAsString();
  235.                 String originalFileName = item.getName().substring(item.getName().lastIndexOf(File.separatorChar) + 1);
  236.                 String extension = originalFileName.substring(originalFileName.lastIndexOf(".") + 1);
  237.                 String fileName = "" + System.currentTimeMillis() + "." + extension;
  238.                 ArrayList pathComponents = new ArrayList();
  239.                 pathComponents.add((Globals.splusInfo.myProps.getProperty("ATTACH_DOC_DRIVE")).trim() + "QSUPPORT");
  240.                 pathComponents.add("BatchUploads");
  241.                 pathComponents.add(uploadType);
  242.                 pathComponents.add(entitiesID);
  243.                 pathComponents.add(usersID);
  244.                 pathComponents.add(fileName);
  245.                 fileName = StringUtils.join(pathComponents , File.separatorChar);
  246.                
  247.                 f = ServerUtil.getFile(fileName);
  248.                 f.getParentFile().mkdirs();
  249.                 item.write(f);
  250.                 result.put("FILE_PATH", f.getAbsolutePath());
  251.                 result.put("ORIGINAL_FILE_PATH", item.getName());
  252.             } else {
  253.                 String fieldName = item.getFieldName();
  254.                 String value = item.getString();
  255.                 if (fieldName.equalsIgnoreCase("jobname")) {
  256.                     result.put("jobname", value);
  257.                 }
  258.             }
  259.         }
  260.         return result;
  261.     }
  262. }
Add Comment
Please, Sign In to add comment