Class: OpenURL::ContextObject

Inherits:
Object
  • Object
show all
Defined in:
lib/openurl/context_object.rb

Overview

The ContextObject class is intended to both create new OpenURL 1.0 context objects or parse existing ones, either from Key-Encoded Values (KEVs) or XML.

Create a new ContextObject programmatically

require 'openurl/context_object'
include OpenURL

ctx = ContextObject.new
ctx.referent.set_format('journal') # important to do this FIRST.

ctx.referent.add_identifier('info:doi/10.1016/j.ipm.2005.03.024')
ctx.referent.('issn', '0306-4573')
ctx.referent.('aulast', 'Bollen')
ctx.referrer.add_identifier('info:sid/google')
puts ctx.kev
# url_ver=Z39.88-2004&ctx_tim=2007-10-29T12%3A18%3A53-0400&ctx_ver=Z39.88-2004&ctx_enc=info%3Aofi%2Fenc%3AUTF-8&ctx_id=&rft.issn=0306-4573&rft.aulast=Bollen&rft_val_fmt=info%3Aofi%2Ffmt%3Axml%3Axsd%3Ajournal&rft_id=info%3Adoi%2F10.1016%2Fj.ipm.2005.03.024&rfr_id=info%3Asid%2Fgoogle

Create a new ContextObject from an existing kev or XML serialization:

ContextObject.new_from_kev( kev_context_object ) ContextObject.new_from_xml( xml_context_object ) # Can be String or REXML::Document

Serialize a ContextObject to kev or XML :

ctx.kev ctx.xml

Constant Summary collapse

@@defined_entities =
{"rft"=>"referent", "rfr"=>"referrer", "rfe"=>"referring-entity", "req"=>"requestor", "svc"=>"service-type", "res"=>"resolver"}

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeContextObject

Creates a new ContextObject object and initializes the ContextObjectEntities.



47
48
49
50
51
52
53
54
55
56
57
# File 'lib/openurl/context_object.rb', line 47

def initialize()       
  @referent = ContextObjectEntity.new
  @referrer = ContextObjectEntity.new
  @referringEntity = ContextObjectEntity.new
  @requestor = ContextObjectEntity.new
  @serviceType = []
  @resolver = []
  @foreign_keys = {}
  @openurl_ver = "Z39.88-2004"
  @admin = {"ctx_ver"=>{"label"=>"version", "value"=>@openurl_ver}, "ctx_tim"=>{"label"=>"timestamp", "value"=>DateTime.now().to_s}, "ctx_id"=>{"label"=>"identifier", "value"=>""}, "ctx_enc"=>{"label"=>"encoding", "value"=>"info:ofi/enc:UTF-8"}}    
end

Instance Attribute Details

#adminObject (readonly)

Returns the value of attribute admin.



39
40
41
# File 'lib/openurl/context_object.rb', line 39

def admin
  @admin
end

#foreign_keysObject

Returns the value of attribute foreign_keys.



41
42
43
# File 'lib/openurl/context_object.rb', line 41

def foreign_keys
  @foreign_keys
end

#openurl_verObject

Returns the value of attribute openurl_ver.



41
42
43
# File 'lib/openurl/context_object.rb', line 41

def openurl_ver
  @openurl_ver
end

#referentObject

Returns the value of attribute referent.



39
40
41
# File 'lib/openurl/context_object.rb', line 39

def referent
  @referent
end

#referrerObject

Returns the value of attribute referrer.



39
40
41
# File 'lib/openurl/context_object.rb', line 39

def referrer
  @referrer
end

#referringEntityObject

Returns the value of attribute referringEntity.



39
40
41
# File 'lib/openurl/context_object.rb', line 39

def referringEntity
  @referringEntity
end

#requestorObject

Returns the value of attribute requestor.



39
40
41
# File 'lib/openurl/context_object.rb', line 39

def requestor
  @requestor
end

#resolverObject (readonly)

Returns the value of attribute resolver.



39
40
41
# File 'lib/openurl/context_object.rb', line 39

def resolver
  @resolver
end

#serviceTypeObject (readonly)

Returns the value of attribute serviceType.



39
40
41
# File 'lib/openurl/context_object.rb', line 39

def serviceType
  @serviceType
end

Class Method Details

.entities(term) ⇒ Object



