Class: Bplmodels::ObjectBase

Inherits:
ActiveFedora::Base
  • Object
show all
Includes:
ActiveFedora::Auditable, Hydra::AccessControls::Permissions, Hydra::ModelMethods
Defined in:
app/models/bplmodels/object_base.rb

Direct Known Subclasses

ComplexObjectBase, SimpleObjectBase

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.mint(args) ⇒ Object

Expects the following args: parent_pid => id of the parent object local_id => local ID of the object local_id_type => type of that local ID label => label of the object institution_pid => instituional access of this file secondary_parent_pids => optional array of additional parent pids



1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
# File 'app/models/bplmodels/object_base.rb', line 1040

def self.mint(args)

  expected_aguments = [:parent_pid, :local_id, :local_id_type, :institution_pid, :secondary_parent_pids]
  expected_aguments.each do |arg|
    if !args.keys.include?(arg)
      raise "Mint called but missing parameter: #{arg}"
    end
  end

  #TODO: Duplication check here to prevent over-writes?

  args[:namespace_id] ||= ARK_CONFIG_GLOBAL['namespace_commonwealth_pid']
  args[:secondary_parent_pids] ||= []

  response = Typhoeus::Request.post(ARK_CONFIG_GLOBAL['url'] + "/arks.json", :params => {:ark=>{:parent_pid=>args[:parent_pid], :secondary_parent_pids=>args[:secondary_parent_pids], :namespace_ark => ARK_CONFIG_GLOBAL['namespace_commonwealth_ark'], :namespace_id=>args[:namespace_id], :url_base => ARK_CONFIG_GLOBAL['ark_commonwealth_base'], :model_type => self.name, :local_original_identifier=>args[:local_id], :local_original_identifier_type=>args[:local_id_type]}})

  begin
    as_json = JSON.parse(response.body)
  rescue => ex
    raise('Error in JSON response for minting an object pid.')
  end

  puts as_json['pid']

  #For some reason, the below stopped working suddenly?
=begin
  dup_check = ActiveFedora::Base.find(:pid=>as_json["pid"])
  if dup_check.present?
    return as_json["pid"]
  end
=end


  Bplmodels::ObjectBase.find_in_batches('id'=>as_json["pid"]) do |group|
    group.each { |solr_result|
      return as_json["pid"]
    }
  end

  object = self.new(:pid=>as_json["pid"])

  object.add_relationship(:is_member_of_collection, "info:fedora/" + args[:parent_pid])
  object.add_relationship(:administrative_set, "info:fedora/" + args[:parent_pid])

  args[:secondary_parent_pids].each do |other_collection_pid|
    object.add_relationship(:is_member_of_collection, "info:fedora/" + other_collection_pid)
  end

  object.add_oai_relationships

  object.label = args[:label] if args[:label].present?

  object..item_ark_info.ark_id = args[:local_id]
  object..item_ark_info.ark_type = args[:local_id_type]
  object..item_ark_info.ark_parent_pid = args[:parent_pid]

  object.read_groups = ["public"]
  object.edit_groups = ["superuser", "admin[#{args[:institution_pid]}]"] if args[:institution_pid]

  return object
end

Instance Method Details

#add_new_volume(pid) ⇒ Object



1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
# File 'app/models/bplmodels/object_base.rb', line 1515

def add_new_volume(pid)
  #raise 'insert new image called with no files or more than one!' if file.blank? || file.is_a?(Array)
  volume = Bplmodels::Volume.find(pid).adapt_to_cmodel
  placement_location = volume..title_info.part_number.first.match(/\d+/).to_s.to_i

  other_volumes_exist = false
  volume_placed = false
  queryed_placement_start_val = 0

  volume_objects = Bplmodels::Finder.getVolumeObjects(self.pid)
  volume_objects.each do |volume_id|
    if !volume_placed
      queryed_placement_end_val = volume_id['title_info_partnum_tsi'].match(/\d+/).to_s.to_i
      queryed_placement_start_val ||= queryed_placement_end_val
      other_volumes_exist = true

      #Case of insert at end
      if volume_id['is_preceding_volume_of_ssim'].blank? && queryed_placement_end_val < placement_location
        preceding_volume = Bplmodels::Volume.find(volume_id['id'])
        preceding_volume.add_relationship(:is_preceding_volume_of, "info:fedora/#{pid}", true)
        preceding_volume.save
        volume.add_relationship(:is_following_volume_of, "info:fedora/#{volume_id['id']}", true)
        volume_placed = true
        #Case of only 1 element of volume 2... insert at beginning
      elsif volume_id['is_preceding_volume_of_ssim'].blank?
        following_volume = Bplmodels::Volume.find(volume_id['id'])
        following_volume.add_relationship(:is_following_volume_of, "info:fedora/#{pid}", true)

        volume.add_relationship(:is_preceding_volume_of, "info:fedora/#{volume_id['id']}", true)
        following_volume.save
        volume_placed = true
        #Case of multiple but insert at front
      elsif volume_id['is_following_volume_of_ssim'].blank? && queryed_placement_start_val < placement_location and queryed_placement_end_val > placement_location
        following_volume = Bplmodels::Volume.find(volume_id['id'])
        following_volume.add_relationship(:is_following_volume_of, "info:fedora/#{pid}", true)

        volume.add_relationship(:is_preceding_volume_of, "info:fedora/#{volume_id['id']}", true)
        following_volume.save
        volume_placed = true
        #Normal case
      elsif queryed_placement_start_val < placement_location and queryed_placement_end_val > placement_location
        following_volume = Bplmodels::Volume.find(volume_id['id'])
        preceding_volume = Bplmodels::Volume.find(volume_id['is_preceding_volume_of_ssim'].gsub('info:fedora/', ''))

        following_volume.remove_relationship(:is_following_volume_of, "info:fedora/#{preceding_volume.pid}", true)
        preceding_volume.remove_relationship(:is_preceding_volume_of, "info:fedora/#{following_volume.pid}", true)


        following_volume.add_relationship(:is_following_volume_of, "info:fedora/#{pid}", true)
        preceding_volume.add_relationship(:is_preceding_volume_of, "info:fedora/#{pid}", true)


        volume.add_relationship(:is_following_volume_of, "info:fedora/#{preceding_volume.pid}", true)
        volume.add_relationship(:is_preceding_volume_of, "info:fedora/#{following_volume.pid}", true)
        preceding_volume.save
        following_volume.save
        volume_placed = true
      end
    end

    queryed_placement_start_val = queryed_placement_end_val
  end

  volume.add_relationship(:is_volume_of, "info:fedora/" + self.pid)

  #FIXME: Doesn't work with PDF?
  #FIXME: Do this better?
  if !other_volumes_exist
    ActiveFedora::Base.find_in_batches('is_exemplary_image_of_ssim'=>"info:fedora/#{pid}") do |group|
      group.each { |exemplary_solr|
        exemplary_image = Bplmodels::File.find(exemplary_solr['id']).adapt_to_cmodel
        exemplary_image.add_relationship(:is_exemplary_image_of, "info:fedora/" + self.pid)
        exemplary_image.save
      }
    end
  elsif placement_location == 1
    if ActiveFedora::Base.find_with_conditions("is_exemplary_image_of_ssim"=>"info:fedora/#{self.pid}").present?
      exemplary_to_remove_id = ActiveFedora::Base.find_with_conditions("is_exemplary_image_of_ssim"=>"info:fedora/#{self.pid}").first['id']
      exemplary_to_remove = ActiveFedora::Base.find(exemplary_to_remove_id).adapt_to_cmodel
      exemplary_to_remove.remove_relationship(:is_exemplary_image_of, "info:fedora/" + exemplary_to_remove_id)
    end

    ActiveFedora::Base.find_in_batches('is_exemplary_image_of_ssim'=>"info:fedora/#{pid}") do |group|
      group.each { |exemplary_solr|
        exemplary_image = Bplmodels::File.find(exemplary_solr['id']).adapt_to_cmodel
        exemplary_image.add_relationship(:is_exemplary_image_of, "info:fedora/" + self.pid)
        exemplary_image.save
      }
    end
  end


  volume.save

  volume
end

#add_oai_relationshipsObject



81
82
83
# File 'app/models/bplmodels/object_base.rb', line 81

def add_oai_relationships
  self.add_relationship(:oai_item_id, "oai:digitalcommonwealth.org:" + self.pid, true)
end

#apply_default_permissionsObject



76
77
78
79
# File 'app/models/bplmodels/object_base.rb', line 76

def apply_default_permissions
  self.datastreams["rightsMetadata"].update_permissions( "group"=>{"Repository Administrators"=>"edit", "Repository Administrators"=>"read", "Repository Administrators"=>"discover"} )
  self.save
end

#assert_content_modelObject



179
180
181
182
183
184
185
186
# File 'app/models/bplmodels/object_base.rb', line 179

def assert_content_model
  super()
  object_superclass = self.class.superclass
  until object_superclass == ActiveFedora::Base || object_superclass == Object do
    add_relationship(:has_model, object_superclass.to_class_uri)
    object_superclass = object_superclass.superclass
  end
end

#cache_invalidateObject



1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
# File 'app/models/bplmodels/object_base.rb', line 1663

def cache_invalidate
  response = Typhoeus::Request.post(DERIVATIVE_CONFIG_GLOBAL['url'] + "/processor/objectcacheinvalidation.json", :params => {:object_pid=>self.pid, :environment=>Bplmodels.environment})
  as_json = JSON.parse(response.body)

  if as_json['result'] == "false"
    raise "Error Deleting the Cache! Server error!"
  end

  return true
