Class: DoverToCalais::ResponseData

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

Overview

This class is responsible for creating a response object that will be passed to Dover, after the data source has been analysed by OpenCalais. If the response contains valid data, the #error attribute will be nil. The response object will then contain the OpenCalais response as an XML string. The user can then call #filter to filter the response. If the response doesn’t contain valid, processed data then the #error won’t be nil (i.e. will be true). The #error attribute can then be read in order to find the cause of the error.

Defined Under Namespace

Classes: Entity, Event, GenericRelation

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(response_data = nil, error = nil) ⇒ ResponseData

creates a new ResponseData object, passing the name of the data source to be processed

Parameters:

  • response_data (Nokogiri::XML::NodeSet, Hash, nil) (defaults to: nil)

    the XML or JSON data returned by OpenCalais

  • error (String, nil) (defaults to: nil)

    an error description if the OpenCalais call has failed



143
144
145
146
147
148
149
150
151
152
153
154
155
# File 'lib/dover_to_calais.rb', line 143

def initialize(response_data = nil, error = nil)
  if response_data.class.to_s == "Nokogiri::XML::Document"
    @xml_data = response_data
  elsif response_data.class.to_s == "Hash"
    @json_data = response_data
    prepare_data(response_data)


  else
    @error = error
  end

end

Instance Attribute Details

#entities_storeObject (readonly)

Returns the value of attribute entities_store.



138
139
140
# File 'lib/dover_to_calais.rb', line 138

def entities_store
  @entities_store
end

#errorString? (readonly)

Returns any error that occurred as a result of the OpenCalais API call, nil if none occurred.

Returns:

  • (String, nil)

    any error that occurred as a result of the OpenCalais API call, nil if none occurred



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
# File 'lib/dover_to_calais.rb', line 78

