-
Notifications
You must be signed in to change notification settings - Fork 98
/
writer.rb
665 lines (617 loc) · 19.8 KB
/
writer.rb
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
# -*- encoding: utf-8 -*-
module RDF
##
# The base class for RDF serializers.
#
# @example Loading an RDF writer implementation
# require 'rdf/ntriples'
#
# @example Iterating over known RDF writer classes
# RDF::Writer.each { |klass| puts klass.name }
#
# @example Obtaining an RDF writer class
# RDF::Writer.for(:ntriples) #=> RDF::NTriples::Writer
# RDF::Writer.for("spec/data/output.nt")
# RDF::Writer.for(file_name: "spec/data/output.nt")
# RDF::Writer.for(file_extension: "nt")
# RDF::Writer.for(content_type: "application/n-triples")
#
# @example Instantiating an RDF writer class
# RDF::Writer.for(:ntriples).new($stdout) { |writer| ... }
#
# @example Serializing RDF statements into a file
# RDF::Writer.open("spec/data/output.nt") do |writer|
# graph.each_statement do |statement|
# writer << statement
# end
# end
#
# @example Serializing RDF statements into a string
# RDF::Writer.for(:ntriples).buffer do |writer|
# graph.each_statement do |statement|
# writer << statement
# end
# end
#
# @example Detecting invalid output
# logger = Logger.new([])
# RDF::Writer.for(:ntriples).buffer(logger: logger) do |writer|
# statement = RDF::Statement.new(
# RDF::URI("https://rubygems.org/gems/rdf"),
# RDF::URI("http://purl.org/dc/terms/creator"),
# nil)
# writer << statement
# end # => RDF::WriterError
# logger.empty? => false
#
# @abstract
# @see RDF::Format
# @see RDF::Reader
class Writer
extend ::Enumerable
extend RDF::Util::Aliasing::LateBound
include RDF::Util::Logger
include RDF::Writable
##
# Enumerates known RDF writer classes.
#
# @yield [klass]
# @yieldparam [Class] klass
# @yieldreturn [void] ignored
# @return [Enumerator]
def self.each(&block)
RDF::Format.map(&:writer).reject(&:nil?).each(&block)
end
##
# Finds an RDF writer class based on the given criteria.
#
# @overload for(format)
# Finds an RDF writer class based on a symbolic name.
#
# @param [Symbol] format
# @return [Class]
#
# @overload for(filename)
# Finds an RDF writer class based on a file name.
#
# @param [String] filename
# @return [Class]
#
# @overload for(options = {})
# Finds an RDF writer class based on various options.
#
# @param [Hash{Symbol => Object}] options
# @option options [String, #to_s] :file_name (nil)
# @option options [Symbol, #to_sym] :file_extension (nil)
# @option options [String, #to_s] :content_type (nil)
# @return [Class]
#
# @return [Class]
def self.for(*arg, &block)
case arg.length
when 0 then arg = nil
when 1 then arg = arg.first
else
raise ArgumentError, "Format.for accepts zero or one argument, got #{arg.length}."
end
arg = arg.merge(has_writer: true) if arg.is_a?(Hash)
if format = self.format || Format.for(arg)
format.writer
end
end
##
# Retrieves the RDF serialization format class for this writer class.
#
# @return [Class]
def self.format(klass = nil)
if klass.nil?
Format.each do |format|
if format.writer == self
return format
end
end
nil # not found
end
end
##
# Options suitable for automatic Writer provisioning.
# @return [Array<RDF::CLI::Option>]
def self.options
[
RDF::CLI::Option.new(
symbol: :canonicalize,
datatype: TrueClass,
control: :checkbox,
on: ["--canonicalize"],
description: "Canonicalize input/output.") {true},
RDF::CLI::Option.new(
symbol: :encoding,
datatype: Encoding,
control: :text,
on: ["--encoding ENCODING"],
description: "The encoding of the input stream.") {|arg| Encoding.find arg},
RDF::CLI::Option.new(
symbol: :prefixes,
datatype: Hash,
multiple: true,
control: :none,
on: ["--prefixes PREFIX,PREFIX"],
description: "A comma-separated list of prefix:uri pairs.") do |arg|
arg.split(',').inject({}) do |memo, pfxuri|
pfx,uri = pfxuri.split(':', 2)
memo.merge(pfx.to_sym => RDF::URI(uri))
end
end,
RDF::CLI::Option.new(
symbol: :unique_bnodes,
datatype: TrueClass,
control: :checkbox,
on: ["--unique-bnodes"],
description: "Use unique Node identifiers.") {true},
]
end
class << self
alias_method :format_class, :format
##
# Use parameters from accept-params to determine if the parameters are acceptable to invoke this writer. The `accept_params` will subsequently be provided to the writer instance.
#
# @example rejecting a writer based on a profile
# JSON::LD::Writer.accept?(profile: "http://www.w3.org/ns/json-ld#compacted http://example.org/black-listed")
# # => false
#
# @param [Hash{Symbol => String}] accept_params
# @yield [accept_params] if a block is given, returns the result of evaluating that block
# @yieldparam [Hash{Symbol => String}] accept_params
# @return [Boolean]
# @see http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.1
def accept?(accept_params)
block_given? ? yield(accept_params) : true
end
end
##
# @param [RDF::Enumerable, #each] data
# the graph or repository to dump
# @param [IO, File, String] io
# the output stream or file to write to
# @param [Hash{Symbol => Object}] options
# passed to {RDF::Writer#initialize} or {RDF::Writer.buffer}
# @return [void]
def self.dump(data, io = nil, **options)
io = File.open(io, 'w') if io.is_a?(String)
method = data.respond_to?(:each_statement) ? :each_statement : :each
if io
new(io, **options) do |writer|
io.set_encoding(writer.encoding) if io.respond_to?(:set_encoding)
data.send(method) do |statement|
writer << statement
end
writer.flush
end
else
buffer(**options) do |writer|
data.send(method) do |statement|
writer << statement
end
end
end
end
##
# Buffers output into a string buffer.
#
# @param [Hash{Symbol => Object}] options
# passed to {RDF::Writer#initialize}
# @yield [writer]
# @yieldparam [RDF::Writer] writer
# @yieldreturn [void]
# @return [String]
# @raise [ArgumentError] if no block is provided
def self.buffer(*args, **options, &block)
raise ArgumentError, "block expected" unless block_given?
StringIO.open do |buffer|
self.new(buffer, *args, **options) do |writer|
buffer.set_encoding(writer.encoding)
block.call(writer)
end
buffer.string
end
end
##
# Writes output to the given `filename`.
#
# @param [String, #to_s] filename
# @param [Symbol] format (nil)
# @param [Hash{Symbol => Object}] options
# any additional options (see {RDF::Writer#initialize} and {RDF::Format.for})
# @return [RDF::Writer]
def self.open(filename, format: nil, **options, &block)
File.open(filename, 'wb') do |file|
format_options = options.dup
format_options[:file_name] ||= filename
self.for(format || format_options).new(file, **options) do |writer|
file.set_encoding(writer.encoding)
block.call(writer)
end
end
end
##
# Returns a symbol appropriate to use with RDF::Writer.for()
# @return [Symbol]
def self.to_sym
self.format.to_sym
end
##
# Returns a symbol appropriate to use with RDF::Writer.for()
# @return [Symbol]
def to_sym
self.class.to_sym
end
##
# Initializes the writer.
#
# @param [IO, File] output
# the output stream
# @param [Hash{Symbol => Object}] options
# any additional options
# @option options [Encoding, String, Symbol] :encoding
# the encoding to use on the output stream.
# Defaults to the format associated with `content_encoding`.
# @option options [Boolean] :canonicalize (false)
# whether to canonicalize terms when serializing
# @option options [Boolean] :validate (false)
# whether to validate terms when serializing
# @option options [Hash] :prefixes (Hash.new)
# the prefix mappings to use (not supported by all writers)
# @option options [#to_s] :base_uri (nil)
# the base URI to use when constructing relative URIs (not supported
# by all writers)
# @option options [Boolean] :unique_bnodes (false)
# Use unique {Node} identifiers, defaults to using the identifier which the node was originall initialized with (if any). Implementations should ensure that Nodes are serialized using a unique representation independent of any identifier used when creating the node. See {NTriples::Writer#format_node}
# @option options [Hash{Symbol => String}] :accept_params
# Parameters from ACCEPT header entry for the media-range matching this writer.
# @yield [writer] `self`
# @yieldparam [RDF::Writer] writer
# @yieldreturn [void]
def initialize(output = $stdout, **options, &block)
@output, @options = output, options.dup
@nodes, @node_id, @node_id_map = {}, 0, {}
if block_given?
write_prologue
case block.arity
when 1 then block.call(self)
else instance_eval(&block)
end
write_epilogue
end
end
##
# Any additional options for this writer.
#
# @return [Hash]
# @since 0.2.2
attr_reader :options
##
# Returns the base URI used for this writer.
#
# @example
# writer.prefixes[:dc] #=> RDF::URI('http://purl.org/dc/terms/')
#
# @return [RDF::URI]
# @since 0.3.4
def base_uri
RDF::URI(@options[:base_uri]) if @options[:base_uri]
end
##
# Returns the URI prefixes currently defined for this writer.
#
# @example
# writer.prefixes[:dc] #=> RDF::URI('http://purl.org/dc/terms/')
#
# @return [Hash{Symbol => RDF::URI}]
# @since 0.2.2
def prefixes
@options[:prefixes] ||= {}
end
##
# Defines the given URI prefixes for this writer.
#
# @example
# writer.prefixes = {
# dc: RDF::URI('http://purl.org/dc/terms/'),
# }
#
# @param [Hash{Symbol => RDF::URI}] prefixes
# @return [Hash{Symbol => RDF::URI}]
# @since 0.3.0
def prefixes=(prefixes)
@options[:prefixes] = prefixes
end
##
# Defines the given named URI prefix for this writer.
#
# @example Defining a URI prefix
# writer.prefix :dc, RDF::URI('http://purl.org/dc/terms/')
#
# @example Returning a URI prefix
# writer.prefix(:dc) #=> RDF::URI('http://purl.org/dc/terms/')
#
# @overload prefix(name, uri)
# @param [Symbol, #to_s] name
# @param [RDF::URI, #to_s] uri
#
# @overload prefix(name)
# @param [Symbol, #to_s] name
#
# @return [RDF::URI]
def prefix(name, uri = nil)
name = name.to_s.empty? ? nil : (name.respond_to?(:to_sym) ? name.to_sym : name.to_s.to_sym)
uri.nil? ? prefixes[name] : prefixes[name] = uri
end
alias_method :prefix!, :prefix
##
# Returns the encoding of the output stream.
#
# @return [Encoding]
def encoding
case @options[:encoding]
when String, Symbol
Encoding.find(@options[:encoding].to_s)
when Encoding
@options[:encoding]
else
@options[:encoding] ||= Encoding.find(self.class.format.content_encoding.to_s)
end
end
##
# Returns `true` if statements and terms should be validated.
#
# @return [Boolean] `true` or `false`
# @since 1.0.8
def validate?
@options[:validate]
end
##
# Returns `true` if terms should be in canonical form.
#
# @note This is for term canonicalization, for graph/dataset canonicalization use `RDF::Normalize`.
#
# @return [Boolean] `true` or `false`
# @since 1.0.8
def canonicalize?
@options[:canonicalize]
end
##
# Flushes the underlying output buffer.
#
# @return [self]
def flush
@output.flush if @output.respond_to?(:flush)
self
end
alias_method :flush!, :flush
##
# @return [self]
# @abstract
def write_prologue
@logged_errors_at_prolog = log_statistics[:error].to_i
self
end
##
# @return [self]
# @raise [RDF::WriterError] if errors logged during processing.
# @abstract
def write_epilogue
if log_statistics[:error].to_i > @logged_errors_at_prolog
raise RDF::WriterError, "Errors found during processing"
end
self
end
##
# @param [String] text
# @return [self]
# @abstract
def write_comment(text)
self
end
##
# Add a statement to the writer. This will check to ensure that the statement is complete (no nil terms) and is valid, if the `:validation` option is set.
#
# Additionally, it will de-duplicate BNode terms sharing a common identifier.
#
# @param [RDF::Statement] statement
# @return [self]
# @note logs error if attempting to write an invalid {RDF::Statement} or if canonicalizing a statement which cannot be canonicalized.
def write_statement(statement)
statement = statement.canonicalize! if canonicalize?
# Make sure BNodes in statement use unique identifiers
if statement.node?
statement.to_quad.map do |term|
if term.is_a?(RDF::Node)
term = term.original while term.original
@nodes[term] ||= begin
# Account for duplicated nodes
@node_id_map[term.to_s] ||= term
if !@node_id_map[term.to_s].equal?(term)
# Rename node
term.make_unique!
@node_id_map[term.to_s] = term
end
end
else
term
end
end
statement = RDF::Statement.from(statement.to_quad)
end
if statement.incomplete?
log_error "Statement #{statement.inspect} is incomplete"
elsif validate? && statement.invalid?
log_error "Statement #{statement.inspect} is invalid"
elsif respond_to?(:write_quad)
write_quad(*statement.to_quad)
else
write_triple(*statement.to_triple)
end
self
rescue ArgumentError => e
log_error e.message
end
alias_method :insert_statement, :write_statement # support the RDF::Writable interface
##
# @param [Array<Array(RDF::Resource, RDF::URI, RDF::Term)>] triples
# @return [self]
# @note logs error if attempting to write an invalid {RDF::Statement} or if canonicalizing a statement which cannot be canonicalized.
def write_triples(*triples)
triples.each { |triple| write_triple(*triple) }
self
end
##
# @param [RDF::Resource] subject
# @param [RDF::URI] predicate
# @param [RDF::Term] object
# @return [self]
# @raise [NotImplementedError] unless implemented in subclass
# @note logs error if attempting to write an invalid {RDF::Statement} or if canonicalizing a statement which cannot be canonicalized.
# @abstract
def write_triple(subject, predicate, object)
raise NotImplementedError.new("#{self.class}#write_triple") # override in subclasses
end
##
# @param [RDF::Term] term
# @return [String]
# @since 0.3.0
def format_term(term, **options)
case term
when String then format_literal(RDF::Literal(term, **options), **options)
when RDF::List then format_list(term, **options)
when RDF::Literal then format_literal(term, **options)
when RDF::URI then format_uri(term, **options)
when RDF::Node then format_node(term, **options)
# FIXME: quoted triples are now deprecated
when RDF::Statement then term.tripleTerm? ? format_tripleTerm(term, **options) : format_quotedTriple(term, **options)
else nil
end
end
##
# @param [RDF::Node] value
# @param [Hash{Symbol => Object}] options = ({})
# @option options [Boolean] :unique_bnodes (false)
# Serialize node using unique identifier, rather than any used to create the node.
# @return [String]
# @raise [NotImplementedError] unless implemented in subclass
# @abstract
def format_node(value, **options)
raise NotImplementedError.new("#{self.class}#format_node") # override in subclasses
end
##
# @param [RDF::URI] value
# @param [Hash{Symbol => Object}] options = ({})
# @return [String]
# @raise [NotImplementedError] unless implemented in subclass
# @abstract
def format_uri(value, **options)
raise NotImplementedError.new("#{self.class}#format_uri") # override in subclasses
end
##
# @param [RDF::Literal, String, #to_s] value
# @param [Hash{Symbol => Object}] options = ({})
# @return [String]
# @raise [NotImplementedError] unless implemented in subclass
# @abstract
def format_literal(value, **options)
raise NotImplementedError.new("#{self.class}#format_literal") # override in subclasses
end
##
# @param [RDF::List] value
# @param [Hash{Symbol => Object}] options = ({})
# @return [String]
# @abstract
# @since 0.2.3
def format_list(value, **options)
format_term(value.subject, **options)
end
##
# Formats a referenced triple term.
#
# @example
# <<<s> <p> <o>>> <p> <o> .
#
# @param [RDF::Statement] value
# @param [Hash{Symbol => Object}] options = ({})
# @return [String]
# @raise [NotImplementedError] unless implemented in subclass
# @abstract
def format_tripleTerm(value, **options)
raise NotImplementedError.new("#{self.class}#format_tripleTerm") # override in subclasses
end
##
# Formats a referenced quoted triple.
#
# @example
# <<<s> <p> <o>>> <p> <o> .
#
# @param [RDF::Statement] value
# @param [Hash{Symbol => Object}] options = ({})
# @return [String]
# @raise [NotImplementedError] unless implemented in subclass
# @abstract
# @deprecated Quoted Triples are now deprecated in favor of Triple Terms
def format_quotedTriple(value, **options)
raise NotImplementedError.new("#{self.class}#format_quotedTriple") # override in subclasses
end
protected
##
# @return [void]
def puts(*args)
@output.puts(*args.map {|s| s.encode(encoding)})
end
##
# @param [RDF::Resource] term
# @return [String]
def uri_for(term)
case
when term.is_a?(RDF::Node)
@nodes[term] ||= term.to_base
when term.respond_to?(:to_uri)
term.to_uri.to_s
else
term.to_s
end
end
##
# @return [String]
def node_id
"_:n#{@node_id += 1}"
end
##
# @param [String] string
# @return [String]
def escaped(string)
string.gsub('\\', '\\\\\\\\').
gsub("\b", '\\b').
gsub("\f", '\\f').
gsub("\t", '\\t').
gsub("\n", '\\n').
gsub("\r", '\\r').
gsub('"', '\\"')
end
##
# @param [String] string
# @return [String]
def quoted(string)
"\"#{string}\""
end
private
@@subclasses = [] # @private
##
# @private
# @return [void]
def self.inherited(child)
@@subclasses << child
super
end
end # Writer
##
# The base class for RDF serialization errors.
class WriterError < IOError
end # WriterError
end # RDF