Commit 1179c8c3 authored by Enriko Käsper's avatar Enriko Käsper
Browse files

Merge branch 'develop' into 'master'

Release: merge 'develop' into 'master' created by Enriko Käsper

See merge request teis/common-api-gateway!153
parents 92c7b2f6 babd1c34
package ee.sm.ti.teis.commongateway.security.mock;
import ee.sm.ti.teis.commongateway.CommonApiGatewayTestBase;
import ee.sm.ti.teis.commongateway.auth.UserCompanySelectionDto;
import ee.sm.ti.teis.gatewaycommon.error.NoResponseFromRabbitException;
import ee.sm.ti.teis.servicerequest.RequestMetaDTO;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.client.ResourceAccessException;
import static java.util.UUID.randomUUID;
import static org.junit.jupiter.api.Assertions.assertThrows;
public class AuthMockControllerTest extends CommonApiGatewayTestBase {
@Autowired
AuthMockController controller;
MockUserLoginRequest mockUser;
@BeforeEach
void setUp() {
mockUser = MockUserLoginRequest.builder()
.idCode("48806060014")
.countryCode("EE")
.build();
}
@Test
void authenticate_throwsResourceAccessException() {
assertThrows(ResourceAccessException.class, () ->
controller.authenticate(mockUser, new RequestMetaDTO()));
}
@Test
void authenticateOfficeUser_throwsResourceAccessException() {
assertThrows(ResourceAccessException.class, () ->
controller.authenticate(mockUser, new RequestMetaDTO()));
}
@Test
void getSelectedCompany_throwsNoResponseFromRabbitException() {
RequestMetaDTO requestMetaDTO = new RequestMetaDTO();
requestMetaDTO.setUserId(randomUUID().toString());
assertThrows(NoResponseFromRabbitException.class, () ->
controller.getSelectedCompany(requestMetaDTO, new UserCompanySelectionDto(), ""));
}
}
package ee.sm.ti.teis.commongateway.tasks.task;
import ee.sm.ti.teis.commongateway.CommonApiGatewayTestBase;
import ee.sm.ti.teis.commongateway.tasks.task.dto.PatchTaskDto;
import ee.sm.ti.teis.commongateway.tasks.task.dto.TaskDto;
import ee.sm.ti.teis.commongateway.tasks.task.dto.TaskRequestParamDto;
import ee.sm.ti.teis.gatewaycommon.error.NoResponseFromRabbitException;
......@@ -27,10 +26,4 @@ public class TaskTestControllerTest extends CommonApiGatewayTestBase {
assertThrows(NoResponseFromRabbitException.class, () ->
controller.delete(new TaskRequestParamDto(), new RequestMetaDTO()));
}
@Test
void patch() {
assertThrows(NoResponseFromRabbitException.class, () ->
controller.patchTask(new PatchTaskDto(), new RequestMetaDTO()));
}
}
spring:
main:
allow-bean-definition-overriding: true
datasource:
driver-class-name: org.testcontainers.jdbc.ContainerDatabaseDriver
url: jdbc:tc:postgresql://localhost:5432/teis
username: teis
password: seis
liquibase:
user: teis
password: seis
change-log: classpath:/db/changelog/db.changelog-integtest.xml
contexts: integtest
rabbitmq:
template:
reply-timeout: 500 # Timeout for `sendAndReceive()` operations.
......@@ -19,11 +9,8 @@ minio:
access-key: teis
secret-key: zvFOY,u8KJrM;0dK/TcVbn
bucket: teis
camunda:
bpm:
admin-user:
id: kermit
password: superSecret
teis:
mockauth:
token-secret: m4evcu4QkUq5v8f9JQs4mq8uRgbsBdDHKKcWs97gpf5hUrXWyQCbENgRE2zFR3P5VY9M6ddkY6Wmjspek6TrG7FP2ySaWZh633w
auth-user-info-api:
url: http://localhost:9009/api-auth
<?xml version="1.0" encoding="UTF-8"?>
<databaseChangeLog xmlns="http://www.liquibase.org/xml/ns/dbchangelog" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.liquibase.org/xml/ns/dbchangelog http://www.liquibase.org/xml/ns/dbchangelog/dbchangelog-3.1.xsd">
<include file="integtest-setup.sql" relativeToChangelogFile="true" />
<include file="classpath:db/changelog/db.changelog-master.xml" />
</databaseChangeLog>
--liquibase formatted sql
--changeset raigo:integtest_setup
CREATE USER teis;
CREATE SCHEMA cache;
CREATE SCHEMA camunda;
......@@ -2,21 +2,20 @@ package ee.sm.ti.teis;
import ee.sm.ti.teis.configuration.ExchangeConfig;
import ee.sm.ti.teis.configuration.QueueConfigurator;
import ee.sm.ti.teis.servicecommon.config.DataSourceConfig;
import ee.sm.ti.teis.servicecommon.config.PropertyLogger;
import org.camunda.bpm.spring.boot.starter.annotation.EnableProcessApplication;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Import;
import org.springframework.scheduling.annotation.EnableScheduling;
@SpringBootApplication
@EnableProcessApplication
@SpringBootApplication(exclude = {DataSourceAutoConfiguration.class})
@Import({PropertyLogger.class,
ExchangeConfig.class,
QueueConfigurator.class,
DataSourceConfig.class})
QueueConfigurator.class})
@EnableConfigurationProperties
@EnableScheduling
public class CommonApiGateway {
public static void main(String[] args) {
SpringApplication.run(CommonApiGateway.class, args);
......
......@@ -12,14 +12,13 @@ import io.swagger.annotations.ApiResponses;
import lombok.RequiredArgsConstructor;
import org.springframework.context.annotation.Profile;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;
import java.util.List;
import java.util.UUID;
@Profile({"dev", "test", "local", "integtest"})
@RestController
@RequestMapping("/admin")
@RequestMapping("admin")
@RequiredArgsConstructor
public class AdminForTestingController extends TeisBaseController {
......@@ -27,10 +26,10 @@ public class AdminForTestingController extends TeisBaseController {
private final MessageProcessingService messageProcessingService;
@ApiOperation(value = "${teis.api.admin.reset-message-email}")
@GetMapping("/reset-message-email/{messageId}")
public String resetMessageEmail(@PathVariable("messageId") UUID messageId, @ApiIgnore RequestMetaDTO requestMetaDTO) {
@GetMapping("reset-message-email/{messageId}")
public UUID resetMessageEmail(@PathVariable UUID messageId, RequestMetaDTO requestMetaDTO) {
ResetMessageEmailRequest request = new ResetMessageEmailRequest();
request.setPayload(new ResetMessageEmailRequest.Parameters(messageId), requestMetaDTO);
request.setPayload(messageId, requestMetaDTO);
return service.resetMessageEmail(request);
}
......@@ -40,9 +39,9 @@ public class AdminForTestingController extends TeisBaseController {
@ApiResponse(code = 400, message = "Sisendi parameetrid ei vasta nõuetele"),
@ApiResponse(code = 403, message = "Kasutajal ei ole õigust andmeobjekti pärida"),
@ApiResponse(code = 404, message = "Sisendis esitatud andmetega objekti ei eksisteeri")})
@PostMapping("/message/{id}/file-references")
@PostMapping("message/{id}/file-references")
public List<FileReferenceDto> createFileReferences(@PathVariable UUID id,
@RequestBody List<MessageFileReferenceDto> dtoList, @ApiIgnore RequestMetaDTO requestMetaDTO) {
@RequestBody List<MessageFileReferenceDto> dtoList, RequestMetaDTO requestMetaDTO) {
CreateMessageFileReferencesRequest request = new CreateMessageFileReferencesRequest();
dtoList.forEach(reference -> reference.setObjectId(id));
request.setPayload(dtoList, requestMetaDTO);
......
......@@ -4,6 +4,8 @@ import ee.sm.ti.teis.gatewaycommon.error.NoResponseFromRabbitException;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.stereotype.Service;
import java.util.UUID;
@Service
public class AdminForTestingProcessingService {
......@@ -13,7 +15,7 @@ public class AdminForTestingProcessingService {
this.gwRabbitTemplate = gwRabbitTemplate;
}
String resetMessageEmail(ResetMessageEmailRequest request) {
UUID resetMessageEmail(ResetMessageEmailRequest request) {
ResetMessageEmailResponse response = (ResetMessageEmailResponse) gwRabbitTemplate.convertSendAndReceive(request.routingKey(), request);
if (response != null) {
return response.processResponse();
......
......@@ -8,7 +8,6 @@ import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import springfox.documentation.annotations.ApiIgnore;
import java.time.LocalDateTime;
......@@ -21,7 +20,7 @@ public class DeadlineController extends TeisBaseController {
@ApiOperation(value = "${teis.api.messages.deadline.get}", response = LocalDateTime.class)
@GetMapping(value = "deadline", produces = MediaType.APPLICATION_JSON_VALUE)
public LocalDateTime getDeadline(GetDeadlineDto getDeadlineDto, @ApiIgnore RequestMetaDTO requestMetaDTO) {
public LocalDateTime getDeadline(GetDeadlineDto getDeadlineDto, RequestMetaDTO requestMetaDTO) {
CalculateDeadlineGwRequest request = new CalculateDeadlineGwRequest();
request.setPayload(getDeadlineDto, requestMetaDTO);
......
......@@ -8,7 +8,7 @@ import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import springfox.documentation.annotations.ApiIgnore;
@RestController
@RequestMapping("feature-flags")
......@@ -19,7 +19,7 @@ public class FeatureFlagController extends TeisBaseController {
@ApiOperation(value = "${teis.api.admin.get-feature-flags}", response = FeatureFlagDto.class)
@GetMapping("{id}")
public FeatureFlagDto getFeatureFlag(@PathVariable("id") String id, @ApiIgnore RequestMetaDTO requestMetaDTO) {
public FeatureFlagDto getFeatureFlag(@PathVariable("id") String id, RequestMetaDTO requestMetaDTO) {
FeatureFlagRequest request = new FeatureFlagRequest();
request.setPayload(id, requestMetaDTO);
......
......@@ -8,7 +8,6 @@ import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import springfox.documentation.annotations.ApiIgnore;
import java.util.Map;
......@@ -21,7 +20,7 @@ public class PathController extends TeisBaseController {
@ApiOperation(value = "${teis.api.path.get}")
@GetMapping(value = "path", produces = MediaType.APPLICATION_JSON_VALUE)
public Map<String,String> getPath(PathDto path, @ApiIgnore RequestMetaDTO requestMetaDTO) {
public Map<String,String> getPath(PathDto path, RequestMetaDTO requestMetaDTO) {
GetPathRequest request = new GetPathRequest();
request.setPayload(path, requestMetaDTO);
return Map.of("path", service.getPath(request));
......
......@@ -7,7 +7,6 @@ import lombok.RequiredArgsConstructor;
import org.springframework.context.annotation.Profile;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;
import java.util.List;
......@@ -21,7 +20,7 @@ public class AuditLogTestController extends TeisBaseController {
@ApiOperation(value = "${teis.api.messages.post-auditlog}", response = AuditLogItemDto.class)
@PostMapping(produces = MediaType.APPLICATION_JSON_VALUE)
public AuditLogItemDto createAuditLogItem(@RequestBody AuditLogItemDto item, @ApiIgnore RequestMetaDTO requestMetaDTO) {
public AuditLogItemDto createAuditLogItem(@RequestBody AuditLogItemDto item, RequestMetaDTO requestMetaDTO) {
CreateAuditLogItemRequest request = new CreateAuditLogItemRequest();
request.setPayload(new CreateAuditLogItemRequest.Parameters(item), requestMetaDTO);
......@@ -38,7 +37,7 @@ public class AuditLogTestController extends TeisBaseController {
public List<AuditLogItemDto> getAuditLogItems(
@RequestParam(name = "parentDataObjectId", required = false) String parentObjectId,
@RequestParam(name = "dataObjectId", required = false) String dataObjectId,
@ApiIgnore RequestMetaDTO requestMetaDTO) {
RequestMetaDTO requestMetaDTO) {
AuditLogItemsRequest request = new AuditLogItemsRequest();
request.setPayload(new AuditLogItemsRequest.Parameters(parentObjectId, dataObjectId), requestMetaDTO);
......
......@@ -11,7 +11,6 @@ import io.swagger.annotations.ApiResponses;
import lombok.RequiredArgsConstructor;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;
import java.util.List;
......@@ -27,7 +26,7 @@ public class ClassifierController extends TeisBaseController {
@ApiResponse(code = 404, message = "Sisendis esitatud andmetega klassifikaatorit ei eksisteeri")
})
@GetMapping(value = "classifier-items", produces = MediaType.APPLICATION_JSON_VALUE)
public List<ClassifierItemDto> getClassifiers(ClassifierItemSearchFilterDto searchFilterDto, @ApiIgnore RequestMetaDTO requestMetaDTO) {
public List<ClassifierItemDto> getClassifiers(ClassifierItemSearchFilterDto searchFilterDto, RequestMetaDTO requestMetaDTO) {
ClassifierItemsRequest request = new ClassifierItemsRequest();
request.setPayload(new ClassifierItemsRequest.Parameters(searchFilterDto), requestMetaDTO);
......@@ -43,7 +42,7 @@ public class ClassifierController extends TeisBaseController {
@PathVariable(name = "id") String id,
@RequestParam(value = "linkedItems", required = false) LinkedItems linkedItems,
@RequestParam(name = "relations", required = false) RelationType relations,
@ApiIgnore RequestMetaDTO requestMetaDTO) {
RequestMetaDTO requestMetaDTO) {
ClassifierItemRequest request = new ClassifierItemRequest();
request.setPayload(new ClassifierItemRequest.Parameters(id, linkedItems, relations), requestMetaDTO);
return classifierProcessingService.getClassifier(request);
......@@ -55,7 +54,7 @@ public class ClassifierController extends TeisBaseController {
})
@GetMapping(value = "classifier-definitions/{definitionId}/default-value", produces = MediaType.APPLICATION_JSON_VALUE)
public ClassifierItemDto getDefinition(
@PathVariable(name = "definitionId") String definitionId, @ApiIgnore RequestMetaDTO requestMetaDTO) {
@PathVariable(name = "definitionId") String definitionId, RequestMetaDTO requestMetaDTO) {
ClassifierDefinitionRequest request = new ClassifierDefinitionRequest();
request.setPayload(new ClassifierDefinitionRequest.Parameters(definitionId), requestMetaDTO);
......
......@@ -43,7 +43,7 @@ public class SecurityConfig extends WebSecurityConfigurerAdapter {
.authorizeRequests()
.antMatchers("/public/**").permitAll()
.antMatchers("/actuator/**").permitAll()
.antMatchers("/v2/api-docs", "/configuration/ui", "/swagger-resources/**", "/configuration/**", "/swagger-ui.html", "/test-role-definitions/**", "/role-definitions/**", "/webjars/**", "/csrf",
.antMatchers("/v2/api-docs", "/configuration/ui", "/swagger-resources/**", "/configuration/**", "/swagger-ui/**", "/swagger-ui.html", "/test-role-definitions/**", "/role-definitions/**", "/webjars/**", "/csrf",
"/").permitAll()
.anyRequest().not().anonymous() // any authenticated user except anonymous
.and()
......
......@@ -9,7 +9,7 @@ import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import springfox.documentation.annotations.ApiIgnore;
@RestController
@RequestMapping("/dumonitor")
......@@ -21,7 +21,7 @@ public class DUMonitorTestController extends TeisBaseController {
@ApiOperation(value = "${teis.api.messages.post-usage-data}", response = String.class)
@PostMapping
public String send(@RequestBody PersonalDataUsageDto usageData, @ApiIgnore RequestMetaDTO requestMetaDTO) {
public String send(@RequestBody PersonalDataUsageDto usageData, RequestMetaDTO requestMetaDTO) {
SendPersonalDataUsageRequest request = new SendPersonalDataUsageRequest();
request.setPayload(new SendPersonalDataUsageRequest.Parameters(usageData), requestMetaDTO);
return processingService.send(request);
......
package ee.sm.ti.teis.commongateway.file;
import com.fasterxml.jackson.databind.ObjectMapper;
import ee.sm.ti.teis.ErrorDTO;
import ee.sm.ti.teis.errors.CommonErrorCode;
import ee.sm.ti.teis.commongateway.classifier.ClassifierItemLightDto;
import ee.sm.ti.teis.exceptions.TeisBusinessException;
import ee.sm.ti.teis.exceptions.TeisResourceNotFoundException;
import ee.sm.ti.teis.exceptions.TeisRestException;
import ee.sm.ti.teis.servicerequest.RequestMetaDTO;
import ee.sm.ti.teis.types.enums.FileParameterType;
import io.minio.MinioClient;
import io.minio.ObjectStat;
import io.minio.errors.ErrorResponseException;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.fileupload.FileItemIterator;
import org.apache.commons.fileupload.FileItemStream;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.fileupload.util.Streams;
import org.apache.tomcat.util.http.fileupload.FileItemIterator;
import org.apache.tomcat.util.http.fileupload.FileItemStream;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.apache.tomcat.util.http.fileupload.servlet.ServletFileUpload;
import org.apache.tomcat.util.http.fileupload.util.Streams;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.util.UUID;
......@@ -30,33 +32,31 @@ import java.util.concurrent.CompletableFuture;
import static ee.sm.ti.teis.errors.CommonErrorCode.BAD_REQUEST;
import static ee.sm.ti.teis.errors.CommonErrorCode.UNSUPPORTED_MEDIA_TYPE;
import static java.util.concurrent.TimeUnit.MILLISECONDS;
import static java.util.stream.Collectors.toList;
import static org.apache.commons.io.FilenameUtils.getExtension;
@Service
@Slf4j
@RequiredArgsConstructor
public class FileContentService {
private static final String CONTEXT_TYPE_FIELD = "contextType";
private static final String THUMBNAIL_SIZE_100 = "100";
private final MinioClient minioClient;
private final FileMetaProcessingService fileMetaProcessingService;
private final FileProcessingService fileProcessingService;
private final ParameterService parameterService;
private final ThumbnailService thumbnailService;
@Value("${teis.file.file-reference.update-timeout}")
private int fileReferenceUpdateTimeout;
@Value("${minio.bucket}")
private String bucketName;
@Value("${minio.bucket-thumbnail}")
private String bucketNameThumbnail;
@Value("${teis.file.upload.allowed-extensions}")
private List<String> allowedExtensions;
public FileReferenceDto updateContext(FileReferenceDto fileReferenceDto, String objectType,
RequestMetaDTO requestMetaDTO) {
return fileProcessingService.updateContext(fileReferenceDto, objectType, requestMetaDTO);
@Value("${teis.file.upload.max-size}")
private Long maxFileUploadSize;
}
public FileReferenceDto saveFileToStorage(HttpServletRequest request, UUID objectId, String objectType,
public FileReferenceDto saveFileToStorage(HttpServletRequest request, UUID objectId, FileObjectType objectType,
RequestMetaDTO requestMetaDTO) throws Exception {
validateCreateBucket();
......@@ -68,14 +68,14 @@ public class FileContentService {
try {
ServletFileUpload upload = new ServletFileUpload();
upload.setSizeMax(maxFileUploadSize);
FileItemIterator iterStream = upload.getItemIterator(request);
setMaxFileSize(objectType, requestMetaDTO, upload);
FileItemIterator iteratorStream = upload.getItemIterator(request);
String fileName = null;
String contentType = null;
boolean fileExists = false;
while (iterStream.hasNext()) {
FileItemStream item = iterStream.next();
while (iteratorStream.hasNext()) {
FileItemStream item = iteratorStream.next();
try (InputStream stream = item.openStream()) {
if (!item.isFormField()) {
if (fileExists) {
......@@ -83,7 +83,7 @@ public class FileContentService {
}
fileName = item.getName();
validateFileExtensionAllowed(fileName);
validateFileExtensionAllowed(fileName, objectType, requestMetaDTO);
contentType = item.getContentType();
......@@ -92,10 +92,15 @@ public class FileContentService {
fileExists = true;
log.info("Saved file to storage with name: {}, contentType: {}", fileName, contentType);
} else {
if (item.getFieldName().equals(CONTEXT_TYPE_FIELD)) {
if (item.getFieldName().equals("data")) {
FileReferenceDto fileReference = getFileReferenceDto(stream);
futureFileReferenceDto = CompletableFuture.supplyAsync(() ->
fileProcessingService.save(fileId, objectId, objectType.name(), fileReference, requestMetaDTO));
} else if (item.getFieldName().equals("contextType")) {
String contextType = Streams.asString(stream);
FileReferenceDto fileReference = FileReferenceDto.builder().contextType(ClassifierItemLightDto.builder().code(contextType).build()).build();
futureFileReferenceDto = CompletableFuture.supplyAsync(() ->
fileProcessingService.save(fileId, objectId, objectType, contextType, requestMetaDTO));
fileProcessingService.save(fileId, objectId, objectType.name(), fileReference, requestMetaDTO));
}
}
}
......@@ -103,7 +108,7 @@ public class FileContentService {
if (futureFileReferenceDto != null) {
fileReferenceDto = futureFileReferenceDto.get(fileReferenceUpdateTimeout, MILLISECONDS);
} else {
fileReferenceDto = saveFileReference(objectId, objectType, requestMetaDTO, fileId);
fileReferenceDto = fileProcessingService.save(fileId, objectId, objectType.name(), new FileReferenceDto(), requestMetaDTO);
}
if (!fileExists) {
......@@ -133,16 +138,18 @@ public class FileContentService {
}
}
private boolean isTeisException(Throwable e) {
return e instanceof TeisBusinessException || e instanceof TeisRestException;
private FileReferenceDto getFileReferenceDto(InputStream stream) throws IOException {
String contextType = Streams.asString(stream);
ObjectMapper objectMapper = new ObjectMapper();
return objectMapper.readValue(contextType, FileReferenceDto.class);
}
private TeisRestException badRequestException(String message) {
return new TeisRestException(ErrorDTO.builder()
.code(BAD_REQUEST.getCode())
.httpResponse(HttpStatus.BAD_REQUEST)
.message(message)
.build());
private void setMaxFileSize(FileObjectType objectType, RequestMetaDTO requestMetaDTO, ServletFileUpload upload) {
if (objectType == FileObjectType.RISK_FACTOR) {
upload.setSizeMax(parameterService.getMaxFileUploadSize(requestMetaDTO, FileParameterType.FILE_UPLOAD_MAX_SIZE_FOR_RISK_FACTOR_IMAGE));
} else {
upload.setSizeMax(parameterService.getMaxFileUploadSize(requestMetaDTO, FileParameterType.FILE_UPLOAD_MAX_SIZE));
}
}
private void validateCreateBucket() throws Exception {
......@@ -153,13 +160,24 @@ public class FileContentService {
}
}
void validateFileExtensionAllowed(String fileName) {
List<String> caseInsensitiveAllowedExtensions = allowedExtensions.stream()
.map(String::toLowerCase)
.collect(toList());
private TeisRestException badRequestException(String message) {
return new TeisRestException(ErrorDTO.builder()
.code(BAD_REQUEST.getCode())
.httpResponse(HttpStatus.BAD_REQUEST)
.message(message)
.build());
}
void validateFileExtensionAllowed(String fileName, FileObjectType objectType, RequestMetaDTO requestMetaDTO) {
List<String> allowedExtensions;
if (objectType == FileObjectType.RISK_FACTOR) {
allowedExtensions = parameterService.getAllowedExtensions(requestMetaDTO, FileParameterType.FILE_UPLOAD_ALLOWED_RISK_FACTOR_IMAGE_EXTENSIONS);
} else {
allowedExtensions = parameterService.getAllowedExtensions(requestMetaDTO, FileParameterType.FILE_UPLOAD_ALLOWED_EXTENSIONS);
}
String extension = getExtension(fileName);
if (!caseInsensitiveAllowedExtensions.contains(extension.toLowerCase())) {
if (!allowedExtensions.contains(extension.toLowerCase())) {
throw new TeisRestException(ErrorDTO.builder()
.code(UNSUPPORTED_MEDIA_TYPE.getCode())
.httpResponse(HttpStatus.UNSUPPORTED_MEDIA_TYPE)
......@@ -168,12 +186,6 @@ public class FileContentService {
}
}
private FileReferenceDto saveFileReference(
UUID objectId, String objectType,
RequestMetaDTO requestMetaDTO, UUID fileId) {
return fileProcessingService.save(fileId, objectId, objectType, null, requestMetaDTO);
}
private FileMetadataDto composeFileMetaData(UUID minioFileName, String originalFileName, String contentType)
throws Exception {
long fileSize = minioClient.statObject(bucketName, minioFileName.toString()).length();
......@@ -212,36 +224,13 @@ public class FileContentService {
response.setContentLengthLong(dto.getSize());
}
void getThumbnailFileFromStorage(String objectId, String fileId, HttpServletResponse response,
String objectType, RequestMetaDTO requestMetaDTO) throws Exception {
log.info("Thumbnail retrieval from storage initiated for file ID: {}", fileId);
FileMetadataDto dto = fileProcessingService.getFile(UUID.fromString(objectId), UUID.fromString(fileId),
objectType, requestMetaDTO);
validateThumbnail(dto);
String thumbnailFileId = dto.getThumbnails().get(THUMBNAIL_SIZE_100);
try {
final ObjectStat objectStat = minioClient.statObject(bucketNameThumbnail, thumbnailFileId);