// til 만들기
@Override
public String createTIL(TILCreateReq tILCreateReq) {
String gitLink = "";
String gitLink2 = "";
String pixelaId = tILCreateReq.getId().toLowerCase();
// user id로 user 정보 얻어오기
User user = userRepository.getUsersById(tILCreateReq.getId()).get();
String repoName = user.getRepo();
String personalAccessToken = user.getPat();
// mission uid로 dir 정보 얻어오기
Mission mission = missionRepository.findMissionByUid(tILCreateReq.getMissionUid());
MissionDirRes mdr = MissionDirRes.of(mission);
String dir = (mdr.getPlanetName() + "/" + mdr.getSatellitesName()).replace(" ", "_");
String fileName = (tILCreateReq.getFileName()).replace(" ", "_");
//////// 파일 변환 시작
String filePath = "./json/testDir/"; // 파일 경로
File file1 = new File(filePath + "document.html");
File file2 = new File(filePath + "Output.md");
// 이전에 파일이 있다면 삭제하기
if (file1.exists() || file2.exists()) {
if (file1.delete() && file2.delete()) {
System.out.println("파일삭제 성공");
} else {
System.out.println("파일삭제 실패");
}
}
// 사용자가 입력한 content
String content = tILCreateReq.getContent();
// 전달 받은 내용(html)으로 파일 생성하기
FileWriter fw;
try {
fw = new FileWriter(filePath + "document.html");
fw.write(content);
fw.close();
} catch (IOException e) {
e.printStackTrace();
}
// html to markdown
Document doc;
try {
doc = new Document(filePath + "document.html");
doc.save(filePath + "Output.md");
} catch (Exception e1) {
e1.printStackTrace();
}
// markdown 파일 입력받기
byte[] binary = getFileBinary(filePath + "Output.md");
// markdown to base64
String base64data = Base64.getEncoder().encodeToString(binary);
//////// 파일 변환 끝
// git API 사용, til 작성하기
try {
URL url = new URL("https://api.github.com/repos/" + tILCreateReq.getId() + "/" + repoName + "/contents/"
+ URLEncoder.encode(dir, "UTF-8") + "/" + URLEncoder.encode(fileName, "UTF-8"));
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("PUT"); // http 메서드
conn.setRequestProperty("Authorization", "Bearer " + personalAccessToken); // header의 auth 정보
conn.setRequestProperty("Accept", "application/vnd.github+json");
conn.setRequestProperty("Content-Type", "application/json;utf-8");
conn.setDoInput(true);
conn.setDoOutput(true); // 서버로부터 받는 값이 있다면 true
JSONObject object = new JSONObject();
object.put("message", tILCreateReq.getMessage());
object.put("content", base64data);
String jsonInputString = object.toString();
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(conn.getOutputStream()));
bw.write(jsonInputString); // 버퍼에 담기
bw.flush(); // 버퍼에 담긴 데이터 전달
BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line = "";
StringBuilder sb = new StringBuilder();
while ((line = br.readLine()) != null) { // 읽을 수 있을 때 까지 반복
sb.append(line);
}
JSONObject json = new JSONObject(sb.toString()); // json으로 변경 (역직렬화)
JSONObject info = json.getJSONObject("content");
JSONObject link = info.getJSONObject("_links");
gitLink = (String) link.get("html");
gitLink2 = URLDecoder.decode(gitLink, "UTF-8");
// db에 til 저장
TIL til = new TIL();
til.setAddress(gitLink2);
til.setMission(mission);
til.setUser(user);
til.setFileName(fileName);
// 경험치 + 5
user.addExp(user.getExp());
userRepository.save(user);
tilRepository.save(til);
} catch (Exception e) {
System.err.println(e);
return gitLink2;
}
boolean isSuccess = false;
int i = 0; // 이거 나중에 지우삼
// pixela update 하기
while (!isSuccess) {
isSuccess = updatePixela(pixelaId);
}
return gitLink2;
}
// 파일 읽어드리는 함수
private static byte[] getFileBinary(String filePath) {
File file = new File(filePath);
byte[] data = new byte[(int) file.length()];
try (FileInputStream stream = new FileInputStream(file)) {
stream.read(data, 0, data.length);
} catch (Throwable e) {
e.printStackTrace();
}
return data;
}
배포하면 jar파일로 빌드 됨
→ 검색해보니까 로컬에서 사용하던 경로를 그대로 사용하면 안되는 것 같음,
(jar로 빌드되면서 구조가 바뀜???)
질문 1 : jar 파일 경로는 어떻게 구하나여????????????
질문 2 : back jar내부에 파일을 지우고 다시 쓸 수 있나요??
현재 흐름으로는 생성되는 html, md 파일명을 똑같이 되게끔 해놨음
→ 새로 til 작성하면 파일 삭제, 생성을 반복