Class: Cul::Fedora::Item

Inherits:
Object
  • Object
show all
Includes:
Open3
Defined in:
lib/cul-fedora/item.rb

Constant Summary collapse

URI_TO_PID =
'info:fedora/'
MAX_LIST_MEMBERS_PER_REQUEST =
500

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(*args) ⇒ Item

Returns a new instance of Item.



26
27
28
29
30
31
32
# File 'lib/cul-fedora/item.rb', line 26

def initialize(*args)
  options = args.extract_options!
  @server = options[:server] || Server.new(options[:server_config])
  @logger = options[:logger]
  @pid = options[:pid] || options[:uri] || raise(ArgumentError, "requires uri or pid")
  @pid = @pid.to_s.sub(URI_TO_PID, "")
end

Instance Attribute Details

#pidObject (readonly)

Returns the value of attribute pid.



12
13
14
# File 'lib/cul-fedora/item.rb', line 12

def pid
  @pid
end

#serverObject (readonly)

Returns the value of attribute server.



12
13
14
# File 'lib/cul-fedora/item.rb', line 12

def server
  @server
end

Instance Method Details

#<=>(other) ⇒ Object



18
19
20
# File 'lib/cul-fedora/item.rb', line 18

def <=>(other)
  pid <=> other.pid
end

#==(other) ⇒ Object



38
39
40
41
# File 'lib/cul-fedora/item.rb', line 38

def ==(other)
  self.server == other.server
  self.pid == other.pid
end

#belongsToObject



120
121
122
123
124
125
126
127
128
129
130
# File 'lib/cul-fedora/item.rb', line 120

def belongsTo
  begin
    result = Nokogiri::XML(datastream("RELS-EXT"))
    result.xpath("/rdf:RDF/rdf:Description/*[local-name()='memberOf']").collect do |member|
      @server.item(member.attributes["resource"].value)
    end
  rescue Exception => e
    logger.error e.message
    []
  end
end

#datastream(name) ⇒ Object



66
67
68
# File 'lib/cul-fedora/item.rb', line 66

def datastream(name)
  request(:request => name.to_s.upcase)
end

#describedByObject



107
108
109
110
111
112
113
114
115
116
117
118
# File 'lib/cul-fedora/item.rb', line 107

def describedBy
  begin
    params = {:method => '/objects', :request => "describedBy", :sdef => "methods/ldpd:sdef.Core"}
    result = request(params)
    Nokogiri::XML(result).css("sparql>results>result>description").collect do ||
      @server.item(.attributes["uri"].value)
    end
  rescue Exception => e
    logger.error e.message
    []
  end
end

#exists?Boolean

Returns:

  • (Boolean)


43
44
45
46
47
48
49
50
51
52
# File 'lib/cul-fedora/item.rb', line 43

def exists?
  begin
    request
    return true
  rescue Exception => e # we should really do some better checking of error type etc here
	  logger.error "no object was found for fedora pid  #{pid}"
    logger.error e.message
    return false
  end
end

#getIndex(profile = "raw") ⇒ Object



62
63
64
# File 'lib/cul-fedora/item.rb', line 62

def getIndex(profile = "raw")
  Nokogiri::XML(request(:request => "getIndex", :sdef => "ldpd:sdef.Core", :profile => profile))
end

#getSizeObject



98
99
100
101
102
103
104
105
# File 'lib/cul-fedora/item.rb', line 98

def getSize()
  begin
    request(:method => "/objects", :sdef => "methods/ldpd:sdef.Aggregator", :request => "getSize").to_i
  rescue Exception => e
    logger.error e.message
    return -1
  end
end

#index_for_ac2(options = {}) ⇒ Object



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
# File 'lib/cul-fedora/item.rb', line 132

