import java.util.List;
public class URLValidator {
/**
* Validates a list of URLs against specified conditions.
* Supports older Java versions (Java 8 and below).
* @param urls The list of URLs to validate.
* @param conditions A list of validation conditions. Each condition is a string.
* Example: ["startsWith://", "endsWith/.html", "contains/login"]
* @return true if all URLs satisfy all conditions, false otherwise.
*/
public static boolean validateURLs(List<String> urls, List<String> conditions) {
if (urls == null || conditions == null || urls.isEmpty() || conditions.isEmpty()) {
return true; // Consider empty lists as valid
}
for (String url : urls) {
boolean passesAllConditions = true;
for (String condition : conditions) {
if (!satisfiesCondition(url, condition)) {
passesAllConditions = false;
break;
}
}
if (!passesAllConditions) {
return false; // If any URL fails a condition, return false immediately
}
}
return true; // All URLs satisfy all conditions
}
/**
* Checks if a URL satisfies a specific condition.
* @param url The URL to check.
* @param condition The condition to check against (e.g., "startsWith://", "endsWith/.html").
* @return true if the URL satisfies the condition, false otherwise.
*/
private static boolean satisfiesCondition(String url, String condition) {
if (condition.startsWith("startsWith:")) {
String prefix = condition.substring("startsWith:".length());
return url.startsWith(prefix);
} else if (condition.startsWith("endsWith:")) {
String suffix = condition.substring("endsWith:".length());
return url.endsWith(suffix);
} else if (condition.startsWith("contains:")) {
String substring = condition.substring("contains:".length());
return url.contains(substring);
} else {
return false; // Unknown condition
}
}
public static void main(String[] args) {
//Example Usage:
List<String> urls = List.of("https://www.example.com", "http://example.org/page.html", "ftp://files.example.com", "example.com");
List<String> conditions = List.of("startsWith://", "endsWith/.html", "contains/example");
boolean isValid = validateURLs(urls, conditions);
System.out.println("URLs are valid: " + isValid); // Expected: false
urls = List.of("https://www.example.com", "http://example.org/page.html", "https://files.example.com/document.pdf");
conditions = List.of("startsWith://", "endsWith/.html", "endsWith/.pdf");
isValid = validateURLs(urls, conditions);
System.out.println("URLs are valid: " + isValid); // Expected: true
}
}
Add your comment