ソースを参照

Move files methods to separate component

Ryan Wright 1 ヶ月 前
コミット
f58acd7c08

+ 3 - 0
src/main/java/org/example/sweater/Application.java

@@ -1,9 +1,12 @@
 package org.example.sweater;
 
+import org.example.sweater.config.UploadProperties;
 import org.springframework.boot.SpringApplication;
 import org.springframework.boot.autoconfigure.SpringBootApplication;
+import org.springframework.boot.context.properties.EnableConfigurationProperties;
 
 @SpringBootApplication
+@EnableConfigurationProperties(UploadProperties.class)
 public class Application {
     public static void main(String[] args) {
         SpringApplication.run(Application.class, args);

+ 16 - 0
src/main/java/org/example/sweater/config/UploadProperties.java

@@ -0,0 +1,16 @@
+package org.example.sweater.config;
+
+import org.springframework.boot.context.properties.ConfigurationProperties;
+
+@ConfigurationProperties(prefix = "upload")
+public class UploadProperties {
+    private String path;
+
+    public String getPath() {
+        return path;
+    }
+
+    public void setPath(String path) {
+        this.path = path;
+    }
+}

+ 14 - 23
src/main/java/org/example/sweater/controller/MainController.java

@@ -4,7 +4,7 @@ import jakarta.servlet.http.HttpServletRequest;
 import org.example.sweater.domain.Message;
 import org.example.sweater.domain.User;
 import org.example.sweater.repos.MessagesRepository;
-import org.springframework.beans.factory.annotation.Value;
+import org.example.sweater.service.FileService;
 import org.springframework.security.core.annotation.AuthenticationPrincipal;
 import org.springframework.security.web.csrf.CsrfToken;
 import org.springframework.stereotype.Controller;
@@ -15,22 +15,18 @@ import org.springframework.web.bind.annotation.PostMapping;
 import org.springframework.web.bind.annotation.RequestParam;
 import org.springframework.web.multipart.MultipartFile;
 
-import java.io.File;
 import java.io.IOException;
 import java.util.Map;
-import java.util.Objects;
-import java.util.UUID;
 
 @Controller
 public class MainController {
-    public MainController(MessagesRepository messagesRepository) {
+    public MainController(MessagesRepository messagesRepository, FileService fileService) {
         this.messagesRepository = messagesRepository;
+        this.fileService = fileService;
     }
 
     private final MessagesRepository messagesRepository;
-
-    @Value("${upload.path}")
-    private String uploadPath;
+    private final FileService fileService;
 
     @ModelAttribute
     public void addCsrfToken(Model model, HttpServletRequest request) {
@@ -78,19 +74,10 @@ public class MainController {
     ) throws IOException {
         Message createdMessage = new Message(text, tag, user);
 
-        if (file != null && !Objects.requireNonNull(file.getOriginalFilename()).isEmpty()) {
-            File uploadDir = new File(uploadPath);
-
-            if (!uploadDir.exists()) {
-                uploadDir.mkdir();
-            }
-
-            String uuidFile = UUID.randomUUID().toString();
-            String fileName = uuidFile + "_" + file.getOriginalFilename();
+        if (file != null) {
+            String savedFileName = fileService.saveFile(file);
 
-            file.transferTo(new File(uploadDir.getAbsolutePath() + "/" + fileName));
-
-            createdMessage.setFilename(fileName);
+            createdMessage.setFilename(savedFileName);
         }
 
         messagesRepository.save(createdMessage);
@@ -103,11 +90,15 @@ public class MainController {
 
     @PostMapping("/feed/delete")
     public String removeMessageById(
-            @RequestParam String id,
+            @RequestParam Message message,
             Map<String, Object> model
     ) {
-        Long idAsInt = Long.parseLong(id);
-        messagesRepository.deleteById(idAsInt);
+        messagesRepository.deleteById(message.getId());
+        String fileName = message.getFilename();
+
+        if (fileName != null) {
+            fileService.deleteFile(fileName);
+        }
 
         Iterable<Message> foundMessages = messagesRepository.findAll();
 

+ 12 - 12
src/main/java/org/example/sweater/domain/Message.java

@@ -13,7 +13,7 @@ public class Message {
 
     @Id
     @GeneratedValue(strategy = GenerationType.AUTO)
-    private Integer id;
+    private Long id;
 
     private String text;
     public void setText(String text) {
@@ -24,9 +24,9 @@ public class Message {
     }
 
     private String tag;
-    public void setTag(String tag) {
-        this.tag = tag;
-    }
+//    public void setTag(String tag) {
+//        this.tag = tag;
+//    }
     public String getTag() {
         return tag;
     }
@@ -39,15 +39,15 @@ public class Message {
         return author != null ? author.getUsername() : "<none>";
     }
 
-    public User getAuthor() {
-        return author;
-    }
-
-    public void setAuthor(User author) {
-        this.author = author;
-    }
+//    public User getAuthor() {
+//        return author;
+//    }
+//
+//    public void setAuthor(User author) {
+//        this.author = author;
+//    }
 
-    public Integer getId() {
+    public Long getId() {
         return id;
     }
 

+ 40 - 0
src/main/java/org/example/sweater/service/FileService.java

@@ -0,0 +1,40 @@
+package org.example.sweater.service;
+
+import org.example.sweater.config.UploadProperties;
+import org.springframework.stereotype.Component;
+import org.springframework.web.multipart.MultipartFile;
+
+import java.io.File;
+import java.io.IOException;
+import java.util.Objects;
+import java.util.UUID;
+
+@Component
+public class FileService {
+    public FileService(UploadProperties uploadProperties) {
+        File uploadDir = new File(uploadProperties.getPath());
+
+        if (!uploadDir.exists()) {
+            uploadDir.mkdir();
+        }
+        this.uploadAbsoluteDir = uploadDir.getAbsolutePath();
+    }
+
+    private final String uploadAbsoluteDir;
+
+    public String saveFile(MultipartFile file) throws IOException, RuntimeException {
+        if (Objects.requireNonNull(file.getOriginalFilename()).isEmpty()) throw new RuntimeException("File name is empty");
+
+        String uuidFile = UUID.randomUUID().toString();
+        String fileName = uuidFile + "_" + file.getOriginalFilename();
+
+        file.transferTo(new File(uploadAbsoluteDir + "/" + fileName));
+
+        return fileName;
+    }
+
+    public void deleteFile(String fileName) {
+        File file = new File(uploadAbsoluteDir + "/" + fileName);
+        file.delete();
+    }
+}

+ 1 - 1
src/main/resources/templates/feed.ftl

@@ -48,7 +48,7 @@
                 </#if>
 
                 <form action="/feed/delete" method="post">
-                    <input type="hidden" value="${message.id}" name="id" />
+                    <input type="hidden" value="${message.id}" name="message" />
                     <input type="hidden" name="${_csrf.parameterName}" value="${_csrf.token}" />
                     <button type="submit">Remove</button>
                 </form>