def index_for_ac2(options = {})
  do_fulltext = options[:fulltext] || false
   = options[:metadata] || true

  status = :success
  error_message = ""


  results = Hash.new { |h,k| h[k] = [] }
  normalize_space = lambda { |s| s.to_s.strip.gsub(/\s{2,}/," ") }
  search_to_content = lambda { |x| x.kind_of?(Nokogiri::XML::Element) ? x.content.strip : x.to_s.strip }
  add_field = lambda { |name, value| results[name] << search_to_content.call(value) }

  get_fullname = lambda { |node| node.nil? ? nil : (node.css("namePart[@type='family']").collect(&:content) | node.css("namePart[@type='given']").collect(&:content)).join(", ") }

  author_roles = ["author","creator","editor","speaker","moderator","interviewee","interviewer","contributor"]
  other_name_roles = ["thesis advisor"]
  corporate_author_roles = ["author"]
  corporate_department_roles = ["originator"]

  organizations = []
  departments = []
    
  begin
    collections = self.belongsTo
    meta = describedBy.first

    meta = Nokogiri::XML(meta.datastream("CONTENT")) if meta
    mods = meta.at_css("mods") if meta

    if mods && 
      # baseline blacklight fields: id is the unique identifier, format determines by default, what partials get called
      add_field.call("id", @pid)
      add_field.call("internal_h",  collections.first.to_s + "/")
      add_field.call("pid", @pid)
      collections.each do |collection|
        add_field.call("member_of", collection)
      end



      title = mods.css("titleInfo>title").first.text
      title_search = normalize_space.call(mods.css("titleInfo>nonSort,title").collect(&:content).join(" "))
      record_creation_date = mods.at_css("recordInfo>recordCreationDate")
      if(record_creation_date.nil?)
        record_creation_date = mods.at_css("recordInfo>recordChangeDate")
      end
      if(!record_creation_date.nil? || !record_creation_date.empty?)
        record_creation_date = DateTime.parse(record_creation_date.text.gsub("UTC", "").strip)
        add_field.call("record_creation_date", record_creation_date.strftime("%Y-%m-%dT%H:%M:%SZ"))
      end
      add_field.call("title_display", title)
      add_field.call("title_search", title_search)

      all_author_names = []
      mods.css("name[@type='personal']").each do |name_node|
        
        fullname = get_fullname.call(name_node)
        note_org = false
        
        if name_node.css("role>roleTerm").collect(&:content).any? { |role| author_roles.include?(role) }

          note_org = true
          all_author_names << fullname
          if(!name_node["ID"].nil?)
            add_field.call("author_uni", name_node["ID"])
          end
          add_field.call("author_search", fullname.downcase)
          add_field.call("author_facet", fullname)

        elsif name_node.css("role>roleTerm").collect(&:content).any? { |role| other_name_roles.include?(role) }

          note_org = true
          first_role = name_node.at_css("role>roleTerm").text
          add_field.call(first_role.gsub(/\s/, '_'), fullname)

        end
        
        if (note_org == true)
          name_node.css("affiliation").each do |affiliation_node|
            affiliation_text = affiliation_node.text
            if(affiliation_text.include?(". "))
              affiliation_split = affiliation_text.split(". ")
              organizations.push(affiliation_split[0].strip)
              departments.push(affiliation_split[1].strip)
            end
          end
        end
        
      end
      
      mods.css("name[@type='corporate']").each do |corp_name_node|
        if((!corp_name_node["ID"].nil? && corp_name_node["ID"].include?("originator")) || corp_name_node.css("role>roleTerm").collect(&:content).any? { |role| corporate_department_roles.include?(role) })
          name_part = corp_name_node.at_css("namePart").text
          if(name_part.include?(". "))
            name_part_split = name_part.split(". ")
            organizations.push(name_part_split[0].strip)
            departments.push(name_part_split[1].strip)
          end
        end
        if corp_name_node.css("role>roleTerm").collect(&:content).any? { |role| corporate_author_roles.include?(role) }
          display_form = corp_name_node.at_css("displayForm") 
          if(!display_form.nil?)
            fullname = display_form.text
          else
            fullname = corp_name_node.at_css("namePart").text
          end
          all_author_names << fullname
          add_field.call("author_search", fullname.downcase)
          add_field.call("author_facet", fullname)
        end
      end

      add_field.call("author_display",all_author_names.join("; "))
      add_field.call("pub_date_facet", mods.at_css("*[@keyDate='yes']"))

      mods.css("genre").each do |genre_node|
        add_field.call("genre_facet", genre_node)
        add_field.call("genre_search", genre_node)
      end


      add_field.call("abstract", mods.at_css("abstract"))
      add_field.call("handle", mods.at_css("identifier[@type='hdl']"))

      mods.css("subject").each do |subject_node|
        if(subject_node.attributes.count == 0)
          subject_node.css("topic").each do |topic_node|
            add_field.call("keyword_search", topic_node.content.downcase)
            add_field.call("subject_facet", topic_node)
            add_field.call("subject_search", topic_node)
          end
        end
      end


      add_field.call("table_of_contents", mods.at_css("tableOfContents"))

      mods.css("note").each { |note| add_field.call("notes", note) }

      if (related_host = mods.at_css("relatedItem[@type='host']"))
        book_journal_title = related_host.at_css("titleInfo>title") 

        if book_journal_title
          book_journal_subtitle = mods.at_css("name>titleInfo>subTitle")

          book_journal_title = book_journal_title.content + ": " + book_journal_subtitle.content.to_s if book_journal_subtitle

        end

        add_field.call("book_journal_title", book_journal_title)

        add_field.call("book_author", get_fullname.call(related_host.at_css("name"))) 

        add_field.call("issn", related_host.at_css("identifier[@type='issn']"))
      end
      
      if(related_series = mods.at_css("relatedItem[@type='series']"))
        if(related_series.has_attribute?("ID"))
          add_field.call("series_facet", related_series.at_css("titleInfo>title"))
		add_field.call("part_number", related_series.at_css("titleInfo>partNumber"))
        end
      end

      add_field.call("publisher", mods.at_css("relatedItem>originInfo>publisher"))
      add_field.call("publisher_location", mods.at_css("relatedItem > originInfo>place>placeTerm[@type='text']"))
      add_field.call("isbn", mods.at_css("relatedItem>identifier[@type='isbn']"))
      add_field.call("doi", mods.at_css("identifier[@type='doi'][@displayLabel='Published version']"))

      mods.css("physicalDescription>internetMediaType").each { |mt| add_field.call("media_type_facet", mt) }

      mods.css("typeOfResource").each { |tr| add_field.call("type_of_resource_facet", tr)}
      mods.css("subject>geographic").each do |geo|
        add_field.call("geographic_area_display", geo)
        add_field.call("geographic_area_search", geo)
      end

      # This is just a placeholder, reminding us that we need to implement citations in some way
      # add_field.call("export_as_mla_citation_txt","")
      
      if(organizations.count > 0)
        organizations = organizations.uniq
        organizations.each do |organization|
          add_field.call("organization_facet", organization)
        end
      end
      
      if(departments.count > 0)
        departments = departments.uniq
        departments.each do |department|
          add_field.call("department_facet", department.to_s.sub(", Department of", "").strip)
        end
      end
      
    end


    if do_fulltext 
      listMembers.each_with_index do |member, i|
        tika_directory = File.expand_path(File.join(File.expand_path(File.dirname(__FILE__)), "..", "tika"))

        resource_file_name = File.join(tika_directory, "scratch", Time.now.to_i.to_s + "_" + rand(10000000).to_s)
        tika_jar = File.join(tika_directory, "tika-0.3.jar")

        File.open(resource_file_name, "w") { |f| f.puts(member.datastream("CONTENT")) }


        tika_result = []
        tika_error = []

        Open3.popen3("java -jar #{tika_jar} -t #{resource_file_name}") do |stdin, stdout, stderr|
          tika_result = stdout.readlines
          tika_error = stderr.readlines
        end

        unless tika_error.empty?
          status = :error
          error_message += tika_error.join("\n")
        else


          add_field.call("ac.fulltext_#{i}", tika_result)
        end

        File.delete(resource_file_name)
      
      
      
      end



    end

  rescue Exception => e
    status = :error
    error_message += e.message
  end

  status = :invalid_format  if results.empty?

  return {:status => status, :error_message => error_message, :results => results}

