1. import java.util.HashMap;
  2. import java.util.Map;
  3. public class MetadataTruncator {
  4. /**
  5. * Truncates metadata fields for sandbox usage.
  6. *
  7. * @param metadata The original metadata as a Map.
  8. * @param truncationMap A map specifying fields to truncate and the desired length.
  9. * Key: field name (String), Value: maximum length (int).
  10. * @return A new Map with truncated metadata.
  11. */
  12. public static Map<String, Object> truncateMetadata(Map<String, Object> metadata, Map<String, Integer> truncationMap) {
  13. Map<String, Object> truncatedMetadata = new HashMap<>(metadata); // Create a copy to avoid modifying the original
  14. if (truncationMap != null) {
  15. for (Map.Entry<String, Integer> entry : truncationMap.entrySet()) {
  16. String fieldName = entry.getKey();
  17. Integer maxLength = entry.getValue();
  18. if (truncatedMetadata.containsKey(fieldName)) {
  19. Object value = truncatedMetadata.get(fieldName);
  20. if (value instanceof String) {
  21. truncatedMetadata.put(fieldName, ((String) value).substring(0, maxLength));
  22. } else if (value instanceof Number) {
  23. //Handle numbers. Truncate to a reasonable representation.
  24. truncatedMetadata.put(fieldName, ((Number) value).intValue()); //convert to int
  25. } else if (value instanceof Long) {
  26. truncatedMetadata.put(fieldName, ((Long) value).longValue());
  27. }
  28. else if (value instanceof Boolean)
  29. {
  30. truncatedMetadata.put(fieldName, value);
  31. }
  32. else {
  33. truncatedMetadata.put(fieldName, value); //Keep other types as they are
  34. }
  35. }
  36. }
  37. }
  38. return truncatedMetadata;
  39. }
  40. public static void main(String[] args) {
  41. //Example Usage
  42. Map<String, Object> metadata = new HashMap<>();
  43. metadata.put("name", "This is a very long name");
  44. metadata.put("description", "A detailed description of the item.");
  45. metadata.put("age", 30);
  46. metadata.put("score", 1234567890);
  47. metadata.put("isActive", true);
  48. Map<String, Integer> truncationMap = new HashMap<>();
  49. truncationMap.put("name", 10);
  50. truncationMap.put("description", 20);
  51. truncationMap.put("score", 8);
  52. Map<String, Object> truncated = truncateMetadata(metadata, truncationMap);
  53. System.out.println(truncated);
  54. }
  55. }

Add your comment