481
482
483
484
485
486
# File 'lib/openurl/context_object.rb', line 481

def self.entities(term)
  return @@defined_entities[term] if @@defined_entities.keys.index(term)
  return @@defined_entities[@@defined_entities.values.index(term)] if @@defined_entities.values.index(term)
  return nil
  
end

.new_from_context_object(context_object) ⇒ Object

Initialize a new ContextObject object from an existing OpenURL::ContextObject



512
513
514
515
516
# File 'lib/openurl/context_object.rb', line 512

def self.new_from_context_object(context_object)
  co = self.new
  co.import_context_object(context_object)
  return co
end

.new_from_form_vars(params) ⇒ Object

Initialize a new ContextObject object from a CGI.params style hash Expects a hash with default value being nil though, not [] as CGI.params actually returns, beware. Can also accept a Rails-style params hash (single string values, not array values), although this may lose some context object information.



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
# File 'lib/openurl/context_object.rb', line 208

def self.new_from_form_vars(params)
  co = self.new
  if ctx_val = (params[:url_ctx_val]||params["url_ctx_val"]) and not ctx_val.empty? # this is where the context object stuff will be
    co.admin.keys.each do | adm |
      if params[adm.to_s]
        if params[adm.to_s].is_a?(Array)
          co.set_administration_key(adm, params[adm.to_s].first) 
        else
          co.set_administration_key(adm, params[adm.to_s]) 
        end
      end
    end
    
    if ctx_format = (params["url_ctx_fmt"]||params[:url_ctx_fmt])
      ctx_format = ctx_format.first if ctx_format.is_a?(Array)
      ctx_val = ctx_val.first if ctx_val.is_a?(Array)        
      if ctx_format  == "info:ofi/fmt:xml:xsd:ctx"
        co.import_xml(ctx_val)
      elsif ctx_format == "info:ofi/fmt:kev:mtx:ctx"
        co.import_kev(ctx_val)
      end
    end  
  else # we'll assume this is standard inline kev
    co.import_hash(params)
  end
  return co
end

.new_from_hash(hash) ⇒ Object

Initialize a new ContextObject object from an existing key/value hash



433
434
435
436
437
# File 'lib/openurl/context_object.rb', line 433

def self.new_from_hash(hash)      
  co = self.new
  co.import_hash(hash)
  return co
end

.new_from_kev(kev) ⇒ Object

Initialize a new ContextObject object from an existing KEV



197
198
199
200
201
# File 'lib/openurl/context_object.rb', line 197

def self.new_from_kev(kev)
  co = self.new
  co.import_kev(kev)
  return co
end

.new_from_xml(xml) ⇒ Object

Initialize a new ContextObject object from an existing XML ContextObject



274
275
276
277
278
# File 'lib/openurl/context_object.rb', line 274

def self.new_from_xml(xml)
  co = self.new
  co.import_xml(xml)
  return co
end

Instance Method Details

#clean_char_encoding!(hash) ⇒ Object

Takes a hash of openurl key/values, as output by CGI.parse from a query string for example (values can be strings or arrays of string). Mutates hash in place.

Force encodes to UTF8 or 8859-1, depending on ctx_enc presence and value.

Replaces any illegal bytes with replacement chars, transcodes to UTF-8 if needed to ensure UTF8 on way out.



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
# File 'lib/openurl/context_object.rb', line 290

def clean_char_encoding!(hash)
  # Bail if we're not in ruby 1.9
  return unless "".respond_to? :encoding
  
  source_encoding = "UTF-8"
  if hash["ctx_enc"] == "info:ofi/enc:ISO-8859-1"
    hash.delete("ctx_enc")
    source_encoding = "ISO-8859-1"      
  end
  
  hash.each_pair do |key, values|
    # get a list of all terminal values, whether wrapped
    # in arrays or not. We're going to mutate them. 
    [values].flatten.compact.each do | v |
        v.force_encoding(source_encoding)
        if source_encoding == "UTF-8"
          v.scrub!
        else
          # transcode, replacing any bad chars. 
          v.encode!("UTF-8", :invalid => :replace, :undef => :replace )
        end
    end
  end
  
end

#coins(classnames = nil, innerHTML = nil) ⇒ Object

Outputs a COinS (ContextObject in SPANS) span tag for the ContextObject. Arguments are any other CSS classes you want included and the innerHTML content.



