added atomic method cabilities
[OpenSRF.git] / 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         osrfAppRegisterMethod( 
16                         MODULENAME, 
17                         "add", 
18                         "osrfMathRun", 
19                         "Addss two numbers",
20                         "[ num1, num2 ]", 2, 0 );
21
22         osrfAppRegisterMethod( 
23                         MODULENAME, 
24                         "sub", 
25                         "osrfMathRun", 
26                         "Subtracts two numbers",
27                         "[ num1, num2 ]", 2, 0 );
28
29         osrfAppRegisterMethod( 
30                         MODULENAME, 
31                         "mult", 
32                         "osrfMathRun", 
33                         "Multiplies two numbers",
34                         "[ num1, num2 ]", 2, 0 );
35
36         osrfAppRegisterMethod( 
37                         MODULENAME, 
38                         "div", 
39                         "osrfMathRun", 
40                         "Divides two numbers",
41                         "[ num1, num2 ]", 2, 0 );
42
43         return 0;
44 }
45
46 int osrfAppChildInit() {
47         return 0;
48 }
49
50 int osrfMathRun( osrfMethodContext* ctx ) {
51
52         OSRF_METHOD_VERIFY_CONTEXT(ctx);        
53
54         jsonObject* x = jsonObjectGetIndex(ctx->params, 0);
55         jsonObject* y = jsonObjectGetIndex(ctx->params, 1);
56
57         if( x && y ) {
58
59                 char* a = jsonObjectToSimpleString(x);
60                 char* b = jsonObjectToSimpleString(y);
61
62                 if( a && b ) {
63
64                         double i = strtod(a, NULL);
65                         double j = strtod(b, NULL);
66                         double r = 0;
67
68                         if(!strcmp(ctx->method->name, "add"))   r = i + j;
69                         if(!strcmp(ctx->method->name, "sub"))   r = i - j;
70                         if(!strcmp(ctx->method->name, "mult"))  r = i * j;
71                         if(!strcmp(ctx->method->name, "div"))   r = i / j;
72
73                         jsonObject* resp = jsonNewNumberObject(r);
74                         osrfAppRespondComplete( ctx, resp );
75                         jsonObjectFree(resp);
76
77                         free(a); free(b);
78                         return 0;
79                 }
80         }
81
82         return -1;
83 }
84
85
86