blob: 4f9ab7c99627ea633dacb693f4ddbc0e66b28cea [file] [log] [blame]
David Reiss68f8c382010-01-11 19:13:18 +00001--
2-- Licensed to the Apache Software Foundation (ASF) under one
3-- or more contributor license agreements. See the NOTICE file
4-- distributed with this work for additional information
5-- regarding copyright ownership. The ASF licenses this file
6-- to you under the Apache License, Version 2.0 (the
7-- "License"); you may not use this file except in compliance
8-- with the License. You may obtain a copy of the License at
9--
10-- http://www.apache.org/licenses/LICENSE-2.0
11--
12-- Unless required by applicable law or agreed to in writing,
13-- software distributed under the License is distributed on an
14-- "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15-- KIND, either express or implied. See the License for the
16-- specific language governing permissions and limitations
17-- under the License.
18--
19
20import qualified Calculator
21import Calculator_Iface
22import Tutorial_Types
23import SharedService_Iface
24import Shared_Types
25
26import Thrift
27import Thrift.Protocol.Binary
28import Thrift.Transport
29import Thrift.Server
30
31import Data.Maybe
32import Text.Printf
33import Control.Exception (throw)
34import Control.Concurrent.MVar
35import qualified Data.Map as M
36import Data.Map ((!))
37import Data.Monoid
38
39data CalculatorHandler = CalculatorHandler {mathLog :: MVar (M.Map Int SharedStruct)}
40
41newCalculatorHandler = do
42 log <- newMVar mempty
43 return $ CalculatorHandler log
44
45instance SharedService_Iface CalculatorHandler where
46 getStruct self k = do
47 myLog <- readMVar (mathLog self)
48 return $ (myLog ! (fromJust k))
49
50
51instance Calculator_Iface CalculatorHandler where
52 ping _ =
53 print "ping()"
54
55 add _ n1 n2 = do
56 printf "add(%d,%d)\n" (fromJust n1) (fromJust n2)
57 return ((fromJust n1)+(fromJust n2))
58
59 calculate self mlogid mwork = do
60 printf "calculate(%d, %s)\n" logid (show work)
61
62 let val = case op work of
63 ADD ->
64 num1 work + num2 work
65 SUBTRACT ->
66 num1 work - num2 work
67 MULTIPLY ->
68 num1 work * num2 work
69 DIVIDE ->
70 if num2 work == 0 then
71 throw $
72 InvalidOperation {
73 f_InvalidOperation_what = Just $ fromEnum $ op work,
74 f_InvalidOperation_why = Just "Cannot divide by 0"
75 }
76 else
77 num1 work `div` num2 work
78
79 let logEntry = SharedStruct (Just logid) (Just (show val))
80 modifyMVar_ (mathLog self) $ return .(M.insert logid logEntry)
81
82 return val
83
84 where
85 -- stupid dynamic languages f'ing it up
86 num1 = fromJust . f_Work_num1
87 num2 = fromJust . f_Work_num2
88 op = fromJust . f_Work_op
89 logid = fromJust mlogid
90 work = fromJust mwork
91
92
93 --return val
94
95 zip _ =
96 print "zip()"
97
98main = do
99 handler <- newCalculatorHandler
100 print "Starting the server..."
101 runBasicServer handler Calculator.process 9090
102 print "done."