Class: BCL::ComponentMethods

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

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeComponentMethods

Returns a new instance of ComponentMethods.



28
29
30
31
32
33
34
35
36
37
38
39
# File 'lib/bcl/component_methods.rb', line 28

def initialize
  @parsed_measures_path = './measures/parsed'
  @config = nil
  @session = nil
  @access_token = nil
  @http = nil
  @api_version = 2.0
  @group_id = nil
  @logged_in = false

  load_config
end

Instance Attribute Details

#configObject

Returns the value of attribute config.



22
23
24
# File 'lib/bcl/component_methods.rb', line 22

def config
  @config
end

#httpObject (readonly)

Returns the value of attribute http.



25
26
27
# File 'lib/bcl/component_methods.rb', line 25

def http
  @http
end

#logged_inObject (readonly)

Returns the value of attribute logged_in.



26
27
28
# File 'lib/bcl/component_methods.rb', line 26

def logged_in
  @logged_in
end

#parsed_measures_pathObject

Returns the value of attribute parsed_measures_path.



23
24
25
# File 'lib/bcl/component_methods.rb', line 23

def parsed_measures_path
  @parsed_measures_path
end

#sessionObject (readonly)

Returns the value of attribute session.



24
25
26
# File 'lib/bcl/component_methods.rb', line 24

def session
  @session
end

Instance Method Details

#construct_post_data(filepath, update, content_type_or_uuid) ⇒ Object

Construct the post parameter for the API content.json end point. param(@update) is a boolean that triggers whether to use content_type or uuid



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
# File 'lib/bcl/component_methods.rb', line 227

def construct_post_data(filepath, update, content_type_or_uuid)
  # TODO: remove special characters in the filename; they create firewall errors
  # filename = filename.gsub(/\W/,'_').gsub(/___/,'_').gsub(/__/,'_').chomp('_').strip

  file_b64 = Base64.encode64(File.binread(filepath))

  data = {}
  data['file'] = {
    'file' => file_b64,
    'filesize' => File.size(filepath).to_s,
    'filename' => File.basename(filepath)
  }

  data['node'] = {}

  # Only include the content type if this is an update
  if update
    data['node']['uuid'] = content_type_or_uuid
  else
    data['node']['type'] = content_type_or_uuid
  end

  # TODO: remove this field_component_tags once BCL is fixed
  data['node']['field_component_tags'] = { 'und' => '1289' }
  data['node']['og_group_ref'] = { 'und' => ['target_id' => @group_id] }

  # NOTE THIS ONLY WORKS IF YOU ARE A BCL SITE ADMIN
  data['node']['publish'] = '1'

  data
end

#delete_receipts(array_of_components) ⇒ Object

Delete receipt files



554
555
556
557
558
559
560
561
562
# File 'lib/bcl/component_methods.rb', line 554

def delete_receipts(array_of_components)
  array_of_components.each do |comp|
    receipt_file = File.dirname(comp) + '/' + File.basename(comp, '.tar.gz') + '.receipt'
    if File.exist?(receipt_file)
      FileUtils.remove_file(receipt_file)

    end
  end
end

#download_component(uid) ⇒ Object



570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
# File 'lib/bcl/component_methods.rb', line 570

def download_component(uid)
  result = @http.get("/api/component/download?uids=#{uid}")
  puts "Downloading: http://#{@http.address}/api/component/download?uids=#{uid}"
  # puts "RESULTS: #{result.inspect}"
  # puts "RESULTS BODY: #{result.body}"
  # look at response code
  if result.code == '200'
    # puts 'Download Successful'
    result.body || nil
  else
    puts "Download fail. Error code #{result.code}"
    nil
  end
rescue StandardError
  puts "Couldn't download uid(s): #{uid}...skipping"
  nil
end

#evaluate_api_response(api_response) ⇒ Object

evaluate the response from the API in a consistent manner



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
# File 'lib/bcl/component_methods.rb', line 174

