[EDIT] MEJOR MANEJO DE SHEETS Y MULTI THREADS PARA EL SERVICIO DE EXCEL

parent a7b24dfd
...@@ -13,6 +13,8 @@ import org.springframework.web.bind.annotation.RestController; ...@@ -13,6 +13,8 @@ import org.springframework.web.bind.annotation.RestController;
import web.multitask.trismegistoservices.services.ExcelService; import web.multitask.trismegistoservices.services.ExcelService;
import web.multitask.trismegistoservices.utils.CommonUtils; import web.multitask.trismegistoservices.utils.CommonUtils;
import java.io.IOException;
@RestController @RestController
@CrossOrigin(origins = "*") @CrossOrigin(origins = "*")
@RequestMapping("excel") @RequestMapping("excel")
...@@ -23,9 +25,11 @@ public class ExcelApi { ...@@ -23,9 +25,11 @@ public class ExcelApi {
CommonUtils commonUtils; CommonUtils commonUtils;
@PostMapping("/public/generate") @PostMapping("/public/generate")
public ResponseEntity<?> generateExcel(@RequestBody String json) { public ResponseEntity<?> generateExcel(@RequestBody String json) throws IOException {
JSONObject jsonBody = new JSONObject(json); JSONObject jsonBody = new JSONObject(json);
byte[] excelByte = excelService.generateExcel(jsonBody); int size = json.getBytes().length;
System.out.println("Size: " + size);
byte[] excelByte = excelService.generateExcel(jsonBody,size);
if (jsonBody.optBoolean("base64", false)) { if (jsonBody.optBoolean("base64", false)) {
JSONObject response = new JSONObject(); JSONObject response = new JSONObject();
response.put("file_name", jsonBody.optString("file_name", "no_name.xlsx")); response.put("file_name", jsonBody.optString("file_name", "no_name.xlsx"));
......
...@@ -47,37 +47,39 @@ class JWTokenApi { ...@@ -47,37 +47,39 @@ class JWTokenApi {
@PostMapping("/validate") @PostMapping("/validate")
public ResponseEntity<?> validateToken(@RequestBody String token) { public ResponseEntity<?> validateToken(@RequestBody String token) {
JSONObject response;
JSONObject json = new JSONObject(token); JSONObject json = new JSONObject(token);
if (jwtTokenUtil.validateToken(json.getString("token"))) { JSONObject response = new JSONObject();
String dataToken = jwtTokenUtil.getDataToken(json.getString("token"));
if (dataToken == null) { if (!jwtTokenUtil.validateToken(json.getString("token"))) {
response = new JSONObject().put("message", "Invalid Token").put("status", false); response.put("message", "Invalid Token").put("status", false);
} else { return ResponseEntity.status(401).body(response.toMap());
boolean isTokenExpired = jwtTokenUtil.isTokenExpired(json.getString("token"));
if (isTokenExpired) {
response = new JSONObject().put("message", "Expired Token").put("status", false);
return ResponseEntity.status(403).body(response.toMap());
}
try {
UserDetails userDetails = userRepo.findByUsername(new JSONObject(dataToken).getString("username"));
if (userDetails.getUsername() == null) {
response = new JSONObject().put("message", "Invalid Token").put("status", false);
} else {
response = new JSONObject().put("message", "Valid Token").put("status", true);
}
} catch (Exception e) {
response = new JSONObject().put("message", "Invalid Token").put("status", false);
}
}
} else {
response = new JSONObject().put("message", "Invalid Token").put("status", false);
} }
if (response.getBoolean("status")) {
return ResponseEntity.ok(response.toMap()); String dataToken = jwtTokenUtil.getDataToken(json.getString("token"));
} else { if (dataToken == null) {
response.put("message", "Invalid Token").put("status", false);
return ResponseEntity.status(401).body(response.toMap());
}
boolean isTokenExpired = jwtTokenUtil.isTokenExpired(json.getString("token"));
if (isTokenExpired) {
response.put("message", "Expired Token").put("status", false);
return ResponseEntity.status(403).body(response.toMap());
}
try {
UserDetails userDetails = userRepo.findByUsername(new JSONObject(dataToken).getString("username"));
if (userDetails == null) {
response.put("message", "Invalid Token").put("status", false);
return ResponseEntity.status(401).body(response.toMap());
}
} catch (Exception e) {
response.put("message", "Invalid Token").put("status", false);
return ResponseEntity.status(401).body(response.toMap()); return ResponseEntity.status(401).body(response.toMap());
} }
response.put("message", "Valid Token").put("status", true);
return ResponseEntity.ok(response.toMap());
} }
@PostMapping("/service/authenticate") @PostMapping("/service/authenticate")
...@@ -96,7 +98,12 @@ class JWTokenApi { ...@@ -96,7 +98,12 @@ class JWTokenApi {
@PostMapping("/remaining") @PostMapping("/remaining")
public ResponseEntity<?> remainingTime(@RequestBody String token) { public ResponseEntity<?> remainingTime(@RequestBody String token) {
JSONObject json = new JSONObject(token); JSONObject json = new JSONObject(token);
return ResponseEntity.ok(new JSONObject().put("remaining", jwtTokenUtil.getExperyTime(json.getString("token"))).put("message", "OK").put("status", true).toMap()); try{
int remaining = jwtTokenUtil.getExperyTime(json.getString("token"));
return ResponseEntity.ok(new JSONObject().put("remaining", remaining).put("message", "OK").put("status", true).toMap());
} catch (Exception e) {
return ResponseEntity.status(401).body(new JSONObject().put("remaining", 0).put("message", "Invalid Token").put("status", false).toMap());
}
} }
} }
\ No newline at end of file
...@@ -48,6 +48,7 @@ public class SecurityConfig{ ...@@ -48,6 +48,7 @@ public class SecurityConfig{
.antMatchers(HttpMethod.GET, "/**").permitAll() .antMatchers(HttpMethod.GET, "/**").permitAll()
// .antMatchers(HttpMethod.POST, "/**").permitAll() // .antMatchers(HttpMethod.POST, "/**").permitAll()
.antMatchers("/token/**").permitAll()); .antMatchers("/token/**").permitAll());
// .anyRequest() // .anyRequest()
// .authenticated()); // .authenticated());
http.addFilterBefore(new JWTokenFilter(jwtTokenUtil, userRepo), UsernamePasswordAuthenticationFilter.class); http.addFilterBefore(new JWTokenFilter(jwtTokenUtil, userRepo), UsernamePasswordAuthenticationFilter.class);
......
...@@ -2,10 +2,14 @@ package web.multitask.trismegistoservices.services; ...@@ -2,10 +2,14 @@ package web.multitask.trismegistoservices.services;
import java.awt.Color; import java.awt.Color;
import java.io.ByteArrayOutputStream; import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.HashMap; import java.util.HashMap;
import java.util.List; import java.util.List;
import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletableFuture;
import java.util.concurrent.atomic.AtomicReference;
import java.util.stream.IntStream;
import org.apache.poi.ss.usermodel.*; import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFCell; import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFCellStyle; import org.apache.poi.xssf.usermodel.XSSFCellStyle;
...@@ -24,51 +28,120 @@ import org.springframework.stereotype.Service; ...@@ -24,51 +28,120 @@ import org.springframework.stereotype.Service;
@Service @Service
public class ExcelService { public class ExcelService {
List<String> stylesSaved = new ArrayList<>(); public byte[] generateExcel(JSONObject json,int size) throws IOException {
List<XSSFCellStyle> styleObjectsSaved = new ArrayList<>();
public byte[] generateExcel(JSONObject json) {
ByteArrayOutputStream outByteStream = new ByteArrayOutputStream(); ByteArrayOutputStream outByteStream = new ByteArrayOutputStream();
XSSFWorkbook workbook = new XSSFWorkbook(); XSSFWorkbook workbook = new XSSFWorkbook();
createSheet(workbook, json); createSheet(workbook, json,size);
try { try {
workbook.write(outByteStream); workbook.write(outByteStream);
workbook.close(); workbook.close();
return outByteStream.toByteArray(); return outByteStream.toByteArray();
} catch (Exception e) { } catch (Exception e) {
workbook.close();
System.out.println(e.getMessage()); System.out.println(e.getMessage());
return null; return null;
} }
} }
@Async public void createSheet(XSSFWorkbook workbook, JSONObject json, int sizeOfBytes) {
public void createSheet(XSSFWorkbook workbook, JSONObject json) { AtomicReference<List<CompletableFuture<Boolean>>> results = new AtomicReference<>(new ArrayList<>());
styleObjectsSaved.clear();
stylesSaved.clear();
List<CompletableFuture<Boolean>> results = new ArrayList<>();
if (json.optJSONArray("sheetArray", new JSONArray()).isEmpty()) { if (json.optJSONArray("sheetArray", new JSONArray()).isEmpty()) {
XSSFSheet sheet = workbook.createSheet(json.optString("sheet_name", "no_name")); XSSFSheet sheet = workbook.createSheet(json.optString("sheet_name", "no_name"));
buildSheet(workbook, sheet, json); buildSheet(workbook, sheet, json);
}else{ for (int i = 0; i < json.getJSONArray("identifiers").length(); i++) {
sheet.setColumnWidth(i, 16 * 512);
}
} else {
JSONArray sheetArray = json.optJSONArray("sheetArray", new JSONArray()); JSONArray sheetArray = json.optJSONArray("sheetArray", new JSONArray());
sheetArray.toList().stream().parallel().forEach(sheetObject -> { if (sizeOfBytes < 100000) {
HashMap<String, Object> sheetMap = (HashMap<String, Object>) sheetObject; for (int i = 0; i < sheetArray.length(); i++) {
JSONObject jsonObject = new JSONObject(sheetMap); JSONObject jsonObject = sheetArray.getJSONObject(i);
XSSFSheet sheet = workbook.createSheet(jsonObject.optString("sheet_name", "no_name")); XSSFSheet sheet = workbook.createSheet(jsonObject.optString("sheet_name", "no_name"));
JSONArray identifiers = jsonObject.getJSONArray("identifiers"); JSONArray identifiers = jsonObject.getJSONArray("identifiers");
for (int j = 0; j < identifiers.length(); j++) { for (int j = 0; j < identifiers.length(); j++) {
sheet.setColumnWidth(j, 16* 512); sheet.setColumnWidth(j, 16 * 512);
}
buildSheet(workbook, sheet, jsonObject);
}
} else {
XSSFSheet[] sheets = new XSSFSheet[sheetArray.length()];
for (int i = 0; i < sheetArray.length(); i++) {
JSONObject jsonObject = sheetArray.getJSONObject(i);
sheets[i] = workbook.createSheet(jsonObject.optString("sheet_name", "no_name"));
}
IntStream.range(0, sheetArray.length()).parallel().forEach(i -> {
JSONObject jsonObject = sheetArray.getJSONObject(i);
JSONArray identifiers = jsonObject.getJSONArray("identifiers");
for (int j = 0; j < identifiers.length(); j++) {
sheets[i].setColumnWidth(j, 16 * 512);
}
CompletableFuture<Boolean> result = buildSheetAsync(workbook, sheets[i], jsonObject);
results.get().add(result);
});
// sheetArray.toList().stream().parallel().forEach(sheetObject -> {
// HashMap<String, Object> sheetMap = (HashMap<String, Object>) sheetObject;
// JSONObject jsonObject = new JSONObject(sheetMap);
// JSONArray identifiers = jsonObject.getJSONArray("identifiers");
// for (int j = 0; j < identifiers.length(); j++) {
// sheets[i].setColumnWidth(j, 16 * 512);
// }
// CompletableFuture<Boolean> result = buildSheetAsync(workbook, sheets[i], jsonObject);
// results.get().add(result);
// });
CompletableFuture.allOf(results.get().toArray(new CompletableFuture[0])).join();
}
}
}
public void buildSheet(XSSFWorkbook workbook, XSSFSheet sheet, JSONObject json) {
final XSSFCellStyle defaultStyle = createCellStyle(workbook, new JSONObject());
List<String> stylesSaved = new ArrayList<>();
List<XSSFCellStyle> styleObjectsSaved = new ArrayList<>();
XSSFRow row;
XSSFCell cell;
XSSFCellStyle cellStyle;
JSONArray identifiers = json.optJSONArray("identifiers", new JSONArray());
JSONArray data = json.optJSONArray("data", new JSONArray());
JSONArray styles = json.optJSONArray("styles", new JSONArray());
fillStylesArray(styles,workbook,stylesSaved,styleObjectsSaved);
for (int i = 0; i < data.length(); i++) {
row = sheet.createRow(i);
JSONObject row_data = data.optJSONObject(i);
for (int j = 0; j < identifiers.length(); j++) {
cell = row.createCell(j);
JSONArray styleArray = styles.optJSONArray(i, new JSONArray());
JSONObject style = styleArray.optJSONObject(j, new JSONObject());
if(style.isEmpty()){
cell.setCellStyle(defaultStyle);
}else{
if(!stylesSaved.contains(style.toString())){
stylesSaved.add(style.toString());
cellStyle = createCellStyle(workbook,style);
cell.setCellStyle(cellStyle);
styleObjectsSaved.add(cellStyle);
}else{
cell.setCellStyle(styleObjectsSaved.get(stylesSaved.indexOf(style.toString())));
}
} }
CompletableFuture<Boolean> result = buildSheet(workbook, sheet, jsonObject); cell.setCellValue(row_data.optString(identifiers.optString(j, "")));
results.add(result); }
});
} }
} }
@Async @Async
public CompletableFuture<Boolean> buildSheet(XSSFWorkbook workbook, XSSFSheet sheet, JSONObject json) { public CompletableFuture<Boolean> buildSheetAsync(XSSFWorkbook workbook, XSSFSheet sheet, JSONObject json) {
final XSSFCellStyle defaultStyle = createCellStyle(workbook, new JSONObject()); final XSSFCellStyle defaultStyle = createCellStyle(workbook, new JSONObject());
List<String> stylesSaved = new ArrayList<>();
List<XSSFCellStyle> styleObjectsSaved = new ArrayList<>();
XSSFRow row; XSSFRow row;
XSSFCell cell; XSSFCell cell;
...@@ -116,7 +189,7 @@ public class ExcelService { ...@@ -116,7 +189,7 @@ public class ExcelService {
XSSFCellStyle style = workbook.createCellStyle(); XSSFCellStyle style = workbook.createCellStyle();
Font font = workbook.createFont(); Font font = workbook.createFont();
style.setAlignment( align.equals("center") ? HorizontalAlignment.CENTER : align.equals("left") ? HorizontalAlignment.LEFT : HorizontalAlignment.RIGHT); style.setAlignment( align.equals("center") ? HorizontalAlignment.CENTER : align.equals("left") ? HorizontalAlignment.LEFT : HorizontalAlignment.RIGHT);
style.setWrapText(false); style.setWrapText(styleJson.optBoolean("wrapText", false));
style.setVerticalAlignment(VerticalAlignment.CENTER); style.setVerticalAlignment(VerticalAlignment.CENTER);
style.setFillPattern(FillPatternType.SOLID_FOREGROUND); style.setFillPattern(FillPatternType.SOLID_FOREGROUND);
style.setBorderBottom(BorderStyle.THIN); style.setBorderBottom(BorderStyle.THIN);
......
...@@ -69,12 +69,12 @@ public class JWTokenUtil implements Serializable{ ...@@ -69,12 +69,12 @@ public class JWTokenUtil implements Serializable{
} }
public int getExperyTime(String token){ public int getExperyTime(String token){
return (int) ((Jwts.parserBuilder() return (int) ((Jwts.parserBuilder()
.setSigningKey(Keys.hmacShaKeyFor(jwtSecret.getBytes())) .setSigningKey(Keys.hmacShaKeyFor(jwtSecret.getBytes()))
.build() .build()
.parseClaimsJws(token) .parseClaimsJws(token)
.getBody() .getBody()
.getExpiration() .getExpiration()
.getTime() - new Date().getTime())); .getTime() - new Date().getTime()));
} }
} }
\ No newline at end of file
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment