import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class LogFlattener {
/**
* Flattens a nested log entry structure into a single-level map.
* Handles potential null values gracefully.
* @param nestedLog The nested log entry data.
* @return A flattened map representing the log entry.
*/
public static Map<String, String> flattenLogEntry(Object nestedLog) {
Map<String, String> flattened = new HashMap<>();
flattenHelper(nestedLog, "", flattened);
return flattened;
}
private static void flattenHelper(Object obj, String prefix, Map<String, String> flattened) {
if (obj == null) {
return; // Handle null values
}
if (obj instanceof Map) {
Map<?, ?> map = (Map<?, ?>) obj;
for (Map.Entry<?, ?> entry : map.entrySet()) {
String key = prefix + entry.getKey().toString();
flattenHelper(entry.getValue(), key + ".", flattened);
}
} else if (obj instanceof List) {
List<?> list = (List<?>) obj;
for (int i = 0; i < list.size(); i++) {
String key = prefix + i;
flattenHelper(list.get(i), key + ".", flattened);
}
} else {
String key = prefix;
flattened.put(key, obj.toString());
}
}
/**
* Simulates a validation check with a fixed retry interval.
* @param logEntry The flattened log entry.
* @param retryCount The number of retry attempts.
* @param retryIntervalMillis The interval between retry attempts in milliseconds.
* @return True if the validation check passes, false otherwise.
*/
public static boolean validateLogEntry(Map<String, String> logEntry, int retryCount, long retryIntervalMillis) throws InterruptedException {
// Simulate a validation check. In a real scenario, this would involve
// querying a database, checking a configuration, etc.
if (logEntry.containsKey("status") && logEntry.get("status").equals("error")) {
System.out.println("Validation failed: Status is error.");
if (retryCount > 0) {
System.out.println("Retrying in " + retryIntervalMillis + "ms...");
Thread.sleep(retryIntervalMillis);
return validateLogEntry(logEntry, retryCount - 1, retryIntervalMillis);
} else {
System.out.println("Validation failed after multiple retries.");
return false;
}
} else {
System.out.println("Validation passed.");
return true;
}
}
public static void main(String[] args) {
// Example usage
Object nestedLog = new HashMap<>();
Map<String, String> innerMap = new HashMap<>();
innerMap.put("code", "404");
innerMap.put("message", "Resource not found");
nestedLog.put("status", "error");
nestedLog.put("details", innerMap);
nestedLog.put("tags", new List<>(){
List<String> list = new ArrayList<>();
{
list.add("error");
list.add("resource");
}
});
Map<String, String> flattenedLog = flattenLogEntry(nestedLog);
System.out.println("Flattened Log Entry: " + flattenedLog);
try {
boolean isValid = validateLogEntry(flattenedLog, 3, 1000); // Retry 3 times with 1 second interval
System.out.println("Log entry is valid: " + isValid);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
Add your comment