165
166
167
# File 'lib/openurl/context_object.rb', line 165

def coins (classnames=nil, innerHTML=nil)      
  return "<span class='Z3988 #{classnames}' title='"+CGI.escapeHTML(self.kev(true))+"'>#{innerHTML}</span>"
end

#deep_copyObject



68
69
70
71
72
# File 'lib/openurl/context_object.rb', line 68

def deep_copy
  cloned = ContextObject.new
  cloned.import_context_object( self )
  return cloned
end

#get_entity_obj(abbr) ⇒ Object

Takes a string abbreviated entity (‘rfr’, ‘rft’, etc.), returns the appropriate ContextObjectEntity object for this ContextObject, in some cases lazily creating and assigning it. @@defined_entities = “rfr”=>“referrer”, “rfe”=>“referring-entity”, “req”=>“requestor”, “svc”=>“service-type”, “res”=>“resolver”



461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
# File 'lib/openurl/context_object.rb', line 461

def get_entity_obj(abbr)
  ivar_name = @@defined_entities[abbr]

  return nil unless ivar_name

  return case ivar_name
    when "service-type"        
      @serviceType << ContextObjectEntity.new if @serviceType.empty?
      @serviceType.first
    when "resolver"
      @resolver << ContextObjectEntity.new if @resolver.empty?
      @resolver.first
    when "referring-entity"
      instance_variable_get("@referringEntity")
    else
      instance_variable_get("@#{ivar_name}")
    end
end

#import_context_object(context_object) ⇒ Object

Imports an existing OpenURL::ContextObject object and sets the appropriate entity values.



491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
# File 'lib/openurl/context_object.rb', line 491

def import_context_object(context_object)
  @admin.each_key { |k|
    self.set_administration_key(k, context_object.admin[k]["value"])
  }	
  ["@referent", "@referringEntity", "@requestor", "@referrer"].each do | ent |
    self.instance_variable_set(ent.to_sym, Marshal::load(Marshal.dump(context_object.instance_variable_get(ent.to_sym))))
  end
  context_object.serviceType.each { |svc|        
    @serviceType << Marshal::load(Marshal.dump(svc))          
  }
  context_object.resolver.each { |res|
    @resolver << Marshal::load(Marshal.dump(res))                  
  }      
  context_object.foreign_keys.each do | key, val |
    self.foreign_keys[key] = val
  end
end

#import_hash(hash) ⇒ Object

Imports an existing hash of ContextObject values and sets the appropriate entities.



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
# File 'lib/openurl/context_object.rb', line 318

