package com.synap.synapeditor;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;
import java.util.UUID;
import java.util.zip.InflaterInputStream;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
@WebServlet(
name = "ImportServlet", urlPatterns = {"/importDoc"} )
public class ImportServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
private static final String UPLOAD_DIRECTORY = "import";
private static final int MEMORY_THRESHOLD = 1024 * 1024 * 3;
private static final int MAX_FILE_SIZE = 1024 * 1024 * 40;
private static final int MAX_REQUEST_SIZE = 1024 * 1024 * 50;
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
if (ServletFileUpload.isMultipartContent(request)) {
DiskFileItemFactory factory = new DiskFileItemFactory();
factory.setSizeThreshold(MEMORY_THRESHOLD);
factory.setRepository(new File(System.getProperty("java.io.tmpdir")));
ServletFileUpload upload = new ServletFileUpload(factory);
upload.setFileSizeMax(MAX_FILE_SIZEsetHeaderEncoding("UTF-8");
upload.setFileSizeMax(MAX_FILE_SIZE);
upload.setSizeMax(MAX_REQUEST_SIZE);
String uploadPath = getServletContext().getRealPath("") + File.separator + UPLOAD_DIRECTORY;
File storeFile = null;
try {
List<FileItem> formItems = upload.parseRequest(request);
if (formItems != null && formItems.size() > 0) {
for (FileItem item : formItems) {
if (!item.isFormField()) {
String fileName = new File(item.getName()).getName();
String filePath = uploadPath + File.separator + fileName;
storeFile = new File(filePath);
item.write(storeFile);
request.setAttribute("message", "File " + fileName + " has uploaded successfully!");
}
}
}
} catch (Exception ex) {
request.setAttribute("message", "There was an error: " + ex.getMessage());
}
// 월별로 파일 변환
Calendar cal = Calendar.getInstance();
String yearMonth = String.format("%04d%02d", cal.get(Calendar.YEAR), cal.get(Calendar.MONTH)+1);
// 파일별로 변환결과를 저장할 경로 생성
String uuid = UUID.randomUUID().toString();
// 경로 생성
File outputPath = new File(uploadPath + File.separator + yearMonth + File.separator + uuid);
if(!outputPath.exists()) {
outputPath.mkdirs();
}
// 변환 실행
executeConverter(storeFile.getAbsolutePath(), outputPath.getAbsolutePath());
// 변환 후 원본 삭제
// 변환된 pb파일을 읽어서 serialzie
if(storeFile.exists()) {
// v2.3.0 부터 파일명이 document.word.pb에서 document.pb로 변경됨 storeFile.delete();
}
Integer[] serializedData = serializePbData(outputPath + "/document.pb");
// 변환된 pb파일을 읽어서 serialzie
// pb파일 삭제v2.3.0 부터 파일명이 document.word.pb에서 document.pb로 변경됨
FileInteger[] pbFileserializedData = new FileserializePbData(outputPath + "/document.pb");
pbFile.deleteOnExit();
// returnpb파일 data를삭제
map으로 구성 File Map<String, Object> map pbFile = new HashMap<>(File(outputPath + "/document.pb");
mapif(pbFile.put("serializedData", serializedData);exists()) {
mappbFile.put("importPath", "/synapeditor/import/" + yearMonth + "/" + uuid);delete();
}
// json 형태로 return (googledata를 gsonmap으로 lib구성
사용) Map Gson gsonmap = new GsonBuilderHashMap().create();
PrintWriter out = response.getWriter(map.put("serializedData", serializedData);
outmap.print(gson.toJson(map));
put("importPath", "/se_jdk15/import/" + yearMonth + "/" + uuid);
out.flush();
} } // json 형태로 return protected(google staticgson int executeConverter(String inputFilePath, String outputPath) {lib 사용)
String SEDOC_CONVERT_DIR = "/workspace/workspace-sts/synapeditor/WebContent/WEB-INF/sedocConverter/sedocConverter_exe"Gson gson = new GsonBuilder().create();
String FONT_DIR = "/workspace/workspace-sts/synapeditor/WebContent/WEB-INF/sedocConverter/fonts" PrintWriter out = response.getWriter();
String TEMP_DIR = "/workspace/workspace-sts/synapeditor/WebContent/WEB-INF/sedocConverter/tmp" out.print(gson.toJson(map));
File tempDir = new File(TEMP_DIR out.flush();
if(!tempDir.exists()) {}
}
protected static int executeConverter(String inputFilePath, String outputPath) {
String SEDOC_CONVERT_DIR = "C:\\workspace\\seimporter\\sedocConverter\\sedocConverter.exe";
String FONT_DIR = "C:\\workspace\\seimporter\\fonts";
String TEMP_DIR = "C:\\workspace\\seimporter\\tmp";
File tempDir = new File(TEMP_DIR);
if(!tempDir.exists()) {
tempDir.mkdirs();
}
File fontDir = new File(FONT_DIR);
if(!fontDir.exists()) {
fontDir.mkdirs();
}
// 변환 명령 구성
String[] cmd = {SEDOC_CONVERT_DIR, "-f", FONT_DIR, inputFilePath, outputPath, TEMP_DIR};
tempDir.mkdirs(); try {
} FileTimer fontDirt = new FileTimer(FONT_DIR);
if(!fontDir.exists()) { Process proc = Runtime.getRuntime().exec(cmd);
TimerTask killer = new fontDir.mkdirsTimeoutProcessKiller(proc);
t.schedule(killer, 20000); // }20초 (변환이 20초 안에 완료되지 않으면 프로세스 종료)
// 변환 명령 구성int exitValue = proc.waitFor();
String[] cmd = {SEDOC_CONVERT_DIR, "-f", FONT_DIR, inputFilePath, outputPath, TEMP_DIR};
killer.cancel();
try { return exitValue;
Timer t =} newcatch Timer(Exception e); {
Process proc = Runtime.getRuntimee.printStackTrace().exec(cmd);
TimerTask killer = new TimeoutProcessKiller(proc);return -1;
}
}
protected static t.schedule(killer, 20000); // 20초 (변환이 20초 안에 완료되지 않으면 프로세스 종료)
Integer[] serializePbData(String pbFilePath) throws IOException {
List<Integer> serializedData = new ArrayList<Integer>();
intFileInputStream exitValuefis = proc.waitFor(new FileInputStream(pbFilePath);
Integer[] data = killer.cancel()null;
fis.skip(16);
return exitValue; InflaterInputStream ifis = new } catch (Exception e) {InflaterInputStream(fis);
byte[] buffer = e.printStackTrace()new byte[1024];
int len return= -1;
}while ((len = ifis.read(buffer)) }!= -1) {
protected static Integer[] serializePbData(String pbFilePath) throwsfor IOException(int {i = 0; i < len; i++) {
List<Integer> serializedData = new ArrayList<Integer>(); FileInputStream fis = new FileInputStream(pbFilePath serializedData.add(buffer[i] & 0xFF);
Integer[] data = null;}
}
fis.skip(16);
data InflaterInputStream ifis = serializedData.toArray(new InflaterInputStream(fisInteger[serializedData.size()]);
byte[] buffer = new byte[1024];ifis.close();
fis.close();
int len = -1; return data;
}
while ((len = ifis.read(buffer)) !=
-1) { private static class TimeoutProcessKiller extends TimerTask {
for (int i = 0; iprivate <Process len; i++) {p;
public TimeoutProcessKiller(Process p) {
serializedData.add(buffer[i] & 0xFF); this.p = p;
} }
} @Override
data = serializedData.toArray(new Integer[serializedData.size()]); public void run() {
ifis.close(); fisp.closedestroy();
return data;}
}
} |