end

#calculate_volume_match_md5sObject



1675
1676
1677
1678
# File 'app/models/bplmodels/object_base.rb', line 1675

def calculate_volume_match_md5s
  self..volume_match_md5s.marc = Digest::MD5.hexdigest(self.marc.content)
  self..volume_match_md5s.iaMeta = Digest::MD5.hexdigest(self.iaMeta.content.gsub(/<\/page_progression>.+$/, '').gsub(/<volume>.+<\/volume>/, ''))
end

#convert_to(klass) ⇒ Object

Rough initial attempt at this implementation use test2.relationships(:has_model)?



160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
# File 'app/models/bplmodels/object_base.rb', line 160

def convert_to(klass)
  #if !self.instance_of?(klass)
  adapted_object = self.adapt_to(klass)

  adapted_object.relationships.each_statement do |statement|
    if statement.predicate == "info:fedora/fedora-system:def/model#hasModel"
      adapted_object.remove_relationship(:has_model, statement.object)
      #puts statement.object
    end
  end

  adapted_object.assert_content_model
  adapted_object.save
  adapted_object
  #end

end

#delete(delete_files = true) ⇒ Object

def save

  super()
end


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
# File 'app/models/bplmodels/object_base.rb', line 97

def delete(delete_files=true)
  if delete_files
    Bplmodels::File.find_in_batches('is_file_of_ssim'=>"info:fedora/#{self.pid}") do |group|
      group.each { |solr_file|
        file = Bplmodels::File.find(solr_file['id']).adapt_to_cmodel
        file.delete
      }
    end
  end

  #FIXME: What if this is interuppted? Need to do this better...
  #Broken so no match for now
  if self.class.name == "Bplmodels::Volume2"
    next_object = nil
    previous_object = nil
    #volume_object = Bplmodels::Finder.getVolumeObjects(self.pid)
    self.relationships.each_statement do |statement|
      puts statement.predicate
      if statement.predicate == "http://projecthydra.org/ns/relations#isPrecedingVolumeOf"
        next_object = ActiveFedora::Base.find(statement.object.to_s.split('/').last).adapt_to_cmodel
      elsif statement.predicate == "http://projecthydra.org/ns/relations#isFollowingVolumeOf"
        previous_object = ActiveFedora::Base.find(statement.object.to_s.split('/').last).adapt_to_cmodel
      end
    end

    if next_object.present? and previous_object.present?
      next_object.relationships.each_statement do |statement|
        if statement.predicate == "http://projecthydra.org/ns/relations#isFollowingVolumeOf"
          next_object.remove_relationship(:is_following_volume_of, statement.object)
        end
      end

      previous_object.relationships.each_statement do |statement|
        if statement.predicate == "http://projecthydra.org/ns/relations#isPrecedingVolumeOf"
          previous_object.remove_relationship(:is_preceding_volume_of, statement.object)
        end
      end

      next_object.add_relationship(:is_following_volume_of, "info:fedora/#{previous_object.pid}", true)
      previous_object.add_relationship(:is_preceding_volume_of, "info:fedora/#{next_object.pid}", true)
      next_object.save
      previous_object.save
    elsif next_object.present? and previous_object.blank?
      next_object.relationships.each_statement do |statement|
        if statement.predicate == "http://projecthydra.org/ns/relations#isFollowingVolumeOf"
          next_object.remove_relationship(:is_following_volume_of, statement.object)
        end
      end

    elsif  next_object.blank? and previous_object.present?
      previous_object.relationships.each_statement do |statement|
        if statement.predicate == "http://projecthydra.org/ns/relations#isPrecedingVolumeOf"
          previous_object.remove_relationship(:is_preceding_volume_of, statement.object)
        end
      end
    end
   self.collection.first.update_index
  end
  super()
end

#deleteAllFilesObject



1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
# File 'app/models/bplmodels/object_base.rb', line 1612

def deleteAllFiles
  Bplmodels::ImageFile.find_in_batches('is_image_of_ssim'=>"info:fedora/#{self.pid}") do |group|
    group.each { |solr_object|
      object = ActiveFedora::Base.find(solr_object['id']).adapt_to_cmodel
      object.delete
    }
  end

  Bplmodels::AudioFile.find_in_batches('is_audio_of_ssim'=>"info:fedora/#{self.pid}") do |group|
    group.each { |solr_object|
      object = ActiveFedora::Base.find(solr_object['id']).adapt_to_cmodel
      object.delete
    }
  end

  Bplmodels::DocumentFile.find_in_batches('is_document_of_ssim'=>"info:fedora/#{self.pid}") do |group|
    group.each { |solr_object|
      object = ActiveFedora::Base.find(solr_object['id']).adapt_to_cmodel
      object.delete
    }
  end
end

#derivative_service(is_new) ⇒ Object



1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
# File 'app/models/bplmodels/object_base.rb', line 1635

def derivative_service(is_new)
  response = Typhoeus::Request.post(DERIVATIVE_CONFIG_GLOBAL['url'] + "/processor/byobject.json", :params => {:pid=>self.pid, :new=>is_new, :environment=>Bplmodels.environment})
  puts response.body.to_s
  as_json = JSON.parse(response.body)

  if as_json['result'] == "false"
    pid = self.object.pid
    self.deleteAllFiles
    self.delete
    raise "Error Generating Derivatives For Object: " + pid
  end

  return true
end

#generate_thumbnail_url(config_hash = nil) ⇒ Object



1101
1102
1103
1104
1105
1106
1107
# File 'app/models/bplmodels/object_base.rb', line 1101

def generate_thumbnail_url(config_hash=nil)
  if config_hash.present?
    return config_hash['url'] + '/ark:/' + config_hash["namespace_commonwealth_ark"].to_s + "/" + self.pid.split(':').last.to_s + "/thumbnail"
  end

  return ARK_CONFIG_GLOBAL['url'] + '/ark:/' + ARK_CONFIG_GLOBAL["namespace_commonwealth_ark"].to_s + "/" + self.pid.split(':').last.to_s + "/thumbnail"
end

#generate_uriObject



1109
1110
1111
# File 'app/models/bplmodels/object_base.rb', line 1109

def generate_uri
  return ARK_CONFIG_GLOBAL['url'] + '/ark:/' + ARK_CONFIG_GLOBAL["namespace_commonwealth_ark"].to_s + "/" + self.pid.split(':').last.to_s
end

#insert_abbyy(file_content) ⇒ Object



1143
1144
1145
1146
# File 'app/models/bplmodels/object_base.rb', line 1143

def insert_abbyy(file_content)
  self.abbyy.content = file_content
  self.abbyy.mimeType = 'application/xml'
end

#insert_djvu_xml(file_content) ⇒ Object



1138
1139
1140
1141
# File 'app/models/bplmodels/object_base.rb', line 1138

def insert_djvu_xml(file_content)
  self.djvuXML.content = file_content
  self.djvuXML.mimeType = 'application/xml'
end

#insert_ia_meta(file_content) ⇒ Object



1123
1124
1125
1126
# File 'app/models/bplmodels/object_base.rb', line 1123

def insert_ia_meta(file_content)
  self.iaMeta.content = file_content
  self.iaMeta.mimeType = 'application/xml'
end

#insert_marc(file_content) ⇒ Object



1113
1114
1115
1116
# File 'app/models/bplmodels/object_base.rb', line 1113

def insert_marc(file_content)
  self.marc.content = file_content
  self.marc.mimeType = 'application/marc'
end

#insert_marc_xml(file_content) ⇒ Object



1118
1119
1120
1121
# File 'app/models/bplmodels/object_base.rb', line 1118

def insert_marc_xml(file_content)
  self.marcXML.content = file_content
  self.marcXML.mimeType = 'application/xml'
end

#insert_new_audio_file(files_hash, institution_pid, set_exemplary = false) ⇒ Object



1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
# File 'app/models/bplmodels/object_base.rb', line 1374

