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.



14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
# File 'lib/bcl/component_methods.rb', line 14

def initialize
  @parsed_measures_path = './measures/parsed'
  @config = nil
  @http = nil
  @api_version = nil

  # load configs from file or default
  load_config

  # configure connection
  url = @config[:server][:url]
  # 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://', '')

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

  puts "Connecting to BCL at URL: #{@config[:server][:url]}"
end

Instance Attribute Details

#configObject

Returns the value of attribute config.



8
9
10
# File 'lib/bcl/component_methods.rb', line 8

def config
  @config
end

#httpObject (readonly)

Returns the value of attribute http.



11
12
13
# File 'lib/bcl/component_methods.rb', line 11

def http
  @http
end

#logged_inObject (readonly)

Returns the value of attribute logged_in.



12
13
14
# File 'lib/bcl/component_methods.rb', line 12

def logged_in
  @logged_in
end

#parsed_measures_pathObject

Returns the value of attribute parsed_measures_path.



9
10
11
# File 'lib/bcl/component_methods.rb', line 9

def parsed_measures_path
  @parsed_measures_path
end

#sessionObject (readonly)

Returns the value of attribute session.



10
11
12
# File 'lib/bcl/component_methods.rb', line 10

def session
  @session
end

Instance Method Details

#delete_receipts(array_of_components) ⇒ Object

Delete receipt files



254
255
256
257
258
259
260
261
# File 'lib/bcl/component_methods.rb', line 254

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



272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
# File 'lib/bcl/component_methods.rb', line 272

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

#list_all_measuresObject



263
264
265
266
267
268
269
270
# File 'lib/bcl/component_methods.rb', line 263

def list_all_measures
  if @api_version == 2.0
    json = search(nil, 'fq[]=bundle%3Anrel_measure&show_rows=100')
  else
    json = search(nil, 'fq=bundle%3Ameasure&show_rows=100')
  end
  json
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



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

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 @api_version == 2.0
    if filter_term.nil?
      filter_term = 'fq[]=bundle%3Anrel_measure'
    elsif !filter_term.include? 'bundle'
      filter_term += '&fq[]=bundle%3Anrel_measure'
    end
  else
    if filter_term.nil?
      filter_term = 'fq=bundle%3Ameasure'
    elsif !filter_term.include? 'bundle'
      filter_term += '&fq=bundle%3Ameasure'
    end
  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



172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
# File 'lib/bcl/component_methods.rb', line 172

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 (legacy NREL is 2.0, otherwise use new syntax and ignore version)
  if @api_version.nil?
    # see if we can extract it from filter_str:
    tmp = filter_str.match(/api_version=\d{1,}.\d{1,}/)
    if tmp
      @api_version = tmp.to_s.gsub(/api_version=/, '').to_f
      puts "@api_version from filter_str: #{@api_version}"
    end
  end

  if @api_version == 2.0
    full_url += "?api_version=#{@api_version}"
  end
  puts "@api_version: #{@api_version}"

  # add filters
  if !filter_str.nil? 
    # strip out api_version from filters, if included & @api_version is defined
    if (filter_str.include? 'api_version=')
      filter_str = filter_str.gsub(/&api_version=\d{1,}.\d{1,}/, '')
      filter_str = filter_str.gsub(/api_version=\d{1,}.\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



137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
# File 'lib/bcl/component_methods.rb', line 137

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

  # add api_version
  if @api_version == 2.0
    # uuid
    full_url += "?api_version=#{@api_version}"
    full_url += "&fq[]=ss_uuid:#{uuid}"
  else
    # uuid
    full_url += "&fq=uuid:#{uuid}"
  end

  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
  end
   
  content
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



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

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



114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
# File 'lib/bcl/component_methods.rb', line 114

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