import java.util.HashMap;
import java.util.Map;
public class CookieValidator {
/**
* Validates cookie configuration against hard-coded limits.
* @param cookieConfig A map containing cookie names and their values (e.g., {"cookie1": "value1", "cookie2": "value2"}).
* @return true if the cookie configuration is valid, false otherwise.
*/
public static boolean validateCookies(Map<String, String> cookieConfig) {
// Hard-coded limits for cookie counts and sizes.
final int MAX_COOKIES = 10;
final int MAX_COOKIE_SIZE = 1024; // in bytes
// Check if the number of cookies exceeds the maximum limit.
if (cookieConfig.size() > MAX_COOKIES) {
System.out.println("Error: Too many cookies. Maximum allowed: " + MAX_COOKIES);
return false;
}
// Validate individual cookie sizes.
for (Map.Entry<String, String> entry : cookieConfig.entrySet()) {
String cookieName = entry.getKey();
String cookieValue = entry.getValue();
if (cookieValue == null) {
System.out.println("Error: Cookie value cannot be null for cookie: " + cookieName);
return false;
}
if (cookieValue.getBytes().length > MAX_COOKIE_SIZE) {
System.out.println("Error: Cookie size exceeds limit for cookie: " + cookieName + ". Maximum allowed: " + MAX_COOKIE_SIZE);
return false;
}
}
// If all checks pass, the cookie configuration is valid.
return true;
}
public static void main(String[] args) {
// Example usage
Map<String, String> config1 = new HashMap<>();
config1.put("sessionID", "abcdef123456");
config1.put("preferences", "{\"theme\": \"dark\", \"language\": \"en\"}"); //Example JSON string
System.out.println("Config 1 is valid: " + validateCookies(config1)); // Expected: true
Map<String, String> config2 = new HashMap<>();
config2.put("cookie1", "value1");
config2.put("cookie2", "value2");
config2.put("cookie3", "value3");
config2.put("cookie4", "value4");
config2.put("cookie5", "value5");
config2.put("cookie6", "value6");
config2.put("cookie7", "value7");
config2.put("cookie8", "value8");
config2.put("cookie9", "value9");
config2.put("cookie10", "value10");
System.out.println("Config 2 is valid: " + validateCookies(config2)); // Expected: false (too many cookies)
Map<String, String> config3 = new HashMap<>();
config3.put("longCookie", "a".repeat(1025));
System.out.println("Config 3 is valid: " + validateCookies(config3)); //Expected: false (cookie size too big)
Map<String, String> config4 = new HashMap<>();
config4.put("nullCookie", null);
System.out.println("Config 4 is valid: " + validateCookies(config4)); //Expected: false (Null cookie value)
}
}
Add your comment