def evaluate_api_response(api_response)
  valid = false
  result = { error: 'could not get json from http post response' }
  case api_response.code
    when '200'
      puts "  Response Code: #{api_response.code}"
      if api_response.body.empty?
        puts '  200 BUT ERROR: Returned body was empty. Possible causes:'
        puts '      - BSD tar on Mac OSX vs gnutar'
        result = { error: 'returned 200, but returned body was empty' }
        valid = false
      else
        puts '  200 - Successful Upload'
        result = JSON.parse api_response.body
        valid = true
      end
    when '404'
      puts "  Error Code: #{api_response.code} - #{api_response.body}"
      puts '   - check these common causes first:'
      puts "     - you are trying to update content that doesn't exist"
      puts "     - you are not an 'administrator member' of the group you're trying to upload to"
      result = JSON.parse api_response.body
      valid = false
    when '406'
      puts "  Error Code: #{api_response.code}"
      # try to parse the response a bit
      error = JSON.parse api_response.body
      puts "temp error: #{error}"
      if error.key?('form_errors')
        if error['form_errors'].key?('field_tar_file')
          result = { error: error['form_errors']['field_tar_file'] }
        elsif error['form_errors'].key?('og_group_ref][und][0][default')
          result = { error: error['form_errors']['og_group_ref][und][0][default'] }
        end
      else
        result = error
      end
      valid = false
    when '500'
      puts "  Error Code: #{api_response.code}"
      result = { error: api_response.message }
      # fail 'server exception'
      valid = false
    else
      puts "  Response: #{api_response.code} - #{api_response.body}"
      valid = false
  end

  [valid, result]
end

#list_all_measuresObject



564
565
566
567
568
# File 'lib/bcl/component_methods.rb', line 564

def list_all_measures
  json = search(nil, 'fq[]=bundle%3Anrel_measure&show_rows=100')

  json
end

#login(username = nil, password = nil, url = nil, group_id = nil) ⇒ Object



41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
# File 'lib/bcl/component_methods.rb', line 41

def (username = nil, password = nil, url = nil, group_id = nil)
  # figure out what url to use
  if url.nil?
    url = @config[:server][:url]
  end
  # look for http vs. https
  if url.include? 'https'
    port = 443
  else
    port = 80
  end
  # strip out http(s)
  url = url.gsub('http://', '')
  url = url.gsub('https://', '')

  if username.nil? || password.nil?
    # log in via cached credentials
    username = @config[:server][:user][:username]
    password = @config[:server][:user][:password]
    @group_id = group_id || @config[:server][:user][:group]
    puts "logging in using credentials in .bcl/config.yml: Connecting to #{url} on port #{port} as #{username} with group #{@group_id}"
  else
    @group_id = group_id || @config[:server][:user][:group]
    puts "logging in using credentials in function arguments: Connecting to #{url} on port #{port} as #{username} with group #{@group_id}"
  end

  if @group_id.nil?
    puts '[WARNING] You did not set a group ID in your config.yml file or pass in a group ID. You can retrieve your group ID from the node number of your group page (e.g., https://bcl.nrel.gov/node/32). Will continue, but you will not be able to upload content.'
  end

  @http = Net::HTTP.new(url, port)
  @http.verify_mode = OpenSSL::SSL::VERIFY_NONE
  if port == 443
    @http.use_ssl = true
  end

  data = %({"username":"#{username}","password":"#{password}"})

   = '/api/user/login.json'
  headers = { 'Content-Type' => 'application/json' }

  res = @http.post(, data, headers)

  # for debugging:
  # res.each do |key, value|
  #  puts "#{key}: #{value}"
  # end

  if res.code == '200'
    puts 'Login Successful'

    bnes = ''
    bni = ''
    junkout = res['set-cookie'].split(';')
    junkout.each do |line|
      if line.match?(/BNES_SESS/)
        bnes = line.match(/(BNES_SESS.*)/)[0]
      end
    end

    junkout.each do |line|
      if line.match?(/BNI/)
        bni = line.match(/(BNI.*)/)[0]
      end
    end

    # puts "DATA: #{data}"
    session_name = ''
    sessid = ''
    json = JSON.parse(res.body)
    json.each do |key, val|
      if key == 'session_name'
        session_name = val
      elsif key == 'sessid'
        sessid = val
      end
    end

    @session = session_name + '=' + sessid + ';' + bni + ';' + bnes

    # get access token
    token_path = '/services/session/token'
    token_headers = { 'Content-Type' => 'application/json', 'Cookie' => @session }
    # puts "token_headers = #{token_headers.inspect}"
    access_token = @http.post(token_path, '', token_headers)
    if access_token.code == '200'
      @access_token = access_token.body
    else
      puts 'Unable to get access token; uploads will not work'
      puts "error code: #{access_token.code}"
      puts "error info: #{access_token.body}"
    end

    # puts "access_token = *#{@access_token}*"
    # puts "cookie = #{@session}"

    res
  else

    puts "error code: #{res.code}"
    puts "error info: #{res.body}"
    puts 'continuing as unauthenticated sessions (you can still search and download)'

    res
  end
