Class: RDF::NTriples::Reader

Inherits:
Reader show all
Includes:
Util::Logger
Defined in:
vendor/bundler/ruby/2.5.0/bundler/gems/rdf-1b20f426c35b/lib/rdf/ntriples/reader.rb

Overview

N-Triples parser.

Examples:

Obtaining an NTriples reader class

RDF::Reader.for(:ntriples)     #=> RDF::NTriples::Reader
RDF::Reader.for("etc/doap.nt")
RDF::Reader.for(file_name:      "etc/doap.nt")
RDF::Reader.for(file_extension: "nt")
RDF::Reader.for(content_type:   "application/n-triples")

Parsing RDF statements from an NTriples file

RDF::NTriples::Reader.open("etc/doap.nt") do |reader|
  reader.each_statement do |statement|
    puts statement.inspect
  end
end

Parsing RDF statements from an NTriples string

data = StringIO.new(File.read("etc/doap.nt"))
RDF::NTriples::Reader.new(data) do |reader|
  reader.each_statement do |statement|
    puts statement.inspect
  end
end

See Also:

Direct Known Subclasses

RDF::NQuads::Reader, Turtle::FreebaseReader

Constant Summary

ESCAPE_CHARS =
["\b", "\f", "\t", "\n", "\r", "\"", "\\"].freeze
UCHAR4 =
/\\u([0-9A-Fa-f]{4,4})/.freeze
UCHAR8 =
/\\U([0-9A-Fa-f]{8,8})/.freeze
UCHAR =
Regexp.union(UCHAR4, UCHAR8).freeze
U_CHARS1 =

Terminals from rdf-turtle.

Unicode regular expressions.

Regexp.compile(<<-EOS.gsub(/\s+/, ''))
  [\\u00C0-\\u00D6]|[\\u00D8-\\u00F6]|[\\u00F8-\\u02FF]|
  [\\u0370-\\u037D]|[\\u037F-\\u1FFF]|[\\u200C-\\u200D]|
  [\\u2070-\\u218F]|[\\u2C00-\\u2FEF]|[\\u3001-\\uD7FF]|
  [\\uF900-\\uFDCF]|[\\uFDF0-\\uFFFD]|[\\u{10000}-\\u{EFFFF}]
EOS
U_CHARS2 =
Regexp.compile("\\u00B7|[\\u0300-\\u036F]|[\\u203F-\\u2040]").freeze
IRI_RANGE =
Regexp.compile("[[^<>\"{}\|\^`\\\\]&&[^\\x00-\\x20]]").freeze
PN_CHARS_BASE =

163s

/[A-Z]|[a-z]|#{U_CHARS1}/.freeze
PN_CHARS_U =

164s

/_|#{PN_CHARS_BASE}/.freeze
PN_CHARS =

166s

/-|[0-9]|#{PN_CHARS_U}|#{U_CHARS2}/.freeze
ECHAR =

159s

