Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ public ResponseEntity<Resource> getFile(@PathVariable String fileKey,
throw new ResponseStatusException(HttpStatus.NOT_FOUND);
}

InputStream inputStream = minioService.getFile(fileKey);
InputStream inputStream = documentService.downloadFile(fileKey);
MediaType mediaType = document.getContentType() != null
? MediaType.parseMediaType(document.getContentType())
: MediaType.APPLICATION_OCTET_STREAM;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,4 +14,6 @@ public interface DocumentRepository extends JpaRepository<Document, Long> {
List<Document> findByIncidentId(Long incidentId);

Optional<Document> findByFileKey(String fileKey);

void deleteByFileKey(String fileKey);
}
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,11 @@
import org.example.team6backend.document.entity.Document;
import org.example.team6backend.document.repository.DocumentRepository;
import org.example.team6backend.incident.entity.Incident;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.server.ResponseStatusException;

import java.io.InputStream;
import java.util.List;
Expand Down Expand Up @@ -54,8 +56,28 @@ public Document uploadFile(MultipartFile file, Incident incident) {
}

/** Download file */
@Transactional
public InputStream downloadFile(String objectKey) {
return minioService.downloadFile(objectKey);
try {
return minioService.downloadFile(objectKey);
} catch (MinioService.FileMissingException e) {
log.warn("Missing file in Minio: {}", objectKey, e);

var docOpt = documentRepository.findByFileKey(objectKey);

if (docOpt.isPresent()) {
log.warn("FOUND document in DB → deleting: {}", objectKey);
documentRepository.delete(docOpt.get());
} else {
log.warn("NO document found in DB for: {}", objectKey);
}

throw new ResponseStatusException(HttpStatus.NOT_FOUND, "File not found");

} catch (Exception e) {
log.error("Failed to download file from Minio: {}", objectKey, e);
throw new ResponseStatusException(HttpStatus.INTERNAL_SERVER_ERROR, "Failed to download file");
}
Comment thread
SandraNelj marked this conversation as resolved.
}

/** Delete file */
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package org.example.team6backend.document.service;

import io.minio.*;
import io.minio.errors.ErrorResponseException;
import jakarta.annotation.PostConstruct;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Value;
Expand Down Expand Up @@ -47,8 +48,13 @@ public void uploadFile(String fileKey, MultipartFile file) {
public InputStream downloadFile(String fileKey) {
try {
return minioClient.getObject(GetObjectArgs.builder().bucket(bucketName).object(fileKey).build());
} catch (ErrorResponseException e) {
if ("NoSuchKey".equals(e.errorResponse().code())) {
throw new FileMissingException("File not found: " + fileKey, e);
}
throw new RuntimeException("Failed to download file: " + fileKey, e);
} catch (Exception e) {
throw new RuntimeException("Failed to download file " + fileKey, e);
throw new RuntimeException("Failed to download file: " + fileKey, e);
}
}

Expand All @@ -68,4 +74,9 @@ public InputStream getFile(String fileKey) {
throw new ResponseStatusException(HttpStatus.NOT_FOUND, "File not found: " + fileKey);
}
}
public class FileMissingException extends RuntimeException {
public FileMissingException(String message, Throwable cause) {
super(message, cause);
}
}
}
6 changes: 5 additions & 1 deletion src/main/resources/static/viewincident.html
Original file line number Diff line number Diff line change
Expand Up @@ -89,7 +89,11 @@ <h2>Incident details</h2>
docsHtml = `<div style="margin-top:10px; display:flex; gap:12px; flex-wrap:wrap;">` + i.documents.map(doc => {
const url = `/documents/${encodeURIComponent(doc.fileKey)}`;
return /\.(jpg|jpeg|png|gif|webp)$/i.test(doc.fileName)
? `<a href="${url}" target="_blank"><img src="${url}" style="width:80px;height:80px;object-fit:cover;border-radius:8px;border:1px solid #2a2a2a;"></a>`
? `<a href="${url}" target="_blank">
<img src="${url}"
onerror="this.parentElement.remove()"
style="width:80px;height:80px;object-fit:cover;border-radius:8px;border:1px solid #2a2a2a;">
</a>`
: `<a href="${url}" target="_blank" class="btn">📄 ${escapeHtml(doc.fileName)}</a>`;
}).join('') + `</div>`;
}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,38 +1,31 @@
package org.example.team6backend.document.controller;