class ResponseData



  class Entity< Struct.new(:type, :name, :ref)

    def to_hash
      a_hash = {}
      self.each_pair do |attr, value|
        a_hash[attr] =  value
      end
      a_hash
    end

  end

  class GenericRelation< Struct.new(:subject, :verb, :object, :detection)

  end #class

  class Event

    attr_reader :entities

    def initialize(events_hash)
      # @entities = entity_hash
      events_hash.each do |k,v|
        unless k.eql?('_typeGroup') || k.eql?('instances') || k.eql?('_typeReference')
          k = 'type' if k.eql?('_type') #don't like the underscore
          ## create and initialize an instance variable for this key/value pair
          self.instance_variable_set("@#{k}", v)
          ## create the getter that returns the instance variable
          self.class.send(:define_method, k, proc{self.instance_variable_get("@#{k}")})
          ## create the setter that sets the instance variable
          self.class.send(:define_method, "#{k}=", proc{|v| self.instance_variable_set("@#{k}", v)})
        end
      end #block
    end #method

    def each_pair
      self.instance_variables.each do |a|
        yield a, self.instance_variable_get(a)
      end
    end

    def [](attrib_name)
      self.instance_variables.each do |a|
        if "@#{a}" == attrib_name
          self.instance_variable_get(a)
        end
      end
    end

    public :each_pair

  end #class




  attr_reader :error, :entities_store, :events_store, :generic_relations_store, :freds
  # creates a new ResponseData object, passing the name of the data source to be processed
  #
  # @param response_data [ Nokogiri::XML::NodeSet, Hash, nil] the XML or JSON data returned by OpenCalais
  # @param error [ String, nil] an error description if the OpenCalais call has failed
  def initialize(response_data = nil, error = nil)
    if response_data.class.to_s == "Nokogiri::XML::Document"
      @xml_data = response_data
    elsif response_data.class.to_s == "Hash"
      @json_data = response_data
      prepare_data(response_data)


    else
      @error = error
    end

  end

  # Returns  the response data as an XML string or an error, if one has occurred.
  #
  # @return [String] an XML string
  def to_s
    if @xml_data
      @xml_data.to_s
    elsif @json_data
      @json_data.to_s
    else
      @error
    end
  end




  # The method will first create three Hash instance variables, where it will store the
  # Entities, Generic Relations and Events -respectively- from the OpenCalais response.
  # The key on each Hash instance variable will be the OpenCalais ID and the value will
  # be the values_hash for that ID.
  # Secondly, the method will iterate through each Entity, find all of it's related
  # Relations and Events and store them -in a relational manner- in Redis, via Ohm.
  #
  # Only applicable with the JSON (rich) output format
  #
  # @param Hash the OpenCalais JSON response, as a Hash
  # @return an GenericRelation Struct if a match is found, nil otherwise

  def prepare_data(results_hash)

    @entities_store = {}
    @generic_relations_store = {}
    @events_store = {}
    # find all Entities in response
    @entities_store = results_hash.select{|key, hash| hash["_typeGroup"] == "entities"}
    # find all GenericRelations in response
    @generic_relations_store = results_hash.select{|key, hash| hash["_typeGroup"] == "relations" &&
    hash["_type"] == "GenericRelations"}
    # find all Events in response
    @events_store = results_hash.select{|key, hash| hash["_typeGroup"] == "relations" &&
    hash["_type"] != "GenericRelations"}

    Ohm.redis = Redic.new(REDIS)


    #for each Entity find all related Relations and Events and store them to Ohm/Redis
    @entities_store.each_pair do |k, v|

      entity_set = EntityModel.find(calais_id: k)

      if entity_set.size > 0 #entity already exists in store
        entity = entity_set.first
        k = entity.calais_id
      else #entity doesn't exist in store
        entity = EntityModel.create(:name => v['name'], :type => v['_type'], :calais_id => k)
        entity.save
      end #if


      #get all referenced relations
      find_in_relations(k).each do |obj|

        found_rel = get_relation(obj[0])
        if found_rel

          found_rel.subject = convert_to_hash(found_rel.subject)
          found_rel.object = convert_to_hash(found_rel.object)

          relation = EntityModel::RelationModel.create(:subject => found_rel.subject,
          :object => found_rel.object,
          :verb => found_rel.verb,
          :detection => found_rel.detection,
          :calais_id => obj[0])
          entity.relations.add(relation)
        end #if
      end #each
      #get all referenced events
      find_in_events(k).each do |obj|
        found_event = get_event(obj[0])
        attribs = {}
        if found_event

          found_event.each_pair do |key, val|

            key = key.to_s.slice(1, key.length-1)
            attribs[key] = val

          end #block

          event = EntityModel::EventModel.create(:calais_id => obj[0], :info_hash => attribs)
          entity.events.add(event)

        end #if

      end #each
    end #each_pair
  end #method



  # Coverts an attribute to an appropriate Hash
  #
  # Only applicable with the JSON (rich) output format
  #
  # @param [String, DoverToCalais::ResponseData::Entity, Hash] an object
  # @return a Hash value
  def convert_to_hash(an_attribute)
    h = {}
    if an_attribute.class.to_s.eql?('String')
      h[:name] = an_attribute
    end

    if an_attribute.class.to_s.eql?('DoverToCalais::ResponseData::Entity')
      h = an_attribute.to_hash
    end

    if an_attribute.class.to_s.eql?('Hash')
      h = an_attribute
    end

    h
  end #method



  # Retrieves the entity with the specified key (OpenCalais ID)
  #
  # Only applicable with the JSON (rich) output format
  #
  # @param String the OpenCalais ID
  # @return an Entity Struct if a match is found, nil otherwise
  def get_entity(ref_key)
    if @entities_store.has_key?(ref_key)
      Entity.new(@entities_store[ref_key]['_type'],  @entities_store[ref_key]['name'], ref_key)
    else
      nil
    end
  end


  # Retrieves the relation with the specified key (OpenCalais ID). The method will also
  # de-reference any of its attributes that refer to other entities via an OpenCalais ID
  # and will replace the references with the appropriate Entity structure, if applicable
  #
  # Only applicable with the JSON (rich) output format
  #
  # @param String the OpenCalais ID
  # @return an GenericRelation Struct if a match is found, nil otherwise
  def get_relation(ref_key)
    if @generic_relations_store.key?(ref_key)

      if @generic_relations_store[ref_key]['relationsubject']
        gr_subject = @generic_relations_store[ref_key]['relationsubject'].match('^http://d.opencalais.com') ?
        get_entity(@generic_relations_store[ref_key]['relationsubject']) :
        @generic_relations_store[ref_key]['relationsubject']
      else
        gr_subject = 'N/A'
      end


      if @generic_relations_store[ref_key]['relationobject']
        gr_object = @generic_relations_store[ref_key]['relationobject'].match('^http://d.opencalais.com') ?
        get_entity(@generic_relations_store[ref_key]['relationobject']) :
        @generic_relations_store[ref_key]['relationobject']
      else
        gr_object = 'N/A'
      end

      GenericRelation.new(gr_subject,
      @generic_relations_store[ref_key]['verb'],
      gr_object,
      @generic_relations_store[ref_key]['instances'][0]['exact'] ||= 'N/A')
    else
      nil
    end
  end

  def get_event(ref_key)

    dereferenced_events = {}

    if @events_store.key?(ref_key)

      @events_store[ref_key].each do |k, v|

        if v.class.to_s.eql?("String") && v.match('^http://d.opencalais.com')
          dereferenced_events[k] = get_entity(v).to_hash
        elsif v.class.to_s.eql?("String") && !v.match('^http://d.opencalais.com')
          h = {}
          h['name'] = v
          dereferenced_events[k] = h
        elsif v.class.to_s.eql?("Array")
          h = {}
          h['name'] = v[0]['exact']
          dereferenced_events[k] = h
        end
      end

      Event.new(dereferenced_events)
    else
      nil
    end
  end


  # Selects a Hash of generic relations, where the relations' subject or object attributes
  # match the specified OpenCalais ID.
  #
  # Only applicable with the JSON (rich) output format
  #
  # @param String the OpenCalais ID
  # @return a Hash with the selected matches
  def find_in_relations(ref_key)
    @generic_relations_store.select{|key, hash| (hash["relationsubject"] == ref_key) ||
    (hash["relationobject"] == ref_key) }

  end

  # Selects a Hash of events, where the events' key matches the
  # specified OpenCalais ID.
  #
  # Only applicable with the JSON (rich) output format
  #
  # @param String the OpenCalais ID
  # @return a Hash with the selected matches
  def find_in_events(ref_key)
    @events_store.select{|key, hash| hash.has_value?(ref_key) }
  end



  # Filters the xml response object to extract relevant data.
  #
  # @param params [Hash] a filter Hash (see code samples)
  # @return [Array[ResponseItem]] a list of relevant response items
  def filter(params)
    unless  @xml_data
      return 'ERR: filter method only works with xml-based output!'

    end

    result = Array.new
    begin
      if @xml_data

        if params[:given]
          found = @xml_data.xpath("//#{params[:given][:entity]}[contains(text(), #{params[:given][:value].inspect})]")
          if found.size > 0
            @xml_data.xpath("//#{params[:entity]}[contains(text(), #{params[:value].inspect})]").each do |node|
              result <<  create_response_item(node)
            end
          end
        else  # no conditional
          @xml_data.xpath("//#{params[:entity]}[contains(text(), #{params[:value].inspect})]").each do |node|
            result <<  create_response_item(node)
          end
        end

        return result
      else # no xml data
        return 'ERR: no valid xml data!'

      end #if

    rescue  Exception=>e
      return "ERR: #filter:  #{e}"

    end

    return result

  end  #method

  # Creates a Response Item from an xml node.
  #
  # @param node [Nokogiri::XML::Node] an XML node
  # @return [ResponseItem] a response item object
  def create_response_item(node)
    node_relevance =  node.attribute('relevance').text.to_f if node.has_attribute?('relevance')
    node_count =  node.attribute('count').text.to_i if node.has_attribute?('count')
    node_normalized =  node.attribute('normalized').text if node.has_attribute?('normalized')
    node_importance = node.attribute('importance').text.to_i if node.has_attribute?('importance')
    node_orig_value =  node.xpath('originalValue').text if node.name.eql?('SocialTag')

    ResponseItem.new(node.name,
    node.text,
    node_relevance,
    node_count,
    node_normalized,
    node_importance,
    node_orig_value )

  end

  public :filter
  private :create_response_item, :prepare_data, :convert_to_hash, :find_in_relations, :find_in_events,
          :get_event, :get_entity

