File: HelpLinksChecker.java

package info (click to toggle)
jalview 2.11.4.1%2Bdfsg-1
  • links: PTS, VCS
  • area: main
  • in suites: sid, trixie
  • size: 445,392 kB
  • sloc: java: 365,549; xml: 2,989; sh: 1,511; perl: 336; lisp: 139; python: 116; makefile: 81; haskell: 60
file content (559 lines) | stat: -rw-r--r-- 14,852 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
/*
 * Jalview - A Sequence Alignment Editor and Viewer (2.11.4.1)
 * Copyright (C) 2024 The Jalview Authors
 * 
 * This file is part of Jalview.
 * 
 * Jalview is free software: you can redistribute it and/or
 * modify it under the terms of the GNU General Public License 
 * as published by the Free Software Foundation, either version 3
 * of the License, or (at your option) any later version.
 *  
 * Jalview is distributed in the hope that it will be useful, but 
 * WITHOUT ANY WARRANTY; without even the implied warranty 
 * of MERCHANTABILITY or FITNESS FOR A PARTICULAR 
 * PURPOSE.  See the GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with Jalview.  If not, see <http://www.gnu.org/licenses/>.
 * The Jalview Authors are detailed in the 'AUTHORS' file.
 */
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

/**
 * A class to check help file cross-references, and external URLs if internet
 * access is available
 * 
 * @author gmcarstairs
 *
 */
public class HelpLinksChecker implements BufferedLineReader.LineCleaner
{
  private static final String HELP_HS = "help.hs";

  private static final String HELP_TOC_XML = "helpTOC.xml";

  private static final String HELP_JHM = "help.jhm";

  private static boolean internetAvailable = true;

  private int targetCount = 0;

  private int mapCount = 0;

  private int internalHrefCount = 0;

  private int anchorRefCount = 0;

  private int invalidAnchorRefCount = 0;

  private int externalHrefCount = 0;

  private int invalidMapUrlCount = 0;

  private int invalidTargetCount = 0;

  private int invalidImageCount = 0;

  private int invalidInternalHrefCount = 0;

  private int invalidExternalHrefCount = 0;

  /**
   * The only parameter should be a path to the root of the help directory in
   * the workspace
   * 
   * @param args
   *          [0] path to the /html folder in the workspace
   * @param args
   *          [1] (optional) -nointernet to suppress external link checking for
   *          a fast check of internal links only
   * @throws IOException
   */
  public static void main(String[] args) throws IOException
  {
    if (args.length == 0 || args.length > 2
            || (args.length == 2 && !args[1].equals("-nointernet")))
    {
      log("Usage: <pathToHelpFolder> [-nointernet]");
      return;
    }

    if (args.length == 2)
    {
      internetAvailable = false;
    }

    new HelpLinksChecker().checkLinks(args[0]);
  }

  /**
   * Checks help links and reports results
   * 
   * @param helpDirectoryPath
   * @throws IOException
   */
  void checkLinks(String helpDirectoryPath) throws IOException
  {
    log("Checking help file links");
    File helpFolder = new File(helpDirectoryPath).getCanonicalFile();
    if (!helpFolder.exists())
    {
      log("Can't find " + helpDirectoryPath);
      return;
    }

    internetAvailable &= connectToUrl("http://www.example.org");

    Map<String, String> tocTargets = checkHelpMappings(helpFolder);

    Map<String, String> unusedTargets = new HashMap<String, String>(
            tocTargets);

    checkTableOfContents(helpFolder, tocTargets, unusedTargets);

    checkHelpSet(helpFolder, tocTargets, unusedTargets);

    checkHtmlFolder(new File(helpFolder, "html"));

    reportResults(unusedTargets);
  }

  /**
   * Checks all html files in the given directory or its sub-directories
   * 
   * @param folder
   * @throws IOException
   */
  private void checkHtmlFolder(File folder) throws IOException
  {
    File[] files = folder.listFiles();
    for (File f : files)
    {
      if (f.isDirectory())
      {
        checkHtmlFolder(f);
      }
      else
      {
        if (f.getAbsolutePath().endsWith(".html"))
        {
          checkHtmlFile(f, folder);
        }
      }
    }
  }

  /**
   * Checks that any image attribute in help.hs is a valid target
   * 
   * @param helpFolder
   * @param tocTargets
   * @param unusedTargets
   *          used targets are removed from here
   */
  private void checkHelpSet(File helpFolder,
          Map<String, String> tocTargets, Map<String, String> unusedTargets)
          throws IOException
  {
    BufferedReader br = new BufferedReader(new FileReader(new File(
            helpFolder, HELP_HS)));
    String data = br.readLine();
    int lineNo = 0;

    while (data != null)
    {
      lineNo++;
      String image = getAttribute(data, "image");
      if (image != null)
      {
        unusedTargets.remove(image);
        if (!tocTargets.containsKey(image))
        {
          log(String.format("Invalid image '%s' at line %d of %s", image,
                  lineNo, HELP_HS));
          invalidImageCount++;
        }
      }
      data = br.readLine();
    }
    br.close();
  }

