import java.util.HashMap;
import java.util.Map;
public class UserDataNormalizer {
/**
* Normalizes user data, performs basic sanity checks, and returns a normalized map.
* @param userData A map of user data.
* @return A normalized map of user data or null if normalization fails.
*/
public static Map<String, Object> normalizeUserData(Map<String, Object> userData) {
if (userData == null || userData.isEmpty()) {
return null; // Handle null or empty input
}
Map<String, Object> normalizedData = new HashMap<>();
// Normalize and validate user ID
Object userId = userData.get("userId");
if (!(userId instanceof String)) {
System.err.println("Error: userId must be a string.");
return null;
}
normalizedData.put("userId", (String) userId);
// Normalize and validate username
Object username = userData.get("username");
if (!(username instanceof String)) {
System.err.println("Error: username must be a string.");
return null;
}
normalizedData.put("username", (String) username);
// Normalize and validate email
Object email = userData.get("email");
if (!(email instanceof String)) {
System.err.println("Error: email must be a string.");
return null;
}
String normalizedEmail = email.toString().trim().toLowerCase();
if (!normalizedEmail.matches("^[\\w-\\.]+@([\\w-]+\\.)+[\\w-]{2,4}$")) {
System.err.println("Error: Invalid email format.");
return null;
}
normalizedData.put("email", normalizedEmail);
// Normalize and validate age
Object age = userData.get("age");
if (!(age instanceof Integer)) {
System.err.println("Error: age must be an integer.");
return null;
}
int normalizedAge = Math.max(0, Math.min(150, (int) age)); // Ensure age is within reasonable bounds
normalizedData.put("age", normalizedAge);
// Normalize and validate registration date
Object registrationDate = userData.get("registrationDate");
if (!(registrationDate instanceof String)) {
System.err.println("Error: registrationDate must be a string.");
return null;
}
normalizedData.put("registrationDate", registrationDate);
return normalizedData;
}
public static void main(String[] args) {
// Example usage
Map<String, Object> userData = new HashMap<>();
userData.put("userId", "123");
userData.put("username", "JohnDoe");
userData.put("email", "john.doe@example.com");
userData.put("age", 30);
userData.put("registrationDate", "2023-01-15");
Map<String, Object> normalizedData = normalizeUserData(userData);
if (normalizedData != null) {
System.out.println("Normalized User Data: " + normalizedData);
} else {
System.out.println("Normalization failed.");
}
//Example of failure
Map<String, Object> badData = new HashMap<>();
badData.put("userId", 123);
badData.put("username", "JohnDoe");
badData.put("email", 123);
Map<String, Object> normalizedBadData = normalizeUserData(badData);
if (normalizedBadData == null) {
System.out.println("Bad data normalization failed as expected");
}
}
}
Add your comment