/\\[tbnrf\\"]/.freeze
IRIREF =

18

/<((?:#{IRI_RANGE}|#{UCHAR})*)>/.freeze
BLANK_NODE_LABEL =

141s

/_:((?:[0-9]|#{PN_CHARS_U})(?:(?:#{PN_CHARS}|\.)*#{PN_CHARS})?)/.freeze
LANGTAG =

144s

/@([a-zA-Z]+(?:-[a-zA-Z0-9]+)*)/.freeze
STRING_LITERAL_QUOTE =

22

/"((?:[^\"\\\n\r]|#{ECHAR}|#{UCHAR})*)"/.freeze
COMMENT =
/^#\s*(.*)$/.freeze
NODEID =
/^#{BLANK_NODE_LABEL}/.freeze
URIREF =
/^#{IRIREF}/.freeze
LITERAL_PLAIN =
/^#{STRING_LITERAL_QUOTE}/.freeze
LITERAL_WITH_LANGUAGE =
/^#{STRING_LITERAL_QUOTE}#{LANGTAG}/.freeze
LITERAL_WITH_DATATYPE =
/^#{STRING_LITERAL_QUOTE}\^\^#{IRIREF}/.freeze
DATATYPE_URI =
/^\^\^#{IRIREF}/.freeze
LITERAL =
Regexp.union(LITERAL_WITH_LANGUAGE, LITERAL_WITH_DATATYPE, LITERAL_PLAIN).freeze
SUBJECT =
Regexp.union(URIREF, NODEID).freeze
PREDICATE =
Regexp.union(URIREF).freeze
OBJECT =
Regexp.union(URIREF, NODEID, LITERAL).freeze
END_OF_STATEMENT =
/^\s*\.\s*(?:#.*)?$/.freeze

Instance Attribute Summary

Attributes inherited from Reader

#options

Class Method Summary collapse

Instance Method Summary collapse

Methods included from Util::Logger

#log_debug, #log_depth, #log_error, #log_fatal, #log_info, #log_recover, #log_recovering?, #log_statistics, #log_warn, #logger

Methods inherited from Reader

#base_uri, #canonicalize?, #close, each, #each_statement, #each_triple, #encoding, #fail_object, #fail_predicate, #fail_subject, for, format, #initialize, #intern?, #lineno, open, options, #prefix, #prefixes, #prefixes=, #read_statement, #rewind, #to_sym, to_sym, #valid?, #validate?

Methods included from Util::Aliasing::LateBound

#alias_method

Methods included from Enumerable

add_entailment, #dump, #each_graph, #each_object, #each_predicate, #each_quad, #each_statement, #each_subject, #each_term, #each_triple, #entail, #enum_graph, #enum_object, #enum_predicate, #enum_quad, #enum_statement, #enum_subject, #enum_term, #enum_triple, #graph_names, #has_graph?, #has_object?, #has_predicate?, #has_quad?, #has_statement?, #has_subject?, #has_term?, #has_triple?, #invalid?, #method_missing, #objects, #predicates, #project_graph, #quads, #respond_to_missing?, #statements, #subjects, #supports?, #terms, #to_a, #to_h, #to_set, #triples, #valid?, #validate!

Methods included from Isomorphic

#bijection_to, #isomorphic_with?

Methods included from Countable

#count, #empty?

Methods included from Readable

#readable?

Constructor Details

This class inherits a constructor from RDF::Reader

Dynamic Method Handling

This class handles dynamic methods through the method_missing method in the class RDF::Enumerable

Class Method Details

.parse_literal(input, **options) ⇒ RDF::Term, RDF::Literal

Reconstructs an RDF value from its serialized N-Triples representation.

Parameters:

Options Hash (**options):

Returns:



146
147
148
149
150
151
152
153
154
155
# File 'vendor/bundler/ruby/2.5.0/bundler/gems/rdf-1b20f426c35b/lib/rdf/ntriples/reader.rb', line 146

def self.parse_literal(input, **options)
  case input
    when LITERAL_WITH_LANGUAGE
      RDF::Literal.new(unescape($1), language: $4)
    when LITERAL_WITH_DATATYPE
      RDF::Literal.new(unescape($1), datatype: $4)
    when LITERAL_PLAIN
      RDF::Literal.new(unescape($1))
  end
end

.parse_node(input, **options) ⇒ RDF::Term, RDF::Node

Reconstructs an RDF value from its serialized N-Triples representation.

Parameters:

Options Hash (**options):

Returns:



126
127
128
129
130
# File 'vendor/bundler/ruby/2.5.0/bundler/gems/rdf-1b20f426c35b/lib/rdf/ntriples/reader.rb', line 126

def self.parse_node(input, **options)
  if input =~ NODEID
    RDF::Node.new($1)
  end
end

.parse_object(input, **options) ⇒ RDF::Term

Reconstructs an RDF value from its serialized N-Triples representation.

Parameters:

Options Hash (**options):

Returns:



119
120
121
# File 'vendor/bundler/ruby/2.5.0/bundler/gems/rdf-1b20f426c35b/lib/rdf/ntriples/reader.rb', line 119

def self.parse_object(input, **options)
  parse_uri(input, options) || parse_node(input, options) || parse_literal(input, options)
end

.parse_predicate(input, *options) ⇒ RDF::Term, RDF::URI

Reconstructs an RDF value from its serialized N-Triples representation.

Parameters:

Options Hash (*options):

Returns:



113
114
115
# File 'vendor/bundler/ruby/2.5.0/bundler/gems/rdf-1b20f426c35b/lib/rdf/ntriples/reader.rb', line 113

def self.parse_predicate(input, *options)
  parse_uri(input, intern: true)
end

.parse_subject(input, **options) ⇒ RDF::Term, RDF::Resource

Reconstructs an RDF value from its serialized N-Triples representation.

Parameters:

Options Hash (**options):

Returns:



106
107
108
# File 'vendor/bundler/ruby/2.5.0/bundler/gems/rdf-1b20f426c35b/lib/rdf/ntriples/reader.rb', line 106

def self.parse_subject(input, **options)
  parse_uri(input, options) || parse_node(input, options)
end

.parse_uri(input, intern: false, **options) ⇒ RDF::Term, RDF::URI

Reconstructs an RDF value from its serialized N-Triples representation.

Parameters:

Options Hash (**options):

Returns:



136
137
138
139
140
141
# File 'vendor/bundler/ruby/2.5.0/bundler/gems/rdf-1b20f426c35b/lib/rdf/ntriples/reader.rb', line 136

def self.parse_uri(input, intern: false, **options)
  if input =~ URIREF
    uri_str = unescape($1)
    RDF::URI.send(intern ? :intern : :new, unescape($1))
  end
end

.unescape(string) ⇒ String



163
164
165
166
167
168
169
170
171
172
173
174
175
# File 'vendor/bundler/ruby/2.5.0/bundler/gems/rdf-1b20f426c35b/lib/rdf/ntriples/reader.rb', line 163

def self.unescape(string)
  string = string.dup.force_encoding(Encoding::UTF_8)

  # Decode \t|\n|\r|\"|\\ character escapes:
  ESCAPE_CHARS.each { |escape| string.gsub!(escape.inspect[1...-1], escape) }

  # Decode \uXXXX and \UXXXXXXXX code points:
  string.gsub!(UCHAR) do
    [($1 || $2).hex].pack('U*')
  end

  string
end

.unserialize(input, **options) ⇒ RDF::Term

Reconstructs an RDF value from its serialized N-Triples representation.

Parameters:

Options Hash (**options):

Returns:



96
97
98
99
100
101
# File 'vendor/bundler/ruby/2.5.0/bundler/gems/rdf-1b20f426c35b/lib/rdf/ntriples/reader.rb', line 96

def self.unserialize(input, **options)
  case input
    when nil then nil
    else self.new(input, {logger: []}.merge(options)).read_value
  end
end

Instance Method Details

#read_commentBoolean

Returns:

  • (Boolean)

See Also:



218
219
220
# File 'vendor/bundler/ruby/2.5.0/bundler/gems/rdf-1b20f426c35b/lib/rdf/ntriples/reader.rb', line 218

def read_comment
  match(COMMENT)
end

#read_eosBoolean

Returns:

  • (Boolean)

See Also:



271
272
273
# File 'vendor/bundler/ruby/2.5.0/bundler/gems/rdf-1b20f426c35b/lib/rdf/ntriples/reader.rb', line 271

def read_eos
  match(END_OF_STATEMENT)
end

#read_literalRDF::Literal

Returns:

See Also:



251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
# File 'vendor/bundler/ruby/2.5.0/bundler/gems/rdf-1b20f426c35b/lib/rdf/ntriples/reader.rb', line 251

def read_literal
  if literal_str = match(LITERAL_PLAIN)
    literal_str = self.class.unescape(literal_str)
    literal = case
      when language = match(LANGTAG)
        RDF::Literal.new(literal_str, language: language)
      when datatype = match(/^(\^\^)/) # FIXME
        RDF::Literal.new(literal_str, datatype: read_uriref || fail_object)
      else
        RDF::Literal.new(literal_str) # plain string literal
    end
    literal.validate!     if validate?
    literal.canonicalize! if canonicalize?
    literal
  end
end

#read_nodeRDF::Node

Returns:

See Also:



241
242
243
244
245
246
# File 'vendor/bundler/ruby/2.5.0/bundler/gems/rdf-1b20f426c35b/lib/rdf/ntriples/reader.rb', line 241

def read_node
   if node_id = match(NODEID)
    @nodes ||= {}
    @nodes[node_id] ||= RDF::Node.new(node_id)
  end
end

#read_tripleArray



192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
# File 'vendor/bundler/ruby/2.5.0/bundler/gems/rdf-1b20f426c35b/lib/rdf/ntriples/reader.rb', line 192

def read_triple
  loop do
    readline.strip! # EOFError thrown on end of input
    line = @line    # for backtracking input in case of parse error

    begin
      unless blank? || read_comment
        subject   = read_uriref || read_node || fail_subject
        predicate = read_uriref(intern: true) || fail_predicate
        object    = read_uriref || read_node || read_literal || fail_object

        if validate? && !read_eos
          log_error("Expected end of statement (found: #{current_line.inspect})", lineno: lineno, exception: RDF::ReaderError)
        end
        return [subject, predicate, object]
      end
    rescue RDF::ReaderError => e
      @line = line  # this allows #read_value to work
      raise e
    end
  end
end

#read_uriref(intern: false, **options) ⇒ RDF::URI

Parameters:

  • intern (Boolean)

    (false) Use Interned Node

Returns:

See Also:



226
227
228
229
230
231
232
233
234
235
236
# File 'vendor/bundler/ruby/2.5.0/bundler/gems/rdf-1b20f426c35b/lib/rdf/ntriples/reader.rb', line 226

def read_uriref(intern: false, **options)
  if uri_str = match(URIREF)
    uri_str = self.class.unescape(uri_str)
    uri = RDF::URI.send(intern? && intern ? :intern : :new, uri_str)
    uri.validate!     if validate?
    uri.canonicalize! if canonicalize?
    uri
  end
rescue ArgumentError => e
  log_error("Invalid URI (found: \"<#{uri_str}>\")", lineno: lineno, token: "<#{uri_str}>", exception: RDF::ReaderError)
end

#read_valueRDF::Term

Returns:



179
180
181
182
183
184
185
186
187
# File 'vendor/bundler/ruby/2.5.0/bundler/gems/rdf-1b20f426c35b/lib/rdf/ntriples/reader.rb', line 179

def read_value
  begin
    read_statement
  rescue RDF::ReaderError
    value = read_uriref || read_node || read_literal
    log_recover
    value
  end
end