Skip to content

Commit 5e85c3f

Browse files
authored
Update BrokenLinkChecker.java
1 parent a330353 commit 5e85c3f

File tree

1 file changed

+20
-7
lines changed

1 file changed

+20
-7
lines changed

java/src/org/openqa/selenium/support/BrokenLinkChecker.java

Lines changed: 20 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -5,24 +5,36 @@
55
import java.net.URI;
66
import java.net.URL;
77
import org.openqa.selenium.WebElement;
8+
import org.slf4j.Logger;
9+
import org.slf4j.LoggerFactory;
810

911
public final class BrokenLinkChecker {
1012

13+
private static final Logger logger = LoggerFactory.getLogger(BrokenLinkChecker.class); // Create a logger instance
14+
1115
private BrokenLinkChecker() {
1216
// Utility class - prevent instantiation
1317
}
1418

1519
public static boolean isBroken(WebElement element) {
20+
if (element == null) {
21+
throw new IllegalArgumentException("Element cannot be null"); // Validate element
22+
}
23+
1624
String url = element.getAttribute("href");
1725
if (url == null || url.trim().isEmpty()) {
18-
return false;
26+
return true; // Treat empty or null URLs as broken
1927
}
2028
return isBroken(url.trim());
2129
}
2230

2331
public static boolean isBroken(String linkURL) {
32+
if (linkURL == null) {
33+
throw new IllegalArgumentException("Link URL cannot be null"); // Validate linkURL
34+
}
35+
2436
try {
25-
URL url = URI.create(linkURL).toURL();
37+
URL url = URI.create(linkURL).toURL(); // This could throw IllegalArgumentException
2638
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
2739
connection.setRequestMethod("HEAD");
2840
connection.setConnectTimeout(5000); // 5 sec timeout
@@ -32,10 +44,11 @@ public static boolean isBroken(String linkURL) {
3244
int responseCode = connection.getResponseCode();
3345
connection.disconnect();
3446

35-
return responseCode >= 400;
36-
} catch (IOException e) {
37-
System.err.println("Error checking link: " + linkURL + " → " + e.getMessage());
38-
return true;
47+
return responseCode >= 400; // Broken link if response code is 400 or higher
48+
} catch (IOException | IllegalArgumentException e) {
49+
// Using SLF4J logger for logging the exception
50+
logger.warn("Error checking link: " + linkURL, e); // Log the exception with warning level
51+
return true; // Return true if any exception occurs (link is considered broken)
3952
}
4053
}
41-
}
54+
}

0 commit comments

Comments
 (0)