import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import javajavax.io.File;
import java.io.FileInputStreamservlet.http.HttpServletRequest;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths*;
import java.util.*;
import java.util.zip.InflaterInputStream;
@Controller
public class ImportController {
static String ROOTDOC_UPLOAD_DIR_REL_PATH = "C:\\workspace\\synapEditorsample\\out\\artifacts\\synapEditorsample_war_exploded";
uploads" + File.separator + "docs";
static String DOCOUTPUT_DIR_UPLOADREL_DIRPATH = "uploads\\docs"; + File.separator + "output";
static
String OUTPUT_DIR = "uploads\\output";
@RequestMapping(value = "/importDoc", method = RequestMethod.POST)
@ResponseBody
public Map<String, Object> importDoc(HttpServletRequest request, @RequestParam("file") MultipartFile importFile)
throws IOException { throws IOException {
String fileNameROOT_ABS_PATH = importFile.getOriginalFilename(request.getSession().getServletContext().getRealPath("");
String uploadPath String UPLOAD_DIR_ABS_PATH = ROOT_ABS_PATH + File.separator + DOC_UPLOAD_DIR_REL_PATH;
makeDirectory(UPLOAD_DIR_ABS_PATH);
FileString uploadDirfileName = new File(uploadPathimportFile.getOriginalFilename();
String inputFileAbsPath if(!uploadDir.exists()) {
= UPLOAD_DIR_ABS_PATH + File.separator + fileName;
uploadDir.mkdirs(writeFile(inputFileAbsPath, importFile.getBytes());
// 파일별로 변환결과를 }저장할 경로 생성
Calendar byte[] bytes = new byte[0];
cal = Calendar.getInstance();
String yearMonth = try {
String.format("%04d%02d", cal.get(Calendar.YEAR), cal.get(Calendar.MONTH)+1);
String bytes = importFile.getBytesuuid = UUID.randomUUID().toString();
String worksDirAbsPath = ROOT_ABS_PATH }+ catch (IOException e) {
File.separator + OUTPUT_DIR_REL_PATH + File.separator + yearMonth + File.separator + uuid;
e.printStackTracemakeDirectory(worksDirAbsPath);
// 문서 변환
} executeConverter(inputFileAbsPath, worksDirAbsPath);
Path inputFilePath// = Paths.get(uploadPath + File.separator + fileName);
변환이 끝난 원본파일은 삭제한다.
deleteFile(inputFileAbsPath);
// try변환된 {pb파일을 읽어서 serialzie
// v2.3.0 부터 파일명이 Files.write(inputFilePath, bytes);
document.word.pb에서 document.pb로 변경됨
String pbAbsPath = worksDirAbsPath }+ catch (IOException e) {File.separator + "document.pb";
Integer[] serializedData = serializePbData(pbAbsPath);
e.printStackTrace();
// pb파일은 삭제
}
// v2.3.0 부터 파일명이 document.word.pb에서 document.pb로 변경됨
Calendar cal = Calendar.getInstance( deleteFile(pbAbsPath);
Map<String, Object> map String= yearMonth = String.format("%04d%02d", cal.get(Calendar.YEAR), cal.get(Calendar.MONTH)+1);
new HashMap<String, Object>();
map.put("serializedData", serializedData);
// 파일별로브라우저에서 변환결과를접근가능한 저장할경로를 경로importPath에 생성담아서 넘겨줍니다.
// OUTPUT_DIR_REL_PATH 경로에 String맞춰서 uuid = UUID.randomUUID().toString();
수정해야 합니다.
map.put("importPath", "uploads/output/" + yearMonth + File"/" worksDir+ =uuid);
new File(ROOT_PATH + File.separator + OUTPUT_DIR + File.separator + yearMonth + File.separator + uuid);
if(!worksDir.exists()) {
worksDir.mkdirs();
}
// 문서 변환
executeConverter(inputFilePath.toAbsolutePath().toString(), worksDir.getAbsolutePath());
// 변환이 끝난 원본파일은 삭제한다.
Files.delete(inputFilePath);
// 변환된 pb파일을 읽어서 serialzie
// v2.3.0 부터 파일명이 document.word.pb에서 document.pb로 변경됨
Integer[] serializedData = serializePbData(worksDir + File.separator + "document.pb");
// pb파일은 삭제
// v2.3.0 부터 파일명이 document.word.pb에서 document.pb로 변경됨
Files.delete(Paths.get(worksDir + File.separator + "document.pb"));
Map<String, Object> map = new HashMap<>();
map.put("serializedData", serializedData);
// 브라우저에서 접근가능한 경로를 importPath에 담아서 넘겨줍니다.
// OUTPUT_DIR 경로에 맞춰서 수정해야 합니다.
map.put("importPath", "uploads/output/" + yearMonth + "/" + uuid);
return map;
}
public static int executeConverter(String inputFilePath, String outputFilePath) {
return map;
}
/**
* 문서 변환 모듈을 실행합니다.
*/
public static int executeConverter(String inputFilePath, String outputFilePath) {
String SEDOC_CONVERTER_DIR = "/home/jyheo/me/git/Others/201806-teamstudy-python-django/sedocConverter"; // 절대경로
String FONT_DIR = SEDOC_CONVERTER_DIR + File.separator + "fonts";
String TEMP_DIR = SEDOC_CONVERTER_DIR + File.separator + "temp";
String SEDOC_CONVERTER_PATH = SEDOC_CONVERTER_DIR + File.separator + "sedocConverter_exe";
makeDirectory(TEMP_DIR);
makeDirectory(FONT_DIR);
// 변화 명령 구성
String[] cmd = {SEDOC_CONVERTER_PATH, "-f", FONT_DIR, inputFilePath, outputFilePath, TEMP_DIR};
try {
String SEDOC_CONVERT_DIRTimer t = "C:\\sedocConverter\\sedocConverter.exe";
new Timer();
StringProcess FONT_DIRproc = "C:\\sedocConverter\\sedocConverter\\fonts";
Runtime.getRuntime().exec(cmd);
StringTimerTask TEMP_DIRkiller = "C:\\sedocConverter\\sedocConverter\\tmp";
new TimeoutProcessKiller(proc);
File tempDir = new File(TEMP_DIR t.schedule(killer, 20000); // 20초 (변환이 20초 안에 완료되지 않으면 if(!tempDir.exists()) {
프로세스 종료)
int exitValue = tempDirproc.mkdirswaitFor();
}
killer.cancel();
File fontDir = new File(FONT_DIR)return exitValue;
} catch if(!fontDir.exists())(Exception e) {
fontDir.mkdirse.printStackTrace();
}
// 변화 명령 구성return -1;
}
}
/**
String[]* cmd문서 = {SEDOC_CONVERT_DIR, "-f", FONT_DIR, inputFilePath, outputFilePath, TEMP_DIR};
try {
Timer t = new Timer();
Process proc = Runtime.getRuntime().exec(cmd);
모듈 실행 후 변환된 결과를 Serialize 합니다.
*/
public static Integer[] serializePbData(String pbFilePath) throws IOException {
List<Integer> serializedData = new ArrayList<Integer>();
FileInputStream fis = null;
InflaterInputStream ifis = null;
Integer[] data = null;
try {
TimerTask killerfis = new TimeoutProcessKillerFileInputStream(procpbFilePath);
t.schedule(killer, 20000fis.skip(16);
//
20초 (변환이 20초 안에 완료되지 않으면 프로세스 종료) ifis = new InflaterInputStream(fis);
intbyte[] exitValuebuffer = proc.waitFor() new byte[1024];
killer.cancel()int len;
while ((len = ifis.read(buffer)) != return exitValue;
-1) {
} catch (Exception e) { for (int i = 0; i < e.printStackTrace();
len; i++) {
return -1; serializedData.add(buffer[i] & 0xFF);
} } }
public Integer[] serializePbData(String pbFilePath) throws IOException {
}
List<Integer> serializedDatadata = serializedData.toArray(new ArrayList<Integer>(Integer[serializedData.size()]);
} finally {
FileInputStream fis = new FileInputStream(pbFilePath); if (ifis != Integer[] data = null;null) ifis.close();
if (fis != null) fis.skipclose(16);
}
InflaterInputStream ifisreturn =data;
new InflaterInputStream(fis);
byte[] buffer = new byte[1024];
int len = -1;
while ((len = ifis.read(buffer)) != -1) {
}
/**
* 파일을 씁니다.
*/
private static void writeFile(String path, byte[] bytes) throws IOException {
OutputStream os = null;
try {
os = new FileOutputStream(path);
os.write(bytes);
for (int i =} 0;finally i{
< len; i++) { if (os != null) os.close();
}
}
serializedData.add(buffer[i] & 0xFF);
}
}
data = serializedData.toArray(new Integer[serializedData.size()]);
ifis.close();
fis.close();
/**
* 파일을 삭제합니다.
*/
private static void deleteFile(String path) {
new File(path).delete();
}
/**
* 디렉토리가 없는 경우 디렉토리를 생성합니다.
*/
private static void makeDirectory(String dirPath) {
File dir = new File(dirPath);
if (!dir.exists()) {
return datadir.mkdir();
}
}
private static class TimeoutProcessKiller extends TimerTask {
private Process p;
public TimeoutProcessKiller(Process p) {
this.p = p;
}
@Override
public void run() {
p.destroy();
}
}
} |