ser

来源:互联网 发布:苹果手机怎样开4g网络 编辑:程序博客网 时间:2024/05/20 09:06
package com.jsw.demo.server.servlet;


import com.jsw.common.cache.Cache;
import com.jsw.common.util.JndiUtils;
import com.jsw.report.service.ReportDownloadLogService;
import com.jsw.support.attach.Attach;
import com.jsw.support.attach.AttachService;


import com.lowagie.text.pdf.BarcodePDF417;
import com.lowagie.text.pdf.PdfContentByte;
import com.lowagie.text.pdf.PdfReader;
import com.lowagie.text.pdf.PdfStamper;
import com.lowagie.text.pdf.PdfWriter;


import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.context.ApplicationContext;


import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;


import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


public class DownloadServlet extends HttpServlet {
  private static final long serialVersionUID = -3505834426167614956L;
  private final static Log log = LogFactory.getLog(DownloadServlet.class);
  private ApplicationContext context;
  private AttachService attachService;
  private ReportDownloadLogService reportDownloadLogService;


  private Cache cache;
  private static final String ERROR_MESSAGE = "<p>系统内部错误,请与管理员联系</p>";
  private static final String EXCEL_CONTENT_TYPE = "application/vnd.ms-excel";
  private static final String ZIP_CONTENT_TYPE = "application/zip";


  public static void main(String[] args) throws Exception {
    PdfReader reader = new PdfReader(new FileInputStream(
        "D:\\0302\\纺织服装行业周报(2011.12.05-2011.12.11)-行业出口增速逐月回落,从防御性的角度继续配置男装.pdf"), "#gT781a@oOo0P323QmH-ew".getBytes());
    PdfStamper stamper = new PdfStamper(reader, new FileOutputStream("D:\\0302\\1212.pdf"));
    stamper.setEncryption(null, "#gT781a@oOo0P323QmH-ew".getBytes(), PdfWriter.ALLOW_PRINTING,
        PdfWriter.ENCRYPTION_AES_128);
    int size = reader.getNumberOfPages();
    PdfContentByte cb = stamper.getUnderContent(size);
    BarcodePDF417 codeEAN = new BarcodePDF417();
    codeEAN.setText("1000789");
    com.lowagie.text.Image img = codeEAN.getImage();
    img.setAbsolutePosition(500, 10);
    cb.addImage(img);
    stamper.close();
  }


  public DownloadServlet() {
    super();
  }


  public void downloadPdf(Long attach, String ownerPassword, InputStream input, OutputStream os) throws Exception {
    Long id = reportDownloadLogService.download(attach);
    PdfReader reader = new PdfReader(input, ownerPassword.getBytes());
    PdfStamper stamper = new PdfStamper(reader, os);
    stamper.setEncryption(null, ownerPassword.getBytes(), PdfWriter.ALLOW_PRINTING, PdfWriter.ENCRYPTION_AES_128);
    int size = reader.getNumberOfPages();
    PdfContentByte cb = stamper.getUnderContent(size);
    BarcodePDF417 codeEAN = new BarcodePDF417();
    codeEAN.setText(id.toString());
    com.lowagie.text.Image img = codeEAN.getImage();
    img.setAbsolutePosition(500, 10);
    cb.addImage(img);
    stamper.close();
  }


  @Override
  public void init() throws ServletException {
    super.init();
    context = (ApplicationContext) JndiUtils.lookupObject(ApplicationContext.class.getName());
    if (context == null) {
      if (log.isErrorEnabled()) {
        log.error("There is no ApplicationContext instance in Jndi context!");
      }
    }
    attachService = context.getAutowireCapableBeanFactory().getBean(AttachService.class);
    if (log.isErrorEnabled() && attachService == null) {
      log.error("AttachService instance was not found in ApplicationContext..");
    }
    cache = context.getAutowireCapableBeanFactory().getBean(Cache.class);
    if (cache == null && log.isErrorEnabled()) {
      log.error("Cache instance was not found in ApplicationContext..");
    }


    reportDownloadLogService = context.getAutowireCapableBeanFactory().getBean(ReportDownloadLogService.class);
    if (reportDownloadLogService == null && log.isErrorEnabled()) {
      log.error("ReportDownloadLogService instance was not found in ApplicationContext..");
    }
  }


