some api changes
[Evergreen.git] / OpenSRF / src / c-apps / osrf_dbmath.c
1 #include "opensrf/osrf_app_session.h"
2 #include "opensrf/osrf_application.h"
3 #include "objson/object.h"
4 #include "opensrf/osrf_log.h"
5
6 #define MODULENAME "opensrf.dbmath"
7
8 int osrfAppInitialize();
9 int osrfAppChildInit();
10 int osrfMathRun( osrfMethodContext* );
11
12
13 int osrfAppInitialize() {
14
15         osrfLogInit(MODULENAME);
16
17         osrfAppRegisterMethod( 
18                         MODULENAME, 
19                         "add", 
20                         "osrfMathRun", 
21                         "Addss two numbers",
22                         "[ num1, num2 ]", 2 );
23
24         osrfAppRegisterMethod( 
25                         MODULENAME, 
26                         "sub", 
27                         "osrfMathRun", 
28                         "Subtracts two numbers",
29                         "[ num1, num2 ]", 2 );
30
31         osrfAppRegisterMethod( 
32                         MODULENAME, 
33                         "mult", 
34                         "osrfMathRun", 
35                         "Multiplies two numbers",
36                         "[ num1, num2 ]", 2 );
37
38         osrfAppRegisterMethod( 
39                         MODULENAME, 
40                         "div", 
41                         "osrfMathRun", 
42                         "Divides two numbers",
43                         "[ num1, num2 ]", 2 );
44
45         return 0;
46 }
47
48 int osrfAppChildInit() {
49         return 0;
50 }
51
52 int osrfMathRun( osrfMethodContext* ctx ) {
53
54         OSRF_METHOD_VERIFY_CONTEXT(ctx);        
55
56         jsonObject* x = jsonObjectGetIndex(ctx->params, 0);
57         jsonObject* y = jsonObjectGetIndex(ctx->params, 1);
58
59         if( x && y ) {
60
61                 char* a = jsonObjectToSimpleString(x);
62                 char* b = jsonObjectToSimpleString(y);
63
64                 if( a && b ) {
65
66                         double i = strtod(a, NULL);
67                         double j = strtod(b, NULL);
68                         double r = 0;
69
70                         if(!strcmp(ctx->method->name, "add"))   r = i + j;
71                         if(!strcmp(ctx->method->name, "sub"))   r = i - j;
72                         if(!strcmp(ctx->method->name, "mult"))  r = i * j;
73                         if(!strcmp(ctx->method->name, "div"))   r = i / j;
74
75                         jsonObject* resp = jsonNewNumberObject(r);
76                         osrfAppRequestRespondComplete( ctx->session, ctx->request, resp );
77                         jsonObjectFree(resp);
78
79                         free(a); free(b);
80                         return 0;
81                 }
82         }
83
84         return -1;
85 }
86
87
88