| 30 |
ashish |
1 |
%%
|
|
|
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 |
|
|
|
20 |
-module(server).
|
|
|
21 |
|
|
|
22 |
-include("calculator_thrift.hrl").
|
|
|
23 |
|
|
|
24 |
-export([start/0, start/1, handle_function/2,
|
|
|
25 |
stop/1, ping/0, add/2, calculate/2, getStruct/1, zip/0]).
|
|
|
26 |
|
|
|
27 |
debug(Format, Data) ->
|
|
|
28 |
error_logger:info_msg(Format, Data).
|
|
|
29 |
|
|
|
30 |
ping() ->
|
|
|
31 |
debug("ping()",[]),
|
|
|
32 |
ok.
|
|
|
33 |
|
|
|
34 |
add(N1, N2) ->
|
|
|
35 |
debug("add(~p,~p)",[N1,N2]),
|
|
|
36 |
N1+N2.
|
|
|
37 |
|
|
|
38 |
calculate(Logid, Work) ->
|
|
|
39 |
{ Op, Num1, Num2 } = { Work#work.op, Work#work.num1, Work#work.num2 },
|
|
|
40 |
debug("calculate(~p, {~p,~p,~p})", [Logid, Op, Num1, Num2]),
|
|
|
41 |
case Op of
|
|
|
42 |
?tutorial_ADD -> Num1 + Num2;
|
|
|
43 |
?tutorial_SUBTRACT -> Num1 - Num2;
|
|
|
44 |
?tutorial_MULTIPLY -> Num1 * Num2;
|
|
|
45 |
|
|
|
46 |
?tutorial_DIVIDE when Num2 == 0 ->
|
|
|
47 |
throw(#invalidOperation{what=Op, why="Cannot divide by 0"});
|
|
|
48 |
?tutorial_DIVIDE ->
|
|
|
49 |
Num1 div Num2;
|
|
|
50 |
|
|
|
51 |
_Else ->
|
|
|
52 |
throw(#invalidOperation{what=Op, why="Invalid operation"})
|
|
|
53 |
end.
|
|
|
54 |
|
|
|
55 |
getStruct(Key) ->
|
|
|
56 |
debug("getStruct(~p)", [Key]),
|
|
|
57 |
#sharedStruct{key=Key, value="RARG"}.
|
|
|
58 |
|
|
|
59 |
zip() ->
|
|
|
60 |
debug("zip", []),
|
|
|
61 |
ok.
|
|
|
62 |
|
|
|
63 |
%%
|
|
|
64 |
|
|
|
65 |
start() ->
|
|
|
66 |
start(9999).
|
|
|
67 |
|
|
|
68 |
start(Port) ->
|
|
|
69 |
Handler = ?MODULE,
|
|
|
70 |
thrift_socket_server:start([{handler, Handler},
|
|
|
71 |
{service, calculator_thrift},
|
|
|
72 |
{port, Port},
|
|
|
73 |
{name, tutorial_server}]).
|
|
|
74 |
|
|
|
75 |
stop(Server) ->
|
|
|
76 |
thrift_socket_server:stop(Server).
|
|
|
77 |
|
|
|
78 |
handle_function(Function, Args) when is_atom(Function), is_tuple(Args) ->
|
|
|
79 |
case apply(?MODULE, Function, tuple_to_list(Args)) of
|
|
|
80 |
ok -> ok;
|
|
|
81 |
Reply -> {reply, Reply}
|
|
|
82 |
end.
|