1. import java.util.ArrayList;
  2. import java.util.List;
  3. import java.util.regex.Matcher;
  4. import java.util.regex.Pattern;
  5. public class URLValidator {
  6. /**
  7. * Validates a list of URLs with basic sanity checks.
  8. *
  9. * @param urls A list of URLs to validate.
  10. * @return A list of error messages, one for each invalid URL. Returns an empty list if all URLs are valid.
  11. */
  12. public static List<String> validateURLs(List<String> urls) {
  13. List<String> errors = new ArrayList<>();
  14. if (urls == null) {
  15. errors.add("Input URL list is null.");
  16. return errors;
  17. }
  18. for (String url : urls) {
  19. if (url == null || url.isEmpty()) {
  20. errors.add("URL is null or empty: " + url);
  21. continue;
  22. }
  23. if (!isValidURLFormat(url)) {
  24. errors.add("Invalid URL format: " + url);
  25. } else {
  26. //Further checks can be added here (e.g., domain existence, protocol check)
  27. }
  28. }
  29. return errors;
  30. }
  31. private static boolean isValidURLFormat(String url) {
  32. // Basic regex for URL format validation. Not exhaustive.
  33. String regex = "^(http(s)?://)?([\\w-]+\\.)+[\\w-]+(/[\\w- ./?%&=]*)?$";
  34. Pattern pattern = Pattern.compile(regex);
  35. Matcher matcher = pattern.matcher(url);
  36. return matcher.matches();
  37. }
  38. public static void main(String[] args) {
  39. List<String> urls = new ArrayList<>();
  40. urls.add("https://www.example.com");
  41. urls.add("http://example.com");
  42. urls.add("invalid-url");
  43. urls.add(" ");
  44. urls.add(null);
  45. urls.add("https://example.com/path with spaces");
  46. List<String> errors = validateURLs(urls);
  47. if (errors.isEmpty()) {
  48. System.out.println("All URLs are valid.");
  49. } else {
  50. System.out.println("Invalid URLs:");
  51. for (String error : errors) {
  52. System.out.println(error);
  53. }
  54. }
  55. }
  56. }

Add your comment