summaryrefslogtreecommitdiffstats
path: root/pki/base/silent/src/com/netscape/pkisilent/http/HTMLDocument.java
blob: df95f8611b37ccfce30e3a0d86b0cbfe737b5102 (plain)
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
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
package com.netscape.pkisilent.http;
// --- BEGIN COPYRIGHT BLOCK ---
// This program 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; version 2 of the License.
//
// This program 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 this program; if not, write to the Free Software Foundation, Inc.,
// 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
//
// (C) 2007 Red Hat, Inc.
// All rights reserved.
// --- END COPYRIGHT BLOCK ---

import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.LinkedHashSet;
import java.util.StringTokenizer;
import java.util.regex.Matcher;
import java.util.regex.Pattern;



public class HTMLDocument
{
  // Indicates whether this HTML document has been parsed.
  boolean parsed;

  // A list of URLs of files that should be retrieved along with the main
  // contents of the document.  This may include any images contained in the
  // document, and possibly any external stylesheets.
  LinkedHashSet<String> associatedFiles;

  // A list of URLs of frames that are contained in the document.
  LinkedHashSet<String> documentFrames;

  // A list of URLs of links that are contained in the document.
  LinkedHashSet<String> documentLinks;

  // A list of URLs of images that are contained in the document.
  LinkedHashSet<String> documentImages;

  // A regular expression pattern that can be used to extract a URI from an HREF
  // tag.
  Pattern hrefPattern;

  // A regular expression pattern that can be used to extract a URI from a SRC
  // tag.
  Pattern srcPattern;

  // The base URL for relative links in this document.
  String baseURL;

  // The URL that may be used to access this document.
  String documentURL;

  // The actual contents of the page.
  String htmlData;

  // The contents of the page converted to lowercase for easier matching.
  String lowerData;

  // The URL for this document with only protocol, host, and port (i.e., no
  // file).
  String protocolHostPort;

  // A string buffer containing the contents of the page with tags removed.
  StringBuffer textData;


  // A set of private variables used for internal processing.
  private boolean lastElementIsAssociatedFile;
  private boolean lastElementIsChunk;
  private boolean lastElementIsComment;
  private boolean lastElementIsFrame;
  private boolean lastElementIsImage;
  private boolean lastElementIsLink;
  private boolean lastElementIsText;
  private int     lastElementEndPos;
  private int     lastElementStartPos;
  private String  lastURL;

	// constructor that helps to parse without url stuff
  public HTMLDocument(String htmlData) 
  {
    this.documentURL = null;
    this.htmlData    = htmlData;
    lowerData        = htmlData.toLowerCase();
    associatedFiles  = null;
    documentLinks    = null;
    documentImages   = null;
    textData         = null;
    parsed           = false;


    // Create the regex patterns that we will use for extracting URIs from tags.
    hrefPattern = Pattern.compile(".*?[hH][rR][eE][fF][\\s=\\\"\\']+" +
                                  "([^\\s\\\"\\'\\>]+).*", Pattern.DOTALL);
    srcPattern  = Pattern.compile(".*?[sS][rR][cC][\\s=\\\"\\']+" +
                                  "([^\\s\\\"\\'\\>]+).*", Pattern.DOTALL);
  }


  /**
   * Creates a new HTML document using the provided data.
   *
   * @param  documentURL  The URL for this document.
   * @param  htmlData     The actual data contained in the HTML document.
   */
  public HTMLDocument(String documentURL, String htmlData)
         throws MalformedURLException
  {
    this.documentURL = documentURL;
    this.htmlData    = htmlData;
    lowerData        = htmlData.toLowerCase();
    associatedFiles  = null;
    documentLinks    = null;
    documentImages   = null;
    textData         = null;
    parsed           = false;


    // Create the regex patterns that we will use for extracting URIs from tags.
    hrefPattern = Pattern.compile(".*?[hH][rR][eE][fF][\\s=\\\"\\']+" +
                                  "([^\\s\\\"\\'\\>]+).*", Pattern.DOTALL);
    srcPattern  = Pattern.compile(".*?[sS][rR][cC][\\s=\\\"\\']+" +
                                  "([^\\s\\\"\\'\\>]+).*", Pattern.DOTALL);

    URL url = new URL(documentURL);
    String urlPath = url.getPath();
    if ((urlPath == null) || (urlPath.length() == 0))
    {
      baseURL          = documentURL;
      protocolHostPort = documentURL;
    }
    else if (urlPath.equals("/"))
    {
      baseURL          = documentURL;
      protocolHostPort = documentURL.substring(0, documentURL.length()-1);
    }
    else if (urlPath.endsWith("/"))
    {
      baseURL = documentURL;

      int port = url.getPort();
      if (port > 0)
      {
        protocolHostPort = url.getProtocol() + "://" + url.getHost() + ":" +
                           port;
      }
      else
      {
        protocolHostPort = url.getProtocol() + "://" + url.getHost();
      }
    }
    else
    {
      int port = url.getPort();
      if (port > 0)
      {
        protocolHostPort = url.getProtocol() + "://" + url.getHost() + ":" +
                           port;
      }
      else
      {
        protocolHostPort = url.getProtocol() + "://" + url.getHost();
      }

      File urlFile = new File(urlPath);
      String parentDirectory = urlFile.getParent();
      if ((parentDirectory == null) || (parentDirectory.length() == 0))
      {
        parentDirectory = "/";
      }
      else if (! parentDirectory.startsWith("/"))
      {
        parentDirectory = "/" + parentDirectory;
      }

      baseURL = protocolHostPort + parentDirectory;
    }

    if (! baseURL.endsWith("/"))
    {
      baseURL = baseURL + "/";
    }
  }



