Class: OMF::SFA::AM::Rest::RestHandler

Inherits:
Base::LObject
  • Object
show all
Defined in:
lib/omf-sfa/am/am-rest/rest_handler.rb

Direct Known Subclasses

AccountHandler, ResourceHandler

Constant Summary collapse

@@service_name =
nil
@@html_template =
File::read(File.dirname(__FILE__) + '/api_template.html')

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(opts = {}) ⇒ RestHandler

Returns a new instance of RestHandler.



107
108
109
# File 'lib/omf-sfa/am/am-rest/rest_handler.rb', line 107

def initialize(opts = {})
  @opts = opts
end

Class Method Details

.load_api_template(fname) ⇒ Object



98
99
100
# File 'lib/omf-sfa/am/am-rest/rest_handler.rb', line 98

def self.load_api_template(fname)
  @@html_template =  File::read(fname)
end

.render_html(parts) ⇒ Object



102
103
104
# File 'lib/omf-sfa/am/am-rest/rest_handler.rb', line 102

def self.render_html(parts)
  self.new().render_html(parts)
end

.service_nameObject



94
95
96
# File 'lib/omf-sfa/am/am-rest/rest_handler.rb', line 94

def self.service_name()
  @@service_name || "Unknown Service"
end

.set_service_name(name) ⇒ Object



90
91
92
# File 'lib/omf-sfa/am/am-rest/rest_handler.rb', line 90

def self.set_service_name(name)
  @@service_name = name
end

Instance Method Details

#call(env) ⇒ Object



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
# File 'lib/omf-sfa/am/am-rest/rest_handler.rb', line 111

def call(env)
  begin
    Thread.current[:http_host] = env["HTTP_HOST"]
    req = ::Rack::Request.new(env)
    if req.request_method == 'OPTIONS'
      return [200 ,{
        'Access-Control-Allow-Origin' => '*' ,
        'Access-Control-Allow-Methods' => 'GET, POST, OPTIONS',
        'Access-Control-Allow-Headers' => 'origin, x-csrftoken, content-type, accept'
      }, ""]
    end
    content_type, body = dispatch(req)
    if body.is_a? Thin::AsyncResponse
      return body.finish
    end
    if req['_format'] == 'html'
      #body = self.class.convert_to_html(body, env, Set.new((@coll_handlers || {}).keys))
      body = convert_to_html(body, env, {}, Set.new((@coll_handlers || {}).keys))
      content_type = 'text/html'
    elsif content_type == 'application/json'
      body = JSON.pretty_generate(body)
    end
    #return [200 ,{'Content-Type' => content_type}, body + "\n"]
    return [200 ,{'Content-Type' => content_type, 'Access-Control-Allow-Origin' => '*' , 'Access-Control-Allow-Methods' => 'GET, POST, OPTIONS' }, body + "\n"]
  rescue RackException => rex
    return rex.reply
  rescue RedirectException => rex
    debug "Redirecting to #{rex.path}"
    return [301, {'Location' => rex.path, "Content-Type" => ""}, ['Next window!']]
  # rescue OMF::SFA::AM::AMManagerException => aex
    # return RackException.new(400, aex.to_s).reply
  rescue Exception => ex
    body = {
      :error => {
        :reason => ex.to_s,
        :bt => ex.backtrace #.select {|l| !l.start_with?('/') }
      }
    }
    warn "ERROR: #{ex}"
    debug ex.backtrace.join("\n")
    return [500, { "Content-Type" => 'application/json', 'Access-Control-Allow-Origin' => '*', 'Access-Control-Allow-Methods' => 'GET, POST, OPTIONS' }, JSON.pretty_generate(body)]
  end
end

#convert_to_html(body, env, opts, collections = Set.new) ⇒ Object



517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
# File 'lib/omf-sfa/am/am-rest/rest_handler.rb', line 517

def convert_to_html(body, env, opts, collections = Set.new)
  req = ::Rack::Request.new(env)
  opts = {
    collections: collections,
    level: 0,
    href_prefix: "#{req.path}/"
  }.merge(opts)

  path = req.path.split('/').select { |p| !p.empty? }
  h2 = ["<a href='/?_format=html&_level=0'>ROOT</a>"]
  path.each_with_index do |s, i|
    h2 << "<a href='/#{path[0 .. i].join('/')}?_format=html&_level=#{i % 2 ? 0 : 1}'>#{s}</a>"
  end

  res = []
  _convert_obj_to_html(body, nil, res, opts)

  render_html(
    result: body,
    title: @@service_name || env["HTTP_HOST"],
    service: h2.join('/'),
    content: res.join("\n")
  )
