import java.util.HashMap;
import java.util.Map;
public class TokenFlattener {
/**
* Flattens a nested authentication token structure into a single-level map.
* Handles potential null values gracefully.
*
* @param token The nested token structure (Map).
* @return A flattened map containing the token data, or an empty map if input is null.
*/
public static Map<String, String> flattenToken(Map<?, ?> token) {
Map<String, String> flattenedToken = new HashMap<>();
if (token == null) {
return flattenedToken; // Handle null input gracefully
}
flattenHelper(token, "", flattenedToken);
return flattenedToken;
}
private static void flattenHelper(Map<?, ?> token, String prefix, Map<String, String> flattenedToken) {
for (Map.Entry<?, ?> entry : token.entrySet()) {
String key = String.valueOf(entry.getKey()); // Convert key to string
String value = String.valueOf(entry.getValue()); // Convert value to string
String newKey = prefix.isEmpty() ? key : prefix + "." + key;
if (value == null) {
flattenedToken.put(newKey, null); // Handle null values
} else {
flattenedToken.put(newKey, value);
}
if (entry.getValue() instanceof Map) {
flattenHelper((Map<?, ?>) entry.getValue(), newKey, flattenedToken); // Recursive call for nested maps
}
}
}
public static void main(String[] args) {
// Example usage:
Map<String, Object> nestedToken = new HashMap<>();
nestedToken.put("username", "testuser");
nestedToken.put("details", new HashMap<>());
Map<String, Object> details = new HashMap<>();
details.put("email", "test@example.com");
details.put("role", "user");
nestedToken.put("permissions", new HashMap<>());
Map<String, String> flattened = flattenToken(nestedToken);
System.out.println(flattened);
}
}
Add your comment