def import_hash(hash)    
  clean_char_encoding!(hash) 
  
  ref = {}
  {"@referent"=>"rft", "@referrer"=>"rfr", "@referringEntity"=>"rfe",
    "@requestor"=>"req"}.each do | ent, abbr |
    next unless hash["#{abbr}_val_fmt"]    
    val = hash["#{abbr}_val_fmt"]
    val = val[0] if val.is_a?(Array)
    self.instance_variable_set(ent.to_sym, ContextObjectEntityFactory.format(val))
  end
  
  {"@serviceType"=>"svc","@resolver"=>"res"}.each do | ent, abbr |
    next unless hash["#{abbr}_val_fmt"]
    val = hash["#{abbr}_val_fmt"]
    val = val[0] if val.is_a?(Array)        
    self.instance_variable_set(ent.to_sym, [ContextObjectEntityFactory.format(val)])
  end  

  openurl_keys = ["url_ver", "url_tim", "url_ctx_fmt"]
  hash.each do |key, value|      
    val = value
    val = value[0] if value.is_a?(Array)

    next if value.nil? || value.empty?
    
    if openurl_keys.include?(key)          
      next # None of these matter much for our purposes
    elsif @admin.has_key?(key)          
      self.set_administration_key(key, val) 
    elsif key.match(/^[a-z]{3}_val_fmt/)        
      next
    elsif key.match(/^[a-z]{3}_ref/)
      # determines if we have a by-reference context object
      (entity, v, fmt) = key.split("_")
      ent = self.get_entity_obj(entity)
      unless ent
        self.foreign_keys[key] = val
        next
      end
      # by-reference requires two fields, format and location, if this is
      # the first field we've run across, set a place holder until we get
      # the other value          
      unless ref[entity]
        if fmt
          ref_key = "format"
        else 
          ref_key = "location"
        end
        ref[entity] = [ref_key, val]
      else
        if ref[entity][0] == "format"              
          instance_variable_get("@#{ent}").set_reference(val, ref[entity][1])
        else
          instance_variable_get("@#{ent}").set_reference(ref[entity][1], val)
        end
      end
    elsif key.match(/^[a-z]{3}_id$/)
      # Get the entity identifier
      (entity, v) = key.split("_")
      ent = self.get_entity_obj(entity)
      unless ent
        self.foreign_keys[key] = val
        next
      end
      # May or may not be an array, turn it into one.
      [value].flatten.each do | id |
        ent.add_identifier(id)
      end
              
    elsif key.match(/^[a-z]{3}_dat$/)
      # Get any private data          
      (entity, v) = key.split("_")
      ent = self.get_entity_obj(entity)
      unless ent
        self.foreign_keys[key] = val
        next
      end          
      ent.set_private_data(val)  
    else
      # collect the entity metadata
      keyparts = key.split(".")            
      if keyparts.length > 1
        # This is 1.0 OpenURL
        ent = self.get_entity_obj(keyparts[0])
        unless ent
          self.foreign_keys[key] = val
          next
        end            
        ent.(keyparts[1], val)
      else
        # This is a 0.1 OpenURL.  Your mileage may vary on how accurately
        # this maps.
        if key == 'id'
          if value.is_a?(Array)
            value.each do | id |
              @referent.add_identifier(id)
            end
          else
            @referent.add_identifier(val)
          end              
        elsif key == 'sid'
          @referrer.set_identifier("info:sid/"+val.to_s) 
        elsif key == 'pid'
          @referent.set_private_data(val.to_s)           
        else 
          @referent.(key, val)
        end
      end
    end
  end  
  

  
  # Initialize a new ContextObject object from an existing key/value hash
  def self.new_from_hash(hash)      
    co = self.new
    co.import_hash(hash)
    return co
  end
  
  # if we don't have a referent format (most likely because we have a 0.1
  # OpenURL), try to determine something from the genre.  If that doesn't 
  # exist, just call it a journal since most 0.1 OpenURLs would be one,
  # anyway. Case insensitive match, because some providers play fast and
  # loose. (BorrowDirect sends 'Book', which can confuse us otherwise)
  unless @referent.format
    fmt = case @referent.['genre']
    when /article|journal|issue|proceeding|conference|preprint/i then 'journal'
    when /book|bookitem|report|document/i then 'book'
    # 'dissertation' is not a real 'genre', but some use it anyway, and should
    # map to format 'dissertation' which is real. 
    when /dissertation/i then 'dissertation' 
    else 'journal'
    end
    @referent.set_format(fmt)
  end
end

#import_kev(kev) ⇒ Object

Imports an existing Key-encoded value string and sets the appropriate entities.



180
181
182
183
184
185
186
187
188
189
190
191
192
193
# File 'lib/openurl/context_object.rb', line 180

def import_kev(kev)      
  co = CGI::parse(kev)
  co2 = {}
  co.each do |key, val|
    if val.is_a?(Array)
      if val.length == 1
        co2[key] = val[0]
      else
        co2[key] = val
      end        
    end      	
  end
  self.import_hash(co2)
end

#import_xml(xml) ⇒ Object

Imports an existing XML encoded context object and sets the appropriate entities



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
# File 'lib/openurl/context_object.rb', line 239

def import_xml(xml)			
  if xml.is_a?(String)        
    xml.force_encoding("UTF-8") if xml.respond_to? :force_encoding
    xml.scrub!
    doc = REXML::Document.new xml.gsub(/>[\s\t]*\n*[\s\t]*</, '><').strip
  elsif xml.is_a?(REXML::Document)
    doc = xml
  else
    raise ArgumentError, "Argument must be an REXML::Document or well-formed XML string"
  end
  
  # Cut to the context object
  ctx = REXML::XPath.first(doc, ".//ctx:context-object", {"ctx"=>"info:ofi/fmt:xml:xsd:ctx"})



  

  
  ctx.attributes.each do |attr, val|				
    @admin.each do |adm, vals|
      self.set_administration_key(adm, val) if vals["label"] == attr											
    end
  end
  ctx.to_a.each do | ent |
    if @@defined_entities.value?(ent.name())
      self.import_entity(ent)
    else
      self.import_custom_node(ent)
    end
  end