end

#find_handler(path, opts) ⇒ Object



221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
# File 'lib/omf-sfa/am/am-rest/rest_handler.rb', line 221

def find_handler(path, opts)
  debug "find_handler: path; '#{path}' opts: #{opts}"
  resource_id = opts[:resource_uri] = path.shift
  opts[:resource] = nil
  if resource_id
    resource = opts[:resource] = find_resource(resource_id, {}, opts)
  end
  return self if path.empty?

  raise OMF::SFA::AM::Rest::UnknownResourceException.new "Unknown resource '#{resource_id}'." unless resource
  opts[:context] = resource
  comp = path.shift
  if (handler = @coll_handlers[comp.to_sym])
    opts[:resource_uri] = path.join('/')
    if handler.is_a? Proc
      return handler.call(path, opts)
    end
    return handler.find_handler(path, opts)
  end
  raise UnknownResourceException.new "Unknown sub collection '#{comp}' for '#{resource_id}:#{resource.class}'."
end

#html_templateObject



542
543
544
# File 'lib/omf-sfa/am/am-rest/rest_handler.rb', line 542

def html_template()
  @@html_template
end

#on_delete(resource_uri, opts) ⇒ Object



202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
# File 'lib/omf-sfa/am/am-rest/rest_handler.rb', line 202

def on_delete(resource_uri, opts)
  if resource = opts[:resource]
    if (context = opts[:context])
      remove_resource_from_context(resource, context)
      res = show_resource_status(resource, opts)
    else
      debug "Delete resource #{resource}"
      res = show_deleted_resource(resource.uuid)
      resource.destroy
    end
  else
    # Delete ALL resources of this type
    raise OMF::SFA::AM::Rest::BadRequestException.new "I'm sorry, Dave. I'm afraid I can't do that."
  end
  resource.reload
  return res
end

#on_get(resource_uri, opts) ⇒ Object



155
156
157
158
159
160
161
162
163
# File 'lib/omf-sfa/am/am-rest/rest_handler.rb', line 155

def on_get(resource_uri, opts)
  debug 'get: resource_uri: "', resource_uri, '"'
  if resource_uri
    resource = opts[:resource]
    show_resource_status(resource, opts)
  else
    show_resource_list(opts)
  end
end

#on_post(resource_uri, opts) ⇒ Object



165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
# File 'lib/omf-sfa/am/am-rest/rest_handler.rb', line 165

def on_post(resource_uri, opts)
  #debug 'POST: resource_uri "', resource_uri, '" - ', opts.inspect
  description, format = parse_body(opts, [:json, :form])
  #debug 'POST(', resource_uri, '): body(', format, '): "', description, '"'

  if resource = opts[:resource]
    debug 'POST: Modify ', resource
    modify_resource(resource, description, opts)
  else
    if description.is_a? Array
      resources = description.map do |d|
        debug 'POST: Create? ', d
        create_resource(d, opts)
      end
      return show_resources(resources, nil, opts)
    else
      debug 'POST: Create ', resource_uri
      if resource_uri
        if UUID.validate(resource_uri)
          description[:uuid] = resource_uri
        else
          description[:name] = resource_uri
        end
      end
      resource = create_resource(description, opts, resource_uri)
    end
  end

  if resource
    show_resource_status(resource, opts)
  elsif context = opts[:context]
    show_resource_status(context, opts)
  else
    raise "Report me. Should never get here"
  end
end

#render_html(parts = {}) ⇒ Object

Render an HTML page using the resource’s template. The template is populated with information provided in ‘parts’

  • :title - HTML title

  • :service - Service path (usually a set of <a>)

  • :content - Main content

  • :footer - Optional footer

  • :result - hash or array describing the result (may used by JS to further format)



497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
# File 'lib/omf-sfa/am/am-rest/rest_handler.rb', line 497

def render_html(parts = {})
  #puts "PP>> #{parts}"
  tmpl = html_template()
  if (result = parts[:result])
    tmpl = tmpl.gsub('##JS##', JSON.pretty_generate(result))
  end
  title = parts[:title] || @@service_name || "Unknown Service"
  tmpl = tmpl.gsub('##TITLE##', title)
  if (service = parts[:service])
    tmpl = tmpl.gsub('##SERVICE##', service)
  end
  if (content = parts[:content])
    tmpl = tmpl.gsub('##CONTENT##', content)
  end
  if (footer = parts[:footer])
    tmpl = tmpl.gsub('##FOOTER##', footer)
  end
  tmpl
end