end

#events_storeObject (readonly)

Returns the value of attribute events_store.



138
139
140
# File 'lib/dover_to_calais.rb', line 138

def events_store
  @events_store
end

#fredsObject (readonly)

Returns the value of attribute freds.



138
139
140
# File 'lib/dover_to_calais.rb', line 138

def freds
  @freds
end

#generic_relations_storeObject (readonly)

Returns the value of attribute generic_relations_store.



138
139
140
# File 'lib/dover_to_calais.rb', line 138

def generic_relations_store
  @generic_relations_store
end

Instance Method Details

#filter(params) ⇒ Array[ResponseItem]

Filters the xml response object to extract relevant data.

Parameters:

  • params (Hash)

    a filter Hash (see code samples)

Returns:

  • (Array[ResponseItem])

    a list of relevant response items



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
# File 'lib/dover_to_calais.rb', line 392

def filter(params)
  unless  @xml_data
    return 'ERR: filter method only works with xml-based output!'

  end

  result = Array.new
  begin
    if @xml_data

      if params[:given]
        found = @xml_data.xpath("//#{params[:given][:entity]}[contains(text(), #{params[:given][:value].inspect})]")
        if found.size > 0
          @xml_data.xpath("//#{params[:entity]}[contains(text(), #{params[:value].inspect})]").each do |node|
            result <<  create_response_item(node)
          end
        end
      else  # no conditional
        @xml_data.xpath("//#{params[:entity]}[contains(text(), #{params[:value].inspect})]").each do |node|
          result <<  create_response_item(node)
        end
      end

      return result
    else # no xml data
      return 'ERR: no valid xml data!'

    end #if

  rescue  Exception=>e
    return "ERR: #filter:  #{e}"

  end

  return result

