From fbd4164e0686d591c20199caeb4ac06d5bfee9ca Mon Sep 17 00:00:00 2001 From: esoe Date: Thu, 23 May 2024 17:53:59 +0300 Subject: [PATCH] =?UTF-8?q?=D1=83=D0=B4=D0=B0=D0=BB=D0=B8=D1=82=D1=8C=20?= =?UTF-8?q?=D0=B2=D1=81=D0=B5=20..?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../controllers/EducationEntryController.java | 2 - explorer_rs/pom.xml | 14 ++- .../explorer_rs/ExplorerRsApplication.java | 4 - .../explorer_rs/config/StorageProperties.java | 17 --- .../controller/FileController.java | 74 ------------ .../controller/PackageController.java | 62 ---------- .../controller/StorageController.java | 35 +++++- .../molokoin/explorer_rs/entity/Document.java | 26 +---- .../explorer_rs/entity/FileResponse.java | 18 --- .../molokoin/explorer_rs/entity/Package.java | 48 -------- .../molokoin/explorer_rs/entity/Record.java | 39 ++++--- .../explorer_rs/repository/DocumentFace.java | 14 --- .../explorer_rs/repository/PackageFace.java | 14 --- .../explorer_rs/repository/RecordFace.java | 9 +- .../service/FileSystemStorage.java | 66 ++++++++--- .../service/FileSystemStorageService.java | 107 ------------------ .../explorer_rs/service/StorageFace.java | 4 +- .../explorer_rs/service/StorageService.java | 16 --- ...itional-spring-configuration-metadata.json | 5 - .../src/main/resources/application.yaml | 4 +- 20 files changed, 131 insertions(+), 447 deletions(-) delete mode 100644 explorer_rs/src/main/java/ru/molokoin/explorer_rs/config/StorageProperties.java delete mode 100644 explorer_rs/src/main/java/ru/molokoin/explorer_rs/controller/FileController.java delete mode 100644 explorer_rs/src/main/java/ru/molokoin/explorer_rs/controller/PackageController.java delete mode 100644 explorer_rs/src/main/java/ru/molokoin/explorer_rs/entity/FileResponse.java delete mode 100644 explorer_rs/src/main/java/ru/molokoin/explorer_rs/entity/Package.java delete mode 100644 explorer_rs/src/main/java/ru/molokoin/explorer_rs/repository/DocumentFace.java delete mode 100644 explorer_rs/src/main/java/ru/molokoin/explorer_rs/repository/PackageFace.java delete mode 100644 explorer_rs/src/main/java/ru/molokoin/explorer_rs/service/FileSystemStorageService.java delete mode 100644 explorer_rs/src/main/java/ru/molokoin/explorer_rs/service/StorageService.java delete mode 100644 explorer_rs/src/main/resources/META-INF/additional-spring-configuration-metadata.json diff --git a/client-service-teachers/src/main/java/ru/molokoin/clientserviceteachers/controllers/EducationEntryController.java b/client-service-teachers/src/main/java/ru/molokoin/clientserviceteachers/controllers/EducationEntryController.java index d1da210..44ba711 100644 --- a/client-service-teachers/src/main/java/ru/molokoin/clientserviceteachers/controllers/EducationEntryController.java +++ b/client-service-teachers/src/main/java/ru/molokoin/clientserviceteachers/controllers/EducationEntryController.java @@ -23,8 +23,6 @@ import com.fasterxml.jackson.databind.JsonMappingException; import reactor.core.publisher.Mono; import ru.molokoin.clientserviceteachers.entities.Course; import ru.molokoin.clientserviceteachers.entities.EducatonEntry; -import ru.molokoin.clientserviceteachers.entities.Program; -import ru.molokoin.clientserviceteachers.entities.ProgramCretarea; import ru.molokoin.clientserviceteachers.entities.Student; @Controller diff --git a/explorer_rs/pom.xml b/explorer_rs/pom.xml index 53a4f91..f53f2d3 100644 --- a/explorer_rs/pom.xml +++ b/explorer_rs/pom.xml @@ -49,7 +49,7 @@ - + + + org.springframework.boot + spring-boot-maven-plugin + + + org.apache.maven.plugins + maven-surefire-plugin + 2.22.2 + + ${tests.skip} + diff --git a/explorer_rs/src/main/java/ru/molokoin/explorer_rs/ExplorerRsApplication.java b/explorer_rs/src/main/java/ru/molokoin/explorer_rs/ExplorerRsApplication.java index de3ccdc..89b9a55 100644 --- a/explorer_rs/src/main/java/ru/molokoin/explorer_rs/ExplorerRsApplication.java +++ b/explorer_rs/src/main/java/ru/molokoin/explorer_rs/ExplorerRsApplication.java @@ -2,12 +2,8 @@ package ru.molokoin.explorer_rs; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; -import org.springframework.boot.context.properties.EnableConfigurationProperties; - -import ru.molokoin.explorer_rs.config.StorageProperties; @SpringBootApplication -@EnableConfigurationProperties(StorageProperties.class) public class ExplorerRsApplication { public static void main(String[] args) { diff --git a/explorer_rs/src/main/java/ru/molokoin/explorer_rs/config/StorageProperties.java b/explorer_rs/src/main/java/ru/molokoin/explorer_rs/config/StorageProperties.java deleted file mode 100644 index 150f6cd..0000000 --- a/explorer_rs/src/main/java/ru/molokoin/explorer_rs/config/StorageProperties.java +++ /dev/null @@ -1,17 +0,0 @@ -package ru.molokoin.explorer_rs.config; - -import org.springframework.boot.context.properties.ConfigurationProperties; - -@ConfigurationProperties(prefix = "storage") -public class StorageProperties { - private String location; - - public String getLocation() { - return location; - } - - public void setLocation(String location) { - this.location = location; - } - -} diff --git a/explorer_rs/src/main/java/ru/molokoin/explorer_rs/controller/FileController.java b/explorer_rs/src/main/java/ru/molokoin/explorer_rs/controller/FileController.java deleted file mode 100644 index 48b6aeb..0000000 --- a/explorer_rs/src/main/java/ru/molokoin/explorer_rs/controller/FileController.java +++ /dev/null @@ -1,74 +0,0 @@ -package ru.molokoin.explorer_rs.controller; - -import java.util.Arrays; -import java.util.List; -import java.util.stream.Collectors; - -import org.springframework.core.io.Resource; -import org.springframework.http.HttpHeaders; -import org.springframework.http.ResponseEntity; -import org.springframework.stereotype.Controller; -import org.springframework.ui.Model; -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.PathVariable; -import org.springframework.web.bind.annotation.PostMapping; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestParam; -import org.springframework.web.bind.annotation.ResponseBody; -import org.springframework.web.multipart.MultipartFile; -import org.springframework.web.servlet.support.ServletUriComponentsBuilder; - -import ru.molokoin.explorer_rs.entity.FileResponse; -import ru.molokoin.explorer_rs.service.StorageService; - -@Controller -@RequestMapping(path = "/explorer_rs") -public class FileController { - private StorageService storageService; - - public FileController(StorageService storageService) { - this.storageService = storageService; - } - - @GetMapping("/list") - public String listAllFiles(Model model) { - model.addAttribute("files", storageService.loadAll().map( - path -> ServletUriComponentsBuilder.fromCurrentContextPath() - .path("/explorer_rs/download/") - .path(path.getFileName().toString()) - .toUriString()) - .collect(Collectors.toList())); - return "listFiles"; - } - - @GetMapping("/download/{filename:.+}") - @ResponseBody - public ResponseEntity downloadFile(@PathVariable String filename) { - Resource resource = storageService.loadAsResource(filename); - return ResponseEntity.ok() - .header(HttpHeaders.CONTENT_DISPOSITION, - "attachment; filename=\"" + resource.getFilename() + "\"") - .body(resource); - } - - @PostMapping("/upload-file") - @ResponseBody - public FileResponse uploadFile(@RequestParam("file") MultipartFile file) { - String name = storageService.store(file); - String uri = ServletUriComponentsBuilder.fromCurrentContextPath() - .path("/download/") - .path(name) - .toUriString(); - - return new FileResponse(name, uri, file.getContentType(), file.getSize()); - } - - @PostMapping("/upload-multiple-files") - @ResponseBody - public List uploadMultipleFiles(@RequestParam("files") MultipartFile[] files) { - return Arrays.stream(files) - .map(file -> uploadFile(file)) - .collect(Collectors.toList()); - } - -} diff --git a/explorer_rs/src/main/java/ru/molokoin/explorer_rs/controller/PackageController.java b/explorer_rs/src/main/java/ru/molokoin/explorer_rs/controller/PackageController.java deleted file mode 100644 index 45c657f..0000000 --- a/explorer_rs/src/main/java/ru/molokoin/explorer_rs/controller/PackageController.java +++ /dev/null @@ -1,62 +0,0 @@ -package ru.molokoin.explorer_rs.controller; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.http.HttpStatus; -import org.springframework.http.MediaType; -import org.springframework.http.ResponseEntity; -import org.springframework.web.bind.annotation.DeleteMapping; -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.PathVariable; -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 ru.molokoin.explorer_rs.repository.PackageFace; -import ru.molokoin.explorer_rs.entity.Package; - -@RestController -@RequestMapping(path = "/", consumes = {"*/*"}) -public class PackageController { - @Autowired - private PackageFace repo; - - @GetMapping("/package/list") - public ResponseEntity getPackages(){ - return new ResponseEntity<>(repo.findAll(), HttpStatus.OK); - } - - @GetMapping("/package/{id}") - public ResponseEntity getPackageByID(@PathVariable Integer id){ - return new ResponseEntity<>(repo.findPackageById(id), HttpStatus.OK); - } - - @PostMapping(path = "/package/create", - consumes = MediaType.APPLICATION_JSON_VALUE, - produces = MediaType.APPLICATION_JSON_VALUE) - public ResponseEntity savePackage(@RequestBody Package pack) { - repo.save(pack); - return new ResponseEntity<>(pack, HttpStatus.CREATED); - } - - @PostMapping(path = "/package/update/{id}", - consumes = MediaType.APPLICATION_JSON_VALUE, - produces = MediaType.APPLICATION_JSON_VALUE) - public ResponseEntity updatePackage(@PathVariable Integer id, @RequestBody Package pack) { - Package p = repo.findPackageById(id); - p.setTitle(pack.getTitle()); - p.setOrigin_title(pack.getOrigin_title()); - p.setType(pack.getType()); - p.setExtension(pack.getExtension()); - p.setDate(pack.getDate()); - repo.save(p); - return new ResponseEntity<>(repo.findPackageById(id), HttpStatus.CREATED); - } - - @DeleteMapping("/package/delete/{id}") - public ResponseEntity deletePackage(@PathVariable Long id){ - Package p = repo.findPackageById(id); - repo.delete(p); - return new ResponseEntity<>("Запись id#" + id + " удалена ... ", HttpStatus.OK); - } -} diff --git a/explorer_rs/src/main/java/ru/molokoin/explorer_rs/controller/StorageController.java b/explorer_rs/src/main/java/ru/molokoin/explorer_rs/controller/StorageController.java index cb0a416..bf4d2c8 100644 --- a/explorer_rs/src/main/java/ru/molokoin/explorer_rs/controller/StorageController.java +++ b/explorer_rs/src/main/java/ru/molokoin/explorer_rs/controller/StorageController.java @@ -1,10 +1,41 @@ package ru.molokoin.explorer_rs.controller; +import java.util.List; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +import ru.molokoin.explorer_rs.service.StorageFace; +import ru.molokoin.explorer_rs.entity.Document;; -@Controller -@RequestMapping(path = "/stroage") +/** + * Контроллер предоставляющий http-api + * для доступа к файлам хранилища данных + * + */ +@RestController +@RequestMapping(path = "/", consumes = {"*/*"}) public class StorageController { + + @Autowired + private StorageFace storage; + + // public StorageController(StorageFace storage){ + // this.storage = storage; + // } + /** + * Получение перечня документов размещенных в хранилище + * - перечень формируется на основании сканирования файловой системы + * @return + */ + @GetMapping(path = "/storage/list") + public ResponseEntity> listStorage(){ + return new ResponseEntity<>(storage.list(), HttpStatus.OK); + } } diff --git a/explorer_rs/src/main/java/ru/molokoin/explorer_rs/entity/Document.java b/explorer_rs/src/main/java/ru/molokoin/explorer_rs/entity/Document.java index 18360ba..5ff3c4d 100644 --- a/explorer_rs/src/main/java/ru/molokoin/explorer_rs/entity/Document.java +++ b/explorer_rs/src/main/java/ru/molokoin/explorer_rs/entity/Document.java @@ -1,39 +1,15 @@ package ru.molokoin.explorer_rs.entity; -import jakarta.persistence.Entity; -import jakarta.persistence.GeneratedValue; -import jakarta.persistence.GenerationType; -import jakarta.persistence.Id; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; @NoArgsConstructor @AllArgsConstructor -@Entity @Data -public class Document { - @Id - @GeneratedValue(strategy=GenerationType.AUTO) - private long id; +public class Document extends Object{ private String name;//наименование файла в файловой системе ({id}.{extension}) - private String name_origin;//оригинальное название загруженного файл private String path;//путь в файловой системе (root/{id}.{extension}) private String extension;//расширение файла private long size;//размер файла - - /** - * @param name - * @param name_origin - * @param path - * @param extension - * @param size - */ - public Document(String name, String name_origin, String path, String extension, long size) { - this.name = name; - this.name_origin = name_origin; - this.path = path; - this.extension = extension; - this.size = size; - } } diff --git a/explorer_rs/src/main/java/ru/molokoin/explorer_rs/entity/FileResponse.java b/explorer_rs/src/main/java/ru/molokoin/explorer_rs/entity/FileResponse.java deleted file mode 100644 index d9c2b90..0000000 --- a/explorer_rs/src/main/java/ru/molokoin/explorer_rs/entity/FileResponse.java +++ /dev/null @@ -1,18 +0,0 @@ -package ru.molokoin.explorer_rs.entity; - -import lombok.Data; - -@Data -public class FileResponse { - private String name; - private String uri; - private String type; - private long size; - - public FileResponse(String name, String uri, String type, long size) { - this.name = name; - this.uri = uri; - this.type = type; - this.size = size; - } -} diff --git a/explorer_rs/src/main/java/ru/molokoin/explorer_rs/entity/Package.java b/explorer_rs/src/main/java/ru/molokoin/explorer_rs/entity/Package.java deleted file mode 100644 index b71485f..0000000 --- a/explorer_rs/src/main/java/ru/molokoin/explorer_rs/entity/Package.java +++ /dev/null @@ -1,48 +0,0 @@ -package ru.molokoin.explorer_rs.entity; - -import java.util.Date; - -import jakarta.persistence.Entity; -import jakarta.persistence.GeneratedValue; -import jakarta.persistence.GenerationType; -import jakarta.persistence.Id; -import lombok.AllArgsConstructor; -import lombok.Data; -import lombok.NoArgsConstructor; - -/** - * Обертка для хранения данных о загружаемом пакете - */ -@NoArgsConstructor -@AllArgsConstructor -@Entity -@Data -public class Package { - @Id - @GeneratedValue(strategy=GenerationType.AUTO) - private long id; - private String title;// Наименование файла в файловой системе - private String origin_title;// Наименование загружаемого файла - private String type;// Наименование загружаемой формы - private String extension;// Расширение файла - private Date date;// Время загрузки пакета на сервер - - // Пока не работает блок авторизации, учет автора безсмысленен - // private Person author;// Пользователь, загрузивший файл - - /** - * Конструктор без id - * @param title - * @param origin_title - * @param type - * @param extension - * @param date - */ - public Package(String title, String origin_title, String type, String extension, Date date) { - this.title = title; - this.origin_title = origin_title; - this.type = type; - this.extension = extension; - this.date = date; - } -} diff --git a/explorer_rs/src/main/java/ru/molokoin/explorer_rs/entity/Record.java b/explorer_rs/src/main/java/ru/molokoin/explorer_rs/entity/Record.java index d284ac7..225a506 100644 --- a/explorer_rs/src/main/java/ru/molokoin/explorer_rs/entity/Record.java +++ b/explorer_rs/src/main/java/ru/molokoin/explorer_rs/entity/Record.java @@ -3,17 +3,10 @@ package ru.molokoin.explorer_rs.entity; import java.util.Date; -import org.hibernate.annotations.OnDelete; -import org.hibernate.annotations.OnDeleteAction; - -import jakarta.persistence.CascadeType; import jakarta.persistence.Entity; -import jakarta.persistence.FetchType; import jakarta.persistence.GeneratedValue; import jakarta.persistence.GenerationType; import jakarta.persistence.Id; -import jakarta.persistence.JoinColumn; -import jakarta.persistence.OneToOne; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; @@ -22,36 +15,42 @@ import lombok.NoArgsConstructor; @AllArgsConstructor @Entity @Data -public class Record { +public class Record extends Document{ @Id @GeneratedValue(strategy=GenerationType.AUTO) private long id; + private String name_origin;//оригинальное название загруженного файл private String type;//тип загруженного документа (реестр, заявка, протокол ...) - private String author; + private String author;//пользователь, оформивший запись private Date berth;//дата и время создания записи private String description;//Пояснения автора записи - /** - * Связь один к одному с таблицей данных файловой системы - */ - @OneToOne(fetch = FetchType.EAGER, cascade = CascadeType.ALL) - @OnDelete(action = OnDeleteAction.SET_NULL) - @JoinColumn(name = "document_id", nullable = true) - private Document document; - /** * Конструктор без id + * @param name + * @param path + * @param extension + * @param size + * @param name_origin * @param type * @param author * @param berth * @param description - * @param document */ - public Record(String type, String author, Date berth, String description, Document document) { + public Record(String name, String path, String extension, long size, String name_origin, String type, String author, + Date berth, String description) { + super(name, path, extension, size); + this.name_origin = name_origin; this.type = type; this.author = author; this.berth = berth; this.description = description; - this.document = document; + } + + public Record(Document document){ + setName(document.getName()); + setPath(document.getPath()); + setExtension(document.getExtension()); + setSize(document.getSize()); } } diff --git a/explorer_rs/src/main/java/ru/molokoin/explorer_rs/repository/DocumentFace.java b/explorer_rs/src/main/java/ru/molokoin/explorer_rs/repository/DocumentFace.java deleted file mode 100644 index 1505e2c..0000000 --- a/explorer_rs/src/main/java/ru/molokoin/explorer_rs/repository/DocumentFace.java +++ /dev/null @@ -1,14 +0,0 @@ -package ru.molokoin.explorer_rs.repository; - -import java.util.List; - -import org.springframework.data.repository.ListCrudRepository; -import org.springframework.stereotype.Repository; - -import ru.molokoin.explorer_rs.entity.Document; - -@Repository -public interface DocumentFace extends ListCrudRepository{ - List findAll(); - Document findDocumentById(long id); -} diff --git a/explorer_rs/src/main/java/ru/molokoin/explorer_rs/repository/PackageFace.java b/explorer_rs/src/main/java/ru/molokoin/explorer_rs/repository/PackageFace.java deleted file mode 100644 index 686a2d6..0000000 --- a/explorer_rs/src/main/java/ru/molokoin/explorer_rs/repository/PackageFace.java +++ /dev/null @@ -1,14 +0,0 @@ -package ru.molokoin.explorer_rs.repository; - -import java.util.List; - -import org.springframework.data.repository.ListCrudRepository; -import org.springframework.stereotype.Repository; - -import ru.molokoin.explorer_rs.entity.Package; - -@Repository -public interface PackageFace extends ListCrudRepository{ - List findAll(); - Package findPackageById(long id); -} diff --git a/explorer_rs/src/main/java/ru/molokoin/explorer_rs/repository/RecordFace.java b/explorer_rs/src/main/java/ru/molokoin/explorer_rs/repository/RecordFace.java index 3714280..09bcdcc 100644 --- a/explorer_rs/src/main/java/ru/molokoin/explorer_rs/repository/RecordFace.java +++ b/explorer_rs/src/main/java/ru/molokoin/explorer_rs/repository/RecordFace.java @@ -1,5 +1,12 @@ package ru.molokoin.explorer_rs.repository; -public interface RecordFace { +import java.util.List; +import org.springframework.data.repository.ListCrudRepository; +import org.springframework.stereotype.Repository; + +@Repository +public interface RecordFace extends ListCrudRepository{ + List findAll(); + Record findRecordById(long id); } diff --git a/explorer_rs/src/main/java/ru/molokoin/explorer_rs/service/FileSystemStorage.java b/explorer_rs/src/main/java/ru/molokoin/explorer_rs/service/FileSystemStorage.java index ac3b6a4..3dba6b2 100644 --- a/explorer_rs/src/main/java/ru/molokoin/explorer_rs/service/FileSystemStorage.java +++ b/explorer_rs/src/main/java/ru/molokoin/explorer_rs/service/FileSystemStorage.java @@ -1,17 +1,20 @@ package ru.molokoin.explorer_rs.service; +import java.io.File; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; +import java.util.ArrayList; +import java.util.Arrays; import java.util.List; +import java.util.Optional; -import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.io.Resource; import org.springframework.stereotype.Service; import jakarta.annotation.PostConstruct; -import ru.molokoin.explorer_rs.config.StorageProperties; +import ru.molokoin.explorer_rs.entity.Document; import ru.molokoin.explorer_rs.exception.StorageException; /** @@ -19,17 +22,10 @@ import ru.molokoin.explorer_rs.exception.StorageException; */ @Service public class FileSystemStorage implements StorageFace{ - private final Path root; //путь к корню хранилища данных - /** - * Конструктор, инициирующий путь к корню хранилиа данных, - * установленный файлом настроек приложения - * @param properties + * Перенести в properties */ - @Autowired - public FileSystemStorage(StorageProperties properties) { - this.root = Paths.get(properties.getLocation()); - } + private final Path root = Paths.get("/app/explorer_rs/uploads") ; //путь к корню хранилища данных /** * При запуске сервера создаем корневую директорию, @@ -45,10 +41,52 @@ public class FileSystemStorage implements StorageFace{ } } + /** + * Получение перечня документов, размещенных в хранилище + * @throws IOException + */ @Override - public List list() { - // TODO Auto-generated method stub - throw new UnsupportedOperationException("Unimplemented method 'list'"); + public List list() { + List docs = new ArrayList<>(); + /** + * Получаем список файлов в директории root + */ + String[] files = root.toFile().list(); + + /** + * извлекаем сведения о каждом файле для формирвоания сущности document + */ + for (String file : new ArrayList<>(Arrays.asList(files))) { + Document doc = new Document(); + + doc.setPath(file); + + /** + * Извлекаем имя файла + */ + doc.setName(new File(file).getName()); + + /** + * Получаем размер файла + */ + long size = 0; + try { + size = Files.size(Paths.get(file)); + } catch (IOException e) { + e.printStackTrace(); + } + doc.setSize(size); + + /** + * Получаем расширение файла + */ + Optional ext = Optional.ofNullable(file) + .filter(f -> f.contains(".")) + .map(f -> f.substring(file.lastIndexOf(".") + 1)); + doc.setExtension(ext.get()); + docs.add(doc); + } + return docs; } @Override diff --git a/explorer_rs/src/main/java/ru/molokoin/explorer_rs/service/FileSystemStorageService.java b/explorer_rs/src/main/java/ru/molokoin/explorer_rs/service/FileSystemStorageService.java deleted file mode 100644 index 0001fb4..0000000 --- a/explorer_rs/src/main/java/ru/molokoin/explorer_rs/service/FileSystemStorageService.java +++ /dev/null @@ -1,107 +0,0 @@ -package ru.molokoin.explorer_rs.service; - -import java.io.IOException; -import java.io.InputStream; -import java.net.MalformedURLException; -import java.nio.file.Files; -import java.nio.file.Path; -import java.nio.file.Paths; -import java.nio.file.StandardCopyOption; -import java.util.stream.Stream; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.core.io.Resource; -import org.springframework.core.io.UrlResource; -import org.springframework.stereotype.Service; -import org.springframework.util.FileSystemUtils; -import org.springframework.util.StringUtils; -import org.springframework.web.multipart.MultipartFile; - -import jakarta.annotation.PostConstruct; -import ru.molokoin.explorer_rs.config.StorageProperties; -import ru.molokoin.explorer_rs.exception.StorageException; -import ru.molokoin.explorer_rs.exception.FileNotFoundException; - -@Service -public class FileSystemStorageService implements StorageService{ - private final Path rootLocation; - - @Autowired - public FileSystemStorageService(StorageProperties properties) { - this.rootLocation = Paths.get(properties.getLocation()); - } - - @Override - @PostConstruct - public void init() { - try { - Files.createDirectories(rootLocation); - } catch (IOException e) { - throw new StorageException("Could not initialize storage location", e); - } - } - - @Override - public String store(MultipartFile file) { - String filename = StringUtils.cleanPath(file.getOriginalFilename()); - try { - if (file.isEmpty()) { - throw new StorageException("Failed to store empty file " + filename); - } - if (filename.contains("..")) { - // This is a security check - throw new StorageException( - "Cannot store file with relative path outside current directory " - + filename); - } - try (InputStream inputStream = file.getInputStream()) { - Files.copy(inputStream, this.rootLocation.resolve(filename), - StandardCopyOption.REPLACE_EXISTING); - } - } - catch (IOException e) { - throw new StorageException("Failed to store file " + filename, e); - } - return filename; - } - - @Override - public Stream loadAll() { - try { - return Files.walk(this.rootLocation, 1) - .filter(path -> !path.equals(this.rootLocation)) - .map(this.rootLocation::relativize); - } - catch (IOException e) { - throw new StorageException("Failed to read stored files", e); - } - } - - @Override - public Path load(String filename) { - return rootLocation.resolve(filename); - } - - @Override - public Resource loadAsResource(String filename) { - try { - Path file = load(filename); - Resource resource = new UrlResource(file.toUri()); - if (resource.exists() || resource.isReadable()) { - return resource; - } - else { - throw new FileNotFoundException( - "Could not read file: " + filename); - } - }catch (MalformedURLException e) { - throw new FileNotFoundException("Could not read file: " + filename, e); - } - } - - @Override - public void deleteAll() { - FileSystemUtils.deleteRecursively(rootLocation.toFile()); - } - -} diff --git a/explorer_rs/src/main/java/ru/molokoin/explorer_rs/service/StorageFace.java b/explorer_rs/src/main/java/ru/molokoin/explorer_rs/service/StorageFace.java index 4d117f7..188f8de 100644 --- a/explorer_rs/src/main/java/ru/molokoin/explorer_rs/service/StorageFace.java +++ b/explorer_rs/src/main/java/ru/molokoin/explorer_rs/service/StorageFace.java @@ -4,6 +4,8 @@ import java.util.List; import org.springframework.core.io.Resource; +import ru.molokoin.explorer_rs.entity.Document; + /** * Интерфейс для работы файловым хранилищем @@ -29,7 +31,7 @@ public interface StorageFace { * получить список размещенных на хосте и не зарегистрированных в базе файлов * @return */ - public List list(); + public List list(); /** * Удаление всех файлов, очистка хранилища diff --git a/explorer_rs/src/main/java/ru/molokoin/explorer_rs/service/StorageService.java b/explorer_rs/src/main/java/ru/molokoin/explorer_rs/service/StorageService.java deleted file mode 100644 index 38db69b..0000000 --- a/explorer_rs/src/main/java/ru/molokoin/explorer_rs/service/StorageService.java +++ /dev/null @@ -1,16 +0,0 @@ -package ru.molokoin.explorer_rs.service; - -import org.springframework.core.io.Resource; -import org.springframework.web.multipart.MultipartFile; - -import java.nio.file.Path; -import java.util.stream.Stream; - -public interface StorageService { - void init(); - String store(MultipartFile file); - Stream loadAll(); - Path load(String filename); - Resource loadAsResource(String filename); - void deleteAll(); -} diff --git a/explorer_rs/src/main/resources/META-INF/additional-spring-configuration-metadata.json b/explorer_rs/src/main/resources/META-INF/additional-spring-configuration-metadata.json deleted file mode 100644 index 12f4d28..0000000 --- a/explorer_rs/src/main/resources/META-INF/additional-spring-configuration-metadata.json +++ /dev/null @@ -1,5 +0,0 @@ -{"properties": [{ - "name": "storage.location", - "type": "java.lang.String", - "description": "Path to local storage for uploaded files" -}]} \ No newline at end of file diff --git a/explorer_rs/src/main/resources/application.yaml b/explorer_rs/src/main/resources/application.yaml index 84f4beb..088a7f4 100644 --- a/explorer_rs/src/main/resources/application.yaml +++ b/explorer_rs/src/main/resources/application.yaml @@ -15,5 +15,5 @@ spring: multipart: max-file-size: 50MB max-request-size: 50MB -storage: - location: ./uploads \ No newline at end of file +# storage: +# location: ./uploads \ No newline at end of file