def insert_new_audio_file(files_hash, institution_pid, set_exemplary=false)
  production_master = files_hash.select{ |hash| hash[:datastream] == 'productionMaster' }.first
  audio_file = Bplmodels::AudioFile.mint(:parent_pid=>self.pid, :local_id=>production_master[:file_name], :local_id_type=>'File Name', :label=>production_master[:file_name], :institution_pid=>institution_pid)

  if audio_file.is_a?(String)
    #Bplmodels::ImageFile.find(last_image_file).delete
    #last_image_file = Bplmodels::ImageFile.mint(:parent_pid=>self.pid, :local_id=>final_file_name, :local_id_type=>'File Name', :label=>final_file_name, :institution_pid=>institution_pid)
    #return true
    return Bplmodels::AudioFile.find(image_file)
  end

  files_hash.each_with_index do |file, file_index|
    datastream = file[:datastream]


    audio_file.send(datastream).content = ::File.open(file[:file_path])

    if file[:file_name].split('.').last.downcase == 'mp3'
      audio_file.send(datastream).mimeType = 'audio/mpeg'
    elsif file[:file_name].split('.').last.downcase == 'wav'
      audio_file.send(datastream).mimeType = 'audio/x-wav'
    elsif file[:file_name].split('.').last.downcase == 'aif'
      audio_file.send(datastream).mimeType = 'audio/x-aiff'
    elsif file[:file_name].split('.').last.downcase == 'txt'
      audio_file.send(datastream).mimeType = 'text/plain'
    else
      raise "Could not find a mimeType for #{file[:file_name].split('.').last.downcase}"
    end

    audio_file.send(datastream).dsLabel = file[:file_name].gsub(/\.(mp3|MP3|wav|WAV|aif|AIF|txt|TXT)$/, '')

    #FIXME!!!
    original_file_location = file[:original_file_location]
    original_file_location ||= file[:file_path]
    audio_file..insert_file_source(original_file_location,file[:file_name],datastream)
    audio_file..item_status.state = "published"
    audio_file..item_status.state_comment = "Added via the ingest image object base method on " + Time.new.year.to_s + "/" + Time.new.month.to_s + "/" + Time.new.day.to_s


  end

  other_audio_exist = false
  Bplmodels::AudioFile.find_in_batches('is_audio_of_ssim'=>"info:fedora/#{self.pid}", 'is_preceding_audio_of_ssim'=>'') do |group|
    group.each { |audio|
      if other_audio_exist
        raise 'This object has an error... likely was interupted during a previous ingest so multiple starting files. Pid: ' + self.pid
      else
        other_images_exist = true
        preceding_audio = Bplmodels::AudioFile.find(audio['id'])
        preceding_audio.add_relationship(:is_preceding_image_of, "info:fedora/#{audio_file.pid}", true)
        preceding_audio.save
        audio_file.add_relationship(:is_following_image_of, "info:fedora/#{audio['id']}", true)
      end

    }
  end

  audio_file.add_relationship(:is_audio_of, "info:fedora/" + self.pid)
  audio_file.add_relationship(:is_file_of, "info:fedora/" + self.pid)

  audio_file.save

  audio_file
end

#insert_new_document_file(files_hash, institution_pid, set_exemplary) ⇒ Object



1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
# File 'app/models/bplmodels/object_base.rb', line 1439

def insert_new_document_file(files_hash, institution_pid, set_exemplary)
  production_master = files_hash.select{ |hash| hash[:datastream] == 'productionMaster' }.first

  #uri_file_part = file
  #Fix common url errors
  #uri_file_part = URI::escape(uri_file_part) if uri_file_part.match(/^http/)

  document_file = Bplmodels::DocumentFile.mint(:parent_pid=>self.pid, :local_id=>production_master[:file_name], :local_id_type=>'File Name', :label=>production_master[:file_name], :institution_pid=>institution_pid)

  if document_file.is_a?(String)
    #Bplmodels::ImageFile.find(last_image_file).delete
    #last_image_file = Bplmodels::ImageFile.mint(:parent_pid=>self.pid, :local_id=>final_file_name, :local_id_type=>'File Name', :label=>final_file_name, :institution_pid=>institution_pid)
    #return true
    return Bplmodels::DocumentFile.find(document_file)
  end

  files_hash.each_with_index do |file, file_index|
    datastream = file[:datastream]

    #Fix common url errors
    if file[:file_path].match(/^http/)
      document_file.send(datastream).content = ::File.open(URI::escape(file[:file_path]))
    else
      document_file.send(datastream).content = ::File.open(file[:file_path])
    end


    if file[:file_name].split('.').last.downcase == 'pdf'
      document_file.send(datastream).mimeType = 'application/pdf'
    elsif file[:file_name].split('.').last.downcase == 'docx'
      document_file.send(datastream).mimeType = 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'
    elsif file[:file_name].split('.').last.downcase == 'doc'
      document_file.send(datastream).mimeType = 'application/msword'
    elsif file[:file_name].split('.').last.downcase == 'txt'
      document_file.send(datastream).mimeType = 'text/plain'
    else
      raise "Could not find a mimeType for #{file[:file_name].split('.').last.downcase}"
    end

    document_file.send(datastream).dsLabel = file[:file_name].gsub(/\.(pdf|PDF|docx|DOCX|doc|DOC|txt|TXT)$/, '')

    #FIXME!!!
    original_file_location = file[:original_file_location]
    original_file_location ||= file[:file_path]
    document_file..insert_file_source(original_file_location,file[:file_name],datastream)
    document_file..item_status.state = "published"
    document_file..item_status.state_comment = "Added via the ingest document object base method on " + Time.new.year.to_s + "/" + Time.new.month.to_s + "/" + Time.new.day.to_s


  end


  Bplmodels::DocumentFile.find_in_batches('is_document_of_ssim'=>"info:fedora/#{self.pid}", 'is_preceding_document_of_ssim'=>'') do |group|
    group.each { |document_id|
      preceding_document = Bplmodels::DocumentFile.find(document_id['id'])
      preceding_document.add_relationship(:is_preceding_document_of, "info:fedora/#{document_file.pid}", true)
      preceding_document.save
      preceding_document.add_relationship(:is_following_document_of, "info:fedora/#{document_id['id']}", true)
    }
  end

  document_file.add_relationship(:is_image_of, "info:fedora/" + self.pid)
  document_file.add_relationship(:is_file_of, "info:fedora/" + self.pid)

  if set_exemplary.nil? || set_exemplary
    if ActiveFedora::Base.find_with_conditions("is_exemplary_image_of_ssim"=>"info:fedora/#{self.pid}").blank?
      document_file.add_relationship(:is_exemplary_image_of, "info:fedora/" + self.pid)
    end
  end


  document_file.save

  document_file
end

#insert_new_ereader_file(files_hash, institution_pid) ⇒ Object



1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
# File 'app/models/bplmodels/object_base.rb', line 1311

def insert_new_ereader_file(files_hash, institution_pid)
  puts 'processing ereader of: ' + self.pid.to_s + ' with file_hash: ' + files_hash.to_s

  production_master = files_hash.select{ |hash| hash[:datastream] == 'productionMaster' }.first

  epub_file = Bplmodels::EreaderFile.mint(:parent_pid=>self.pid, :local_id=>production_master[:file_name], :local_id_type=>'File Name', :label=>production_master[:file_name], :institution_pid=>institution_pid)

  if epub_file.is_a?(String)
    #Bplmodels::ImageFile.find(last_image_file).delete
    #last_image_file = Bplmodels::ImageFile.mint(:parent_pid=>self.pid, :local_id=>final_file_name, :local_id_type=>'File Name', :label=>final_file_name, :institution_pid=>institution_pid)
    #return true
    return Bplmodels::EreaderFile.find(epub_file)
  end

  files_hash.each_with_index do |file, file_index|
    datastream = file[:datastream]


    epub_file.send(datastream).content = ::File.open(file[:file_path])

    if file[:file_name].split('.').last.downcase == 'epub'
      epub_file.send(datastream).mimeType = 'application/epub+zip'
    elsif file[:file_name].split('.').last.downcase == 'mobi'
      epub_file.send(datastream).mimeType = 'application/x-mobipocket-ebook'
    elsif file[:file_name].split('.').last.downcase == 'zip'
      epub_file.send(datastream).mimeType = 'application/zip'
    elsif file[:file_name].split('.').last.downcase == 'txt'
      epub_file.send(datastream).mimeType = 'text/plain'
    else
      epub_file.send(datastream).mimeType = 'application/epub+zip'
    end

    epub_file.send(datastream).dsLabel = file[:file_name].gsub(/\.(epub|EPUB|mobi|MOBI|zip|ZIP|txt|TXT)$/, '')

    #FIXME!!!
    original_file_location = file[:original_file_location]
    original_file_location ||= file[:file_path]
    epub_file..insert_file_source(original_file_location,file[:file_name],datastream)
    epub_file..item_status.state = "published"
    epub_file..item_status.state_comment = "Added via the ingest image object base method on " + Time.new.year.to_s + "/" + Time.new.month.to_s + "/" + Time.new.day.to_s


  end


  Bplmodels::EreaderFile.find_in_batches('is_ereader_of_ssim'=>"info:fedora/#{self.pid}", 'is_preceding_ereader_of_ssim'=>'') do |group|
    group.each { |ereader_id|
      other_images_exist = true
      preceding_ereader = Bplmodels::EreaderFile.find(ereader_id['id'])
      preceding_ereader.add_relationship(:is_preceding_ereader_of, "info:fedora/#{epub_file.pid}", true)
      preceding_ereader.save
      epub_file.add_relationship(:is_following_ereader_of, "info:fedora/#{ereader_id['id']}", true)
    }
  end

  epub_file.add_relationship(:is_ereader_of, "info:fedora/" + self.pid)
  epub_file.add_relationship(:is_file_of, "info:fedora/" + self.pid)

  epub_file.save

  epub_file
end

#insert_new_file(files_hash, file_ingest_source, institution_pid, set_exemplary = nil) ⇒ Object

Expects a hash of the following keys :file_path -> The path to the file :datastream -> The datastream for the file :file_name -> The name of the file



1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
# File 'app/models/bplmodels/object_base.rb', line 1164