end

#listMembersObject



78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
# File 'lib/cul-fedora/item.rb', line 78

def listMembers()
  begin
    i = 1
    size = getSize
    items = []
    while (i <= size)
      result = Nokogiri::XML(request(:method => "/objects", :sdef => "methods/ldpd:sdef.Aggregator", :request => "listMembers", :format => "sparql", :max => MAX_LIST_MEMBERS_PER_REQUEST, :start => (i - 1)))

      result.css("sparql>results>result>member").collect do |result_node|
        items << @server.item(result_node.attributes["uri"].value)
      end
      i = i + MAX_LIST_MEMBERS_PER_REQUEST
    end
    return items
  rescue Exception => e
    logger.error e.message
    []
  end
end

#loggerObject



34
35
36
# File 'lib/cul-fedora/item.rb', line 34

def logger
  @logger ||= Logger.new
end

#pid_escapedObject



22
23
24
# File 'lib/cul-fedora/item.rb', line 22

def pid_escaped
  pid.gsub(/:/,'\\:')
end

#request(options = {}) ⇒ Object



54
55
56
# File 'lib/cul-fedora/item.rb', line 54

def request(options = {})
  @server.request(options.merge(:pid => @pid))
end

#request_path(options = {}) ⇒ Object



58
59
60
# File 'lib/cul-fedora/item.rb', line 58

def request_path(options = {})
  @server.request_path(options.merge(:pid => @pid))
end

#risearch_for_membersObject



71
72
73
74
75
76
# File 'lib/cul-fedora/item.rb', line 71

def risearch_for_members()
  results = JSON::parse(@server.request(:method => "", :request => "risearch", :format => "json", :lang => "itql", :query => sprintf(@server.riquery, @pid)))["results"]

  results.collect { |r| @server.item(r["member"]) }

end

#to_sObject



379
380
381
# File 'lib/cul-fedora/item.rb', line 379

def to_s
  @pid
end