55import java .net .URI ;
66import java .net .URL ;
77import org .openqa .selenium .WebElement ;
8+ import org .slf4j .Logger ;
9+ import org .slf4j .LoggerFactory ;
810
911public 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