  /**
   * Actually parses the HTML document and extracts useful elements from it.
   *
   * @return  <CODE>true</CODE> if the page could be parsed successfully, or
   *          <CODE>false</CODE> if not.
   */
  public boolean parse()
  {
    if (parsed)
    {
      return true;
    }


    try
    {
      associatedFiles = new LinkedHashSet<String>();
      documentFrames  = new LinkedHashSet<String>();
      documentLinks   = new LinkedHashSet<String>();
      documentImages  = new LinkedHashSet<String>();
      textData        = new StringBuffer();

      lastElementStartPos = 0;
      lastElementEndPos   = -1;
      String element;
      while ((element = nextDocumentElement()) != null)
      {
        if (element.length() == 0)
        {
          continue;
        }

        if (lastElementIsText)
        {
          char lastChar;
          if (textData.length() == 0)
          {
            lastChar = ' ';
          }
          else
          {
            lastChar = textData.charAt(textData.length()-1);
          }
          char firstChar = element.charAt(0);
          if (! ((lastChar == ' ') || (lastChar == '\t') ||
                 (lastChar == '\r') || (lastChar == '\n')) ||
                 (firstChar == ' ') || (firstChar == '\t') ||
                 (firstChar == '\r') || (firstChar == '\n'))
          {
            textData.append(" ");
          }

          textData.append(element);
        }
        else if (lastElementIsImage)
        {
          if (lastURL != null)
          {
            documentImages.add(lastURL);
            associatedFiles.add(lastURL);
          }
        }
        else if (lastElementIsFrame)
        {
          if (lastURL != null)
          {
            documentFrames.add(lastURL);
            associatedFiles.add(lastURL);
          }
        }
        else if (lastElementIsLink)
        {
          if (lastURL != null)
          {
            documentLinks.add(lastURL);
          }
        }
        else if (lastElementIsAssociatedFile)
        {
          if (lastURL != null)
          {
            associatedFiles.add(lastURL);
          }
        }
        else if (lastElementIsChunk || lastElementIsComment)
        {
          // Don't need to do anything with this.
        }
        else
        {
          // Also don't need anything here.
        }
      }

      parsed = true;
    }
    catch (Exception e)
    {
      associatedFiles = null;
      documentLinks   = null;
      documentImages  = null;
      textData        = null;
      parsed          = false;
    }

    return parsed;
  }



