From 39dca18e52e1de56595939a191ff1662b2e5eb04 Mon Sep 17 00:00:00 2001 From: germano Date: Mon, 8 Apr 2019 01:04:39 -0300 Subject: [PATCH 01/54] Functional upload to a directory in the desktop by multipart file POST. Not handling userId and only images yet. Without Tests --- .../java/hive/album/AlbumApplication.java | 17 +++ .../album/controller/AlbumController.java | 65 +++++++++++ .../hive/album/repository/UserRepository.java | 8 ++ .../storage/FileSystemStorageService.java | 106 ++++++++++++++++++ .../hive/album/storage/iStorageService.java | 23 ++++ .../src/main/resources/application.properties | 16 +++ .../hive/album/AlbumApplicationTests.java | 16 +++ settings.gradle | 1 + 8 files changed, 252 insertions(+) create mode 100644 album/src/main/java/hive/album/AlbumApplication.java create mode 100644 album/src/main/java/hive/album/controller/AlbumController.java create mode 100644 album/src/main/java/hive/album/repository/UserRepository.java create mode 100644 album/src/main/java/hive/album/storage/FileSystemStorageService.java create mode 100644 album/src/main/java/hive/album/storage/iStorageService.java create mode 100644 album/src/main/resources/application.properties create mode 100644 album/src/test/java/hive/album/AlbumApplicationTests.java diff --git a/album/src/main/java/hive/album/AlbumApplication.java b/album/src/main/java/hive/album/AlbumApplication.java new file mode 100644 index 0000000..af7b98c --- /dev/null +++ b/album/src/main/java/hive/album/AlbumApplication.java @@ -0,0 +1,17 @@ +package hive.album; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.boot.autoconfigure.domain.EntityScan; +import org.springframework.cloud.netflix.eureka.EnableEurekaClient; + +@SpringBootApplication +@EnableEurekaClient +@EntityScan( basePackages = {"hive.entity"} ) +public class AlbumApplication { + + public static void main(String[] args) { + SpringApplication.run(AlbumApplication.class, args); + } + +} diff --git a/album/src/main/java/hive/album/controller/AlbumController.java b/album/src/main/java/hive/album/controller/AlbumController.java new file mode 100644 index 0000000..b245ea7 --- /dev/null +++ b/album/src/main/java/hive/album/controller/AlbumController.java @@ -0,0 +1,65 @@ +package hive.album.controller; + +import hive.album.entity.Something; +import hive.album.storage.iStorageService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.HttpHeaders; +import org.springframework.http.ResponseEntity; +import org.springframework.ui.Model; +import org.springframework.core.io.Resource; +import org.springframework.web.bind.annotation.*; +import org.springframework.web.multipart.MultipartFile; +import org.springframework.web.servlet.mvc.method.annotation.MvcUriComponentsBuilder; +import org.springframework.web.servlet.mvc.support.RedirectAttributes; + +import java.io.IOException; +import java.util.stream.Collectors; + +@RestController +@RequestMapping("/") +public class AlbumController { + @GetMapping("/") + public String a(){ + return "a"; + } + @GetMapping("/sum") + public Something sumNumbers(@RequestParam(value = "n1", required = false) String n1, + @RequestParam(value = "n2", required = false) String n2) { + var algo =new Something(); + int num1=Integer.parseInt(n1); + num1+= Integer.parseInt(n2); + algo.setContent("soma "+(num1)); + return algo; + } + private final iStorageService storageService; + + @Autowired + public AlbumController(iStorageService storageService) { + this.storageService = storageService; + } +/* + @GetMapping("/") + public String listUploadedImages(Model model) throws IOException { + model.addAttribute("files", storageService.loadAll().map( + path -> MvcUriComponentsBuilder.fromMethodName(FileUploadController.class, + "serveFile", path.getFileName().toString()).build().toString()) + .collect(Collectors.toList())); + return "uploadForm"; + } +*/ + @GetMapping("/files/{filename:.+}") + @ResponseBody + public ResponseEntity serveFile(@PathVariable String filename) { + + Resource file = storageService.loadAsResource(filename); + return ResponseEntity.ok().header(HttpHeaders.CONTENT_DISPOSITION, + "attachment; filename=\"" + file.getFilename() + "\"").body(file); + } + + @PostMapping("/") + public String handleFileUpload(@RequestParam("file") MultipartFile file) { + storageService.store(file); + return "{Mensagem:Sucesso}"; + } + +} diff --git a/album/src/main/java/hive/album/repository/UserRepository.java b/album/src/main/java/hive/album/repository/UserRepository.java new file mode 100644 index 0000000..f8a8278 --- /dev/null +++ b/album/src/main/java/hive/album/repository/UserRepository.java @@ -0,0 +1,8 @@ +package hive.album.repository; + +import hive.entity.user.User; +import org.springframework.data.repository.CrudRepository; + +public interface UserRepository extends CrudRepository { + User findByUsername(String username); +} diff --git a/album/src/main/java/hive/album/storage/FileSystemStorageService.java b/album/src/main/java/hive/album/storage/FileSystemStorageService.java new file mode 100644 index 0000000..1b44111 --- /dev/null +++ b/album/src/main/java/hive/album/storage/FileSystemStorageService.java @@ -0,0 +1,106 @@ +package hive.album.storage; +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; + +@Service +public class FileSystemStorageService implements iStorageService{ + + private final Path rootLocation; + + //@Autowired + public FileSystemStorageService() { + this.rootLocation = Paths.get("C:\\Users\\Germano\\Desktop\\AlbumTest"); + } + + @Override + public void store(MultipartFile file) { + String filename = StringUtils.cleanPath(file.getOriginalFilename()); + try { + if (file.isEmpty()) { + //throw new StorageException("Failed to store empty file " + filename); + throw new RuntimeException(); + } + if (filename.contains("..")) { + // This is a security check + /*throw new StorageException( + "Cannot store file with relative path outside current directory " + + filename);*/ + throw new RuntimeException(); + } + 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); + throw new RuntimeException("Failed to store file " + filename, e); + } + } + + @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); + throw new RuntimeException("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 RuntimeException("Could not read file: " + filename); + + } + } + catch (MalformedURLException e) { + throw new RuntimeException("Could not read file: " + filename, e); + } + } + + @Override + public void deleteAll() { + FileSystemUtils.deleteRecursively(rootLocation.toFile()); + } + + @Override + public void init() { + try { + Files.createDirectories(rootLocation); + } + catch (IOException e) { + throw new RuntimeException("Could not initialize storage", e); + } + } +} \ No newline at end of file diff --git a/album/src/main/java/hive/album/storage/iStorageService.java b/album/src/main/java/hive/album/storage/iStorageService.java new file mode 100644 index 0000000..e324b07 --- /dev/null +++ b/album/src/main/java/hive/album/storage/iStorageService.java @@ -0,0 +1,23 @@ +package hive.album.storage; + +import org.springframework.core.io.Resource; +import org.springframework.web.multipart.MultipartFile; + +import java.nio.file.Path; +import java.util.stream.Stream; + +public interface iStorageService { + + void init(); + + void store(MultipartFile file); + + Stream loadAll(); + + Path load(String filename); + + Resource loadAsResource(String filename); + + void deleteAll(); + +} \ No newline at end of file diff --git a/album/src/main/resources/application.properties b/album/src/main/resources/application.properties new file mode 100644 index 0000000..0fe8530 --- /dev/null +++ b/album/src/main/resources/application.properties @@ -0,0 +1,16 @@ +spring.application.name=album-service +server.port=9500 +eureka.client.service-url.default-zone=http://localhost:8761/eureka +# H2 +spring.h2.console.enabled=false +spring.h2.console.path=/h2 +# Datasource +spring.datasource.url=jdbc:h2:file:./db/auth;AUTO_SERVER=TRUE +spring.datasource.username=sa +spring.datasource.password= +spring.datasource.driver-class-name=org.h2.Driver +#spring.jpa.hibernate.ddl-auto=create-drop +spring.jpa.hibernate.ddl-auto=create +spring.jpa.show-sql=true +spring.jpa.properties.hibernate.format_sql=true +logging.level.org.hibernate.type=trace \ No newline at end of file diff --git a/album/src/test/java/hive/album/AlbumApplicationTests.java b/album/src/test/java/hive/album/AlbumApplicationTests.java new file mode 100644 index 0000000..d9d808c --- /dev/null +++ b/album/src/test/java/hive/album/AlbumApplicationTests.java @@ -0,0 +1,16 @@ +package hive.album; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +@RunWith(SpringRunner.class) +@SpringBootTest +public class AlbumApplicationTests { + + @Test + public void contextLoads() { + } + +} diff --git a/settings.gradle b/settings.gradle index 0f23109..9b67a0a 100644 --- a/settings.gradle +++ b/settings.gradle @@ -5,4 +5,5 @@ include 'common' include 'gateway' include 'naming-server' include 'entity' +include 'album' From 9359b64993ef8b3d63e4e5f1dbeb64509f1668a7 Mon Sep 17 00:00:00 2001 From: germano Date: Thu, 11 Apr 2019 21:18:46 -0300 Subject: [PATCH 02/54] =?UTF-8?q?refatora=C3=A7=C3=A3o=20de=20metodos=20e?= =?UTF-8?q?=20novas=20configura=C3=A7=C3=B5es=20em=20application=20propert?= =?UTF-8?q?ies?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- album/build.gradle | 53 +++++++++++++++++++ ...lication.java => SmugshotApplication.java} | 7 ++- .../album/controller/AlbumController.java | 25 ++++----- .../album/repository/imageRespository.java | 9 ++++ .../storage/FileSystemStorageService.java | 24 ++++----- .../src/main/resources/application.properties | 5 +- ...sts.java => SmugshotApplicationTests.java} | 2 +- 7 files changed, 90 insertions(+), 35 deletions(-) create mode 100644 album/build.gradle rename album/src/main/java/hive/album/{AlbumApplication.java => SmugshotApplication.java} (71%) create mode 100644 album/src/main/java/hive/album/repository/imageRespository.java rename album/src/test/java/hive/album/{AlbumApplicationTests.java => SmugshotApplicationTests.java} (87%) diff --git a/album/build.gradle b/album/build.gradle new file mode 100644 index 0000000..2e8e18a --- /dev/null +++ b/album/build.gradle @@ -0,0 +1,53 @@ +buildscript { + ext { + springBootVersion = '2.1.3.RELEASE' + springCloudVersion = 'Greenwich.SR1' + } + repositories { + mavenCentral() + maven { url 'https://repo.spring.io/milestone' } + } + dependencies { + classpath "org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}" as Object + classpath "org.springframework.cloud:spring-cloud-dependencies:${springCloudVersion}" as Object + } +} + +plugins { + id "io.spring.dependency-management" version "1.0.5.RELEASE" + id 'java' + id 'org.springframework.boot' version '2.1.3.RELEASE' +} + +apply plugin: 'io.spring.dependency-management' + +group = 'hive' +version = '0.0.1-SNAPSHOT' +sourceCompatibility = '11' + +repositories { + mavenCentral() + maven { url 'https://repo.spring.io/milestone' } +} + +dependencies { + implementation project(':common') + implementation project(':entity') + + implementation 'javax.xml.bind:jaxb-api:2.3.1' + implementation 'javax.activation:activation:1.1.1' + implementation 'org.glassfish.jaxb:jaxb-runtime:2.3.2' + + implementation 'org.springframework.boot:spring-boot-starter-web' + implementation 'org.springframework.boot:spring-boot-starter-data-jpa' + implementation 'com.h2database:h2' + implementation 'org.springframework.cloud:spring-cloud-starter-netflix-eureka-client' + testImplementation 'org.springframework.boot:spring-boot-starter-test' +} + +dependencyManagement { + imports { + mavenBom "org.springframework.boot:spring-boot-dependencies:${springBootVersion}" + mavenBom "org.springframework.cloud:spring-cloud-dependencies:${springCloudVersion}" + } +} \ No newline at end of file diff --git a/album/src/main/java/hive/album/AlbumApplication.java b/album/src/main/java/hive/album/SmugshotApplication.java similarity index 71% rename from album/src/main/java/hive/album/AlbumApplication.java rename to album/src/main/java/hive/album/SmugshotApplication.java index af7b98c..48b60e2 100644 --- a/album/src/main/java/hive/album/AlbumApplication.java +++ b/album/src/main/java/hive/album/SmugshotApplication.java @@ -7,11 +7,10 @@ @SpringBootApplication @EnableEurekaClient -@EntityScan( basePackages = {"hive.entity"} ) -public class AlbumApplication { +@EntityScan( basePackages = {"hive.entity.user"} ) +public class SmugshotApplication { public static void main(String[] args) { - SpringApplication.run(AlbumApplication.class, args); + SpringApplication.run(SmugshotApplication.class, args); } - } diff --git a/album/src/main/java/hive/album/controller/AlbumController.java b/album/src/main/java/hive/album/controller/AlbumController.java index b245ea7..424a763 100644 --- a/album/src/main/java/hive/album/controller/AlbumController.java +++ b/album/src/main/java/hive/album/controller/AlbumController.java @@ -1,7 +1,7 @@ package hive.album.controller; -import hive.album.entity.Something; import hive.album.storage.iStorageService; +import hive.common.security.HiveHeaders; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpHeaders; import org.springframework.http.ResponseEntity; @@ -22,15 +22,6 @@ public class AlbumController { public String a(){ return "a"; } - @GetMapping("/sum") - public Something sumNumbers(@RequestParam(value = "n1", required = false) String n1, - @RequestParam(value = "n2", required = false) String n2) { - var algo =new Something(); - int num1=Integer.parseInt(n1); - num1+= Integer.parseInt(n2); - algo.setContent("soma "+(num1)); - return algo; - } private final iStorageService storageService; @Autowired @@ -47,19 +38,21 @@ public String listUploadedImages(Model model) throws IOException { return "uploadForm"; } */ - @GetMapping("/files/{filename:.+}") + @GetMapping("/smugshot/{filename:.+}") @ResponseBody - public ResponseEntity serveFile(@PathVariable String filename) { - + public ResponseEntity serveFile + (@PathVariable String filename, + @RequestHeader(name = HiveHeaders.AUTHENTICATED_USER_NAME_HEADER) final String username) + { Resource file = storageService.loadAsResource(filename); - return ResponseEntity.ok().header(HttpHeaders.CONTENT_DISPOSITION, + return ResponseEntity.ok().header( + HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + file.getFilename() + "\"").body(file); } - @PostMapping("/") + @PostMapping("/smugshot/") public String handleFileUpload(@RequestParam("file") MultipartFile file) { storageService.store(file); return "{Mensagem:Sucesso}"; } - } diff --git a/album/src/main/java/hive/album/repository/imageRespository.java b/album/src/main/java/hive/album/repository/imageRespository.java new file mode 100644 index 0000000..ed53036 --- /dev/null +++ b/album/src/main/java/hive/album/repository/imageRespository.java @@ -0,0 +1,9 @@ +package hive.album.repository; + +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.stereotype.Repository; + +@Repository +interface imageRespository extends JpaRepository { + +} \ No newline at end of file diff --git a/album/src/main/java/hive/album/storage/FileSystemStorageService.java b/album/src/main/java/hive/album/storage/FileSystemStorageService.java index 1b44111..ea8a602 100644 --- a/album/src/main/java/hive/album/storage/FileSystemStorageService.java +++ b/album/src/main/java/hive/album/storage/FileSystemStorageService.java @@ -8,7 +8,7 @@ import java.nio.file.StandardCopyOption; import java.util.stream.Stream; -import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; import org.springframework.core.io.Resource; import org.springframework.core.io.UrlResource; import org.springframework.stereotype.Service; @@ -18,12 +18,12 @@ @Service public class FileSystemStorageService implements iStorageService{ - - private final Path rootLocation; - + @Value("${hive.mugshot.image-directory-path}") + private String imageDirectoryPathAsString; + private Path imageDirectoryPath; //@Autowired public FileSystemStorageService() { - this.rootLocation = Paths.get("C:\\Users\\Germano\\Desktop\\AlbumTest"); + this.imageDirectoryPath = Paths.get(imageDirectoryPathAsString); } @Override @@ -42,7 +42,7 @@ public void store(MultipartFile file) { throw new RuntimeException(); } try (InputStream inputStream = file.getInputStream()) { - Files.copy(inputStream, this.rootLocation.resolve(filename), + Files.copy(inputStream, this.imageDirectoryPath.resolve(filename), StandardCopyOption.REPLACE_EXISTING); } } @@ -55,9 +55,9 @@ public void store(MultipartFile file) { @Override public Stream loadAll() { try { - return Files.walk(this.rootLocation, 1) - .filter(path -> !path.equals(this.rootLocation)) - .map(this.rootLocation::relativize); + return Files.walk(this.imageDirectoryPath, 1) + .filter(path -> !path.equals(this.imageDirectoryPath)) + .map(this.imageDirectoryPath::relativize); } catch (IOException e) { //throw new StorageException("Failed to read stored files", e); @@ -68,7 +68,7 @@ public Stream loadAll() { @Override public Path load(String filename) { - return rootLocation.resolve(filename); + return imageDirectoryPath.resolve(filename); } @Override @@ -91,13 +91,13 @@ public Resource loadAsResource(String filename) { @Override public void deleteAll() { - FileSystemUtils.deleteRecursively(rootLocation.toFile()); + FileSystemUtils.deleteRecursively(imageDirectoryPath.toFile()); } @Override public void init() { try { - Files.createDirectories(rootLocation); + Files.createDirectories(imageDirectoryPath); } catch (IOException e) { throw new RuntimeException("Could not initialize storage", e); diff --git a/album/src/main/resources/application.properties b/album/src/main/resources/application.properties index 0fe8530..7b1cedd 100644 --- a/album/src/main/resources/application.properties +++ b/album/src/main/resources/application.properties @@ -1,4 +1,4 @@ -spring.application.name=album-service +spring.application.name=smugshot-service server.port=9500 eureka.client.service-url.default-zone=http://localhost:8761/eureka # H2 @@ -13,4 +13,5 @@ spring.datasource.driver-class-name=org.h2.Driver spring.jpa.hibernate.ddl-auto=create spring.jpa.show-sql=true spring.jpa.properties.hibernate.format_sql=true -logging.level.org.hibernate.type=trace \ No newline at end of file +logging.level.org.hibernate.type=trace +hive.mugshot.image-directory-path=./smugshot_images_profiles \ No newline at end of file diff --git a/album/src/test/java/hive/album/AlbumApplicationTests.java b/album/src/test/java/hive/album/SmugshotApplicationTests.java similarity index 87% rename from album/src/test/java/hive/album/AlbumApplicationTests.java rename to album/src/test/java/hive/album/SmugshotApplicationTests.java index d9d808c..0d7a069 100644 --- a/album/src/test/java/hive/album/AlbumApplicationTests.java +++ b/album/src/test/java/hive/album/SmugshotApplicationTests.java @@ -7,7 +7,7 @@ @RunWith(SpringRunner.class) @SpringBootTest -public class AlbumApplicationTests { +public class SmugshotApplicationTests { @Test public void contextLoads() { From e63440e61b926794495aea3a8f1eeaa48a7e90a4 Mon Sep 17 00:00:00 2001 From: germano Date: Sun, 14 Apr 2019 01:28:57 -0300 Subject: [PATCH 03/54] Reformulated the Profile Images's API --- .../java/hive/album/MugshotApplication.java | 16 +++ .../album/controller/AlbumController.java | 58 ---------- .../album/controller/MugshotController.java | 62 ++++++++++ .../java/hive/album/entity/ProfileImage.java | 25 +++++ .../album/exception/FileSizeException.java | 7 ++ .../exception/ImageAlreadyExistException.java | 7 ++ .../hive/album/exception/ImageNotFound.java | 7 ++ .../exception/ImageProfileException.java | 7 ++ .../album/exception/InvalidPathException.java | 8 ++ .../hive/album/repository/UserRepository.java | 2 + .../album/repository/imageRespository.java | 9 -- .../storage/FileSystemStorageService.java | 106 ------------------ .../java/hive/album/storage/ImageStorer.java | 62 ++++++++++ .../hive/album/storage/iStorageService.java | 23 ---- .../src/main/resources/application.properties | 2 +- .../controller/SmugshotControllerTest.java | 14 +++ 16 files changed, 218 insertions(+), 197 deletions(-) create mode 100644 album/src/main/java/hive/album/MugshotApplication.java delete mode 100644 album/src/main/java/hive/album/controller/AlbumController.java create mode 100644 album/src/main/java/hive/album/controller/MugshotController.java create mode 100644 album/src/main/java/hive/album/entity/ProfileImage.java create mode 100644 album/src/main/java/hive/album/exception/FileSizeException.java create mode 100644 album/src/main/java/hive/album/exception/ImageAlreadyExistException.java create mode 100644 album/src/main/java/hive/album/exception/ImageNotFound.java create mode 100644 album/src/main/java/hive/album/exception/ImageProfileException.java create mode 100644 album/src/main/java/hive/album/exception/InvalidPathException.java delete mode 100644 album/src/main/java/hive/album/repository/imageRespository.java delete mode 100644 album/src/main/java/hive/album/storage/FileSystemStorageService.java create mode 100644 album/src/main/java/hive/album/storage/ImageStorer.java delete mode 100644 album/src/main/java/hive/album/storage/iStorageService.java create mode 100644 album/src/test/java/hive/album/controller/SmugshotControllerTest.java diff --git a/album/src/main/java/hive/album/MugshotApplication.java b/album/src/main/java/hive/album/MugshotApplication.java new file mode 100644 index 0000000..c1d70b3 --- /dev/null +++ b/album/src/main/java/hive/album/MugshotApplication.java @@ -0,0 +1,16 @@ +package hive.album; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.boot.autoconfigure.domain.EntityScan; +import org.springframework.cloud.netflix.eureka.EnableEurekaClient; + +@SpringBootApplication +@EnableEurekaClient +@EntityScan( basePackages = {"hive.entity"} ) +public class MugshotApplication { + public static void main(String[] args) { + SpringApplication.run(MugshotApplication.class, args); + } + +} diff --git a/album/src/main/java/hive/album/controller/AlbumController.java b/album/src/main/java/hive/album/controller/AlbumController.java deleted file mode 100644 index 424a763..0000000 --- a/album/src/main/java/hive/album/controller/AlbumController.java +++ /dev/null @@ -1,58 +0,0 @@ -package hive.album.controller; - -import hive.album.storage.iStorageService; -import hive.common.security.HiveHeaders; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.http.HttpHeaders; -import org.springframework.http.ResponseEntity; -import org.springframework.ui.Model; -import org.springframework.core.io.Resource; -import org.springframework.web.bind.annotation.*; -import org.springframework.web.multipart.MultipartFile; -import org.springframework.web.servlet.mvc.method.annotation.MvcUriComponentsBuilder; -import org.springframework.web.servlet.mvc.support.RedirectAttributes; - -import java.io.IOException; -import java.util.stream.Collectors; - -@RestController -@RequestMapping("/") -public class AlbumController { - @GetMapping("/") - public String a(){ - return "a"; - } - private final iStorageService storageService; - - @Autowired - public AlbumController(iStorageService storageService) { - this.storageService = storageService; - } -/* - @GetMapping("/") - public String listUploadedImages(Model model) throws IOException { - model.addAttribute("files", storageService.loadAll().map( - path -> MvcUriComponentsBuilder.fromMethodName(FileUploadController.class, - "serveFile", path.getFileName().toString()).build().toString()) - .collect(Collectors.toList())); - return "uploadForm"; - } -*/ - @GetMapping("/smugshot/{filename:.+}") - @ResponseBody - public ResponseEntity serveFile - (@PathVariable String filename, - @RequestHeader(name = HiveHeaders.AUTHENTICATED_USER_NAME_HEADER) final String username) - { - Resource file = storageService.loadAsResource(filename); - return ResponseEntity.ok().header( - HttpHeaders.CONTENT_DISPOSITION, - "attachment; filename=\"" + file.getFilename() + "\"").body(file); - } - - @PostMapping("/smugshot/") - public String handleFileUpload(@RequestParam("file") MultipartFile file) { - storageService.store(file); - return "{Mensagem:Sucesso}"; - } -} diff --git a/album/src/main/java/hive/album/controller/MugshotController.java b/album/src/main/java/hive/album/controller/MugshotController.java new file mode 100644 index 0000000..22cb647 --- /dev/null +++ b/album/src/main/java/hive/album/controller/MugshotController.java @@ -0,0 +1,62 @@ +package hive.album.controller; + +import hive.album.entity.ProfileImage; +import hive.album.exception.ImageNotFound; +import hive.album.repository.UserRepository; +import hive.album.storage.ImageStorer; +import hive.common.security.HiveHeaders; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpStatus; +import org.springframework.http.MediaType; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.*; +import org.springframework.web.multipart.MultipartFile; +import org.springframework.core.io.Resource; + +import javax.servlet.http.HttpServletResponse; +import java.io.IOException; +import java.nio.file.NoSuchFileException; +import java.nio.file.Paths; + +@RestController +@RequestMapping("/") +public class MugshotController { + private final UserRepository userRepository; + @Value("${hive.mugshot.image-directory-path}") + private String rootDir; + @Autowired + private ImageStorer imageStorer; + @ResponseStatus(code = HttpStatus.I_AM_A_TEAPOT, reason = "The server is working") + @GetMapping("/hey") + public void hey() {} + @GetMapping("/dir") + public String getRootDirectory() { + return rootDir; + } + @Autowired + public MugshotController(UserRepository userRepository) { + this.userRepository = userRepository; + } + //tratar multiplos arquivos excecao + //tratar replace de imagens + //tratar replace de imagem não proprietaria + //tratar renomeacao de imagem + @PostMapping("smugshot") + public String sendImageProfile + ( @RequestParam("image") MultipartFile insertedImage, + @RequestHeader(name = HiveHeaders.AUTHENTICATED_USER_NAME_HEADER) final String username) { + return imageStorer.StoreImageProfile(insertedImage); + } + @GetMapping(value="smugshot/{profileImageName:.+}",produces = MediaType.IMAGE_JPEG_VALUE) + public ResponseEntity searchProfileImage + (@RequestHeader(name = HiveHeaders.AUTHENTICATED_USER_NAME_HEADER) final String username, + @PathVariable String profileImageName){ + var user = userRepository.findByUsername(username); + Resource file = imageStorer.loadImage(profileImageName); + return ResponseEntity.ok().header( + HttpHeaders.CONTENT_DISPOSITION, + "attachment; filename=\"" + file.getFilename() + "\"").body(file); + } +} diff --git a/album/src/main/java/hive/album/entity/ProfileImage.java b/album/src/main/java/hive/album/entity/ProfileImage.java new file mode 100644 index 0000000..f302d39 --- /dev/null +++ b/album/src/main/java/hive/album/entity/ProfileImage.java @@ -0,0 +1,25 @@ +package hive.album.entity; + +public class ProfileImage { + private String path; + private String content; + + public ProfileImage() { + } + public ProfileImage(String path, String content) { + this.path = path; + this.content = content; + } + public String getPath() { + return path; + } + public void setPath(String path) { + this.path = path; + } + public String getContent() { + return content; + } + public void setContent(String content) { + this.content = content; + } +} diff --git a/album/src/main/java/hive/album/exception/FileSizeException.java b/album/src/main/java/hive/album/exception/FileSizeException.java new file mode 100644 index 0000000..efa38f4 --- /dev/null +++ b/album/src/main/java/hive/album/exception/FileSizeException.java @@ -0,0 +1,7 @@ +package hive.album.exception; +import org.springframework.http.HttpStatus; +import org.springframework.web.bind.annotation.ResponseStatus; + +@ResponseStatus(code = HttpStatus.BAD_REQUEST, reason = "Invalid size of file") +public class FileSizeException extends RuntimeException{ +} diff --git a/album/src/main/java/hive/album/exception/ImageAlreadyExistException.java b/album/src/main/java/hive/album/exception/ImageAlreadyExistException.java new file mode 100644 index 0000000..a9be030 --- /dev/null +++ b/album/src/main/java/hive/album/exception/ImageAlreadyExistException.java @@ -0,0 +1,7 @@ +package hive.album.exception; +import org.springframework.http.HttpStatus; +import org.springframework.web.bind.annotation.ResponseStatus; + +@ResponseStatus(code = HttpStatus.BAD_REQUEST, reason = "The Image already exists") +public class ImageAlreadyExistException extends RuntimeException{ +} diff --git a/album/src/main/java/hive/album/exception/ImageNotFound.java b/album/src/main/java/hive/album/exception/ImageNotFound.java new file mode 100644 index 0000000..dc009d9 --- /dev/null +++ b/album/src/main/java/hive/album/exception/ImageNotFound.java @@ -0,0 +1,7 @@ +package hive.album.exception; +import org.springframework.http.HttpStatus; +import org.springframework.web.bind.annotation.ResponseStatus; + +@ResponseStatus(code = HttpStatus.BAD_REQUEST, reason = "Image not found") +public class ImageNotFound extends RuntimeException{ +} diff --git a/album/src/main/java/hive/album/exception/ImageProfileException.java b/album/src/main/java/hive/album/exception/ImageProfileException.java new file mode 100644 index 0000000..71651c2 --- /dev/null +++ b/album/src/main/java/hive/album/exception/ImageProfileException.java @@ -0,0 +1,7 @@ +package hive.album.exception; +import org.springframework.http.HttpStatus; +import org.springframework.web.bind.annotation.ResponseStatus; + +@ResponseStatus(code = HttpStatus.BAD_REQUEST, reason = "Failed to store the image due to some I/O problem or permission") +public class ImageProfileException extends RuntimeException{ +} diff --git a/album/src/main/java/hive/album/exception/InvalidPathException.java b/album/src/main/java/hive/album/exception/InvalidPathException.java new file mode 100644 index 0000000..348c5ff --- /dev/null +++ b/album/src/main/java/hive/album/exception/InvalidPathException.java @@ -0,0 +1,8 @@ +package hive.album.exception; + +import org.springframework.http.HttpStatus; +import org.springframework.web.bind.annotation.ResponseStatus; + +@ResponseStatus(code = HttpStatus.BAD_REQUEST, reason = "Invalid path") +public class InvalidPathException extends RuntimeException { +} \ No newline at end of file diff --git a/album/src/main/java/hive/album/repository/UserRepository.java b/album/src/main/java/hive/album/repository/UserRepository.java index f8a8278..2982937 100644 --- a/album/src/main/java/hive/album/repository/UserRepository.java +++ b/album/src/main/java/hive/album/repository/UserRepository.java @@ -4,5 +4,7 @@ import org.springframework.data.repository.CrudRepository; public interface UserRepository extends CrudRepository { + User findByUsername(String username); + } diff --git a/album/src/main/java/hive/album/repository/imageRespository.java b/album/src/main/java/hive/album/repository/imageRespository.java deleted file mode 100644 index ed53036..0000000 --- a/album/src/main/java/hive/album/repository/imageRespository.java +++ /dev/null @@ -1,9 +0,0 @@ -package hive.album.repository; - -import org.springframework.data.jpa.repository.JpaRepository; -import org.springframework.stereotype.Repository; - -@Repository -interface imageRespository extends JpaRepository { - -} \ No newline at end of file diff --git a/album/src/main/java/hive/album/storage/FileSystemStorageService.java b/album/src/main/java/hive/album/storage/FileSystemStorageService.java deleted file mode 100644 index ea8a602..0000000 --- a/album/src/main/java/hive/album/storage/FileSystemStorageService.java +++ /dev/null @@ -1,106 +0,0 @@ -package hive.album.storage; -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.Value; -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; - -@Service -public class FileSystemStorageService implements iStorageService{ - @Value("${hive.mugshot.image-directory-path}") - private String imageDirectoryPathAsString; - private Path imageDirectoryPath; - //@Autowired - public FileSystemStorageService() { - this.imageDirectoryPath = Paths.get(imageDirectoryPathAsString); - } - - @Override - public void store(MultipartFile file) { - String filename = StringUtils.cleanPath(file.getOriginalFilename()); - try { - if (file.isEmpty()) { - //throw new StorageException("Failed to store empty file " + filename); - throw new RuntimeException(); - } - if (filename.contains("..")) { - // This is a security check - /*throw new StorageException( - "Cannot store file with relative path outside current directory " - + filename);*/ - throw new RuntimeException(); - } - try (InputStream inputStream = file.getInputStream()) { - Files.copy(inputStream, this.imageDirectoryPath.resolve(filename), - StandardCopyOption.REPLACE_EXISTING); - } - } - catch (IOException e) { - //throw new StorageException("Failed to store file " + filename, e); - throw new RuntimeException("Failed to store file " + filename, e); - } - } - - @Override - public Stream loadAll() { - try { - return Files.walk(this.imageDirectoryPath, 1) - .filter(path -> !path.equals(this.imageDirectoryPath)) - .map(this.imageDirectoryPath::relativize); - } - catch (IOException e) { - //throw new StorageException("Failed to read stored files", e); - throw new RuntimeException("Failed to read stored files", e); - } - - } - - @Override - public Path load(String filename) { - return imageDirectoryPath.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 RuntimeException("Could not read file: " + filename); - - } - } - catch (MalformedURLException e) { - throw new RuntimeException("Could not read file: " + filename, e); - } - } - - @Override - public void deleteAll() { - FileSystemUtils.deleteRecursively(imageDirectoryPath.toFile()); - } - - @Override - public void init() { - try { - Files.createDirectories(imageDirectoryPath); - } - catch (IOException e) { - throw new RuntimeException("Could not initialize storage", e); - } - } -} \ No newline at end of file diff --git a/album/src/main/java/hive/album/storage/ImageStorer.java b/album/src/main/java/hive/album/storage/ImageStorer.java new file mode 100644 index 0000000..9036d81 --- /dev/null +++ b/album/src/main/java/hive/album/storage/ImageStorer.java @@ -0,0 +1,62 @@ +package hive.album.storage; + +import hive.album.exception.ImageAlreadyExistException; +import hive.album.exception.ImageProfileException; +import hive.album.exception.InvalidPathException; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.core.io.Resource; +import org.springframework.core.io.UrlResource; +import org.springframework.stereotype.Service; +import org.springframework.web.multipart.MultipartFile; + +import java.io.IOException; +import java.net.MalformedURLException; +import java.nio.file.FileAlreadyExistsException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; + +@Service +public class ImageStorer { + @Value("${hive.mugshot.image-directory-path}") + private String rootDir; + private Path resolvePathFullUrlWith(String filename) { + return Paths.get(rootDir).resolve(filename); + } + public String StoreImageProfile(MultipartFile insertedImage){ + this.createDirectoryIfNotExist(); + try { + Files.copy( insertedImage.getInputStream(), + Paths.get(rootDir).resolve(insertedImage.getOriginalFilename())); + }catch(FileAlreadyExistsException e){ + throw new ImageAlreadyExistException(); + } + catch (IOException e) { + throw new RuntimeException(e); + } + return "Image Stored in Success"; + } + private void createDirectoryIfNotExist(){ + Path parentDir = Paths.get(rootDir); + if (!Files.exists(parentDir)) { + try { + Files.createDirectories(parentDir); + } catch (IOException e) { + throw new RuntimeException("Not capable to create the directory.\n"+e); + } + } + } + public Resource loadImage(String ImageName) { + try { + Path file = resolvePathFullUrlWith(ImageName); + Resource resource = new UrlResource(file.toUri()); + if (resource.exists() || resource.isReadable()) { + return resource; + } + } catch (MalformedURLException e) { + e.printStackTrace(); + throw new InvalidPathException(); + } + return null; + } +} diff --git a/album/src/main/java/hive/album/storage/iStorageService.java b/album/src/main/java/hive/album/storage/iStorageService.java deleted file mode 100644 index e324b07..0000000 --- a/album/src/main/java/hive/album/storage/iStorageService.java +++ /dev/null @@ -1,23 +0,0 @@ -package hive.album.storage; - -import org.springframework.core.io.Resource; -import org.springframework.web.multipart.MultipartFile; - -import java.nio.file.Path; -import java.util.stream.Stream; - -public interface iStorageService { - - void init(); - - void store(MultipartFile file); - - Stream loadAll(); - - Path load(String filename); - - Resource loadAsResource(String filename); - - void deleteAll(); - -} \ No newline at end of file diff --git a/album/src/main/resources/application.properties b/album/src/main/resources/application.properties index 7b1cedd..05801a2 100644 --- a/album/src/main/resources/application.properties +++ b/album/src/main/resources/application.properties @@ -14,4 +14,4 @@ spring.jpa.hibernate.ddl-auto=create spring.jpa.show-sql=true spring.jpa.properties.hibernate.format_sql=true logging.level.org.hibernate.type=trace -hive.mugshot.image-directory-path=./smugshot_images_profiles \ No newline at end of file +hive.mugshot.image-directory-path=../smugshot_images_profiles \ No newline at end of file diff --git a/album/src/test/java/hive/album/controller/SmugshotControllerTest.java b/album/src/test/java/hive/album/controller/SmugshotControllerTest.java new file mode 100644 index 0000000..933b6c6 --- /dev/null +++ b/album/src/test/java/hive/album/controller/SmugshotControllerTest.java @@ -0,0 +1,14 @@ +package hive.album.controller; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +@RunWith(SpringRunner.class) +@SpringBootTest +public class SmugshotControllerTest { + @Test + public void givenAutenticatedUserNameDoesNotOwnImage_WhenUploadImage_then430isReturned() { + } +} From 9f3baec7b430ee28adb8394784527a78bbf095ff Mon Sep 17 00:00:00 2001 From: germano Date: Sun, 14 Apr 2019 17:26:26 -0300 Subject: [PATCH 04/54] Added Delete Method. Post and Gets uses username as folder name now. --- .../album/controller/MugshotController.java | 81 +++++++++++-------- .../java/hive/album/storage/ImageStorer.java | 40 ++++++--- 2 files changed, 77 insertions(+), 44 deletions(-) diff --git a/album/src/main/java/hive/album/controller/MugshotController.java b/album/src/main/java/hive/album/controller/MugshotController.java index 22cb647..7175ae3 100644 --- a/album/src/main/java/hive/album/controller/MugshotController.java +++ b/album/src/main/java/hive/album/controller/MugshotController.java @@ -1,10 +1,10 @@ package hive.album.controller; -import hive.album.entity.ProfileImage; -import hive.album.exception.ImageNotFound; +import hive.album.exception.UserNotFoundException; import hive.album.repository.UserRepository; import hive.album.storage.ImageStorer; import hive.common.security.HiveHeaders; +import hive.entity.user.User; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.http.HttpHeaders; @@ -15,48 +15,65 @@ import org.springframework.web.multipart.MultipartFile; import org.springframework.core.io.Resource; -import javax.servlet.http.HttpServletResponse; -import java.io.IOException; -import java.nio.file.NoSuchFileException; -import java.nio.file.Paths; - @RestController -@RequestMapping("/") +@RequestMapping("/smugshot") public class MugshotController { - private final UserRepository userRepository; + @Value("${hive.mugshot.image-directory-path}") private String rootDir; - @Autowired - private ImageStorer imageStorer; - @ResponseStatus(code = HttpStatus.I_AM_A_TEAPOT, reason = "The server is working") - @GetMapping("/hey") - public void hey() {} - @GetMapping("/dir") - public String getRootDirectory() { + + private final ImageStorer imageStorer; + private final UserRepository userRepository; + + @Autowired public MugshotController(UserRepository userRepository,ImageStorer imageStorer) { + this.imageStorer=imageStorer; + this.userRepository = userRepository; + userRepository.save(new User("TESTE","123",0,0)); + userRepository.save(new User("GERMANO","123",0,0)); + userRepository.save(new User("JAVA","123",0,0)); + } + + @ResponseStatus(code = HttpStatus.I_AM_A_TEAPOT, reason = "The server is working and have an user") + @GetMapping("/hey") public void hey(){} + + @GetMapping("/dir") public String getRootDirectory() { return rootDir; } - @Autowired - public MugshotController(UserRepository userRepository) { - this.userRepository = userRepository; + @GetMapping("/user") public String getUser + (@RequestHeader(name = HiveHeaders.AUTHENTICATED_USER_NAME_HEADER) final String username) + { + var user=userRepository.findByUsername(username); + return user.getUsername(); } //tratar multiplos arquivos excecao //tratar replace de imagens //tratar replace de imagem não proprietaria //tratar renomeacao de imagem - @PostMapping("smugshot") - public String sendImageProfile - ( @RequestParam("image") MultipartFile insertedImage, - @RequestHeader(name = HiveHeaders.AUTHENTICATED_USER_NAME_HEADER) final String username) { - return imageStorer.StoreImageProfile(insertedImage); + @PostMapping + public String sendImageProfile(@RequestParam("image") MultipartFile insertedImage, @RequestHeader(name = HiveHeaders.AUTHENTICATED_USER_NAME_HEADER) final String username) { + var user = userRepository.findByUsername(username); + if(user==null){ + throw new UserNotFoundException(); + } + return imageStorer.StoreImageProfile(username,insertedImage); } - @GetMapping(value="smugshot/{profileImageName:.+}",produces = MediaType.IMAGE_JPEG_VALUE) - public ResponseEntity searchProfileImage - (@RequestHeader(name = HiveHeaders.AUTHENTICATED_USER_NAME_HEADER) final String username, - @PathVariable String profileImageName){ + + @GetMapping(value = "/{profileImageName:.+}", produces = MediaType.IMAGE_JPEG_VALUE) + public ResponseEntity searchProfileImage(@RequestHeader(name = HiveHeaders.AUTHENTICATED_USER_NAME_HEADER) final String username, @PathVariable String profileImageName) { + var user = userRepository.findByUsername(username); + if(user==null){ + throw new UserNotFoundException(); + } + Resource file = imageStorer.loadImage(username,profileImageName); + return ResponseEntity.ok().header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + file.getFilename() + "\"").body(file); + } + + @DeleteMapping + public void deleteProfileImage(@RequestHeader(name = HiveHeaders.AUTHENTICATED_USER_NAME_HEADER) final String username) { var user = userRepository.findByUsername(username); - Resource file = imageStorer.loadImage(profileImageName); - return ResponseEntity.ok().header( - HttpHeaders.CONTENT_DISPOSITION, - "attachment; filename=\"" + file.getFilename() + "\"").body(file); + if(user==null){ + throw new UserNotFoundException(); + } + imageStorer.deleteAllUserImages(username); } } diff --git a/album/src/main/java/hive/album/storage/ImageStorer.java b/album/src/main/java/hive/album/storage/ImageStorer.java index 9036d81..0c1a06c 100644 --- a/album/src/main/java/hive/album/storage/ImageStorer.java +++ b/album/src/main/java/hive/album/storage/ImageStorer.java @@ -1,6 +1,7 @@ package hive.album.storage; import hive.album.exception.ImageAlreadyExistException; +import hive.album.exception.ImageNotFound; import hive.album.exception.ImageProfileException; import hive.album.exception.InvalidPathException; import org.springframework.beans.factory.annotation.Value; @@ -20,14 +21,14 @@ public class ImageStorer { @Value("${hive.mugshot.image-directory-path}") private String rootDir; - private Path resolvePathFullUrlWith(String filename) { - return Paths.get(rootDir).resolve(filename); - } - public String StoreImageProfile(MultipartFile insertedImage){ - this.createDirectoryIfNotExist(); + + public String StoreImageProfile(String userDirectoryName,MultipartFile insertedImage){ + this.createDirectoryIfNotExist(userDirectoryName); try { - Files.copy( insertedImage.getInputStream(), - Paths.get(rootDir).resolve(insertedImage.getOriginalFilename())); + Files.copy( + insertedImage.getInputStream(), + resolvePathFullUrlWith(userDirectoryName,insertedImage.getOriginalFilename()) + ); }catch(FileAlreadyExistsException e){ throw new ImageAlreadyExistException(); } @@ -36,8 +37,8 @@ public String StoreImageProfile(MultipartFile insertedImage){ } return "Image Stored in Success"; } - private void createDirectoryIfNotExist(){ - Path parentDir = Paths.get(rootDir); + private void createDirectoryIfNotExist(String userDirectoryPath){ + Path parentDir = Paths.get(rootDir,userDirectoryPath); if (!Files.exists(parentDir)) { try { Files.createDirectories(parentDir); @@ -46,17 +47,32 @@ private void createDirectoryIfNotExist(){ } } } - public Resource loadImage(String ImageName) { + + public Resource loadImage(String userDirectoryName,String ImageName) { try { - Path file = resolvePathFullUrlWith(ImageName); + Path file = resolvePathFullUrlWith(userDirectoryName,ImageName); Resource resource = new UrlResource(file.toUri()); if (resource.exists() || resource.isReadable()) { return resource; + }else{ + throw new ImageNotFound(); } } catch (MalformedURLException e) { e.printStackTrace(); throw new InvalidPathException(); } - return null; + } + private Path resolvePathFullUrlWith(String userDirectoryName,String filename) { + return Paths.get(rootDir).resolve(userDirectoryName).resolve(filename); + } + + public void deleteAllUserImages(String userDirectoryName) { + Path parentDir = Paths.get(rootDir,userDirectoryName); + try { + Files.deleteIfExists(parentDir); + } catch (IOException e) { + e.printStackTrace(); + throw new RuntimeException("Not capable to delete the directory.\n"+e); + } } } From 362c801e37d7f1412e9516ef33df3b0c9cdd8b9d Mon Sep 17 00:00:00 2001 From: germano Date: Sun, 14 Apr 2019 17:28:57 -0300 Subject: [PATCH 05/54] Added new Exceptions and alteration in the root images directory. --- album/src/main/java/hive/album/MugshotApplication.java | 1 - .../src/main/java/hive/album/exception/ImageNotFound.java | 2 +- .../java/hive/album/exception/UserNotFoundException.java | 8 ++++++++ .../main/java/hive/album/repository/UserRepository.java | 4 ++-- album/src/main/resources/application.properties | 2 +- 5 files changed, 12 insertions(+), 5 deletions(-) create mode 100644 album/src/main/java/hive/album/exception/UserNotFoundException.java diff --git a/album/src/main/java/hive/album/MugshotApplication.java b/album/src/main/java/hive/album/MugshotApplication.java index c1d70b3..a98245f 100644 --- a/album/src/main/java/hive/album/MugshotApplication.java +++ b/album/src/main/java/hive/album/MugshotApplication.java @@ -12,5 +12,4 @@ public class MugshotApplication { public static void main(String[] args) { SpringApplication.run(MugshotApplication.class, args); } - } diff --git a/album/src/main/java/hive/album/exception/ImageNotFound.java b/album/src/main/java/hive/album/exception/ImageNotFound.java index dc009d9..f2c1563 100644 --- a/album/src/main/java/hive/album/exception/ImageNotFound.java +++ b/album/src/main/java/hive/album/exception/ImageNotFound.java @@ -2,6 +2,6 @@ import org.springframework.http.HttpStatus; import org.springframework.web.bind.annotation.ResponseStatus; -@ResponseStatus(code = HttpStatus.BAD_REQUEST, reason = "Image not found") +@ResponseStatus(code = HttpStatus.NOT_FOUND, reason = "Image not found for this user") public class ImageNotFound extends RuntimeException{ } diff --git a/album/src/main/java/hive/album/exception/UserNotFoundException.java b/album/src/main/java/hive/album/exception/UserNotFoundException.java new file mode 100644 index 0000000..e45007a --- /dev/null +++ b/album/src/main/java/hive/album/exception/UserNotFoundException.java @@ -0,0 +1,8 @@ +package hive.album.exception; + +import org.springframework.http.HttpStatus; +import org.springframework.web.bind.annotation.ResponseStatus; + +@ResponseStatus(code = HttpStatus.BAD_REQUEST, reason = "The user does not exist") +public class UserNotFoundException extends RuntimeException { +} \ No newline at end of file diff --git a/album/src/main/java/hive/album/repository/UserRepository.java b/album/src/main/java/hive/album/repository/UserRepository.java index 2982937..b18c313 100644 --- a/album/src/main/java/hive/album/repository/UserRepository.java +++ b/album/src/main/java/hive/album/repository/UserRepository.java @@ -2,9 +2,9 @@ import hive.entity.user.User; import org.springframework.data.repository.CrudRepository; +import org.springframework.http.HttpStatus; +import org.springframework.web.bind.annotation.ResponseStatus; public interface UserRepository extends CrudRepository { - User findByUsername(String username); - } diff --git a/album/src/main/resources/application.properties b/album/src/main/resources/application.properties index 05801a2..7b1cedd 100644 --- a/album/src/main/resources/application.properties +++ b/album/src/main/resources/application.properties @@ -14,4 +14,4 @@ spring.jpa.hibernate.ddl-auto=create spring.jpa.show-sql=true spring.jpa.properties.hibernate.format_sql=true logging.level.org.hibernate.type=trace -hive.mugshot.image-directory-path=../smugshot_images_profiles \ No newline at end of file +hive.mugshot.image-directory-path=./smugshot_images_profiles \ No newline at end of file From f55ec29059a350afa17bbf5be832d57572c2d1b5 Mon Sep 17 00:00:00 2001 From: germano Date: Fri, 19 Apr 2019 15:26:10 -0300 Subject: [PATCH 06/54] Removed verifications of user existence. --- .../java/hive/album/controller/MugshotController.java | 11 +---------- 1 file changed, 1 insertion(+), 10 deletions(-) diff --git a/album/src/main/java/hive/album/controller/MugshotController.java b/album/src/main/java/hive/album/controller/MugshotController.java index 7175ae3..4211ed9 100644 --- a/album/src/main/java/hive/album/controller/MugshotController.java +++ b/album/src/main/java/hive/album/controller/MugshotController.java @@ -33,7 +33,7 @@ public class MugshotController { userRepository.save(new User("JAVA","123",0,0)); } - @ResponseStatus(code = HttpStatus.I_AM_A_TEAPOT, reason = "The server is working and have an user") + @ResponseStatus(code = HttpStatus.OK, reason = "The server is working and have an user") @GetMapping("/hey") public void hey(){} @GetMapping("/dir") public String getRootDirectory() { @@ -52,18 +52,12 @@ public class MugshotController { @PostMapping public String sendImageProfile(@RequestParam("image") MultipartFile insertedImage, @RequestHeader(name = HiveHeaders.AUTHENTICATED_USER_NAME_HEADER) final String username) { var user = userRepository.findByUsername(username); - if(user==null){ - throw new UserNotFoundException(); - } return imageStorer.StoreImageProfile(username,insertedImage); } @GetMapping(value = "/{profileImageName:.+}", produces = MediaType.IMAGE_JPEG_VALUE) public ResponseEntity searchProfileImage(@RequestHeader(name = HiveHeaders.AUTHENTICATED_USER_NAME_HEADER) final String username, @PathVariable String profileImageName) { var user = userRepository.findByUsername(username); - if(user==null){ - throw new UserNotFoundException(); - } Resource file = imageStorer.loadImage(username,profileImageName); return ResponseEntity.ok().header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + file.getFilename() + "\"").body(file); } @@ -71,9 +65,6 @@ public ResponseEntity searchProfileImage(@RequestHeader(name = HiveHea @DeleteMapping public void deleteProfileImage(@RequestHeader(name = HiveHeaders.AUTHENTICATED_USER_NAME_HEADER) final String username) { var user = userRepository.findByUsername(username); - if(user==null){ - throw new UserNotFoundException(); - } imageStorer.deleteAllUserImages(username); } } From 7631c725407dd5fd7e41c42811b04f546204f5b8 Mon Sep 17 00:00:00 2001 From: germano Date: Fri, 19 Apr 2019 23:10:16 -0300 Subject: [PATCH 07/54] Added:Image reSizer util --- .../java/hive/album/storage/ImageUtils.java | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) create mode 100644 album/src/main/java/hive/album/storage/ImageUtils.java diff --git a/album/src/main/java/hive/album/storage/ImageUtils.java b/album/src/main/java/hive/album/storage/ImageUtils.java new file mode 100644 index 0000000..0cf437e --- /dev/null +++ b/album/src/main/java/hive/album/storage/ImageUtils.java @@ -0,0 +1,17 @@ +package hive.album.storage; + +import java.awt.*; +import java.awt.image.BufferedImage; + +public class ImageUtils { + private static int imageSizeInPixels =256; + public static BufferedImage resizeImageToSquare(BufferedImage inputtedImage) { + // multi-pass bilinear div 2 + var bufferedImageWithNewSize = new BufferedImage(imageSizeInPixels, imageSizeInPixels, BufferedImage.TYPE_INT_RGB); + var reSizer = bufferedImageWithNewSize.createGraphics(); + reSizer.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR); + reSizer.drawImage(inputtedImage, 0, 0, imageSizeInPixels, imageSizeInPixels, null); + reSizer.dispose(); + return bufferedImageWithNewSize; + } +} From c5abfa8e024df55fbb163ca77e18480dbdcebd2d Mon Sep 17 00:00:00 2001 From: germano Date: Sat, 20 Apr 2019 01:06:40 -0300 Subject: [PATCH 08/54] Alteration: Controller reduced to POST,GET,DELETE --- .../album/controller/MugshotController.java | 49 ++++++------------- 1 file changed, 15 insertions(+), 34 deletions(-) diff --git a/album/src/main/java/hive/album/controller/MugshotController.java b/album/src/main/java/hive/album/controller/MugshotController.java index 4211ed9..7e05293 100644 --- a/album/src/main/java/hive/album/controller/MugshotController.java +++ b/album/src/main/java/hive/album/controller/MugshotController.java @@ -16,55 +16,36 @@ import org.springframework.core.io.Resource; @RestController -@RequestMapping("/smugshot") +@RequestMapping("/mugshot") public class MugshotController { - @Value("${hive.mugshot.image-directory-path}") private String rootDir; - private final ImageStorer imageStorer; private final UserRepository userRepository; - - @Autowired public MugshotController(UserRepository userRepository,ImageStorer imageStorer) { - this.imageStorer=imageStorer; + private String imageName="ProfileImage.jpg"; + @Autowired public MugshotController(ImageStorer imageStorer,UserRepository userRepository) { this.userRepository = userRepository; - userRepository.save(new User("TESTE","123",0,0)); - userRepository.save(new User("GERMANO","123",0,0)); - userRepository.save(new User("JAVA","123",0,0)); + this.imageStorer = imageStorer; } - @ResponseStatus(code = HttpStatus.OK, reason = "The server is working and have an user") - @GetMapping("/hey") public void hey(){} - - @GetMapping("/dir") public String getRootDirectory() { - return rootDir; - } - @GetMapping("/user") public String getUser - (@RequestHeader(name = HiveHeaders.AUTHENTICATED_USER_NAME_HEADER) final String username) - { - var user=userRepository.findByUsername(username); - return user.getUsername(); - } - //tratar multiplos arquivos excecao - //tratar replace de imagens - //tratar replace de imagem não proprietaria - //tratar renomeacao de imagem + @ResponseStatus(code = HttpStatus.OK, reason = "Profile image Stored In Success") @PostMapping - public String sendImageProfile(@RequestParam("image") MultipartFile insertedImage, @RequestHeader(name = HiveHeaders.AUTHENTICATED_USER_NAME_HEADER) final String username) { - var user = userRepository.findByUsername(username); - return imageStorer.StoreImageProfile(username,insertedImage); + public void sendImageProfile(@RequestParam("image") MultipartFile insertedImage, @RequestHeader(name = HiveHeaders.AUTHENTICATED_USER_NAME_HEADER) final String username) { + var userID=userRepository.findByUsername(username).getId().toString(); + imageStorer.StoreImageProfile(userID,insertedImage,imageName); } - @GetMapping(value = "/{profileImageName:.+}", produces = MediaType.IMAGE_JPEG_VALUE) - public ResponseEntity searchProfileImage(@RequestHeader(name = HiveHeaders.AUTHENTICATED_USER_NAME_HEADER) final String username, @PathVariable String profileImageName) { - var user = userRepository.findByUsername(username); - Resource file = imageStorer.loadImage(username,profileImageName); + @GetMapping(produces = MediaType.IMAGE_JPEG_VALUE) + public ResponseEntity searchProfileImage(@RequestHeader(name = HiveHeaders.AUTHENTICATED_USER_NAME_HEADER) final String username) { + var userID=userRepository.findByUsername(username).getId().toString(); + Resource file = imageStorer.loadImage(userID,imageName); return ResponseEntity.ok().header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + file.getFilename() + "\"").body(file); } + @ResponseStatus(code = HttpStatus.NO_CONTENT, reason = "Profile image successfully deleted") @DeleteMapping public void deleteProfileImage(@RequestHeader(name = HiveHeaders.AUTHENTICATED_USER_NAME_HEADER) final String username) { - var user = userRepository.findByUsername(username); - imageStorer.deleteAllUserImages(username); + var userID=userRepository.findByUsername(username).getId().toString(); + imageStorer.deleteAllUserImages(userID,imageName); } } From dd832d122ab3ee058fd4c192c0dba762630ce009 Mon Sep 17 00:00:00 2001 From: germano Date: Sat, 20 Apr 2019 01:09:43 -0300 Subject: [PATCH 09/54] Added: Class intended to do general cool things like tree directories. For now this class contains some temporary methods to create hard-coded Users. --- .../album/controller/UtilsController.java | 50 +++++++++++++++++++ 1 file changed, 50 insertions(+) create mode 100644 album/src/main/java/hive/album/controller/UtilsController.java diff --git a/album/src/main/java/hive/album/controller/UtilsController.java b/album/src/main/java/hive/album/controller/UtilsController.java new file mode 100644 index 0000000..821844e --- /dev/null +++ b/album/src/main/java/hive/album/controller/UtilsController.java @@ -0,0 +1,50 @@ +package hive.album.controller; + +import hive.album.repository.UserRepository; +import hive.album.storage.ImageStorer; +import hive.common.security.HiveHeaders; +import hive.entity.user.User; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.core.io.Resource; +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpStatus; +import org.springframework.http.MediaType; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.*; + +@RestController +@RequestMapping("/utils") +public class UtilsController { + private final UserRepository userRepository; + private final ImageStorer imageStorer; + @ResponseStatus(code = HttpStatus.OK, reason = "The server is working and have an user") + @GetMapping("/hey") public void hey(){} + @GetMapping("/dir") public String getRootDirectory() { + return "nothing"; + } + @Autowired public UtilsController(UserRepository userRepository,ImageStorer imageStorer){ + this.userRepository=userRepository; + this.imageStorer=imageStorer; + userRepository.save(new User("User","123",0,0)); + userRepository.save(new User("Germano","123",0,0)); + userRepository.save(new User("Java","123",0,0)); + userRepository.save(new User("com espaço","123",0,0)); + userRepository.save(new User("com/barra","123",0,0)); + userRepository.save(new User("愛","123",0,0)); + } + @GetMapping("/user") public User getUser + (@RequestHeader(name = HiveHeaders.AUTHENTICATED_USER_NAME_HEADER) final String username) + { + return userRepository.findByUsername(username); + } + @GetMapping("/users") public Iterable getAllUser() + { + return userRepository.findAll(); + } + @GetMapping(value = "searchImage/{profileImageName:.+}", produces = MediaType.IMAGE_JPEG_VALUE) + public ResponseEntity searchSomeImage(@RequestHeader(name = HiveHeaders.AUTHENTICATED_USER_NAME_HEADER) final String username, @PathVariable String profileImageName) { + var userID=userRepository.findByUsername(username).getId().toString(); + Resource file = imageStorer.loadImage(username,profileImageName); + return ResponseEntity.ok().header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + file.getFilename() + "\"").body(file); + } +} From 6e2113f444cf7c8a83d4a3f110b6ae7cb8559fc4 Mon Sep 17 00:00:00 2001 From: germano Date: Sat, 20 Apr 2019 01:11:38 -0300 Subject: [PATCH 10/54] Alteration: Only multiPartFile upload test is working properly for now. --- .../controller/SmugshotControllerTest.java | 86 ++++++++++++++++++- 1 file changed, 85 insertions(+), 1 deletion(-) diff --git a/album/src/test/java/hive/album/controller/SmugshotControllerTest.java b/album/src/test/java/hive/album/controller/SmugshotControllerTest.java index 933b6c6..675cac5 100644 --- a/album/src/test/java/hive/album/controller/SmugshotControllerTest.java +++ b/album/src/test/java/hive/album/controller/SmugshotControllerTest.java @@ -1,14 +1,98 @@ package hive.album.controller; +import hive.album.repository.UserRepository; +import hive.album.storage.ImageStorer; +import hive.common.security.HiveHeaders; +import hive.entity.user.User; +import org.apache.commons.lang.RandomStringUtils; +import org.hamcrest.Matchers; +import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.core.io.UrlResource; +import org.springframework.mock.web.MockMultipartFile; import org.springframework.test.context.junit4.SpringRunner; +import org.springframework.test.util.ReflectionTestUtils; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.ResultHandler; +import org.springframework.test.web.servlet.setup.MockMvcBuilders; +import org.springframework.web.multipart.MultipartFile; +import java.util.concurrent.ThreadLocalRandom; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; +import static org.mockito.Mockito.when; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.model; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.multipart; +import static org.mockito.BDDMockito.given; @RunWith(SpringRunner.class) @SpringBootTest public class SmugshotControllerTest { + @Value("${hive.mugshot.image-directory-path}") + private String rootDir; + private MockMvc mockMvc; + @Mock + private UserRepository userRepository; + @Mock + private ImageStorer imageStorer; + @Mock + private User user; + private String username = RandomStringUtils.randomAlphabetic(8); + private Integer userId = 3;//ThreadLocalRandom.current().nextInt(Integer.MAX_VALUE); + private MockMultipartFile multipartFile; + @Before + public void setup() { + MockitoAnnotations.initMocks(this); + when(user.getId()).thenReturn(userId); + when(userRepository.findByUsername(username)).thenReturn(user); + var mugshotController = new MugshotController(imageStorer,userRepository); + ReflectionTestUtils.setField(mugshotController, "rootDir", rootDir); + mockMvc = MockMvcBuilders.standaloneSetup(mugshotController).build(); + multipartFile = new MockMultipartFile("image", "ProfileImage.jpg", "image/jpeg", "Spring Framework".getBytes()); + } + //SUCCESS: @Test - public void givenAutenticatedUserNameDoesNotOwnImage_WhenUploadImage_then430isReturned() { + public void givenValidImage_WhenImageRetrieved_then200isReturned() throws Exception{ + mockMvc.perform( + get("/mugshot").header("authenticated-user-name",username) + ).andExpect(status().isOk()) + .andExpect(model().attribute("files", + Matchers.contains("http://localhost/mugshot_images_profiles/ProfileImage.jpg"))); + } + @Test + public void givenValidImage_WhenImageUploaded_then200isReturned() throws Exception{ + mockMvc.perform( + multipart("/mugshot").file(multipartFile).header("authenticated-user-name",username) + ).andExpect(status().isOk()); + } + @Test + public void givenValidImage_WhenImageDeleted_then204isReturned() throws Exception{ + mockMvc.perform( + delete("/mugshot").header("authenticated-user-name",username) + ).andExpect(status().isNoContent()); + } + //ERRORS: + @Test + public void givenFileNotFound_WhenImageRetrieved_then404isReturned() throws Exception{ + } + @Test + public void givenUnsupportedMediaType_WhenImageUploaded_then415isReturned(){ + + } + @Test + public void givenFileTooLarge_WhenImageUploaded_then413isReturned(){ + + } + @Test + public void givenMultipleFile_WhenImageUploaded_then413isReturned(){ + } } From 2371ec6656024f087f1382a58540f90ce4bb74c8 Mon Sep 17 00:00:00 2001 From: germano Date: Sat, 20 Apr 2019 01:12:39 -0300 Subject: [PATCH 11/54] Alteration: Only multiPartFile upload test is working properly for now. --- .../java/hive/album/storage/ImageStorer.java | 24 +++++++------------ 1 file changed, 9 insertions(+), 15 deletions(-) diff --git a/album/src/main/java/hive/album/storage/ImageStorer.java b/album/src/main/java/hive/album/storage/ImageStorer.java index 0c1a06c..c3dcc76 100644 --- a/album/src/main/java/hive/album/storage/ImageStorer.java +++ b/album/src/main/java/hive/album/storage/ImageStorer.java @@ -2,7 +2,6 @@ import hive.album.exception.ImageAlreadyExistException; import hive.album.exception.ImageNotFound; -import hive.album.exception.ImageProfileException; import hive.album.exception.InvalidPathException; import org.springframework.beans.factory.annotation.Value; import org.springframework.core.io.Resource; @@ -10,32 +9,27 @@ import org.springframework.stereotype.Service; import org.springframework.web.multipart.MultipartFile; +import javax.imageio.ImageIO; import java.io.IOException; import java.net.MalformedURLException; -import java.nio.file.FileAlreadyExistsException; -import java.nio.file.Files; -import java.nio.file.Path; -import java.nio.file.Paths; +import java.nio.file.*; @Service public class ImageStorer { @Value("${hive.mugshot.image-directory-path}") private String rootDir; - public String StoreImageProfile(String userDirectoryName,MultipartFile insertedImage){ + public void StoreImageProfile(String userDirectoryName,MultipartFile insertedImage,String imageStoredName){ this.createDirectoryIfNotExist(userDirectoryName); try { - Files.copy( - insertedImage.getInputStream(), - resolvePathFullUrlWith(userDirectoryName,insertedImage.getOriginalFilename()) - ); + var buff=ImageUtils.resizeImageToSquare(ImageIO.read(insertedImage.getInputStream())); + ImageIO.write(buff,"png", resolveRootPathFullUrlWith(userDirectoryName,imageStoredName).toFile()); }catch(FileAlreadyExistsException e){ throw new ImageAlreadyExistException(); } catch (IOException e) { throw new RuntimeException(e); } - return "Image Stored in Success"; } private void createDirectoryIfNotExist(String userDirectoryPath){ Path parentDir = Paths.get(rootDir,userDirectoryPath); @@ -50,7 +44,7 @@ private void createDirectoryIfNotExist(String userDirectoryPath){ public Resource loadImage(String userDirectoryName,String ImageName) { try { - Path file = resolvePathFullUrlWith(userDirectoryName,ImageName); + Path file = resolveRootPathFullUrlWith(userDirectoryName,ImageName); Resource resource = new UrlResource(file.toUri()); if (resource.exists() || resource.isReadable()) { return resource; @@ -62,12 +56,12 @@ public Resource loadImage(String userDirectoryName,String ImageName) { throw new InvalidPathException(); } } - private Path resolvePathFullUrlWith(String userDirectoryName,String filename) { + private Path resolveRootPathFullUrlWith(String userDirectoryName, String filename) { return Paths.get(rootDir).resolve(userDirectoryName).resolve(filename); } - public void deleteAllUserImages(String userDirectoryName) { - Path parentDir = Paths.get(rootDir,userDirectoryName); + public void deleteAllUserImages(String userDirectoryName,String ImageName) { + Path parentDir = resolveRootPathFullUrlWith(userDirectoryName,ImageName); try { Files.deleteIfExists(parentDir); } catch (IOException e) { From 49053f3d4337c68abb5c4dcc4c069f6485156a3c Mon Sep 17 00:00:00 2001 From: germano Date: Sat, 20 Apr 2019 01:13:55 -0300 Subject: [PATCH 12/54] Alteration: ImageStorer can resize images now! --- album/src/main/java/hive/album/storage/ImageStorer.java | 3 +++ 1 file changed, 3 insertions(+) diff --git a/album/src/main/java/hive/album/storage/ImageStorer.java b/album/src/main/java/hive/album/storage/ImageStorer.java index c3dcc76..ecb1efd 100644 --- a/album/src/main/java/hive/album/storage/ImageStorer.java +++ b/album/src/main/java/hive/album/storage/ImageStorer.java @@ -69,4 +69,7 @@ public void deleteAllUserImages(String userDirectoryName,String ImageName) { throw new RuntimeException("Not capable to delete the directory.\n"+e); } } + public void ResizeImage(){ + + } } From 5ee2aa5f5cd1f02f39c284c6bb249c29166385dd Mon Sep 17 00:00:00 2001 From: germano Date: Sun, 21 Apr 2019 23:27:57 -0300 Subject: [PATCH 13/54] New exception for 415(NotSupportedMediaType) http response. --- .../album/exception/NotAcceptedFileFormatException.java | 7 +++++++ 1 file changed, 7 insertions(+) create mode 100644 album/src/main/java/hive/album/exception/NotAcceptedFileFormatException.java diff --git a/album/src/main/java/hive/album/exception/NotAcceptedFileFormatException.java b/album/src/main/java/hive/album/exception/NotAcceptedFileFormatException.java new file mode 100644 index 0000000..ac75e94 --- /dev/null +++ b/album/src/main/java/hive/album/exception/NotAcceptedFileFormatException.java @@ -0,0 +1,7 @@ +package hive.album.exception; +import org.springframework.http.HttpStatus; +import org.springframework.web.bind.annotation.ResponseStatus; + +@ResponseStatus(code = HttpStatus.UNSUPPORTED_MEDIA_TYPE, reason = "Media type unsupported") +public class NotAcceptedFileFormatException extends RuntimeException{ +} From 9fadf1ae1b005c79d91c48ceccd1dea5b11f4343 Mon Sep 17 00:00:00 2001 From: germano Date: Sun, 21 Apr 2019 23:29:19 -0300 Subject: [PATCH 14/54] Added upload size limit. --- album/src/main/resources/application.properties | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/album/src/main/resources/application.properties b/album/src/main/resources/application.properties index 7b1cedd..6c3e6be 100644 --- a/album/src/main/resources/application.properties +++ b/album/src/main/resources/application.properties @@ -14,4 +14,6 @@ spring.jpa.hibernate.ddl-auto=create spring.jpa.show-sql=true spring.jpa.properties.hibernate.format_sql=true logging.level.org.hibernate.type=trace -hive.mugshot.image-directory-path=./smugshot_images_profiles \ No newline at end of file +# Mugshot +hive.mugshot.image-directory-path=./mugshot_images_profiles +spring.http.multipart.max-file-size=1MB \ No newline at end of file From 7e9621a5df0ce14d248d75d1eb8da28db2241620 Mon Sep 17 00:00:00 2001 From: germano Date: Sun, 21 Apr 2019 23:58:06 -0300 Subject: [PATCH 15/54] new Exception for 413(PayloadTooLarge) http response --- album/src/main/java/hive/album/exception/FileSizeException.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/album/src/main/java/hive/album/exception/FileSizeException.java b/album/src/main/java/hive/album/exception/FileSizeException.java index efa38f4..f049eb2 100644 --- a/album/src/main/java/hive/album/exception/FileSizeException.java +++ b/album/src/main/java/hive/album/exception/FileSizeException.java @@ -2,6 +2,6 @@ import org.springframework.http.HttpStatus; import org.springframework.web.bind.annotation.ResponseStatus; -@ResponseStatus(code = HttpStatus.BAD_REQUEST, reason = "Invalid size of file") +@ResponseStatus(code = HttpStatus.PAYLOAD_TOO_LARGE,reason = "Invalid size of file") public class FileSizeException extends RuntimeException{ } From 5847d294f98bf9018bd7b731cfa8292e34c68000 Mon Sep 17 00:00:00 2001 From: germano Date: Mon, 22 Apr 2019 00:47:01 -0300 Subject: [PATCH 16/54] Added validation of Image extension --- .../java/hive/album/storage/ImageStorer.java | 59 +++++++++++-------- .../java/hive/album/storage/ImageUtils.java | 41 +++++++++++++ 2 files changed, 75 insertions(+), 25 deletions(-) diff --git a/album/src/main/java/hive/album/storage/ImageStorer.java b/album/src/main/java/hive/album/storage/ImageStorer.java index ecb1efd..49a5dde 100644 --- a/album/src/main/java/hive/album/storage/ImageStorer.java +++ b/album/src/main/java/hive/album/storage/ImageStorer.java @@ -1,7 +1,6 @@ package hive.album.storage; -import hive.album.exception.ImageAlreadyExistException; -import hive.album.exception.ImageNotFound; +import hive.album.exception.*; import hive.album.exception.InvalidPathException; import org.springframework.beans.factory.annotation.Value; import org.springframework.core.io.Resource; @@ -14,34 +13,26 @@ import java.net.MalformedURLException; import java.nio.file.*; +import static hive.album.storage.ImageUtils.validateIfHasAnImageAsExtension; + @Service public class ImageStorer { @Value("${hive.mugshot.image-directory-path}") private String rootDir; - public void StoreImageProfile(String userDirectoryName,MultipartFile insertedImage,String imageStoredName){ + verifyIfIsPayloadTooLarge(insertedImage.getSize()); + //Fix the method for image name with spaces + verifyIfHasImageExtension(insertedImage.getOriginalFilename()); this.createDirectoryIfNotExist(userDirectoryName); try { - var buff=ImageUtils.resizeImageToSquare(ImageIO.read(insertedImage.getInputStream())); - ImageIO.write(buff,"png", resolveRootPathFullUrlWith(userDirectoryName,imageStoredName).toFile()); - }catch(FileAlreadyExistsException e){ + var buff = ImageUtils.resizeImageToSquare(ImageIO.read(insertedImage.getInputStream())); + ImageIO.write(buff, "png", resolveRootPathFullUrlWith(userDirectoryName, imageStoredName).toFile()); + } catch (FileAlreadyExistsException e) { throw new ImageAlreadyExistException(); - } - catch (IOException e) { + } catch (IOException e) { throw new RuntimeException(e); } } - private void createDirectoryIfNotExist(String userDirectoryPath){ - Path parentDir = Paths.get(rootDir,userDirectoryPath); - if (!Files.exists(parentDir)) { - try { - Files.createDirectories(parentDir); - } catch (IOException e) { - throw new RuntimeException("Not capable to create the directory.\n"+e); - } - } - } - public Resource loadImage(String userDirectoryName,String ImageName) { try { Path file = resolveRootPathFullUrlWith(userDirectoryName,ImageName); @@ -56,11 +47,7 @@ public Resource loadImage(String userDirectoryName,String ImageName) { throw new InvalidPathException(); } } - private Path resolveRootPathFullUrlWith(String userDirectoryName, String filename) { - return Paths.get(rootDir).resolve(userDirectoryName).resolve(filename); - } - - public void deleteAllUserImages(String userDirectoryName,String ImageName) { + public void deleteImage(String userDirectoryName, String ImageName) { Path parentDir = resolveRootPathFullUrlWith(userDirectoryName,ImageName); try { Files.deleteIfExists(parentDir); @@ -69,7 +56,29 @@ public void deleteAllUserImages(String userDirectoryName,String ImageName) { throw new RuntimeException("Not capable to delete the directory.\n"+e); } } - public void ResizeImage(){ + + private void createDirectoryIfNotExist(String userDirectoryPath){ + Path parentDir = Paths.get(rootDir,userDirectoryPath); + if (!Files.exists(parentDir)) { + try { + Files.createDirectories(parentDir); + } catch (IOException e) { + throw new RuntimeException("Not capable to create the directory.\n"+e); + } + } + } + private Path resolveRootPathFullUrlWith(String userDirectoryName, String filename) { + return Paths.get(rootDir).resolve(userDirectoryName).resolve(filename); + } + private void verifyIfIsPayloadTooLarge(long fileSize){ + if(fileSize>(1024*1024+1)) { + throw new FileSizeException(); + } + } + private void verifyIfHasImageExtension(String filename){ + if(!validateIfHasAnImageAsExtension(filename)) { + throw new NotAcceptedFileFormatException(); + } } } diff --git a/album/src/main/java/hive/album/storage/ImageUtils.java b/album/src/main/java/hive/album/storage/ImageUtils.java index 0cf437e..37fc2c3 100644 --- a/album/src/main/java/hive/album/storage/ImageUtils.java +++ b/album/src/main/java/hive/album/storage/ImageUtils.java @@ -2,9 +2,18 @@ import java.awt.*; import java.awt.image.BufferedImage; +import java.util.regex.Matcher; +import java.util.regex.Pattern; public class ImageUtils { private static int imageSizeInPixels =256; + private static final String IMAGE_PATTERN = "(.+\\.(gif|png|bmp|jpeg|jpg)$)"; + public static boolean validateIfHasAnImageAsExtension(final String image){ + var pattern = Pattern.compile(IMAGE_PATTERN); + var matcher = pattern.matcher(image); + return matcher.matches(); + } + public static BufferedImage resizeImageToSquare(BufferedImage inputtedImage) { // multi-pass bilinear div 2 var bufferedImageWithNewSize = new BufferedImage(imageSizeInPixels, imageSizeInPixels, BufferedImage.TYPE_INT_RGB); @@ -14,4 +23,36 @@ public static BufferedImage resizeImageToSquare(BufferedImage inputtedImage) { reSizer.dispose(); return bufferedImageWithNewSize; } + private BufferedImage generateRandomImage(){ + var img=new BufferedImage(4,4,BufferedImage.TYPE_INT_RGB); + var maxH=img.getHeight(); + var maxV=img.getWidth(); + for(int vertical=0;vertical Date: Mon, 22 Apr 2019 23:30:04 -0300 Subject: [PATCH 17/54] Updated tests --- .../controller/MugshotControllerTest.java | 163 ++++++++++++++++++ .../album/controller/UtilsControllerTest.java | 42 +++++ 2 files changed, 205 insertions(+) create mode 100644 album/src/test/java/hive/album/controller/MugshotControllerTest.java create mode 100644 album/src/test/java/hive/album/controller/UtilsControllerTest.java diff --git a/album/src/test/java/hive/album/controller/MugshotControllerTest.java b/album/src/test/java/hive/album/controller/MugshotControllerTest.java new file mode 100644 index 0000000..13a3c8a --- /dev/null +++ b/album/src/test/java/hive/album/controller/MugshotControllerTest.java @@ -0,0 +1,163 @@ +package hive.album.controller; + +import hive.album.exception.ImageNotFound; +import hive.album.repository.UserRepository; +import hive.album.storage.ImageStorer; +import hive.entity.user.User; +import org.apache.commons.lang.RandomStringUtils; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.core.io.UrlResource; +import org.springframework.http.MediaType; +import org.springframework.mock.web.MockMultipartFile; +import org.springframework.test.context.junit4.SpringRunner; +import org.springframework.test.util.ReflectionTestUtils; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.setup.MockMvcBuilders; + +import javax.imageio.ImageIO; +import java.awt.image.BufferedImage; +import java.io.ByteArrayOutputStream; +import java.io.File; +import java.net.MalformedURLException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.concurrent.ThreadLocalRandom; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; +import static org.mockito.BDDMockito.given; +import static org.mockito.Mockito.when; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.multipart; +import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; + +@RunWith(SpringRunner.class) +@SpringBootTest +public class MugshotControllerTest { + @Value("${hive.mugshot.image-directory-path}") + private String rootDir; + private MockMvc mockMvc; + private String imageName="ProfileImage.jpg"; + private String validDirectoryName; + @Mock + private UserRepository userRepository; + @Autowired + private ImageStorer imageStorer; + @Mock + private User user; + private String username = RandomStringUtils.randomAlphabetic(8); + private Integer userId = ThreadLocalRandom.current().nextInt(Integer.MAX_VALUE); + private MockMultipartFile multipartFile; + + @Before + public void setup() { + MockitoAnnotations.initMocks(this); + when(user.getId()).thenReturn(userId); + when(userRepository.findByUsername(username)).thenReturn(user); + var mugshotController = new MugshotController(imageStorer,userRepository); + ReflectionTestUtils.setField(mugshotController, "rootDir", rootDir); + mockMvc = MockMvcBuilders.standaloneSetup(mugshotController).build(); + validDirectoryName = (rootDir + "/" + user.getId() + "/"); + } + + private void createImageForTest(String directoryName) throws Exception{ + var file=new File(directoryName + "/ProfileImage.jpg"); + ImageIO.write(new BufferedImage(512,512,BufferedImage.TYPE_INT_RGB),"jpg",file); + } + private void createDirectoryForTest(String directoryName) throws Exception{ + Files.createDirectories(Paths.get(directoryName)); + } + private void deleteTestDirectory(String directoryName) throws Exception{ + Files.delete(Paths.get(directoryName)); + } + private void deleteTestImage(String directoryName) throws Exception{ + Files.delete(Paths.get(directoryName+"/ProfileImage.jpg")); + } + //SUCCESS: + @Test + public void givenValidImage_WhenImageRetrieved_then200andJpegImageTypeIsReturned() throws Exception{ + createDirectoryForTest(validDirectoryName); + createImageForTest(validDirectoryName); + try { + mockMvc.perform( + get("/mugshot") + .header("authenticated-user-name", username)) + .andExpect(status().isOk()) + .andExpect(content().contentType(MediaType.IMAGE_JPEG)) + .andDo(print()); + }finally { + deleteTestImage(validDirectoryName); + deleteTestDirectory(validDirectoryName); + } + } + @Test + public void givenValidImage_WhenImageUploaded_then200isReturned() throws Exception{ + multipartFile = new MockMultipartFile("image", "Profile Image.jpg", MediaType.IMAGE_JPEG_VALUE, "Spring Framework".getBytes()); + mockMvc.perform( + multipart("/mugshot").file(multipartFile).header("authenticated-user-name",username)) + .andExpect(status().isOk()) + .andDo(print()); + deleteTestImage(validDirectoryName); + deleteTestDirectory(validDirectoryName); + } + @Test + public void givenValidImage_WhenImageDeleted_then204isReturned() throws Exception{ + mockMvc.perform( + delete("/mugshot").header("authenticated-user-name",username) + ).andExpect(status().isNoContent()); + } + //ERRORS: + @Test + public void givenFileNotFound_WhenImageRetrieved_then404isReturned() throws Exception{ + createDirectoryForTest(validDirectoryName); + try { + mockMvc.perform( + get("/mugshot") + .header("authenticated-user-name", username)) + .andExpect(status().isNotFound()) + .andDo(print()); + }finally { + deleteTestDirectory(validDirectoryName); + } + } + @Test + public void givenUnsupportedMediaType_WhenImageUploaded_then415isReturned()throws Exception{ + BufferedImage originalImage = new BufferedImage(512, 512, BufferedImage.TYPE_INT_RGB); + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + ImageIO.write(originalImage, "jpg", baos); + multipartFile = new MockMultipartFile("image", "ProfileImage.wmv", MediaType.APPLICATION_PDF_VALUE, baos.toByteArray()); + mockMvc.perform(multipart("/mugshot") + .file(multipartFile) + .header("authenticated-user-name", username)) + .andExpect(status().isUnsupportedMediaType()) + .andDo(print()); + } + //falar com vitor sobre a gambiarra + @Test + public void givenFileTooLarge_WhenImageUploaded_then413isReturned() throws Exception{ + byte[] moreThan1MB = new byte[1024 * 1024 * 2]; + multipartFile = new MockMultipartFile("image", "ProfileImage.jpeg", MediaType.IMAGE_JPEG_VALUE, moreThan1MB); + mockMvc.perform(multipart("/mugshot") + .file(multipartFile).header("authenticated-user-name", username)) + .andExpect(status().isPayloadTooLarge()) + .andDo(print()); + } + @Test + public void givenWrongBodyRequestKey_WhenImageUploaded_then400isReturned() throws Exception{ + byte[] moreThan1MB = new byte[0]; + multipartFile = new MockMultipartFile("wrongBodyKey", "ProfileImage.jpeg", MediaType.IMAGE_JPEG_VALUE, moreThan1MB); + mockMvc.perform(multipart("/mugshot") + .file(multipartFile).header("authenticated-user-name", username)) + .andExpect(status().isBadRequest()) + .andDo(print()); + } +} diff --git a/album/src/test/java/hive/album/controller/UtilsControllerTest.java b/album/src/test/java/hive/album/controller/UtilsControllerTest.java new file mode 100644 index 0000000..235c0c7 --- /dev/null +++ b/album/src/test/java/hive/album/controller/UtilsControllerTest.java @@ -0,0 +1,42 @@ +package hive.album.controller; + +import hive.album.repository.UserRepository; +import hive.album.storage.ImageStorer; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; +import org.springframework.test.util.ReflectionTestUtils; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.setup.MockMvcBuilders; + +import static org.mockito.Mockito.when; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; +@RunWith(SpringRunner.class) +@SpringBootTest +public class UtilsControllerTest { + private MockMvc mockMvc; + @Mock + private UserRepository userRepository; + @Mock + private ImageStorer imageStorer; + @Before + public void setup() { + MockitoAnnotations.initMocks(this); + var utilsController = new UtilsController(userRepository,imageStorer); + mockMvc = MockMvcBuilders.standaloneSetup(utilsController).build(); + } + + @Test + public void givenRequestWithOkResponseAsDefault_whenVerifyIfTheServeIsOk_then200isReturned() throws Exception{ + mockMvc + .perform( + get("/utils/hey") + ) + .andExpect(status().isOk()); + } +} From 19b1ba7e3986dc6d1e8895c8cb68522f4580347d Mon Sep 17 00:00:00 2001 From: germano Date: Mon, 22 Apr 2019 23:31:33 -0300 Subject: [PATCH 18/54] Removed user existence validation --- .../main/java/hive/album/controller/MugshotController.java | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/album/src/main/java/hive/album/controller/MugshotController.java b/album/src/main/java/hive/album/controller/MugshotController.java index 7e05293..aa43ed9 100644 --- a/album/src/main/java/hive/album/controller/MugshotController.java +++ b/album/src/main/java/hive/album/controller/MugshotController.java @@ -1,10 +1,8 @@ package hive.album.controller; -import hive.album.exception.UserNotFoundException; import hive.album.repository.UserRepository; import hive.album.storage.ImageStorer; import hive.common.security.HiveHeaders; -import hive.entity.user.User; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.http.HttpHeaders; @@ -46,6 +44,6 @@ public ResponseEntity searchProfileImage(@RequestHeader(name = HiveHea @DeleteMapping public void deleteProfileImage(@RequestHeader(name = HiveHeaders.AUTHENTICATED_USER_NAME_HEADER) final String username) { var userID=userRepository.findByUsername(username).getId().toString(); - imageStorer.deleteAllUserImages(userID,imageName); + imageStorer.deleteImage(userID,imageName); } } From ccaecf7e9c148638b255beed58d153c35cf0586b Mon Sep 17 00:00:00 2001 From: germano Date: Mon, 22 Apr 2019 23:35:29 -0300 Subject: [PATCH 19/54] correction in typo --- ...ugshotApplicationTests.java => MugshotApplicationTests.java} | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) rename album/src/test/java/hive/album/{SmugshotApplicationTests.java => MugshotApplicationTests.java} (87%) diff --git a/album/src/test/java/hive/album/SmugshotApplicationTests.java b/album/src/test/java/hive/album/MugshotApplicationTests.java similarity index 87% rename from album/src/test/java/hive/album/SmugshotApplicationTests.java rename to album/src/test/java/hive/album/MugshotApplicationTests.java index 0d7a069..9ca102f 100644 --- a/album/src/test/java/hive/album/SmugshotApplicationTests.java +++ b/album/src/test/java/hive/album/MugshotApplicationTests.java @@ -7,7 +7,7 @@ @RunWith(SpringRunner.class) @SpringBootTest -public class SmugshotApplicationTests { +public class MugshotApplicationTests { @Test public void contextLoads() { From 69d8cbc9fbbfed40b40e16298ec3cde82135ea39 Mon Sep 17 00:00:00 2001 From: germano Date: Mon, 22 Apr 2019 23:40:37 -0300 Subject: [PATCH 20/54] Deleted class typo --- .../java/hive/album/SmugshotApplication.java | 16 --- .../controller/SmugshotControllerTest.java | 98 ------------------- 2 files changed, 114 deletions(-) delete mode 100644 album/src/main/java/hive/album/SmugshotApplication.java delete mode 100644 album/src/test/java/hive/album/controller/SmugshotControllerTest.java diff --git a/album/src/main/java/hive/album/SmugshotApplication.java b/album/src/main/java/hive/album/SmugshotApplication.java deleted file mode 100644 index 48b60e2..0000000 --- a/album/src/main/java/hive/album/SmugshotApplication.java +++ /dev/null @@ -1,16 +0,0 @@ -package hive.album; - -import org.springframework.boot.SpringApplication; -import org.springframework.boot.autoconfigure.SpringBootApplication; -import org.springframework.boot.autoconfigure.domain.EntityScan; -import org.springframework.cloud.netflix.eureka.EnableEurekaClient; - -@SpringBootApplication -@EnableEurekaClient -@EntityScan( basePackages = {"hive.entity.user"} ) -public class SmugshotApplication { - - public static void main(String[] args) { - SpringApplication.run(SmugshotApplication.class, args); - } -} diff --git a/album/src/test/java/hive/album/controller/SmugshotControllerTest.java b/album/src/test/java/hive/album/controller/SmugshotControllerTest.java deleted file mode 100644 index 675cac5..0000000 --- a/album/src/test/java/hive/album/controller/SmugshotControllerTest.java +++ /dev/null @@ -1,98 +0,0 @@ -package hive.album.controller; - -import hive.album.repository.UserRepository; -import hive.album.storage.ImageStorer; -import hive.common.security.HiveHeaders; -import hive.entity.user.User; -import org.apache.commons.lang.RandomStringUtils; -import org.hamcrest.Matchers; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.Mock; -import org.mockito.MockitoAnnotations; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Value; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.core.io.UrlResource; -import org.springframework.mock.web.MockMultipartFile; -import org.springframework.test.context.junit4.SpringRunner; -import org.springframework.test.util.ReflectionTestUtils; -import org.springframework.test.web.servlet.MockMvc; -import org.springframework.test.web.servlet.ResultHandler; -import org.springframework.test.web.servlet.setup.MockMvcBuilders; -import org.springframework.web.multipart.MultipartFile; - -import java.util.concurrent.ThreadLocalRandom; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; -import static org.mockito.Mockito.when; -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.model; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.multipart; -import static org.mockito.BDDMockito.given; -@RunWith(SpringRunner.class) -@SpringBootTest -public class SmugshotControllerTest { - @Value("${hive.mugshot.image-directory-path}") - private String rootDir; - private MockMvc mockMvc; - @Mock - private UserRepository userRepository; - @Mock - private ImageStorer imageStorer; - @Mock - private User user; - private String username = RandomStringUtils.randomAlphabetic(8); - private Integer userId = 3;//ThreadLocalRandom.current().nextInt(Integer.MAX_VALUE); - private MockMultipartFile multipartFile; - @Before - public void setup() { - MockitoAnnotations.initMocks(this); - when(user.getId()).thenReturn(userId); - when(userRepository.findByUsername(username)).thenReturn(user); - var mugshotController = new MugshotController(imageStorer,userRepository); - ReflectionTestUtils.setField(mugshotController, "rootDir", rootDir); - mockMvc = MockMvcBuilders.standaloneSetup(mugshotController).build(); - multipartFile = new MockMultipartFile("image", "ProfileImage.jpg", "image/jpeg", "Spring Framework".getBytes()); - } - //SUCCESS: - @Test - public void givenValidImage_WhenImageRetrieved_then200isReturned() throws Exception{ - mockMvc.perform( - get("/mugshot").header("authenticated-user-name",username) - ).andExpect(status().isOk()) - .andExpect(model().attribute("files", - Matchers.contains("http://localhost/mugshot_images_profiles/ProfileImage.jpg"))); - } - @Test - public void givenValidImage_WhenImageUploaded_then200isReturned() throws Exception{ - mockMvc.perform( - multipart("/mugshot").file(multipartFile).header("authenticated-user-name",username) - ).andExpect(status().isOk()); - } - @Test - public void givenValidImage_WhenImageDeleted_then204isReturned() throws Exception{ - mockMvc.perform( - delete("/mugshot").header("authenticated-user-name",username) - ).andExpect(status().isNoContent()); - } - //ERRORS: - @Test - public void givenFileNotFound_WhenImageRetrieved_then404isReturned() throws Exception{ - } - @Test - public void givenUnsupportedMediaType_WhenImageUploaded_then415isReturned(){ - - } - @Test - public void givenFileTooLarge_WhenImageUploaded_then413isReturned(){ - - } - @Test - public void givenMultipleFile_WhenImageUploaded_then413isReturned(){ - - } -} From 6f0a2ceb4b67561321260190fb567b9e2dcfb930 Mon Sep 17 00:00:00 2001 From: germano Date: Fri, 26 Apr 2019 00:24:49 -0300 Subject: [PATCH 21/54] Added image type validation --- .../album/controller/MugshotController.java | 21 ++++++++++++++----- 1 file changed, 16 insertions(+), 5 deletions(-) diff --git a/album/src/main/java/hive/album/controller/MugshotController.java b/album/src/main/java/hive/album/controller/MugshotController.java index aa43ed9..ce30cf7 100644 --- a/album/src/main/java/hive/album/controller/MugshotController.java +++ b/album/src/main/java/hive/album/controller/MugshotController.java @@ -1,5 +1,6 @@ package hive.album.controller; +import hive.album.exception.NotAcceptedFileFormatException; import hive.album.repository.UserRepository; import hive.album.storage.ImageStorer; import hive.common.security.HiveHeaders; @@ -13,28 +14,37 @@ import org.springframework.web.multipart.MultipartFile; import org.springframework.core.io.Resource; +import static hive.album.storage.ImageUtils.validateIfHasAnImageAsExtension; + @RestController @RequestMapping("/mugshot") public class MugshotController { @Value("${hive.mugshot.image-directory-path}") private String rootDir; + @Value("${hive.mugshot.profile-image-name}") + private String imageName; private final ImageStorer imageStorer; private final UserRepository userRepository; - private String imageName="ProfileImage.jpg"; @Autowired public MugshotController(ImageStorer imageStorer,UserRepository userRepository) { this.userRepository = userRepository; this.imageStorer = imageStorer; } - @ResponseStatus(code = HttpStatus.OK, reason = "Profile image Stored In Success") + @ResponseStatus(code = HttpStatus.OK, reason = "Profile image successfully stored") @PostMapping - public void sendImageProfile(@RequestParam("image") MultipartFile insertedImage, @RequestHeader(name = HiveHeaders.AUTHENTICATED_USER_NAME_HEADER) final String username) { + public void sendImageProfile( + @RequestParam("image") MultipartFile insertedImage, + @RequestHeader(name = HiveHeaders.AUTHENTICATED_USER_NAME_HEADER) final String username) { + if(!validateIfHasAnImageAsExtension(insertedImage.getOriginalFilename())) { + throw new NotAcceptedFileFormatException(); + } var userID=userRepository.findByUsername(username).getId().toString(); imageStorer.StoreImageProfile(userID,insertedImage,imageName); } @GetMapping(produces = MediaType.IMAGE_JPEG_VALUE) - public ResponseEntity searchProfileImage(@RequestHeader(name = HiveHeaders.AUTHENTICATED_USER_NAME_HEADER) final String username) { + public ResponseEntity searchProfileImage( + @RequestHeader(name = HiveHeaders.AUTHENTICATED_USER_NAME_HEADER) final String username) { var userID=userRepository.findByUsername(username).getId().toString(); Resource file = imageStorer.loadImage(userID,imageName); return ResponseEntity.ok().header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + file.getFilename() + "\"").body(file); @@ -42,7 +52,8 @@ public ResponseEntity searchProfileImage(@RequestHeader(name = HiveHea @ResponseStatus(code = HttpStatus.NO_CONTENT, reason = "Profile image successfully deleted") @DeleteMapping - public void deleteProfileImage(@RequestHeader(name = HiveHeaders.AUTHENTICATED_USER_NAME_HEADER) final String username) { + public void deleteProfileImage( + @RequestHeader(name = HiveHeaders.AUTHENTICATED_USER_NAME_HEADER) final String username) { var userID=userRepository.findByUsername(username).getId().toString(); imageStorer.deleteImage(userID,imageName); } From fb272e3fad1bfedd63a8aed4c2661f98366f460f Mon Sep 17 00:00:00 2001 From: germano Date: Fri, 26 Apr 2019 00:26:20 -0300 Subject: [PATCH 22/54] removed verifyIfIsPayloadTooLarge and verifyIfHasImageExtension methods --- .../java/hive/album/storage/ImageStorer.java | 21 +++---------------- 1 file changed, 3 insertions(+), 18 deletions(-) diff --git a/album/src/main/java/hive/album/storage/ImageStorer.java b/album/src/main/java/hive/album/storage/ImageStorer.java index 49a5dde..a55b067 100644 --- a/album/src/main/java/hive/album/storage/ImageStorer.java +++ b/album/src/main/java/hive/album/storage/ImageStorer.java @@ -13,22 +13,17 @@ import java.net.MalformedURLException; import java.nio.file.*; -import static hive.album.storage.ImageUtils.validateIfHasAnImageAsExtension; - @Service public class ImageStorer { @Value("${hive.mugshot.image-directory-path}") private String rootDir; + @Value("${hive.mugshot.profile-image-dimension}") + private int imageSizeInPixels; public void StoreImageProfile(String userDirectoryName,MultipartFile insertedImage,String imageStoredName){ - verifyIfIsPayloadTooLarge(insertedImage.getSize()); - //Fix the method for image name with spaces - verifyIfHasImageExtension(insertedImage.getOriginalFilename()); this.createDirectoryIfNotExist(userDirectoryName); try { - var buff = ImageUtils.resizeImageToSquare(ImageIO.read(insertedImage.getInputStream())); + var buff = ImageUtils.resizeImageToSquare(ImageIO.read(insertedImage.getInputStream()),imageSizeInPixels); ImageIO.write(buff, "png", resolveRootPathFullUrlWith(userDirectoryName, imageStoredName).toFile()); - } catch (FileAlreadyExistsException e) { - throw new ImageAlreadyExistException(); } catch (IOException e) { throw new RuntimeException(e); } @@ -71,14 +66,4 @@ private void createDirectoryIfNotExist(String userDirectoryPath){ private Path resolveRootPathFullUrlWith(String userDirectoryName, String filename) { return Paths.get(rootDir).resolve(userDirectoryName).resolve(filename); } - private void verifyIfIsPayloadTooLarge(long fileSize){ - if(fileSize>(1024*1024+1)) { - throw new FileSizeException(); - } - } - private void verifyIfHasImageExtension(String filename){ - if(!validateIfHasAnImageAsExtension(filename)) { - throw new NotAcceptedFileFormatException(); - } - } } From 70c1a15ea387884d8f4f63af3d9f482cc41ddc87 Mon Sep 17 00:00:00 2001 From: germano Date: Fri, 26 Apr 2019 00:26:57 -0300 Subject: [PATCH 23/54] Scope changes. --- .../main/java/hive/album/storage/ImageUtils.java | 13 ++++++++----- 1 file changed, 8 insertions(+), 5 deletions(-) diff --git a/album/src/main/java/hive/album/storage/ImageUtils.java b/album/src/main/java/hive/album/storage/ImageUtils.java index 37fc2c3..58d9b95 100644 --- a/album/src/main/java/hive/album/storage/ImageUtils.java +++ b/album/src/main/java/hive/album/storage/ImageUtils.java @@ -1,20 +1,23 @@ package hive.album.storage; +import org.springframework.beans.factory.annotation.Value; + import java.awt.*; import java.awt.image.BufferedImage; import java.util.regex.Matcher; import java.util.regex.Pattern; -public class ImageUtils { - private static int imageSizeInPixels =256; +public final class ImageUtils { private static final String IMAGE_PATTERN = "(.+\\.(gif|png|bmp|jpeg|jpg)$)"; + private ImageUtils(){ + } public static boolean validateIfHasAnImageAsExtension(final String image){ var pattern = Pattern.compile(IMAGE_PATTERN); var matcher = pattern.matcher(image); return matcher.matches(); } - public static BufferedImage resizeImageToSquare(BufferedImage inputtedImage) { + public static BufferedImage resizeImageToSquare(BufferedImage inputtedImage,int imageSizeInPixels) { // multi-pass bilinear div 2 var bufferedImageWithNewSize = new BufferedImage(imageSizeInPixels, imageSizeInPixels, BufferedImage.TYPE_INT_RGB); var reSizer = bufferedImageWithNewSize.createGraphics(); @@ -23,7 +26,7 @@ public static BufferedImage resizeImageToSquare(BufferedImage inputtedImage) { reSizer.dispose(); return bufferedImageWithNewSize; } - private BufferedImage generateRandomImage(){ + public static BufferedImage generateRandomImage(){ var img=new BufferedImage(4,4,BufferedImage.TYPE_INT_RGB); var maxH=img.getHeight(); var maxV=img.getWidth(); @@ -38,7 +41,7 @@ private BufferedImage generateRandomImage(){ } return img; } - private BufferedImage generateRandomBWImage(){ + public static BufferedImage generateRandomBWImage(){ var img=new BufferedImage(9,9,BufferedImage.TYPE_INT_RGB); var maxH=img.getHeight(); var maxV=img.getWidth(); From 33cb12a4548b6cf4db4f95cb45162cb02b1fdf73 Mon Sep 17 00:00:00 2001 From: germano Date: Fri, 26 Apr 2019 00:27:44 -0300 Subject: [PATCH 24/54] New tests and mocks. --- .../controller/MugshotControllerTest.java | 106 +++++++++--------- .../hive/album/storage/ImageStorerTest.java | 89 +++++++++++++++ .../hive/album/storage/ImageUtilsTest.java | 38 +++++++ 3 files changed, 181 insertions(+), 52 deletions(-) create mode 100644 album/src/test/java/hive/album/storage/ImageStorerTest.java create mode 100644 album/src/test/java/hive/album/storage/ImageUtilsTest.java diff --git a/album/src/test/java/hive/album/controller/MugshotControllerTest.java b/album/src/test/java/hive/album/controller/MugshotControllerTest.java index 13a3c8a..cbc77db 100644 --- a/album/src/test/java/hive/album/controller/MugshotControllerTest.java +++ b/album/src/test/java/hive/album/controller/MugshotControllerTest.java @@ -1,10 +1,12 @@ package hive.album.controller; import hive.album.exception.ImageNotFound; +import hive.album.exception.NotAcceptedFileFormatException; import hive.album.repository.UserRepository; import hive.album.storage.ImageStorer; import hive.entity.user.User; import org.apache.commons.lang.RandomStringUtils; +import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; @@ -13,8 +15,11 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.core.io.Resource; import org.springframework.core.io.UrlResource; +import org.springframework.http.HttpHeaders; import org.springframework.http.MediaType; +import org.springframework.http.ResponseEntity; import org.springframework.mock.web.MockMultipartFile; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.util.ReflectionTestUtils; @@ -25,6 +30,7 @@ import java.awt.image.BufferedImage; import java.io.ByteArrayOutputStream; import java.io.File; +import java.io.IOException; import java.net.MalformedURLException; import java.nio.file.Files; import java.nio.file.Path; @@ -43,20 +49,32 @@ @RunWith(SpringRunner.class) @SpringBootTest public class MugshotControllerTest { - @Value("${hive.mugshot.image-directory-path}") - private String rootDir; + private MockMvc mockMvc; - private String imageName="ProfileImage.jpg"; private String validDirectoryName; + private String username = RandomStringUtils.randomAlphabetic(8); + private Integer userId = ThreadLocalRandom.current().nextInt(Integer.MAX_VALUE); + private MockMultipartFile multipartFile; + @Value("${hive.mugshot.image-directory-path}") + private String rootDir; + @Value("${hive.mugshot.profile-image-name}") + private String imageName; @Mock private UserRepository userRepository; - @Autowired + @Mock private ImageStorer imageStorer; @Mock private User user; - private String username = RandomStringUtils.randomAlphabetic(8); - private Integer userId = ThreadLocalRandom.current().nextInt(Integer.MAX_VALUE); - private MockMultipartFile multipartFile; + + private Resource createImageForTest(String directoryName) throws Exception{ + var file=new File(directoryName + "/ProfileImage.jpg"); + ImageIO.write(new BufferedImage(512,512,BufferedImage.TYPE_INT_RGB),"jpg",file); + return new UrlResource(file.toURI()); + } + + private void createDirectoryForTest(String directoryName) throws Exception{ + Files.createDirectories(Paths.get(directoryName)); + } @Before public void setup() { @@ -65,40 +83,26 @@ public void setup() { when(userRepository.findByUsername(username)).thenReturn(user); var mugshotController = new MugshotController(imageStorer,userRepository); ReflectionTestUtils.setField(mugshotController, "rootDir", rootDir); + ReflectionTestUtils.setField(mugshotController, "imageName", imageName); mockMvc = MockMvcBuilders.standaloneSetup(mugshotController).build(); validDirectoryName = (rootDir + "/" + user.getId() + "/"); } - private void createImageForTest(String directoryName) throws Exception{ - var file=new File(directoryName + "/ProfileImage.jpg"); - ImageIO.write(new BufferedImage(512,512,BufferedImage.TYPE_INT_RGB),"jpg",file); - } - private void createDirectoryForTest(String directoryName) throws Exception{ - Files.createDirectories(Paths.get(directoryName)); - } - private void deleteTestDirectory(String directoryName) throws Exception{ - Files.delete(Paths.get(directoryName)); - } - private void deleteTestImage(String directoryName) throws Exception{ - Files.delete(Paths.get(directoryName+"/ProfileImage.jpg")); - } //SUCCESS: @Test public void givenValidImage_WhenImageRetrieved_then200andJpegImageTypeIsReturned() throws Exception{ createDirectoryForTest(validDirectoryName); - createImageForTest(validDirectoryName); - try { + var resourceImage=createImageForTest(validDirectoryName); + given(imageStorer.loadImage(userId.toString(),imageName)) + .willReturn(resourceImage); mockMvc.perform( get("/mugshot") .header("authenticated-user-name", username)) .andExpect(status().isOk()) .andExpect(content().contentType(MediaType.IMAGE_JPEG)) .andDo(print()); - }finally { - deleteTestImage(validDirectoryName); - deleteTestDirectory(validDirectoryName); - } } + @Test public void givenValidImage_WhenImageUploaded_then200isReturned() throws Exception{ multipartFile = new MockMultipartFile("image", "Profile Image.jpg", MediaType.IMAGE_JPEG_VALUE, "Spring Framework".getBytes()); @@ -106,58 +110,56 @@ public void givenValidImage_WhenImageUploaded_then200isReturned() throws Excepti multipart("/mugshot").file(multipartFile).header("authenticated-user-name",username)) .andExpect(status().isOk()) .andDo(print()); - deleteTestImage(validDirectoryName); - deleteTestDirectory(validDirectoryName); } + @Test public void givenValidImage_WhenImageDeleted_then204isReturned() throws Exception{ mockMvc.perform( delete("/mugshot").header("authenticated-user-name",username) ).andExpect(status().isNoContent()); } + //ERRORS: @Test public void givenFileNotFound_WhenImageRetrieved_then404isReturned() throws Exception{ + given(imageStorer.loadImage(userId.toString(),imageName)).willThrow(new ImageNotFound()); createDirectoryForTest(validDirectoryName); - try { - mockMvc.perform( - get("/mugshot") - .header("authenticated-user-name", username)) - .andExpect(status().isNotFound()) - .andDo(print()); - }finally { - deleteTestDirectory(validDirectoryName); - } + mockMvc.perform( + get("/mugshot") + .header("authenticated-user-name", username)) + .andExpect(status().isNotFound()) + .andDo(print()); } + @Test public void givenUnsupportedMediaType_WhenImageUploaded_then415isReturned()throws Exception{ BufferedImage originalImage = new BufferedImage(512, 512, BufferedImage.TYPE_INT_RGB); - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - ImageIO.write(originalImage, "jpg", baos); - multipartFile = new MockMultipartFile("image", "ProfileImage.wmv", MediaType.APPLICATION_PDF_VALUE, baos.toByteArray()); + ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); + ImageIO.write(originalImage, "jpg", byteArrayOutputStream); + multipartFile = new MockMultipartFile("image", "Unsupported.Extension.wmv", MediaType.APPLICATION_PDF_VALUE, byteArrayOutputStream.toByteArray()); mockMvc.perform(multipart("/mugshot") .file(multipartFile) .header("authenticated-user-name", username)) .andExpect(status().isUnsupportedMediaType()) .andDo(print()); } - //falar com vitor sobre a gambiarra - @Test - public void givenFileTooLarge_WhenImageUploaded_then413isReturned() throws Exception{ - byte[] moreThan1MB = new byte[1024 * 1024 * 2]; - multipartFile = new MockMultipartFile("image", "ProfileImage.jpeg", MediaType.IMAGE_JPEG_VALUE, moreThan1MB); - mockMvc.perform(multipart("/mugshot") - .file(multipartFile).header("authenticated-user-name", username)) - .andExpect(status().isPayloadTooLarge()) - .andDo(print()); - } + @Test public void givenWrongBodyRequestKey_WhenImageUploaded_then400isReturned() throws Exception{ - byte[] moreThan1MB = new byte[0]; - multipartFile = new MockMultipartFile("wrongBodyKey", "ProfileImage.jpeg", MediaType.IMAGE_JPEG_VALUE, moreThan1MB); + byte[] EmptyFile = new byte[0]; + multipartFile = new MockMultipartFile("wrongBodyKey", "ProfileImage.jpeg", MediaType.IMAGE_JPEG_VALUE, EmptyFile); mockMvc.perform(multipart("/mugshot") .file(multipartFile).header("authenticated-user-name", username)) .andExpect(status().isBadRequest()) .andDo(print()); } + + @After + public void deleteCreatedDirectory() throws IOException { + Path createdDirectoryPath=Paths.get(rootDir,userId.toString()); + Path createdImagePath=createdDirectoryPath.resolve(imageName); + Files.deleteIfExists(createdImagePath); + Files.deleteIfExists(createdDirectoryPath); + } + } diff --git a/album/src/test/java/hive/album/storage/ImageStorerTest.java b/album/src/test/java/hive/album/storage/ImageStorerTest.java new file mode 100644 index 0000000..60479f1 --- /dev/null +++ b/album/src/test/java/hive/album/storage/ImageStorerTest.java @@ -0,0 +1,89 @@ +package hive.album.storage; + +import hive.album.exception.NotAcceptedFileFormatException; +import org.junit.*; +import org.junit.rules.ExpectedException; +import org.junit.runner.RunWith; +import org.mockito.Mock; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.http.MediaType; +import org.springframework.mock.web.MockMultipartFile; +import org.springframework.test.context.junit4.SpringRunner; + +import javax.imageio.ImageIO; +import java.awt.image.BufferedImage; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.concurrent.ThreadLocalRandom; + +import static org.mockito.Mockito.when; + +@RunWith(SpringRunner.class) +@SpringBootTest +public class ImageStorerTest { + private Integer userId; + private MockMultipartFile multipartFile; + @Autowired + private ImageStorer imageStorer; + @Value("${hive.mugshot.image-directory-path}") + private String rootDir; + @Value("${hive.mugshot.profile-image-name}") + private String imageName; + @Value("${hive.mugshot.profile-image-dimension}") + private int imageSizeInPixels; + + + @Before + public void setUp(){ + userId= ThreadLocalRandom.current().nextInt(Integer.MAX_VALUE); + multipartFile=new MockMultipartFile( + "image", + "WhateverName.gif", + MediaType.IMAGE_JPEG_VALUE, + "Spring Framework".getBytes() + ); + } + + @Test + public void uploadImage_WhenImageNameAndUserDirectoryIsNotNull_expectExistenceOfFile(){ + imageStorer.StoreImageProfile(userId.toString(),multipartFile,imageName); + Path path=Paths.get(rootDir,userId.toString(),imageName); + Assert.assertTrue(Files.exists(path)); + } + + @Test + public void deleteImage_WhenImageNameAndUserDirectoryIsNotNull_expectNoExistenceOfFile(){ + imageStorer.deleteImage(userId.toString(),imageName); + Path path=Paths.get(rootDir,userId.toString(),imageName); + Assert.assertFalse(Files.exists(path)); + } + + @Test + public void loadImage_WhenMultipartIsNotNull_expectConfiguredImageName() throws IOException { + imageStorer.StoreImageProfile(userId.toString(),multipartFile,imageName); + var resource=imageStorer.loadImage(userId.toString(),imageName); + Assert.assertEquals(imageName,resource.getFile().getName()); + } + + @Test + public void loadImage_WhenMultipartIsNotNull_expectConfiguredImageSize() throws IOException { + imageStorer.StoreImageProfile(userId.toString(),multipartFile,imageName); + var resource=imageStorer.loadImage(userId.toString(),imageName); + var image=ImageIO.read(resource.getFile()); + Assert.assertEquals(imageSizeInPixels,image.getHeight()); + Assert.assertEquals(imageSizeInPixels,image.getWidth()); + } + + @After + public void deleteCreatedDirectoryAndFile() throws IOException { + Path createdDirectoryPath=Paths.get(rootDir,userId.toString()); + Path createdImagePath=createdDirectoryPath.resolve(imageName); + Files.deleteIfExists(createdImagePath); + Files.deleteIfExists(createdDirectoryPath); + } + +} diff --git a/album/src/test/java/hive/album/storage/ImageUtilsTest.java b/album/src/test/java/hive/album/storage/ImageUtilsTest.java new file mode 100644 index 0000000..5b35517 --- /dev/null +++ b/album/src/test/java/hive/album/storage/ImageUtilsTest.java @@ -0,0 +1,38 @@ +package hive.album.storage; + +import org.junit.Assert; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +import java.awt.image.BufferedImage; + +@RunWith(SpringRunner.class) +@SpringBootTest +public class ImageUtilsTest { + @Value("${hive.mugshot.profile-image-dimension}") + private int imageSizeInPixels; + @Test + public void validateIfHasAnImageAsExtension_whenParameterDoesNotMatchPattern_expectFalseValue(){ + Assert.assertFalse(ImageUtils.validateIfHasAnImageAsExtension("a.zip")); + } + @Test + public void validateIfHasAnImageAsExtension_whenParameterMatchPattern_expectTrueValue(){ + Assert.assertTrue(ImageUtils.validateIfHasAnImageAsExtension("a.gif")); + } + @Test + public void resizeImageToSquare_whenInitialImageIsNotNull_expectSquareImageInConfiguredSize(){ + var initialImage=new BufferedImage(10,50,BufferedImage.TYPE_INT_RGB); + var resizedImage=ImageUtils.resizeImageToSquare(initialImage,imageSizeInPixels); + Assert.assertEquals(imageSizeInPixels,resizedImage.getWidth()); + Assert.assertEquals(imageSizeInPixels,resizedImage.getHeight()); + } + @Test + public void whenGenerateRandomImage_expectSquareImageInConfiguredSize(){ + var generatedImage=ImageUtils.generateRandomBWImage(); + Assert.assertEquals(imageSizeInPixels,generatedImage.getWidth()); + Assert.assertEquals(imageSizeInPixels,generatedImage.getHeight()); + } +} From a6ce8ed44e330f8a8d0edd1c72643ebb2722f881 Mon Sep 17 00:00:00 2001 From: germano Date: Sat, 27 Apr 2019 00:23:16 -0300 Subject: [PATCH 25/54] Renamed the entire module --- mugshot/build.gradle | 53 ++++++ .../java/hive/mugshot/MugshotApplication.java | 15 ++ .../mugshot/controller/MugshotController.java | 58 +++++++ .../mugshot/controller/UtilsController.java | 55 +++++++ .../mugshot/exception/FileSizeException.java | 7 + .../exception/ImageAlreadyExistException.java | 7 + .../hive/mugshot/exception/ImageNotFound.java | 7 + .../exception/ImageProfileException.java | 7 + .../exception/InvalidPathException.java | 8 + .../NotAcceptedFileFormatException.java | 7 + .../exception/UserNotFoundException.java | 8 + .../mugshot/repository/UserRepository.java | 8 + .../hive/mugshot/storage/ImageStorer.java | 81 ++++++++++ .../java/hive/mugshot/storage/ImageUtils.java | 62 +++++++ .../src/main/resources/application.properties | 21 +++ .../hive/mugshot/MugshotApplicationTests.java | 16 ++ .../controller/MugshotControllerTest.java | 151 ++++++++++++++++++ .../controller/UtilsControllerTest.java | 70 ++++++++ .../hive/mugshot/storage/ImageStorerTest.java | 85 ++++++++++ .../hive/mugshot/storage/ImageUtilsTest.java | 41 +++++ 20 files changed, 767 insertions(+) create mode 100644 mugshot/build.gradle create mode 100644 mugshot/src/main/java/hive/mugshot/MugshotApplication.java create mode 100644 mugshot/src/main/java/hive/mugshot/controller/MugshotController.java create mode 100644 mugshot/src/main/java/hive/mugshot/controller/UtilsController.java create mode 100644 mugshot/src/main/java/hive/mugshot/exception/FileSizeException.java create mode 100644 mugshot/src/main/java/hive/mugshot/exception/ImageAlreadyExistException.java create mode 100644 mugshot/src/main/java/hive/mugshot/exception/ImageNotFound.java create mode 100644 mugshot/src/main/java/hive/mugshot/exception/ImageProfileException.java create mode 100644 mugshot/src/main/java/hive/mugshot/exception/InvalidPathException.java create mode 100644 mugshot/src/main/java/hive/mugshot/exception/NotAcceptedFileFormatException.java create mode 100644 mugshot/src/main/java/hive/mugshot/exception/UserNotFoundException.java create mode 100644 mugshot/src/main/java/hive/mugshot/repository/UserRepository.java create mode 100644 mugshot/src/main/java/hive/mugshot/storage/ImageStorer.java create mode 100644 mugshot/src/main/java/hive/mugshot/storage/ImageUtils.java create mode 100644 mugshot/src/main/resources/application.properties create mode 100644 mugshot/src/test/java/hive/mugshot/MugshotApplicationTests.java create mode 100644 mugshot/src/test/java/hive/mugshot/controller/MugshotControllerTest.java create mode 100644 mugshot/src/test/java/hive/mugshot/controller/UtilsControllerTest.java create mode 100644 mugshot/src/test/java/hive/mugshot/storage/ImageStorerTest.java create mode 100644 mugshot/src/test/java/hive/mugshot/storage/ImageUtilsTest.java diff --git a/mugshot/build.gradle b/mugshot/build.gradle new file mode 100644 index 0000000..2e8e18a --- /dev/null +++ b/mugshot/build.gradle @@ -0,0 +1,53 @@ +buildscript { + ext { + springBootVersion = '2.1.3.RELEASE' + springCloudVersion = 'Greenwich.SR1' + } + repositories { + mavenCentral() + maven { url 'https://repo.spring.io/milestone' } + } + dependencies { + classpath "org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}" as Object + classpath "org.springframework.cloud:spring-cloud-dependencies:${springCloudVersion}" as Object + } +} + +plugins { + id "io.spring.dependency-management" version "1.0.5.RELEASE" + id 'java' + id 'org.springframework.boot' version '2.1.3.RELEASE' +} + +apply plugin: 'io.spring.dependency-management' + +group = 'hive' +version = '0.0.1-SNAPSHOT' +sourceCompatibility = '11' + +repositories { + mavenCentral() + maven { url 'https://repo.spring.io/milestone' } +} + +dependencies { + implementation project(':common') + implementation project(':entity') + + implementation 'javax.xml.bind:jaxb-api:2.3.1' + implementation 'javax.activation:activation:1.1.1' + implementation 'org.glassfish.jaxb:jaxb-runtime:2.3.2' + + implementation 'org.springframework.boot:spring-boot-starter-web' + implementation 'org.springframework.boot:spring-boot-starter-data-jpa' + implementation 'com.h2database:h2' + implementation 'org.springframework.cloud:spring-cloud-starter-netflix-eureka-client' + testImplementation 'org.springframework.boot:spring-boot-starter-test' +} + +dependencyManagement { + imports { + mavenBom "org.springframework.boot:spring-boot-dependencies:${springBootVersion}" + mavenBom "org.springframework.cloud:spring-cloud-dependencies:${springCloudVersion}" + } +} \ No newline at end of file diff --git a/mugshot/src/main/java/hive/mugshot/MugshotApplication.java b/mugshot/src/main/java/hive/mugshot/MugshotApplication.java new file mode 100644 index 0000000..009a2fb --- /dev/null +++ b/mugshot/src/main/java/hive/mugshot/MugshotApplication.java @@ -0,0 +1,15 @@ +package hive.mugshot; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.boot.autoconfigure.domain.EntityScan; +import org.springframework.cloud.netflix.eureka.EnableEurekaClient; + +@SpringBootApplication +@EnableEurekaClient +@EntityScan( basePackages = {"hive.entity"} ) +public class MugshotApplication { + public static void main(String[] args) { + SpringApplication.run(MugshotApplication.class, args); + } +} diff --git a/mugshot/src/main/java/hive/mugshot/controller/MugshotController.java b/mugshot/src/main/java/hive/mugshot/controller/MugshotController.java new file mode 100644 index 0000000..cb3c0e8 --- /dev/null +++ b/mugshot/src/main/java/hive/mugshot/controller/MugshotController.java @@ -0,0 +1,58 @@ +package hive.mugshot.controller; + +import hive.mugshot.exception.NotAcceptedFileFormatException; +import hive.mugshot.repository.UserRepository; +import hive.mugshot.storage.ImageStorer; +import hive.common.security.HiveHeaders; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpStatus; +import org.springframework.http.MediaType; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.*; +import org.springframework.web.multipart.MultipartFile; +import org.springframework.core.io.Resource; + +import static hive.mugshot.storage.ImageUtils.validateIfHasAnImageAsExtension; + +@RestController +@RequestMapping("/mugshot") +public class MugshotController { + @Value("${hive.mugshot.profile-image-name}") + private String imageName; + private final ImageStorer imageStorer; + private final UserRepository userRepository; + @Autowired public MugshotController(ImageStorer imageStorer,UserRepository userRepository) { + this.userRepository = userRepository; + this.imageStorer = imageStorer; + } + + @ResponseStatus(code = HttpStatus.OK, reason = "Profile image successfully stored") + @PostMapping + public void sendImageProfile( + @RequestParam("image") MultipartFile insertedImage, + @RequestHeader(name = HiveHeaders.AUTHENTICATED_USER_NAME_HEADER) final String username) { + if(!validateIfHasAnImageAsExtension(insertedImage.getOriginalFilename())) { + throw new NotAcceptedFileFormatException(); + } + var userID=userRepository.findByUsername(username).getId().toString(); + imageStorer.storeImageProfile(userID,insertedImage,imageName); + } + + @GetMapping(produces = MediaType.IMAGE_JPEG_VALUE) + public ResponseEntity searchProfileImage( + @RequestHeader(name = HiveHeaders.AUTHENTICATED_USER_NAME_HEADER) final String username) { + var userID=userRepository.findByUsername(username).getId().toString(); + Resource file = imageStorer.loadImage(userID,imageName); + return ResponseEntity.ok().header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + file.getFilename() + "\"").body(file); + } + + @ResponseStatus(code = HttpStatus.NO_CONTENT, reason = "Profile image successfully deleted") + @DeleteMapping + public void deleteProfileImage( + @RequestHeader(name = HiveHeaders.AUTHENTICATED_USER_NAME_HEADER) final String username) { + var userID=userRepository.findByUsername(username).getId().toString(); + imageStorer.deleteImage(userID,imageName); + } +} diff --git a/mugshot/src/main/java/hive/mugshot/controller/UtilsController.java b/mugshot/src/main/java/hive/mugshot/controller/UtilsController.java new file mode 100644 index 0000000..7a685ed --- /dev/null +++ b/mugshot/src/main/java/hive/mugshot/controller/UtilsController.java @@ -0,0 +1,55 @@ +package hive.mugshot.controller; + +import hive.mugshot.repository.UserRepository; +import hive.mugshot.storage.ImageStorer; +import hive.mugshot.storage.ImageUtils; +import hive.common.security.HiveHeaders; +import hive.entity.user.User; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.core.io.Resource; +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpStatus; +import org.springframework.http.MediaType; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.*; + +@RestController +@RequestMapping("/utils") +public class UtilsController { + private final UserRepository userRepository; + private final ImageStorer imageStorer; + @Value("${hive.mugshot.profile-image-name}") + private String imageName; + + + @ResponseStatus(code = HttpStatus.OK, reason = "The server is working") + @GetMapping("/hey") public void hey(){} + @Autowired + public UtilsController(ImageStorer imageStorer,UserRepository userRepository){ + this.userRepository=userRepository; + this.imageStorer=imageStorer; + userRepository.save(new User("User","123",0,0)); + userRepository.save(new User("Germano","123",0,0)); + userRepository.save(new User("Java","123",0,0)); + userRepository.save(new User("com espaco","123",0,0)); + userRepository.save(new User("com/barra","123",0,0)); + userRepository.save(new User("愛","123",0,0)); + } + + @GetMapping(value = "searchImage/{profileImageName:.+}", produces = MediaType.IMAGE_JPEG_VALUE) + public ResponseEntity searchSomeImage(@RequestHeader(name = HiveHeaders.AUTHENTICATED_USER_NAME_HEADER) final String username, @PathVariable String profileImageName) { + var userID=userRepository.findByUsername(username).getId().toString(); + Resource file = imageStorer.loadImage(username,profileImageName); + return ResponseEntity.ok().header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + file.getFilename() + "\"").body(file); + } + + @ResponseStatus(code = HttpStatus.OK, reason = "Random image generated and successfully stored") + @PostMapping("/generateRandomImage") + public void generateRandomImage(@RequestHeader(name = HiveHeaders.AUTHENTICATED_USER_NAME_HEADER) final String username) { + var generatedImage=ImageUtils.generateRandomImage(); + var userID=userRepository.findByUsername(username).getId(); + imageStorer.storeImageProfile(userID.toString(),generatedImage,imageName); + } + +} diff --git a/mugshot/src/main/java/hive/mugshot/exception/FileSizeException.java b/mugshot/src/main/java/hive/mugshot/exception/FileSizeException.java new file mode 100644 index 0000000..9d6d0e2 --- /dev/null +++ b/mugshot/src/main/java/hive/mugshot/exception/FileSizeException.java @@ -0,0 +1,7 @@ +package hive.mugshot.exception; +import org.springframework.http.HttpStatus; +import org.springframework.web.bind.annotation.ResponseStatus; + +@ResponseStatus(code = HttpStatus.PAYLOAD_TOO_LARGE,reason = "Invalid size of file") +public class FileSizeException extends RuntimeException{ +} diff --git a/mugshot/src/main/java/hive/mugshot/exception/ImageAlreadyExistException.java b/mugshot/src/main/java/hive/mugshot/exception/ImageAlreadyExistException.java new file mode 100644 index 0000000..c7eacc6 --- /dev/null +++ b/mugshot/src/main/java/hive/mugshot/exception/ImageAlreadyExistException.java @@ -0,0 +1,7 @@ +package hive.mugshot.exception; +import org.springframework.http.HttpStatus; +import org.springframework.web.bind.annotation.ResponseStatus; + +@ResponseStatus(code = HttpStatus.BAD_REQUEST, reason = "The Image already exists") +public class ImageAlreadyExistException extends RuntimeException{ +} diff --git a/mugshot/src/main/java/hive/mugshot/exception/ImageNotFound.java b/mugshot/src/main/java/hive/mugshot/exception/ImageNotFound.java new file mode 100644 index 0000000..5fbfa6f --- /dev/null +++ b/mugshot/src/main/java/hive/mugshot/exception/ImageNotFound.java @@ -0,0 +1,7 @@ +package hive.mugshot.exception; +import org.springframework.http.HttpStatus; +import org.springframework.web.bind.annotation.ResponseStatus; + +@ResponseStatus(code = HttpStatus.NOT_FOUND, reason = "Image not found for this user") +public class ImageNotFound extends RuntimeException{ +} diff --git a/mugshot/src/main/java/hive/mugshot/exception/ImageProfileException.java b/mugshot/src/main/java/hive/mugshot/exception/ImageProfileException.java new file mode 100644 index 0000000..2137cef --- /dev/null +++ b/mugshot/src/main/java/hive/mugshot/exception/ImageProfileException.java @@ -0,0 +1,7 @@ +package hive.mugshot.exception; +import org.springframework.http.HttpStatus; +import org.springframework.web.bind.annotation.ResponseStatus; + +@ResponseStatus(code = HttpStatus.BAD_REQUEST, reason = "Failed to store the image due to some I/O problem or permission") +public class ImageProfileException extends RuntimeException{ +} diff --git a/mugshot/src/main/java/hive/mugshot/exception/InvalidPathException.java b/mugshot/src/main/java/hive/mugshot/exception/InvalidPathException.java new file mode 100644 index 0000000..1a199ad --- /dev/null +++ b/mugshot/src/main/java/hive/mugshot/exception/InvalidPathException.java @@ -0,0 +1,8 @@ +package hive.mugshot.exception; + +import org.springframework.http.HttpStatus; +import org.springframework.web.bind.annotation.ResponseStatus; + +@ResponseStatus(code = HttpStatus.BAD_REQUEST, reason = "Invalid path") +public class InvalidPathException extends RuntimeException { +} \ No newline at end of file diff --git a/mugshot/src/main/java/hive/mugshot/exception/NotAcceptedFileFormatException.java b/mugshot/src/main/java/hive/mugshot/exception/NotAcceptedFileFormatException.java new file mode 100644 index 0000000..8f58da2 --- /dev/null +++ b/mugshot/src/main/java/hive/mugshot/exception/NotAcceptedFileFormatException.java @@ -0,0 +1,7 @@ +package hive.mugshot.exception; +import org.springframework.http.HttpStatus; +import org.springframework.web.bind.annotation.ResponseStatus; + +@ResponseStatus(code = HttpStatus.UNSUPPORTED_MEDIA_TYPE, reason = "Media type unsupported") +public class NotAcceptedFileFormatException extends RuntimeException{ +} diff --git a/mugshot/src/main/java/hive/mugshot/exception/UserNotFoundException.java b/mugshot/src/main/java/hive/mugshot/exception/UserNotFoundException.java new file mode 100644 index 0000000..84d85a0 --- /dev/null +++ b/mugshot/src/main/java/hive/mugshot/exception/UserNotFoundException.java @@ -0,0 +1,8 @@ +package hive.mugshot.exception; + +import org.springframework.http.HttpStatus; +import org.springframework.web.bind.annotation.ResponseStatus; + +@ResponseStatus(code = HttpStatus.BAD_REQUEST, reason = "The user does not exist") +public class UserNotFoundException extends RuntimeException { +} \ No newline at end of file diff --git a/mugshot/src/main/java/hive/mugshot/repository/UserRepository.java b/mugshot/src/main/java/hive/mugshot/repository/UserRepository.java new file mode 100644 index 0000000..e431394 --- /dev/null +++ b/mugshot/src/main/java/hive/mugshot/repository/UserRepository.java @@ -0,0 +1,8 @@ +package hive.mugshot.repository; + +import hive.entity.user.User; +import org.springframework.data.repository.CrudRepository; + +public interface UserRepository extends CrudRepository { + User findByUsername(String username); +} diff --git a/mugshot/src/main/java/hive/mugshot/storage/ImageStorer.java b/mugshot/src/main/java/hive/mugshot/storage/ImageStorer.java new file mode 100644 index 0000000..3c50cf1 --- /dev/null +++ b/mugshot/src/main/java/hive/mugshot/storage/ImageStorer.java @@ -0,0 +1,81 @@ +package hive.mugshot.storage; + +import hive.mugshot.exception.*; +import hive.mugshot.exception.InvalidPathException; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.core.io.Resource; +import org.springframework.core.io.UrlResource; +import org.springframework.stereotype.Service; +import org.springframework.web.multipart.MultipartFile; + +import javax.imageio.ImageIO; +import java.awt.image.BufferedImage; +import java.io.IOException; +import java.net.MalformedURLException; +import java.nio.file.*; + +@Service +public class ImageStorer { + @Value("${hive.mugshot.image-directory-path}") + private String rootDir; + @Value("${hive.mugshot.profile-image-dimension}") + private int imageSizeInPixels; + public void storeImageProfile(String userDirectoryName, MultipartFile insertedImage, String imageStoredName){ + this.createDirectoryIfNotExist(userDirectoryName); + try { + var buff = ImageUtils.resizeImageToSquare(ImageIO.read(insertedImage.getInputStream()),imageSizeInPixels); + ImageIO.write(buff, "jpg", resolveRootPathFullUrlWith(userDirectoryName, imageStoredName).toFile()); + } catch (IOException e) { + throw new RuntimeException(e); + } + } + public void storeImageProfile(String userDirectoryName, BufferedImage insertedImage, String imageStoredName){ + this.createDirectoryIfNotExist(userDirectoryName); + try { + var buff = ImageUtils.resizeImageToSquare(insertedImage,imageSizeInPixels); + ImageIO.write(buff, "jpg", resolveRootPathFullUrlWith(userDirectoryName, imageStoredName).toFile()); + } catch (IOException e) { + throw new RuntimeException(e); + } + } + public Resource loadImage(String userDirectoryName,String ImageName) { + try { + Path file = resolveRootPathFullUrlWith(userDirectoryName,ImageName); + Resource resource = new UrlResource(file.toUri()); + if (resource.exists() || resource.isReadable()) { + return resource; + }else{ + throw new ImageNotFound(); + } + } catch (MalformedURLException e) { + e.printStackTrace(); + throw new InvalidPathException(); + } + } + public void deleteImage(String userDirectoryName, String ImageName) { + Path parentDir = resolveRootPathFullUrlWith(userDirectoryName,ImageName); + try { + Files.deleteIfExists(parentDir); + } catch (IOException e) { + e.printStackTrace(); + throw new RuntimeException("Not capable to delete the directory.\n"+e); + } + } + + + private void createDirectoryIfNotExist(String userDirectoryPath){ + Path parentDir = Paths.get(rootDir,userDirectoryPath); + if (!Files.exists(parentDir)) { + try { + Files.createDirectories(parentDir); + } catch (IOException e) { + throw new RuntimeException("Not capable to create the directory.\n"+e); + } + } + } + private Path resolveRootPathFullUrlWith(String userDirectoryName, String filename) { + return Paths.get(rootDir).resolve(userDirectoryName).resolve(filename); + } +} + + diff --git a/mugshot/src/main/java/hive/mugshot/storage/ImageUtils.java b/mugshot/src/main/java/hive/mugshot/storage/ImageUtils.java new file mode 100644 index 0000000..15d7f57 --- /dev/null +++ b/mugshot/src/main/java/hive/mugshot/storage/ImageUtils.java @@ -0,0 +1,62 @@ +package hive.mugshot.storage; + +import java.awt.*; +import java.awt.image.BufferedImage; +import java.util.Random; +import java.util.regex.Pattern; + +public final class ImageUtils { + private static final String IMAGE_PATTERN = "(.+\\.(gif|png|bmp|jpeg|jpg)$)"; + private ImageUtils(){ + } + public static boolean validateIfHasAnImageAsExtension(final String image){ + var pattern = Pattern.compile(IMAGE_PATTERN); + var matcher = pattern.matcher(image); + return matcher.matches(); + } + + public static BufferedImage resizeImageToSquare(BufferedImage inputtedImage,int imageSizeInPixels) { + // multi-pass bilinear div 2 + var bufferedImageWithNewSize = new BufferedImage(imageSizeInPixels, imageSizeInPixels, BufferedImage.TYPE_INT_RGB); + var reSizer = bufferedImageWithNewSize.createGraphics(); + var resizingMode= + (inputtedImage.getHeight() Date: Sat, 27 Apr 2019 00:44:25 -0300 Subject: [PATCH 26/54] Added polymorphism to StoreImageProfile() --- .../java/hive/album/storage/ImageStorer.java | 20 +++++++++++++++---- 1 file changed, 16 insertions(+), 4 deletions(-) diff --git a/album/src/main/java/hive/album/storage/ImageStorer.java b/album/src/main/java/hive/album/storage/ImageStorer.java index a55b067..3e1520e 100644 --- a/album/src/main/java/hive/album/storage/ImageStorer.java +++ b/album/src/main/java/hive/album/storage/ImageStorer.java @@ -9,21 +9,31 @@ import org.springframework.web.multipart.MultipartFile; import javax.imageio.ImageIO; +import java.awt.image.BufferedImage; import java.io.IOException; import java.net.MalformedURLException; import java.nio.file.*; @Service public class ImageStorer { - @Value("${hive.mugshot.image-directory-path}") + @Value("${hive.album.image-directory-path}") private String rootDir; - @Value("${hive.mugshot.profile-image-dimension}") + @Value("${hive.album.profile-image-dimension}") private int imageSizeInPixels; - public void StoreImageProfile(String userDirectoryName,MultipartFile insertedImage,String imageStoredName){ + public void storeImageProfile(String userDirectoryName, MultipartFile insertedImage, String imageStoredName){ this.createDirectoryIfNotExist(userDirectoryName); try { var buff = ImageUtils.resizeImageToSquare(ImageIO.read(insertedImage.getInputStream()),imageSizeInPixels); - ImageIO.write(buff, "png", resolveRootPathFullUrlWith(userDirectoryName, imageStoredName).toFile()); + ImageIO.write(buff, "jpg", resolveRootPathFullUrlWith(userDirectoryName, imageStoredName).toFile()); + } catch (IOException e) { + throw new RuntimeException(e); + } + } + public void storeImageProfile(String userDirectoryName, BufferedImage insertedImage, String imageStoredName){ + this.createDirectoryIfNotExist(userDirectoryName); + try { + var buff = ImageUtils.resizeImageToSquare(insertedImage,imageSizeInPixels); + ImageIO.write(buff, "jpg", resolveRootPathFullUrlWith(userDirectoryName, imageStoredName).toFile()); } catch (IOException e) { throw new RuntimeException(e); } @@ -67,3 +77,5 @@ private Path resolveRootPathFullUrlWith(String userDirectoryName, String filenam return Paths.get(rootDir).resolve(userDirectoryName).resolve(filename); } } + + From dfcdfb5c8154aeaedc25e0d80e49e1944a188b9e Mon Sep 17 00:00:00 2001 From: germano Date: Sat, 27 Apr 2019 00:58:17 -0300 Subject: [PATCH 27/54] UtilsController can generate random profile images. --- .../album/controller/UtilsController.java | 50 +++++++++++++++++++ 1 file changed, 50 insertions(+) create mode 100644 mugshot/src/main/java/hive/album/controller/UtilsController.java diff --git a/mugshot/src/main/java/hive/album/controller/UtilsController.java b/mugshot/src/main/java/hive/album/controller/UtilsController.java new file mode 100644 index 0000000..31639a0 --- /dev/null +++ b/mugshot/src/main/java/hive/album/controller/UtilsController.java @@ -0,0 +1,50 @@ +package hive.album.controller; + +import hive.album.repository.UserRepository; +import hive.album.storage.ImageStorer; +import hive.album.storage.ImageUtils; +import hive.common.security.HiveHeaders; +import hive.entity.user.User; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.core.io.Resource; +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpStatus; +import org.springframework.http.MediaType; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.*; + +@RestController +@RequestMapping("/utils") +public class UtilsController { + private final UserRepository userRepository; + private final ImageStorer imageStorer; + @Value("${hive.album.profile-image-name}") + private String imageName; + + + @ResponseStatus(code = HttpStatus.OK, reason = "The server is working") + @GetMapping("/hey") public void hey(){} + @Autowired + public UtilsController(ImageStorer imageStorer,UserRepository userRepository){ + this.userRepository=userRepository; + this.imageStorer=imageStorer; + userRepository.save(new User("Test_User","123",0,0)); + } + + @GetMapping(value = "searchImage/{profileImageName:.+}", produces = MediaType.IMAGE_JPEG_VALUE) + public ResponseEntity searchSomeImage(@RequestHeader(name = HiveHeaders.AUTHENTICATED_USER_NAME_HEADER) final String username, @PathVariable String profileImageName) { + var userID=userRepository.findByUsername(username).getId().toString(); + Resource file = imageStorer.loadImage(username,profileImageName); + return ResponseEntity.ok().header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + file.getFilename() + "\"").body(file); + } + + @ResponseStatus(code = HttpStatus.OK, reason = "Random image generated and successfully stored") + @PostMapping("/generateRandomImage") + public void generateRandomImage(@RequestHeader(name = HiveHeaders.AUTHENTICATED_USER_NAME_HEADER) final String username) { + var generatedImage=ImageUtils.generateRandomImage(); + var userID=userRepository.findByUsername(username).getId(); + imageStorer.storeImageProfile(userID.toString(),generatedImage,imageName); + } + +} From 1afe85f5dfd49445a75b4e324d052e6683dc0e22 Mon Sep 17 00:00:00 2001 From: germano Date: Sat, 27 Apr 2019 01:06:20 -0300 Subject: [PATCH 28/54] SetUp for tests with valid image --- .../java/hive/mugshot/storage/ImageStorerTest.java | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/mugshot/src/test/java/hive/mugshot/storage/ImageStorerTest.java b/mugshot/src/test/java/hive/mugshot/storage/ImageStorerTest.java index 2204d00..e1f17f0 100644 --- a/mugshot/src/test/java/hive/mugshot/storage/ImageStorerTest.java +++ b/mugshot/src/test/java/hive/mugshot/storage/ImageStorerTest.java @@ -1,5 +1,4 @@ package hive.mugshot.storage; - import org.junit.*; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; @@ -10,6 +9,8 @@ import org.springframework.test.context.junit4.SpringRunner; import javax.imageio.ImageIO; +import java.awt.image.BufferedImage; +import java.io.ByteArrayOutputStream; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; @@ -32,13 +33,16 @@ public class ImageStorerTest { @Before - public void setUp(){ + public void setUp() throws IOException { userId= ThreadLocalRandom.current().nextInt(Integer.MAX_VALUE); + var initialImage=new BufferedImage(512,512,BufferedImage.TYPE_INT_RGB); + var byteArrayOutputStream = new ByteArrayOutputStream(); + ImageIO.write(initialImage,"jpg",byteArrayOutputStream); multipartFile=new MockMultipartFile( "image", "WhateverName.gif", MediaType.IMAGE_JPEG_VALUE, - "Spring Framework".getBytes() + byteArrayOutputStream.toByteArray() ); } From 6f8f5f4f324247955b7ce463a6066177f927163c Mon Sep 17 00:00:00 2001 From: germano Date: Sat, 27 Apr 2019 01:08:41 -0300 Subject: [PATCH 29/54] Added an special user to try the API --- .../main/java/hive/mugshot/controller/UtilsController.java | 7 +------ 1 file changed, 1 insertion(+), 6 deletions(-) diff --git a/mugshot/src/main/java/hive/mugshot/controller/UtilsController.java b/mugshot/src/main/java/hive/mugshot/controller/UtilsController.java index 7a685ed..bdb88e1 100644 --- a/mugshot/src/main/java/hive/mugshot/controller/UtilsController.java +++ b/mugshot/src/main/java/hive/mugshot/controller/UtilsController.java @@ -29,12 +29,7 @@ public class UtilsController { public UtilsController(ImageStorer imageStorer,UserRepository userRepository){ this.userRepository=userRepository; this.imageStorer=imageStorer; - userRepository.save(new User("User","123",0,0)); - userRepository.save(new User("Germano","123",0,0)); - userRepository.save(new User("Java","123",0,0)); - userRepository.save(new User("com espaco","123",0,0)); - userRepository.save(new User("com/barra","123",0,0)); - userRepository.save(new User("愛","123",0,0)); + userRepository.save(new User("Test_User","123",0,0)); } @GetMapping(value = "searchImage/{profileImageName:.+}", produces = MediaType.IMAGE_JPEG_VALUE) From e2039ddf804e00e15a1afd0688015bdc075f8099 Mon Sep 17 00:00:00 2001 From: germano Date: Sat, 27 Apr 2019 01:10:05 -0300 Subject: [PATCH 30/54] Removed the entire module with "Album" as name --- album/build.gradle | 53 ------ .../java/hive/album/MugshotApplication.java | 15 -- .../album/controller/MugshotController.java | 60 ------- .../album/controller/UtilsController.java | 50 ------ .../java/hive/album/entity/ProfileImage.java | 25 --- .../album/exception/FileSizeException.java | 7 - .../exception/ImageAlreadyExistException.java | 7 - .../hive/album/exception/ImageNotFound.java | 7 - .../exception/ImageProfileException.java | 7 - .../album/exception/InvalidPathException.java | 8 - .../NotAcceptedFileFormatException.java | 7 - .../exception/UserNotFoundException.java | 8 - .../hive/album/repository/UserRepository.java | 10 -- .../java/hive/album/storage/ImageStorer.java | 81 --------- .../java/hive/album/storage/ImageUtils.java | 61 ------- .../src/main/resources/application.properties | 19 -- .../hive/album/MugshotApplicationTests.java | 16 -- .../controller/MugshotControllerTest.java | 165 ------------------ .../album/controller/UtilsControllerTest.java | 42 ----- .../hive/album/storage/ImageStorerTest.java | 89 ---------- .../hive/album/storage/ImageUtilsTest.java | 38 ---- 21 files changed, 775 deletions(-) delete mode 100644 album/build.gradle delete mode 100644 album/src/main/java/hive/album/MugshotApplication.java delete mode 100644 album/src/main/java/hive/album/controller/MugshotController.java delete mode 100644 album/src/main/java/hive/album/controller/UtilsController.java delete mode 100644 album/src/main/java/hive/album/entity/ProfileImage.java delete mode 100644 album/src/main/java/hive/album/exception/FileSizeException.java delete mode 100644 album/src/main/java/hive/album/exception/ImageAlreadyExistException.java delete mode 100644 album/src/main/java/hive/album/exception/ImageNotFound.java delete mode 100644 album/src/main/java/hive/album/exception/ImageProfileException.java delete mode 100644 album/src/main/java/hive/album/exception/InvalidPathException.java delete mode 100644 album/src/main/java/hive/album/exception/NotAcceptedFileFormatException.java delete mode 100644 album/src/main/java/hive/album/exception/UserNotFoundException.java delete mode 100644 album/src/main/java/hive/album/repository/UserRepository.java delete mode 100644 album/src/main/java/hive/album/storage/ImageStorer.java delete mode 100644 album/src/main/java/hive/album/storage/ImageUtils.java delete mode 100644 album/src/main/resources/application.properties delete mode 100644 album/src/test/java/hive/album/MugshotApplicationTests.java delete mode 100644 album/src/test/java/hive/album/controller/MugshotControllerTest.java delete mode 100644 album/src/test/java/hive/album/controller/UtilsControllerTest.java delete mode 100644 album/src/test/java/hive/album/storage/ImageStorerTest.java delete mode 100644 album/src/test/java/hive/album/storage/ImageUtilsTest.java diff --git a/album/build.gradle b/album/build.gradle deleted file mode 100644 index 2e8e18a..0000000 --- a/album/build.gradle +++ /dev/null @@ -1,53 +0,0 @@ -buildscript { - ext { - springBootVersion = '2.1.3.RELEASE' - springCloudVersion = 'Greenwich.SR1' - } - repositories { - mavenCentral() - maven { url 'https://repo.spring.io/milestone' } - } - dependencies { - classpath "org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}" as Object - classpath "org.springframework.cloud:spring-cloud-dependencies:${springCloudVersion}" as Object - } -} - -plugins { - id "io.spring.dependency-management" version "1.0.5.RELEASE" - id 'java' - id 'org.springframework.boot' version '2.1.3.RELEASE' -} - -apply plugin: 'io.spring.dependency-management' - -group = 'hive' -version = '0.0.1-SNAPSHOT' -sourceCompatibility = '11' - -repositories { - mavenCentral() - maven { url 'https://repo.spring.io/milestone' } -} - -dependencies { - implementation project(':common') - implementation project(':entity') - - implementation 'javax.xml.bind:jaxb-api:2.3.1' - implementation 'javax.activation:activation:1.1.1' - implementation 'org.glassfish.jaxb:jaxb-runtime:2.3.2' - - implementation 'org.springframework.boot:spring-boot-starter-web' - implementation 'org.springframework.boot:spring-boot-starter-data-jpa' - implementation 'com.h2database:h2' - implementation 'org.springframework.cloud:spring-cloud-starter-netflix-eureka-client' - testImplementation 'org.springframework.boot:spring-boot-starter-test' -} - -dependencyManagement { - imports { - mavenBom "org.springframework.boot:spring-boot-dependencies:${springBootVersion}" - mavenBom "org.springframework.cloud:spring-cloud-dependencies:${springCloudVersion}" - } -} \ No newline at end of file diff --git a/album/src/main/java/hive/album/MugshotApplication.java b/album/src/main/java/hive/album/MugshotApplication.java deleted file mode 100644 index a98245f..0000000 --- a/album/src/main/java/hive/album/MugshotApplication.java +++ /dev/null @@ -1,15 +0,0 @@ -package hive.album; - -import org.springframework.boot.SpringApplication; -import org.springframework.boot.autoconfigure.SpringBootApplication; -import org.springframework.boot.autoconfigure.domain.EntityScan; -import org.springframework.cloud.netflix.eureka.EnableEurekaClient; - -@SpringBootApplication -@EnableEurekaClient -@EntityScan( basePackages = {"hive.entity"} ) -public class MugshotApplication { - public static void main(String[] args) { - SpringApplication.run(MugshotApplication.class, args); - } -} diff --git a/album/src/main/java/hive/album/controller/MugshotController.java b/album/src/main/java/hive/album/controller/MugshotController.java deleted file mode 100644 index ce30cf7..0000000 --- a/album/src/main/java/hive/album/controller/MugshotController.java +++ /dev/null @@ -1,60 +0,0 @@ -package hive.album.controller; - -import hive.album.exception.NotAcceptedFileFormatException; -import hive.album.repository.UserRepository; -import hive.album.storage.ImageStorer; -import hive.common.security.HiveHeaders; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Value; -import org.springframework.http.HttpHeaders; -import org.springframework.http.HttpStatus; -import org.springframework.http.MediaType; -import org.springframework.http.ResponseEntity; -import org.springframework.web.bind.annotation.*; -import org.springframework.web.multipart.MultipartFile; -import org.springframework.core.io.Resource; - -import static hive.album.storage.ImageUtils.validateIfHasAnImageAsExtension; - -@RestController -@RequestMapping("/mugshot") -public class MugshotController { - @Value("${hive.mugshot.image-directory-path}") - private String rootDir; - @Value("${hive.mugshot.profile-image-name}") - private String imageName; - private final ImageStorer imageStorer; - private final UserRepository userRepository; - @Autowired public MugshotController(ImageStorer imageStorer,UserRepository userRepository) { - this.userRepository = userRepository; - this.imageStorer = imageStorer; - } - - @ResponseStatus(code = HttpStatus.OK, reason = "Profile image successfully stored") - @PostMapping - public void sendImageProfile( - @RequestParam("image") MultipartFile insertedImage, - @RequestHeader(name = HiveHeaders.AUTHENTICATED_USER_NAME_HEADER) final String username) { - if(!validateIfHasAnImageAsExtension(insertedImage.getOriginalFilename())) { - throw new NotAcceptedFileFormatException(); - } - var userID=userRepository.findByUsername(username).getId().toString(); - imageStorer.StoreImageProfile(userID,insertedImage,imageName); - } - - @GetMapping(produces = MediaType.IMAGE_JPEG_VALUE) - public ResponseEntity searchProfileImage( - @RequestHeader(name = HiveHeaders.AUTHENTICATED_USER_NAME_HEADER) final String username) { - var userID=userRepository.findByUsername(username).getId().toString(); - Resource file = imageStorer.loadImage(userID,imageName); - return ResponseEntity.ok().header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + file.getFilename() + "\"").body(file); - } - - @ResponseStatus(code = HttpStatus.NO_CONTENT, reason = "Profile image successfully deleted") - @DeleteMapping - public void deleteProfileImage( - @RequestHeader(name = HiveHeaders.AUTHENTICATED_USER_NAME_HEADER) final String username) { - var userID=userRepository.findByUsername(username).getId().toString(); - imageStorer.deleteImage(userID,imageName); - } -} diff --git a/album/src/main/java/hive/album/controller/UtilsController.java b/album/src/main/java/hive/album/controller/UtilsController.java deleted file mode 100644 index 821844e..0000000 --- a/album/src/main/java/hive/album/controller/UtilsController.java +++ /dev/null @@ -1,50 +0,0 @@ -package hive.album.controller; - -import hive.album.repository.UserRepository; -import hive.album.storage.ImageStorer; -import hive.common.security.HiveHeaders; -import hive.entity.user.User; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.core.io.Resource; -import org.springframework.http.HttpHeaders; -import org.springframework.http.HttpStatus; -import org.springframework.http.MediaType; -import org.springframework.http.ResponseEntity; -import org.springframework.web.bind.annotation.*; - -@RestController -@RequestMapping("/utils") -public class UtilsController { - private final UserRepository userRepository; - private final ImageStorer imageStorer; - @ResponseStatus(code = HttpStatus.OK, reason = "The server is working and have an user") - @GetMapping("/hey") public void hey(){} - @GetMapping("/dir") public String getRootDirectory() { - return "nothing"; - } - @Autowired public UtilsController(UserRepository userRepository,ImageStorer imageStorer){ - this.userRepository=userRepository; - this.imageStorer=imageStorer; - userRepository.save(new User("User","123",0,0)); - userRepository.save(new User("Germano","123",0,0)); - userRepository.save(new User("Java","123",0,0)); - userRepository.save(new User("com espaço","123",0,0)); - userRepository.save(new User("com/barra","123",0,0)); - userRepository.save(new User("愛","123",0,0)); - } - @GetMapping("/user") public User getUser - (@RequestHeader(name = HiveHeaders.AUTHENTICATED_USER_NAME_HEADER) final String username) - { - return userRepository.findByUsername(username); - } - @GetMapping("/users") public Iterable getAllUser() - { - return userRepository.findAll(); - } - @GetMapping(value = "searchImage/{profileImageName:.+}", produces = MediaType.IMAGE_JPEG_VALUE) - public ResponseEntity searchSomeImage(@RequestHeader(name = HiveHeaders.AUTHENTICATED_USER_NAME_HEADER) final String username, @PathVariable String profileImageName) { - var userID=userRepository.findByUsername(username).getId().toString(); - Resource file = imageStorer.loadImage(username,profileImageName); - return ResponseEntity.ok().header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + file.getFilename() + "\"").body(file); - } -} diff --git a/album/src/main/java/hive/album/entity/ProfileImage.java b/album/src/main/java/hive/album/entity/ProfileImage.java deleted file mode 100644 index f302d39..0000000 --- a/album/src/main/java/hive/album/entity/ProfileImage.java +++ /dev/null @@ -1,25 +0,0 @@ -package hive.album.entity; - -public class ProfileImage { - private String path; - private String content; - - public ProfileImage() { - } - public ProfileImage(String path, String content) { - this.path = path; - this.content = content; - } - public String getPath() { - return path; - } - public void setPath(String path) { - this.path = path; - } - public String getContent() { - return content; - } - public void setContent(String content) { - this.content = content; - } -} diff --git a/album/src/main/java/hive/album/exception/FileSizeException.java b/album/src/main/java/hive/album/exception/FileSizeException.java deleted file mode 100644 index f049eb2..0000000 --- a/album/src/main/java/hive/album/exception/FileSizeException.java +++ /dev/null @@ -1,7 +0,0 @@ -package hive.album.exception; -import org.springframework.http.HttpStatus; -import org.springframework.web.bind.annotation.ResponseStatus; - -@ResponseStatus(code = HttpStatus.PAYLOAD_TOO_LARGE,reason = "Invalid size of file") -public class FileSizeException extends RuntimeException{ -} diff --git a/album/src/main/java/hive/album/exception/ImageAlreadyExistException.java b/album/src/main/java/hive/album/exception/ImageAlreadyExistException.java deleted file mode 100644 index a9be030..0000000 --- a/album/src/main/java/hive/album/exception/ImageAlreadyExistException.java +++ /dev/null @@ -1,7 +0,0 @@ -package hive.album.exception; -import org.springframework.http.HttpStatus; -import org.springframework.web.bind.annotation.ResponseStatus; - -@ResponseStatus(code = HttpStatus.BAD_REQUEST, reason = "The Image already exists") -public class ImageAlreadyExistException extends RuntimeException{ -} diff --git a/album/src/main/java/hive/album/exception/ImageNotFound.java b/album/src/main/java/hive/album/exception/ImageNotFound.java deleted file mode 100644 index f2c1563..0000000 --- a/album/src/main/java/hive/album/exception/ImageNotFound.java +++ /dev/null @@ -1,7 +0,0 @@ -package hive.album.exception; -import org.springframework.http.HttpStatus; -import org.springframework.web.bind.annotation.ResponseStatus; - -@ResponseStatus(code = HttpStatus.NOT_FOUND, reason = "Image not found for this user") -public class ImageNotFound extends RuntimeException{ -} diff --git a/album/src/main/java/hive/album/exception/ImageProfileException.java b/album/src/main/java/hive/album/exception/ImageProfileException.java deleted file mode 100644 index 71651c2..0000000 --- a/album/src/main/java/hive/album/exception/ImageProfileException.java +++ /dev/null @@ -1,7 +0,0 @@ -package hive.album.exception; -import org.springframework.http.HttpStatus; -import org.springframework.web.bind.annotation.ResponseStatus; - -@ResponseStatus(code = HttpStatus.BAD_REQUEST, reason = "Failed to store the image due to some I/O problem or permission") -public class ImageProfileException extends RuntimeException{ -} diff --git a/album/src/main/java/hive/album/exception/InvalidPathException.java b/album/src/main/java/hive/album/exception/InvalidPathException.java deleted file mode 100644 index 348c5ff..0000000 --- a/album/src/main/java/hive/album/exception/InvalidPathException.java +++ /dev/null @@ -1,8 +0,0 @@ -package hive.album.exception; - -import org.springframework.http.HttpStatus; -import org.springframework.web.bind.annotation.ResponseStatus; - -@ResponseStatus(code = HttpStatus.BAD_REQUEST, reason = "Invalid path") -public class InvalidPathException extends RuntimeException { -} \ No newline at end of file diff --git a/album/src/main/java/hive/album/exception/NotAcceptedFileFormatException.java b/album/src/main/java/hive/album/exception/NotAcceptedFileFormatException.java deleted file mode 100644 index ac75e94..0000000 --- a/album/src/main/java/hive/album/exception/NotAcceptedFileFormatException.java +++ /dev/null @@ -1,7 +0,0 @@ -package hive.album.exception; -import org.springframework.http.HttpStatus; -import org.springframework.web.bind.annotation.ResponseStatus; - -@ResponseStatus(code = HttpStatus.UNSUPPORTED_MEDIA_TYPE, reason = "Media type unsupported") -public class NotAcceptedFileFormatException extends RuntimeException{ -} diff --git a/album/src/main/java/hive/album/exception/UserNotFoundException.java b/album/src/main/java/hive/album/exception/UserNotFoundException.java deleted file mode 100644 index e45007a..0000000 --- a/album/src/main/java/hive/album/exception/UserNotFoundException.java +++ /dev/null @@ -1,8 +0,0 @@ -package hive.album.exception; - -import org.springframework.http.HttpStatus; -import org.springframework.web.bind.annotation.ResponseStatus; - -@ResponseStatus(code = HttpStatus.BAD_REQUEST, reason = "The user does not exist") -public class UserNotFoundException extends RuntimeException { -} \ No newline at end of file diff --git a/album/src/main/java/hive/album/repository/UserRepository.java b/album/src/main/java/hive/album/repository/UserRepository.java deleted file mode 100644 index b18c313..0000000 --- a/album/src/main/java/hive/album/repository/UserRepository.java +++ /dev/null @@ -1,10 +0,0 @@ -package hive.album.repository; - -import hive.entity.user.User; -import org.springframework.data.repository.CrudRepository; -import org.springframework.http.HttpStatus; -import org.springframework.web.bind.annotation.ResponseStatus; - -public interface UserRepository extends CrudRepository { - User findByUsername(String username); -} diff --git a/album/src/main/java/hive/album/storage/ImageStorer.java b/album/src/main/java/hive/album/storage/ImageStorer.java deleted file mode 100644 index 3e1520e..0000000 --- a/album/src/main/java/hive/album/storage/ImageStorer.java +++ /dev/null @@ -1,81 +0,0 @@ -package hive.album.storage; - -import hive.album.exception.*; -import hive.album.exception.InvalidPathException; -import org.springframework.beans.factory.annotation.Value; -import org.springframework.core.io.Resource; -import org.springframework.core.io.UrlResource; -import org.springframework.stereotype.Service; -import org.springframework.web.multipart.MultipartFile; - -import javax.imageio.ImageIO; -import java.awt.image.BufferedImage; -import java.io.IOException; -import java.net.MalformedURLException; -import java.nio.file.*; - -@Service -public class ImageStorer { - @Value("${hive.album.image-directory-path}") - private String rootDir; - @Value("${hive.album.profile-image-dimension}") - private int imageSizeInPixels; - public void storeImageProfile(String userDirectoryName, MultipartFile insertedImage, String imageStoredName){ - this.createDirectoryIfNotExist(userDirectoryName); - try { - var buff = ImageUtils.resizeImageToSquare(ImageIO.read(insertedImage.getInputStream()),imageSizeInPixels); - ImageIO.write(buff, "jpg", resolveRootPathFullUrlWith(userDirectoryName, imageStoredName).toFile()); - } catch (IOException e) { - throw new RuntimeException(e); - } - } - public void storeImageProfile(String userDirectoryName, BufferedImage insertedImage, String imageStoredName){ - this.createDirectoryIfNotExist(userDirectoryName); - try { - var buff = ImageUtils.resizeImageToSquare(insertedImage,imageSizeInPixels); - ImageIO.write(buff, "jpg", resolveRootPathFullUrlWith(userDirectoryName, imageStoredName).toFile()); - } catch (IOException e) { - throw new RuntimeException(e); - } - } - public Resource loadImage(String userDirectoryName,String ImageName) { - try { - Path file = resolveRootPathFullUrlWith(userDirectoryName,ImageName); - Resource resource = new UrlResource(file.toUri()); - if (resource.exists() || resource.isReadable()) { - return resource; - }else{ - throw new ImageNotFound(); - } - } catch (MalformedURLException e) { - e.printStackTrace(); - throw new InvalidPathException(); - } - } - public void deleteImage(String userDirectoryName, String ImageName) { - Path parentDir = resolveRootPathFullUrlWith(userDirectoryName,ImageName); - try { - Files.deleteIfExists(parentDir); - } catch (IOException e) { - e.printStackTrace(); - throw new RuntimeException("Not capable to delete the directory.\n"+e); - } - } - - - private void createDirectoryIfNotExist(String userDirectoryPath){ - Path parentDir = Paths.get(rootDir,userDirectoryPath); - if (!Files.exists(parentDir)) { - try { - Files.createDirectories(parentDir); - } catch (IOException e) { - throw new RuntimeException("Not capable to create the directory.\n"+e); - } - } - } - private Path resolveRootPathFullUrlWith(String userDirectoryName, String filename) { - return Paths.get(rootDir).resolve(userDirectoryName).resolve(filename); - } -} - - diff --git a/album/src/main/java/hive/album/storage/ImageUtils.java b/album/src/main/java/hive/album/storage/ImageUtils.java deleted file mode 100644 index 58d9b95..0000000 --- a/album/src/main/java/hive/album/storage/ImageUtils.java +++ /dev/null @@ -1,61 +0,0 @@ -package hive.album.storage; - -import org.springframework.beans.factory.annotation.Value; - -import java.awt.*; -import java.awt.image.BufferedImage; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -public final class ImageUtils { - private static final String IMAGE_PATTERN = "(.+\\.(gif|png|bmp|jpeg|jpg)$)"; - private ImageUtils(){ - } - public static boolean validateIfHasAnImageAsExtension(final String image){ - var pattern = Pattern.compile(IMAGE_PATTERN); - var matcher = pattern.matcher(image); - return matcher.matches(); - } - - public static BufferedImage resizeImageToSquare(BufferedImage inputtedImage,int imageSizeInPixels) { - // multi-pass bilinear div 2 - var bufferedImageWithNewSize = new BufferedImage(imageSizeInPixels, imageSizeInPixels, BufferedImage.TYPE_INT_RGB); - var reSizer = bufferedImageWithNewSize.createGraphics(); - reSizer.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR); - reSizer.drawImage(inputtedImage, 0, 0, imageSizeInPixels, imageSizeInPixels, null); - reSizer.dispose(); - return bufferedImageWithNewSize; - } - public static BufferedImage generateRandomImage(){ - var img=new BufferedImage(4,4,BufferedImage.TYPE_INT_RGB); - var maxH=img.getHeight(); - var maxV=img.getWidth(); - for(int vertical=0;vertical Date: Sat, 27 Apr 2019 15:40:53 -0300 Subject: [PATCH 31/54] EOL at EOF --- mugshot/build.gradle | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/mugshot/build.gradle b/mugshot/build.gradle index 2e8e18a..6515ebf 100644 --- a/mugshot/build.gradle +++ b/mugshot/build.gradle @@ -50,4 +50,4 @@ dependencyManagement { mavenBom "org.springframework.boot:spring-boot-dependencies:${springBootVersion}" mavenBom "org.springframework.cloud:spring-cloud-dependencies:${springCloudVersion}" } -} \ No newline at end of file +} From ccb9592eeca4d5cd2c2e5789a8ff47eef2100c24 Mon Sep 17 00:00:00 2001 From: germano Date: Sat, 27 Apr 2019 15:47:13 -0300 Subject: [PATCH 32/54] Refactored @RequestMapping --- .../main/java/hive/mugshot/controller/MugshotController.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/mugshot/src/main/java/hive/mugshot/controller/MugshotController.java b/mugshot/src/main/java/hive/mugshot/controller/MugshotController.java index cb3c0e8..135e625 100644 --- a/mugshot/src/main/java/hive/mugshot/controller/MugshotController.java +++ b/mugshot/src/main/java/hive/mugshot/controller/MugshotController.java @@ -17,7 +17,7 @@ import static hive.mugshot.storage.ImageUtils.validateIfHasAnImageAsExtension; @RestController -@RequestMapping("/mugshot") +@RequestMapping("/") public class MugshotController { @Value("${hive.mugshot.profile-image-name}") private String imageName; From d287db25a6aa683cbc401f73c74ebba5be0cc4c7 Mon Sep 17 00:00:00 2001 From: germano Date: Sat, 27 Apr 2019 15:55:00 -0300 Subject: [PATCH 33/54] EOL at EOF --- .../main/java/hive/mugshot/exception/UserNotFoundException.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/mugshot/src/main/java/hive/mugshot/exception/UserNotFoundException.java b/mugshot/src/main/java/hive/mugshot/exception/UserNotFoundException.java index 84d85a0..948d8d0 100644 --- a/mugshot/src/main/java/hive/mugshot/exception/UserNotFoundException.java +++ b/mugshot/src/main/java/hive/mugshot/exception/UserNotFoundException.java @@ -5,4 +5,4 @@ @ResponseStatus(code = HttpStatus.BAD_REQUEST, reason = "The user does not exist") public class UserNotFoundException extends RuntimeException { -} \ No newline at end of file +} From b6374fbcdd87a8cc42bd762c3718d4664068a3eb Mon Sep 17 00:00:00 2001 From: germano Date: Sat, 27 Apr 2019 16:01:15 -0300 Subject: [PATCH 34/54] Switched explicit variable types to var --- .../hive/mugshot/storage/ImageStorer.java | 32 ++++++++++--------- 1 file changed, 17 insertions(+), 15 deletions(-) diff --git a/mugshot/src/main/java/hive/mugshot/storage/ImageStorer.java b/mugshot/src/main/java/hive/mugshot/storage/ImageStorer.java index 3c50cf1..ee4d454 100644 --- a/mugshot/src/main/java/hive/mugshot/storage/ImageStorer.java +++ b/mugshot/src/main/java/hive/mugshot/storage/ImageStorer.java @@ -20,28 +20,30 @@ public class ImageStorer { private String rootDir; @Value("${hive.mugshot.profile-image-dimension}") private int imageSizeInPixels; + public void storeImageProfile(String userDirectoryName, MultipartFile insertedImage, String imageStoredName){ - this.createDirectoryIfNotExist(userDirectoryName); + createDirectoryIfNotExist(userDirectoryName); try { var buff = ImageUtils.resizeImageToSquare(ImageIO.read(insertedImage.getInputStream()),imageSizeInPixels); - ImageIO.write(buff, "jpg", resolveRootPathFullUrlWith(userDirectoryName, imageStoredName).toFile()); + ImageIO.write(buff, "jpg", createFullPathToTheFile(userDirectoryName, imageStoredName).toFile()); } catch (IOException e) { throw new RuntimeException(e); } } + public void storeImageProfile(String userDirectoryName, BufferedImage insertedImage, String imageStoredName){ - this.createDirectoryIfNotExist(userDirectoryName); + createDirectoryIfNotExist(userDirectoryName); try { var buff = ImageUtils.resizeImageToSquare(insertedImage,imageSizeInPixels); - ImageIO.write(buff, "jpg", resolveRootPathFullUrlWith(userDirectoryName, imageStoredName).toFile()); + ImageIO.write(buff, "jpg", createFullPathToTheFile(userDirectoryName, imageStoredName).toFile()); } catch (IOException e) { throw new RuntimeException(e); } } - public Resource loadImage(String userDirectoryName,String ImageName) { + public Resource loadImage(String userDirectoryName,String imageName) { try { - Path file = resolveRootPathFullUrlWith(userDirectoryName,ImageName); - Resource resource = new UrlResource(file.toUri()); + var file = createFullPathToTheFile(userDirectoryName,imageName); + var resource = new UrlResource(file.toUri()); if (resource.exists() || resource.isReadable()) { return resource; }else{ @@ -52,30 +54,30 @@ public Resource loadImage(String userDirectoryName,String ImageName) { throw new InvalidPathException(); } } - public void deleteImage(String userDirectoryName, String ImageName) { - Path parentDir = resolveRootPathFullUrlWith(userDirectoryName,ImageName); + + public void deleteImage(String userDirectoryName, String imageName) { + var parentDir = createFullPathToTheFile(userDirectoryName,imageName); try { Files.deleteIfExists(parentDir); } catch (IOException e) { e.printStackTrace(); - throw new RuntimeException("Not capable to delete the directory.\n"+e); + throw new RuntimeException("Unable to delete the directory.\n"+e); } } - private void createDirectoryIfNotExist(String userDirectoryPath){ Path parentDir = Paths.get(rootDir,userDirectoryPath); if (!Files.exists(parentDir)) { try { Files.createDirectories(parentDir); } catch (IOException e) { - throw new RuntimeException("Not capable to create the directory.\n"+e); + throw new RuntimeException("Unable to create the directory.\n"+e); } } } - private Path resolveRootPathFullUrlWith(String userDirectoryName, String filename) { + + private Path createFullPathToTheFile(String userDirectoryName, String filename) { return Paths.get(rootDir).resolve(userDirectoryName).resolve(filename); } -} - +} From e282e7283b904b7b8b702a4622700f1bce460521 Mon Sep 17 00:00:00 2001 From: germano Date: Sat, 27 Apr 2019 16:04:50 -0300 Subject: [PATCH 35/54] Regex: added "start of line" --- mugshot/src/main/java/hive/mugshot/storage/ImageUtils.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/mugshot/src/main/java/hive/mugshot/storage/ImageUtils.java b/mugshot/src/main/java/hive/mugshot/storage/ImageUtils.java index 15d7f57..0e4a7ce 100644 --- a/mugshot/src/main/java/hive/mugshot/storage/ImageUtils.java +++ b/mugshot/src/main/java/hive/mugshot/storage/ImageUtils.java @@ -6,7 +6,7 @@ import java.util.regex.Pattern; public final class ImageUtils { - private static final String IMAGE_PATTERN = "(.+\\.(gif|png|bmp|jpeg|jpg)$)"; + private static final String IMAGE_PATTERN = "(^.+\\.(gif|png|bmp|jpeg|jpg)$)"; private ImageUtils(){ } public static boolean validateIfHasAnImageAsExtension(final String image){ From 5da3af022a52e2ea35e6305544e38dad16046d88 Mon Sep 17 00:00:00 2001 From: germano Date: Sat, 27 Apr 2019 16:05:45 -0300 Subject: [PATCH 36/54] Regex: added "start of line" --- mugshot/src/main/java/hive/mugshot/storage/ImageUtils.java | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/mugshot/src/main/java/hive/mugshot/storage/ImageUtils.java b/mugshot/src/main/java/hive/mugshot/storage/ImageUtils.java index 0e4a7ce..16ffabf 100644 --- a/mugshot/src/main/java/hive/mugshot/storage/ImageUtils.java +++ b/mugshot/src/main/java/hive/mugshot/storage/ImageUtils.java @@ -7,8 +7,10 @@ public final class ImageUtils { private static final String IMAGE_PATTERN = "(^.+\\.(gif|png|bmp|jpeg|jpg)$)"; + private ImageUtils(){ } + public static boolean validateIfHasAnImageAsExtension(final String image){ var pattern = Pattern.compile(IMAGE_PATTERN); var matcher = pattern.matcher(image); @@ -28,6 +30,7 @@ public static BufferedImage resizeImageToSquare(BufferedImage inputtedImage,int reSizer.dispose(); return bufferedImageWithNewSize; } + public static BufferedImage generateRandomImage(){ var yellow=0xF6BD60; var orange=0xE9724C; @@ -58,5 +61,5 @@ public static BufferedImage generateRandomImage(){ } return img; } -} +} From 8185cf141af6af1c8cb52ddaf06319acdd3d3ce3 Mon Sep 17 00:00:00 2001 From: germano Date: Sat, 27 Apr 2019 16:07:30 -0300 Subject: [PATCH 37/54] Added spacing between methods --- .../hive/mugshot/controller/MugshotController.java | 12 +++++++++--- 1 file changed, 9 insertions(+), 3 deletions(-) diff --git a/mugshot/src/main/java/hive/mugshot/controller/MugshotController.java b/mugshot/src/main/java/hive/mugshot/controller/MugshotController.java index 135e625..d5c9aa7 100644 --- a/mugshot/src/main/java/hive/mugshot/controller/MugshotController.java +++ b/mugshot/src/main/java/hive/mugshot/controller/MugshotController.java @@ -19,10 +19,12 @@ @RestController @RequestMapping("/") public class MugshotController { + @Value("${hive.mugshot.profile-image-name}") private String imageName; private final ImageStorer imageStorer; private final UserRepository userRepository; + @Autowired public MugshotController(ImageStorer imageStorer,UserRepository userRepository) { this.userRepository = userRepository; this.imageStorer = imageStorer; @@ -32,7 +34,8 @@ public class MugshotController { @PostMapping public void sendImageProfile( @RequestParam("image") MultipartFile insertedImage, - @RequestHeader(name = HiveHeaders.AUTHENTICATED_USER_NAME_HEADER) final String username) { + @RequestHeader(name = HiveHeaders.AUTHENTICATED_USER_NAME_HEADER) final String username + ){ if(!validateIfHasAnImageAsExtension(insertedImage.getOriginalFilename())) { throw new NotAcceptedFileFormatException(); } @@ -42,7 +45,8 @@ public void sendImageProfile( @GetMapping(produces = MediaType.IMAGE_JPEG_VALUE) public ResponseEntity searchProfileImage( - @RequestHeader(name = HiveHeaders.AUTHENTICATED_USER_NAME_HEADER) final String username) { + @RequestHeader(name = HiveHeaders.AUTHENTICATED_USER_NAME_HEADER) final String username + ){ var userID=userRepository.findByUsername(username).getId().toString(); Resource file = imageStorer.loadImage(userID,imageName); return ResponseEntity.ok().header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + file.getFilename() + "\"").body(file); @@ -51,8 +55,10 @@ public ResponseEntity searchProfileImage( @ResponseStatus(code = HttpStatus.NO_CONTENT, reason = "Profile image successfully deleted") @DeleteMapping public void deleteProfileImage( - @RequestHeader(name = HiveHeaders.AUTHENTICATED_USER_NAME_HEADER) final String username) { + @RequestHeader(name = HiveHeaders.AUTHENTICATED_USER_NAME_HEADER) final String username + ){ var userID=userRepository.findByUsername(username).getId().toString(); imageStorer.deleteImage(userID,imageName); } + } From 6a4d6173a043873655a622b780f90a7fb5c89813 Mon Sep 17 00:00:00 2001 From: germano Date: Sat, 27 Apr 2019 16:08:46 -0300 Subject: [PATCH 38/54] EOL at EOF --- mugshot/src/main/resources/application.properties | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/mugshot/src/main/resources/application.properties b/mugshot/src/main/resources/application.properties index cd594d9..3499442 100644 --- a/mugshot/src/main/resources/application.properties +++ b/mugshot/src/main/resources/application.properties @@ -18,4 +18,4 @@ logging.level.org.hibernate.type=trace hive.mugshot.image-directory-path=./mugshot_images_profiles hive.mugshot.profile-image-name=ProfileImage.jpg hive.mugshot.profile-image-dimension=256 -spring.http.multipart.max-file-size=1MB \ No newline at end of file +spring.http.multipart.max-file-size=1MB From f5d9d1340bedd48110013dd4a3f7cbc927c0c7db Mon Sep 17 00:00:00 2001 From: germano Date: Sat, 27 Apr 2019 16:17:10 -0300 Subject: [PATCH 39/54] Comments removed --- .../hive/mugshot/controller/MugshotControllerTest.java | 7 ++----- 1 file changed, 2 insertions(+), 5 deletions(-) diff --git a/mugshot/src/test/java/hive/mugshot/controller/MugshotControllerTest.java b/mugshot/src/test/java/hive/mugshot/controller/MugshotControllerTest.java index 3a6095c..f4498d6 100644 --- a/mugshot/src/test/java/hive/mugshot/controller/MugshotControllerTest.java +++ b/mugshot/src/test/java/hive/mugshot/controller/MugshotControllerTest.java @@ -74,7 +74,6 @@ public void setup() { validDirectoryName = (rootDir + "/" + user.getId() + "/"); } - //SUCCESS: @Test public void givenValidImage_WhenImageRetrieved_then200andJpegImageTypeIsReturned() throws Exception{ createDirectoryForTest(validDirectoryName); @@ -85,8 +84,7 @@ public void givenValidImage_WhenImageRetrieved_then200andJpegImageTypeIsReturned get("/mugshot") .header("authenticated-user-name", username)) .andExpect(status().isOk()) - .andExpect(content().contentType(MediaType.IMAGE_JPEG)) - .andDo(print()); + .andExpect(content().contentType(MediaType.IMAGE_JPEG)); } @Test @@ -105,7 +103,6 @@ public void givenValidImage_WhenImageDeleted_then204isReturned() throws Exceptio ).andExpect(status().isNoContent()); } - //ERRORS: @Test public void givenFileNotFound_WhenImageRetrieved_then404isReturned() throws Exception{ given(imageStorer.loadImage(userId.toString(),imageName)).willThrow(new ImageNotFound()); @@ -131,7 +128,7 @@ public void givenUnsupportedMediaType_WhenImageUploaded_then415isReturned()throw } @Test - public void givenWrongBodyRequestKey_WhenImageUploaded_then400isReturned() throws Exception{ + public void givenWrongRequestBodyKey_WhenImageUploaded_then400isReturned() throws Exception{ byte[] EmptyFile = new byte[0]; multipartFile = new MockMultipartFile("wrongBodyKey", "ProfileImage.jpeg", MediaType.IMAGE_JPEG_VALUE, EmptyFile); mockMvc.perform(multipart("/mugshot") From 54bc1309613350dc0d635572eb076e5a8a825041 Mon Sep 17 00:00:00 2001 From: germano Date: Sat, 27 Apr 2019 16:19:36 -0300 Subject: [PATCH 40/54] Alteration on the url for tests --- .../mugshot/controller/MugshotControllerTest.java | 15 ++++++++------- 1 file changed, 8 insertions(+), 7 deletions(-) diff --git a/mugshot/src/test/java/hive/mugshot/controller/MugshotControllerTest.java b/mugshot/src/test/java/hive/mugshot/controller/MugshotControllerTest.java index f4498d6..5f8bb54 100644 --- a/mugshot/src/test/java/hive/mugshot/controller/MugshotControllerTest.java +++ b/mugshot/src/test/java/hive/mugshot/controller/MugshotControllerTest.java @@ -81,17 +81,18 @@ public void givenValidImage_WhenImageRetrieved_then200andJpegImageTypeIsReturned given(imageStorer.loadImage(userId.toString(),imageName)) .willReturn(resourceImage); mockMvc.perform( - get("/mugshot") + get("/") .header("authenticated-user-name", username)) .andExpect(status().isOk()) - .andExpect(content().contentType(MediaType.IMAGE_JPEG)); + .andExpect(content().contentType(MediaType.IMAGE_JPEG)) + .andDo(print()); } @Test public void givenValidImage_WhenImageUploaded_then200isReturned() throws Exception{ multipartFile = new MockMultipartFile("image", "Profile Image.jpg", MediaType.IMAGE_JPEG_VALUE, "Spring Framework".getBytes()); mockMvc.perform( - multipart("/mugshot").file(multipartFile).header("authenticated-user-name",username)) + multipart("/").file(multipartFile).header("authenticated-user-name",username)) .andExpect(status().isOk()) .andDo(print()); } @@ -99,7 +100,7 @@ public void givenValidImage_WhenImageUploaded_then200isReturned() throws Excepti @Test public void givenValidImage_WhenImageDeleted_then204isReturned() throws Exception{ mockMvc.perform( - delete("/mugshot").header("authenticated-user-name",username) + delete("/").header("authenticated-user-name",username) ).andExpect(status().isNoContent()); } @@ -108,7 +109,7 @@ public void givenFileNotFound_WhenImageRetrieved_then404isReturned() throws Exce given(imageStorer.loadImage(userId.toString(),imageName)).willThrow(new ImageNotFound()); createDirectoryForTest(validDirectoryName); mockMvc.perform( - get("/mugshot") + get("/") .header("authenticated-user-name", username)) .andExpect(status().isNotFound()) .andDo(print()); @@ -120,7 +121,7 @@ public void givenUnsupportedMediaType_WhenImageUploaded_then415isReturned()throw ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); ImageIO.write(originalImage, "jpg", byteArrayOutputStream); multipartFile = new MockMultipartFile("image", "Unsupported.Extension.wmv", MediaType.APPLICATION_PDF_VALUE, byteArrayOutputStream.toByteArray()); - mockMvc.perform(multipart("/mugshot") + mockMvc.perform(multipart("/") .file(multipartFile) .header("authenticated-user-name", username)) .andExpect(status().isUnsupportedMediaType()) @@ -131,7 +132,7 @@ public void givenUnsupportedMediaType_WhenImageUploaded_then415isReturned()throw public void givenWrongRequestBodyKey_WhenImageUploaded_then400isReturned() throws Exception{ byte[] EmptyFile = new byte[0]; multipartFile = new MockMultipartFile("wrongBodyKey", "ProfileImage.jpeg", MediaType.IMAGE_JPEG_VALUE, EmptyFile); - mockMvc.perform(multipart("/mugshot") + mockMvc.perform(multipart("/") .file(multipartFile).header("authenticated-user-name", username)) .andExpect(status().isBadRequest()) .andDo(print()); From 52bbb2cb0277ebd391006a7e09ff4cd297fe0314 Mon Sep 17 00:00:00 2001 From: germano Date: Sat, 27 Apr 2019 16:21:56 -0300 Subject: [PATCH 41/54] Deleted the "hey" test --- .../hive/mugshot/controller/UtilsControllerTest.java | 9 +-------- 1 file changed, 1 insertion(+), 8 deletions(-) diff --git a/mugshot/src/test/java/hive/mugshot/controller/UtilsControllerTest.java b/mugshot/src/test/java/hive/mugshot/controller/UtilsControllerTest.java index deeb3a5..9fcd265 100644 --- a/mugshot/src/test/java/hive/mugshot/controller/UtilsControllerTest.java +++ b/mugshot/src/test/java/hive/mugshot/controller/UtilsControllerTest.java @@ -49,14 +49,6 @@ public void setup() { mockMvc = MockMvcBuilders.standaloneSetup(utilsController).build(); } - @Test - public void givenRequestWithOkResponseAsDefault_whenVerifyIfTheServeIsOk_then200isReturned() throws Exception{ - mockMvc - .perform( - get("/utils/hey") - ) - .andExpect(status().isOk()); - } @Test public void givenUserName_whenRequestGeneratedImage_then200isReturned() throws Exception{ mockMvc @@ -67,4 +59,5 @@ public void givenUserName_whenRequestGeneratedImage_then200isReturned() throws E .andExpect(status().isOk()) .andDo(print()); } + } From f5a435322f0de9ec3bd5ac8a97029e5d9abda542 Mon Sep 17 00:00:00 2001 From: germano Date: Sat, 27 Apr 2019 16:26:00 -0300 Subject: [PATCH 42/54] Import static for asserts --- .../hive/mugshot/storage/ImageStorerTest.java | 16 +++++++++------- 1 file changed, 9 insertions(+), 7 deletions(-) diff --git a/mugshot/src/test/java/hive/mugshot/storage/ImageStorerTest.java b/mugshot/src/test/java/hive/mugshot/storage/ImageStorerTest.java index e1f17f0..ba9d0be 100644 --- a/mugshot/src/test/java/hive/mugshot/storage/ImageStorerTest.java +++ b/mugshot/src/test/java/hive/mugshot/storage/ImageStorerTest.java @@ -17,6 +17,8 @@ import java.nio.file.Paths; import java.util.concurrent.ThreadLocalRandom; +import static org.junit.Assert.*; + @RunWith(SpringRunner.class) @SpringBootTest public class ImageStorerTest { @@ -47,24 +49,24 @@ public void setUp() throws IOException { } @Test - public void uploadImage_WhenImageNameAndUserDirectoryIsNotNull_expectExistenceOfFile(){ + public void uploadImage_WhenImageNameAndUserDirectoryIsNotNull_expectFileExists(){ imageStorer.storeImageProfile(userId.toString(),multipartFile,imageName); Path path=Paths.get(rootDir,userId.toString(),imageName); - Assert.assertTrue(Files.exists(path)); + assertTrue(Files.exists(path)); } @Test - public void deleteImage_WhenImageNameAndUserDirectoryIsNotNull_expectNoExistenceOfFile(){ + public void deleteImage_WhenImageNameAndUserDirectoryIsNotNull_expectFileDoesNotExists(){ imageStorer.deleteImage(userId.toString(),imageName); Path path=Paths.get(rootDir,userId.toString(),imageName); - Assert.assertFalse(Files.exists(path)); + assertFalse(Files.exists(path)); } @Test public void loadImage_WhenMultipartIsNotNull_expectConfiguredImageName() throws IOException { imageStorer.storeImageProfile(userId.toString(),multipartFile,imageName); var resource=imageStorer.loadImage(userId.toString(),imageName); - Assert.assertEquals(imageName,resource.getFile().getName()); + assertEquals(imageName,resource.getFile().getName()); } @Test @@ -72,8 +74,8 @@ public void loadImage_WhenMultipartIsNotNull_expectConfiguredImageSize() throws imageStorer.storeImageProfile(userId.toString(),multipartFile,imageName); var resource=imageStorer.loadImage(userId.toString(),imageName); var image=ImageIO.read(resource.getFile()); - Assert.assertEquals(imageSizeInPixels,image.getHeight()); - Assert.assertEquals(imageSizeInPixels,image.getWidth()); + assertEquals(imageSizeInPixels,image.getHeight()); + assertEquals(imageSizeInPixels,image.getWidth()); } @After From e2b96eecfeaa9114bc92e959909fc5e8942de275 Mon Sep 17 00:00:00 2001 From: germano Date: Sat, 27 Apr 2019 16:27:32 -0300 Subject: [PATCH 43/54] Deleted test user, method "hey" and "searchSomeImage" --- .../java/hive/mugshot/controller/UtilsController.java | 11 ----------- 1 file changed, 11 deletions(-) diff --git a/mugshot/src/main/java/hive/mugshot/controller/UtilsController.java b/mugshot/src/main/java/hive/mugshot/controller/UtilsController.java index bdb88e1..5889e35 100644 --- a/mugshot/src/main/java/hive/mugshot/controller/UtilsController.java +++ b/mugshot/src/main/java/hive/mugshot/controller/UtilsController.java @@ -22,21 +22,10 @@ public class UtilsController { @Value("${hive.mugshot.profile-image-name}") private String imageName; - - @ResponseStatus(code = HttpStatus.OK, reason = "The server is working") - @GetMapping("/hey") public void hey(){} @Autowired public UtilsController(ImageStorer imageStorer,UserRepository userRepository){ this.userRepository=userRepository; this.imageStorer=imageStorer; - userRepository.save(new User("Test_User","123",0,0)); - } - - @GetMapping(value = "searchImage/{profileImageName:.+}", produces = MediaType.IMAGE_JPEG_VALUE) - public ResponseEntity searchSomeImage(@RequestHeader(name = HiveHeaders.AUTHENTICATED_USER_NAME_HEADER) final String username, @PathVariable String profileImageName) { - var userID=userRepository.findByUsername(username).getId().toString(); - Resource file = imageStorer.loadImage(username,profileImageName); - return ResponseEntity.ok().header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + file.getFilename() + "\"").body(file); } @ResponseStatus(code = HttpStatus.OK, reason = "Random image generated and successfully stored") From 882455ceb190e40b0f7cd218cbbcc4364a3abe4e Mon Sep 17 00:00:00 2001 From: germano Date: Sat, 27 Apr 2019 16:27:53 -0300 Subject: [PATCH 44/54] added "mugshot" --- settings.gradle | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/settings.gradle b/settings.gradle index 9b67a0a..3005eb6 100644 --- a/settings.gradle +++ b/settings.gradle @@ -5,5 +5,6 @@ include 'common' include 'gateway' include 'naming-server' include 'entity' -include 'album' - +include 'kirby' +include 'pokedex' +include 'mugshot' From 74e5befb780de82bf1e7d900191e3664c96e16b4 Mon Sep 17 00:00:00 2001 From: germano Date: Sat, 27 Apr 2019 22:58:06 -0300 Subject: [PATCH 45/54] Solved bug of pull request --- .../album/controller/UtilsController.java | 50 ------------------- 1 file changed, 50 deletions(-) delete mode 100644 mugshot/src/main/java/hive/album/controller/UtilsController.java diff --git a/mugshot/src/main/java/hive/album/controller/UtilsController.java b/mugshot/src/main/java/hive/album/controller/UtilsController.java deleted file mode 100644 index 31639a0..0000000 --- a/mugshot/src/main/java/hive/album/controller/UtilsController.java +++ /dev/null @@ -1,50 +0,0 @@ -package hive.album.controller; - -import hive.album.repository.UserRepository; -import hive.album.storage.ImageStorer; -import hive.album.storage.ImageUtils; -import hive.common.security.HiveHeaders; -import hive.entity.user.User; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Value; -import org.springframework.core.io.Resource; -import org.springframework.http.HttpHeaders; -import org.springframework.http.HttpStatus; -import org.springframework.http.MediaType; -import org.springframework.http.ResponseEntity; -import org.springframework.web.bind.annotation.*; - -@RestController -@RequestMapping("/utils") -public class UtilsController { - private final UserRepository userRepository; - private final ImageStorer imageStorer; - @Value("${hive.album.profile-image-name}") - private String imageName; - - - @ResponseStatus(code = HttpStatus.OK, reason = "The server is working") - @GetMapping("/hey") public void hey(){} - @Autowired - public UtilsController(ImageStorer imageStorer,UserRepository userRepository){ - this.userRepository=userRepository; - this.imageStorer=imageStorer; - userRepository.save(new User("Test_User","123",0,0)); - } - - @GetMapping(value = "searchImage/{profileImageName:.+}", produces = MediaType.IMAGE_JPEG_VALUE) - public ResponseEntity searchSomeImage(@RequestHeader(name = HiveHeaders.AUTHENTICATED_USER_NAME_HEADER) final String username, @PathVariable String profileImageName) { - var userID=userRepository.findByUsername(username).getId().toString(); - Resource file = imageStorer.loadImage(username,profileImageName); - return ResponseEntity.ok().header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + file.getFilename() + "\"").body(file); - } - - @ResponseStatus(code = HttpStatus.OK, reason = "Random image generated and successfully stored") - @PostMapping("/generateRandomImage") - public void generateRandomImage(@RequestHeader(name = HiveHeaders.AUTHENTICATED_USER_NAME_HEADER) final String username) { - var generatedImage=ImageUtils.generateRandomImage(); - var userID=userRepository.findByUsername(username).getId(); - imageStorer.storeImageProfile(userID.toString(),generatedImage,imageName); - } - -} From 3930583af5c64d0793d7af9965c20812e82cd70c Mon Sep 17 00:00:00 2001 From: germano Date: Sat, 27 Apr 2019 23:17:19 -0300 Subject: [PATCH 46/54] Changed path to database file --- mugshot/src/main/resources/application.properties | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/mugshot/src/main/resources/application.properties b/mugshot/src/main/resources/application.properties index 3499442..1b0e93c 100644 --- a/mugshot/src/main/resources/application.properties +++ b/mugshot/src/main/resources/application.properties @@ -5,7 +5,7 @@ eureka.client.service-url.default-zone=http://localhost:8761/eureka spring.h2.console.enabled=false spring.h2.console.path=/h2 # Datasource -spring.datasource.url=jdbc:h2:file:./db/auth;AUTO_SERVER=TRUE +spring.datasource.url=jdbc:h2:file:../db/h2db;AUTO_SERVER=TRUE spring.datasource.username=sa spring.datasource.password= spring.datasource.driver-class-name=org.h2.Driver From 81cb2eb93a11556333c6411d0ffc806bf3bfda76 Mon Sep 17 00:00:00 2001 From: germano Date: Sat, 27 Apr 2019 23:19:06 -0300 Subject: [PATCH 47/54] changed @autowired position --- .../main/java/hive/mugshot/controller/MugshotController.java | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/mugshot/src/main/java/hive/mugshot/controller/MugshotController.java b/mugshot/src/main/java/hive/mugshot/controller/MugshotController.java index d5c9aa7..dba110f 100644 --- a/mugshot/src/main/java/hive/mugshot/controller/MugshotController.java +++ b/mugshot/src/main/java/hive/mugshot/controller/MugshotController.java @@ -25,7 +25,8 @@ public class MugshotController { private final ImageStorer imageStorer; private final UserRepository userRepository; - @Autowired public MugshotController(ImageStorer imageStorer,UserRepository userRepository) { + @Autowired + public MugshotController(ImageStorer imageStorer,UserRepository userRepository) { this.userRepository = userRepository; this.imageStorer = imageStorer; } From 11d2a1a95c531d4635ea05e12dbf0658e9b2d5a4 Mon Sep 17 00:00:00 2001 From: germano Date: Sat, 27 Apr 2019 23:19:45 -0300 Subject: [PATCH 48/54] EOL at EOF --- .../main/java/hive/mugshot/exception/InvalidPathException.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/mugshot/src/main/java/hive/mugshot/exception/InvalidPathException.java b/mugshot/src/main/java/hive/mugshot/exception/InvalidPathException.java index 1a199ad..47a2a5e 100644 --- a/mugshot/src/main/java/hive/mugshot/exception/InvalidPathException.java +++ b/mugshot/src/main/java/hive/mugshot/exception/InvalidPathException.java @@ -5,4 +5,4 @@ @ResponseStatus(code = HttpStatus.BAD_REQUEST, reason = "Invalid path") public class InvalidPathException extends RuntimeException { -} \ No newline at end of file +} From 348a9b4aa5721a23c71291d0ce403ad34fa1d4ae Mon Sep 17 00:00:00 2001 From: germano Date: Sat, 27 Apr 2019 23:47:40 -0300 Subject: [PATCH 49/54] Increased test coverage --- .../java/hive/mugshot/storage/ImageStorerTest.java | 13 +++++++++++-- 1 file changed, 11 insertions(+), 2 deletions(-) diff --git a/mugshot/src/test/java/hive/mugshot/storage/ImageStorerTest.java b/mugshot/src/test/java/hive/mugshot/storage/ImageStorerTest.java index ba9d0be..5a986f5 100644 --- a/mugshot/src/test/java/hive/mugshot/storage/ImageStorerTest.java +++ b/mugshot/src/test/java/hive/mugshot/storage/ImageStorerTest.java @@ -22,8 +22,10 @@ @RunWith(SpringRunner.class) @SpringBootTest public class ImageStorerTest { + private Integer userId; private MockMultipartFile multipartFile; + private BufferedImage initialImage; @Autowired private ImageStorer imageStorer; @Value("${hive.mugshot.image-directory-path}") @@ -37,7 +39,7 @@ public class ImageStorerTest { @Before public void setUp() throws IOException { userId= ThreadLocalRandom.current().nextInt(Integer.MAX_VALUE); - var initialImage=new BufferedImage(512,512,BufferedImage.TYPE_INT_RGB); + initialImage=new BufferedImage(512,512,BufferedImage.TYPE_INT_RGB); var byteArrayOutputStream = new ByteArrayOutputStream(); ImageIO.write(initialImage,"jpg",byteArrayOutputStream); multipartFile=new MockMultipartFile( @@ -49,12 +51,19 @@ public void setUp() throws IOException { } @Test - public void uploadImage_WhenImageNameAndUserDirectoryIsNotNull_expectFileExists(){ + public void uploadImage_WhenMultipartFileIsProvided_expectFileExists(){ imageStorer.storeImageProfile(userId.toString(),multipartFile,imageName); Path path=Paths.get(rootDir,userId.toString(),imageName); assertTrue(Files.exists(path)); } + @Test + public void uploadImage_WhenBufferedImageIsProvided_expectFileExists(){ + imageStorer.storeImageProfile(userId.toString(),initialImage,imageName); + Path path=Paths.get(rootDir,userId.toString(),imageName); + assertTrue(Files.exists(path)); + } + @Test public void deleteImage_WhenImageNameAndUserDirectoryIsNotNull_expectFileDoesNotExists(){ imageStorer.deleteImage(userId.toString(),imageName); From 42e01a1a0fe33011c8276ab6b0a0749ce1e6bb6a Mon Sep 17 00:00:00 2001 From: germano Date: Sun, 28 Apr 2019 00:16:51 -0300 Subject: [PATCH 50/54] Added spaces --- .../java/hive/mugshot/controller/MugshotControllerTest.java | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/mugshot/src/test/java/hive/mugshot/controller/MugshotControllerTest.java b/mugshot/src/test/java/hive/mugshot/controller/MugshotControllerTest.java index 5f8bb54..9110b9b 100644 --- a/mugshot/src/test/java/hive/mugshot/controller/MugshotControllerTest.java +++ b/mugshot/src/test/java/hive/mugshot/controller/MugshotControllerTest.java @@ -38,14 +38,16 @@ public class MugshotControllerTest { private MockMvc mockMvc; + private MockMultipartFile multipartFile; private String validDirectoryName; private String username = RandomStringUtils.randomAlphabetic(8); private Integer userId = ThreadLocalRandom.current().nextInt(Integer.MAX_VALUE); - private MockMultipartFile multipartFile; + @Value("${hive.mugshot.image-directory-path}") private String rootDir; @Value("${hive.mugshot.profile-image-name}") private String imageName; + @Mock private UserRepository userRepository; @Mock From f7618cfa15fbd4223a87881492bf053a330be5e1 Mon Sep 17 00:00:00 2001 From: germano Date: Sun, 28 Apr 2019 00:21:41 -0300 Subject: [PATCH 51/54] Added spaces --- .../java/hive/mugshot/controller/MugshotControllerTest.java | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/mugshot/src/test/java/hive/mugshot/controller/MugshotControllerTest.java b/mugshot/src/test/java/hive/mugshot/controller/MugshotControllerTest.java index 9110b9b..1103503 100644 --- a/mugshot/src/test/java/hive/mugshot/controller/MugshotControllerTest.java +++ b/mugshot/src/test/java/hive/mugshot/controller/MugshotControllerTest.java @@ -37,12 +37,13 @@ @SpringBootTest public class MugshotControllerTest { - private MockMvc mockMvc; - private MockMultipartFile multipartFile; private String validDirectoryName; private String username = RandomStringUtils.randomAlphabetic(8); private Integer userId = ThreadLocalRandom.current().nextInt(Integer.MAX_VALUE); + private MockMvc mockMvc; + private MockMultipartFile multipartFile; + @Value("${hive.mugshot.image-directory-path}") private String rootDir; @Value("${hive.mugshot.profile-image-name}") From f149ed04d2730ce5ea74a7e55c64623ed2928710 Mon Sep 17 00:00:00 2001 From: germano Date: Sun, 28 Apr 2019 00:22:12 -0300 Subject: [PATCH 52/54] Added spaces --- .../java/hive/mugshot/controller/UtilsControllerTest.java | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/mugshot/src/test/java/hive/mugshot/controller/UtilsControllerTest.java b/mugshot/src/test/java/hive/mugshot/controller/UtilsControllerTest.java index 9fcd265..8f5a273 100644 --- a/mugshot/src/test/java/hive/mugshot/controller/UtilsControllerTest.java +++ b/mugshot/src/test/java/hive/mugshot/controller/UtilsControllerTest.java @@ -27,11 +27,14 @@ @SpringBootTest public class UtilsControllerTest { - private MockMvc mockMvc; private String username = RandomStringUtils.randomAlphabetic(8); private Integer userId = ThreadLocalRandom.current().nextInt(Integer.MAX_VALUE); + + private MockMvc mockMvc; + @Value("${hive.mugshot.profile-image-name}") private String imageName; + @Mock private UserRepository userRepository; @Mock From 871fc9d6849c5a8c81ccc41e61563a8fa92733c8 Mon Sep 17 00:00:00 2001 From: germano Date: Sun, 28 Apr 2019 00:22:50 -0300 Subject: [PATCH 53/54] Added spaces --- .../test/java/hive/mugshot/storage/ImageStorerTest.java | 1 + .../test/java/hive/mugshot/storage/ImageUtilsTest.java | 8 ++++++-- 2 files changed, 7 insertions(+), 2 deletions(-) diff --git a/mugshot/src/test/java/hive/mugshot/storage/ImageStorerTest.java b/mugshot/src/test/java/hive/mugshot/storage/ImageStorerTest.java index 5a986f5..b152672 100644 --- a/mugshot/src/test/java/hive/mugshot/storage/ImageStorerTest.java +++ b/mugshot/src/test/java/hive/mugshot/storage/ImageStorerTest.java @@ -26,6 +26,7 @@ public class ImageStorerTest { private Integer userId; private MockMultipartFile multipartFile; private BufferedImage initialImage; + @Autowired private ImageStorer imageStorer; @Value("${hive.mugshot.image-directory-path}") diff --git a/mugshot/src/test/java/hive/mugshot/storage/ImageUtilsTest.java b/mugshot/src/test/java/hive/mugshot/storage/ImageUtilsTest.java index 4abd3bb..2b070cb 100644 --- a/mugshot/src/test/java/hive/mugshot/storage/ImageUtilsTest.java +++ b/mugshot/src/test/java/hive/mugshot/storage/ImageUtilsTest.java @@ -12,16 +12,20 @@ @RunWith(SpringRunner.class) @SpringBootTest public class ImageUtilsTest { + @Value("${hive.mugshot.profile-image-dimension}") private int imageSizeInPixels; + @Test public void validateIfHasAnImageAsExtension_whenParameterDoesNotMatchPattern_expectFalseValue(){ Assert.assertFalse(ImageUtils.validateIfHasAnImageAsExtension("a.zip")); } + @Test public void validateIfHasAnImageAsExtension_whenParameterMatchPattern_expectTrueValue(){ Assert.assertTrue(ImageUtils.validateIfHasAnImageAsExtension("a.gif")); } + @Test public void resizeImageToSquare_whenInitialImageIsNotNull_expectSquareImageInConfiguredSize(){ var initialImage=new BufferedImage(10,50,BufferedImage.TYPE_INT_RGB); @@ -29,6 +33,7 @@ public void resizeImageToSquare_whenInitialImageIsNotNull_expectSquareImageInCon Assert.assertEquals(imageSizeInPixels,resizedImage.getWidth()); Assert.assertEquals(imageSizeInPixels,resizedImage.getHeight()); } + @Test public void whenGenerateRandomImageAndResizeToSquare_expectSquareImageInConfiguredSize(){ var generatedImage=ImageUtils.generateRandomImage(); @@ -36,6 +41,5 @@ public void whenGenerateRandomImageAndResizeToSquare_expectSquareImageInConfigur Assert.assertEquals(imageSizeInPixels,imageResized.getWidth()); Assert.assertEquals(imageSizeInPixels,imageResized.getHeight()); } -} - +} From d511affce0776dc1608e1a4ed63f6af7df6561c9 Mon Sep 17 00:00:00 2001 From: Francisco Cidade Date: Thu, 2 May 2019 18:58:08 -0300 Subject: [PATCH 54/54] =?UTF-8?q?prepara=C3=A7=C3=A3o=20do=20ambiente=20pa?= =?UTF-8?q?ra=20o=20novo=20reposit=C3=B3rio?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../0/ProfileImage.jpg | Bin 0 -> 4723 bytes .../mugshot/controller/MugshotController.java | 20 ++++------- .../mugshot/controller/UtilsController.java | 16 +++------ .../controller/MugshotControllerTest.java | 31 +++++++----------- .../controller/UtilsControllerTest.java | 7 ++-- 5 files changed, 25 insertions(+), 49 deletions(-) create mode 100644 mugshot/mugshot_images_profiles/0/ProfileImage.jpg diff --git a/mugshot/mugshot_images_profiles/0/ProfileImage.jpg b/mugshot/mugshot_images_profiles/0/ProfileImage.jpg new file mode 100644 index 0000000000000000000000000000000000000000..ccc1e8b8a1ae76b0654aad20893a1c2ab24b533d GIT binary patch literal 4723 zcmex=^(PF6}rMnOeST|r4lSw=>~TvNxu(8R<c1}I=;VrF4wW9Q)H;sz?% zD!{d!pzFb!U9xX3zTPI5o8roG<0MW4oqZMDikqloVbuf*=gfJ(V&YTRE(2~ znmD<{#3dx9RMpfqG__1j&CD$omas|0V!1q#bGi literal 0 HcmV?d00001 diff --git a/mugshot/src/main/java/hive/mugshot/controller/MugshotController.java b/mugshot/src/main/java/hive/mugshot/controller/MugshotController.java index dba110f..1d4e6f3 100644 --- a/mugshot/src/main/java/hive/mugshot/controller/MugshotController.java +++ b/mugshot/src/main/java/hive/mugshot/controller/MugshotController.java @@ -1,7 +1,6 @@ package hive.mugshot.controller; import hive.mugshot.exception.NotAcceptedFileFormatException; -import hive.mugshot.repository.UserRepository; import hive.mugshot.storage.ImageStorer; import hive.common.security.HiveHeaders; import org.springframework.beans.factory.annotation.Autowired; @@ -23,11 +22,9 @@ public class MugshotController { @Value("${hive.mugshot.profile-image-name}") private String imageName; private final ImageStorer imageStorer; - private final UserRepository userRepository; @Autowired - public MugshotController(ImageStorer imageStorer,UserRepository userRepository) { - this.userRepository = userRepository; + public MugshotController(ImageStorer imageStorer) { this.imageStorer = imageStorer; } @@ -35,31 +32,28 @@ public MugshotController(ImageStorer imageStorer,UserRepository userRepository) @PostMapping public void sendImageProfile( @RequestParam("image") MultipartFile insertedImage, - @RequestHeader(name = HiveHeaders.AUTHENTICATED_USER_NAME_HEADER) final String username + @RequestHeader(name = HiveHeaders.AUTHENTICATED_USER_ID) final String userId ){ if(!validateIfHasAnImageAsExtension(insertedImage.getOriginalFilename())) { throw new NotAcceptedFileFormatException(); } - var userID=userRepository.findByUsername(username).getId().toString(); - imageStorer.storeImageProfile(userID,insertedImage,imageName); + imageStorer.storeImageProfile(userId,insertedImage,imageName); } @GetMapping(produces = MediaType.IMAGE_JPEG_VALUE) public ResponseEntity searchProfileImage( - @RequestHeader(name = HiveHeaders.AUTHENTICATED_USER_NAME_HEADER) final String username + @RequestHeader(name = HiveHeaders.AUTHENTICATED_USER_ID) final String userId ){ - var userID=userRepository.findByUsername(username).getId().toString(); - Resource file = imageStorer.loadImage(userID,imageName); + Resource file = imageStorer.loadImage(userId,imageName); return ResponseEntity.ok().header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + file.getFilename() + "\"").body(file); } @ResponseStatus(code = HttpStatus.NO_CONTENT, reason = "Profile image successfully deleted") @DeleteMapping public void deleteProfileImage( - @RequestHeader(name = HiveHeaders.AUTHENTICATED_USER_NAME_HEADER) final String username + @RequestHeader(name = HiveHeaders.AUTHENTICATED_USER_ID) final String userId ){ - var userID=userRepository.findByUsername(username).getId().toString(); - imageStorer.deleteImage(userID,imageName); + imageStorer.deleteImage(userId,imageName); } } diff --git a/mugshot/src/main/java/hive/mugshot/controller/UtilsController.java b/mugshot/src/main/java/hive/mugshot/controller/UtilsController.java index 5889e35..7069b35 100644 --- a/mugshot/src/main/java/hive/mugshot/controller/UtilsController.java +++ b/mugshot/src/main/java/hive/mugshot/controller/UtilsController.java @@ -1,39 +1,31 @@ package hive.mugshot.controller; -import hive.mugshot.repository.UserRepository; import hive.mugshot.storage.ImageStorer; import hive.mugshot.storage.ImageUtils; import hive.common.security.HiveHeaders; -import hive.entity.user.User; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; -import org.springframework.core.io.Resource; -import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; -import org.springframework.http.MediaType; -import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; @RestController @RequestMapping("/utils") public class UtilsController { - private final UserRepository userRepository; + private final ImageStorer imageStorer; @Value("${hive.mugshot.profile-image-name}") private String imageName; @Autowired - public UtilsController(ImageStorer imageStorer,UserRepository userRepository){ - this.userRepository=userRepository; + public UtilsController(ImageStorer imageStorer){ this.imageStorer=imageStorer; } @ResponseStatus(code = HttpStatus.OK, reason = "Random image generated and successfully stored") @PostMapping("/generateRandomImage") - public void generateRandomImage(@RequestHeader(name = HiveHeaders.AUTHENTICATED_USER_NAME_HEADER) final String username) { + public void generateRandomImage(@RequestHeader(name = HiveHeaders.AUTHENTICATED_USER_ID) final String userId) { var generatedImage=ImageUtils.generateRandomImage(); - var userID=userRepository.findByUsername(username).getId(); - imageStorer.storeImageProfile(userID.toString(),generatedImage,imageName); + imageStorer.storeImageProfile(userId,generatedImage,imageName); } } diff --git a/mugshot/src/test/java/hive/mugshot/controller/MugshotControllerTest.java b/mugshot/src/test/java/hive/mugshot/controller/MugshotControllerTest.java index 1103503..85ca955 100644 --- a/mugshot/src/test/java/hive/mugshot/controller/MugshotControllerTest.java +++ b/mugshot/src/test/java/hive/mugshot/controller/MugshotControllerTest.java @@ -1,7 +1,6 @@ package hive.mugshot.controller; import hive.mugshot.exception.ImageNotFound; -import hive.mugshot.repository.UserRepository; import hive.mugshot.storage.ImageStorer; import hive.entity.user.User; @@ -25,12 +24,11 @@ import java.nio.file.*; import javax.imageio.ImageIO; import java.awt.image.BufferedImage; -import java.util.concurrent.ThreadLocalRandom; +import static hive.common.security.HiveHeaders.AUTHENTICATED_USER_ID; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*; import static org.mockito.BDDMockito.given; -import static org.mockito.Mockito.when; import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print; @RunWith(SpringRunner.class) @@ -38,8 +36,7 @@ public class MugshotControllerTest { private String validDirectoryName; - private String username = RandomStringUtils.randomAlphabetic(8); - private Integer userId = ThreadLocalRandom.current().nextInt(Integer.MAX_VALUE); + private String userId = RandomStringUtils.randomAlphabetic(8); private MockMvc mockMvc; private MockMultipartFile multipartFile; @@ -49,8 +46,6 @@ public class MugshotControllerTest { @Value("${hive.mugshot.profile-image-name}") private String imageName; - @Mock - private UserRepository userRepository; @Mock private ImageStorer imageStorer; @Mock @@ -69,9 +64,7 @@ private void createDirectoryForTest(String directoryName) throws Exception{ @Before public void setup() { MockitoAnnotations.initMocks(this); - when(user.getId()).thenReturn(userId); - when(userRepository.findByUsername(username)).thenReturn(user); - var mugshotController = new MugshotController(imageStorer,userRepository); + var mugshotController = new MugshotController(imageStorer); ReflectionTestUtils.setField(mugshotController, "imageName", imageName); mockMvc = MockMvcBuilders.standaloneSetup(mugshotController).build(); validDirectoryName = (rootDir + "/" + user.getId() + "/"); @@ -81,11 +74,11 @@ public void setup() { public void givenValidImage_WhenImageRetrieved_then200andJpegImageTypeIsReturned() throws Exception{ createDirectoryForTest(validDirectoryName); var resourceImage=createImageForTest(validDirectoryName); - given(imageStorer.loadImage(userId.toString(),imageName)) + given(imageStorer.loadImage(userId,imageName)) .willReturn(resourceImage); mockMvc.perform( get("/") - .header("authenticated-user-name", username)) + .header(AUTHENTICATED_USER_ID, userId)) .andExpect(status().isOk()) .andExpect(content().contentType(MediaType.IMAGE_JPEG)) .andDo(print()); @@ -95,7 +88,7 @@ public void givenValidImage_WhenImageRetrieved_then200andJpegImageTypeIsReturned public void givenValidImage_WhenImageUploaded_then200isReturned() throws Exception{ multipartFile = new MockMultipartFile("image", "Profile Image.jpg", MediaType.IMAGE_JPEG_VALUE, "Spring Framework".getBytes()); mockMvc.perform( - multipart("/").file(multipartFile).header("authenticated-user-name",username)) + multipart("/").file(multipartFile).header(AUTHENTICATED_USER_ID, userId)) .andExpect(status().isOk()) .andDo(print()); } @@ -103,17 +96,17 @@ public void givenValidImage_WhenImageUploaded_then200isReturned() throws Excepti @Test public void givenValidImage_WhenImageDeleted_then204isReturned() throws Exception{ mockMvc.perform( - delete("/").header("authenticated-user-name",username) + delete("/").header(AUTHENTICATED_USER_ID, userId) ).andExpect(status().isNoContent()); } @Test public void givenFileNotFound_WhenImageRetrieved_then404isReturned() throws Exception{ - given(imageStorer.loadImage(userId.toString(),imageName)).willThrow(new ImageNotFound()); + given(imageStorer.loadImage(userId,imageName)).willThrow(new ImageNotFound()); createDirectoryForTest(validDirectoryName); mockMvc.perform( get("/") - .header("authenticated-user-name", username)) + .header(AUTHENTICATED_USER_ID, userId)) .andExpect(status().isNotFound()) .andDo(print()); } @@ -126,7 +119,7 @@ public void givenUnsupportedMediaType_WhenImageUploaded_then415isReturned()throw multipartFile = new MockMultipartFile("image", "Unsupported.Extension.wmv", MediaType.APPLICATION_PDF_VALUE, byteArrayOutputStream.toByteArray()); mockMvc.perform(multipart("/") .file(multipartFile) - .header("authenticated-user-name", username)) + .header(AUTHENTICATED_USER_ID, userId)) .andExpect(status().isUnsupportedMediaType()) .andDo(print()); } @@ -136,14 +129,14 @@ public void givenWrongRequestBodyKey_WhenImageUploaded_then400isReturned() throw byte[] EmptyFile = new byte[0]; multipartFile = new MockMultipartFile("wrongBodyKey", "ProfileImage.jpeg", MediaType.IMAGE_JPEG_VALUE, EmptyFile); mockMvc.perform(multipart("/") - .file(multipartFile).header("authenticated-user-name", username)) + .file(multipartFile).header(AUTHENTICATED_USER_ID, userId)) .andExpect(status().isBadRequest()) .andDo(print()); } @After public void deleteCreatedDirectory() throws IOException { - Path createdDirectoryPath=Paths.get(rootDir,userId.toString()); + Path createdDirectoryPath=Paths.get(rootDir,userId); Path createdImagePath=createdDirectoryPath.resolve(imageName); Files.deleteIfExists(createdImagePath); Files.deleteIfExists(createdDirectoryPath); diff --git a/mugshot/src/test/java/hive/mugshot/controller/UtilsControllerTest.java b/mugshot/src/test/java/hive/mugshot/controller/UtilsControllerTest.java index 8f5a273..8e48668 100644 --- a/mugshot/src/test/java/hive/mugshot/controller/UtilsControllerTest.java +++ b/mugshot/src/test/java/hive/mugshot/controller/UtilsControllerTest.java @@ -35,8 +35,6 @@ public class UtilsControllerTest { @Value("${hive.mugshot.profile-image-name}") private String imageName; - @Mock - private UserRepository userRepository; @Mock private ImageStorer imageStorer; @Mock @@ -46,8 +44,7 @@ public class UtilsControllerTest { public void setup() { MockitoAnnotations.initMocks(this); when(user.getId()).thenReturn(userId); - when(userRepository.findByUsername(username)).thenReturn(user); - var utilsController = new UtilsController(imageStorer,userRepository); + var utilsController = new UtilsController(imageStorer); ReflectionTestUtils.setField(utilsController, "imageName", imageName); mockMvc = MockMvcBuilders.standaloneSetup(utilsController).build(); } @@ -57,7 +54,7 @@ public void givenUserName_whenRequestGeneratedImage_then200isReturned() throws E mockMvc .perform( post("/utils/generateRandomImage") - .header(HiveHeaders.AUTHENTICATED_USER_NAME_HEADER, username) + .header(HiveHeaders.AUTHENTICATED_USER_ID, username) ) .andExpect(status().isOk()) .andDo(print());