import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ThreadLocalRandom;
public class DataValidator {
/**
* Replaces values in a dataset with retry logic for validation checks.
*
* @param dataset The dataset to validate (represented as a Map).
* @param validationFunction The function to apply for validation.
* @param maxRetries The maximum number of retry attempts.
* @return The modified dataset with potentially retried values.
*/
public static Map<String, Object> validateWithRetry(Map<String, Object> dataset, ValidationFunction validationFunction, int maxRetries) {
Map<String, Object> modifiedDataset = new HashMap<>(dataset); // Create a copy to avoid modifying the original
for (Map.Entry<String, Object> entry : modifiedDataset.entrySet()) {
String key = entry.getKey();
Object value = entry.getValue();
int retryCount = 0;
boolean isValid = false;
while (retryCount < maxRetries && !isValid) {
try {
if (validationFunction.validate(value)) {
isValid = true;
} else {
retryCount++;
// Simulate some delay or random modification if validation fails.
if(retryCount > 1){
value = modifyValue(value); //modify the value for further retry
}
}
} catch (Exception e) {
// Handle exceptions during validation (e.g., network errors).
retryCount++;
if(retryCount > 1){
value = modifyValue(value);
}
// Log the error or handle appropriately.
}
}
modifiedDataset.put(key, value); // Put back the value, even if not valid after max retries
}
return modifiedDataset;
}
/**
* Simulates modifying a value for retry purposes. Can be customized.
* @param value the value to modify
* @return the modified value
*/
private static Object modifyValue(Object value) {
if (value instanceof Integer) {
return ThreadLocalRandom.current().nextInt(0, 101); // Random integer between 0 and 100
} else if (value instanceof String) {
return "retry_" + value.toString();
}
return value; // Return original if type not handled
}
/**
* Functional interface for validation logic.
*/
public interface ValidationFunction {
boolean validate(Object value);
}
public static void main(String[] args) {
// Example Usage
Map<String, Object> data = new HashMap<>();
data.put("age", 30);
data.put("email", "test@example.com");
data.put("score", "abc"); //invalid score
data.put("value",123);
ValidationFunction ageValidator = value -> {
if (value instanceof Integer) {
return ((Integer) value) >= 0 && (Integer) value <= 120;
}
return false;
};
ValidationFunction emailValidator = value -> {
if (value instanceof String) {
return value.matches("^[\\w-\\.]+@([\\w-]+\\.)+[\\w-]{2,4}$");
}
return false;
};
Map<String, Object> validatedData = validateWithRetry(data, ageValidator, 3);
System.out.println(validatedData);
validatedData = validateWithRetry(data, emailValidator, 2);
System.out.println(validatedData);
}
}
Add your comment