r1445@opsdev009 (orig r76771): mcslee | 2008-01-07 13:50:30 -0800
[amiethrift.git] / tutorial / rb / RubyServer.rb
blob6ecb563434ef0a0b1baba00eeb70b20796b2442d
1 #!/usr/bin/env ruby
3 $:.push('../gen-rb')
5 require 'thrift/transport/tsocket'
6 require 'thrift/protocol/tbinaryprotocol'
7 require 'thrift/server/tserver'
9 require 'Calculator'
10 require 'shared_types'
12 class CalculatorHandler
13   def initialize()
14     @log = {}
15   end
17   def ping()
18     puts "ping()"
19   end
21   def add(n1, n2)
22     print "add(", n1, ",", n2, ")\n"
23     return n1 + n2
24   end
26   def calculate(logid, work)
27     print "calculate(", logid, ", {", work.op, ",", work.num1, ",", work.num2,"})\n"
28     if work.op == Operation::ADD
29       val = work.num1 + work.num2
30     elsif work.op == Operation::SUBTRACT
31       val = work.num1 - work.num2
32     elsif work.op == Operation::MULTIPLY
33       val = work.num1 * work.num2
34     elsif work.op == Operation::DIVIDE
35       if work.num2 == 0
36         x = InvalidOperation.new()
37         x.what = work.op
38         x.why = "Cannot divide by 0"
39         raise x
40       end
41       val = work.num1 / work.num2
42     else
43       x = InvalidOperation.new()
44       x.what = work.op
45       x.why = "Invalid operation"
46       raise x
47     end
49     entry = SharedStruct.new()
50     entry.key = logid
51     entry.value = "#{val}"
52     @log[logid] = entry
54     return val
56   end
58   def getStruct(key)
59     print "getStruct(", key, ")\n"
60     return @log[key]
61   end
63   def zip()
64     print "zip\n"
65   end
67 end
69 handler = CalculatorHandler.new()
70 processor = Calculator::Processor.new(handler)
71 transport = TServerSocket.new(9090)
72 transportFactory = TBufferedTransportFactory.new()
73 server = TSimpleServer.new(processor, transport, transportFactory)
75 puts "Starting the server..."
76 server.serve()
77 puts "done."