Class: Blix::Rest::Server

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

Instance Method Summary collapse

Constructor Details

#initialize(opts = {}) ⇒ Server

Returns a new instance of Server.



6
7
8
9
10
11
12
13
14
15
16
17
18
# File 'lib/blix/rest/server.rb', line 6

def initialize(opts = {})
  @_parsers = {}
  @_mime_types = {}

  # register the default parsers and any passed in as options.

  register_parser('html', HtmlFormatParser.new)
  register_parser('json', JsonFormatParser.new)
  register_parser('xml', XmlFormatParser.new)
  register_parser('raw', RawFormatParser.new)
  extract_parsers_from_options(opts)
  @_options = opts
end

Instance Method Details

#_cacheObject

the object serving as a cache



27
28
29
30
31
32
33
34
35
36
37
# File 'lib/blix/rest/server.rb', line 27

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



21
22
23
# File 'lib/blix/rest/server.rb', line 21

def _options
  @_options
end

#call(env) ⇒ Object

the call function is the interface with the rack framework



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

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

  verb  = env['REQUEST_METHOD']
  path  = req.path
  path  = CGI.unescape(path).gsub('+',' ') 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] # override


  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 end 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)
    rescue ServiceError => e
      set_default_headers(parser,response)
      response.set(e.status, parser.format_error(e.message), e.headers)
    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'))
      ::Blix::Rest.logger <<  "----------------------------\n#{$!}\n----------------------------"
      ::Blix::Rest.logger <<  "----------------------------\n#{$@}\n----------------------------"
    else # no error
      set_default_headers(parser,response)
      parser.format_response(value, response)
      # 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

  [response.status.to_i, response.headers, response.content]
end

#extract_parsers_from_options(opts) ⇒ Object



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

def extract_parsers_from_options(opts)
  opts.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



153
154
155
# File 'lib/blix/rest/server.rb', line 153

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 !!!!!



114
115
116
117
118
119
120
# File 'lib/blix/rest/server.rb', line 114

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



123
124
125
126
127
128
129
130
131
# File 'lib/blix/rest/server.rb', line 123

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 mjltiple accept formats here.. mime can include ‘…/*’ and ‘/’ FIXME



136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
# File 'lib/blix/rest/server.rb', line 136

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



55
56
57
# File 'lib/blix/rest/server.rb', line 55

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

#get_parser_from_type(type) ⇒ Object



59
60
61
# File 'lib/blix/rest/server.rb', line 59

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

#register_parser(format, parser) ⇒ Object



63
64
65
66
67
68
69
# File 'lib/blix/rest/server.rb', line 63

def register_parser(format, parser)
  raise "#{k} 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



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

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 then
                          json = MultiJson.load(body)
                          if json.is_a?(Hash)
                            json
                          else
                            { '_json' => json }
                          end
                        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



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

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



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

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