  @Override
  protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    doPost(req, resp);
  }


  @Override
  protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    String attachIds = req.getParameter("attachIds");
    String downLoadZipFileName = req.getParameter("fileName");
    // 批量下载
    if (attachIds != null) {
      batchDownload(downLoadZipFileName, attachIds, req, resp);
      return;
    }
    String attachGroup = req.getParameter("attachGroup");
    String downloadName = req.getParameter("downloadName");
    if (attachGroup != null) {
      downLoadAttachGroup(attachGroup, downloadName, resp, req);
      return;
    }
    String attachId = req.getParameter("attachId");
    // 附件下载
    if (attachId != null) {
      downLoadAttach(Long.parseLong(attachId), resp, req);
      return;
    }
    String cacheKey = req.getParameter("cacheKey");
    // 导出Excel
    exportExcel(cacheKey, req, resp);
  }


  void downloadPdf(Long attach, HttpServletResponse response, File file) throws Exception {
    OutputStream os = response.getOutputStream();
    FileInputStream input = new FileInputStream(file);
    downloadPdf(attach, "#gT781a@oOo0P323QmH-ew", input, os);
  }


  private List<Long> assembleAttachGroupids(String attachIds) {
    String[] attachIdsArray = attachIds.split(",");
    List<Long> result = new ArrayList<Long>();
    for (String attachId : attachIdsArray) {
      result.add(Long.valueOf(attachId));
    }
    return result;
  }


  /**
   * 批量下载
   * 
   * @param downLoadZipFileName 下载之后的文件名
   * @param attachIds 附件id的字符串,逗号分隔
   * @param request
   * @param response
   * @throws IOException
   */
  private void batchDownload(String downLoadZipFileName, String attachIds, HttpServletRequest request,
      HttpServletResponse response) throws IOException {
    if (attachIds.isEmpty()) {
      if (log.isInfoEnabled()) {
        log.info("there is no attachId..");
        return;
      }
    }
    List<Long> attachIdList = assembleAttachGroupids(attachIds);
    log.info("here are all the attachIds of the selected items:" + attachIdList);
    File targetZipFile = null;
    log.info("try to generate zip files of all the attach files..");
    try {
      targetZipFile = attachService.getAttachesZipFile(downLoadZipFileName, attachIdList);
    } catch (Throwable e) {
      log.error("", e);
      handleError(response, ERROR_MESSAGE);
      return;
    }
    if (targetZipFile == null || !targetZipFile.exists()) {
      log.error("can not generate zip files with these attachIds:" + attachIdList);
      handleError(response, ERROR_MESSAGE);
      return;
    }
    log.info("the requst zip file has generated successfully:" + targetZipFile.getName());
    configResponse(response, ZIP_CONTENT_TYPE, downLoadZipFileName, request.getHeader("USER-AGENT"));
    WriteFileToClient(response, new FileInputStream(targetZipFile));
    return;


  }


  /**
   * 设置HttpResponse
   * 
   * @param response
   * @param contentType
   * @param fileName
   * @param agent
   * @throws UnsupportedEncodingException
   */
  private void configResponse(HttpServletResponse response, String contentType, String fileName, String agent)
      throws UnsupportedEncodingException {
    // response.reset();
    if (contentType != null) {
      response.setContentType(contentType);
    }
    if (fileName != null) {
      fileName = fileName.replaceAll("\\s+", "");
      if (null != agent && -1 != agent.indexOf("MSIE")) {
        response.addHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(fileName, "utf8"));
      } else if (null != agent && -1 != agent.indexOf("Mozilla")) {
        fileName = fileName.replaceAll(" ", "_");
        response.addHeader("Content-Disposition", "attachment; filename="
            + new String(fileName.getBytes("utf8"), "ISO-8859-1"));
      } else {
        response.addHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(fileName, "utf8"));
      }
    }
  }


  /**
   * 下载附件
   * 
   * @throws IOException
   */
  private void downLoadAttach(long attachId, HttpServletResponse response, HttpServletRequest request)
      throws IOException {
    if (log.isInfoEnabled()) {
      log.info("try to find Attach instance by Id:" + attachId);
    }
    Attach attach = attachService.findById(attachId);
    if (attach == null && log.isErrorEnabled()) {
      log.error("can not find Attach instance by Id:" + attachId);
      handleError(response, ERROR_MESSAGE);
      return;
    }


    if (log.isInfoEnabled()) {
      log.info("the Attach instance has been found.first,try to find the associated file in the cache by cacheKey:"
          + attachId);
    }
    File targetAttachFile = (File) cache.getCache("attachCache").get(String.valueOf(attachId));
    if (targetAttachFile != null && targetAttachFile.exists()) {
      log.info("the attach file has been found in the cache,so we download this file ..");
      configResponse(response, attach.getContentType(), attach.getFullFileName(), request.getHeader("USER-AGENT"));


      if (targetAttachFile.getName().endsWith(".pdf")) {


        try {
          downloadPdf(attach.getId(), response, targetAttachFile);
          return;
        } catch (Exception e) {
          log.error("downloadPdf fail", e);
        }
      }


      WriteFileToClient(response, new FileInputStream(targetAttachFile));
      return;
    }
    if (log.isInfoEnabled()) {
      log.info("the target attach file was not found in the cache,try to find associated file in the attach directory by attachId:"
          + attachId);
    }
    File attachFile = null;
    try {
      attachFile = attachService.getAttachFile(attachId);
    } catch (Exception e1) {
      log.error("can not find associated file in the attach directory!");
      handleError(response, e1.getMessage());
      return;
    }
    if (!attachFile.exists() && log.isErrorEnabled()) {
      log.error("can not find associated file in the attach directory!");
      handleError(response, ERROR_MESSAGE);
      return;
    } else {
      log.info("the associated file:" + attachFile.getName() + " has been found in the attach directory..");
      log.info("first ,put the attach File " + attachFile.getName() + " into attachCache for later download request...");
      cache.getCache("attachCache").put(String.valueOf(attachId), attachFile);
    }
    configResponse(response, attach.getContentType(), attach.getFullFileName(), request.getHeader("USER-AGENT"));
    if (attachFile.getName().endsWith(".pdf")) {
      try {
        downloadPdf(attach.getId(), response, attachFile);
        return;
      } catch (Exception e) {
        log.error("", e);
      }
    }
    WriteFileToClient(response, new FileInputStream(attachFile));
  }


  private void downLoadAttachGroup(String attachGroup, String downloadName, HttpServletResponse response,
      HttpServletRequest request) throws IOException {
    if (log.isInfoEnabled()) {
      log.info("try to find AttachGroup instance from cache by Id:" + attachGroup);
    }
    File targetAttachFile = (File) cache.getCache("attachCache").get(String.valueOf(attachGroup));
    if (targetAttachFile == null) {
      if (log.isInfoEnabled()) {
        log.info("can not find attach group from cache:" + attachGroup);
      }
      try {
        targetAttachFile = attachService.getAttachGroupZipFile(downloadName, attachGroup);
      } catch (Throwable e) {
        log.error("", e);
        handleError(response, ERROR_MESSAGE);
        return;
      }
    } else if (targetAttachFile.getName().endsWith(".pdf")) {
      try {
        downloadPdf(null, response, targetAttachFile);
        return;
      } catch (Exception e) {
        log.error("", e);
      }
    }


    if (log.isInfoEnabled()) {
      log.info("get attach group :" + attachGroup);
    }
    if (targetAttachFile == null || !targetAttachFile.exists()) {
      log.error("can not find Attach instance by Id:" + attachGroup);
      handleError(response, ERROR_MESSAGE);
      return;
    }


    log.info("the attach file has been found in the cache,so we download this file ..");
    configResponse(response, ZIP_CONTENT_TYPE, downloadName, request.getHeader("USER-AGENT"));
    WriteFileToClient(response, new FileInputStream(targetAttachFile));
    return;


  }


  /**
   * 导出Excel
   * 
   * @param cacheKey
   * @param request
   * @param response
   * @throws IOException
   */
  private void exportExcel(String cacheKey, HttpServletRequest request, HttpServletResponse response)
      throws IOException {
    if (log.isInfoEnabled()) {
      log.info("try to find the target excel in the cache by cacheKey:" + cacheKey);
    }
    File excel = (File) cache.getCache("excelCache").get(cacheKey);
    if (log.isErrorEnabled() && excel == null) {
      log.error("the excel file object stored in the cache is null!");
      handleError(response, ERROR_MESSAGE);
      return;
    }
    if (log.isErrorEnabled() && !excel.exists()) {
      log.error("the excel file does not exist in the cache");
      handleError(response, ERROR_MESSAGE);
      return;
    }
    if (log.isInfoEnabled()) {
      log.info("the requested excel:" + excel.getName() + " has been found in the cache,start to export it..");
    }
    configResponse(response, EXCEL_CONTENT_TYPE, excel.getName(), request.getHeader("USER-AGENT"));
    WriteFileToClient(response, new FileInputStream(excel));
  }


  /**
   * 处理异常
   * 
   * @param response
   * @throws IOException
   */
  private void handleError(HttpServletResponse response, String message) throws IOException {
    response.sendError(500, message);
  }


  /**
   * 将文件以二进制流的形式输出到客户端
   * 
   * @param response
   * @param file
   * @throws IOException
   */
  private void WriteFileToClient(HttpServletResponse response, InputStream input) throws IOException {
    OutputStream os = response.getOutputStream();


    byte[] buf = new byte[1024];
    int read = 0;
    try {
      while ((read = input.read(buf)) >= 0) {
        os.write(buf, 0, read);
      }
    } catch (Exception e) {
      e.printStackTrace();
    } finally {
      try {
        os.flush();
        input.close();
        os.close();
      } catch (Exception e) {
        e.printStackTrace();
        if (log.isErrorEnabled()) {
          log.error("write file as binary stream to response failed.");
          log.error(e.getMessage(), e);
        }
      }
    }
  }


}
原创粉丝点击