Class: XMLCleaner

Inherits:
Object
  • Object
show all
Defined in:
public/app/lib/xml_cleaner.rb

Defined Under Namespace

Classes: NamespaceCorrectingErrorHandler

Constant Summary collapse

MAX_ITERATIONS =

To ensure we make progress, we’ll attempt to fix up to this many errors before giving up.

10000

Instance Method Summary collapse

Constructor Details

#initializeXMLCleaner

Returns a new instance of XMLCleaner.



7
8
9
# File 'public/app/lib/xml_cleaner.rb', line 7

def initialize
  @log = Rails.logger
end

Instance Method Details

#clean(file_path) ⇒ Object



11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
# File 'public/app/lib/xml_cleaner.rb', line 11

def clean(file_path)
  factory = javax.xml.parsers.DocumentBuilderFactory.new_instance
  factory.setValidating(true)
  factory.setNamespaceAware(true)

  builder = factory.new_document_builder
  builder.setErrorHandler(NamespaceCorrectingErrorHandler.new(file_path))

  attempt = 0
  begin
    attempt += 1
    replace_html_entities(file_path)
    builder.parse(java.io.File.new(file_path))
  rescue NamespaceCorrectingErrorHandler::RetryParse
    if attempt >= MAX_ITERATIONS
      raise "Maximum error count (#{attempt}) exceeded for this document.  Giving up!"
    else
      @log.info("Corrected error in XML markup.  Parsing again (attempt: #{attempt}).")
      retry
    end
  rescue
    raise "Failed to clean XML: #{$!}"
  end
end

#replace_html_entities(file_path) ⇒ Object

Decode HTML entities so they can be parsed as XML



37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
# File 'public/app/lib/xml_cleaner.rb', line 37

def replace_html_entities(file_path)
  File.open(file_path + ".tmp", "w") do |outfile|
    File.open(file_path) do |infile|
      infile.each_with_index do |line, index|
        line = HTMLEntities.new.decode(line)
        # decode turns & into & so need to undo that here for PDF to work
        if line.match(/&\s+/) || line.match(/&[A-Za-z]+[^;]/)
          line.gsub!('&', '&')
        end
        outfile.puts(line)
      end
    end
  end
  File.rename(file_path + ".tmp", file_path)
end