[ADD] SE AGREGO SERVICIO DE DRIVE Y SE OPTIMIZO LOS METODOS DE MUCHOS SERVICIOS

parent 43368e71
......@@ -2,10 +2,6 @@ package web.multitask.trismegistoservices;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.core.task.TaskExecutor;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
@SpringBootApplication
public class AppApplication {
......@@ -14,15 +10,4 @@ public class AppApplication {
SpringApplication.run(AppApplication.class, args);
}
// @Bean("threadPoolTaskExecutor")
// TaskExecutor asyncExecutor() {
// ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
// executor.setCorePoolSize(10);
// executor.setMaxPoolSize(1000);
// executor.setQueueCapacity(500);
// executor.setThreadNamePrefix("AsyncThread-");
// executor.initialize();
// return executor;
// }
}
\ No newline at end of file
package web.multitask.trismegistoservices.api;
import lombok.AllArgsConstructor;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.http.ResponseEntity;
......@@ -10,23 +11,19 @@ import web.multitask.trismegistoservices.repository.UserRespository;
@RestController
@CrossOrigin("*")
@RequestMapping("/api")
@AllArgsConstructor
public class AppApi {
final ProcedureMysql procedureMysql;
final UserRespository userRepo;
public AppApi(ProcedureMysql procedureMysql, UserRespository userRepo) {
this.procedureMysql = procedureMysql;
this.userRepo = userRepo;
}
@PostMapping("/private/procedure")
public ResponseEntity<?> callProcedure(@RequestBody String body) {
JSONObject json = new JSONObject(body);
if (json.has("procedure")) {
try {
JSONArray params = json.isNull("params") ? new JSONArray() : json.getJSONArray("params");
JSONObject response = procedureMysql.ProcedureExecution(json.getString("procedure"),json.getString("database"), params.toList().toArray());
JSONObject response = procedureMysql.ProcedureExecution(json.getString("procedure"), json.getString("database"), params.toList().toArray());
return ResponseEntity.ok(response.toMap());
} catch (Exception e) {
return ResponseEntity.internalServerError().body(new JSONObject().put("message", e.getMessage()).put("status", false).toMap());
......@@ -37,7 +34,7 @@ public class AppApi {
}
@GetMapping("/private/users")
public ResponseEntity<?> getUsers (){
public ResponseEntity<?> getUsers() {
return ResponseEntity.ok(new JSONObject().put("data", userRepo.findAll()).put("message", "Success").put("status", true).toMap());
}
......
......@@ -14,12 +14,12 @@ import java.io.InputStreamReader;
@RequestMapping("console")
public class ConsoleApi {
@PostMapping("/public/command")
public ResponseEntity<?> pull(@RequestBody String jsonBody) {
public ResponseEntity<?> pull(@RequestBody String jsonBody) {
JSONObject json = new JSONObject(jsonBody);
String command = json.optString("command","");
if(json.optBoolean("sudo",false)){
command = "echo '"+json.optString("password","")+"' | sudo -S "+command;
String command = json.optString("command", "");
if (json.optBoolean("sudo", false)) {
command = "echo '" + json.optString("password", "") + "' | sudo -S " + command;
}
try {
ProcessBuilder processBuilder = new ProcessBuilder("bash", "-c", command)
......@@ -37,8 +37,8 @@ public class ConsoleApi {
int exitCode = process.waitFor();
return ResponseEntity.ok(
"Exit Code: " + exitCode + "\n" +
output.toString());
"Exit Code: " + exitCode + "\n" +
output.toString());
} catch (IOException | InterruptedException e) {
throw new RuntimeException(e);
}
......
package web.multitask.trismegistoservices.api;
import kotlin.ParameterName;
import lombok.AllArgsConstructor;
import org.json.JSONObject;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import web.multitask.trismegistoservices.model.DriveRequest;
import web.multitask.trismegistoservices.services.DriveService;
import javax.annotation.Nullable;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@RestController
@CrossOrigin(origins = "*")
@RequestMapping("drive")
@AllArgsConstructor
public class DriveApi {
DriveService driveService;
public DriveApi(DriveService driveService) {
this.driveService = driveService;
}
@PostMapping(path = "/public/upload", consumes = { MediaType.MULTIPART_FORM_DATA_VALUE })
public ResponseEntity<?> uploadFile(@ModelAttribute DriveRequest request) {
String folder_id = request.getFolder_id();
String file_name = request.getFile_name();
// String base64_name = request.getBase64_name();
// String base64_file = request.getBase64_file();
MultipartFile file = request.getFile();
String responseDrive = driveService.uploadFile(folder_id, file_name, file, new JSONObject());
JSONObject response = new JSONObject();
if(responseDrive == null){
response.put("status", "error");
response.put("message", "Error al subir el archivo");
return ResponseEntity.badRequest().body(response.toMap());
}else{
response.put("status", "success");
response.put("message", "Archivo subido correctamente");
response.put("file_id", responseDrive);
return ResponseEntity.ok(response.toMap());
}
}
DriveService driveService;
@PostMapping(path = "/public/upload", consumes = {MediaType.MULTIPART_FORM_DATA_VALUE})
public ResponseEntity<?> uploadFile(@ModelAttribute DriveRequest request) {
String folder_id = request.getFolder_id();
String file_name = request.getFile_name();
MultipartFile file = request.getFile();
String responseDrive = driveService.uploadFile(folder_id, file_name, file, new JSONObject());
JSONObject response = new JSONObject();
if (responseDrive == null) {
response.put("status", false);
response.put("message", "Error al subir el archivo");
return ResponseEntity.badRequest().body(response.toMap());
} else {
response.put("status", true);
response.put("message", "Archivo subido correctamente");
response.put("file_id", responseDrive);
return ResponseEntity.ok(response.toMap());
}
}
@GetMapping(path = "/public/download/{id}")
public ResponseEntity<?> downloadFile(@PathVariable String id, @Nullable @RequestParam(name = "base64") Boolean base64) {
if(base64 == null) base64 = false;
return driveService.getFile(id, base64);
}
}
\ No newline at end of file
package web.multitask.trismegistoservices.api;
import java.io.File;
import java.io.IOException;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.io.FileUtils;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import lombok.AllArgsConstructor;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import web.multitask.trismegistoservices.services.ExcelService;
import web.multitask.trismegistoservices.utils.CommonUtils;
@RestController
@CrossOrigin(origins = "*")
@RequestMapping("excel")
@AllArgsConstructor
public class ExcelApi {
@Autowired
ExcelService excelService;
CommonUtils commonUtils;
@PostMapping("/public/generate")
public ResponseEntity<?> generateExcel(HttpServletResponse response,@RequestBody String json) {
JSONObject jsonObject = new JSONObject(json);
byte[] excelByte = excelService.generateExcel(jsonObject);
// excelByte to InputStreamResource
File file = new File(System.getProperty("java.io.tmpdir") + "/excel.xlsx");
try {
FileUtils.writeByteArrayToFile(file, excelByte);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
public ResponseEntity<?> generateExcel(@RequestBody String json) {
JSONObject jsonBody = new JSONObject(json);
byte[] excelByte = excelService.generateExcel(jsonBody);
if (jsonBody.optBoolean("base64", false)) {
JSONObject response = new JSONObject();
response.put("file_name", jsonBody.optString("file_name", "no_name.xlsx"));
response.put("base64", commonUtils.byteToBase64(excelByte));
response.put("message", "OK");
response.put("status", true);
return ResponseEntity.ok().body(response.toMap());
} else {
Resource resource = excelService.convertByteToResource(excelByte, jsonBody.optString("file_name", "no_name.xlsx"));
HttpHeaders headers = new HttpHeaders();
headers.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=" + jsonBody.optString("file_name", "no_name.xlsx"));
return ResponseEntity.ok()
.headers(headers)
.contentLength(excelByte.length)
.body(resource);
}
Resource resource = excelService.convertByteToResource(excelByte, jsonObject.optString("file_name", "no_name.xlsx"));
return ResponseEntity.ok().body(resource);
}
}
\ No newline at end of file
package web.multitask.trismegistoservices.api;
import lombok.AllArgsConstructor;
import org.json.JSONObject;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.userdetails.UserDetails;
......@@ -8,8 +9,10 @@ import org.springframework.web.bind.annotation.*;
import web.multitask.trismegistoservices.model.User;
import web.multitask.trismegistoservices.repository.UserRespository;
import web.multitask.trismegistoservices.utils.JWTokenUtil;
import java.math.BigInteger;
import java.util.Objects;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
......@@ -17,30 +20,26 @@ import org.springframework.web.bind.annotation.RequestBody;
@RestController
@RequestMapping("/token")
@CrossOrigin
@AllArgsConstructor
class JWTokenApi {
private final JWTokenUtil jwtTokenUtil;
private final UserRespository userRepo;
public JWTokenApi(JWTokenUtil jwtTokenUtil, UserRespository userRepo) {
this.jwtTokenUtil = jwtTokenUtil;
this.userRepo = userRepo;
}
@PostMapping("/authenticate")
public ResponseEntity<?> createAuthenticationToken(@RequestBody String authenticationRequest) {
JSONObject response;
JSONObject json = new JSONObject(authenticationRequest);
String username = json.getString("username");
try{
UserDetails userDetails = userRepo.findByUsername(username);
if (!Objects.equals(userDetails.getPassword(), json.getString("password"))) {
response = new JSONObject().put("token", "").put("message", "Invalid Credentials").put("status", false);
return ResponseEntity.status(401).body(response.toMap());
} else {
return ResponseEntity.ok(new JSONObject().put("token", jwtTokenUtil.generateToken((User) userDetails, json.optBigInteger("ms", BigInteger.valueOf(3600000)))).put("message", "Generated").put("status", true).toMap());
}
}catch (Exception e){
try {
UserDetails userDetails = userRepo.findByUsername(username);
if (!Objects.equals(userDetails.getPassword(), json.getString("password"))) {
response = new JSONObject().put("token", "").put("message", "Invalid Credentials").put("status", false);
return ResponseEntity.status(401).body(response.toMap());
} else {
return ResponseEntity.ok(new JSONObject().put("token", jwtTokenUtil.generateToken((User) userDetails, json.optBigInteger("ms", BigInteger.valueOf(3600000)))).put("message", "Generated").put("status", true).toMap());
}
} catch (Exception e) {
response = new JSONObject().put("token", "").put("message", "Invalid Credentials").put("status", false);
return ResponseEntity.status(401).body(response.toMap());
}
......
package web.multitask.trismegistoservices.api;
import org.json.JSONObject;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import lombok.AllArgsConstructor;
import web.multitask.trismegistoservices.services.PDFService;
import web.multitask.trismegistoservices.utils.CommonUtils;
@RestController
@CrossOrigin(origins = "*")
@RequestMapping("/pdf")
@AllArgsConstructor
public class PDFApi {
PDFService pdfService;
public PDFApi(PDFService pdfService) {
this.pdfService = pdfService;
}
CommonUtils commonUtils;
@PostMapping("/public/html")
public ResponseEntity<?> htmlToPdf(@RequestBody String json) {
try {
JSONObject bodyJson = new JSONObject(json);
HttpHeaders headers = new HttpHeaders();
headers.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=" + bodyJson.getString("name"));
ByteArrayResource resource = pdfService.htmlToPdf(bodyJson.getString("html"));
MediaType mediaType = org.springframework.http.MediaType.APPLICATION_PDF;
if (mediaType != null) {
return ResponseEntity.ok().headers(headers)
.contentLength(resource.contentLength())
.contentType(mediaType)
.body(resource);
} else {
return ResponseEntity.badRequest().body("Error");
JSONObject jsonBody = new JSONObject(json);
byte[] bytes = pdfService.generatePdf(jsonBody.getString("html"));
if(jsonBody.optBoolean("base64")){
String base64 = commonUtils.byteToBase64(bytes);
return ResponseEntity.ok().body(
new JSONObject()
.put("base64", base64)
.put("file_name", jsonBody.optString("file_name", "pdf.pdf"))
.put("status", true)
.put("message", "OK")
);
}else{
Resource resource = commonUtils.byteToResource(bytes, jsonBody.optString("file_name", "no_name.pdf"));
HttpHeaders headers = new HttpHeaders();
headers.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=" + jsonBody.optString("file_name", "no_name.pdf"));
return ResponseEntity.ok()
.headers(headers)
.contentLength(bytes.length)
.contentType(MediaType.APPLICATION_PDF)
.body(resource);
}
}catch (Exception e){
System.out.println(e);
......
package web.multitask.trismegistoservices.config;
import lombok.AllArgsConstructor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.authentication.configuration.AuthenticationConfiguration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
......@@ -23,29 +23,20 @@ import web.multitask.trismegistoservices.utils.JWTokenUtil;
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@AllArgsConstructor
public class SecurityConfig{
private final UserRespository userRepo;
private final JWTokenUtil jwtTokenUtil;
public SecurityConfig(UserRespository userRepo, JWTokenUtil jwtTokenUtil) {
this.userRepo = userRepo;
this.jwtTokenUtil = jwtTokenUtil;
}
@Bean
AuthenticationManager authenticationManager(AuthenticationConfiguration authenticationConfiguration)
throws Exception {
return authenticationConfiguration.getAuthenticationManager();
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userRepo::findByUsername);
}
@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
SecurityFilterChain configure(HttpSecurity http) throws Exception {
http.cors(AbstractHttpConfigurer::disable).csrf(AbstractHttpConfigurer::disable)
.sessionManagement(management -> management.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
.authorizeHttpRequests(
......@@ -60,6 +51,7 @@ public class SecurityConfig extends WebSecurityConfigurerAdapter {
// .anyRequest()
// .authenticated());
http.addFilterBefore(new JWTokenFilter(jwtTokenUtil, userRepo), UsernamePasswordAuthenticationFilter.class);
return http.build();
}
@Bean
......
......@@ -5,8 +5,6 @@ import org.springframework.messaging.handler.annotation.DestinationVariable;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.handler.annotation.SendTo;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestParam;
import web.multitask.trismegistoservices.model.Message;
import web.multitask.trismegistoservices.model.Response;
......
......@@ -14,7 +14,6 @@ import org.springframework.stereotype.Component;
import org.springframework.util.LinkedMultiValueMap;
import web.multitask.trismegistoservices.repository.UserRespository;
import web.multitask.trismegistoservices.utils.JWTokenUtil;
import java.util.Objects;
@Component
......@@ -34,7 +33,6 @@ public class AuthChannelInterceptorAdapter implements ChannelInterceptor {
assert accessor != null;
if (StompCommand.CONNECT == accessor.getCommand()) {
// final String authorization = Objects.requireNonNull(accessor.getHeader("nativeHeaders")).toString();
LinkedMultiValueMap<String, String> map = (LinkedMultiValueMap<String, String>) accessor.getHeader("nativeHeaders");
String authorization = Objects.requireNonNull(Objects.requireNonNull(map).get("Authorization")).get(0);
assert authorization != null;
......
......@@ -5,6 +5,8 @@ import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import lombok.AllArgsConstructor;
import lombok.NoArgsConstructor;
import org.jetbrains.annotations.NotNull;
import org.json.JSONObject;
import org.springframework.core.annotation.Order;
......@@ -22,20 +24,13 @@ import web.multitask.trismegistoservices.utils.JWTokenUtil;
@Component
@Order(1)
@AllArgsConstructor
@NoArgsConstructor
public class JWTokenFilter extends OncePerRequestFilter {
private JWTokenUtil jwtTokenUtil = null;
private UserRespository userRepo = null;
public JWTokenFilter(JWTokenUtil jwtTokenUtil, UserRespository userRepo) {
this.jwtTokenUtil = jwtTokenUtil;
this.userRepo = userRepo;
}
public JWTokenFilter() {
}
@Override
protected void doFilterInternal(HttpServletRequest request, @NotNull HttpServletResponse response, @NotNull FilterChain chain)
throws ServletException, IOException, java.io.IOException {
......
......@@ -2,13 +2,16 @@
package web.multitask.trismegistoservices.interfaces;
import org.json.JSONObject;
import org.springframework.http.ResponseEntity;
import org.springframework.web.multipart.MultipartFile;
import java.io.OutputStream;
public interface IDriveService {
String uploadFile(String folder_id, String file_name, MultipartFile file, JSONObject base64);
String createFolder(String folder_id, String folder_name);
String deleteFile(String file_id);
String deleteFolder(String folder_id);
String getFile(String file_id);
ResponseEntity<?> getFile(String file_id,Boolean base64);
String getFolder(String folder_id);
}
}
\ No newline at end of file
package web.multitask.trismegistoservices.model;
import org.springframework.web.multipart.MultipartFile;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
......
......@@ -2,7 +2,6 @@ package web.multitask.trismegistoservices.model;
import org.json.JSONObject;
import org.springframework.web.multipart.MultipartFile;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
......
package web.multitask.trismegistoservices.services;
import java.io.ByteArrayInputStream;
import java.io.*;
import java.util.Collections;
import lombok.AllArgsConstructor;
import org.json.JSONObject;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
......@@ -12,15 +17,14 @@ import com.google.api.services.drive.model.File;
import web.multitask.trismegistoservices.config.GoogleConfig;
import web.multitask.trismegistoservices.interfaces.IDriveService;
import web.multitask.trismegistoservices.utils.CommonUtils;
@Service
@AllArgsConstructor
public class DriveService implements IDriveService {
private final GoogleConfig googleConfig;
public DriveService(GoogleConfig googleConfig) {
this.googleConfig = googleConfig;
}
private final CommonUtils commonUtils;
@Override
public String uploadFile(String folder_id, String file_name, MultipartFile file, JSONObject base64) {
......@@ -44,6 +48,43 @@ public class DriveService implements IDriveService {
}
@Override
public ResponseEntity<?> getFile(String file_id, Boolean base64) {
try {
File file = googleConfig.getDrive().files().get(file_id).execute();
InputStream inputStream = googleConfig.getDrive().files().get(file_id).executeMediaAsInputStream();
java.io.File tempFile = new java.io.File(System.getProperty("java.io.tmpdir") + "/temp." + file.getName().split("\\.")[1]);
tempFile.deleteOnExit();
try (FileOutputStream fos = new FileOutputStream(tempFile)) {
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = inputStream.read(buffer)) != -1) {
fos.write(buffer, 0, bytesRead);
}
}
if (base64) {
String base64String = commonUtils.fileToBase64(tempFile);
return ResponseEntity.ok().body(
new JSONObject()
.put("base64", base64String)
.put("file_name", file.getName())
.put("status", true)
.put("message", "OK").toMap()
);
} else {
Resource resource = commonUtils.fileToResource(tempFile);
HttpHeaders headers = new HttpHeaders();
headers.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=" + file.getName());
return ResponseEntity.ok()
.headers(headers)
.contentLength(tempFile.length())
.body(resource);
}
} catch (IOException e) {
throw new RuntimeException(e);
}
}
@Override
public String createFolder(String folder_id, String folder_name) {
// TODO Auto-generated method stub
throw new UnsupportedOperationException("Unimplemented method 'createFolder'");
......@@ -62,12 +103,6 @@ public class DriveService implements IDriveService {
}
@Override
public String getFile(String file_id) {
// TODO Auto-generated method stub
throw new UnsupportedOperationException("Unimplemented method 'getFile'");
}
@Override
public String getFolder(String folder_id) {
// TODO Auto-generated method stub
throw new UnsupportedOperationException("Unimplemented method 'getFolder'");
......
......@@ -32,7 +32,7 @@ public class ExcelService {
workbook.close();
return outByteStream.toByteArray();
} catch (Exception e) {
e.printStackTrace();
System.out.println(e.getMessage());
return null;
}
}
......@@ -56,7 +56,6 @@ public class ExcelService {
final XSSFCellStyle defaultStyle = createCellStyle(workbook, new JSONObject());
JSONArray identifiers = json.optJSONArray("identifiers", new JSONArray());
JSONArray data = json.optJSONArray("data", new JSONArray());
JSONArray styles = json.optJSONArray("styles", new JSONArray());
for (int i = 0; i < data.length(); i++) {
......
package web.multitask.trismegistoservices.services;
import com.itextpdf.html2pdf.ConverterProperties;
import com.itextpdf.html2pdf.HtmlConverter;
import com.itextpdf.html2pdf.resolver.font.DefaultFontProvider;
......@@ -14,17 +13,7 @@ import java.io.FileOutputStream;
@Service
public class PDFService {
public ByteArrayResource htmlToPdf(String html){
try{
byte[] pdfBytes = generatePdf(html);
return new ByteArrayResource(pdfBytes);
} catch (Exception e) {
System.out.println(e.getMessage());
return null;
}
}
private byte[] generatePdf(String htmlContent) throws Exception {
public byte[] generatePdf(String htmlContent) throws Exception {
ConverterProperties properties = new ConverterProperties();
DefaultFontProvider fontProvider = new DefaultFontProvider(false, false, false);
fontProvider.addFont("/fonts/Roboto-Regular.ttf");
......@@ -35,13 +24,4 @@ public class PDFService {
return org.apache.commons.io.FileUtils.readFileToByteArray(file);
}
private JSONArray pdfToBase64(String pdf){
try{
byte[] pdfBytes = generatePdf(pdf);
return new JSONArray(pdfBytes);
} catch (Exception e) {
System.out.println(e.getMessage());
return null;
}
}
}
\ No newline at end of file
// package web.multitask.trismegistoservices.utils;
package web.multitask.trismegistoservices.utils;
// import io.github.cdimascio.dotenv.Dotenv;
// import org.json.JSONObject;
// import org.apache.commons.io.FileUtils;
// import org.springframework.stereotype.Service;
// import org.springframework.web.multipart.MultipartFile;
import org.apache.commons.io.FileUtils;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
// import java.io.File;
// import java.util.Arrays;
// import java.util.Base64;
// import java.util.Objects;
import java.io.File;
import java.io.IOException;
import java.util.Base64;
// @Service
// public class CommonUtils {
@Service
public class CommonUtils {
// private final Dotenv dotenv;
private final String FILE_FOLDER = System.getProperty("java.io.tmpdir");
// public CommonUtils( Dotenv dotenv ) {
// this.dotenv = dotenv;
// }
public String multipartFileToBase64(MultipartFile file) throws IOException {
byte[] byteArray = file.getBytes();
return Base64.getEncoder().encodeToString(byteArray);
}
// public JSONObject convertToBase64(MultipartFile file) {
// JSONObject response = new JSONObject();
// try{
// byte[] byteArray = file.getBytes();
// String base64 = Base64.getEncoder().encodeToString(byteArray);
// response.put("base64", base64);
// response.put("name", file.getOriginalFilename());
// response.put("size", file.getSize());
// response.put("extension", file.getContentType());
// return response;
// } catch (Exception e) {
// System.out.println(e.getMessage());
// return null;
// }
// }
// public File convertToFile(String base64, String name) {
// try{
// byte[] byteArray = Base64.getDecoder().decode(base64);
// String folder = dotenv.get("FILE_FOLDER") + "/" + name;
// File outputFile = new File(folder);
// FileUtils.writeByteArrayToFile(outputFile, byteArray);
// return outputFile;
// } catch (Exception e) {
// System.out.println(e.getMessage());
// return null;
// }
// }
public File base64ToFile(String base64, String name) {
try {
byte[] byteArray = Base64.getDecoder().decode(base64);
String folder = FILE_FOLDER + "/" + name;
File outputFile = new File(folder);
FileUtils.writeByteArrayToFile(outputFile, byteArray);
return outputFile;
} catch (Exception e) {
System.out.println(e.getMessage());
return null;
}
}
// public boolean deleteAllFiles() {
// try {
// String folder= dotenv.get("FILE_FOLDER");
// assert folder != null;
// File file = new File(folder);
// if (file.isDirectory()) {
// Boolean[] results = Arrays.stream(Objects.requireNonNull(file.listFiles())).map(File::delete).toArray(Boolean[]::new);
// return Arrays.asList(results).contains(false);
// }else{
// return file.delete();
// }
// } catch (Exception e) {
// System.out.println(e.getMessage());
// return false;
// }
// }
// }
\ No newline at end of file
public String fileToBase64(File file) {
try {
byte[] byteArray = FileUtils.readFileToByteArray(file);
return Base64.getEncoder().encodeToString(byteArray);
} catch (Exception e) {
System.out.println(e.getMessage());
return null;
}
}
public String byteToBase64(byte[] byteArray) {
return Base64.getEncoder().encodeToString(byteArray);
}
public Resource byteToResource(byte[] byteArray, String name) {
return new ByteArrayResource(byteArray) {
@Override
public String getFilename() {
return name;
}
};
}
public Resource fileToResource(File file) {
return new FileSystemResource(file);
}
public Resource base64ToResource(String base64, String name) {
byte[] byteArray = Base64.getDecoder().decode(base64);
return new ByteArrayResource(byteArray) {
@Override
public String getFilename() {
return name;
}
};
}
}
\ No newline at end of file
......@@ -7,4 +7,7 @@ spring.datasource.driverClassName=com.mysql.cj.jdbc.Driver
# spring.jpa.show-sql=true
app.jwtSecret=9a4f2c8d3b7a1e6f45c8a0b3f267d8b1d4e6f3c8a9d2b5f8e3a9c8b5f6v8a3d9
spring.jpa.hibernate.ddl-auto = update
spring.security.filter.order=1
\ No newline at end of file
spring.security.filter.order=1
spring.servlet.multipart.max-file-size=100MB
spring.servlet.multipart.max-request-size=100MB
\ 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