Skip to content

Commit

Permalink
Merge pull request #117 from yennanliu/warehouse-dev-003-add-report
Browse files Browse the repository at this point in the history
warehouse-dev-003-add-report : Minor fix
  • Loading branch information
yennanliu authored Nov 12, 2023
2 parents 96638f0 + 22f1a5a commit ed0a8ff
Show file tree
Hide file tree
Showing 15 changed files with 288 additions and 7 deletions.
14 changes: 14 additions & 0 deletions springWarehouse/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -179,6 +179,20 @@
<scope>test</scope>
</dependency>

<!-- time zone -->
<dependency>
<groupId>joda-time</groupId>
<artifactId>joda-time</artifactId>
<version>2.9.2</version>
</dependency>

<!-- json file IO -->
<dependency>
<groupId>com.googlecode.json-simple</groupId>
<artifactId>json-simple</artifactId>
<version>1.1.1</version>
</dependency>

</dependencies>

<build>
Expand Down
6 changes: 3 additions & 3 deletions springWarehouse/sql/ddl/download_status.sql
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,6 @@ CREATE TABLE IF NOT EXISTS download_status(

INSERT INTO download_status(download_url, status, create_time)
VALUES
("some_url", "pending", now()),
("some_url", "failed", now()),
("some_url", "completed", now());
("20231112-17-15-24_report.json", "pending", now()),
("20231112-17-15-24_report.json", "failed", now()),
("20231112-17-15-24_report.json", "completed", now());
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,10 @@
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yen.springWarehouse.bean.DownloadStatus;
import com.yen.springWarehouse.mapper.DownloadStatusMapper;
import com.yen.springWarehouse.service.DownloadStatusService;

import com.yen.springWarehouse.util.DateTimeUtils;
import com.yen.springWarehouse.util.FileUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
Expand All @@ -18,7 +20,11 @@
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
Expand All @@ -29,6 +35,12 @@ public class DownloadController {
@Autowired
DownloadStatusService downloadStatusService;

@Autowired
DownloadStatusMapper downloadStatusMapper;

String userDirectory = new File("").getAbsolutePath();
final String prefix = userDirectory + "/src/main/resources/report/";

@GetMapping("/list")
public String list(Map<String, Object> map, @RequestParam(value="pageNo", required=false, defaultValue="1") String pageNoStr) {

Expand All @@ -48,17 +60,52 @@ public String list(Map<String, Object> map, @RequestParam(value="pageNo", requir

log.info("iPage.total = {}, iPage.getPages = {} iPage = {}", iPage.getTotal(), iPage.getPages(), iPage);
map.put("page", iPage);

return "download/list_download";
}

@GetMapping("/create_report")
public String createDownload() {

DateTimeUtils dateTimeUtils = new DateTimeUtils();
String timestamp = dateTimeUtils.getCurrentDateYYYYMMDDHHMMSS();
FileUtil fileUtil = new FileUtil();

// create report
String fileName = timestamp + "_report.json";
Map<String, Object> map = new HashMap<>();
map.put("name", "king");
map.put("age", 17);
// save file to local // TODO : save it to remote file system (e.g. S3)
Boolean result = fileUtil.writeJsonFile(map, prefix + fileName);
if (result) {
DownloadStatus downloadStatus = new DownloadStatus();
downloadStatus.setStatus("completed");
downloadStatus.setDownloadUrl(fileName);
downloadStatus.setCreateTime(new Date());
log.info("save File OK");
// save to DB
downloadStatusService.save(downloadStatus);
} else {
log.info("save File failed");
}
return "download/success";
}

// TODO : fix : make GET request with report id
@GetMapping("/download_report")
public ResponseEntity<Resource> downloadFile() throws IOException {

// Load the file from the classpath (assuming it's in the resources/static directory)
Resource resource = new ClassPathResource("/test.json");
// Resource resource = new ClassPathResource("/test.json");
// HttpHeaders headers = new HttpHeaders();
// headers.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=test.json");

List<DownloadStatus> downloadStatusList = downloadStatusMapper.getAllDownloadStatus();
// TODO : fix below (currently only get 1st downloadStatus)
String downloadUrl = "/report/" + downloadStatusList.get(0).getDownloadUrl();
Resource resource = new ClassPathResource(downloadUrl);
HttpHeaders headers = new HttpHeaders();
headers.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=test.json");
headers.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=%s".format("test.json"));

return ResponseEntity.ok()
.headers(headers)
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
package com.yen.springWarehouse.util;


import org.joda.time.DateTime;
import org.joda.time.DateTimeZone;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.TimeZone;

public class DateTimeUtils {

public static SimpleDateFormat getFormatter(String formatPattern){
SimpleDateFormat formatter = new SimpleDateFormat(formatPattern);
return formatter;
}

public static String getCurrentDate(){
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
formatter.setTimeZone(TimeZone.getTimeZone("GMT"));
Date date = new Date();
String currentDate = formatter.format(date);
return currentDate;
}

public static String getCurrentDateYYYYMMDDHHMMSS(){
SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMdd-HH-mm-ss");
//formatter.setTimeZone(TimeZone.getTimeZone("GMT"));
Date date = new Date();
String currentDate = formatter.format(date);
return currentDate;
}

public static String getCurrentDateUTC(){
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
DateTime now = DateTime.now( DateTimeZone.UTC );
String currentDate = formatter.format(now);
return currentDate;
}

public static String getNDayBeforeDate(Integer dateBefore){
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
Calendar cal = Calendar.getInstance();
cal.add(Calendar.DATE, -1 * dateBefore);
String yesterday_date = dateFormat.format(cal.getTime());
return yesterday_date;
}

public static String getYesterdayDate(){
return getNDayBeforeDate(1);
}

public static String getYesterdayDateWithoutDash(){
return getYesterdayDate().replace("-", "");
}

public static String addDashToDateTime(String dateTime){

DateFormat fromFormat = new SimpleDateFormat("yyyyMMdd");
DateFormat toFormat = new SimpleDateFormat("yyyy-MM-dd");

Date d = null;
String d1 = null;

try {
d = fromFormat.parse(dateTime);
} catch (ParseException e) {
throw new RuntimeException(e);
}
d1 = toFormat.format(d);
return d1;
}

}

Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
package com.yen.springWarehouse.util;

import lombok.extern.slf4j.Slf4j;
import org.json.simple.JSONObject;

import java.io.BufferedOutputStream;
import java.io.DataOutputStream;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.util.Map;

@Slf4j
public class FileUtil {

public Boolean writeFile(String intputString, String fileName){

try{
String value = intputString; //"Hello";
FileOutputStream fos = new FileOutputStream(fileName);
DataOutputStream outStream = new DataOutputStream(new BufferedOutputStream(fos));
outStream.writeUTF(value);
outStream.close();
return true;
}catch (Exception e){
log.error("writeFile error : " + e);
return false;
}
}

// https://www.tutorialspoint.com/how-to-write-create-a-json-file-using-java
public Boolean writeJsonFile(Map<String, Object> map, String fileName){
try{
JSONObject jsonObject = new JSONObject();
// insert map to jsonObject
for (String key : map.keySet()){
jsonObject.put(key, map.get(key));
}
FileWriter file = new FileWriter(fileName);
file.write(jsonObject.toJSONString());
file.close();
return true;
}catch (Exception e){
log.error("writeJsonFile error : " + e);
return false;
}
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
{"name":"king","age":17}
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
{"name":"king","age":17}
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
{"name":"king","age":17}
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
{"name":"king","age":17}
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
{"name":"king","age":17}
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
{"name":"king","age":17}
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,11 @@
<body style="padding:8px;">
<h3 class="title">Report Download</h3>

<a href="/download/create_report">
<button class="create_report">Create Download</button>
</a>


<form action="" method="POST">
<input type="hidden" name="_method" value="DELETE"/>
</form>
Expand Down
13 changes: 13 additions & 0 deletions springWarehouse/src/main/resources/templates/download/success.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Create Download OK</title>
<link rel="stylesheet" type="text/css" th:href="@{/css/style.css}" />
</head>
<body style="padding:8px;">
<h3 class="title">Create Download OK</h3>

<script type="text/javascript" th:src="@{/js/jquery-3.1.1.min.js}"></script>
</body>
</html>
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
package com.yen.springWarehouse.controller;

import com.yen.springWarehouse.util.DateTimeUtils;
import org.junit.jupiter.api.Test;

import java.text.SimpleDateFormat;

import static org.junit.jupiter.api.Assertions.*;

class DownloadControllerTest {

@Test
public void testPrepareDownloadFile(){

String timeStamp = new SimpleDateFormat("yyyyMMdd-HH-mm-ss").format(new java.util.Date());
System.out.println(timeStamp);

System.out.println();

DateTimeUtils dateTimeUtils = new DateTimeUtils();
System.out.println(dateTimeUtils.getCurrentDateYYYYMMDDHHMMSS());
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
package com.yen.springWarehouse.util;

import com.yen.springWarehouse.controller.DownloadController;
import org.junit.jupiter.api.Test;

import java.io.File;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

import static org.junit.jupiter.api.Assertions.*;

class FileUtilTest {

@Test
public void testWriteJsonFile() throws URISyntaxException {

String userDirectory = new File("").getAbsolutePath();
System.out.println(">>> current path = " + userDirectory); // >>> crrent path = /Users/yennanliu/SpringPlayground/springWarehouse
String prefix = userDirectory + "/src/main/resources/report";

FileUtil fileUtil = new FileUtil();
String fileName = prefix + "/" + "test_output_2.json";
Map<String, Object> map = new HashMap<>();
map.put("name", "king");
map.put("age", 17);
Boolean result = fileUtil.writeJsonFile(map, fileName);
System.out.println("write json to : " + fileName);
System.out.println(result);
}

@Test
public void testWriteJsonFile2() throws URISyntaxException {

URL url = this.getClass().getResource("/report");
File parentDirectory = new File(new URI(url.toString()));

System.out.println("url = " + url);
System.out.println("url.getPath() = " + url.getPath());
System.out.println("parentDirectory = " + parentDirectory);

}

}

0 comments on commit ed0a8ff

Please sign in to comment.