end

#get_relation(ref_key) ⇒ Object

Retrieves the relation with the specified key (OpenCalais ID). The method will also de-reference any of its attributes that refer to other entities via an OpenCalais ID and will replace the references with the appropriate Entity structure, if applicable

Only applicable with the JSON (rich) output format

Parameters:

  • String

    the OpenCalais ID

Returns:

  • an GenericRelation Struct if a match is found, nil otherwise



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
# File 'lib/dover_to_calais.rb', line 305

def get_relation(ref_key)
  if @generic_relations_store.key?(ref_key)

    if @generic_relations_store[ref_key]['relationsubject']
      gr_subject = @generic_relations_store[ref_key]['relationsubject'].match('^http://d.opencalais.com') ?
      get_entity(@generic_relations_store[ref_key]['relationsubject']) :
      @generic_relations_store[ref_key]['relationsubject']
    else
      gr_subject = 'N/A'
    end


    if @generic_relations_store[ref_key]['relationobject']
      gr_object = @generic_relations_store[ref_key]['relationobject'].match('^http://d.opencalais.com') ?
      get_entity(@generic_relations_store[ref_key]['relationobject']) :
      @generic_relations_store[ref_key]['relationobject']
    else
      gr_object = 'N/A'
    end

    GenericRelation.new(gr_subject,
    @generic_relations_store[ref_key]['verb'],
    gr_object,
    @generic_relations_store[ref_key]['instances'][0]['exact'] ||= 'N/A')
  else
    nil
  end
end

#to_sString

Returns the response data as an XML string or an error, if one has occurred.

Returns:

  • (String)

    an XML string



160
161
162
163
164
165
166
167
168
# File 'lib/dover_to_calais.rb', line 160

def to_s
  if @xml_data
    @xml_data.to_s
  elsif @json_data
    @json_data.to_s
  else
    @error
  end
end