-
Notifications
You must be signed in to change notification settings - Fork 58
/
client.rb
773 lines (717 loc) · 25.3 KB
/
client.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
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
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
require 'net/http/persistent' # @see http://rubygems.org/gems/net-http-persistent
require 'rdf' # @see http://rubygems.org/gems/rdf
require 'rdf/ntriples' # @see http://rubygems.org/gems/rdf
begin
require 'nokogiri'
rescue LoadError
require 'rexml/document'
end
module SPARQL
##
# A SPARQL 1.0/1.1 client for RDF.rb.
#
# @see http://www.w3.org/TR/sparql11-query/
# @see http://www.w3.org/TR/sparql11-protocol/
# @see http://www.w3.org/TR/sparql11-results-json/
# @see http://www.w3.org/TR/sparql11-results-csv-tsv/
class Client
autoload :Query, 'sparql/client/query'
autoload :Repository, 'sparql/client/repository'
autoload :Update, 'sparql/client/update'
autoload :VERSION, 'sparql/client/version'
class ClientError < StandardError; end
class MalformedQuery < ClientError; end
class ServerError < StandardError; end
RESULT_JSON = 'application/sparql-results+json'.freeze
RESULT_XML = 'application/sparql-results+xml'.freeze
RESULT_CSV = 'text/csv'.freeze
RESULT_TSV = 'text/tab-separated-values'.freeze
RESULT_BOOL = 'text/boolean'.freeze # Sesame-specific
RESULT_BRTR = 'application/x-binary-rdf-results-table'.freeze # Sesame-specific
RESULT_ALL = [
RESULT_JSON,
RESULT_XML,
RESULT_BOOL,
"#{RESULT_TSV};q=0.8",
"#{RESULT_CSV};q=0.2",
'*/*;q=0.1'
].join(', ').freeze
GRAPH_ALL = (
RDF::Format.content_types.keys +
['*/*;q=0.1']
).join(', ').freeze
ACCEPT_JSON = {'Accept' => RESULT_JSON}.freeze
ACCEPT_XML = {'Accept' => RESULT_XML}.freeze
ACCEPT_CSV = {'Accept' => RESULT_CSV}.freeze
ACCEPT_TSV = {'Accept' => RESULT_TSV}.freeze
ACCEPT_BRTR = {'Accept' => RESULT_BRTR}.freeze
ACCEPT_RESULTS = {'Accept' => RESULT_ALL}.freeze
ACCEPT_GRAPH = {'Accept' => GRAPH_ALL}.freeze
DEFAULT_PROTOCOL = 1.0
DEFAULT_METHOD = :post
XMLNS = {'sparql' => 'http://www.w3.org/2005/sparql-results#'}.freeze
##
# The SPARQL endpoint URL, or an RDF::Queryable instance, to use the native SPARQL engine.
#
# @return [RDF::URI, RDF::Queryable]
attr_reader :url
##
# The HTTP headers that will be sent in requests to the endpoint.
#
# @return [Hash{String => String}]
attr_reader :headers
##
# Any miscellaneous configuration.
#
# @return [Hash{Symbol => Object}]
attr_reader :options
##
# Initialize a new sparql client, either using the URL of
# a SPARQL endpoint or an `RDF::Queryable` instance to use
# the native SPARQL gem.
#
# @param [String, RDF::Queryable, #to_s] url
# URL of endpoint, or queryable object.
# @param [Hash{Symbol => Object}] options
# @option options [Symbol] :method (DEFAULT_METHOD)
# @option options [Number] :protocol (DEFAULT_PROTOCOL)
# @option options [Hash] :headers
# @option options [Hash] :read_timeout
def initialize(url, options = {}, &block)
case url
when RDF::Queryable
@url, @options = url, options.dup
else
@url, @options = RDF::URI.new(url.to_s), options.dup
@headers = @options.delete(:headers) || {}
@http = http_klass(@url.scheme)
end
if block_given?
case block.arity
when 1 then block.call(self)
else instance_eval(&block)
end
end
end
##
# Executes a boolean `ASK` query.
#
# @param (see Query.ask)
# @return [Query]
def ask(*args)
call_query_method(:ask, *args)
end
##
# Executes a tuple `SELECT` query.
#
# @param (see Query.select)
# @return [Query]
def select(*args)
call_query_method(:select, *args)
end
##
# Executes a `DESCRIBE` query.
#
# @param (see Query.describe)
# @return [Query]
def describe(*args)
call_query_method(:describe, *args)
end
##
# Executes a graph `CONSTRUCT` query.
#
# @param (see Query.construct)
# @return [Query]
def construct(*args)
call_query_method(:construct, *args)
end
##
# Executes an `INSERT DATA` operation.
#
# This requires that the endpoint support SPARQL 1.1 Update.
#
# Note that for inserting non-trivial amounts of data, you probably
# ought to consider using the RDF store's native bulk-loading facilities
# or APIs, as `INSERT DATA` operations entail comparably higher
# parsing overhead.
#
# @example Inserting data constructed ad-hoc
# client.insert_data(RDF::Graph.new { |graph|
# graph << [:jhacker, RDF::Vocab::FOAF.name, "J. Random Hacker"]
# })
#
# @example Inserting data sourced from a file or URL
# data = RDF::Graph.load("http://rdf.rubyforge.org/doap.nt")
# client.insert_data(data)
#
# @example Inserting data into a named graph
# client.insert_data(data, :graph => "http://example.org/")
#
# @param [RDF::Enumerable] data
# @param [Hash{Symbol => Object}] options
# @option options [RDF::URI, String] :graph
# @return [void] `self`
# @see http://www.w3.org/TR/sparql11-update/#insertData
def insert_data(data, options = {})
self.update(Update::InsertData.new(data, options))
end
##
# Executes a `DELETE DATA` operation.
#
# This requires that the endpoint support SPARQL 1.1 Update.
#
# @example Deleting data sourced from a file or URL
# data = RDF::Graph.load("http://rdf.rubyforge.org/doap.nt")
# client.delete_data(data)
#
# @example Deleting data from a named graph
# client.delete_data(data, :graph => "http://example.org/")
#
# @param [RDF::Enumerable] data
# @param [Hash{Symbol => Object}] options
# @option options [RDF::URI, String] :graph
# @return [void] `self`
# @see http://www.w3.org/TR/sparql11-update/#deleteData
def delete_data(data, options = {})
self.update(Update::DeleteData.new(data, options))
end
##
# Executes a `DELETE/INSERT` operation.
#
# This requires that the endpoint support SPARQL 1.1 Update.
#
# @param [RDF::Enumerable] delete_graph
# @param [RDF::Enumerable] insert_graph
# @param [RDF::Enumerable] where_graph
# @param [Hash{Symbol => Object}] options
# @option options [RDF::URI, String] :graph
# @return [void] `self`
# @see http://www.w3.org/TR/sparql11-update/#deleteInsert
def delete_insert(delete_graph, insert_graph = nil, where_graph = nil, options = {})
self.update(Update::DeleteInsert.new(delete_graph, insert_graph, where_graph, options))
end
##
# Executes a `CLEAR GRAPH` operation.
#
# This is a convenience wrapper for the {#clear} method.
#
# @example `CLEAR GRAPH <http://example.org/>`
# client.clear_graph("http://example.org/")
#
# @param [RDF::URI, String] graph_uri
# @param [Hash{Symbol => Object}] options
# @option options [Boolean] :silent
# @return [void] `self`
# @see http://www.w3.org/TR/sparql11-update/#clear
def clear_graph(graph_uri, options = {})
self.clear(:graph, graph_uri, options)
end
##
# Executes a `CLEAR` operation.
#
# This requires that the endpoint support SPARQL 1.1 Update.
#
# @example `CLEAR GRAPH <http://example.org/>`
# client.clear(:graph, RDF::URI("http://example.org/"))
#
# @example `CLEAR DEFAULT`
# client.clear(:default)
#
# @example `CLEAR NAMED`
# client.clear(:named)
#
# @example `CLEAR ALL`
# client.clear(:all)
#
# @overload clear(what, *arguments)
# @param [Symbol, #to_sym] what
# @param [Array] arguments splat of other arguments to {Update::Clear}.
# @option options [Boolean] :silent
# @return [void] `self`
#
# @overload clear(what, *arguments, options = {})
# @param [Symbol, #to_sym] what
# @param [Array] arguments splat of other arguments to {Update::Clear}.
# @param [Hash{Symbol => Object}] options
# @option options [Boolean] :silent
# @return [void] `self`
#
# @see http://www.w3.org/TR/sparql11-update/#clear
def clear(what, *arguments)
self.update(Update::Clear.new(what, *arguments))
end
##
# @private
def call_query_method(meth, *args)
client = self
result = Query.send(meth, *args)
(class << result; self; end).send(:define_method, :execute) do
client.query(self)
end
result
end
##
# Returns a mapping of blank node results for this client.
#
# @private
def nodes
@nodes ||= {}
end
##
# Executes a SPARQL query and returns the parsed results.
#
# @param [String, #to_s] query
# @param [Hash{Symbol => Object}] options
# @option options [String] :content_type
# @option options [Hash] :headers
# @return [Array<RDF::Query::Solution>]
# @see http://www.w3.org/TR/sparql11-protocol/#query-operation
def query(query, options = {})
@op = :query
@alt_endpoint = options[:endpoint]
case @url
when RDF::Queryable
require 'sparql' unless defined?(::SPARQL::Grammar)
begin
SPARQL.execute(query, @url, options)
rescue SPARQL::MalformedQuery
$stderr.puts "error running #{query}: #{$!}"
raise
end
else
parse_response(response(query, options), options)
end
end
##
# Executes a SPARQL update operation.
#
# @param [String, #to_s] query
# @param [Hash{Symbol => Object}] options
# @option options [String] :endpoint
# @option options [String] :content_type
# @option options [Hash] :headers
# @return [void] `self`
# @see http://www.w3.org/TR/sparql11-protocol/#update-operation
def update(query, options = {})
@op = :update
@alt_endpoint = options[:endpoint]
case @url
when RDF::Queryable
require 'sparql' unless defined?(::SPARQL::Grammar)
SPARQL.execute(query, @url, options.merge(update: true))
else
response(query, options)
end
self
end
##
# Executes a SPARQL query and returns the Net::HTTP::Response of the
# result.
#
# @param [String, #to_s] query
# @param [Hash{Symbol => Object}] options
# @option options [String] :content_type
# @option options [Hash] :headers
# @return [String]
def response(query, options = {})
headers = options[:headers] || {}
headers['Accept'] = options[:content_type] if options[:content_type]
request(query, headers) do |response|
case response
when Net::HTTPBadRequest # 400 Bad Request
raise MalformedQuery.new(response.body + " Processing query #{query}")
when Net::HTTPClientError # 4xx
raise ClientError.new(response.body + " Processing query #{query}")
when Net::HTTPServerError # 5xx
raise ServerError.new(response.body + " Processing query #{query}")
when Net::HTTPSuccess # 2xx
response
end
end
end
##
# @param [Net::HTTPSuccess] response
# @param [Hash{Symbol => Object}] options
# @return [Object]
def parse_response(response, options = {})
case options[:content_type] || response.content_type
when NilClass
response.body
when RESULT_BOOL # Sesame-specific
response.body == 'true'
when RESULT_JSON
self.class.parse_json_bindings(response.body, nodes)
when RESULT_XML
self.class.parse_xml_bindings(response.body, nodes)
when RESULT_CSV
self.class.parse_csv_bindings(response.body, nodes)
when RESULT_TSV
self.class.parse_tsv_bindings(response.body, nodes)
else
parse_rdf_serialization(response, options)
end
end
##
# @param [String, Hash] json
# @return [<RDF::Query::Solutions>]
# @see http://www.w3.org/TR/rdf-sparql-json-res/#results
def self.parse_json_bindings(json, nodes = {})
require 'json' unless defined?(::JSON)
json = JSON.parse(json.to_s) unless json.is_a?(Hash)
case
when json.has_key?('boolean')
json['boolean']
when json.has_key?('results')
solutions = json['results']['bindings'].map do |row|
row = row.inject({}) do |cols, (name, value)|
cols.merge(name.to_sym => parse_json_value(value, nodes))
end
RDF::Query::Solution.new(row)
end
RDF::Query::Solutions.new(solutions)
end
end
##
# @param [Hash{String => String}] value
# @return [RDF::Value]
# @see http://www.w3.org/TR/sparql11-results-json/#select-encode-terms
# @see http://www.w3.org/TR/rdf-sparql-json-res/#variable-binding-results
def self.parse_json_value(value, nodes = {})
case value['type'].to_sym
when :bnode
nodes[id = value['value']] ||= RDF::Node.new(id)
when :uri
RDF::URI.new(value['value'])
when :literal
RDF::Literal.new(value['value'], :datatype => value['datatype'], :language => value['xml:lang'])
when :'typed-literal'
RDF::Literal.new(value['value'], :datatype => value['datatype'])
else nil
end
end
##
# @param [String, Array<Array<String>>] csv
# @return [<RDF::Query::Solutions>]
# @see http://www.w3.org/TR/sparql11-results-csv-tsv/
def self.parse_csv_bindings(csv, nodes = {})
require 'csv' unless defined?(::CSV)
csv = CSV.parse(csv.to_s) unless csv.is_a?(Array)
vars = csv.shift
solutions = RDF::Query::Solutions.new
csv.each do |row|
solution = RDF::Query::Solution.new
row.each_with_index do |v, i|
term = case v
when /^_:(.*)$/ then nodes[$1] ||= RDF::Node($1)
when /^\w+:.*$/ then RDF::URI(v)
else RDF::Literal(v)
end
solution[vars[i].to_sym] = term
end
solutions << solution
end
solutions
end
##
# @param [String, Array<Array<String>>] tsv
# @return [<RDF::Query::Solutions>]
# @see http://www.w3.org/TR/sparql11-results-csv-tsv/
def self.parse_tsv_bindings(tsv, nodes = {})
tsv = tsv.lines.map {|l| l.chomp.split("\t")} unless tsv.is_a?(Array)
vars = tsv.shift.map {|h| h.sub(/^\?/, '')}
solutions = RDF::Query::Solutions.new
tsv.each do |row|
solution = RDF::Query::Solution.new
row.each_with_index do |v, i|
if !v.empty?
term = RDF::NTriples.unserialize(v) || case v
when /^\d+\.\d*[eE][+-]?[0-9]+$/ then RDF::Literal::Double.new(v)
when /^\d*\.\d+[eE][+-]?[0-9]+$/ then RDF::Literal::Double.new(v)
when /^\d*\.\d+$/ then RDF::Literal::Decimal.new(v)
when /^\d+$/ then RDF::Literal::Integer.new(v)
else
RDF::Literal(v)
end
nodes[term.id] = term if term.is_a? RDF::Node
solution[vars[i].to_sym] = term
end
end
solutions << solution
end
solutions
end
##
# @param [String, IO, Nokogiri::XML::Node, REXML::Element] xml
# @return [<RDF::Query::Solutions>]
# @see http://www.w3.org/TR/rdf-sparql-json-res/#results
def self.parse_xml_bindings(xml, nodes = {})
xml.force_encoding(::Encoding::UTF_8) if xml.respond_to?(:force_encoding)
if defined?(::Nokogiri)
xml = Nokogiri::XML(xml).root unless xml.is_a?(Nokogiri::XML::Document)
case
when boolean = xml.xpath("//sparql:boolean", XMLNS)[0]
boolean.text == 'true'
when results = xml.xpath("//sparql:results", XMLNS)[0]
solutions = results.elements.map do |result|
row = {}
result.elements.each do |binding|
name = binding.attr('name').to_sym
value = binding.elements.first
row[name] = parse_xml_value(value, nodes)
end
RDF::Query::Solution.new(row)
end
RDF::Query::Solutions.new(solutions)
end
else
# REXML
xml = REXML::Document.new(xml).root unless xml.is_a?(REXML::Element)
case
when boolean = xml.elements['boolean']
boolean.text == 'true'
when results = xml.elements['results']
solutions = results.elements.map do |result|
row = {}
result.elements.each do |binding|
name = binding.attributes['name'].to_sym
value = binding.select { |node| node.kind_of?(::REXML::Element) }.first
row[name] = parse_xml_value(value, nodes)
end
RDF::Query::Solution.new(row)
end
RDF::Query::Solutions.new(solutions)
end
end
end
##
# @param [Nokogiri::XML::Element, REXML::Element] value
# @return [RDF::Value]
# @see http://www.w3.org/TR/rdf-sparql-json-res/#variable-binding-results
def self.parse_xml_value(value, nodes = {})
case value.name.to_sym
when :bnode
nodes[id = value.text] ||= RDF::Node.new(id)
when :uri
RDF::URI.new(value.text)
when :literal
lang = value.respond_to?(:attr) ? value.attr('xml:lang') : value.attributes['xml:lang']
datatype = value.respond_to?(:attr) ? value.attr('datatype') : value.attributes['datatype']
RDF::Literal.new(value.text, :language => lang, :datatype => datatype)
else nil
end
end
##
# @param [Net::HTTPSuccess] response
# @param [Hash{Symbol => Object}] options
# @return [RDF::Enumerable]
def parse_rdf_serialization(response, options = {})
options = {:content_type => response.content_type} unless options[:content_type]
if reader = RDF::Reader.for(options)
reader.new(response.body)
else
raise RDF::ReaderError, "no suitable rdf reader was found."
end
end
##
# Serializes a URI or URI string into SPARQL syntax.
#
# @param [RDF::URI, String] uri
# @return [String]
# @private
def self.serialize_uri(uri)
case uri
when String then RDF::NTriples.serialize(RDF::URI(uri))
when RDF::URI then RDF::NTriples.serialize(uri)
else raise ArgumentError, "expected the graph URI to be a String or RDF::URI, but got #{uri.inspect}"
end
end
##
# Serializes an `RDF::Value` into SPARQL syntax.
#
# @param [RDF::Value] value
# @param [Boolean] use_vars (false) Use variables in place of BNodes
# @return [String]
# @private
def self.serialize_value(value, use_vars = false)
# SPARQL queries are UTF-8, but support ASCII-style Unicode escapes, so
# the N-Triples serializer is fine unless it's a variable:
case
when value.nil? then RDF::Query::Variable.new.to_s
when value.variable? then value.to_s
when value.node? then (use_vars ? RDF::Query::Variable.new(value.id) : value)
else RDF::NTriples.serialize(value)
end
end
##
# Serializes a SPARQL predicate
#
# @param [RDF::Value, Array, String] value
# @param [Fixnum] rdepth
# @return [String]
# @private
def self.serialize_predicate(value,rdepth=0)
case value
when nil
RDF::Query::Variable.new.to_s
when String then value
when Array
s = value.map{|v|serialize_predicate(v,rdepth+1)}.join
rdepth > 0 ? "(#{s})" : s
when RDF::Value
# abbreviate RDF.type in the predicate position per SPARQL grammar
value.equal?(RDF.type) ? 'a' : serialize_value(value)
end
end
##
# Serializes a SPARQL graph
#
# @param [RDF::Enumerable] patterns
# @param [Boolean] use_vars (false) Use variables in place of BNodes
# @return [String]
# @private
def self.serialize_patterns(patterns, use_vars = false)
patterns.map do |pattern|
serialized_pattern = case pattern
when SPARQL::Client::QueryElement then [pattern.to_s]
else
RDF::Statement.from(pattern).to_triple.each_with_index.map do |v, i|
if i == 1
SPARQL::Client.serialize_predicate(v)
else
SPARQL::Client.serialize_value(v, use_vars)
end
end
end
serialized_pattern.join(' ') + ' .'
end
end
##
# Outputs a developer-friendly representation of this object to `stderr`.
#
# @return [void]
def inspect!
warn(inspect)
end
##
# Returns a developer-friendly representation of this object.
#
# @return [String]
def inspect
sprintf("#<%s:%#0x(%s)>", self.class.name, __id__, url.to_s)
end
protected
##
# Returns an HTTP class or HTTP proxy class based on the `http_proxy`
# and `https_proxy` environment variables.
#
# @param [String] scheme
# @return [Net::HTTP::Proxy]
def http_klass(scheme)
proxy_url = nil
case scheme
when 'http'
value = ENV['http_proxy']
proxy_url = URI.parse(value) unless value.nil? || value.empty?
when 'https'
value = ENV['https_proxy']
proxy_url = URI.parse(value) unless value.nil? || value.empty?
end
klass = if Net::HTTP::Persistent::VERSION >= '3.0'
Net::HTTP::Persistent.new(name: self.class.to_s, proxy: proxy_url)
else
Net::HTTP::Persistent.new(self.class.to_s, proxy_url)
end
klass.keep_alive = @options[:keep_alive] || 120
klass.read_timeout = @options[:read_timeout] || 60
klass
end
##
# Performs an HTTP request against the SPARQL endpoint.
#
# @param [String, #to_s] query
# @param [Hash{String => String}] headers
# @yield [response]
# @yieldparam [Net::HTTPResponse] response
# @return [Net::HTTPResponse]
# @see http://www.w3.org/TR/sparql11-protocol/#query-operation
def request(query, headers = {}, &block)
# Make sure an appropriate Accept header is present
headers['Accept'] ||= if (query.respond_to?(:expects_statements?) ?
query.expects_statements? :
(query =~ /CONSTRUCT|DESCRIBE|DELETE|CLEAR/))
GRAPH_ALL
else
RESULT_ALL
end
request = send("make_#{request_method(query)}_request", query, headers)
request.basic_auth(url.user, url.password) if url.user && !url.user.empty?
pre_http_hook(request) if respond_to?(:pre_http_hook)
response = @http.request(::URI.parse(url.to_s), request)
post_http_hook(response) if respond_to?(:post_http_hook)
10.times do
if response.kind_of? Net::HTTPRedirection
response = @http.request(::URI.parse(response['location']), request)
else
return block_given? ? block.call(response) : response
end
end
raise ServerError, "Infinite redirect at #{url}. Redirected more than 10 times."
end
##
# Return the HTTP verb for posting this request.
# this is useful if you need to override the HTTP verb based on the request being made.
# (e.g. Marmotta 3.3.0 requires GET for DELETE requests, but can accept POST for INSERT)
def request_method(query)
(options[:method] || DEFAULT_METHOD).to_sym
end
##
# Constructs an HTTP GET request according to the SPARQL Protocol.
#
# @param [String, #to_s] query
# @param [Hash{String => String}] headers
# @return [Net::HTTPRequest]
# @see http://www.w3.org/TR/sparql11-protocol/#query-via-get
def make_get_request(query, headers = {})
url = self.url.dup
url.query_values = (url.query_values || {}).merge(:query => query.to_s)
request = Net::HTTP::Get.new(url.request_uri, self.headers.merge(headers))
request
end
##
# Constructs an HTTP POST request according to the SPARQL Protocol.
#
# @param [String, #to_s] query
# @param [Hash{String => String}] headers
# @return [Net::HTTPRequest]
# @see http://www.w3.org/TR/sparql11-protocol/#query-via-post-direct
# @see http://www.w3.org/TR/sparql11-protocol/#query-via-post-urlencoded
def make_post_request(query, headers = {})
if @alt_endpoint.nil?
endpoint = url.request_uri
else
endpoint = @alt_endpoint
end
request = Net::HTTP::Post.new(endpoint, self.headers.merge(headers))
case (self.options[:protocol] || DEFAULT_PROTOCOL).to_s
when '1.1'
request['Content-Type'] = 'application/sparql-' + (@op || :query).to_s
request.body = query.to_s
when '1.0'
request.set_form_data((@op || :query) => query.to_s)
else
raise ArgumentError, "unknown SPARQL protocol version: #{self.options[:protocol].inspect}"
end
request
end
# A query element can be used as a component of a query. It may be initialized with a string, which is wrapped in an appropriate container depending on the type of QueryElement. Implements {#to_s} to property serialize when generating a SPARQL query.
class QueryElement
attr_reader :elements
def initialize(*args)
@elements = args
end
def to_s
raise NotImplemented
end
end
end # Client
end # SPARQL