1. import java.util.HashMap;
  2. import java.util.Map;
  3. public class TokenFlattener {
  4. /**
  5. * Flattens a nested authentication token structure into a single-level map.
  6. * Handles potential null values gracefully.
  7. *
  8. * @param token The nested token structure (Map).
  9. * @return A flattened map containing the token data, or an empty map if input is null.
  10. */
  11. public static Map<String, String> flattenToken(Map<?, ?> token) {
  12. Map<String, String> flattenedToken = new HashMap<>();
  13. if (token == null) {
  14. return flattenedToken; // Handle null input gracefully
  15. }
  16. flattenHelper(token, "", flattenedToken);
  17. return flattenedToken;
  18. }
  19. private static void flattenHelper(Map<?, ?> token, String prefix, Map<String, String> flattenedToken) {
  20. for (Map.Entry<?, ?> entry : token.entrySet()) {
  21. String key = String.valueOf(entry.getKey()); // Convert key to string
  22. String value = String.valueOf(entry.getValue()); // Convert value to string
  23. String newKey = prefix.isEmpty() ? key : prefix + "." + key;
  24. if (value == null) {
  25. flattenedToken.put(newKey, null); // Handle null values
  26. } else {
  27. flattenedToken.put(newKey, value);
  28. }
  29. if (entry.getValue() instanceof Map) {
  30. flattenHelper((Map<?, ?>) entry.getValue(), newKey, flattenedToken); // Recursive call for nested maps
  31. }
  32. }
  33. }
  34. public static void main(String[] args) {
  35. // Example usage:
  36. Map<String, Object> nestedToken = new HashMap<>();
  37. nestedToken.put("username", "testuser");
  38. nestedToken.put("details", new HashMap<>());
  39. Map<String, Object> details = new HashMap<>();
  40. details.put("email", "test@example.com");
  41. details.put("role", "user");
  42. nestedToken.put("permissions", new HashMap<>());
  43. Map<String, String> flattened = flattenToken(nestedToken);
  44. System.out.println(flattened);
  45. }
  46. }

Add your comment