def insert_new_file(files_hash, file_ingest_source, institution_pid, set_exemplary=nil)
  puts files_hash.to_s

  raise 'Missing insert_new_file params' if files_hash.first[:file_path].blank? || files_hash.first[:datastream].blank? || files_hash.first[:file_name].blank?

  production_master = files_hash.select{ |hash| hash[:datastream] == 'productionMaster' }.first

  if production_master[:file_name].downcase.include?('.tif')
    self..insert_media_type('image/tiff')
    self..insert_media_type('image/jpeg')
    self..insert_media_type('image/jp2')
    inserted_obj = self.insert_new_image_file(files_hash, institution_pid,set_exemplary)
  elsif production_master[:file_name].downcase.include?('.jp2')
      self..insert_media_type('image/jpeg')
      self..insert_media_type('image/jp2')
      inserted_obj = self.insert_new_image_file(files_hash, institution_pid,set_exemplary)
  elsif production_master[:file_name].downcase.include?('.png')
    self..insert_media_type('image/png')
    self..insert_media_type('image/jpeg')
    self..insert_media_type('image/jp2')
    inserted_obj = self.insert_new_image_file(files_hash, institution_pid,set_exemplary)
  elsif production_master[:file_name].downcase.include?('.mp3')
    self..insert_media_type('audio/mpeg')
    inserted_obj = self.insert_new_audio_file(files_hash, institution_pid)
  elsif production_master[:file_name].downcase.include?('.wav')
    self..insert_media_type('audio/x-wav')
    inserted_obj = self.insert_new_audio_file(files_hash, institution_pid)
  elsif production_master[:file_name].downcase.include?('.aif')
    self..insert_media_type('audio/x-aiff')
    inserted_obj = self.insert_new_audio_file(files_hash, institution_pid)
  elsif production_master[:file_name].downcase.include?('.pdf')
    self..insert_media_type('application/pdf')
    ocr_preproduction_master = files_hash.select{ |hash| hash[:datastream] == 'preProductionNegativeMaster' }.first
=begin
    if ocr_preproduction_master.present?
      self.descMetadata.insert_media_type('application/vnd.openxmlformats-officedocument.wordprocessingml.document')
    end
=end

    inserted_obj = self.insert_new_document_file(files_hash, institution_pid,set_exemplary)
  elsif production_master[:file_name].downcase.include?('.epub')
    self..insert_media_type('application/epub+zip')
    inserted_obj = self.insert_new_ereader_file(files_hash, institution_pid)
  elsif production_master[:file_name].downcase.include?('.mobi')
    self..insert_media_type('application/x-mobipocket-ebook')
    inserted_obj = self.insert_new_ereader_file(files_hash, institution_pid)
  elsif production_master[:file_name].downcase.include?('daisy.zip')
    self..insert_media_type('application/zip')
    inserted_obj = self.insert_new_ereader_file(files_hash, institution_pid)
  else
    self..insert_media_type('image/jpeg')
    self..insert_media_type('image/jp2')
    inserted_obj = self.insert_new_image_file(files_hash, institution_pid,set_exemplary)
  end

  self..item_source.ingest_origin = file_ingest_source if self..item_source.ingest_origin.blank?
  files_hash.each do |file|
    original_file_location = file[:original_file_location]
    original_file_location ||= file[:file_path]
    self..insert_file_source(original_file_location,file[:file_name],file[:datastream])
  end
  inserted_obj
end

#insert_new_image_file(files_hash, institution_pid, set_exemplary) ⇒ Object



1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
# File 'app/models/bplmodels/object_base.rb', line 1227

def insert_new_image_file(files_hash, institution_pid, set_exemplary)
  #raise 'insert new image called with no files or more than one!' if file.blank? || file.is_a?(Array)

  puts 'processing image of: ' + self.pid.to_s + ' with file_hash: ' + files_hash.to_s

  production_master = files_hash.select{ |hash| hash[:datastream] == 'productionMaster' }.first

  #uri_file_part = file
  #Fix common url errors
  #uri_file_part = URI::escape(uri_file_part) if uri_file_part.match(/^http/)

  image_file = Bplmodels::ImageFile.mint(:parent_pid=>self.pid, :local_id=>production_master[:file_name], :local_id_type=>'File Name', :label=>production_master[:file_name], :institution_pid=>institution_pid)

  if image_file.is_a?(String)
    #Bplmodels::ImageFile.find(last_image_file).delete
    #last_image_file = Bplmodels::ImageFile.mint(:parent_pid=>self.pid, :local_id=>final_file_name, :local_id_type=>'File Name', :label=>final_file_name, :institution_pid=>institution_pid)
    #return true
    return Bplmodels::ImageFile.find(image_file)
  end

  files_hash.each_with_index do |file, file_index|
    datastream = file[:datastream]


    image_file.send(datastream).content = ::File.open(file[:file_path])

    if file[:file_name].split('.').last.downcase == 'tif'
      image_file.send(datastream).mimeType = 'image/tiff'
    elsif file[:file_name].split('.').last.downcase == 'jpg'
      image_file.send(datastream).mimeType = 'image/jpeg'
    elsif file[:file_name].split('.').last.downcase == 'jp2'
      image_file.send(datastream).mimeType = 'image/jp2'
    elsif file[:file_name].split('.').last.downcase == 'png'
      image_file.send(datastream).mimeType = 'image/png'
    elsif file[:file_name].split('.').last.downcase == 'txt'
      image_file.send(datastream).mimeType = 'text/plain'
    else
      #image_file.send(datastream).mimeType = 'image/jpeg'
      raise "Could not find a mimeType for #{file[:file_name].split('.').last.downcase}"
    end

    image_file.send(datastream).dsLabel = file[:file_name].gsub(/\.(tif|TIF|jpg|JPG|jpeg|JPEG|jp2|JP2|png|PNG|txt|TXT)$/, '')

    #FIXME!!!
    original_file_location = file[:original_file_location]
    original_file_location ||= file[:file_path]
    image_file..insert_file_source(original_file_location,file[:file_name],datastream)
    image_file..item_status.state = "published"
    image_file..item_status.state_comment = "Added via the ingest image object base method on " + Time.new.year.to_s + "/" + Time.new.month.to_s + "/" + Time.new.day.to_s


  end

    other_images_exist = false
    Bplmodels::ImageFile.find_in_batches('is_image_of_ssim'=>"info:fedora/#{self.pid}", 'is_preceding_image_of_ssim'=>'') do |group|
      group.each { |image_id|
        if other_images_exist
          raise 'This object has an error... likely was interupted during a previous ingest so multiple starting files. Pid: ' + self.pid
        else
          other_images_exist = true
          preceding_image = Bplmodels::ImageFile.find(image_id['id'])
          preceding_image.add_relationship(:is_preceding_image_of, "info:fedora/#{image_file.pid}", true)
          preceding_image.save
          image_file.add_relationship(:is_following_image_of, "info:fedora/#{image_id['id']}", true)
        end

      }
    end

  image_file.add_relationship(:is_image_of, "info:fedora/" + self.pid)
  image_file.add_relationship(:is_file_of, "info:fedora/" + self.pid)

  if set_exemplary.nil? || set_exemplary
    if ActiveFedora::Base.find_with_conditions("is_exemplary_image_of_ssim"=>"info:fedora/#{self.pid}").blank?
      image_file.add_relationship(:is_exemplary_image_of, "info:fedora/" + self.pid)
    end
  end


  image_file.save

  image_file
end

#insert_plain_text(file_content) ⇒ Object



1133
1134
1135
1136
# File 'app/models/bplmodels/object_base.rb', line 1133

def insert_plain_text(file_content)
  self.plainText.content = file_content
  self.plainText.mimeType = 'text/plain'
end

#insert_scan_data(file_content) ⇒ Object



1128
1129
1130
1131
# File 'app/models/bplmodels/object_base.rb', line 1128

def insert_scan_data(file_content)
  self.scanData.content = file_content
  self.scanData.mimeType = 'application/xml'
end

#oai_thumbnail_service(is_new, urls, system_type, thumbnail_url = nil) ⇒ Object



1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
# File 'app/models/bplmodels/object_base.rb', line 1650

def oai_thumbnail_service(is_new, urls, system_type, thumbnail_url=nil)
  response = Typhoeus::Request.post(DERIVATIVE_CONFIG_GLOBAL['url'] + "/processor/oaithumbnail.json", :params => {:pid=>self.pid, :new=>is_new, :environment=>Bplmodels.environment, :image_urls=>urls, :system_type=>system_type, :thumbnail_url=>thumbnail_url})
  as_json = JSON.parse(response.body)

  if as_json['result'] == "false"
    pid = self.object.pid
    self.delete
    raise "Error Generating OAI Thumbnail For Object: " + pid
  end

  return true
end

#remove_oai_relationshipsObject



85
86
87
# File 'app/models/bplmodels/object_base.rb', line 85

def remove_oai_relationships
  self.remove_relationship(:oai_item_id, "oai:digitalcommonwealth.org:" + self.pid, true)
end

#simple_insert_file(file_path, file_name, ingest_source, institution_pid, original_file_location = nil, set_exemplary = nil) ⇒ Object



1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
# File 'app/models/bplmodels/object_base.rb', line 1148

def simple_insert_file(file_path, file_name, ingest_source, institution_pid, original_file_location=nil, set_exemplary=nil)
  files_hash = []
  file_hash = {}
  file_hash[:datastream] = 'productionMaster'
  file_hash[:file_path] = file_path
  file_hash[:file_name] = file_name
  file_hash[:original_file_location] = original_file_location
  files_hash << file_hash

  insert_new_file(files_hash, ingest_source, institution_pid, set_exemplary)
end

#to_solr(doc = {}) ⇒ Object



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
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
# File 'app/models/bplmodels/object_base.rb', line 188