end

#push_content(filename_and_path, write_receipt_file, content_type) ⇒ Object

pushes component to the bcl and publishes them (if logged-in as BCL Website Admin user). username, password, and group_id are set in the ~/.bcl/config.yml file



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
# File 'lib/bcl/component_methods.rb', line 261

def push_content(filename_and_path, write_receipt_file, content_type)
  raise 'Please login before pushing components' if @session.nil?
  raise 'Do not have a valid access token; try again' if @access_token.nil?

  data = construct_post_data(filename_and_path, false, content_type)

  path = '/api/content.json'
  headers = { 'Content-Type' => 'application/json', 'X-CSRF-Token' => @access_token, 'Cookie' => @session }

  res = @http.post(path, JSON.dump(data), headers)

  valid, json = evaluate_api_response(res)

  if valid
    # write out a receipt file into the same directory of the component with the same file name as
    # the component
    if write_receipt_file
      File.open("#{File.dirname(filename_and_path)}/#{File.basename(filename_and_path, '.tar.gz')}.receipt", 'w') do |file|
        file << Time.now.to_s
      end
    end
  end

  [valid, json]
end

#push_contents(array_of_components, skip_files_with_receipts, content_type) ⇒ Object



330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
# File 'lib/bcl/component_methods.rb', line 330

def push_contents(array_of_components, skip_files_with_receipts, content_type)
  logs = []
  array_of_components.each do |comp|
    receipt_file = File.dirname(comp) + '/' + File.basename(comp, '.tar.gz') + '.receipt'
    log_message = ''
    if skip_files_with_receipts && File.exist?(receipt_file)
      log_message = "skipping because found receipt #{comp}"
      puts log_message
    else
      log_message = "pushing content #{File.basename(comp, '.tar.gz')}"
      puts log_message
      valid, res = push_content(comp, true, content_type)
      log_message += " #{valid} #{res.inspect.chomp}"
    end
    logs << log_message
  end

  logs
end

#retrieve_measures(search_term = nil, filter_term = nil, return_all_pages = false, &_block) ⇒ Object

retrieve measures for parsing metadata. specify a search term to narrow down search or leave nil to retrieve all set all_pages to true to iterate over all pages of results can’t specify filters other than the hard-coded bundle and show_rows



152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
# File 'lib/bcl/component_methods.rb', line 152

def retrieve_measures(search_term = nil, filter_term = nil, return_all_pages = false, &_block)
  # raise "Please login before performing this action" if @session.nil?

  # make sure filter_term includes bundle
  if filter_term.nil?
    filter_term = 'fq[]=bundle%3Anrel_measure'
  elsif !filter_term.include? 'bundle'
    filter_term += '&fq[]=bundle%3Anrel_measure'
  end

  # use provided search term or nil.
  # if return_all_pages is true, iterate over pages of API results. Otherwise only return first 100
  results = search(search_term, filter_term, return_all_pages)
  puts "#{results[:result].count} results returned"

  results[:result].each do |result|
    puts "retrieving measure: #{result[:measure][:name]}"
    yield result
  end
end

#search(search_str = nil, filter_str = nil, all = false) ⇒ Object

