280 lines
9.4 KiB
Java
280 lines
9.4 KiB
Java
package net.gepafin.tendermanagement.util;
|
|
|
|
import java.lang.reflect.Field;
|
|
import java.lang.reflect.Type;
|
|
import java.nio.charset.StandardCharsets;
|
|
import java.security.SecureRandom;
|
|
import java.util.Base64;
|
|
import java.util.List;
|
|
import java.util.Map;
|
|
import java.util.function.Consumer;
|
|
import java.util.function.Supplier;
|
|
import java.util.regex.Pattern;
|
|
import java.util.stream.Collectors;
|
|
|
|
import org.apache.commons.collections4.MapUtils;
|
|
import org.slf4j.Logger;
|
|
import org.slf4j.LoggerFactory;
|
|
import org.springframework.http.HttpStatus;
|
|
|
|
import com.fasterxml.jackson.core.JsonProcessingException;
|
|
import com.fasterxml.jackson.core.json.JsonReadFeature;
|
|
import com.fasterxml.jackson.core.type.TypeReference;
|
|
import com.fasterxml.jackson.databind.DeserializationFeature;
|
|
import com.fasterxml.jackson.databind.ObjectMapper;
|
|
import com.fasterxml.jackson.databind.type.TypeFactory;
|
|
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
|
|
|
|
import feign.FeignException;
|
|
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;
|
|
|
|
|
|
public class Utils {
|
|
|
|
public static final Logger log = LoggerFactory.getLogger(Utils.class);
|
|
|
|
private static final ObjectMapper mapper = new ObjectMapper()
|
|
.registerModule(new JavaTimeModule())
|
|
.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
|
|
|
|
public static <T, U> U convertObject(T source, Class<U> destinationClass) {
|
|
try {
|
|
return mapper.convertValue(source, destinationClass);
|
|
} catch (Exception e) {
|
|
log.error("Error converting object: " + e.getMessage(), e);
|
|
}
|
|
return null;
|
|
}
|
|
|
|
public static <T, U> List<U> convertSourceListToDestinationList(List<T> sourceList, Class<U> destinationClass) {
|
|
try {
|
|
return sourceList.stream()
|
|
.map(source -> mapper.convertValue(source, destinationClass))
|
|
.collect(Collectors.toList());
|
|
} catch (Exception e) {
|
|
log.error("Error converting list: " + e.getMessage(), e);
|
|
}
|
|
return null;
|
|
}
|
|
|
|
public static <T, U> List<U> convertSourceToList(T source, Class<U> destinationClass) {
|
|
try {
|
|
// Convert single source object to a single-element list of destination type
|
|
return List.of(mapper.convertValue(source, destinationClass));
|
|
} catch (Exception e) {
|
|
log.error("Error converting single object to list: " + e.getMessage(), e);
|
|
}
|
|
return null;
|
|
}
|
|
public static String extractFileName(String filePath) {
|
|
if (filePath == null || filePath.isEmpty()) {
|
|
return null;
|
|
}
|
|
int lastSlashIndex = filePath.lastIndexOf('/');
|
|
|
|
if (lastSlashIndex >= 0 && lastSlashIndex < filePath.length() - 1) {
|
|
return filePath.substring(lastSlashIndex + 1);
|
|
} else {
|
|
return filePath;
|
|
}
|
|
}
|
|
public static String decodeBase64String(String decodedString) {
|
|
if (StringUtils.isBlank(decodedString)) {
|
|
return decodedString;
|
|
}
|
|
byte[] decode = Base64.getDecoder().decode(decodedString.getBytes(StandardCharsets.UTF_8));
|
|
return new String(decode, StandardCharsets.UTF_8);
|
|
}
|
|
|
|
public static <T> void setIfNotNull(Consumer<T> setter, T value) {
|
|
if (value != null) {
|
|
setter.accept(value);
|
|
}
|
|
}
|
|
public static <T> void setIfUpdated(Supplier<T> getter, Consumer<T> setter, T newValue) {
|
|
T currentValue = getter.get();
|
|
if (newValue != null && !newValue.equals(currentValue)) {
|
|
setter.accept(newValue);
|
|
}
|
|
}
|
|
public static <T> String convertListToJsonString(List<T> list) {
|
|
try {
|
|
return mapper.writeValueAsString(list);
|
|
} catch (JsonProcessingException e) {
|
|
e.printStackTrace();
|
|
// Handle exception or throw a custom exception
|
|
return null;
|
|
}
|
|
}
|
|
public static <T> List<T> convertJsonStringToList(String jsonString, Class<T> clazz) {
|
|
try {
|
|
TypeReference<List<T>> typeRef = new TypeReference<List<T>>() {
|
|
@Override
|
|
public Type getType() {
|
|
return TypeFactory.defaultInstance().constructCollectionType(List.class, clazz);
|
|
}
|
|
};
|
|
return mapper.readValue(jsonString, typeRef);
|
|
} catch (Exception e) {
|
|
e.printStackTrace();
|
|
// Handle the exception appropriately (e.g., throw a custom exception)
|
|
return null;
|
|
}
|
|
}
|
|
public static String convertMapIntoJsonString(Map<String, Object> map) {
|
|
try {
|
|
ObjectMapper mapper = new ObjectMapper();
|
|
if (MapUtils.isNotEmpty(map)) {
|
|
return mapper.writeValueAsString(map);
|
|
}
|
|
} catch (JsonProcessingException e) {
|
|
log.error(e.getMessage());
|
|
}
|
|
return null;
|
|
}
|
|
public static Map<String, Object> convertIntoJson(String jsonString) {
|
|
if (jsonString != null && !jsonString.isEmpty()) {
|
|
try {
|
|
ObjectMapper mapper = new ObjectMapper();
|
|
mapper.configure(JsonReadFeature.ALLOW_UNESCAPED_CONTROL_CHARS.mappedFeature(), true);
|
|
return mapper.readValue(jsonString, Map.class);
|
|
} catch (Exception e) {
|
|
log.error(e.getMessage());
|
|
}
|
|
}
|
|
return null;
|
|
}
|
|
public static <T, U> U convertSourceObjectToDestinationObject(T source, Class<U> destinationClass) {
|
|
try {
|
|
mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
|
|
mapper.registerModule(new JavaTimeModule());
|
|
return mapper.convertValue(source, destinationClass);
|
|
} catch (Exception e) {
|
|
log.error("Error converting object: " + e.getMessage(), e);
|
|
}
|
|
return null;
|
|
}
|
|
public static <T> void retainOnlySpecificFields(T requestObject, List<T> retainFields) throws IllegalAccessException {
|
|
// Get all declared fields of the request object's class
|
|
Field[] fields = requestObject.getClass().getDeclaredFields();
|
|
|
|
for (Field field : fields) {
|
|
field.setAccessible(true); // To allow access to private fields
|
|
|
|
// Check if the field is in the retainFields list
|
|
if (!retainFields.contains(field.getName())) {
|
|
field.set(requestObject, null); // Set the field to null if not in the retain list
|
|
}
|
|
}
|
|
}
|
|
|
|
public static String encodeData(String data) {
|
|
return Base64.getEncoder().encodeToString(data.getBytes(StandardCharsets.UTF_8));
|
|
}
|
|
|
|
public static String decodeData(String token) {
|
|
byte[] decodedBytes = Base64.getDecoder().decode(token);
|
|
return new String(decodedBytes, StandardCharsets.UTF_8);
|
|
}
|
|
|
|
public static String generateSecureToken() {
|
|
SecureRandom secureRandom = new SecureRandom();
|
|
byte[] tokenBytes = new byte[24];
|
|
secureRandom.nextBytes(tokenBytes);
|
|
String token = Base64.getUrlEncoder().withoutPadding().encodeToString(tokenBytes);
|
|
log.debug("Generated secure token: {}", token);
|
|
return token;
|
|
}
|
|
|
|
public static Map<String, List<Object>> convertStringIntoMap(String jsonString) {
|
|
try {
|
|
return mapper.readValue(jsonString, new TypeReference<Map<String, List<Object>>>() {
|
|
});
|
|
} catch (Exception e) {
|
|
log.error("Error converting object: " + e.getMessage(), e);
|
|
return null;
|
|
}
|
|
}
|
|
|
|
public static void callException(Integer staus, FeignException ex) {
|
|
switch (staus) {
|
|
case 400:
|
|
throw new FeignClientValidationException(HttpStatus.valueOf(staus), ex.getMessage());
|
|
|
|
case 401:
|
|
throw new FeignClientUnauthorizedException(HttpStatus.valueOf(staus), ex.getMessage());
|
|
|
|
case 403:
|
|
throw new FeignClientForbiddenException(HttpStatus.valueOf(staus), ex.getMessage());
|
|
|
|
case 404:
|
|
throw new FeignClientNotFoundException(HttpStatus.valueOf(staus), ex.getMessage());
|
|
default:
|
|
log.error("Exception occured :- {0}", ex);
|
|
throw ex;
|
|
}
|
|
}
|
|
|
|
public static Boolean isValidEmail(String email) {
|
|
String EMAIL_REGEX = "^[A-Za-z0-9+_.-]+@[A-Za-z0-9.-]+$";
|
|
if (email == null || email.isEmpty()) {
|
|
return false;
|
|
}
|
|
Pattern pattern = Pattern.compile(EMAIL_REGEX);
|
|
return pattern.matcher(email).matches();
|
|
}
|
|
|
|
public static String randomKey(Integer range) {
|
|
String data = String.valueOf(System.currentTimeMillis());
|
|
return data.substring(data.length() - range);
|
|
}
|
|
|
|
public static String convertObjectToJsonString(Object object) {
|
|
try {
|
|
// Check if the object is a string
|
|
if (object instanceof String) {
|
|
String str = (String) object;
|
|
// Return null if the string is null or empty
|
|
if (str != null && !str.trim().isEmpty()) {
|
|
return str; // Return the non-empty string
|
|
} else {
|
|
return null; // Return null for null or empty string
|
|
}
|
|
} else if (object != null) {
|
|
// Convert non-string objects (arrays, objects) to JSON strings
|
|
return mapper.writeValueAsString(object);
|
|
}
|
|
return null; // Return null if the object is null
|
|
} catch (JsonProcessingException e) {
|
|
log.error("Error while converting object to string: {}", e.getMessage(), e);
|
|
return null; // Return null in case of exception
|
|
}
|
|
}
|
|
|
|
|
|
public static Object getFieldValueAsObject(String fieldValue) {
|
|
ObjectMapper mapper = new ObjectMapper();
|
|
try {
|
|
// Check if the string is a valid JSON object, array, or simple string
|
|
if (fieldValue.startsWith("{")) {
|
|
// Convert to a Map (representing an object)
|
|
return mapper.readValue(fieldValue, Map.class);
|
|
} else if (fieldValue.startsWith("[")) {
|
|
// Convert to a List (representing an array)
|
|
return mapper.readValue(fieldValue, List.class);
|
|
} else {
|
|
// Return the raw string (it's a simple value)
|
|
return fieldValue;
|
|
}
|
|
} catch (JsonProcessingException e) {
|
|
log.error("Error while converting string to object: {}", e.getMessage(), e);
|
|
return fieldValue; // If there's an error, return the raw string
|
|
}
|
|
}
|
|
|
|
}
|