end

#kev(no_date = false) ⇒ Object

Output the ContextObject as a Key-encoded value string. Pass a boolean true argument if you do not want the ctx_tim key included.



112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
# File 'lib/openurl/context_object.rb', line 112

def kev(no_date=false)
  kevs = ["url_ver=#{self.openurl_ver}", "url_ctx_fmt=#{CGI.escape("info:ofi/fmt:kev:mtx:ctx")}"]
  
  # Loop through the administrative metadata      
  @admin.each_key do |k|
    next if k == "ctx_tim" && no_date                    
    kevs.push(k+"="+CGI.escape(@admin[k]["value"].to_s)) if @admin[k]["value"]                  
  end

  {@referent=>"rft", @referringEntity=>"rfe", @requestor=>"req", @referrer=>"rfr"}.each do | ent, abbr |
    kevs.push(ent.kev(abbr)) unless ent.empty?                  
  end
  
  {@serviceType=>"svc", @resolver=>"res"}.each do |entCont, abbr|        
    entCont.each do |ent|
      next if ent.empty?          
      kevs.push(ent.kev(abbr))
    end
  end        
  return kevs.join("&")
end

#set_administration_key(key, val) ⇒ Object

Sets a ContextObject administration field.

Raises:

  • (ArgumentException)


172
173
174
175
# File 'lib/openurl/context_object.rb', line 172

def set_administration_key(key, val)
  raise ArgumentException, "#{key} is not a valid admin key!" unless @admin.keys.index(key)
  @admin[key]["value"] = val
end

#to_hashObject

Outputs the ContextObject as a ruby hash—hash version of the kev format. Outputting a context object as a hash is imperfect, because context objects can have multiple elements with the same key–and because some keys depend on SAP1 vs SAP2. So this function is really deprecated, but here because we have so much code dependent on it.



140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
# File 'lib/openurl/context_object.rb', line 140

def to_hash            
  co_hash = {"url_ver"=>self.openurl_ver, "url_ctx_fmt"=>"info:ofi/fmt:kev:mtx:ctx"}           
  
  @admin.each_key do |k|
    co_hash[k]=@admin[k]["value"] if @admin[k]["value"]
  end

  {@referent=>"rft", @referringEntity=>"rfe", @requestor=>"req", @referrer=>"rfr"}.each do | ent, abbr |
    co_hash.merge!(ent.to_hash(abbr)) unless ent.empty?
  end

  # svc  and res are arrays of ContextObjectEntity
  {@serviceType=>"svc", @resolver=>"res"}.each do |ent_list, abbr|        
    ent_list.each do |ent|
      co_hash.merge!(ent.to_hash(abbr)) unless ent.empty?
    end
  end        
  return co_hash
end

#xmlObject

Serialize the ContextObject to XML.



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
# File 'lib/openurl/context_object.rb', line 76

def xml      
  doc = REXML::Document.new()
  coContainer = doc.add_element "ctx:context-objects"
  coContainer.add_namespace("ctx","info:ofi/fmt:xml:xsd:ctx")
  coContainer.add_namespace("xsi", "http://www.w3.org/2001/XMLSchema-instance")
  coContainer.add_attribute("xsi:schemaLocation", "info:ofi/fmt:xml:xsd:ctx http://www.openurl.info/registry/docs/info:ofi/fmt:xml:xsd:ctx")
  co = coContainer.add_element "ctx:context-object"
  @admin.each_key do |k|
    next if k == "ctx_enc"
    co.add_attribute(@admin[k]["label"], @admin[k]["value"])
  end

  [{@referent=>"rft"}, 
    {@referringEntity=>"rfe"}, {@requestor=>"req"},        
    {@referrer=>"rfr"}].each do | entity |
    
    entity.each do | ent, label |
      ent.xml(co, label) unless ent.empty?
    end
  end
  
  [{@serviceType=>"svc"}, {@resolver=>"res"}].each do |entity|
    entity.each do | entCont, label |        
      entCont.each do |ent|
        ent.xml(co, label) unless ent.empty?                      
      end
    end
  end

  return doc.to_s
end