def to_solr(doc = {} )
  doc = super(doc)
  #doc['has_model_ssim'] = [doc['has_model_ssim'][0], 'info:fedora/afmodel:Bplmodels_SimpleObjectBase']


  doc['label_ssim'] = self.label.to_s

  # dates
  doc['date_start_dtsi'] = []
  doc['date_start_tsim'] = []
  doc['date_end_dtsi'] = []
  doc['date_end_tsim'] = []
  doc['date_facet_ssim'] = []
  doc['date_type_ssm'] = []
  doc['date_start_qualifier_ssm'] = []
  doc['note_date_tsim'] = []
  dates_static = []
  dates_start = []
  dates_end = []

  # these values get appended to dates in _dtsi Solr format
  start_date_suffix_for_yyyy = '-01-01T00:00:00.000Z'
  start_date_suffix_for_yyyymm = '-01T01:00:00.000Z'
  start_date_suffix_for_yyyymmdd = 'T00:00:00.000Z'
  end_date_suffix_for_yyyy = '-12-31T23:59:59.999Z'
  end_date_suffix_for_yyyymm = '-28T23:59:59.999Z' # TODO: end DD value should depend on MM value ('31' for Jan., '28' for Feb., etc.)
  end_date_suffix_for_yyyymmdd = 'T23:59:59.999Z'

  # dateOther
  if self..date(0).date_other[0]
    self..date(0).date_other.each do |date_other|
      doc['note_date_tsim'] << date_other
    end
  end

  # dateCreated, dateIssued, copyrightDate
  if self..date(0).dates_created[0] || self..date(0).dates_issued[0] || self..date(0).dates_copyright[0]

    #dateCreated
    if self..date(0).dates_created[0]
      self..date(0).dates_created.each_with_index do |date,index|
        #FIXME: Has to add "date.present" and the when '' case for oai-test:h415pc718
        if date.present?
          case self..date(0).dates_created(index).point[0]
            when nil, ''
              dates_static << date
              doc['date_type_ssm'] << 'dateCreated'
              doc['date_start_qualifier_ssm'].append(self..date(0).dates_created(index).qualifier[0].presence || 'nil')
            when 'start'
              dates_start << date
              doc['date_type_ssm'] << 'dateCreated'
              doc['date_start_qualifier_ssm'].append(self..date(0).dates_created(index).qualifier[0].presence || 'nil')
            when 'end'
              dates_end << date
          end
        end
      end
    end
    # dateIssued
    if self..date(0).dates_issued[0]
      self..date(0).dates_issued.each_with_index do |date,index|
        case self..date(0).dates_issued(index).point[0]
          when nil
            dates_static << date
            doc['date_type_ssm'] << 'dateIssued'
            doc['date_start_qualifier_ssm'].append(self..date(0).dates_issued(index).qualifier[0].presence || 'nil')
          when 'start'
            dates_start << date
            doc['date_type_ssm'] << 'dateIssued'
            doc['date_start_qualifier_ssm'].append(self..date(0).dates_issued(index).qualifier[0].presence || 'nil')
          when 'end'
            dates_end << date
        end
      end
    end
    # dateCopyright
    if self..date(0).dates_copyright[0]
      self..date(0).dates_copyright.each_with_index do |date,index|
        case self..date(0).dates_copyright(index).point[0]
          when nil
            dates_static << date
            doc['date_type_ssm'] << 'copyrightDate'
            doc['date_start_qualifier_ssm'].append(self..date(0).dates_copyright(index).qualifier[0].presence || 'nil')
          when 'start'
            dates_start << date
            doc['date_type_ssm'] << 'copyrightDate'
            doc['date_start_qualifier_ssm'].append(self..date(0).dates_copyright(index).qualifier[0].presence || 'nil')
          when 'end'
            dates_end << date
        end
      end
    end

    # push the date values as-is into text fields
    dates_static.each do |static_date|
      doc['date_start_tsim'] << static_date
      doc['date_end_tsim'] << 'nil' # hacky, but can't assign null in Solr
    end
    dates_start.each do |start_date|
      doc['date_start_tsim'] << start_date
    end
    dates_end.each do |end_date|
      doc['date_end_tsim'] << end_date
    end

    # set the date ranges for date-time fields and decade faceting
    sorted_start_dates = (dates_static + dates_start).sort
    earliest_date = sorted_start_dates[0]
    date_facet_start = earliest_date[0..3].to_i
    latest_date = dates_end.sort.reverse[0]

    # set earliest date
    if earliest_date =~ /[0-9]{4}[0-9-]*\z/ # rough date format matching
      if earliest_date.length == 4
        doc['date_start_dtsi'].append(earliest_date + start_date_suffix_for_yyyy)
      elsif earliest_date.length == 7
        doc['date_start_dtsi'].append(earliest_date + start_date_suffix_for_yyyymm)
      elsif earliest_date.length > 11
        doc['date_start_dtsi'].append(earliest_date)
      else
        doc['date_start_dtsi'].append(earliest_date + start_date_suffix_for_yyyymmdd)
      end
    end

    # set latest date
    if latest_date && latest_date =~ /[0-9]{4}[0-9-]*\z/
      date_facet_end = latest_date[0..3].to_i
      if latest_date.length == 4
        doc['date_end_dtsi'].append(latest_date + end_date_suffix_for_yyyy)
      elsif latest_date.length == 7
        doc['date_end_dtsi'].append(latest_date + end_date_suffix_for_yyyymm)
      elsif latest_date.length > 11
        doc['date_end_dtsi'].append(latest_date)
      else
        doc['date_end_dtsi'].append(latest_date + end_date_suffix_for_yyyymmdd)
      end
    else
      date_facet_end = 0
      latest_start_date = sorted_start_dates[-1]
      if latest_start_date =~ /[0-9]{4}[0-9-]*\z/
        if latest_start_date.length == 4
          doc['date_end_dtsi'].append(latest_start_date + end_date_suffix_for_yyyy)
        elsif latest_start_date.length == 7
          doc['date_end_dtsi'].append(latest_start_date + end_date_suffix_for_yyyymm)
        elsif latest_start_date.length > 11
          doc['date_end_dtsi'].append(latest_start_date)
        else
          doc['date_end_dtsi'].append(latest_start_date + end_date_suffix_for_yyyymmdd)
        end
      end
    end

    # decade faceting
    (1100..2020).step(10) do |index|
      if (date_facet_start >= index && date_facet_start < index+10) || (date_facet_end != -1 && index > date_facet_start && date_facet_end >= index)
        doc['date_facet_ssim'].append(index.to_s + 's')
      end
    end

    doc['date_facet_yearly_ssim'] = []
    # yearly faceting
    (1100..2020).step(1) do |index|
      if (date_facet_start >= index && date_facet_start < index+1) || (date_facet_end != -1 && index > date_facet_start && date_facet_end >= index)
        doc['date_facet_yearly_ssim'].append(index.to_s + 's')
      end
    end

  end

  doc['abstract_tsim'] = self..abstract
  doc['table_of_contents_tsi'] = self..table_of_contents[0]

  doc['genre_basic_tsim'] = self..genre_basic
  doc['genre_specific_tsim'] = self..genre_specific

  doc['genre_basic_ssim'] = self..genre_basic
  doc['genre_specific_ssim'] = self..genre_specific

  # will need to make this more generic when we have more id fields with @invalid
  if self..local_other
    doc['identifier_local_other_tsim'] = []
    doc['identifier_local_other_invalid_tsim'] = []
    self..identifier.each_with_index do |id_val, index|
      if self..identifier(index).type_at[0] == 'local-other'
        if self..identifier(index).invalid[0]
          doc['identifier_local_other_invalid_tsim'].append(id_val)
        else
          doc['identifier_local_other_tsim'].append(id_val)
        end
      end
    end
  end


  doc['identifier_local_call_tsim'] = self..local_call
  doc['identifier_local_barcode_tsim'] = self..local_barcode
  doc['identifier_isbn_tsim'] = self..isbn
  doc['identifier_lccn_tsim'] = self..lccn
  doc['identifier_ia_id_ssi'] = self..ia_id

  doc['identifier_ark_ssi'] = ''

  doc['local_accession_id_tsim'] = self..local_accession[0].to_s

  #Assign collection, admin, and institution labels
  doc['collection_name_ssim'] = []
  doc['collection_name_tsim'] = []
  doc['collection_pid_ssm'] = []

  object_institution_pid = nil
  object_collections = self.relationships(:is_member_of_collection)
  object_collections.each do |collection_ident|
    solr_response_collection = ActiveFedora::Base.find_with_conditions("id"=>collection_ident.gsub('info:fedora/','')).first
    doc['collection_name_ssim'] << solr_response_collection["label_ssim"].first.to_s
    doc['collection_name_tsim'] << solr_response_collection["label_ssim"].first.to_s
    doc['collection_pid_ssm'] << solr_response_collection["id"].to_s

    if object_institution_pid.blank?
      object_institution_pid = solr_response_collection['institution_pid_ssi']
      solr_response_institution = ActiveFedora::Base.find_with_conditions("id"=>object_institution_pid).first
      doc['institution_name_ssim'] = solr_response_institution["label_ssim"].first.to_s
      doc['institution_name_tsim'] = solr_response_institution["label_ssim"].first.to_s
      doc['institution_pid_ssi'] = solr_response_institution["id"].to_s
      doc['institution_pid_si'] = solr_response_institution["id"].to_s
    end
  end

  object_admin_set = self.relationships(:administrative_set).first
  if object_admin_set.present?
    solr_response_admin = ActiveFedora::Base.find_with_conditions("id"=>object_admin_set.gsub('info:fedora/','')).first
    doc['admin_set_name_ssim'] = solr_response_admin["label_ssim"].first.to_s
    doc['admin_set_name_tsim'] = solr_response_admin["label_ssim"].first.to_s
    doc['admin_set_pid_ssm'] = solr_response_admin["id"].to_s
  else
    raise "Potential problem setting administrative set?"
  end




  #self.descMetadata.identifier_uri.each do |identifier|
  #if idenfifier.include?("ark")
  #doc['identifier_uri_ss']  =  self.descMetadata.identifier_uri
  #end
  #end
  if  self..identifier_uri.length > 1
    doc['identifier_uri_ss']  =  self..identifier_uri[1]
  else
    doc['identifier_uri_ss']  =  self..identifier_uri[0]
  end


  doc['publisher_tsim'] = self..origin_info.publisher

  doc['pubplace_tsim'] = self..origin_info.place.place_term

  doc['edition_tsim'] = self..origin_info.edition

  doc['issuance_tsim'] = self..origin_info.issuance

  doc['classification_tsim'] = self..classification

  doc['lang_term_ssim'] = self..language.language_term
  #doc['lang_val_uri_ssim'] = self.descMetadata.language.language_term.lang_val_uri

  # relatedItem, except subseries, subsubseries, etc.
  if self..mods(0).related_item.length > 0
    (0..self..mods(0).related_item.length-1).each do |index|
      related_item_type = self..mods(0).related_item(index).type[0]
      if related_item_type == 'isReferencedBy'
        doc['related_item_' + related_item_type.downcase + '_ssm'] ||= []
        doc['related_item_' + related_item_type.downcase + '_ssm'].append(self..mods(0).related_item(index).href[0])
      else
        doc['related_item_' + related_item_type + '_tsim'] ||= []
        doc['related_item_' + related_item_type + '_ssim'] ||= []
        related_title_prefix = self..mods(0).related_item(index).title_info.nonSort[0] ? self..mods(0).related_item(index).title_info.nonSort[0] + ' ' : ''
        doc['related_item_' + related_item_type + '_tsim'].append(related_title_prefix + self..mods(0).related_item(index).title_info.title[0])
        doc['related_item_' + related_item_type + '_ssim'].append(related_title_prefix + self..mods(0).related_item(index).title_info.title[0])
      end
    end
  end

  # subseries
  if self..related_item.subseries
    doc['related_item_subseries_tsim'] ||= []
    doc['related_item_subseries_ssim'] ||= []
    (0..self..mods(0).related_item.subseries.length-1).each do |index|
      subseries_prefix = self..mods(0).related_item.subseries(index).title_info.nonSort[0] ? self..mods(0).related_item.subseries(index).title_info.nonSort[0] + ' ' : ''
      subseries_value = subseries_prefix + self..mods(0).related_item.subseries(index).title_info.title[0]
      doc['related_item_subseries_tsim'].append(subseries_value)
      doc['related_item_subseries_ssim'].append(subseries_value)
    end
  end

  # subsubseries
  if self..related_item.subseries.subsubseries
    doc['related_item_subsubseries_tsim'] ||= []
    doc['related_item_subsubseries_ssim'] ||= []
    (0..self..mods(0).related_item.subseries.subsubseries.length-1).each do |index|
      subsubseries_prefix = self..mods(0).related_item.subseries.subsubseries(index).title_info.nonSort[0] ? self..mods(0).related_item.subseries.subsubseries(index).title_info.nonSort[0] + ' ' : ''
      subsubseries_value = subsubseries_prefix + self..mods(0).related_item.subseries.subsubseries(index).title_info.title[0]
      doc['related_item_subsubseries_tsim'].append(subsubseries_value)
      doc['related_item_subsubseries_ssim'].append(subsubseries_value)
    end
  end

  #doc['titleInfo_primary_ssim'] = self.descMetadata.title_info(0).main_title.to_s
  #doc['name_personal_ssim'] = self.descMetadata.name(0).to_s

  doc['name_personal_tsim'] = []
  doc['name_personal_role_tsim'] = []
  doc['name_corporate_tsim'] = []
  doc['name_corporate_role_tsim'] = []

  doc['name_generic_tsim'] = []
  doc['name_generic_role_tsim'] = []

  0.upto self..mods(0).name.length-1 do |index|
    if self..mods(0).name(index).type[0] == "personal"
      if self..mods(0).name(index).date.length > 0
        doc['name_personal_tsim'].append(self..mods(0).name(index).namePart[0] + ", " + self..mods(0).name(index).date[0])
      else
        doc['name_personal_tsim'].append(self..mods(0).name(index).namePart[0])
      end
      if self..mods(0).name(index).role.length > 1
        doc['name_personal_role_tsim'].append(self..mods(0).name(index).role.join('||').gsub(/[\n]\s*/,''))
      else
        doc['name_personal_role_tsim'].append(self..mods(0).name(index).role.text[0])
      end

    elsif self..mods(0).name(index).type[0] == "corporate"
      corporate_name = self..mods(0).name(index).namePart.join(". ").gsub(/\.\./,'.')
      # TODO -- do we need the conditional below?
      # don't think corp names have dates
      if self..mods(0).name(index).date.length > 0
        doc['name_corporate_tsim'].append(corporate_name + ", " + self..mods(0).name(index).date[0])
      else
        doc['name_corporate_tsim'].append(corporate_name)
      end
      if self..mods(0).name(index).role.length > 1
        doc['name_corporate_role_tsim'].append(self..mods(0).name(index).role.join('||').gsub(/[\n]\s*/,''))
      else
        doc['name_corporate_role_tsim'].append(self..mods(0).name(index).role.text[0])
      end

    else
      if self..mods(0).name(index).date.length > 0
        doc['name_generic_tsim'].append(self..mods(0).name(index).namePart[0] + ", " + self..mods(0).name(index).date[0])
      else
        doc['name_generic_tsim'].append(self..mods(0).name(index).namePart[0])
      end
      if self..mods(0).name(index).role.length > 1
        doc['name_generic_role_tsim'].append(self..mods(0).name(index).role.join('||').gsub(/[\n]\s*/,''))
      else
        doc['name_generic_role_tsim'].append(self..mods(0).name(index).role.text[0])
      end
    end

  end

  doc['name_facet_ssim'] = doc['name_personal_tsim'] + doc['name_corporate_tsim'] + doc['name_generic_tsim']


  doc['type_of_resource_ssim'] = self..type_of_resource

  doc['extent_tsi']  = self..physical_description(0).extent[0]
  doc['digital_origin_ssi']  = self..physical_description(0).digital_origin[0]
  doc['internet_media_type_ssim']  = self..physical_description(0).internet_media_type

  doc['physical_location_ssim']  = self..item_location.physical_location
  doc['physical_location_tsim']  = self..item_location.physical_location

  doc['sub_location_tsim']  = self..item_location.holding_simple.copy_information.sub_location

  doc['shelf_locator_tsim']  = self..item_location.holding_simple.copy_information.shelf_locator

  doc['subject_topic_tsim'] = self..subject.topic

  # subject - geographic
  subject_geo = self..subject.geographic

  # subject - hierarchicalGeographic
  country = self..subject.hierarchical_geographic.country
  province = self..subject.hierarchical_geographic.province
  region = self..subject.hierarchical_geographic.region
  state = self..subject.hierarchical_geographic.state
  territory = self..subject.hierarchical_geographic.territory
  county = self..subject.hierarchical_geographic.county
  city = self..subject.hierarchical_geographic.city
  city_section = self..subject.hierarchical_geographic.city_section
  island = self..subject.hierarchical_geographic.island
  area = self..subject.hierarchical_geographic.area

  doc['subject_geo_country_ssim'] = country
  doc['subject_geo_province_ssim'] = province
  doc['subject_geo_region_ssim'] = region
  doc['subject_geo_state_ssim'] = state
  doc['subject_geo_territory_ssim'] = territory
  doc['subject_geo_county_ssim'] = county
  doc['subject_geo_city_ssim'] = city
  doc['subject_geo_citysection_ssim'] = city_section
  doc['subject_geo_island_ssim'] = island
  doc['subject_geo_area_ssim'] = area

  geo_subjects = (country + province + region + state + territory + area + island + city + city_section + subject_geo).uniq # all except 'county'

  # add all subject-geo values to subject-geo text field for searching (remove dupes)
  doc['subject_geographic_tsim'] = geo_subjects + county.uniq

  # add " (county)" to county values for better faceting
  county_facet = []
  if county.length > 0
    county.each do |county_value|
      county_facet << county_value + ' (county)'
    end
  end

  # add all subject-geo values to subject-geo facet field (remove dupes)
  doc['subject_geographic_ssim'] = geo_subjects + county_facet.uniq

  # scale
  doc['subject_scale_tsim'] = self..subject.cartographics.scale

  # coordinates / bbox
  if self..subject.cartographics.coordinates.length > 0
    doc['subject_coordinates_geospatial'] = self..subject.cartographics.coordinates # includes both bbox and point data
    self..subject.cartographics.coordinates.each do |coordinates|
      if coordinates.scan(/[\s]/).length == 3
        doc['subject_bbox_geospatial'] ||= []
        doc['subject_bbox_geospatial'] << coordinates
      else
        doc['subject_point_geospatial'] ||= []
        doc['subject_point_geospatial'] << coordinates
      end
    end
  end

  # geographic data as GeoJSON (2 fields)
  # subject_geojson_facet_ssim = for map-based faceting + display
  # subject_hiergeo_geojson_ssm = for display of hiergeo metadata
  doc['subject_geojson_facet_ssim'] = []
  doc['subject_hiergeo_geojson_ssm'] = []
  doc['subject_geo_nonhier_ssim'] = [] # other non-hierarchical geo subjects
  0.upto self..subject.length-1 do |subject_index|

    this_subject = self..mods(0).subject(subject_index)

    # TGN-id-derived hierarchical geo subjects. assumes only longlat points, no bboxes
    if this_subject.hierarchical_geographic.any?
      geojson_hash_base = {type: 'Feature', geometry: {type: 'Point'}}

      if this_subject.cartographics.coordinates.any? # get the coordinates
        coords = this_subject.cartographics.coordinates[0]
        if coords.match(/^[-]?[\d]*[\.]?[\d]*,[-]?[\d]*[\.]?[\d]*$/)
          geojson_hash_base[:geometry][:coordinates] = coords.split(',').reverse.map { |v| v.to_f }
        end
      end

      facet_geojson_hash = geojson_hash_base.dup
      hiergeo_geojson_hash = geojson_hash_base.dup

      # get the hierGeo elements, except 'continent'
      hiergeo_hash = {}
      .terminology.retrieve_node(:subject,:hierarchical_geographic).children.each do |hgterm|
        hiergeo_hash[hgterm[0]] = '' unless hgterm[0].to_s == 'continent'
      end
      hiergeo_hash.each_key do |k|
        hiergeo_hash[k] = this_subject.hierarchical_geographic.send(k)[0].presence
      end
      hiergeo_hash.reject! {|k,v| !v } # remove any nil values

      if this_subject.geographic[0]
        other_geo_value = this_subject.geographic[0]
        other_geo_value << " (#{this_subject.geographic.display_label[0]})" if this_subject.geographic.display_label[0]
        hiergeo_hash[:other] = other_geo_value
      end

      unless hiergeo_hash.empty?
        hiergeo_geojson_hash[:properties] = hiergeo_hash
        facet_geojson_hash[:properties] = {placename: DatastreamInputFuncs.render_display_placename(hiergeo_hash)}
        doc['subject_hiergeo_geojson_ssm'].append(hiergeo_geojson_hash.to_json)
      end

      if geojson_hash_base[:geometry][:coordinates].is_a?(Array)
        doc['subject_geojson_facet_ssim'].append(facet_geojson_hash.to_json)
      end

    end

    # coordinates or bboxes w/o hierGeo elements, but maybe non-hierGeo geographic strings
    if this_subject.cartographics.coordinates.any? && this_subject.hierarchical_geographic.blank?
      geojson_hash = {type: 'Feature', geometry: {type: '', coordinates: []}}
      coords = this_subject.cartographics.coordinates[0]
      if coords.scan(/[\s]/).length == 3 #bbox TODO: better checking for bbox syntax
        unless coords == '-180.0 -90.0 180.0 90.0' # don't want 'whole world' bboxes
          coords_array = coords.split(' ').map { |v| v.to_f }
          if coords_array[0] > coords_array[2] # bbox that crosses dateline
            if coords_array[0] > 0
              degrees_to_add = 180-coords_array[0]
              coords_array[0] = -(180 + degrees_to_add)
            elsif coords_array[0] < 0 && coords_array[2] < 0
              degrees_to_add = 180+coords_array[2]
              coords_array[2] = 180 + degrees_to_add
            else
              Rails.logger.error("This bbox format was not parsed correctly: '#{coords}'")
            end
          end
          geojson_hash[:bbox] = coords_array
          geojson_hash[:geometry][:type] = 'Polygon'
          geojson_hash[:geometry][:coordinates] = [[[coords_array[0],coords_array[1]],
                                                    [coords_array[2],coords_array[1]],
                                                    [coords_array[2],coords_array[3]],
                                                    [coords_array[0],coords_array[3]],
                                                    [coords_array[0],coords_array[1]]]]
        end
      elsif coords.match(/^[-]?[\d]+[\.]?[\d]*,[\s]?[-]?[\d]+[\.]?[\d]*$/)
        geojson_hash[:geometry][:type] = 'Point'
        geojson_hash[:geometry][:coordinates] = coords.split(',').reverse.map { |v| v.to_f }
      end

      if this_subject.geographic[0]
        doc['subject_geo_nonhier_ssim'] << this_subject.geographic[0]
        geojson_hash[:properties] = {placename: this_subject.geographic[0]}
      end

      unless geojson_hash[:geometry][:coordinates].blank?
        doc['subject_geojson_facet_ssim'].append(geojson_hash.to_json)
      end
    end

    # non-hierarchical geo subjects w/o coordinates
    if this_subject.cartographics.coordinates.empty? && this_subject.hierarchical_geographic.blank? && this_subject.geographic[0]
      doc['subject_geo_nonhier_ssim'] << this_subject.geographic[0]
    end

  end

  # name subjects
  doc['subject_name_personal_tsim'] = []
  doc['subject_name_corporate_tsim'] = []
  doc['subject_name_conference_tsim'] = []
  doc['subject_facet_ssim'] = []
  0.upto self..subject.length-1 do |index|
    if self..subject(index).personal_name.length > 0
      if self..subject(index).personal_name.date.length > 0
        subject_name_personal = self..subject(index).personal_name.name_part[0] + ", " + self..subject(index).personal_name.date[0]
      else
        subject_name_personal = self..subject(index).personal_name.name_part[0]
      end
      doc['subject_name_personal_tsim'].append(subject_name_personal)
      doc['subject_facet_ssim'].append(subject_name_personal)
    end
    if self..subject(index).corporate_name.length > 0
      subject_name_corporate = self..subject(index).corporate_name.name_part.join('. ').gsub(/\.\./,'.')
      # TODO -- do we need the conditional below?
      # don't think corp names have dates
      if self..subject(index).corporate_name.date.length > 0
        subject_name_corporate = subject_name_corporate + ", " + self..subject(index).corporate_name.date[0]
      end
      doc['subject_name_corporate_tsim'].append(subject_name_corporate)
      doc['subject_facet_ssim'].append(subject_name_corporate)
    end
    if self..subject(index).conference_name.length > 0
      subject_name_conference = self..subject(index).conference_name.name_part[0]
      doc['subject_name_conference_tsim'].append(subject_name_conference)
      doc['subject_facet_ssim'].append(subject_name_conference)
    end

  end

  doc['subject_facet_ssim'].concat(self..subject.topic)

  # temporal subjects
  if self..subject.temporal.length > 0

    doc['subject_temporal_start_tsim'] = []
    doc['subject_temporal_start_dtsim'] = []
    doc['subject_temporal_facet_ssim'] = []
    doc['subject_temporal_end_tsim'] = []
    doc['subject_temporal_end_dtsim'] = []
    subject_date_range_start = []
    subject_date_range_end = []

    self..subject.temporal.each_with_index do |value,index|
      if self..subject.temporal.point[index] != 'end'
        doc['subject_temporal_start_tsim'] << value
        subject_date_range_start << value
        # if there is no accompanying end date, create nil value placeholders
        unless self..subject.temporal.point[index+1] == 'end'
          subject_date_range_end << nil
          doc['subject_temporal_end_tsim'] << 'nil'
        end
      else
        doc['subject_temporal_end_tsim'] << value
        subject_date_range_end << value
      end
    end

    if subject_date_range_start.length > 0
      subject_date_range_start.each_with_index do |date_start,index|
        formatted_date_subject_start = false
        formatted_date_subject_end = false
        if date_start =~ /[0-9]{4}[0-9-]*\z/ # rough check for date formatting
          formatted_date_subject_start = true
          if date_start.length == 7
            doc['subject_temporal_start_dtsim'] << date_start + start_date_suffix_for_yyyymm
          elsif date_start.length == 10
            doc['subject_temporal_start_dtsim'] << date_start + start_date_suffix_for_yyyymmdd
          else
            doc['subject_temporal_start_dtsim'] << date_start[0..3] + start_date_suffix_for_yyyy
          end
        end
        if subject_date_range_end[index]
          doc['subject_temporal_facet_ssim'] << date_start[0..3] + '-' + subject_date_range_end[index][0..3]
          if formatted_date_subject_start
            if subject_date_range_end[index] =~ /[0-9]{4}[0-9-]*\z/ # rough check for date formatting
              formatted_date_subject_end = true
              if subject_date_range_end[index].length == 7
                doc['subject_temporal_end_dtsim'] << subject_date_range_end[index] + end_date_suffix_for_yyyymm
              elsif subject_date_range_end[index].length == 10
                doc['subject_temporal_end_dtsim'] << subject_date_range_end[index] + end_date_suffix_for_yyyymmdd
              else
                doc['subject_temporal_end_dtsim'] << subject_date_range_end[index][0..3] + end_date_suffix_for_yyyy
              end
            end
          end
        else
          doc['subject_temporal_facet_ssim'] << date_start
        end
        if formatted_date_subject_start && !formatted_date_subject_end
          if date_start.length == 7
            doc['subject_temporal_end_dtsim'] << date_start + end_date_suffix_for_yyyymm
          elsif date_start.length == 10
            doc['subject_temporal_end_dtsim'] << date_start + end_date_suffix_for_yyyymmdd
          else
            doc['subject_temporal_end_dtsim'] << date_start[0..3] + end_date_suffix_for_yyyy
          end
        end
      end
    end

    # add temporal subject values to subject facet field
    doc['subject_facet_ssim'].concat(doc['subject_temporal_facet_ssim'])
  end

  # title subjects
  if self..subject.title_info.length > 0
    doc['subject_title_tsim'] = []
    self..subject.title_info.title.each do |subject_title|
      doc['subject_title_tsim'] << subject_title
    end
    doc['subject_facet_ssim'].concat(doc['subject_title_tsim'])
  end

  # de-dupe various subject fields (needed for LCSH-style subjects from MODS OAI feeds)
  subjs_to_dedupe = %w(subject_topic_tsim subject_geo_nonhier_ssim subject_hiergeo_geojson_ssm subject_name_corporate_tsim subject_name_personal_tsim subject_name_conference_tsim subject_temporal_facet_ssim subject_title_tsim)
  subjs_to_dedupe.each do |subj_to_dedupe|
    doc[subj_to_dedupe] = doc[subj_to_dedupe].uniq if doc[subj_to_dedupe]
  end

  # remove values from subject_geo_nonhier_ssim
  # that are represented in subject_hiergeo_geojson_ssm
  if doc['subject_geo_nonhier_ssim'] && doc['subject_hiergeo_geojson_ssm']
    doc['subject_geo_nonhier_ssim'].each do |non_hier_geo_subj|
      doc['subject_hiergeo_geojson_ssm'].each do |hiergeo_geojson_feature|
        #if hiergeo_geojson_feature.match(/#{non_hier_geo_subj}/)
        if hiergeo_geojson_feature.include?(non_hier_geo_subj)
          doc['subject_geo_nonhier_ssim'].delete(non_hier_geo_subj)
        end
      end
    end
  end

  doc['active_fedora_model_suffix_ssi'] = self.rels_ext.model.class.to_s.gsub(/\A[\w]*::/,'')

  doc['rights_ssm'] = []
  doc['license_ssm'] = []
  0.upto self..use_and_reproduction.length-1 do |index|
    case self..use_and_reproduction(index).displayLabel.first
      when 'rights'
        doc['rights_ssm'] << self..use_and_reproduction(index).first
      when 'license'
        doc['license_ssm'] << self..use_and_reproduction(index).first
    end
  end

  doc['restrictions_on_access_ssm'] = self..restriction_on_access

  doc['note_tsim'] = []
  doc['note_resp_tsim'] = []
  doc['note_performers_tsim'] = []
  doc['note_acquisition_tsim'] = []
  doc['note_ownership_tsim'] = []
  doc['note_citation_tsim'] = []
  doc['note_reference_tsim'] = []
  doc['note_physical_tsim'] = []

  0.upto self..note.length-1 do |index|
    if self..note(index).type_at.first == 'statement of responsibility'
      doc['note_resp_tsim'].append(self..mods(0).note(index).first)
    elsif self..note(index).type_at.first == 'date'
      doc['note_date_tsim'].append(self..mods(0).note(index).first)
    elsif self..note(index).type_at.first == 'performers'
      doc['note_performers_tsim'].append(self..mods(0).note(index).first)
    elsif self..note(index).type_at.first == 'acquisition'
      doc['note_acquisition_tsim'].append(self..mods(0).note(index).first)
    elsif self..note(index).type_at.first == 'ownership'
      doc['note_ownership_tsim'].append(self..mods(0).note(index).first)
    elsif self..note(index).type_at.first == 'preferred citation'
      doc['note_citation_tsim'].append(self..mods(0).note(index).first)
    elsif self..note(index).type_at.first == 'citation/reference'
      doc['note_reference_tsim'].append(self..mods(0).note(index).first)
    else
      doc['note_tsim'].append(self..mods(0).note(index).first)
    end
  end

  0.upto self..physical_description.length-1 do |physical_index|
    0.upto self..physical_description(physical_index).note.length-1 do |note_index|
      if self..physical_description(physical_index).note(note_index).first != nil
        doc['note_physical_tsim'].append(self..physical_description(physical_index).note(note_index).first)
      end
    end
  end

  doc['title_info_alternative_tsim'] = []
  doc['title_info_uniform_tsim'] = []
  doc['title_info_primary_trans_tsim'] = []
  doc['title_info_translated_tsim'] = []
  self..mods(0).title.each_with_index do |title_value,index|
    title_prefix = self..mods(0).title_info(index).nonSort[0] ? self..mods(0).title_info(index).nonSort[0] + ' ' : '' # shouldn't be adding space; see Trac ticket #101
    if self..mods(0).title_info(index).usage[0] == 'primary'
      if self..mods(0).title_info(index).type[0] == 'translated'
        if self..mods(0).title_info(index).display_label[0] == 'primary_display'
          doc['title_info_primary_tsi'] = title_prefix + title_value
          doc['title_info_primary_ssort'] = title_value
          doc['title_info_partnum_tsi'] = self..mods(0).title_info(index).part_number
          doc['title_info_partname_tsi'] = self..mods(0).title_info(index).part_name
        else
          doc['title_info_primary_trans_tsim'] << title_prefix + title_value
        end
      else
        doc['title_info_primary_tsi'] = title_prefix + title_value
        doc['title_info_primary_ssort'] = title_value
        doc['title_info_partnum_tsi'] = self..mods(0).title_info(index).part_number
        doc['title_info_partname_tsi'] = self..mods(0).title_info(index).part_name
      end
      if self..mods(0).title_info(index).supplied[0] == 'yes'
        doc['supplied_title_bs'] = 'true'
      end
    elsif self..mods(0).title_info(index).type[0] == 'alternative'
      doc['title_info_alternative_tsim'] << title_prefix + title_value
      if self..mods(0).title_info(index).supplied[0] == 'yes'
        doc['supplied_alternative_title_bs'] = 'true'
      end
      doc['title_info_alternative_label_ssm'] = self..mods(0).title_info(index).display_label
    elsif self..mods(0).title_info(index).type[0] == 'uniform'
      doc['title_info_uniform_tsim'] << title_prefix + title_value
    elsif self..mods(0).title_info(index).type[0] == 'translated'
      doc['title_info_translated_tsim'] << title_prefix + title_value
    end
  end

  doc['subtitle_tsim'] = self..title_info.subtitle


  if self.
    doc['workflow_state_ssi'] = self..item_status.state
    doc['processing_state_ssi'] = self..item_status.processing
  end

  ActiveFedora::Base.find_in_batches('is_exemplary_image_of_ssim'=>"info:fedora/#{self.pid}") do |group|
    group.each { |exemplary_solr|
      doc['exemplary_image_ssi'] = exemplary_solr['id']
    }
  end

