import java.util.HashMap;
import java.util.Map;
public class MetadataTruncator {
/**
* Truncates metadata fields for sandbox usage.
*
* @param metadata The original metadata as a Map.
* @param truncationMap A map specifying fields to truncate and the desired length.
* Key: field name (String), Value: maximum length (int).
* @return A new Map with truncated metadata.
*/
public static Map<String, Object> truncateMetadata(Map<String, Object> metadata, Map<String, Integer> truncationMap) {
Map<String, Object> truncatedMetadata = new HashMap<>(metadata); // Create a copy to avoid modifying the original
if (truncationMap != null) {
for (Map.Entry<String, Integer> entry : truncationMap.entrySet()) {
String fieldName = entry.getKey();
Integer maxLength = entry.getValue();
if (truncatedMetadata.containsKey(fieldName)) {
Object value = truncatedMetadata.get(fieldName);
if (value instanceof String) {
truncatedMetadata.put(fieldName, ((String) value).substring(0, maxLength));
} else if (value instanceof Number) {
//Handle numbers. Truncate to a reasonable representation.
truncatedMetadata.put(fieldName, ((Number) value).intValue()); //convert to int
} else if (value instanceof Long) {
truncatedMetadata.put(fieldName, ((Long) value).longValue());
}
else if (value instanceof Boolean)
{
truncatedMetadata.put(fieldName, value);
}
else {
truncatedMetadata.put(fieldName, value); //Keep other types as they are
}
}
}
}
return truncatedMetadata;
}
public static void main(String[] args) {
//Example Usage
Map<String, Object> metadata = new HashMap<>();
metadata.put("name", "This is a very long name");
metadata.put("description", "A detailed description of the item.");
metadata.put("age", 30);
metadata.put("score", 1234567890);
metadata.put("isActive", true);
Map<String, Integer> truncationMap = new HashMap<>();
truncationMap.put("name", 10);
truncationMap.put("description", 20);
truncationMap.put("score", 8);
Map<String, Object> truncated = truncateMetadata(metadata, truncationMap);
System.out.println(truncated);
}
}
Add your comment