Simple method to search bcl and return the result as hash with symbols If all = true, iterate over pages of results and return all JSON ONLY



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
# File 'lib/bcl/component_methods.rb', line 480

def search(search_str = nil, filter_str = nil, all = false)
  full_url = '/api/search/'

  # add search term
  if !search_str.nil? && search_str != ''
    full_url += search_str
    # strip out xml in case it's included. make sure .json is included
    full_url = full_url.gsub('.xml', '')
    unless search_str.include? '.json'
      full_url += '.json'
    end
  else
    full_url += '*.json'
  end

  # add api_version
  if @api_version < 2.0
    puts "WARNING:  attempting to use search with api_version #{@api_version}. Use API v2.0 for this functionality."
  end
  full_url += "?api_version=#{@api_version}"

  # add filters
  unless filter_str.nil?
    # strip out api_version from filters, if included
    if filter_str.include? 'api_version='
      filter_str = filter_str.gsub(/api_version=\d{1,}/, '')
      filter_str = filter_str.gsub(/&api_version=\d{1,}/, '')
    end
    full_url = full_url + '&' + filter_str
  end

  # simple search vs. all results
  if !all
    puts "search url: #{full_url}"
    res = @http.get(full_url)
    # return unparsed
    JSON.parse res.body, symbolize_names: true
  else
    # iterate over result pages
    # modify filter_str for show_rows=200 for maximum returns
    if filter_str.include? 'show_rows='
      full_url = full_url.gsub(/show_rows=\d{1,}/, 'show_rows=200')
    else
      full_url += '&show_rows=200'
    end
    # make sure filter_str doesn't already have a page=x
    full_url.gsub(/page=\d{1,}/, '')

    pagecnt = 0
    continue = 1
    results = []
    while continue == 1
      # retrieve current page
      full_url_all = full_url + "&page=#{pagecnt}"
      puts "search url: #{full_url_all}"
      response = @http.get(full_url_all)
      # parse here so you can build results array
      res = JSON.parse response.body, symbolize_names: true

      if res[:result].count > 0
        pagecnt += 1
        res[:result].each do |r|
          results << r
        end
      else
        continue = 0
      end
    end
    # return unparsed b/c that is what is expected
    return { result: results }
  end
end

#search_by_uuid(uuid, vid = nil) ⇒ Object



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
# File 'lib/bcl/component_methods.rb', line 434

def search_by_uuid(uuid, vid = nil)
  full_url = '/api/search.json'
  action = nil

  # add api_version
  if @api_version < 2.0
    puts "WARNING:  attempting to use search with api_version #{@api_version}. Use API v2.0 for this functionality."
  end
  full_url += "?api_version=#{@api_version}"

  # uuid
  full_url += "&fq[]=ss_uuid:#{uuid}"

  res = @http.get(full_url)
  res = JSON.parse res.body

  if res['result'].count > 0
    # found content, check version
    content = res['result'].first
    # puts "first result: #{content}"

    # parse out measure vs component
    if content['measure']
      content = content['measure']
    else
      content = content['component']
    end

    # TODO: check version_modified date if it exists?
    if !vid.nil? && content['vuuid'] == vid
      # no update needed
      action = 'noop'
    else
      # vid doesn't match: update existing
      action = 'update'
    end
  else
    # no uuid found: push new
    action = 'push'
  end
  action
end

#update_content(filename_and_path, write_receipt_file, uuid = nil) ⇒ Object

pushes updated content to the bcl and publishes it (if logged-in as BCL Website Admin user). username and password set in ~/.bcl/config.yml file



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
# File 'lib/bcl/component_methods.rb', line 289

