package net.eulerframework.web.core.base.controller;

import java.io.File;
import java.io.IOException;
import java.util.Date;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;

import com.fasterxml.jackson.databind.ObjectMapper;

import net.eulerframework.common.util.io.file.FileReadException;
import net.eulerframework.common.util.io.file.SimpleFileIOUtil;
import net.eulerframework.web.core.base.WebContextAccessable;

public abstract class BaseController extends WebContextAccessable {
    
    @Resource private ObjectMapper objectMapper;
    
    protected ObjectMapper getObjectMapper() {
        return this.objectMapper;
    }
    
    protected void writeString(String string) throws IOException{
        this.getResponse().getOutputStream().write(string.getBytes("UTF-8"));
    }

    protected void writeFile(String fileName, File file) throws FileReadException, IOException {
        byte[] fileData = SimpleFileIOUtil.readFileByMultiBytes(file, 1024);
        
        HttpServletResponse response = this.getResponse();

        response.setCharacterEncoding("utf-8");
        response.setContentType(MediaType.MULTIPART_FORM_DATA_VALUE);
        response.setHeader("Content-Disposition", 
                "attachment;fileName=" + new String(fileName.getBytes("utf-8"), "ISO8859-1"));

        response.setStatus(HttpStatus.OK.value());
        response.getOutputStream().write(fileData);
    }
    
    protected void setNoCacheHeader() {
        HttpServletResponse response = this.getResponse();
        response.setHeader("Cache-Control", "no-cache, no-store, max-age=0, must-revalidate");
        response.setHeader("Pragma", "no-cache");
        response.setDateHeader("Date", new Date().getTime());
        response.setIntHeader("Expires", 0);
    }
}

@@ -206,96 +206,8 @@
 e;%0A%0A
-import org.springframework.http.HttpStatus;%0Aimport org.springframework.http.MediaType;%0A%0A
 impo
@@ -816,16 +816,20 @@
 ;%0A    %7D%0A
+    
 %0A    pro
@@ -922,94 +922,8 @@
 n %7B%0A
-        byte%5B%5D fileData = SimpleFileIOUtil.readFileByMultiBytes(file, 1024);%0A        %0A
     
@@ -978,32 +978,34 @@
 nse();%0A%0A        
+//
 response.setChar
@@ -1040,67 +1040,223 @@
     
-response.setContentType(MediaType.MULTIPART_FORM_DATA_VALUE
+String contentType = %22application/octet-stream%22;//new MimetypesFileTypeMap().getContentType(fileName);%0A        response.setContentType(contentType);%0A        //response.setContentType(MimeType.getFileContentType(%22*%22)
 );%0A 
@@ -1400,17 +1400,16 @@
 9-1%22));%0A
-%0A
         
@@ -1424,46 +1424,118 @@
 .set
-Status(HttpStatus.OK.value());%0A       
+Header(%22Content-Length%22, String.valueOf(file.length()));%0A        SimpleFileIOUtil.readFileToOutputStream(file,
  res
@@ -1561,23 +1561,8 @@
 am()
-.write(fileData
 );%0A 

enforce file download