5ba90973b23a7352372bbd493a5c727a0b9670b9
[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
211   }
212
213   /**
214    * Reads the given html file and checks any href attibute values are either
215    * <ul>
216    * <li>a valid relative file path, or</li>
217    * <li>a valid absolute URL (if external link checking is enabled)</li>
218    * </ul>
219    * 
220    * @param htmlFile
221    * @param htmlFolder
222    *          the parent folder (for validation of relative paths)
223    */
224   private void checkHtmlFile(File htmlFile, File htmlFolder)
225           throws IOException
226   {
227     BufferedReader br = new BufferedReader(new FileReader(htmlFile));
228     String data = br.readLine();
229     int lineNo = 0;
230     while (data != null)
231     {
232       lineNo++;
233       String href = getAttribute(data, "href");
234       if (href != null)
235       {
236         String anchor = null;
237         int anchorPos = href.indexOf("#");
238         if (anchorPos != -1)
239         {
240           anchor = href.substring(anchorPos + 1);
241           href = href.substring(0, anchorPos);
242         }
243         boolean badLink = false;
244         if (href.startsWith("http"))
245         {
246           externalHrefCount++;
247           if (internetAvailable)
248           {
249             if (!connectToUrl(href))
250             {
251               badLink = true;
252               invalidExternalHrefCount++;
253             }
254           }
255         }
256         else
257         {
258           internalHrefCount++;
259           File hrefFile = href.equals("") ? htmlFile : new File(htmlFolder,
260                   href);
261           if (!hrefFile.exists())
262           {
263             badLink = true;
264             invalidInternalHrefCount++;
265           }
266           if (anchor != null)
267           {
268             anchorRefCount++;
269             if (!badLink)
270             {
271               if (!checkAnchorExists(hrefFile, anchor))
272               {
273                 System.out.println(String.format(
274                         "Invalid anchor: %s at line %d of %s", anchor,
275                         lineNo, getPath(htmlFile)));
276                 invalidAnchorRefCount++;
277               }
278             }
279           }
280         }
281         if (badLink)
282         {
283           System.out.println(String.format(
284                   "Invalid href %s at line %d of %s", href, lineNo,
285                   getPath(htmlFile)));
286         }
287       }
288       data = br.readLine();
289     }
290     br.close();
291   }
292
293   /**
294    * Reads the file and checks for the presence of the given html anchor
295    * 
296    * @param hrefFile
297    * @param anchor
298    * @return true if anchor is found else false
299    */
300   private boolean checkAnchorExists(File hrefFile, String anchor)
301   {
302     String nameAnchor = "<a name=\"" + anchor + "\"";
303     String idAnchor = "<a id=\"" + anchor + "\"";
304     boolean found = false;
305     try
306     {
307       BufferedReader br = new BufferedReader(new FileReader(hrefFile));
308       String data = br.readLine();
309       while (data != null)
310       {
311         if (data.contains(nameAnchor) || data.contains(idAnchor))
312         {
313           found = true;
314           break;
315         }
316         data = br.readLine();
317       }
318       br.close();
319     } catch (IOException e)
320     {
321       // ignore
322     }
323     return found;
324   }
325
326   /**
327    * Returns the part of the file path starting from /help/
328    * 
329    * @param helpFile
330    * @return
331    */
332   private String getPath(File helpFile)
333   {
334     String path = helpFile.getPath();
335     int helpPos = path.indexOf("/help/");
336     return helpPos == -1 ? path : path.substring(helpPos);
337   }
338
339   /**
340    * Returns true if the URL returns an input stream, or false if the URL
341    * returns an error code or we cannot connect to it (e.g. no internet
342    * available)
343    * 
344    * @param url
345    * @return
346    */
347   private boolean connectToUrl(String url)
348   {
349     try
350     {
351       URL u = new URL(url);
352       InputStream connection = u.openStream();
353       connection.close();
354       return true;
355     } catch (Throwable t)
356     {
357       return false;
358     }
359   }
360
361   /**
362    * Reads file help.jhm and checks that
363    * <ul>
364    * <li>each target attribute is in tocTargets</li>
365    * <li>each url attribute is a valid relative file link</li>
366    * </ul>
367    * 
368    * @param helpFolder
369    */
370   private Map<String, String> checkHelpMappings(File helpFolder)
371           throws IOException
372   {
373     Map<String, String> targets = new HashMap<String, String>();
374     BufferedReader br = new BufferedReader(new FileReader(new File(
375             helpFolder, HELP_JHM)));
376     String data = br.readLine();
377     int lineNo = 0;
378     while (data != null)
379     {
380       lineNo++;
381
382       /*
383        * record target, check for duplicates
384        */
385       String target = getAttribute(data, "target");
386       if (target != null)
387       {
388         mapCount++;
389         if (targets.containsKey(target))
390         {
391           System.out.println(String.format(
392                   "Duplicate target mapping to %s at line %d of %s",
393                   target, lineNo, HELP_JHM));
394         }
395         else
396         {
397           targetCount++;
398         }
399       }
400
401       /*
402        * validate url
403        */
404       String url = getAttribute(data, "url");
405       if (url != null)
406       {
407         targets.put(target, url);
408         int anchorPos = url.indexOf("#");
409         if (anchorPos != -1)
410         {
411           url = url.substring(0, anchorPos);
412         }
413         if (!new File(helpFolder, url).exists())
414         {
415           System.out.println(String.format(
416                   "Invalid url path '%s' at line %d of %s", url, lineNo,
417                   HELP_JHM));
418           invalidMapUrlCount++;
419         }
420       }
421       data = br.readLine();
422     }
423     br.close();
424     return targets;
425   }
426
427   /**
428    * Reads file helpTOC.xml and reports any invalid targets
429    * 
430    * @param helpFolder
431    * @param tocTargets
432    * @param unusedTargets
433    *          used targets are removed from this map
434    * 
435    * @return
436    * @throws IOException
437    */
438   private void checkTableOfContents(File helpFolder,
439           Map<String, String> tocTargets, Map<String, String> unusedTargets)
440           throws IOException
441   {
442     BufferedReader br = new BufferedReader(new FileReader(new File(
443             helpFolder, HELP_TOC_XML)));
444     String data = br.readLine();
445     int lineNo = 0;
446     while (data != null)
447     {
448       lineNo++;
449       /*
450        * assuming no more than one "target" per line of file here
451        */
452       String target = getAttribute(data, "target");
453       if (target != null)
454       {
455         unusedTargets.remove(target);
456         if (!tocTargets.containsKey(target))
457         {
458           System.out.println(String.format(
459                   "Invalid target '%s' at line %d of %s", target, lineNo,
460                   HELP_TOC_XML));
461           invalidTargetCount++;
462         }
463       }
464       data = br.readLine();
465     }
466     br.close();
467   }
468
469   /**
470    * Returns the value of an attribute if found in the data, else null
471    * 
472    * @param data
473    * @param attName
474    * @return
475    */
476   private static String getAttribute(String data, String attName)
477   {
478     /*
479      * make a partial attempt at ignoring within <!-- html comments -->
480      * (doesn't work if multi-line)
481      */
482     int commentStartPos = data.indexOf("<!--");
483     int commentEndPos = commentStartPos == -1 ? -1 : data.substring(
484             commentStartPos + 4).indexOf("-->");
485     String value = null;
486     String match = attName + "=\"";
487     int attPos = data.indexOf(match);
488     if (attPos > 0
489             && (commentStartPos == -1 || attPos < commentStartPos || attPos > commentEndPos))
490     {
491       data = data.substring(attPos + match.length());
492       value = data.substring(0, data.indexOf("\""));
493     }
494     return value;
495   }
496 }