import org.example.team6backend.document.entity.Document;
import org.example.team6backend.document.service.DocumentService;
import org.example.team6backend.document.service.MinioService;
import org.example.team6backend.incident.entity.Incident;
import org.example.team6backend.incident.service.IncidentService;
import org.example.team6backend.security.CustomOAuth2UserService;
import org.example.team6backend.security.CustomUserDetails;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.ImportAutoConfiguration;
import org.springframework.boot.security.oauth2.client.autoconfigure.OAuth2ClientAutoConfiguration;
import org.springframework.boot.security.oauth2.client.autoconfigure.servlet.OAuth2ClientWebSecurityAutoConfiguration;
import org.springframework.boot.webmvc.test.autoconfigure.AutoConfigureMockMvc;
import org.springframework.boot.webmvc.test.autoconfigure.WebMvcTest;
import org.springframework.http.HttpHeaders;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.test.context.bean.override.mockito.MockitoBean;
import org.springframework.test.web.servlet.MockMvc;

import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.authentication;
import java.io.ByteArrayInputStream;
import java.util.Map;
import java.util.Optional;

import static org.mockito.ArgumentMatchers.*;
import static org.mockito.Mockito.when;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;

import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.example.team6backend.user.entity.AppUser;
import org.example.team6backend.user.entity.UserRole;

@WebMvcTest(value = DocumentController.class, excludeAutoConfiguration = {OAuth2ClientAutoConfiguration.class,
OAuth2ClientWebSecurityAutoConfiguration.class})
Expand All @@ -56,25 +49,6 @@ public class DocumentControllerTest {
@MockitoBean
private CustomOAuth2UserService customOAuth2UserService;

private AppUser testUser;

@BeforeEach
void setupSecurity() {
testUser = new AppUser();
testUser.setId("test-user-id");
testUser.setName("Test User");
testUser.setEmail("test@test.com");
testUser.setRole(UserRole.ADMIN);
testUser.setActive(true);

CustomUserDetails principal = new CustomUserDetails(testUser, Map.of());

UsernamePasswordAuthenticationToken auth = new UsernamePasswordAuthenticationToken(principal, null,
principal.getAuthorities());

SecurityContextHolder.getContext().setAuthentication(auth);
}

@Test
void getFile_shouldReturnDocument() throws Exception {
Incident incident = new Incident();
Expand All @@ -86,12 +60,19 @@ void getFile_shouldReturnDocument() throws Exception {
document.setFileKey("abc");
document.setIncident(incident);

AppUser appUser = new AppUser();
appUser.setName("Test User");
appUser.setEmail("test@test.com");

CustomUserDetails principal = new CustomUserDetails(appUser, Map.of());
UsernamePasswordAuthenticationToken auth = new UsernamePasswordAuthenticationToken(principal, "password",
principal.getAuthorities());

when(documentService.getByFileKey("abc")).thenReturn(Optional.of(document));
when(incidentService.getById(eq(1L), any())).thenReturn(incident);
when(minioService.getFile("abc")).thenReturn(new ByteArrayInputStream("hello".getBytes()));
when(documentService.downloadFile("abc")).thenReturn(new ByteArrayInputStream("hello".getBytes()));

mockMvc.perform(get("/documents/abc")).andExpect(status().isOk())
.andExpect(header().string(HttpHeaders.CONTENT_DISPOSITION, "inline; filename=\"test.pdf\""));
mockMvc.perform(get("/documents/abc").with(authentication(auth))).andExpect(status().isOk());
}

@Test
Expand Down
Loading