  /**
   * Retrieves the next element from the HTML document.  An HTML element can
   * include a string of plain text, a single HTML tag, or a larger chunk of
   * HTML including a start and end tag, all of which should be considered a
   * single element.
   */
  private String nextDocumentElement()
  {
    // If we're at the end of the HTML, then return null.
    if (lastElementEndPos >= htmlData.length())
    {
      return null;
    }


    // Initialize the variables we will use for the search.
    lastElementStartPos         = lastElementEndPos+1;
    lastElementIsAssociatedFile = false;
    lastElementIsChunk          = false;
    lastElementIsComment        = false;
    lastElementIsFrame          = false;
    lastElementIsImage          = false;
    lastElementIsLink           = false;
    lastElementIsText           = false;
    lastURL                     = null;


    // Find the location of the next open angle bracket.  If there is none, then
    // the rest of the document must be plain text.
    int openPos = lowerData.indexOf('<', lastElementStartPos);
    if (openPos < 0)
    {
      lastElementEndPos = htmlData.length();
      lastElementIsText = true;
      return htmlData.substring(lastElementStartPos);
    }


    // If the location of the next open tag is not we started looking, then read
    // everything up to that tag as text.
    if (openPos > lastElementStartPos)
    {
      lastElementEndPos = openPos-1;
      lastElementIsText = true;
      return htmlData.substring(lastElementStartPos, openPos);
    }


    // The start position is an open tag.  See if the tag is actually "<!--",
    // which indicates an HTML comment.  If that's the case, then find the
    // closing "-->".
    if (openPos == lowerData.indexOf("<!--", lastElementStartPos))
    {
      int closePos = lowerData.indexOf("-->", openPos+1);
      if (closePos < 0)
      {
        // This looks like an unterminated comment.  We can't do much else
        // here, so just stop parsing.
        return null;
      }
      else
      {
        lastElementEndPos    = closePos + 2;
        lastElementIsComment = true;
        return htmlData.substring(lastElementStartPos, lastElementEndPos+1);
      }
    }


    // Find the location of the next close angle bracket.  If there is none,
    // then we have an unmatched open tag.  What to do here?  I guess just treat
    // the rest of the document as text.
    int closePos = lowerData.indexOf('>', openPos+1);
    if (closePos < 0)
    {
      lastElementEndPos = htmlData.length();
      lastElementIsText = true;
      return htmlData.substring(lastElementStartPos);
    }


    // Grab the contents of the tag in both normal and lowercase.
    String tag         = htmlData.substring(openPos, closePos+1);
    String strippedTag = htmlData.substring(openPos+1, closePos).trim();
    StringTokenizer tokenizer = new StringTokenizer(strippedTag, " \t\r\n=\"'");
    lastElementEndPos = closePos;

    if (! tokenizer.hasMoreTokens())
    {
      return tag;
    }

    String token      = tokenizer.nextToken();
    String lowerToken = token.toLowerCase();

    if (lowerToken.equals("a") || lowerToken.equals("area"))
    {
      while (tokenizer.hasMoreTokens())
      {
        token = tokenizer.nextToken();
        if (token.equalsIgnoreCase("href"))
        {
          try
          {
            Matcher matcher = hrefPattern.matcher(tag);
            lastURL = uriToURL(matcher.replaceAll("$1"));
            if (lastURL != null)
            {
              lastElementIsLink = true;
            }
          } catch (Exception e) {}
          break;
        }
      }
    }
    else if (lowerToken.equals("base"))
    {
      while (tokenizer.hasMoreTokens())
      {
        token = tokenizer.nextToken();
        if (token.equalsIgnoreCase("href"))
        {
          try
          {
            Matcher matcher = hrefPattern.matcher(tag);
            String  uri     = matcher.replaceAll("$1");
            if (! uri.endsWith("/"))
            {
              uri = uri + "/";
            }

            baseURL = uri;
          } catch (Exception e) {}
          break;
        }
      }
    }
    else if (lowerToken.equals("frame") || lowerToken.equals("iframe") ||
             lowerToken.equals("input"))
    {
      while (tokenizer.hasMoreTokens())
      {
        token = tokenizer.nextToken();
        if (token.equalsIgnoreCase("src"))
        {
          try
          {
            Matcher matcher = srcPattern.matcher(tag);
            String  uri     = matcher.replaceAll("$1");
            lastURL = uriToURL(uri);
            if (lastURL != null)
            {
              lastElementIsFrame          = true;
              lastElementIsAssociatedFile = true;
            }
          } catch (Exception e) {}
          break;
        }
      }
    }
    else if (lowerToken.equals("img"))
    {
      while (tokenizer.hasMoreTokens())
      {
        token = tokenizer.nextToken();
        if (token.equalsIgnoreCase("src"))
        {
          try
          {
            Matcher matcher = srcPattern.matcher(tag);
            String  uri     = matcher.replaceAll("$1");
            lastURL = uriToURL(uri);
            if (lastURL != null)
            {
              lastElementIsImage = true;
            }
          } catch (Exception e) {}
          break;
        }
      }
    }
    else if (lowerToken.equals("link"))
    {
      boolean isStyleSheet = false;

      while (tokenizer.hasMoreTokens())
      {
        token = tokenizer.nextToken();
        if (token.equalsIgnoreCase("href"))
        {
          try
          {
            Matcher matcher = hrefPattern.matcher(tag);
            String  uri     = matcher.replaceAll("$1");
            lastURL = uriToURL(uri);
            if (lastURL != null)
            {
              lastElementIsLink = true;
            }
          } catch (Exception e) {}
          break;
        }
        else if (token.equalsIgnoreCase("rel"))
        {
          if (tokenizer.hasMoreTokens())
          {
            String relType = tokenizer.nextToken();
            if (relType.equalsIgnoreCase("stylesheet"))
            {
              isStyleSheet = true;
            }
          }
        }
      }

      if (lastURL != null)
      {
        if (isStyleSheet)
        {
          lastElementIsAssociatedFile = true;
        }
        else
        {
          lastElementIsLink = true;
        }
      }
    }
    else if (lowerToken.equals("script"))
    {
      while (tokenizer.hasMoreTokens())
      {
        token = tokenizer.nextToken();
        if (token.equalsIgnoreCase("src"))
        {
          try
          {
            Matcher matcher = srcPattern.matcher(tag);
            String  uri     = matcher.replaceAll("$1");
            lastURL = uriToURL(uri);
          } catch (Exception e) {}
          break;
        }
      }

      if (lastURL == null)
      {
        int endScriptPos = lowerData.indexOf("</script>", lastElementEndPos+1);
        if (endScriptPos > 0)
        {
          lastElementEndPos = endScriptPos + 8;
          tag = htmlData.substring(lastElementStartPos, lastElementEndPos+1);
          lastElementIsChunk = true;
        }
      }
      else
      {
        lastElementIsAssociatedFile = true;
      }
    }

    return tag;
  }



