JAL-2119 non-zero exit if any invalid links
[jalview.git] / utils / HelpLinksChecker.java
1
2
3 import java.io.BufferedReader;
4 import java.io.File;
5 import java.io.FileReader;
6 import java.io.IOException;
7 import java.io.InputStream;
8 import java.net.URL;
9 import java.util.HashMap;
10 import java.util.Map;
11
12 /**
13  * A class to check help file cross-references, and external URLs if internet
14  * access is available
15  * 
16  * @author gmcarstairs
17  *
18  */
19 public class HelpLinksChecker
20 {
21   private static final String HELP_HS = "help.hs";
22
23   private static final String HELP_TOC_XML = "helpTOC.xml";
24
25   private static final String HELP_JHM = "help.jhm";
26
27   private static boolean internetAvailable = true;
28
29   private int targetCount = 0;
30
31   private int mapCount = 0;
32
33   private int internalHrefCount = 0;
34
35   private int anchorRefCount = 0;
36
37   private int invalidAnchorRefCount = 0;
38
39   private int externalHrefCount = 0;
40
41   private int invalidMapUrlCount = 0;
42
43   private int invalidTargetCount = 0;
44
45   private int invalidImageCount = 0;
46
47   private int invalidInternalHrefCount = 0;
48
49   private int invalidExternalHrefCount = 0;
50
51   /**
52    * The only parameter should be a path to the root of the help directory in
53    * the workspace
54    * 
55    * @param args
56    *          [0] path to the /html folder in the workspace
57    * @param args
58    *          [1] (optional) -nointernet to suppress external link checking for
59    *          a fast check of internal links only
60    * @throws IOException
61    */
62   public static void main(String[] args) throws IOException
63   {
64     if (args.length == 0 || args.length > 2
65             || (args.length == 2 && !args[1].equals("-nointernet")))
66     {
67       System.out.println("Usage: <pathToHelpFolder> [-nointernet]");
68       return;
69     }
70
71     if (args.length == 2)
72     {
73       internetAvailable = false;
74     }
75
76     new HelpLinksChecker().checkLinks(args[0]);
77   }
78
79   /**
80    * Checks help links and reports results
81    * 
82    * @param helpDirectoryPath
83    * @throws IOException
84    */
85   void checkLinks(String helpDirectoryPath) throws IOException
86   {
87     System.out.println("Checking help file links");
88     File helpFolder = new File(helpDirectoryPath);
89     if (!helpFolder.exists())
90     {
91       System.out.println("Can't find " + helpDirectoryPath);
92       return;
93     }
94
95     internetAvailable &= connectToUrl("http://www.example.org");
96
97     Map<String, String> tocTargets = checkHelpMappings(helpFolder);
98
99     Map<String, String> unusedTargets = new HashMap<String, String>(
100             tocTargets);
101
102     checkTableOfContents(helpFolder, tocTargets, unusedTargets);
103
104     checkHelpSet(helpFolder, tocTargets, unusedTargets);
105
106     checkHtmlFolder(new File(helpFolder, "html"));
107
108     reportResults(unusedTargets);
109   }
110
111   /**
112    * Checks all html files in the given directory or its sub-directories
113    * 
114    * @param folder
115    * @throws IOException
116    */
117   private void checkHtmlFolder(File folder) throws IOException
118   {
119     File[] files = folder.listFiles();
120     for (File f : files)
121     {
122       if (f.isDirectory())
123       {
124         checkHtmlFolder(f);
125       }
126       else
127       {
128         if (f.getAbsolutePath().endsWith(".html"))
129         {
130           checkHtmlFile(f, folder);
131         }
132       }
133     }
134   }
135
136   /**
137    * Checks that any image attribute in help.hs is a valid target
138    * 
139    * @param helpFolder
140    * @param tocTargets
141    * @param unusedTargets
142    *          used targets are removed from here
143    */
144   private void checkHelpSet(File helpFolder,
145           Map<String, String> tocTargets, Map<String, String> unusedTargets)
146           throws IOException
147   {
148     BufferedReader br = new BufferedReader(new FileReader(new File(
149             helpFolder, HELP_HS)));
150     String data = br.readLine();
151     int lineNo = 0;
152
153     while (data != null)
154     {
155       lineNo++;
156       String image = getAttribute(data, "image");
157       if (image != null)
158       {
159         unusedTargets.remove(image);
160         if (!tocTargets.containsKey(image))
161         {
162           System.out.println(String.format(
163                   "Invalid image '%s' at line %d of %s", image, lineNo,
164                   HELP_HS));
165           invalidImageCount++;
166         }
167       }
168       data = br.readLine();
169     }
170     br.close();
171   }
172
173   /**
174    * Print counts to sysout
175    * 
176    * @param unusedTargets
177    */
178   private void reportResults(Map<String, String> unusedTargets)
179   {
180     System.out.println("\nResults:");
181     System.out.println(targetCount + " distinct help targets");
182     System.out.println(mapCount + " help mappings");
183     System.out.println(invalidTargetCount + " invalid targets");
184     System.out.println(unusedTargets.size() + " unused targets");
185     for (String target : unusedTargets.keySet())
186     {
187       System.out.println(String.format("    %s: %s", target,
188               unusedTargets.get(target)));
189     }
190     System.out.println(invalidMapUrlCount + " invalid map urls");
191     System.out.println(invalidImageCount + " invalid image attributes");
192     System.out.println(String.format(
193             "%d internal href links (%d with anchors - not checked)",
194             internalHrefCount, anchorRefCount));
195     System.out.println(invalidInternalHrefCount
196             + " invalid internal href links");
197     System.out.println(invalidAnchorRefCount
198             + " invalid internal anchor links");
199     System.out.println(externalHrefCount + " external href links");
200     if (internetAvailable)
201     {
202       System.out.println(invalidExternalHrefCount
203               + " invalid external href links");
204     }
205     else
206     {
207       System.out
208               .println("External links not verified as internet not available");
209     }
210     if (invalidInternalHrefCount > 0 || invalidExternalHrefCount > 0
211             || invalidImageCount > 0 || invalidAnchorRefCount > 0)
212     {
213       System.exit(1);
214     }
215   }
216
217   /**
218    * Reads the given html file and checks any href attibute values are either
219    * <ul>
220    * <li>a valid relative file path, or</li>
221    * <li>a valid absolute URL (if external link checking is enabled)</li>
222    * </ul>
223    * 
224    * @param htmlFile
225    * @param htmlFolder
226    *          the parent folder (for validation of relative paths)
227    */
228   private void checkHtmlFile(File htmlFile, File htmlFolder)
229           throws IOException
230   {
231     BufferedReader br = new BufferedReader(new FileReader(htmlFile));
232     String data = br.readLine();
233     int lineNo = 0;
234     while (data != null)
235     {
236       lineNo++;
237       String href = getAttribute(data, "href");
238       if (href != null)
239       {
240         String anchor = null;
241         int anchorPos = href.indexOf("#");
242         if (anchorPos != -1)
243         {
244           anchor = href.substring(anchorPos + 1);
245           href = href.substring(0, anchorPos);
246         }
247         boolean badLink = false;
248         if (href.startsWith("http"))
249         {
250           externalHrefCount++;
251           if (internetAvailable)
252           {
253             if (!connectToUrl(href))
254             {
255               badLink = true;
256               invalidExternalHrefCount++;
257             }
258           }
259         }
260         else
261         {
262           internalHrefCount++;
263           File hrefFile = href.equals("") ? htmlFile : new File(htmlFolder,
264                   href);
265           if (!hrefFile.exists())
266           {
267             badLink = true;
268             invalidInternalHrefCount++;
269           }
270           if (anchor != null)
271           {
272             anchorRefCount++;
273             if (!badLink)
274             {
275               if (!checkAnchorExists(hrefFile, anchor))
276               {
277                 System.out.println(String.format(
278                         "Invalid anchor: %s at line %d of %s", anchor,
279                         lineNo, getPath(htmlFile)));
280                 invalidAnchorRefCount++;
281               }
282             }
283           }
284         }
285         if (badLink)
286         {
287           System.out.println(String.format(
288                   "Invalid href %s at line %d of %s", href, lineNo,
289                   getPath(htmlFile)));
290         }
291       }
292       data = br.readLine();
293     }
294     br.close();
295   }
296
297   /**
298    * Reads the file and checks for the presence of the given html anchor
299    * 
300    * @param hrefFile
301    * @param anchor
302    * @return true if anchor is found else false
303    */
304   private boolean checkAnchorExists(File hrefFile, String anchor)
305   {
306     String nameAnchor = "<a name=\"" + anchor + "\"";
307     String idAnchor = "<a id=\"" + anchor + "\"";
308     boolean found = false;
309     try
310     {
311       BufferedReader br = new BufferedReader(new FileReader(hrefFile));
312       String data = br.readLine();
313       while (data != null)
314       {
315         if (data.contains(nameAnchor) || data.contains(idAnchor))
316         {
317           found = true;
318           break;
319         }
320         data = br.readLine();
321       }
322       br.close();
323     } catch (IOException e)
324     {
325       // ignore
326     }
327     return found;
328   }
329
330   /**
331    * Returns the part of the file path starting from /help/
332    * 
333    * @param helpFile
334    * @return
335    */
336   private String getPath(File helpFile)
337   {
338     String path = helpFile.getPath();
339     int helpPos = path.indexOf("/help/");
340     return helpPos == -1 ? path : path.substring(helpPos);
341   }
342
343   /**
344    * Returns true if the URL returns an input stream, or false if the URL
345    * returns an error code or we cannot connect to it (e.g. no internet
346    * available)
347    * 
348    * @param url
349    * @return
350    */
351   private boolean connectToUrl(String url)
352   {
353     try
354     {
355       URL u = new URL(url);
356       InputStream connection = u.openStream();
357       connection.close();
358       return true;
359     } catch (Throwable t)
360     {
361       return false;
362     }
363   }
364
365   /**
366    * Reads file help.jhm and checks that
367    * <ul>
368    * <li>each target attribute is in tocTargets</li>
369    * <li>each url attribute is a valid relative file link</li>
370    * </ul>
371    * 
372    * @param helpFolder
373    */
374   private Map<String, String> checkHelpMappings(File helpFolder)
375           throws IOException
376   {
377     Map<String, String> targets = new HashMap<String, String>();
378     BufferedReader br = new BufferedReader(new FileReader(new File(
379             helpFolder, HELP_JHM)));
380     String data = br.readLine();
381     int lineNo = 0;
382     while (data != null)
383     {
384       lineNo++;
385
386       /*
387        * record target, check for duplicates
388        */
389       String target = getAttribute(data, "target");
390       if (target != null)
391       {
392         mapCount++;
393         if (targets.containsKey(target))
394         {
395           System.out.println(String.format(
396                   "Duplicate target mapping to %s at line %d of %s",
397                   target, lineNo, HELP_JHM));
398         }
399         else
400         {
401           targetCount++;
402         }
403       }
404
405       /*
406        * validate url
407        */
408       String url = getAttribute(data, "url");
409       if (url != null)
410       {
411         targets.put(target, url);
412         int anchorPos = url.indexOf("#");
413         if (anchorPos != -1)
414         {
415           url = url.substring(0, anchorPos);
416         }
417         if (!new File(helpFolder, url).exists())
418         {
419           System.out.println(String.format(
420                   "Invalid url path '%s' at line %d of %s", url, lineNo,
421                   HELP_JHM));
422           invalidMapUrlCount++;
423         }
424       }
425       data = br.readLine();
426     }
427     br.close();
428     return targets;
429   }
430
431   /**
432    * Reads file helpTOC.xml and reports any invalid targets
433    * 
434    * @param helpFolder
435    * @param tocTargets
436    * @param unusedTargets
437    *          used targets are removed from this map
438    * 
439    * @return
440    * @throws IOException
441    */
442   private void checkTableOfContents(File helpFolder,
443           Map<String, String> tocTargets, Map<String, String> unusedTargets)
444           throws IOException
445   {
446     BufferedReader br = new BufferedReader(new FileReader(new File(
447             helpFolder, HELP_TOC_XML)));
448     String data = br.readLine();
449     int lineNo = 0;
450     while (data != null)
451     {
452       lineNo++;
453       /*
454        * assuming no more than one "target" per line of file here
455        */
456       String target = getAttribute(data, "target");
457       if (target != null)
458       {
459         unusedTargets.remove(target);
460         if (!tocTargets.containsKey(target))
461         {
462           System.out.println(String.format(
463                   "Invalid target '%s' at line %d of %s", target, lineNo,
464                   HELP_TOC_XML));
465           invalidTargetCount++;
466         }
467       }
468       data = br.readLine();
469     }
470     br.close();
471   }
472
473   /**
474    * Returns the value of an attribute if found in the data, else null
475    * 
476    * @param data
477    * @param attName
478    * @return
479    */
480   private static String getAttribute(String data, String attName)
481   {
482     /*
483      * make a partial attempt at ignoring within <!-- html comments -->
484      * (doesn't work if multi-line)
485      */
486     int commentStartPos = data.indexOf("<!--");
487     int commentEndPos = commentStartPos == -1 ? -1 : data.substring(
488             commentStartPos + 4).indexOf("-->");
489     String value = null;
490     String match = attName + "=\"";
491     int attPos = data.indexOf(match);
492     if (attPos > 0
493             && (commentStartPos == -1 || attPos < commentStartPos || attPos > commentEndPos))
494     {
495       data = data.substring(attPos + match.length());
496       value = data.substring(0, data.indexOf("\""));
497     }
498     return value;
499   }
500 }