Class: Blix::Rest::Server

Inherits:
Object
  • Object
show all
Defined in:
lib/blix/rest/server.rb

Instance Method Summary collapse

Constructor Details

#initialize(options = {}) ⇒ Server

Returns a new instance of Server.



6
7
8
9
10
11
# File 'lib/blix/rest/server.rb', line 6

def initialize(options = {})
  @_parsers = {}
  @_mime_types = {}
  @_options = options
  setup_parsers(options)
end

Instance Method Details

#_cacheObject

the object serving as a cache



19
20
21
22
23
24
25
26
27
28
29
# File 'lib/blix/rest/server.rb', line 19

def _cache
  @_cache ||= begin
    obj = _options[:cache] || _options['cache']
    if obj
      raise "cache must be a subclass of Blix::Rest::Cache" unless obj.is_a?(Cache)
      obj
    else
      MemoryCache.new
    end
  end
end

#_optionsObject

options passed to the server



14
15
16
# File 'lib/blix/rest/server.rb', line 14

def _options
  @_options
end

#call(env) ⇒ Object

the call function is the interface with the rack framework



154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
# File 'lib/blix/rest/server.rb', line 154

def call(env)
  t1 = Time.now
  req = Rack::Request.new(env)

  verb = env['REQUEST_METHOD']
  path = req.path
  path = CGI.unescape(path) unless _options[:unescape] == false

  blk, path_params, options, is_wild = RequestMapper.match(verb, path)

  match_all = RequestMapper.match('ALL', path) unless blk && !is_wild
  blk, path_params, options = match_all if match_all && match_all[0]

  default_format = options && options[:default] && options[:default].to_sym
  force_format   = options && options[:force] && options[:force].to_sym
  do_cache       = options && options[:cache] && !Blix::Rest.cache_disabled
  clear_cache    = options && options[:cache_reset]
  query_format   = options && options[:query] && req.GET['format'] && req.GET['format'].to_sym
  format         = query_format || path_params[:format] || get_format_new(env, options) || default_format || :json
  parser         = get_parser(force_format || format)

  unless parser
    if blk
      return [406, {}, ["Invalid Format: #{format}"]]
    else
      return [404, {}, ["Invalid Url"]]
    end
  end

  parser._options = options

  # check for cached response and return with cached response if found.
  if do_cache && (response = _cache["#{verb}|#{format}|#{path}"])
    return [response.status, response.headers.merge('x-blix-cache' => 'cached'), response.content]
  end

  response = Response.new

  if blk
    begin
      params = env['params']
      context = Context.new(path_params, params, req, format, response, verb, self)
      value   = blk.call(context)
      response_options = context.response_options || {}
    rescue ServiceError => e
      set_default_headers(parser, response)
      response.set(e.status, parser.format_error(e.message), e.headers)
      logger << e.message if $VERBOSE
    rescue RawResponse => e
      value = e.content
      value = [value.to_s] unless value.respond_to?(:each) || value.respond_to?(:call)
      response.status = e.status if e.status
      response.content = value
      response.headers.merge!(e.headers) if e.headers
    rescue AuthorizationError => e
      set_default_headers(parser, response)
      response.set(401, parser.format_error(e.message), AUTH_HEADER => "#{e.type} realm=\"#{e.realm}\", charset=\"UTF-8\"")
    rescue Exception => e
      set_default_headers(parser, response)
      response.set(500, parser.format_error('internal error'))
      logger << e.message
      logger << e.backtrace.join("\n")
    else # no error
      response.set_options(response_options)
      if response_options[:raw]
        response.content = value
      else
        set_default_headers(parser, response)
        parser.format_response(value, response)
      end
      # cache response if requested
      _cache.clear if clear_cache
      _cache["#{verb}|#{format}|#{path}"] = response if do_cache
    end
  else
    set_default_headers(parser, response)
    response.set(404, parser.format_error('Invalid Url'))
  end

  logger << "#{verb} #{path} total time=#{((Time.now - t1) * 1000).round(2)}ms" if $VERBOSE
  [response.status.to_i, response.headers, response.content]
end

#extract_parsers_from_options(options) ⇒ Object



31
32
33
34
35
36
37
38
39
# File 'lib/blix/rest/server.rb', line 31

def extract_parsers_from_options(options)
  options.each do |k, v|
    next unless k =~ /^(\w*)_parser$/

    format = Regexp.last_match(1)
    parser = v
    register_parser(format, parser)
  end
end

#format_error(_message, _format) ⇒ Object

convert the response to the appropriate format