  /**
   * Print counts to sysout
   * 
   * @param unusedTargets
   */
  private void reportResults(Map<String, String> unusedTargets)
  {
    log("\nResults:");
    log(targetCount + " distinct help targets");
    log(mapCount + " help mappings");
    log(invalidTargetCount + " invalid targets");
    log(unusedTargets.size() + " unused targets");
    for (String target : unusedTargets.keySet())
    {
      log(String.format("    %s: %s", target, unusedTargets.get(target)));
    }
    log(invalidMapUrlCount + " invalid map urls");
    log(invalidImageCount + " invalid image attributes");
    log(String.format("%d internal href links (%d with anchors)",
            internalHrefCount, anchorRefCount));
    log(invalidInternalHrefCount + " invalid internal href links");
    log(invalidAnchorRefCount + " invalid internal anchor links");
    log(externalHrefCount + " external href links");
    if (internetAvailable)
    {
      log(invalidExternalHrefCount + " invalid external href links");
    }
    else
    {
      System.out
              .println("External links not verified as internet not available");
    }
    if (invalidInternalHrefCount > 0 || invalidExternalHrefCount > 0
            || invalidImageCount > 0 || invalidAnchorRefCount > 0)
    {
      log("*** Failed ***");
      System.exit(1);
    }
    log("*** Success ***");
  }

  /**
   * @param s
   */
  static void log(String s)
  {
    System.out.println(s);
  }

  /**
   * Reads the given html file and checks any href attibute values are either
   * <ul>
   * <li>a valid relative file path, or</li>
   * <li>a valid absolute URL (if external link checking is enabled)</li>
   * </ul>
   * 
   * @param htmlFile
   * @param htmlFolder
   *          the parent folder (for validation of relative paths)
   */
  private void checkHtmlFile(File htmlFile, File htmlFolder)
          throws IOException
  {
    BufferedReader br = new BufferedReader(new FileReader(htmlFile));
    String data = br.readLine();
    int lineNo = 0;
    while (data != null)
    {
      lineNo++;
      String href = getAttribute(data, "href");
      if (href != null)
      {
        String anchor = null;
        int anchorPos = href.indexOf("#");
        if (anchorPos != -1)
        {
          anchor = href.substring(anchorPos + 1);
          href = href.substring(0, anchorPos);
        }
        boolean badLink = false;
        if (href.startsWith("http"))
        {
          externalHrefCount++;
          if (internetAvailable)
          {
            if (!connectToUrl(href))
            {
              badLink = true;
              invalidExternalHrefCount++;
            }
          }
        }
        else
        {
          internalHrefCount++;
          String relFile = System.getProperty("os.name").indexOf("Win") > -1 ? href.replace("/", File.separator) : href;
          File hrefFile = href.equals("") ? htmlFile : new File(htmlFolder,
                  href);
          if (hrefFile != htmlFile && !fileExists(hrefFile, relFile))
          {
            badLink = true;
            invalidInternalHrefCount++;
          }
          if (anchor != null)
          {
            anchorRefCount++;
            if (!badLink)
            {
              if (!checkAnchorExists(hrefFile, anchor))
              {
                log(String.format("Invalid anchor: %s at line %d of %s",
                        anchor, lineNo, getPath(htmlFile)));
                invalidAnchorRefCount++;
              }
            }
          }
        }
        if (badLink)
        {
          log(String.format("Invalid href %s at line %d of %s", href,
                  lineNo, getPath(htmlFile)));
        }
      }
      data = br.readLine();
    }
    br.close();
  }

  /**
   * Performs a case-sensitive check that the href'd file exists
   * 
   * @param hrefFile
   * @return
   * @throws IOException
   */
  boolean fileExists(File hrefFile, String href) throws IOException
  {
    if (!hrefFile.exists())
    {
      return false;
    }

    /*
     * On Mac or Windows, file.exists() is not case sensitive, so do an
     * additional check with case sensitivity 
     */
    int slashPos = href.lastIndexOf(File.separator);
    String expectedFileName = slashPos == -1 ? href : href
            .substring(slashPos + 1);
    String cp = hrefFile.getCanonicalPath();
    slashPos = cp.lastIndexOf(File.separator);
    String actualFileName = slashPos == -1 ? cp : cp
            .substring(slashPos + 1);

    return expectedFileName.equals(actualFileName);
  }