=begin
  ocr_text_normal = ''
  ocr_text_squished = ''
  ActiveFedora::Base.find_in_batches('is_image_of_ssim'=>"info:fedora/#{self.pid}") do |group|
    group.each { |image_file|
      if image_file['has_ocr_master_ssi'] == 'true'
        ocr_text_normal += image_file['full_ocr_ssi']
        ocr_text_squished += image_file['compressed_ocr_ssi']
      end

    }
  end

  doc['full_ocr_si'] = ocr_text_normal[0..10000] if ocr_text_normal.present?
  doc['full_ocr_ssi'] = ocr_text_normal[0..10000] if ocr_text_normal.present?
  doc['compressed_ocr_si'] = ocr_text_squished[0..10000] if ocr_text_squished.present?
  doc['compressed_ocr_ssi'] = ocr_text_squished[0..10000] if ocr_text_squished.present?
=end


  if self.plainText.present?
    doc['ocr_tiv'] = self.plainText.content.squish

    pages_ocr_check = Bplmodels::ImageFile.find_with_conditions({"is_image_of_ssim"=>"info:fedora/#{self.pid}","has_ocr_text_bsi"=>"true"}, rows: '1', fl: 'id,has_ocr_text_bsi' )
    doc['has_searchable_text_bsi'] = true if pages_ocr_check.present?
  end

  if self.scanData.present?
    scan_data_xml = Nokogiri::XML(self.scanData.content)
    #See http://archive.org/download/handbookforkitch00neel (created in 2009) for a record lacking this
    doc['text_direction_ssi'] = scan_data_xml.xpath("//globalHandedness/page-progression").first.text if scan_data_xml.xpath("//globalHandedness/page-progression").first.present?
  end

  #Handle the case of multiple volumes...
  if self.class.name == 'Bplmodels::Book'
    volume_check = Bplmodels::Finder.getVolumeObjects(self.pid)
    if volume_check.present?
      doc['ocr_tiv'] = ''
      volume_check.each do |volume|
        #FIXME!!!
        volume_object = ActiveFedora::Base.find(volume['id']).adapt_to_cmodel
        doc['ocr_tiv'] += volume_object.plainText.content.squish + ' ' if volume_object.plainText.present?
      end
    end
  end


  if self..volume_match_md5s.present?
    doc['marc_md5_sum_ssi'] = self..volume_match_md5s.marc.first
    doc['iaMeta_matcher_md5_ssi'] = self..volume_match_md5s.iaMeta.first
  end

  if self..marked_for_deletion.present?
    doc['marked_for_deletion_bsi']  =  self..marked_for_deletion.first
    doc['marked_for_deletion_reason_ssi']  =  self..marked_for_deletion.reason.first
  end

  if self..item_designations.present?
    if self..item_designations(0).flagged_for_content.present?
      doc['flagged_content_ssi'] = self..item_designations(0).flagged_for_content
    end
  end


  #doc['all_text_timv'] = [self.descMetadata.abstract, main_title, self.rels_ext.model.class.to_s.gsub(/\A[\w]*::/,''),self.descMetadata.item_location(0).physical_location[0]]

  doc
end