Merge branch 'ExceptionBesoin1' into 'main'

Exception besoin1

See merge request pdl-l3/teams/2023/v1/v1d!11
This commit is contained in:
Theophyl Hoguet committed 2023-03-13 23:13:47 +01:00
commit 3d076e21d3
5 files changed
+179 -168

No files matched your search

@@ -28,68 +28,68 @@ import org.springframework.web.servlet.mvc.support.RedirectAttributes;
@RestController @RestController
public class ImageController { public class ImageController {
@Autowired @Autowired
private ObjectMapper mapper; private ObjectMapper mapper;
private final ImageDao imageDao; private final ImageDao imageDao;
public ImageController(ImageDao imageDao) { public ImageController(ImageDao imageDao) {
this.imageDao = imageDao; this.imageDao = imageDao;
} }
@GetMapping(value = "/images/{id}", produces = MediaType.IMAGE_JPEG_VALUE) @GetMapping(value = "/images/{id}", produces = MediaType.IMAGE_JPEG_VALUE)
public ResponseEntity<?> getImage(@PathVariable("id") long id) { public ResponseEntity<?> getImage(@PathVariable("id") long id) {
Optional<Image> image = imageDao.retrieve(id); Optional<Image> image = imageDao.retrieve(id);
if (image.isPresent()) { if (image.isPresent()) {
InputStream inputStream = new ByteArrayInputStream(image.get().getData()); InputStream inputStream = new ByteArrayInputStream(image.get().getData());
return ResponseEntity.ok().contentType(MediaType.IMAGE_JPEG).body(new InputStreamResource(inputStream)); return ResponseEntity.ok().contentType(MediaType.IMAGE_JPEG).body(new InputStreamResource(inputStream));
} }
return new ResponseEntity<>("Image id=" + id + " not found.", HttpStatus.NOT_FOUND); return new ResponseEntity<>("Image id=" + id + " not found.", HttpStatus.NOT_FOUND);
} }
@DeleteMapping(value = "/images/{id}") @DeleteMapping(value = "/images/{id}")
public ResponseEntity<?> deleteImage(@PathVariable("id") long id) { public ResponseEntity<?> deleteImage(@PathVariable("id") long id) {
Optional<Image> image = imageDao.retrieve(id); Optional<Image> image = imageDao.retrieve(id);
if (image.isPresent()) { if (image.isPresent()) {
imageDao.delete(image.get()); imageDao.delete(image.get());
return new ResponseEntity<>("Image id=" + id + " deleted.", HttpStatus.OK); return new ResponseEntity<>("Image id=" + id + " deleted.", HttpStatus.OK);
} }
return new ResponseEntity<>("Image id=" + id + " not found.", HttpStatus.NOT_FOUND); return new ResponseEntity<>("Image id=" + id + " not found.", HttpStatus.NOT_FOUND);
} }
@PostMapping(value = "/images") @PostMapping(value = "/images")
public ResponseEntity<?> addImage(@RequestParam("file") MultipartFile file, RedirectAttributes redirectAttributes) { public ResponseEntity<?> addImage(@RequestParam("file") MultipartFile file, RedirectAttributes redirectAttributes) {
String contentType = file.getContentType(); String contentType = file.getContentType();
if (contentType != null && !contentType.equals(MediaType.IMAGE_JPEG.toString())) { if (contentType != null && !contentType.equals(MediaType.IMAGE_JPEG.toString())) {
return new ResponseEntity<>("Only JPEG file format supported", HttpStatus.UNSUPPORTED_MEDIA_TYPE); return new ResponseEntity<>("Only JPEG file format supported", HttpStatus.UNSUPPORTED_MEDIA_TYPE);
} }
try { try {
imageDao.create(new Image(file.getOriginalFilename(), file.getBytes())); imageDao.create(new Image(file.getOriginalFilename(), file.getBytes()));
} catch (IOException e) { } catch (IOException e) {
return new ResponseEntity<>("Failure to read file", HttpStatus.NO_CONTENT); return new ResponseEntity<>("Failure to read file", HttpStatus.NO_CONTENT);
} }
return new ResponseEntity<>("Image uploaded", HttpStatus.CREATED); return new ResponseEntity<>("Image uploaded", HttpStatus.CREATED);
} }
@GetMapping(value = "/images", produces = "application/json") @GetMapping(value = "/images", produces = "application/json")
@ResponseBody @ResponseBody
public ArrayNode getImageList() { public ArrayNode getImageList() {
List<Image> images = imageDao.retrieveAll(); List<Image> images = imageDao.retrieveAll();
ArrayNode nodes = mapper.createArrayNode(); ArrayNode nodes = mapper.createArrayNode();
for (Image image : images) { for (Image image : images) {
ObjectNode objectNode = mapper.createObjectNode(); ObjectNode objectNode = mapper.createObjectNode();
objectNode.put("id", image.getId()); objectNode.put("id", image.getId());
objectNode.put("name", image.getName()); objectNode.put("name", image.getName());
objectNode.put("size", image.getSize()); objectNode.put("size", image.getSize());
objectNode.put("type", image.getMediaType().toString()); objectNode.put("type", image.getMediaType().toString());
nodes.add(objectNode); nodes.add(objectNode);
} }
return nodes; return nodes;
} }
} }
+57 -55
View File
@@ -16,68 +16,70 @@ import org.springframework.stereotype.Repository;
@Repository @Repository
public class ImageDao implements Dao<Image> { public class ImageDao implements Dao<Image> {
private final Map<Long, Image> images = new HashMap<>(); private final Map<Long, Image> images = new HashMap<>();
public ImageDao() { public ImageDao() {
try { try {
final var folderPath = new ClassPathResource("images"); final var folderPath = new ClassPathResource("images");
final var folder = folderPath.getFile(); if (!folderPath.exists())
getAllImages(folder); throw new ImageResourceMissingException("folder images doesn't not exsit");
} catch (final Exception e) { final var folder = folderPath.getFile();
e.printStackTrace(); getAllImages(folder);
} } catch (final Exception e) {
} e.printStackTrace();
}
}
public void getAllImages(final File folder) { public void getAllImages(final File folder) {
for (final File file : folder.listFiles()) { for (final File file : folder.listFiles()) {
if (file.isDirectory()) { if (file.isDirectory()) {
getAllImages(file); getAllImages(file);
} else { } else {
String extension = ""; String extension = "";
int i = file.getName().lastIndexOf('.'); int i = file.getName().lastIndexOf('.');
if (i > 0) { if (i > 0) {
extension = file.getName().substring(i + 1); extension = file.getName().substring(i + 1);
} }
if (!extension.equals("jpg") && !extension.equals("png")) { if (!extension.equals("jpg") && !extension.equals("png")) {
continue; continue;
} }
byte[] fileContent; byte[] fileContent;
try { try {
fileContent = Files.readAllBytes(file.toPath()); fileContent = Files.readAllBytes(file.toPath());
Image img = new Image(file.getName(), fileContent); Image img = new Image(file.getName(), fileContent);
images.put(img.getId(), img); images.put(img.getId(), img);
} catch (final IOException e) { } catch (final IOException e) {
e.printStackTrace(); e.printStackTrace();
} }
} }
} }
} }
@Override @Override
public Optional<Image> retrieve(final long id) { public Optional<Image> retrieve(final long id) {
return Optional.ofNullable(images.get(id)); return Optional.ofNullable(images.get(id));
} }
@Override @Override
public List<Image> retrieveAll() { public List<Image> retrieveAll() {
return new ArrayList<Image>(images.values()); return new ArrayList<Image>(images.values());
} }
@Override @Override
public void create(final Image img) { public void create(final Image img) {
images.put(img.getId(), img); images.put(img.getId(), img);
} }
@Override @Override
public void update(final Image img, final String[] params) { public void update(final Image img, final String[] params) {
img.setName(Objects.requireNonNull(params[0], "Name cannot be null")); img.setName(Objects.requireNonNull(params[0], "Name cannot be null"));
images.put(img.getId(), img); images.put(img.getId(), img);
} }
@Override @Override
public void delete(final Image img) { public void delete(final Image img) {
images.remove(img.getId()); images.remove(img.getId());
} }
} }
@@ -0,0 +1,9 @@
package pdl.backend;
import java.io.FileNotFoundException;
public class ImageResourceMissingException extends FileNotFoundException {
public ImageResourceMissingException(String message) {
super(message);
}
}
@@ -7,13 +7,13 @@ import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest @SpringBootTest
class BackendApplicationTests { class BackendApplicationTests {
@Test @Test
void contextLoads() { void contextLoads() {
} }
@Test @Test
@Order(1) @Order(1)
public void appLaunchShouldReturnError() throws Exception { public void appLaunchShouldReturnError() throws Exception {
} }
} }
@@ -26,68 +26,68 @@ import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
@TestMethodOrder(OrderAnnotation.class) @TestMethodOrder(OrderAnnotation.class)
public class ImageControllerTests { public class ImageControllerTests {
@Autowired @Autowired
private MockMvc mockMvc; private MockMvc mockMvc;
@BeforeAll @BeforeAll
public static void reset() { public static void reset() {
// reset Image class static counter // reset Image class static counter
ReflectionTestUtils.setField(Image.class, "count", Long.valueOf(0)); ReflectionTestUtils.setField(Image.class, "count", Long.valueOf(0));
} }
@Test @Test
@Order(1) @Order(1)
public void getImageListShouldReturnSuccess() throws Exception { public void getImageListShouldReturnSuccess() throws Exception {
this.mockMvc.perform(get("/images")).andDo(print()).andExpect(status().isOk()) this.mockMvc.perform(get("/images")).andDo(print()).andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON)); .andExpect(content().contentType(MediaType.APPLICATION_JSON));
} }
@Test @Test
@Order(2) @Order(2)
public void getImageShouldReturnNotFound() throws Exception { public void getImageShouldReturnNotFound() throws Exception {
this.mockMvc.perform(get("/images/1000")).andDo(print()).andExpect(status().isNotFound()); this.mockMvc.perform(get("/images/1000")).andDo(print()).andExpect(status().isNotFound());
} }
@Test @Test
@Order(3) @Order(3)
public void getImageShouldReturnSuccess() throws Exception { public void getImageShouldReturnSuccess() throws Exception {
this.mockMvc.perform(get("/images/0")).andExpect(status().isOk()); this.mockMvc.perform(get("/images/0")).andExpect(status().isOk());
} }
@Test @Test
@Order(4) @Order(4)
public void deleteImagesShouldReturnMethodNotAllowed() throws Exception { public void deleteImagesShouldReturnMethodNotAllowed() throws Exception {
this.mockMvc.perform(delete("/images")).andDo(print()).andExpect(status().isMethodNotAllowed()); this.mockMvc.perform(delete("/images")).andDo(print()).andExpect(status().isMethodNotAllowed());
} }
@Test @Test
@Order(5) @Order(5)
public void deleteImageShouldReturnNotFound() throws Exception { public void deleteImageShouldReturnNotFound() throws Exception {
this.mockMvc.perform(delete("/images/1000")).andDo(print()).andExpect(status().isNotFound()); this.mockMvc.perform(delete("/images/1000")).andDo(print()).andExpect(status().isNotFound());
} }
@Test @Test
@Order(6) @Order(6)
public void deleteImageShouldReturnSuccess() throws Exception { public void deleteImageShouldReturnSuccess() throws Exception {
this.mockMvc.perform(delete("/images/0")).andDo(print()).andExpect(status().isOk()); this.mockMvc.perform(delete("/images/0")).andDo(print()).andExpect(status().isOk());
} }
@Test @Test
@Order(7) @Order(7)
public void createImageShouldReturnSuccess() throws Exception { public void createImageShouldReturnSuccess() throws Exception {
final ClassPathResource imgFile = new ClassPathResource("images/test.jpg"); final ClassPathResource imgFile = new ClassPathResource("images/test.jpg");
MockMultipartFile multipartFile = new MockMultipartFile("file", "test.jpg", "image/jpeg", MockMultipartFile multipartFile = new MockMultipartFile("file", "test.jpg", "image/jpeg",
imgFile.getInputStream()); imgFile.getInputStream());
this.mockMvc.perform(MockMvcRequestBuilders.multipart("/images").file(multipartFile)).andDo(print()) this.mockMvc.perform(MockMvcRequestBuilders.multipart("/images").file(multipartFile)).andDo(print())
.andExpect(status().isCreated()); .andExpect(status().isCreated());
} }
@Test @Test
@Order(8) @Order(8)
public void createImageShouldReturnUnsupportedMediaType() throws Exception { public void createImageShouldReturnUnsupportedMediaType() throws Exception {
MockMultipartFile multipartFile = new MockMultipartFile("file", "test.jpg", "text/plain", "Test".getBytes()); MockMultipartFile multipartFile = new MockMultipartFile("file", "test.jpg", "text/plain", "Test".getBytes());
this.mockMvc.perform(MockMvcRequestBuilders.multipart("/images").file(multipartFile)).andDo(print()) this.mockMvc.perform(MockMvcRequestBuilders.multipart("/images").file(multipartFile)).andDo(print())
.andExpect(status().isUnsupportedMediaType()); .andExpect(status().isUnsupportedMediaType());
} }
} }