149
150
151
# File 'lib/blix/rest/server.rb', line 149

def format_error(_message, _format)
  parser
end

#get_format(env) ⇒ Object

accept header can have multiple entries. match on regexp can look like this text/html,application/xhtml+xml,application/xml;q=0.9,/;q=0.8 !!!!!



101
102
103
104
105
106
107
# File 'lib/blix/rest/server.rb', line 101

def get_format(env)
  case env['HTTP_ACCEPT']
  when JSON_ENCODED then :json
  when HTML_ENCODED then :html
  when XML_ENCODED then :xml
  end
end

#get_format_from_mime(mime) ⇒ Object

determine standard format from http mime type



110
111
112
113
114
115
116
117
118
# File 'lib/blix/rest/server.rb', line 110

def get_format_from_mime(mime)
  case mime
  when 'application/json' then :json
  when 'text/html' then :html
  when 'application/xml' then :xml
  when 'application/xhtml+xml' then :xhtml
  when '*/*' then :*
  end
end

#get_format_new(env, options) ⇒ Object

attempt to handle multiple accept formats here.. mime can include ‘…/*’ and ‘/’ FIXME



132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
# File 'lib/blix/rest/server.rb', line 132

def get_format_new(env, options)
  accept = options && options[:accept] || :json
  accept = [accept].flatten

  requested = env['HTTP_ACCEPT'].to_s.split(',')
  requested.each do |request|
    parts = request.split(';') # the quality part is after a ;
    mime = parts[0].strip # the mime type
    try = get_format_from_mime(mime)
    next unless try
    return accept[0] || :json if try == :*
    return try if accept.include?(try)
  end
  nil # no match found
end

#get_parser(format) ⇒ Object



46
47
48
# File 'lib/blix/rest/server.rb', line 46

def get_parser(format)
  @_parsers[format.to_s]
end

#get_parser_from_type(type) ⇒ Object



50
51
52
# File 'lib/blix/rest/server.rb', line 50

def get_parser_from_type(type)
  @_mime_types[type.downcase]
end

#register_parser(format, parser) ⇒ Object



54
55
56
57
58
59
60
# File 'lib/blix/rest/server.rb', line 54

def register_parser(format, parser)
  raise "#{format} must be an object with parent class Blix::Rest::FormatParser" unless parser.is_a?(FormatParser)

  parser._format = format
  @_parsers[format.to_s.downcase] = parser
  parser._types.each { |t| @_mime_types[t.downcase] = parser } # register each of the mime types
end

#retrieve_params(env) ⇒ Object

retrieve parameters from the http request



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
# File 'lib/blix/rest/server.rb', line 63

def retrieve_params(env)
  post_params = {}
  body = ''
  params = env['params'] || {}
  params.merge!(::Rack::Utils.parse_nested_query(env['QUERY_STRING']))

  if env['rack.input']
    post_params = ::Rack::Utils::Multipart.parse_multipart(env)
    unless post_params
      body = env['rack.input'].read
      env['rack.input'].rewind

      if body.empty?
        post_params = {}
      else
        begin
          post_params = case env['CONTENT_TYPE']
                        when URL_ENCODED
                          ::Rack::Utils.parse_nested_query(body)
                        when JSON_ENCODED
                          json = MultiJson.load(body)
                          json.is_a?(Hash) ? json : { '_json' => json }
                        else
                          {}
                        end
        rescue StandardError => e
          raise BadRequestError, "Invalid parameters: #{e.class}"
        end
      end
    end
  end
  [params, post_params, body]
end

#set_custom_headers(format, headers) ⇒ Object



40
41
42
43
44
# File 'lib/blix/rest/server.rb', line 40

def set_custom_headers(format, headers)
  parser = get_parser(format)
  raise "parser not found for custom headers format=>#{format}" unless parser
  parser.__custom_headers = headers
end

#set_default_headers(parser, response) ⇒ Object



237
238
239
240
241
242
243
# File 'lib/blix/rest/server.rb', line 237

def set_default_headers(parser, response)
  if parser.__custom_headers
    response.headers.merge! parser.__custom_headers
  else
    parser.set_default_headers(response.headers)
  end
end

#setup_parsers(options) ⇒ Object



120
121
122
123
124
125
126
127
# File 'lib/blix/rest/server.rb', line 120

def setup_parsers(options)
  # Register default parsers
  register_parser('html', HtmlFormatParser.new)
  register_parser('json', JsonFormatParser.new)
  register_parser('xml', XmlFormatParser.new)
  register_parser('raw', RawFormatParser.new)
  extract_parsers_from_options(options)
end