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

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