  /**
   * Reads the file and checks for the presence of the given html anchor
   * 
   * @param hrefFile
   * @param anchor
   * @return true if anchor is found else false
   */
  private boolean checkAnchorExists(File hrefFile, String anchor)
  {
    String nameAnchor = "<a name=\"" + anchor + "\"";
    String idAnchor = "<a id=\"" + anchor + "\"";
    boolean found = false;
    try
    {
      BufferedReader br = new BufferedReader(new FileReader(hrefFile));
      BufferedLineReader blr = new BufferedLineReader(br, 3, this);
      String data = blr.read();
      while (data != null)
      {
        if (data.contains(nameAnchor) || data.contains(idAnchor))
        {
          found = true;
          break;
        }
        data = blr.read();
      }
      br.close();
    } catch (IOException e)
    {
      // ignore
    }
    return found;
  }

  /**
   * Returns the part of the file path starting from /help/
   * 
   * @param helpFile
   * @return
   */
  private String getPath(File helpFile)
  {
    String path = helpFile.getPath();
    int helpPos = path.indexOf("/help/");
    return helpPos == -1 ? path : path.substring(helpPos);
  }

  /**
   * Returns true if the URL returns an input stream, or false if the URL
   * returns an error code or we cannot connect to it (e.g. no internet
   * available)
   * 
   * @param url
   * @return
   */
  private boolean connectToUrl(String url)
  {
    try
    {
      URL u = new URL(url);
      InputStream connection = u.openStream();
      connection.close();
      return true;
    } catch (Throwable t)
    {
      return false;
    }
  }

  /**
   * Reads file help.jhm and checks that
   * <ul>
   * <li>each target attribute is in tocTargets</li>
   * <li>each url attribute is a valid relative file link</li>
   * </ul>
   * 
   * @param helpFolder
   */
  private Map<String, String> checkHelpMappings(File helpFolder)
          throws IOException
  {
    Map<String, String> targets = new HashMap<String, String>();
    BufferedReader br = new BufferedReader(new FileReader(new File(
            helpFolder, HELP_JHM)));
    String data = br.readLine();
    int lineNo = 0;
    while (data != null)
    {
      lineNo++;

      /*
       * record target, check for duplicates
       */
      String target = getAttribute(data, "target");
      if (target != null)
      {
        mapCount++;
        if (targets.containsKey(target))
        {
          log(String.format(
                  "Duplicate target mapping to %s at line %d of %s",
                  target, lineNo, HELP_JHM));
        }
        else
        {
          targetCount++;
        }
      }

      /*
       * validate url
       */
      String url = getAttribute(data, "url");
      if (url != null)
      {
        targets.put(target, url);
        int anchorPos = url.indexOf("#");
        if (anchorPos != -1)
        {
          url = url.substring(0, anchorPos);
        }
        if (!new File(helpFolder, url).exists())
        {
          log(String.format("Invalid url path '%s' at line %d of %s", url,
                  lineNo, HELP_JHM));
          invalidMapUrlCount++;
        }
      }
      data = br.readLine();
    }
    br.close();
    return targets;
  }

  /**
   * Reads file helpTOC.xml and reports any invalid targets
   * 
   * @param helpFolder
   * @param tocTargets
   * @param unusedTargets
   *          used targets are removed from this map
   * 
   * @return
   * @throws IOException
   */
  private void checkTableOfContents(File helpFolder,
          Map<String, String> tocTargets, Map<String, String> unusedTargets)
          throws IOException
  {
    BufferedReader br = new BufferedReader(new FileReader(new File(
            helpFolder, HELP_TOC_XML)));
    String data = br.readLine();
    int lineNo = 0;
    while (data != null)
    {
      lineNo++;
      /*
       * assuming no more than one "target" per line of file here
       */
      String target = getAttribute(data, "target");
      if (target != null)
      {
        unusedTargets.remove(target);
        if (!tocTargets.containsKey(target))
        {
          log(String.format("Invalid target '%s' at line %d of %s", target,
                  lineNo, HELP_TOC_XML));
          invalidTargetCount++;
        }
      }
      data = br.readLine();
    }
    br.close();
  }

  /**
   * Returns the value of an attribute if found in the data, else null
   * 
   * @param data
   * @param attName
   * @return
   */
  private static String getAttribute(String data, String attName)
  {
    /*
     * make a partial attempt at ignoring within <!-- html comments -->
     * (doesn't work if multi-line)
     */
    int commentStartPos = data.indexOf("<!--");
    int commentEndPos = commentStartPos == -1 ? -1 : data.substring(
            commentStartPos + 4).indexOf("-->");
    String value = null;
    String match = attName + "=\"";
    int attPos = data.indexOf(match);
    if (attPos > 0
            && (commentStartPos == -1 || attPos < commentStartPos || attPos > commentEndPos))
    {
      data = data.substring(attPos + match.length());
      value = data.substring(0, data.indexOf("\""));
    }
    return value;
  }

  /**
   * Trim whitespace from concatenated lines but preserve one space for valid
   * parsing
   */
  @Override
  public String cleanLine(String l)
  {
    return l.trim() + " ";
  }
}