1. import java.util.HashMap;
  2. import java.util.Map;
  3. public class CookieValidator {
  4. /**
  5. * Validates cookie configuration against hard-coded limits.
  6. * @param cookieConfig A map containing cookie names and their values (e.g., {"cookie1": "value1", "cookie2": "value2"}).
  7. * @return true if the cookie configuration is valid, false otherwise.
  8. */
  9. public static boolean validateCookies(Map<String, String> cookieConfig) {
  10. // Hard-coded limits for cookie counts and sizes.
  11. final int MAX_COOKIES = 10;
  12. final int MAX_COOKIE_SIZE = 1024; // in bytes
  13. // Check if the number of cookies exceeds the maximum limit.
  14. if (cookieConfig.size() > MAX_COOKIES) {
  15. System.out.println("Error: Too many cookies. Maximum allowed: " + MAX_COOKIES);
  16. return false;
  17. }
  18. // Validate individual cookie sizes.
  19. for (Map.Entry<String, String> entry : cookieConfig.entrySet()) {
  20. String cookieName = entry.getKey();
  21. String cookieValue = entry.getValue();
  22. if (cookieValue == null) {
  23. System.out.println("Error: Cookie value cannot be null for cookie: " + cookieName);
  24. return false;
  25. }
  26. if (cookieValue.getBytes().length > MAX_COOKIE_SIZE) {
  27. System.out.println("Error: Cookie size exceeds limit for cookie: " + cookieName + ". Maximum allowed: " + MAX_COOKIE_SIZE);
  28. return false;
  29. }
  30. }
  31. // If all checks pass, the cookie configuration is valid.
  32. return true;
  33. }
  34. public static void main(String[] args) {
  35. // Example usage
  36. Map<String, String> config1 = new HashMap<>();
  37. config1.put("sessionID", "abcdef123456");
  38. config1.put("preferences", "{\"theme\": \"dark\", \"language\": \"en\"}"); //Example JSON string
  39. System.out.println("Config 1 is valid: " + validateCookies(config1)); // Expected: true
  40. Map<String, String> config2 = new HashMap<>();
  41. config2.put("cookie1", "value1");
  42. config2.put("cookie2", "value2");
  43. config2.put("cookie3", "value3");
  44. config2.put("cookie4", "value4");
  45. config2.put("cookie5", "value5");
  46. config2.put("cookie6", "value6");
  47. config2.put("cookie7", "value7");
  48. config2.put("cookie8", "value8");
  49. config2.put("cookie9", "value9");
  50. config2.put("cookie10", "value10");
  51. System.out.println("Config 2 is valid: " + validateCookies(config2)); // Expected: false (too many cookies)
  52. Map<String, String> config3 = new HashMap<>();
  53. config3.put("longCookie", "a".repeat(1025));
  54. System.out.println("Config 3 is valid: " + validateCookies(config3)); //Expected: false (cookie size too big)
  55. Map<String, String> config4 = new HashMap<>();
  56. config4.put("nullCookie", null);
  57. System.out.println("Config 4 is valid: " + validateCookies(config4)); //Expected: false (Null cookie value)
  58. }
  59. }

Add your comment