public
Description: GET, POST, PUT, DELETE, with something around (ruby)
Homepage: http://rufus.rubyforge.org/rufus-verbs
Clone URL: git://github.com/jmettraux/rufus-verbs.git
rufus-verbs / test / items.rb
100644 334 lines (232 sloc) 5.648 kb
1
2
3
4
5
6
7
8
9
10
11
12
13
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
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
147
148
149
150
151
152
153
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
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
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
286
287
288
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
329
330
331
332
333
334
#
# an in-memory resource set for testing rufus-verbs
#
# jmettraux@gmail.com
#
# Fri Jan 11 12:36:45 JST 2008
#
 
require 'date'
require 'webrick'
 
 
$dcount = 0 # tracking the number of hits when doing digest auth
 
 
#
# the hash for the /items resource (collection)
#
class LastModifiedHash
 
  def initialize
 
    @hash = {}
    touch
  end
 
  def touch (key=nil)
 
    now = Time.now.httpdate
    @hash[key] = now if key
    @hash['__self'] = now
  end
 
  def delete (key)
 
    @hash.delete key
    @hash['__self'] = Time.now.httpdate
  end
 
  def last_modified (key)
 
    key = key || '__self'
    @hash[key]
  end
 
  def clear
 
    @hash.clear
    @hash['__self'] = Time.now.httpdate
  end
end
 
 
#
# This servlet provides a RESTful in-memory resource "/items".
#
class ItemServlet < WEBrick::HTTPServlet::AbstractServlet
 
  @@items = {}
  @@last_item_id = -1
 
  @@lastmod = LastModifiedHash.new
 
  @@authenticator = WEBrick::HTTPAuth::DigestAuth.new(
    :UserDB => WEBrick::HTTPAuth::Htdigest.new('test/test.htdigest'),
    :Realm => 'test_realm')
 
  def initialize (server, *options)
 
    super
    @auth = server.auth
  end
 
  #
  # Overriding the service() method to perform a potential auth check
  #
  def service (req, res)
 
    if @auth == :basic
 
      WEBrick::HTTPAuth.basic_auth(req, res, "items") do |u, p|
        (u != nil and u == p)
      end
 
    elsif @auth == :digest
 
      $dcount += 1
      @@authenticator.authenticate(req, res)
    end
 
    super
  end
 
  def do_GET (req, res)
 
    i = item_id req
 
    return reply(res, 404, "no item '#{i}'") \
      if i and not items[i]
 
    representation, et, lm = fetch_representation i
 
    since = req['If-Modified-Since']
    since = DateTime.parse(since) if since
    match = req['If-None-Match']
 
    if ((not since and not match) or
      (since and (since > DateTime.parse(lm))) or
      (match and (match != et)))
 
      res['Etag'] = et
      res['Last-Modified'] = lm
      res.body = representation.inspect + "\n"
 
    else
 
      reply(res, 304, "Not Modified")
    end
  end
 
  def do_POST (req, res)
 
    query = WEBrick::HTTPUtils::parse_query(req.query_string)
    m = query['_method']
    m = m.downcase if m
    return do_PUT(req, res) if m == 'put'
    return do_DELETE(req, res) if m == 'delete'
 
    i = item_id req
 
    i = (@@last_item_id += 1) unless i
 
    items[i] = req.body
    lastmod.touch i
 
    res['Location'] = "#{@host}/items/#{i}"
    reply res, 201, "item created"
  end
 
  def do_PUT (req, res)
 
    i = item_id req
 
    return reply(res, 404, "no item '#{i}'") unless items[i]
 
    items[i] = req.body
    lastmod.touch i
 
    reply res, 200, "item updated"
  end
 
  def do_DELETE (req, res)
 
    i = item_id req
 
    return reply(res, 404, "no item '#{i}'") unless items[i]
 
    items.delete i
    lastmod.delete i
 
    reply res, 200, "item deleted"
  end
 
  #
  # clears the items
  #
  def self.flush
 
    @@items.clear
    @@lastmod.clear
  end
 
  protected
 
  def items
    @@items
  end
 
  def lastmod
    @@lastmod
  end
 
  def is_modified (req, key)
 
    since = req['If-Modified-Since']
    match = req['If-None-Match']
 
    return true unless since or match
 
    #puts
    #p [ since, match ]
    #puts
 
    (since or match)
  end
 
  #
  # Returns representation, etag, last_modified
  #
  def fetch_representation (key=nil)
 
    representation = if key
      items[key]
    else
      items
    end
 
    [ representation,
      representation.inspect.hash.to_s,
      lastmod.last_modified(key) ]
  end
 
  def reply (res, code, message)
 
    res.status = code
    res.body = message + "\n"
    res['Content-type'] = "text/plain"
  end
 
  def item_id (req)
 
    p = req.path_info[1..-1]
    return nil if not p or p == ''
    p.to_i
  end
end
 
#
# just redirecting to the ItemServlet...
#
class ThingServlet < WEBrick::HTTPServlet::AbstractServlet
 
  def do_GET (req, res)
 
    res.set_redirect(
      WEBrick::HTTPStatus[303],
      "http://localhost:7777/items")
  end
end
 
#
# testing Rufus::Verbs cookies...
#
class CookieServlet < WEBrick::HTTPServlet::AbstractServlet
 
  @@sessions = {}
 
  def do_GET (req, res)
 
    res.body = get_session(req, res).inspect
  end
 
  def do_POST (req, res)
 
    get_session(req, res) << req.body.strip
    res.body = "ok."
  end
 
  protected
 
  def get_session (req, res)
 
    c = req.cookies.find { |c| c.name == 'tcookie' }
 
    if c
      @@sessions[c.value]
    else
      s = []
      key = (Time.now.to_f * 100000).to_i.to_s
      @@sessions[key] = s
      res.cookies << WEBrick::Cookie.new('tcookie', key)
      s
    end
  end
end
 
#
# a servlet that doesn't reply (for timeout testing)
#
class LostServlet < WEBrick::HTTPServlet::AbstractServlet
 
  def do_GET (req, res)
 
    sleep 200
  end
end
 
#
# Serving items, a dummy resource...
# Also serving things, which just redirect to items...
#
class ItemServer
 
  def initialize (args={})
 
    port = args[:port] || 7777
 
    #al = [
    # [ "", WEBrick::AccessLog::COMMON_LOG_FORMAT ],
    # [ "", WEBrick::AccessLog::REFERER_LOG_FORMAT ]]
 
    @server = WEBrick::HTTPServer.new :Port => port, :AccessLog => nil
 
    class << @server
      attr_accessor :auth
    end
 
    @server.auth = args[:auth]
 
    @server.mount "/items", ItemServlet
    @server.mount "/things", ThingServlet
    @server.mount "/cookie", CookieServlet
    @server.mount "/lost", LostServlet
 
    [ 'INT', 'TERM' ].each do |signal|
      trap(signal) { shutdown }
    end
  end
 
  def start
 
    Thread.new { @server.start }
      # else the server and the test lock each other
  end
 
  def shutdown
 
    ItemServlet.flush
    @server.shutdown
  end
end