Added mcollective 2.3.1 package
[packages/trusty/mcollective.git] / lib / mcollective / vendor / json / tools / server.rb
1 #!/usr/bin/env ruby
2
3 require 'webrick'
4 include WEBrick
5 $:.unshift 'ext'
6 $:.unshift 'lib'
7 require 'json'
8
9 class JSONServlet < HTTPServlet::AbstractServlet
10   @@count = 1
11
12   def do_GET(req, res)
13     obj = {
14       "TIME" => Time.now.strftime("%FT%T"),
15       "foo" => "Bär",
16       "bar" => "© ≠ €!",
17       'a' => 2,
18       'b' => 3.141,
19       'COUNT' => @@count += 1,
20       'c' => 'c',
21       'd' => [ 1, "b", 3.14 ],
22       'e' => { 'foo' => 'bar' },
23       'g' => "松本行弘",
24       'h' => 1000.0,
25       'i' => 0.001,
26       'j' => "\xf0\xa0\x80\x81",
27     }
28     res.body = JSON.generate obj
29     res['Content-Type'] = "application/json"
30   end
31 end
32
33 def create_server(err, dir, port)
34   dir = File.expand_path(dir)
35   err.puts "Surf to:", "http://#{Socket.gethostname}:#{port}"
36
37   s = HTTPServer.new(
38     :Port         => port,
39     :DocumentRoot => dir,
40     :Logger       => WEBrick::Log.new(err),
41     :AccessLog    => [
42       [ err, WEBrick::AccessLog::COMMON_LOG_FORMAT  ],
43       [ err, WEBrick::AccessLog::REFERER_LOG_FORMAT ],
44       [ err, WEBrick::AccessLog::AGENT_LOG_FORMAT   ]
45     ]
46   )
47   s.mount("/json", JSONServlet)
48   s
49 end
50
51 default_dir = File.expand_path(File.join(File.dirname(__FILE__), '..', 'data'))
52 dir = ARGV.shift || default_dir
53 port = (ARGV.shift || 6666).to_i
54 s = create_server(STDERR, dir, 6666)
55 t = Thread.new { s.start }
56 trap(:INT) do
57   s.shutdown
58   t.join
59   exit
60 end
61 sleep