1. import java.util.List;
  2. public class URLValidator {
  3. /**
  4. * Validates a list of URLs against specified conditions.
  5. * Supports older Java versions (Java 8 and below).
  6. * @param urls The list of URLs to validate.
  7. * @param conditions A list of validation conditions. Each condition is a string.
  8. * Example: ["startsWith://", "endsWith/.html", "contains/login"]
  9. * @return true if all URLs satisfy all conditions, false otherwise.
  10. */
  11. public static boolean validateURLs(List<String> urls, List<String> conditions) {
  12. if (urls == null || conditions == null || urls.isEmpty() || conditions.isEmpty()) {
  13. return true; // Consider empty lists as valid
  14. }
  15. for (String url : urls) {
  16. boolean passesAllConditions = true;
  17. for (String condition : conditions) {
  18. if (!satisfiesCondition(url, condition)) {
  19. passesAllConditions = false;
  20. break;
  21. }
  22. }
  23. if (!passesAllConditions) {
  24. return false; // If any URL fails a condition, return false immediately
  25. }
  26. }
  27. return true; // All URLs satisfy all conditions
  28. }
  29. /**
  30. * Checks if a URL satisfies a specific condition.
  31. * @param url The URL to check.
  32. * @param condition The condition to check against (e.g., "startsWith://", "endsWith/.html").
  33. * @return true if the URL satisfies the condition, false otherwise.
  34. */
  35. private static boolean satisfiesCondition(String url, String condition) {
  36. if (condition.startsWith("startsWith:")) {
  37. String prefix = condition.substring("startsWith:".length());
  38. return url.startsWith(prefix);
  39. } else if (condition.startsWith("endsWith:")) {
  40. String suffix = condition.substring("endsWith:".length());
  41. return url.endsWith(suffix);
  42. } else if (condition.startsWith("contains:")) {
  43. String substring = condition.substring("contains:".length());
  44. return url.contains(substring);
  45. } else {
  46. return false; // Unknown condition
  47. }
  48. }
  49. public static void main(String[] args) {
  50. //Example Usage:
  51. List<String> urls = List.of("https://www.example.com", "http://example.org/page.html", "ftp://files.example.com", "example.com");
  52. List<String> conditions = List.of("startsWith://", "endsWith/.html", "contains/example");
  53. boolean isValid = validateURLs(urls, conditions);
  54. System.out.println("URLs are valid: " + isValid); // Expected: false
  55. urls = List.of("https://www.example.com", "http://example.org/page.html", "https://files.example.com/document.pdf");
  56. conditions = List.of("startsWith://", "endsWith/.html", "endsWith/.pdf");
  57. isValid = validateURLs(urls, conditions);
  58. System.out.println("URLs are valid: " + isValid); // Expected: true
  59. }
  60. }

Add your comment