source: trunk/zoo-project/zoo-kernel/service_internal_js.c @ 713

Last change on this file since 713 was 640, checked in by djay, 9 years ago

First version including zoo_service shared library

  • Property svn:eol-style set to native
  • Property svn:mime-type set to text/x-csrc
File size: 26.0 KB
RevLine 
[580]1/*
[1]2 * Author : Gérald FENOY
3 *
[360]4 * Copyright (c) 2009-2012 GeoLabs SARL
[1]5 *
6 * Permission is hereby granted, free of charge, to any person obtaining a copy
7 * of this software and associated documentation files (the "Software"), to deal
8 * in the Software without restriction, including without limitation the rights
9 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10 * copies of the Software, and to permit persons to whom the Software is
11 * furnished to do so, subject to the following conditions:
12 *
13 * The above copyright notice and this permission notice shall be included in
14 * all copies or substantial portions of the Software.
15 *
16 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
22 * THE SOFTWARE.
23 */
24
[640]25#include "service_internal_js.h"
26#include "response_print.h"
[1]27
[383]28#ifndef JSCLASS_GLOBAL_FLAGS
29#define JSCLSAS_GLOBAL_FLAGS 0
30#endif
31
[1]32static char dbg[1024];
33
[580]34/**
35 * The function used as alert from the JavaScript environment (ZOO-API)
36 *
37 * @param cx the JavaScript context
38 * @param argc the number of parameters
39 * @param argv1 the parameter values
40 * @return true
41 */
[274]42JSBool
43JSAlert(JSContext *cx, uintN argc, jsval *argv1)
44{
45  jsval *argv = JS_ARGV(cx,argv1);
46  int i=0;
47  JS_MaybeGC(cx);
48  for(i=0;i<argc;i++){
49    JSString* jsmsg = JS_ValueToString(cx,argv[i]);
[471]50    char *tmp=JS_EncodeString(cx,jsmsg);
51    fprintf(stderr,"[ZOO-API:JS] %s\n",tmp);
52    free(tmp);
[274]53  }
54  JS_MaybeGC(cx);
55 
56  return JS_TRUE;
57}
58
[580]59/**
60 * The function used as importScript from the JavaScript environment (ZOO-API)
61 *
62 * @param cx the JavaScript context
63 * @param argc the number of parameters
64 * @param argv1 the parameter values
65 * @return true
66 */
[336]67JSBool
68JSLoadScripts(JSContext *cx, uintN argc, jsval *argv1)
69{
70  JS_MaybeGC(cx);
71
72  char ntmp[1024];
73  getcwd(ntmp,1024);
74
75  jsval *argv = JS_ARGV(cx,argv1);
76  int i=0;
77  JS_MaybeGC(cx);
78  for(i=0;i<argc;i++){
79    char *filename = JSValToChar(cx,&argv[i]);
[364]80    char *api0=(char*)malloc((strlen(ntmp)+strlen(filename)+2)*sizeof(char));
81    sprintf(api0,"%s/%s",ntmp,filename);
[336]82#ifdef JS_DEBUG
83    fprintf(stderr,"Trying to load %s\n",api0);
[364]84    fflush(stderr);
[336]85#endif
86    JSObject *api_script1=loadZooApiFile(cx,JS_GetGlobalObject(cx),api0);
[471]87    free(api0);
[336]88  }
89  JS_MaybeGC(cx);
90  JS_SET_RVAL(cx, argv1, JSVAL_VOID);
91 
92  return JS_TRUE;
93}
94
[580]95/**
96 * Load a JavaScript file then run the function corresponding to the service by
97 * passing the conf, inputs and outputs parameters by value as JavaScript
98 * Objects.
99 *
100 * @param main_conf the conf maps containing the main.cfg settings
101 * @param request the map containing the HTTP request
102 * @param s the service structure
103 * @param inputs the maps containing the inputs
104 * @param outputs the maps containing the outputs
[581]105 * @return SERVICE_SUCCEEDED or SERVICE_FAILED if the service run, -1
[580]106 *  if the service failed to load or throw error at runtime.
107 */
108int zoo_js_support(maps** main_conf,map* request,service* s,maps **inputs,maps **outputs)
[1]109{
[640]110  /*maps* main=*main_conf;
[9]111  maps* _inputs=*inputs;
[640]112  maps* _outputs=*outputs;*/
[9]113
[1]114  /* The class of the global object. */
[383]115  JSClass global_class= {
[1]116    "global", JSCLASS_GLOBAL_FLAGS,
[364]117    JS_PropertyStub, JS_PropertyStub, JS_PropertyStub, JS_StrictPropertyStub,
[1]118    JS_EnumerateStub, JS_ResolveStub, JS_ConvertStub, JS_FinalizeStub,
119    JSCLASS_NO_OPTIONAL_MEMBERS
120  };
121
122  /* JS variables. */
123  JSRuntime *rt;
124  JSContext *cx;
125  JSObject  *global;
126
127  /* Create a JS runtime. */
128  rt = JS_NewRuntime(8L * 1024L * 1024L);
129  if (rt == NULL)
130    return 1;
[9]131 
[1]132  /* Create a context. */
[384]133  cx = JS_NewContext(rt,8192);
[1]134  if (cx == NULL){
135    return 1;
136  }
[383]137  JS_SetOptions(cx, JSOPTION_VAROBJFIX | JSOPTION_JIT | JSOPTION_METHODJIT);
[1]138  JS_SetVersion(cx, JSVERSION_LATEST);
139  JS_SetErrorReporter(cx, reportError);
140
141  /* Create the global object. */
[328]142  global = JS_NewCompartmentAndGlobalObject(cx, &global_class, NULL);
[1]143
144  /* Populate the global object with the standard globals,
145     like Object and Array. */
146  if (!JS_InitStandardClasses(cx, global)){
147    return 1;
148  }
[274]149
[403]150  /* Define specific function and global variable to share with JS runtime
151   */
[368]152  jsval tmp=INT_TO_JSVAL(3);
153  if (!JS_SetProperty(cx, global, "SERVICE_SUCCEEDED", &tmp))
154    return 1;
155  tmp=INT_TO_JSVAL(4);
156  if (!JS_SetProperty(cx, global, "SERVICE_FAILED", &tmp))
157    return 1;
[1]158  if (!JS_DefineFunction(cx, global, "ZOORequest", JSRequest, 4, 0))
159    return 1;
[377]160  if (!JS_DefineFunction(cx, global, "ZOOTranslate", JSTranslate, 4, 0))
161    return 1;
[26]162  if (!JS_DefineFunction(cx, global, "ZOOUpdateStatus", JSUpdateStatus, 2, 0))
163    return 1;
[274]164  if (!JS_DefineFunction(cx, global, "alert", JSAlert, 2, 0))
[336]165    return 1; 
166  if (!JS_DefineFunction(cx, global, "importScripts", JSLoadScripts, 1, 0))
[274]167    return 1;
[1]168
[336]169  /**
170   * Add private context object
171   */
172  void* cxPrivate = request;
173  JS_SetContextPrivate(cx,cxPrivate);
[505]174
[42]175  map* tmpm1=getMap(request,"metapath");
176  char ntmp[1024];
177  getcwd(ntmp,1024);
178
179  /**
180   * Load the first part of the ZOO-API
181   */
[505]182  char *api0=(char*)malloc((strlen(ntmp)+17)*sizeof(char));
183  sprintf(api0,"%s/ZOO-proj4js.js",ntmp);
[274]184#ifdef JS_DEBUG
[42]185  fprintf(stderr,"Trying to load %s\n",api0);
[274]186#endif
187  JSObject *api_script1=loadZooApiFile(cx,global,api0);
[471]188  free(api0);
[42]189  fflush(stderr);
190
[505]191  char *api1=(char*)malloc((strlen(ntmp)+13)*sizeof(char));
192  sprintf(api1,"%s/ZOO-api.js",ntmp);
[274]193#ifdef JS_DEBUG
[42]194  fprintf(stderr,"Trying to load %s\n",api1);
[274]195#endif
196  JSObject *api_script2=loadZooApiFile(cx,global,api1);
[471]197  free(api1);
[42]198  fflush(stderr);
199
[1]200  /* Your application code here. This may include JSAPI calls
201     to create your own custom JS objects and run scripts. */
[640]202  //maps* out=*outputs;
[1]203  int res=SERVICE_FAILED;
[640]204  //maps* mc=*main_conf;
[1]205  map* tmpm2=getMap(s->content,"serviceProvider");
[42]206
[364]207  char *filename=(char*)malloc(strlen(tmpm1->value)+strlen(tmpm2->value)+strlen(ntmp)+3);
[329]208  sprintf(filename,"%s/%s/%s",ntmp,tmpm1->value,tmpm2->value);
209  filename[strlen(tmpm1->value)+strlen(tmpm2->value)+strlen(ntmp)+2]=0;
[274]210#ifdef JS_DEBUG
[26]211  fprintf(stderr,"FILENAME %s\n",filename);
[274]212#endif
[1]213  struct stat file_status;
214  stat(filename, &file_status);
[471]215  //char *source=(char*)malloc(file_status.st_size);
[640]216  //uint16 lineno;
[1]217  jsval rval;
218  JSBool ok ;
[274]219  JSObject *script = JS_CompileFile(cx, global, filename);
[9]220  if(script!=NULL){
[1]221    (void)JS_ExecuteScript(cx, global, script, &rval);
222  }
223  else{
224    char tmp1[1024];
225    sprintf(tmp1,"Unable to load JavaScript file %s",filename);
[471]226    free(filename);
[576]227    errorException(*main_conf,tmp1,"NoApplicableCode",NULL);
[471]228    JS_MaybeGC(cx);
[1]229    JS_DestroyContext(cx);
230    JS_DestroyRuntime(rt);
231    JS_ShutDown();
[471]232    return -1;
[1]233  }
[471]234 
[383]235
[1]236  /* Call a function in obj's scope. */
237  jsval argv[3];
[9]238  JSObject *jsargv1=JSObject_FromMaps(cx,*main_conf);
239  argv[0] = OBJECT_TO_JSVAL(jsargv1);
240  JSObject *jsargv2=JSObject_FromMaps(cx,*inputs);
241  argv[1] = OBJECT_TO_JSVAL(jsargv2);
242  JSObject *jsargv3=JSObject_FromMaps(cx,*outputs);
243  argv[2] = OBJECT_TO_JSVAL(jsargv3);
244  jsval rval1=JSVAL_NULL;
[1]245#ifdef JS_DEBUG
246  fprintf(stderr, "object %p\n", (void *) argv[2]);
247#endif
248
249  ok = JS_CallFunctionName(cx, global, s->name, 3, argv, &rval1);
250
251#ifdef JS_DEBUG
252  fprintf(stderr, "object %p\n", (void *) argv[2]);
253#endif
254
255  JSObject *d;
[9]256  if (ok==JS_TRUE && JSVAL_IS_OBJECT(rval1)==JS_TRUE) {
[1]257#ifdef JS_DEBUG
258    fprintf(stderr,"Function run sucessfully !\n");
259#endif
260    /* Should get a number back from the service function call. */
261    ok = JS_ValueToObject(cx, rval1, &d);
262  }else{
263    /* Unable to run JS function */
264    char tmp1[1024];
[9]265    if(strlen(dbg)==0)
266      sprintf(dbg,"No result was found after the function call");
[274]267    sprintf(tmp1,"Unable to run %s from the JavaScript file %s : \n %s",s->name,filename,dbg);
268#ifdef JS_DEBUG
[1]269    fprintf(stderr,"%s",tmp1);
[274]270#endif
[576]271    errorException(*main_conf,tmp1,"NoApplicableCode",NULL);
[471]272    free(filename);
273    JS_MaybeGC(cx);
[1]274    JS_DestroyContext(cx);
275    JS_DestroyRuntime(rt);
276    JS_ShutDown();
[9]277    // Should return -1 here but the unallocation won't work from zoo_service_loader.c line 1847
[471]278    return -1;
[1]279  }
280
[640]281  //jsval t=OBJECT_TO_JSVAL(d);
[9]282  if(JS_IsArrayObject(cx,d)){
[1]283#ifdef JS_DEBUG
284    fprintf(stderr,"An array was returned !\n");
285#endif
[364]286    jsuint       len;
[9]287    if((JS_GetArrayLength(cx, d, &len)==JS_FALSE)){
[1]288#ifdef JS_DEBUG
289      fprintf(stderr,"outputs array is empty\n");
290#endif
291    }
292    jsval tmp1;
[9]293    JSBool hasResult=JS_GetElement(cx,d,0,&tmp1);
[1]294    res=JSVAL_TO_INT(tmp1);
295#ifdef JS_DEBUG
296    fprintf(stderr," * %d * \n",res);
297#endif
[383]298    if(res==SERVICE_SUCCEEDED){
299      jsval tmp2;
300      JSBool hasElement=JS_GetElement(cx,d,1,&tmp2);
301      if(hasElement==JS_TRUE){
302        freeMaps(outputs);
303        free(*outputs);
304        *outputs=mapsFromJSObject(cx,tmp2);
305      }
306    }else{
307      jsval tmp3;
308      JSBool hasConf=JS_GetElement(cx,d,1,&tmp3);
309      if(hasConf==JS_TRUE){
310        freeMaps(main_conf);
311        free(*main_conf);
312        *main_conf=mapsFromJSObject(cx,tmp3);
313      }
[9]314    }
[383]315
[1]316  }
317  else{
[9]318#ifdef JS_DEBUG
[383]319    fprintf(stderr,"The service didn't return an array !\n");
[9]320#endif
[383]321    /**
322     * Extract result
323     */
[1]324    jsval tmp1;
[9]325    JSBool hasResult=JS_GetProperty(cx,d,"result",&tmp1);
[1]326    res=JSVAL_TO_INT(tmp1);
327
[9]328#ifdef JS_DEBUG
[1]329    fprintf(stderr," * %d * \n",res);
[9]330#endif
[383]331    /**
332     * Extract outputs when available.
333     */
[1]334    jsval tmp2;
[9]335    JSBool hasElement=JS_GetProperty(cx,d,"outputs",&tmp2);
[383]336    if(!JSVAL_IS_VOID(tmp2) && hasElement==JS_TRUE){
337      freeMaps(outputs);
338      free(*outputs);   
339      *outputs=mapsFromJSObject(cx,tmp2);
340    }
341    JS_MaybeGC(cx);
[274]342#ifdef JS_DEBUG
[383]343    if(JSVAL_IS_VOID(tmp2))
[1]344      fprintf(stderr,"No outputs property returned\n");
[383]345    else{
346      if(JS_IsArrayObject(cx,JSVAL_TO_OBJECT(tmp2)))
347        fprintf(stderr,"outputs is an array as expected\n");
348      else
349        fprintf(stderr,"outputs is not an array as expected\n");
350    }
351    JS_MaybeGC(cx);
[274]352#endif
[383]353
354    /**
355     * Extract conf when available.
356     */
357    jsval tmp3;
358    JSBool hasConf=JS_GetProperty(cx,d,"conf",&tmp3);
359    if(!JSVAL_IS_VOID(tmp3) && hasConf==JS_TRUE){
360      freeMaps(main_conf);
361      free(*main_conf);
362      *main_conf=mapsFromJSObject(cx,tmp3);
363    }
364    JS_MaybeGC(cx);
365
[1]366#ifdef JS_DEBUG
[364]367    dumpMaps(*outputs);
[1]368#endif
369  }
370  /* Cleanup. */
[383]371  JS_MaybeGC(cx);
[274]372  JS_DestroyContext(cx);
[1]373  JS_DestroyRuntime(rt);
374  JS_ShutDown();
[471]375  free(filename);
[1]376#ifdef JS_DEBUG
377  fprintf(stderr,"Returned value %d\n",res);
378#endif
379  return res;
380}
381
[580]382/**
383 * Load a JavaScript file
384 *
385 * @param cx the JavaScript context
[586]386 * @param global the global JavaScript object (not used)
[580]387 * @param filename the file name to load
388 * @return a JavaScript Object on success, NULL if an errro occured
389 */
[274]390JSObject * loadZooApiFile(JSContext *cx,JSObject  *global, char* filename){
[42]391  struct stat api_status;
392  int s=stat(filename, &api_status);
393  if(s==0){
394    jsval rval;
[274]395    JSObject *script = JS_CompileFile(cx, JS_GetGlobalObject(cx), filename);
[42]396    if(script!=NULL){
[274]397      (void)JS_ExecuteScript(cx, JS_GetGlobalObject(cx), script, &rval);
398#ifdef JS_DEBUG
[42]399      fprintf(stderr,"**************\n%s correctly loaded\n**************\n",filename);
[274]400#endif
[42]401      return script;
402    }
[274]403#ifdef JS_DEBUG
[42]404    else
405      fprintf(stderr,"\n**************\nUnable to run %s\n**************\n",filename);
[274]406#endif
[42]407  }
[274]408#ifdef JS_DEBUG
[42]409  else
410    fprintf(stderr,"\n**************\nUnable to load %s\n**************\n",filename);
[274]411#endif
[42]412  return NULL;
413}
414
[580]415/**
416 * Convert a maps to a JavaScript Object
417 *
418 * @param cx the JavaScript context
419 * @param t the maps to convert
420 * @return a new JavaScript Object
421 */
[1]422JSObject* JSObject_FromMaps(JSContext *cx,maps* t){
[328]423  JSObject* res=JS_NewObject(cx, NULL, NULL, NULL);
[9]424  if(res==NULL)
425    fprintf(stderr,"Array Object is NULL!\n");
[1]426  maps* tmp=t;
427  while(tmp!=NULL){
428    JSObject *pval=JSObject_FromMap(cx,tmp->content);
429    jsval pvalj=OBJECT_TO_JSVAL(pval);
[328]430    JS_SetProperty(cx, res, tmp->name, &pvalj);
[1]431#ifdef JS_DEBUG
432    fprintf(stderr,"Length of the Array %d, element : %s added \n",len,tmp->name);
433#endif
434    tmp=tmp->next;
435  } 
436  return res;
437}
438
[580]439/**
440 * Convert a map to a JavaScript Object
441 *
442 * @param cx the JavaScript context
443 * @param t the map to convert
444 * @return a new JavaScript Object
445 */
[1]446JSObject* JSObject_FromMap(JSContext *cx,map* t){
447  JSObject* res=JS_NewObject(cx, NULL, NULL, NULL);
448  map* tmpm=t;
[360]449  map* isArray=getMap(t,"isArray");
450  map* isBinary=getMap(t,"size");
451  map* tmap=getMapType(t);
[403]452#ifdef JS_DEBUG
[360]453  if(tmap==NULL)
454    fprintf(stderr,"tmap is null !\n");
455  else
456    fprintf(stderr,"tmap is not null ! (%s = %s)\n",tmap->name,tmap->value);
[364]457#endif
[640]458  while(isArray==NULL && tmpm!=NULL){
[410]459    jsval jsstr;
[640]460    if((isBinary!=NULL && strncasecmp(tmpm->name,"value",5)==0))
[410]461      jsstr = STRING_TO_JSVAL(JS_NewStringCopyN(cx,tmpm->value,atoi(isBinary->value)));
462    else
463      jsstr = STRING_TO_JSVAL(JS_NewStringCopyN(cx,tmpm->value,strlen(tmpm->value)));
464    JS_SetProperty(cx, res, tmpm->name,&jsstr);
[1]465#ifdef JS_DEBUG
[410]466    fprintf(stderr,"[JS] %s => %s\n",tmpm->name,tmpm->value);
[1]467#endif
[410]468    tmpm=tmpm->next;
[1]469  }
[410]470  if(isArray!=NULL){
[360]471    map* len=getMap(t,"length");
472    int cnt=atoi(len->value);
473    JSObject* values=JS_NewArrayObject( cx, cnt, NULL );
474    JSObject* mvalues=JS_NewArrayObject( cx, cnt, NULL );
475    map *tmpm1,*tmpm2;
476    int i=0;
477    for(i=0;i<cnt;i++){
478      tmpm1=getMapArray(t,"value",i);
479      tmpm2=getMapArray(t,tmap->name,i);
480      if(tmpm1!=NULL){
481        jsval jsstr = STRING_TO_JSVAL(JS_NewStringCopyN(cx,tmpm1->value,strlen(tmpm1->value)));
482        JS_SetElement( cx, values, i, &jsstr );
483      }
484      if(tmpm2!=NULL){
485        jsval jsstr = STRING_TO_JSVAL(JS_NewStringCopyN(cx,tmpm2->value,strlen(tmpm2->value)));
486        JS_SetElement( cx, mvalues, i, &jsstr );
487      }
488    }
489    jsval jvalues=OBJECT_TO_JSVAL(values);
490    jsval jmvalues=OBJECT_TO_JSVAL(mvalues);
491    JS_SetProperty(cx, res,"value",&jvalues);
492    JS_SetProperty(cx, res,tmap->name,&jmvalues);
493  }
[1]494  return res;
495}
496
[580]497/**
498 * Convert a JavaScript Object to a maps
499 *
500 * @param cx the JavaScript context
501 * @param t the JavaScript Object to convert
502 * @return a new maps containing the JavaScript Object
503 */
[1]504maps* mapsFromJSObject(JSContext *cx,jsval t){
505  maps *res=NULL;
506  maps *tres=NULL;
[9]507  jsint oi=0;
508  JSObject* tt=JSVAL_TO_OBJECT(t);
[333]509  if(JS_IsArrayObject(cx,tt)){
[1]510#ifdef JS_DEBUG
511    fprintf(stderr,"Is finally an array !\n");
[333]512#endif
[1]513  }
[333]514  else{
515#ifdef JS_DEBUG
[1]516    fprintf(stderr,"Is not an array !\n");
517#endif
[333]518    JSIdArray *idp=JS_Enumerate(cx,tt);
519    if(idp!=NULL) {
520      int index;
521      jsdouble argNum;
522#ifdef JS_DEBUG
523      fprintf(stderr,"Properties length :  %d \n",idp->length);
524#endif
525     
526      for (index=0,argNum=idp->length;index<argNum;index++) { 
527        jsval id = idp->vector[index];
528        jsval vp;
529        JS_IdToValue(cx,id,&vp);
[640]530        char *tmp;
[333]531        JSString *jsmsg;
532        size_t len1;
533        jsmsg = JS_ValueToString(cx,vp);
534        len1 = JS_GetStringLength(jsmsg);
[471]535       
536        tmp=JS_EncodeString(cx,jsmsg);
[333]537        tres=(maps*)malloc(MAPS_SIZE);
[471]538        tres->name=zStrdup(tmp);
[333]539        tres->content=NULL;
540        tres->next=NULL;
541
542        jsval nvp=JSVAL_NULL;
[471]543        if((JS_GetProperty(cx, tt, tmp, &nvp)==JS_FALSE)){
[333]544#ifdef JS_DEBUG
[471]545          fprintf(stderr,"Enumerate id : %d => %s => No more value\n",oi,tmp);
[333]546#endif
547        }
[471]548        free(tmp);
[364]549        JSObject *nvp1=JSVAL_TO_OBJECT(JSVAL_NULL);
[333]550        JS_ValueToObject(cx,nvp,&nvp1);
551        jsval nvp1j=OBJECT_TO_JSVAL(nvp1);
552        if(JSVAL_IS_OBJECT(nvp1j)){
553          tres->content=mapFromJSObject(cx,nvp1j);
554        }
555
556        if(res==NULL)
557          res=dupMaps(&tres);
558        else
559          addMapsToMaps(&res,tres);
560        freeMaps(&tres);
561        free(tres);
562        tres=NULL;
[403]563               
[333]564      }
[471]565      JS_DestroyIdArray(cx,idp);
[333]566    }
567  }
568
[364]569  jsuint len;
[9]570  JSBool hasLen=JS_GetArrayLength(cx, tt, &len);
[383]571#ifdef JS_DEBUG
[9]572  if(hasLen==JS_FALSE){
[1]573    fprintf(stderr,"outputs array is empty\n");
574  }
575  fprintf(stderr,"outputs array length : %d\n",len);
576#endif
[640]577  for(oi=0;hasLen && oi < len;oi++){
[1]578#ifdef JS_DEBUG
[9]579    fprintf(stderr,"outputs array length : %d step %d \n",len,oi);
[1]580#endif
581    jsval tmp1;
[9]582    JSBool hasElement=JS_GetElement(cx,tt,oi,&tmp1);
583    JSObject *otmp1=JSVAL_TO_OBJECT(tmp1);
584    JSIdArray *idp=JS_Enumerate(cx,otmp1);
[1]585    if(idp!=NULL) {
586      int index;
587      jsdouble argNum;
588#ifdef JS_DEBUG
589      fprintf(stderr,"Properties length :  %d \n",idp->length);
590#endif
[274]591      tres=(maps*)malloc(MAPS_SIZE);
592      tres->name=NULL;
593      tres->content=NULL;
594      tres->next=NULL;
595
[1]596      for (index=0,argNum=idp->length;index<argNum;index++) { 
[9]597        jsval id = idp->vector[index];
[1]598        jsval vp;
599        JS_IdToValue(cx,id,&vp);
[640]600        char *tmp;
[1]601        JSString *jsmsg;
602        size_t len1;
603        jsmsg = JS_ValueToString(cx,vp);
604        len1 = JS_GetStringLength(jsmsg);
[471]605        tmp=JS_EncodeString(cx,jsmsg);
[1]606#ifdef JS_DEBUG
[471]607        fprintf(stderr,"Enumerate id : %d => %s\n",oi,tmp);
[1]608#endif
[9]609        jsval nvp=JSVAL_NULL;
[471]610        if((JS_GetProperty(cx, JSVAL_TO_OBJECT(tmp1), tmp, &nvp)==JS_FALSE)){
[1]611#ifdef JS_DEBUG
[471]612          fprintf(stderr,"Enumerate id : %d => %s => No more value\n",oi,tmp);
[1]613#endif
[274]614        }
[471]615        free(tmp);
[1]616        if(JSVAL_IS_OBJECT(nvp)){
617#ifdef JS_DEBUG
618          fprintf(stderr,"JSVAL NVP IS OBJECT\n");
619#endif
620        }
[274]621
[364]622        JSObject *nvp1=JSVAL_TO_OBJECT(JSVAL_NULL);
[1]623        JS_ValueToObject(cx,nvp,&nvp1);
624        jsval nvp1j=OBJECT_TO_JSVAL(nvp1);
625        if(JSVAL_IS_OBJECT(nvp1j)){
[274]626          JSString *jsmsg1;
[471]627          char *tmp1, *tmp2;
[364]628          JSObject *nvp2=JSVAL_TO_OBJECT(JSVAL_NULL);
[274]629          jsmsg1 = JS_ValueToString(cx,nvp1j);
630          len1 = JS_GetStringLength(jsmsg1);
[471]631          tmp1=JS_EncodeString(cx,jsmsg1);
632          tmp2=JS_EncodeString(cx,jsmsg);
[277]633#ifdef JS_DEBUG
[471]634          fprintf(stderr,"JSVAL NVP1J IS OBJECT %s = %s\n",JS_EncodeString(cx,jsmsg),tmp1);
[277]635#endif
[471]636          if(strcasecmp(tmp1,"[object Object]")==0){
637            tres->name=zStrdup(tmp2);
[274]638            tres->content=mapFromJSObject(cx,nvp1j);
639          }
[1]640          else
[471]641            if(strcasecmp(tmp2,"name")==0){
642              tres->name=zStrdup(tmp1);
[274]643            }
644            else{
645              if(tres->content==NULL)
[471]646                tres->content=createMap(tmp2,tmp1);
[274]647              else
[471]648                addToMap(tres->content,tmp2,tmp1);
[274]649            }
[471]650          free(tmp1);
651          free(tmp2);
[1]652        }
653#ifdef JS_DEBUG
654        else
655          fprintf(stderr,"JSVAL NVP1J IS NOT OBJECT !!\n");
656#endif
657      }
[277]658#ifdef JS_DEBUG
[274]659      dumpMaps(tres);
[277]660#endif
[274]661      if(res==NULL)
662        res=dupMaps(&tres);
663      else
664        addMapsToMaps(&res,tres);
665      freeMaps(&tres);
666      free(tres);
667      tres=NULL;
[471]668      JS_DestroyIdArray(cx,idp);
[1]669    }
670  }
[277]671#ifdef JS_DEBUG
[1]672  dumpMaps(res);
[277]673#endif
[1]674  return res;
675}
676
[580]677/**
678 * Convert a JavaScript Object to a map
679 *
680 * @param cx the JavaScript context
681 * @param t the JavaScript Object to convert
682 * @return a new map containing the JavaScript Object
683 */
[1]684map* mapFromJSObject(JSContext *cx,jsval t){
685  map *res=NULL;
[9]686  JSIdArray *idp=JS_Enumerate(cx,JSVAL_TO_OBJECT(t));
[1]687#ifdef JS_DEBUG
688  fprintf(stderr,"Properties %p\n",(void*)t);
689#endif
690  if(idp!=NULL) {
691    int index;
692    jsdouble argNum;
693#ifdef JS_DEBUG
694    fprintf(stderr,"Properties length :  %d \n",idp->length);
695#endif
696    for (index=0,argNum=idp->length;index<argNum;index++) { 
[9]697      jsval id = idp->vector[index];
[1]698      jsval vp;
699      JS_IdToValue(cx,id,&vp);
[640]700      char *tmp, *tmp1;
[1]701      JSString *jsmsg,*jsmsg1;
702      size_t len,len1;
703      jsmsg = JS_ValueToString(cx,vp);
704      len = JS_GetStringLength(jsmsg);
705      jsval nvp;
[471]706      tmp=JS_EncodeString(cx,jsmsg);
707      JS_GetProperty(cx, JSVAL_TO_OBJECT(t), tmp, &nvp);
[1]708      jsmsg1 = JS_ValueToString(cx,nvp);
709      len1 = JS_GetStringLength(jsmsg1);
[471]710      tmp1=JS_EncodeString(cx,jsmsg1);
[1]711#ifdef JS_DEBUG
[471]712      fprintf(stderr,"Enumerate id : %d [ %s => %s ]\n",index,tmp,tmp1);
[1]713#endif
[9]714      if(res!=NULL){
[26]715#ifdef JS_DEBUG
[471]716        fprintf(stderr,"%s - %s\n",tmp,tmp1);
[26]717#endif
[471]718        addToMap(res,tmp,tmp1);
[9]719      }
720      else{
[471]721        res=createMap(tmp,tmp1);
[9]722        res->next=NULL;
723      }
[471]724      free(tmp);
725      free(tmp1);
[26]726#ifdef JS_DEBUG
[9]727      dumpMap(res);
[26]728#endif
[1]729    }
[471]730    JS_DestroyIdArray(cx,idp);
[1]731  }
732#ifdef JS_DEBUG
733  dumpMap(res);
734#endif
735  return res;
736}
737
[580]738/**
739 * Print debug information messages on stderr
740 *
741 * @param cx the JavaScript context
742 * @param message the error message
743 * @param report the JavaScript Error Report
744 */
[1]745void reportError(JSContext *cx, const char *message, JSErrorReport *report)
746{
747  sprintf(dbg,"%s:%u:%s\n",
748          report->filename ? report->filename : "<no filename>",
749          (unsigned int) report->lineno,
750          message);
751#ifdef JS_DEBUG
752  fprintf(stderr,"%s",dbg);
753#endif
754  fflush(stderr);
755}
756
[580]757/**
758 * Convert a JavaScript value to a char*
759 *
760 * @param context the JavaScript context
761 * @param arg the JavaScript value
762 * @return a new char*
763 * @warning be sure to free the ressources returned by this function
764 */
[368]765char* JSValToChar(JSContext* context, jsval* arg) {
766  char *c;
767  char *tmp;
768  JSString *jsmsg;
769  size_t len;
770  int i;
771  if(!JSVAL_IS_STRING(*arg)) {
772    return NULL;
773  }
774  jsmsg = JS_ValueToString(context,*arg);
775  len = JS_GetStringLength(jsmsg);
776  tmp = JS_EncodeString(context,jsmsg);
777  c = (char*)malloc((len+1)*sizeof(char));
778  c[len] = '\0';
779#ifdef ULINET_DEBUG
780  fprintf(stderr,"%d \n",len);
781#endif
782  for(i = 0;i < len;i++) {
783    c[i] = tmp[i];
784    c[i+1] = 0;
785  }
786#ifdef ULINET_DEBUG
787  fprintf(stderr,"%s \n",c);
788#endif
789  return c;
790}
791
[580]792/**
793 * Set the HTTP header of a request
794 *
795 * @param handle the HINTERNET handle
796 * @param cx the JavaScript context
797 * @param header the JavaScript Array containing the headers to send
798 * @return the HINTERNET handle
799 */
[492]800HINTERNET setHeader(HINTERNET* handle,JSContext *cx,JSObject *header){
[368]801  jsuint length=0;
802  jsint i=0;
803  char *tmp1;
804#ifdef ULINET_DEBUG
805  fprintf(stderr,"setHeader\n");
806#endif
807  if(JS_IsArrayObject(cx,header)){
808#ifdef ULINET_DEBUG
809    fprintf(stderr,"header is an array\n");
810#endif
811    JS_GetArrayLength(cx,header,&length);
812#ifdef ULINET_DEBUG
813    fprintf(stderr,"header is an array of %d elements\n",length);
814#endif
[492]815    handle->ihandle[handle->nb].header=NULL;
[368]816    for(i=0;i<length;i++){
817      jsval tmp;
818      JS_GetElement(cx,header,i,&tmp);
819      tmp1=JSValToChar(cx,&tmp);
820#ifdef ULINET_DEBUG
[492]821      curl_easy_setopt(handle->ihandle[handle->nb].handle,CURLOPT_VERBOSE,1);
[368]822      fprintf(stderr,"Element of array n° %d, value : %s\n",i,tmp1);
823#endif
[492]824      handle->ihandle[handle->nb].header=curl_slist_append(handle->ihandle[handle->nb].header, tmp1);
[368]825      free(tmp1);
826    }
827  }
828  else{
829    fprintf(stderr,"not an array !!!!!!!\n");
830  }
[492]831  return *handle;
[368]832}
833
[580]834/**
835 * The function used as ZOOTranslate from the JavaScript environment.
836 * Use the ZOO-Services messages translation function from the Python
837 * environment (ZOO-API)
838 *
839 * @param cx the JavaScript context
840 * @param argc the number of parameters
841 * @param argv1 the parameter values
842 * @return true
843 */
[368]844JSBool
[377]845JSTranslate(JSContext *cx, uintN argc, jsval *argv1)
846{
847  jsval *argv = JS_ARGV(cx,argv1);
848  char *str=JSValToChar(cx,&argv[0]);
849  char *tmpValue=_ss(str);
850  JS_SET_RVAL(cx, argv1,STRING_TO_JSVAL(JS_NewStringCopyN(cx,tmpValue,strlen(tmpValue)))); 
851  JS_MaybeGC(cx);
852  return JS_TRUE;
853}
854
[580]855/**
856 * The function used as ZOORequest from the JavaScript environment (ZOO-API)
857 *
858 * @param cx the JavaScript context
859 * @param argc the number of parameters
860 * @param argv1 the parameter values
861 * @return true
862 * @see setHeader
863 */
[377]864JSBool
[368]865JSRequest(JSContext *cx, uintN argc, jsval *argv1)
866{
867  jsval *argv = JS_ARGV(cx,argv1);
868  HINTERNET hInternet;
869  JSObject *header;
870  char *url;
871  char *method;
872  char* tmpValue;
873  size_t dwRead;
874  JS_MaybeGC(cx);
875  hInternet=InternetOpen("ZooWPSClient\0",
876                         INTERNET_OPEN_TYPE_PRECONFIG,
877                         NULL,NULL, 0);
878  if(!CHECK_INET_HANDLE(hInternet))
879    return JS_FALSE;
880  if(argc>=2){
881    method=JSValToChar(cx,&argv[0]);
882    url=JSValToChar(cx,&argv[1]);
883  }
884  else{
[453]885    method=zStrdup("GET");
[368]886    url=JSValToChar(cx,argv);
887  }
[492]888  hInternet.waitingRequests[hInternet.nb]=strdup(url);
[368]889  if(argc==4){
890    char *body;
891    body=JSValToChar(cx,&argv[2]);
892    header=JSVAL_TO_OBJECT(argv[3]);
893#ifdef ULINET_DEBUG
894    fprintf(stderr,"URL (%s) \nBODY (%s)\n",url,body);
895#endif
896    if(JS_IsArrayObject(cx,header))
[492]897      setHeader(&hInternet,cx,header);
[368]898#ifdef ULINET_DEBUG
899    fprintf(stderr,"BODY (%s)\n",body);
900#endif
[492]901    InternetOpenUrl(&hInternet,hInternet.waitingRequests[hInternet.nb],body,strlen(body),
902                    INTERNET_FLAG_NO_CACHE_WRITE,0);   
903    processDownloads(&hInternet);
[368]904    free(body);
905  }else{
906    if(argc==3){
907      char *body=JSValToChar(cx,&argv[2]);
[492]908      InternetOpenUrl(&hInternet,hInternet.waitingRequests[hInternet.nb],body,strlen(body),
909                      INTERNET_FLAG_NO_CACHE_WRITE,0);
910      processDownloads(&hInternet);
[368]911      free(body);
[492]912    }else{
913      InternetOpenUrl(&hInternet,hInternet.waitingRequests[hInternet.nb],NULL,0,
914                      INTERNET_FLAG_NO_CACHE_WRITE,0);
915      processDownloads(&hInternet);
[368]916    }
917  }
[492]918  tmpValue=(char*)malloc((hInternet.ihandle[0].nDataLen+1)*sizeof(char));
919  InternetReadFile(hInternet.ihandle[0],(LPVOID)tmpValue,hInternet.ihandle[0].nDataLen,&dwRead);
[368]920#ifdef ULINET_DEBUG
921  fprintf(stderr,"content downloaded (%d) (%s) \n",dwRead,tmpValue);
922#endif
923  if(dwRead==0){
924    JS_SET_RVAL(cx, argv1,STRING_TO_JSVAL(JS_NewStringCopyN(cx,"Unable to access the file.",strlen("Unable to access the file."))));
925    return JS_TRUE;
926  }
927
928#ifdef ULINET_DEBUG
929  fprintf(stderr,"content downloaded (%d) (%s) \n",dwRead,tmpValue);
930#endif
931  JS_SET_RVAL(cx, argv1,STRING_TO_JSVAL(JS_NewStringCopyN(cx,tmpValue,strlen(tmpValue))));
932  free(url);
933  if(argc>=2)
934    free(method);
[492]935  InternetCloseHandle(&hInternet);
[368]936  JS_MaybeGC(cx);
937  return JS_TRUE;
938}
[580]939
940/**
941 * The function used as ZOOUpdateStatus from the JavaScript environment
942 * (ZOO-API).
943 *
944 * @param cx the JavaScript context
945 * @param argc the number of parameters
946 * @param argv1 the parameter values
947 * @return true
[581]948 * @see setHeader,_updateStatus
[580]949 */
950JSBool
951JSUpdateStatus(JSContext *cx, uintN argc, jsval *argv1)
952{
953  jsval *argv = JS_ARGV(cx,argv1);
954  JS_MaybeGC(cx);
955  int istatus=0;
956  char *status=NULL;
957  maps *conf;
958  if(argc>2){
959#ifdef JS_DEBUG
960    fprintf(stderr,"Number of arguments used to call the function : %i",argc);
961#endif
962    return JS_FALSE;
963  }
964  conf=mapsFromJSObject(cx,argv[0]);
965  if(JS_ValueToInt32(cx,argv[1],&istatus)==JS_TRUE){
966    char tmpStatus[4];
967    sprintf(tmpStatus,"%i",istatus);
968    tmpStatus[3]=0;
969    status=strdup(tmpStatus);
970  }
971  if(getMapFromMaps(conf,"lenv","status")!=NULL){
972    if(status!=NULL){
973      setMapInMaps(conf,"lenv","status",status);
974      free(status);
975    }
976    else
977      setMapInMaps(conf,"lenv","status","15");
978    _updateStatus(conf);
979  }
980  freeMaps(&conf);
981  free(conf);
982  JS_MaybeGC(cx);
983  return JS_TRUE;
984}
985
Note: See TracBrowser for help on using the repository browser.

Search

ZOO Sponsors

http://www.zoo-project.org/trac/chrome/site/img/geolabs-logo.pnghttp://www.zoo-project.org/trac/chrome/site/img/neogeo-logo.png http://www.zoo-project.org/trac/chrome/site/img/apptech-logo.png http://www.zoo-project.org/trac/chrome/site/img/3liz-logo.png http://www.zoo-project.org/trac/chrome/site/img/gateway-logo.png

Become a sponsor !

Knowledge partners

http://www.zoo-project.org/trac/chrome/site/img/ocu-logo.png http://www.zoo-project.org/trac/chrome/site/img/gucas-logo.png http://www.zoo-project.org/trac/chrome/site/img/polimi-logo.png http://www.zoo-project.org/trac/chrome/site/img/fem-logo.png http://www.zoo-project.org/trac/chrome/site/img/supsi-logo.png http://www.zoo-project.org/trac/chrome/site/img/cumtb-logo.png

Become a knowledge partner

Related links

http://zoo-project.org/img/ogclogo.png http://zoo-project.org/img/osgeologo.png