def update_content(filename_and_path, write_receipt_file, uuid = nil)
  raise 'Please login before pushing components' unless @session

  # get the UUID if zip or xml file
  version_id = nil
  if uuid.nil?
    puts File.extname(filename_and_path).downcase
    if filename_and_path.match?(/^.*.tar.gz$/i)
      uuid, version_id = uuid_vid_from_tarball(filename_and_path)
      puts "Parsed uuid out of tar.gz file with value #{uuid}"
    end
  else
    # verify the uuid via regex
    unless uuid.match?(/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/)
      raise "uuid of #{uuid} is invalid"
    end
  end
  raise 'Please pass in a tar.gz file or pass in the uuid' unless uuid

  data = construct_post_data(filename_and_path, true, uuid)

  path = '/api/content.json'
  headers = { 'Content-Type' => 'application/json', 'X-CSRF-Token' => @access_token, 'Cookie' => @session }

  res = @http.post(path, JSON.dump(data), headers)

  valid, json = evaluate_api_response(res)

  if valid
    # write out a receipt file into the same directory of the component with the same file name as
    # the component
    if write_receipt_file
      File.open("#{File.dirname(filename_and_path)}/#{File.basename(filename_and_path, '.tar.gz')}.receipt", 'w') do |file|
        file << Time.now.to_s
      end
    end
  end

  [valid, json]
end

#update_contents(array_of_tarball_components, skip_files_with_receipts) ⇒ Object



409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
# File 'lib/bcl/component_methods.rb', line 409

def update_contents(array_of_tarball_components, skip_files_with_receipts)
  logs = []
  array_of_tarball_components.each do |comp|
    receipt_file = File.dirname(comp) + '/' + File.basename(comp, '.tar.gz') + '.receipt'
    log_message = ''
    if skip_files_with_receipts && File.exist?(receipt_file)
      log_message = "skipping update because found receipt #{File.basename(comp)}"
      puts log_message
    else
      uuid, vid = uuid_vid_from_tarball(comp)
      if uuid.nil?
        log_message = "ERROR: uuid not found for #{File.basename(comp)}"
        puts log_message
      else
        log_message = "pushing updated content #{File.basename(comp)}"
        puts log_message
        valid, res = update_content(comp, true, uuid)
        log_message += " #{valid} #{res.inspect.chomp}"
      end
    end
    logs << log_message
  end
  logs
end

#uuid_vid_from_tarball(path_to_tarball) ⇒ Object

Unpack the tarball in memory and extract the XML file to read the UUID and Version ID



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
# File 'lib/bcl/component_methods.rb', line 351

def uuid_vid_from_tarball(path_to_tarball)
  uuid = nil
  vid = nil

  raise "File does not exist #{path_to_tarball}" unless File.exist? path_to_tarball

  tgz = Zlib::GzipReader.open(path_to_tarball)
  Archive::Tar::Minitar::Reader.open(tgz).each do |entry|
    # If taring with tar zcf ameasure.tar.gz -C measure_dir .
    if entry.name =~ /^.{0,2}component.xml$/ || entry.name =~ /^.{0,2}measure.xml$/
      # xml_to_parse = File.new( entry.read )
      xml_file = REXML::Document.new entry.read

      # pull out some information
      if entry.name.match?(/component/)
        u = xml_file.elements['component/uid']
        v = xml_file.elements['component/version_id']
      else
        u = xml_file.elements['measure/uid']
        v = xml_file.elements['measure/version_id']
      end
      raise "Could not find UUID in XML file #{path_to_tarball}" unless u

      # Don't error on version not existing.

      uuid = u.text
      vid = v ? v.text : nil

      # puts "uuid = #{uuid}; vid = #{vid}"
    end
  end

  [uuid, vid]
end

#uuid_vid_from_xml(path_to_xml) ⇒ Object



386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
# File 'lib/bcl/component_methods.rb', line 386

def uuid_vid_from_xml(path_to_xml)
  uuid = nil
  vid = nil

  raise "File does not exist #{path_to_xml}" unless File.exist? path_to_xml

  xml_to_parse = File.new(path_to_xml)
  xml_file = REXML::Document.new xml_to_parse

  if path_to_xml.to_s.split('/').last.match?(/component.xml/)
    u = xml_file.elements['component/uid']
    v = xml_file.elements['component/version_id']
  else
    u = xml_file.elements['measure/uid']
    v = xml_file.elements['measure/version_id']
  end
  raise "Could not find UUID in XML file #{path_to_tarball}" unless u

  uuid = u.text
  vid = v ? v.text : nil
  [uuid, vid]
end