Merge pull request #260 from Kitzanos/feature/GEPAFINBE-200

GEPAFINBE-200 (Check for 0 bytes in file)
This commit is contained in:
Rinaldo
2025-04-07 09:06:51 +02:00
committed by GitHub
6 changed files with 119 additions and 78 deletions

View File

@@ -209,7 +209,6 @@ public class DelegationDao {
companyDao.validateCompany(companyId); companyDao.validateCompany(companyId);
companyDao.getUserWithCompany(userEntity.getId(), companyId); companyDao.getUserWithCompany(userEntity.getId(), companyId);
validateFileType(file);
UserWithCompanyEntity userWithCompanyEntity=companyService.getUserWithCompany(userEntity.getId(),companyId); UserWithCompanyEntity userWithCompanyEntity=companyService.getUserWithCompany(userEntity.getId(),companyId);
UserCompanyDelegationEntity userCompanyDelegationEntity = userCompanyDelegationRepository UserCompanyDelegationEntity userCompanyDelegationEntity = userCompanyDelegationRepository
.findByUserIdAndUserWithCompanyIdAndStatus(userEntity.getId(), userWithCompanyEntity.getId(), .findByUserIdAndUserWithCompanyIdAndStatus(userEntity.getId(), userWithCompanyEntity.getId(),

View File

@@ -15,6 +15,7 @@ import net.gepafin.tendermanagement.enums.FormActionEnum;
import net.gepafin.tendermanagement.model.request.ApplicationRequestBean; import net.gepafin.tendermanagement.model.request.ApplicationRequestBean;
import net.gepafin.tendermanagement.model.response.*; import net.gepafin.tendermanagement.model.response.*;
import net.gepafin.tendermanagement.service.ApplicationService; import net.gepafin.tendermanagement.service.ApplicationService;
import net.gepafin.tendermanagement.util.Utils;
import net.gepafin.tendermanagement.util.Validator; import net.gepafin.tendermanagement.util.Validator;
import net.gepafin.tendermanagement.web.rest.api.errors.CustomValidationException; import net.gepafin.tendermanagement.web.rest.api.errors.CustomValidationException;
import net.gepafin.tendermanagement.web.rest.api.errors.ForbiddenAccessException; import net.gepafin.tendermanagement.web.rest.api.errors.ForbiddenAccessException;
@@ -112,6 +113,7 @@ public class ApplicationServiceImpl implements ApplicationService {
@Override @Override
@Transactional(rollbackFor = Exception.class) @Transactional(rollbackFor = Exception.class)
public ApplicationSignedDocumentResponse uploadSignedDocument(HttpServletRequest request, Long applicationId, MultipartFile file) { public ApplicationSignedDocumentResponse uploadSignedDocument(HttpServletRequest request, Long applicationId, MultipartFile file) {
Utils.validateFileType(file);
return applicationDao.uploadSignedDocument(request, applicationId, file); return applicationDao.uploadSignedDocument(request, applicationId, file);
} }

View File

@@ -9,6 +9,7 @@ import net.gepafin.tendermanagement.model.request.CompanyDocumentRequest;
import net.gepafin.tendermanagement.model.response.CompanyDocumentResponseBean; import net.gepafin.tendermanagement.model.response.CompanyDocumentResponseBean;
import net.gepafin.tendermanagement.model.response.DocumentResponseBean; import net.gepafin.tendermanagement.model.response.DocumentResponseBean;
import net.gepafin.tendermanagement.service.CompanyDocumentService; import net.gepafin.tendermanagement.service.CompanyDocumentService;
import net.gepafin.tendermanagement.util.Utils;
import net.gepafin.tendermanagement.util.Validator; import net.gepafin.tendermanagement.util.Validator;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
@@ -31,6 +32,7 @@ public class CompanyDocumentServiceImpl implements CompanyDocumentService {
public List<CompanyDocumentResponseBean> uploadFileForCompany(HttpServletRequest request, List<MultipartFile> files, Long companyId, Long documentCategoryId , CompanyDocumentTypeEnum documentSourceTypeEnum, LocalDateTime expirationDate,String name) { public List<CompanyDocumentResponseBean> uploadFileForCompany(HttpServletRequest request, List<MultipartFile> files, Long companyId, Long documentCategoryId , CompanyDocumentTypeEnum documentSourceTypeEnum, LocalDateTime expirationDate,String name) {
Map<String, Object> userInfo = validator.getUserInfoFromToken(request); Map<String, Object> userInfo = validator.getUserInfoFromToken(request);
Long userId = validator.getUserId(userInfo); Long userId = validator.getUserId(userInfo);
files.forEach(Utils::validateFileType);
return companyDocumentDao.uploadFileForCompany(request,userId,files,companyId,documentCategoryId,documentSourceTypeEnum,expirationDate,name); return companyDocumentDao.uploadFileForCompany(request,userId,files,companyId,documentCategoryId,documentSourceTypeEnum,expirationDate,name);
} }

View File

@@ -4,8 +4,10 @@ import java.io.ByteArrayOutputStream;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import jdk.jshell.execution.Util;
import net.gepafin.tendermanagement.model.request.LimitRequest; import net.gepafin.tendermanagement.model.request.LimitRequest;
import net.gepafin.tendermanagement.model.response.VatCheckResponseBean; import net.gepafin.tendermanagement.model.response.VatCheckResponseBean;
import net.gepafin.tendermanagement.util.Utils;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional; import org.springframework.transaction.annotation.Transactional;
@@ -107,6 +109,7 @@ public class CompanyServiceImpl implements CompanyService {
public CompanyDelegationResponse uploadCompanyDelegation(HttpServletRequest request, Long companyId, MultipartFile file) { public CompanyDelegationResponse uploadCompanyDelegation(HttpServletRequest request, Long companyId, MultipartFile file) {
UserEntity userEntity = validator.validateUser(request); UserEntity userEntity = validator.validateUser(request);
validator.validateUserWithCompany(request, companyId); validator.validateUserWithCompany(request, companyId);
Utils.validateFileType(file);
return delegationDao.uploadCompanyDelegation(userEntity, companyId, file); return delegationDao.uploadCompanyDelegation(userEntity, companyId, file);
} }

View File

@@ -11,6 +11,7 @@ import net.gepafin.tendermanagement.enums.DocumentSourceTypeEnum;
import net.gepafin.tendermanagement.enums.DocumentTypeEnum; import net.gepafin.tendermanagement.enums.DocumentTypeEnum;
import net.gepafin.tendermanagement.model.response.DocumentResponseBean; import net.gepafin.tendermanagement.model.response.DocumentResponseBean;
import net.gepafin.tendermanagement.service.DocumentService; import net.gepafin.tendermanagement.service.DocumentService;
import net.gepafin.tendermanagement.util.Utils;
import net.gepafin.tendermanagement.util.Validator; import net.gepafin.tendermanagement.util.Validator;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
@@ -31,6 +32,7 @@ public class DocumentServiceImpl implements DocumentService {
public List<DocumentResponseBean> uploadFile(HttpServletRequest request,List<MultipartFile> files, Long sourceId, DocumentSourceTypeEnum sourceType, DocumentTypeEnum fileType) { public List<DocumentResponseBean> uploadFile(HttpServletRequest request,List<MultipartFile> files, Long sourceId, DocumentSourceTypeEnum sourceType, DocumentTypeEnum fileType) {
Map<String, Object> userInfo = validator.getUserInfoFromToken(request); Map<String, Object> userInfo = validator.getUserInfoFromToken(request);
Long userId = validator.getUserId(userInfo); Long userId = validator.getUserId(userInfo);
files.forEach(Utils::validateFileType);
return documentDao.uploadFiles(userId,files,sourceId,sourceType,fileType); return documentDao.uploadFiles(userId,files,sourceId,sourceType,fileType);
} }
@Override @Override

View File

@@ -39,6 +39,7 @@ import net.gepafin.tendermanagement.constants.GepafinConstant;
import net.gepafin.tendermanagement.enums.MatchModeEnum; import net.gepafin.tendermanagement.enums.MatchModeEnum;
import net.gepafin.tendermanagement.model.request.FilterCriteria; import net.gepafin.tendermanagement.model.request.FilterCriteria;
import net.gepafin.tendermanagement.model.request.GlobalFilters; import net.gepafin.tendermanagement.model.request.GlobalFilters;
import net.gepafin.tendermanagement.web.rest.api.errors.*;
import net.objecthunter.exp4j.Expression; import net.objecthunter.exp4j.Expression;
import net.objecthunter.exp4j.ExpressionBuilder; import net.objecthunter.exp4j.ExpressionBuilder;
import org.apache.commons.collections4.MapUtils; import org.apache.commons.collections4.MapUtils;
@@ -56,13 +57,10 @@ import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import feign.FeignException; import feign.FeignException;
import io.micrometer.common.util.StringUtils; import io.micrometer.common.util.StringUtils;
import net.gepafin.tendermanagement.web.rest.api.errors.FeignClientForbiddenException;
import net.gepafin.tendermanagement.web.rest.api.errors.FeignClientNotFoundException;
import net.gepafin.tendermanagement.web.rest.api.errors.FeignClientUnauthorizedException;
import net.gepafin.tendermanagement.web.rest.api.errors.FeignClientValidationException;
import org.springframework.mock.web.MockHttpServletRequest; import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.web.context.request.RequestContextHolder; import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes; import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.multipart.MultipartFile;
import javax.crypto.Cipher; import javax.crypto.Cipher;
import javax.crypto.Mac; import javax.crypto.Mac;
@@ -114,6 +112,7 @@ public class Utils {
} }
return null; return null;
} }
public static String extractFileName(String filePath) { public static String extractFileName(String filePath) {
if (filePath == null || filePath.isEmpty()) { if (filePath == null || filePath.isEmpty()) {
return null; return null;
@@ -126,6 +125,7 @@ public class Utils {
return filePath; return filePath;
} }
} }
public static String decodeBase64String(String decodedString) { public static String decodeBase64String(String decodedString) {
if (StringUtils.isBlank(decodedString)) { if (StringUtils.isBlank(decodedString)) {
return decodedString; return decodedString;
@@ -134,17 +134,19 @@ public class Utils {
return new String(decode, StandardCharsets.UTF_8); return new String(decode, StandardCharsets.UTF_8);
} }
public static <T> void setIfNotNull(Consumer<T> setter, T value) { public static <T> void setIfNotNull(Consumer<T> setter, T value) {
if (value != null) { if (value != null) {
setter.accept(value); setter.accept(value);
} }
} }
public static <T> void setIfUpdated(Supplier<T> getter, Consumer<T> setter, T newValue) {
T currentValue = getter.get(); public static <T> void setIfUpdated(Supplier<T> getter, Consumer<T> setter, T newValue) {
if (newValue != null && !newValue.equals(currentValue)) { T currentValue = getter.get();
setter.accept(newValue); if (newValue != null && !newValue.equals(currentValue)) {
} setter.accept(newValue);
} }
}
public static <T> String convertListToJsonString(List<T> list) { public static <T> String convertListToJsonString(List<T> list) {
try { try {
return mapper.writeValueAsString(list); return mapper.writeValueAsString(list);
@@ -154,6 +156,7 @@ public class Utils {
return null; return null;
} }
} }
public static <T> List<T> convertJsonStringToList(String jsonString, Class<T> clazz) { public static <T> List<T> convertJsonStringToList(String jsonString, Class<T> clazz) {
try { try {
TypeReference<List<T>> typeRef = new TypeReference<List<T>>() { TypeReference<List<T>> typeRef = new TypeReference<List<T>>() {
@@ -169,6 +172,7 @@ public class Utils {
return null; return null;
} }
} }
public static String convertMapIntoJsonString(Map<String, Object> map) { public static String convertMapIntoJsonString(Map<String, Object> map) {
try { try {
ObjectMapper mapper = new ObjectMapper(); ObjectMapper mapper = new ObjectMapper();
@@ -183,6 +187,7 @@ public class Utils {
} }
return null; return null;
} }
public static Map<String, Object> convertIntoJson(String jsonString) { public static Map<String, Object> convertIntoJson(String jsonString) {
if (jsonString != null && !jsonString.isEmpty()) { if (jsonString != null && !jsonString.isEmpty()) {
try { try {
@@ -195,6 +200,7 @@ public class Utils {
} }
return null; return null;
} }
public static <T, U> U convertSourceObjectToDestinationObject(T source, Class<U> destinationClass) { public static <T, U> U convertSourceObjectToDestinationObject(T source, Class<U> destinationClass) {
try { try {
mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES); mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
@@ -205,6 +211,7 @@ public class Utils {
} }
return null; return null;
} }
public static <T> void retainOnlySpecificFields(T requestObject, List<T> retainFields) throws IllegalAccessException { public static <T> void retainOnlySpecificFields(T requestObject, List<T> retainFields) throws IllegalAccessException {
// Get all declared fields of the request object's class // Get all declared fields of the request object's class
Field[] fields = requestObject.getClass().getDeclaredFields(); Field[] fields = requestObject.getClass().getDeclaredFields();
@@ -220,22 +227,23 @@ public class Utils {
} }
public static String encodeData(String data) { public static String encodeData(String data) {
return Base64.getEncoder().encodeToString(data.getBytes(StandardCharsets.UTF_8)); return Base64.getEncoder().encodeToString(data.getBytes(StandardCharsets.UTF_8));
} }
public static String decodeData(String token) { public static String decodeData(String token) {
byte[] decodedBytes = Base64.getDecoder().decode(token); byte[] decodedBytes = Base64.getDecoder().decode(token);
return new String(decodedBytes, StandardCharsets.UTF_8); return new String(decodedBytes, StandardCharsets.UTF_8);
} }
public static String generateSecureSamlToken() { public static String generateSecureSamlToken() {
SecureRandom secureRandom = new SecureRandom(); SecureRandom secureRandom = new SecureRandom();
byte[] tokenBytes = new byte[24]; byte[] tokenBytes = new byte[24];
secureRandom.nextBytes(tokenBytes); secureRandom.nextBytes(tokenBytes);
String token = Base64.getUrlEncoder().withoutPadding().encodeToString(tokenBytes); String token = Base64.getUrlEncoder().withoutPadding().encodeToString(tokenBytes);
log.debug("Generated secure token: {}", token); log.debug("Generated secure token: {}", token);
return token; return token;
} }
public static String generateSecureToken() { public static String generateSecureToken() {
SecureRandom secureRandom = new SecureRandom(); SecureRandom secureRandom = new SecureRandom();
byte[] tokenBytes = new byte[5]; byte[] tokenBytes = new byte[5];
@@ -244,6 +252,7 @@ public class Utils {
log.debug("Generated secure token: {}", token); log.debug("Generated secure token: {}", token);
return token; return token;
} }
public static Map<String, List<Object>> convertStringIntoMap(String jsonString) { public static Map<String, List<Object>> convertStringIntoMap(String jsonString) {
try { try {
return mapper.readValue(jsonString, new TypeReference<Map<String, List<Object>>>() { return mapper.readValue(jsonString, new TypeReference<Map<String, List<Object>>>() {
@@ -256,20 +265,20 @@ public class Utils {
public static void callException(Integer staus, FeignException ex) { public static void callException(Integer staus, FeignException ex) {
switch (staus) { switch (staus) {
case 400: case 400:
throw new FeignClientValidationException(HttpStatus.valueOf(staus), ex.getMessage()); throw new FeignClientValidationException(HttpStatus.valueOf(staus), ex.getMessage());
case 401: case 401:
throw new FeignClientUnauthorizedException(HttpStatus.valueOf(staus), ex.getMessage()); throw new FeignClientUnauthorizedException(HttpStatus.valueOf(staus), ex.getMessage());
case 403: case 403:
throw new FeignClientForbiddenException(HttpStatus.valueOf(staus), ex.getMessage()); throw new FeignClientForbiddenException(HttpStatus.valueOf(staus), ex.getMessage());
case 404: case 404:
throw new FeignClientNotFoundException(HttpStatus.valueOf(staus), ex.getMessage()); throw new FeignClientNotFoundException(HttpStatus.valueOf(staus), ex.getMessage());
default: default:
log.error("Exception occured :- {0}", ex); log.error("Exception occured :- {0}", ex);
throw ex; throw ex;
} }
} }
@@ -330,7 +339,7 @@ public class Utils {
} }
} }
public static Map<String, Map<String, String>> parseJsonContent(String jsonContent) { public static Map<String, Map<String, String>> parseJsonContent(String jsonContent) {
ObjectMapper objectMapper = new ObjectMapper(); ObjectMapper objectMapper = new ObjectMapper();
try { try {
return mapper.readValue(jsonContent, HashMap.class); return mapper.readValue(jsonContent, HashMap.class);
@@ -342,19 +351,20 @@ public class Utils {
// Utility method to replace placeholders with their values, handling nulls // Utility method to replace placeholders with their values, handling nulls
public static String replacePlaceholders(String text, Map<String, String> placeholders) { public static String replacePlaceholders(String text, Map<String, String> placeholders) {
if (text == null) { if (text == null) {
return ""; return "";
} }
for (Map.Entry<String, String> entry : placeholders.entrySet()) { for (Map.Entry<String, String> entry : placeholders.entrySet()) {
text = replaceNull(text, entry.getKey(), entry.getValue()); text = replaceNull(text, entry.getKey(), entry.getValue());
} }
return text; return text;
} }
// Method to safely replace nulls with an empty string or a default value // Method to safely replace nulls with an empty string or a default value
private static String replaceNull(String text, String target, String replacement) { private static String replaceNull(String text, String target, String replacement) {
return text.replace(target, replacement != null ? replacement : ""); return text.replace(target, replacement != null ? replacement : "");
} }
public static String getClientIpAddress(HttpServletRequest request) { public static String getClientIpAddress(HttpServletRequest request) {
String header = request.getHeader("X-Forwarded-For"); String header = request.getHeader("X-Forwarded-For");
if (org.apache.commons.lang3.StringUtils.isBlank(header)) { if (org.apache.commons.lang3.StringUtils.isBlank(header)) {
@@ -363,6 +373,7 @@ public class Utils {
return new StringTokenizer(header, ",").nextToken().trim(); return new StringTokenizer(header, ",").nextToken().trim();
} }
public static <T> List<T> convertJsonToList(String json, TypeReference<List<T>> typeRef) { public static <T> List<T> convertJsonToList(String json, TypeReference<List<T>> typeRef) {
ObjectMapper objectMapper = new ObjectMapper(); ObjectMapper objectMapper = new ObjectMapper();
try { try {
@@ -375,11 +386,15 @@ public class Utils {
public static String convertObjectToJson(Object obj) { public static String convertObjectToJson(Object obj) {
try { try {
if(obj == null){return null;} if (obj == null) {
return null;
}
return new ObjectMapper().writeValueAsString(obj); return new ObjectMapper().writeValueAsString(obj);
} catch (JsonProcessingException e) { } catch (JsonProcessingException e) {
log.error("Failed to convert object to JSON: {}", e.getMessage(), e); log.error("Failed to convert object to JSON: {}", e.getMessage(), e);
throw new RuntimeException("Failed to convert object to JSON", e);}} throw new RuntimeException("Failed to convert object to JSON", e);
}
}
public static String replaceSpacesWithUnderscores(String content) { public static String replaceSpacesWithUnderscores(String content) {
if (content == null) { if (content == null) {
@@ -387,10 +402,10 @@ public class Utils {
} }
return content.trim().replace(" ", "_"); return content.trim().replace(" ", "_");
} }
public static List<Map<String, Object>> convertJsonStringIntoJsonList(String jsonString) { public static List<Map<String, Object>> convertJsonStringIntoJsonList(String jsonString) {
try { try {
if(isEmpty(jsonString)) if (isEmpty(jsonString)) {
{
return new ArrayList<>(); return new ArrayList<>();
} }
ObjectMapper mapper = new ObjectMapper(); ObjectMapper mapper = new ObjectMapper();
@@ -401,6 +416,7 @@ public class Utils {
} }
return null; return null;
} }
public static String convertToString(Object input) { public static String convertToString(Object input) {
if (input == null) { if (input == null) {
return "null"; // Return string "null" for null input return "null"; // Return string "null" for null input
@@ -462,6 +478,7 @@ public class Utils {
throw new RuntimeException("Error converting map to string", e); throw new RuntimeException("Error converting map to string", e);
} }
} }
public static boolean isValidDateString(String dateStr) { public static boolean isValidDateString(String dateStr) {
Pattern datePattern = Pattern.compile("\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}"); Pattern datePattern = Pattern.compile("\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}");
return datePattern.matcher(dateStr).matches(); return datePattern.matcher(dateStr).matches();
@@ -479,7 +496,7 @@ public class Utils {
return targetFormat.format(date); return targetFormat.format(date);
} catch (ParseException e) { } catch (ParseException e) {
log.error("error while prcoessing date formate"); log.error("error while prcoessing date formate");
return null; return null;
} }
} }
@@ -525,6 +542,7 @@ public class Utils {
return "Invalid amount format"; return "Invalid amount format";
} }
} }
public static boolean isItalianFormattedAmount(String input) { public static boolean isItalianFormattedAmount(String input) {
// Regular expression to match Italian-style amounts (e.g., 41.003,00 or 123,45) // Regular expression to match Italian-style amounts (e.g., 41.003,00 or 123,45)
String sanitizedInput = input.replace(",", ""); String sanitizedInput = input.replace(",", "");
@@ -537,7 +555,7 @@ public class Utils {
public static String encryptCredential(String value) { public static String encryptCredential(String value) {
try { try {
if(Boolean.FALSE.equals(isEmpty(value))) { if (Boolean.FALSE.equals(isEmpty(value))) {
IvParameterSpec iv = new IvParameterSpec(GepafinConstant.ENCRYPT_INIT_VECTOR.getBytes("UTF-8")); IvParameterSpec iv = new IvParameterSpec(GepafinConstant.ENCRYPT_INIT_VECTOR.getBytes("UTF-8"));
SecretKeySpec skeySpec = new SecretKeySpec(Base64.getDecoder().decode(GepafinConstant.ENCRYPT_KEY), "AES"); SecretKeySpec skeySpec = new SecretKeySpec(Base64.getDecoder().decode(GepafinConstant.ENCRYPT_KEY), "AES");
@@ -558,7 +576,7 @@ public class Utils {
public static String decryptCredential(String encrypted) { public static String decryptCredential(String encrypted) {
try { try {
if(Boolean.FALSE.equals(isEmpty(encrypted))) { if (Boolean.FALSE.equals(isEmpty(encrypted))) {
IvParameterSpec iv = new IvParameterSpec(GepafinConstant.ENCRYPT_INIT_VECTOR.getBytes("UTF-8")); IvParameterSpec iv = new IvParameterSpec(GepafinConstant.ENCRYPT_INIT_VECTOR.getBytes("UTF-8"));
SecretKeySpec skeySpec = new SecretKeySpec(Base64.getDecoder().decode(GepafinConstant.ENCRYPT_KEY), "AES"); SecretKeySpec skeySpec = new SecretKeySpec(Base64.getDecoder().decode(GepafinConstant.ENCRYPT_KEY), "AES");
@@ -623,17 +641,17 @@ public class Utils {
} }
public static void setHttpServletRequestForScheduler() { public static void setHttpServletRequestForScheduler() {
MockHttpServletRequest mockRequest = new MockHttpServletRequest(); MockHttpServletRequest mockRequest = new MockHttpServletRequest();
mockRequest.setRequestURI("/scheduled"); mockRequest.setRequestURI("/scheduled");
mockRequest.setMethod("POST"); mockRequest.setMethod("POST");
ServletRequestAttributes attributes = new ServletRequestAttributes(mockRequest); ServletRequestAttributes attributes = new ServletRequestAttributes(mockRequest);
RequestContextHolder.setRequestAttributes(attributes); RequestContextHolder.setRequestAttributes(attributes);
} }
public static void clearHttpServletRequest() { public static void clearHttpServletRequest() {
// Clear the RequestContextHolder after task execution // Clear the RequestContextHolder after task execution
RequestContextHolder.resetRequestAttributes(); RequestContextHolder.resetRequestAttributes();
} }
public static String generateAuthTokenForLoginToOdessa() { public static String generateAuthTokenForLoginToOdessa() {
@@ -742,7 +760,8 @@ public class Utils {
public static String createChannelForUserAndCompany(Long userId, Long companyId) { public static String createChannelForUserAndCompany(Long userId, Long companyId) {
return GepafinConstant.COMMON_SINGLE_CHANNEL_PREFIX + userId + GepafinConstant.COMPANY_PREFIX + companyId; return GepafinConstant.COMMON_SINGLE_CHANNEL_PREFIX + userId + GepafinConstant.COMPANY_PREFIX + companyId;
} }
public static GlobalFilters setPageNumberAndLimit(GlobalFilters globalFilters){
public static GlobalFilters setPageNumberAndLimit(GlobalFilters globalFilters) {
if (globalFilters == null) { if (globalFilters == null) {
if (globalFilters.getLimit() == null || globalFilters.getLimit() <= 0) { if (globalFilters.getLimit() == null || globalFilters.getLimit() <= 0) {
globalFilters.setLimit(GepafinConstant.DEFAULT_PAGE_LIMIT); globalFilters.setLimit(GepafinConstant.DEFAULT_PAGE_LIMIT);
@@ -770,6 +789,7 @@ public class Utils {
private static Map<String, Object> defaultErrorResponse() { private static Map<String, Object> defaultErrorResponse() {
return Collections.singletonMap("message", Translator.toLocale(GepafinConstant.INVALID_VATNUMBER)); return Collections.singletonMap("message", Translator.toLocale(GepafinConstant.INVALID_VATNUMBER));
} }
public static List<String> extractValues(String input) { public static List<String> extractValues(String input) {
List<String> extractedValues = new ArrayList<>(); List<String> extractedValues = new ArrayList<>();
Pattern pattern = Pattern.compile("\\{(.*?)\\}"); // Regex to match {value} Pattern pattern = Pattern.compile("\\{(.*?)\\}"); // Regex to match {value}
@@ -780,6 +800,7 @@ public class Utils {
} }
return extractedValues; return extractedValues;
} }
public static double evaluateExpression(String expression) { public static double evaluateExpression(String expression) {
try { try {
Expression exp = new ExpressionBuilder(expression).build(); Expression exp = new ExpressionBuilder(expression).build();
@@ -789,6 +810,7 @@ public class Utils {
return Double.NaN; // Return NaN if the expression is invalid return Double.NaN; // Return NaN if the expression is invalid
} }
} }
public static boolean isNumeric(String input) { public static boolean isNumeric(String input) {
if (input == null || input.trim().isEmpty()) { if (input == null || input.trim().isEmpty()) {
return false; return false;
@@ -796,9 +818,11 @@ public class Utils {
return input.matches("-?\\d+(\\.\\d+)?"); return input.matches("-?\\d+(\\.\\d+)?");
} }
public static boolean isValidBoolean(String value) { public static boolean isValidBoolean(String value) {
return "true".equalsIgnoreCase(value) || "false".equalsIgnoreCase(value); return "true".equalsIgnoreCase(value) || "false".equalsIgnoreCase(value);
} }
public static Map<String, Object> convertJsonStringToMap(String jsonString) { public static Map<String, Object> convertJsonStringToMap(String jsonString) {
try { try {
return mapper.readValue(jsonString, Map.class); return mapper.readValue(jsonString, Map.class);
@@ -908,8 +932,10 @@ public class Utils {
switch (mode) { switch (mode) {
case DATEIS -> predicates.add(criteriaBuilder.equal(dateField, dateValue)); case DATEIS -> predicates.add(criteriaBuilder.equal(dateField, dateValue));
case DATEISNOT -> predicates.add(criteriaBuilder.notEqual(dateField, dateValue)); case DATEISNOT -> predicates.add(criteriaBuilder.notEqual(dateField, dateValue));
case BEFORE -> predicates.add(criteriaBuilder.lessThan(fieldPath.as(Timestamp.class), Timestamp.valueOf(dateTimeValue))); case BEFORE ->
case AFTER -> predicates.add(criteriaBuilder.greaterThan(fieldPath.as(Timestamp.class), Timestamp.valueOf(dateTimeValue))); predicates.add(criteriaBuilder.lessThan(fieldPath.as(Timestamp.class), Timestamp.valueOf(dateTimeValue)));
case AFTER ->
predicates.add(criteriaBuilder.greaterThan(fieldPath.as(Timestamp.class), Timestamp.valueOf(dateTimeValue)));
} }
} }
} }
@@ -934,6 +960,12 @@ public class Utils {
return (obj instanceof String str) ? str : null; return (obj instanceof String str) ? str : null;
} }
public static void validateFileType(MultipartFile file) {
if (file.isEmpty()) {
throw new CustomValidationException(Status.VALIDATION_ERROR,
Translator.toLocale(GepafinConstant.VALIDATION_ERROR_FILE_EMPTY));
}
}
public static void applyFiltersByPagination(Root<?> root, CriteriaBuilder criteriaBuilder, List<Predicate> predicates, Map<String, FilterCriteria> filters) { public static void applyFiltersByPagination(Root<?> root, CriteriaBuilder criteriaBuilder, List<Predicate> predicates, Map<String, FilterCriteria> filters) {
if (Boolean.FALSE.equals(filters.isEmpty())) { if (Boolean.FALSE.equals(filters.isEmpty())) {
@@ -948,10 +980,11 @@ public class Utils {
if (fieldPath != null) { if (fieldPath != null) {
Utils.applyStringFilter(fieldPath, criteriaBuilder, predicates, value, matchMode); Utils.applyStringFilter(fieldPath, criteriaBuilder, predicates, value, matchMode);
Utils.applyNumberFilter(fieldPath, criteriaBuilder, predicates, value, matchMode); Utils.applyNumberFilter(fieldPath, criteriaBuilder, predicates, value, matchMode);
Utils.applyDateFilter(fieldPath, criteriaBuilder, predicates, value, matchMode,root); Utils.applyDateFilter(fieldPath, criteriaBuilder, predicates, value, matchMode, root);
} }
} }
} }
} }
} }
} }