  /**
   * Converts the provided URI to a URL.  The provided URI may be a URL already,
   * or it may also be an absolute path on the server or a path relative to the
   * base URL.
   *
   * @param  uri  The URI to convert to a URL.
   *
   * @return  The URL based on the provided URI.
   */
  private String uriToURL(String uri)
  {
    String url = null;

    if (uri.indexOf("://") > 0)
    {
      if (uri.startsWith("http"))
      {
        url = uri;
      }
    }
    else if (uri.startsWith("/"))
    {
      url = protocolHostPort + uri;
    }
    else
    {
      url = baseURL + uri;
    }

    return url;
  }



  /**
   * Retrieves the URL of this HTML document.
   *
   * @return  The URL of this HTML document.
   */
  public String getDocumentURL()
  {
    return documentURL;
  }



  /**
   * Retrieves the original HTML data used to create this document.
   *
   * @return  The orginal HTML data used to create this document.
   */
  public String getHTMLData()
  {
    return htmlData;
  }



  /**
   * Retrieves the contents of the HTML document with all tags removed.
   *
   * @return  The contents of the HTML document with all tags removed, or
   *          <CODE>null</CODE> if a problem occurs while trying to parse the
   *          HTML.
   */
  public String getTextData()
  {
    if (! parsed)
    {
      if (! parse())
      {
        return null;
      }
    }

    return textData.toString();
  }



  /**
   * Retrieves an array containing a set of URLs parsed from the HTML document
   * that reference files that would normally be downloaded as part of
   * retrieving a page in a browser.  This includes images and external style
   * sheets.
   *
   * @return  An array containing a set of URLs to files associated with the
   *          HTML document, or <CODE>null</CODE> if a problem occurs while
   *          trying to parse the HTML.
   */
  public String[] getAssociatedFiles()
  {
    if (! parsed)
    {
      if (! parse())
      {
        return null;
      }
    }

    String[] urlArray = new String[associatedFiles.size()];
    associatedFiles.toArray(urlArray);
    return urlArray;
  }



  /**
   * Retrieves an array containing a set of URLs parsed from the HTML document
   * that are in the form of links to other content.
   *
   * @return  An array containing a set of URLs parsed from the HTML document
   *          that are in the form of links to other content, or
   *          <CODE>null</CODE> if a problem occurs while trying to parse the
   *          HTML.
   */
  public String[] getDocumentLinks()
  {
    if (! parsed)
    {
      if (! parse())
      {
        return null;
      }
    }

    String[] urlArray = new String[documentLinks.size()];
    documentLinks.toArray(urlArray);
    return urlArray;
  }



  /**
   * Retrieves an array containing a set of URLs parsed from the HTML document
   * that reference images used in the document.
   *
   * @return  An array containing a set of URLs parsed from the HTML document
   *          that reference images used in the document.
   */
  public String[] getDocumentImages()
  {
    if (! parsed)
    {
      if (! parse())
      {
        return null;
      }
    }

    String[] urlArray = new String[documentImages.size()];
    documentImages.toArray(urlArray);
    return urlArray;
  }



  /**
   * Retrieves an array containing a set of URLs parsed from the HTML document
   * that reference frames used in the document.
   *
   * @return  An array containing a set of URLs parsed from the HTML document
   *          that reference frames used in the document.
   */
  public String[] getDocumentFrames()
  {
    if (! parsed)
    {
      if (! parse())
      {
        return null;
      }
    }

    String[] urlArray = new String[documentFrames.size()];
    documentFrames.toArray(urlArray);
    return urlArray;
  }
}