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

Last change on this file since 680 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
Line 
1/*
2 * Author : Gérald FENOY
3 *
4 * Copyright (c) 2009-2012 GeoLabs SARL
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
25#include "service_internal_js.h"
26#include "response_print.h"
27
28#ifndef JSCLASS_GLOBAL_FLAGS
29#define JSCLSAS_GLOBAL_FLAGS 0
30#endif
31
32static char dbg[1024];
33
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 */
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]);
50    char *tmp=JS_EncodeString(cx,jsmsg);
51    fprintf(stderr,"[ZOO-API:JS] %s\n",tmp);
52    free(tmp);
53  }
54  JS_MaybeGC(cx);
55 
56  return JS_TRUE;
57}
58
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 */
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]);
80    char *api0=(char*)malloc((strlen(ntmp)+strlen(filename)+2)*sizeof(char));
81    sprintf(api0,"%s/%s",ntmp,filename);
82#ifdef JS_DEBUG
83    fprintf(stderr,"Trying to load %s\n",api0);
84    fflush(stderr);
85#endif
86    JSObject *api_script1=loadZooApiFile(cx,JS_GetGlobalObject(cx),api0);
87    free(api0);
88  }
89  JS_MaybeGC(cx);
90  JS_SET_RVAL(cx, argv1, JSVAL_VOID);
91 
92  return JS_TRUE;
93}
94
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
105 * @return SERVICE_SUCCEEDED or SERVICE_FAILED if the service run, -1
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)
109{
110  /*maps* main=*main_conf;
111  maps* _inputs=*inputs;
112  maps* _outputs=*outputs;*/
113
114  /* The class of the global object. */
115  JSClass global_class= {
116    "global", JSCLASS_GLOBAL_FLAGS,
117    JS_PropertyStub, JS_PropertyStub, JS_PropertyStub, JS_StrictPropertyStub,
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;
131 
132  /* Create a context. */
133  cx = JS_NewContext(rt,8192);
134  if (cx == NULL){
135    return 1;
136  }
137  JS_SetOptions(cx, JSOPTION_VAROBJFIX | JSOPTION_JIT | JSOPTION_METHODJIT);
138  JS_SetVersion(cx, JSVERSION_LATEST);
139  JS_SetErrorReporter(cx, reportError);
140
141  /* Create the global object. */
142  global = JS_NewCompartmentAndGlobalObject(cx, &global_class, NULL);
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  }
149
150  /* Define specific function and global variable to share with JS runtime
151   */
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;
158  if (!JS_DefineFunction(cx, global, "ZOORequest", JSRequest, 4, 0))
159    return 1;
160  if (!JS_DefineFunction(cx, global, "ZOOTranslate", JSTranslate, 4, 0))
161    return 1;
162  if (!JS_DefineFunction(cx, global, "ZOOUpdateStatus", JSUpdateStatus, 2, 0))
163    return 1;
164  if (!JS_DefineFunction(cx, global, "alert", JSAlert, 2, 0))
165    return 1; 
166  if (!JS_DefineFunction(cx, global, "importScripts", JSLoadScripts, 1, 0))
167    return 1;
168
169  /**
170   * Add private context object
171   */
172  void* cxPrivate = request;
173  JS_SetContextPrivate(cx,cxPrivate);
174
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   */
182  char *api0=(char*)malloc((strlen(ntmp)+17)*sizeof(char));
183  sprintf(api0,"%s/ZOO-proj4js.js",ntmp);
184#ifdef JS_DEBUG
185  fprintf(stderr,"Trying to load %s\n",api0);
186#endif
187  JSObject *api_script1=loadZooApiFile(cx,global,api0);
188  free(api0);
189  fflush(stderr);
190
191  char *api1=(char*)malloc((strlen(ntmp)+13)*sizeof(char));
192  sprintf(api1,"%s/ZOO-api.js",ntmp);
193#ifdef JS_DEBUG
194  fprintf(stderr,"Trying to load %s\n",api1);
195#endif
196  JSObject *api_script2=loadZooApiFile(cx,global,api1);
197  free(api1);
198  fflush(stderr);
199
200  /* Your application code here. This may include JSAPI calls
201     to create your own custom JS objects and run scripts. */
202  //maps* out=*outputs;
203  int res=SERVICE_FAILED;
204  //maps* mc=*main_conf;
205  map* tmpm2=getMap(s->content,"serviceProvider");
206
207  char *filename=(char*)malloc(strlen(tmpm1->value)+strlen(tmpm2->value)+strlen(ntmp)+3);
208  sprintf(filename,"%s/%s/%s",ntmp,tmpm1->value,tmpm2->value);
209  filename[strlen(tmpm1->value)+strlen(tmpm2->value)+strlen(ntmp)+2]=0;
210#ifdef JS_DEBUG
211  fprintf(stderr,"FILENAME %s\n",filename);
212#endif
213  struct stat file_status;
214  stat(filename, &file_status);
215  //char *source=(char*)malloc(file_status.st_size);
216  //uint16 lineno;
217  jsval rval;
218  JSBool ok ;
219  JSObject *script = JS_CompileFile(cx, global, filename);
220  if(script!=NULL){
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);
226    free(filename);
227    errorException(*main_conf,tmp1,"NoApplicableCode",NULL);
228    JS_MaybeGC(cx);
229    JS_DestroyContext(cx);
230    JS_DestroyRuntime(rt);
231    JS_ShutDown();
232    return -1;
233  }
234 
235
236  /* Call a function in obj's scope. */
237  jsval argv[3];
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;
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;
256  if (ok==JS_TRUE && JSVAL_IS_OBJECT(rval1)==JS_TRUE) {
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];
265    if(strlen(dbg)==0)
266      sprintf(dbg,"No result was found after the function call");
267    sprintf(tmp1,"Unable to run %s from the JavaScript file %s : \n %s",s->name,filename,dbg);
268#ifdef JS_DEBUG
269    fprintf(stderr,"%s",tmp1);
270#endif
271    errorException(*main_conf,tmp1,"NoApplicableCode",NULL);
272    free(filename);
273    JS_MaybeGC(cx);
274    JS_DestroyContext(cx);
275    JS_DestroyRuntime(rt);
276    JS_ShutDown();
277    // Should return -1 here but the unallocation won't work from zoo_service_loader.c line 1847
278    return -1;
279  }
280
281  //jsval t=OBJECT_TO_JSVAL(d);
282  if(JS_IsArrayObject(cx,d)){
283#ifdef JS_DEBUG
284    fprintf(stderr,"An array was returned !\n");
285#endif
286    jsuint       len;
287    if((JS_GetArrayLength(cx, d, &len)==JS_FALSE)){
288#ifdef JS_DEBUG
289      fprintf(stderr,"outputs array is empty\n");
290#endif
291    }
292    jsval tmp1;
293    JSBool hasResult=JS_GetElement(cx,d,0,&tmp1);
294    res=JSVAL_TO_INT(tmp1);
295#ifdef JS_DEBUG
296    fprintf(stderr," * %d * \n",res);
297#endif
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      }
314    }
315
316  }
317  else{
318#ifdef JS_DEBUG
319    fprintf(stderr,"The service didn't return an array !\n");
320#endif
321    /**
322     * Extract result
323     */
324    jsval tmp1;
325    JSBool hasResult=JS_GetProperty(cx,d,"result",&tmp1);
326    res=JSVAL_TO_INT(tmp1);
327
328#ifdef JS_DEBUG
329    fprintf(stderr," * %d * \n",res);
330#endif
331    /**
332     * Extract outputs when available.
333     */
334    jsval tmp2;
335    JSBool hasElement=JS_GetProperty(cx,d,"outputs",&tmp2);
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);
342#ifdef JS_DEBUG
343    if(JSVAL_IS_VOID(tmp2))
344      fprintf(stderr,"No outputs property returned\n");
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);
352#endif
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
366#ifdef JS_DEBUG
367    dumpMaps(*outputs);
368#endif
369  }
370  /* Cleanup. */
371  JS_MaybeGC(cx);
372  JS_DestroyContext(cx);
373  JS_DestroyRuntime(rt);
374  JS_ShutDown();
375  free(filename);
376#ifdef JS_DEBUG
377  fprintf(stderr,"Returned value %d\n",res);
378#endif
379  return res;
380}
381
382/**
383 * Load a JavaScript file
384 *
385 * @param cx the JavaScript context
386 * @param global the global JavaScript object (not used)
387 * @param filename the file name to load
388 * @return a JavaScript Object on success, NULL if an errro occured
389 */
390JSObject * loadZooApiFile(JSContext *cx,JSObject  *global, char* filename){
391  struct stat api_status;
392  int s=stat(filename, &api_status);
393  if(s==0){
394    jsval rval;
395    JSObject *script = JS_CompileFile(cx, JS_GetGlobalObject(cx), filename);
396    if(script!=NULL){
397      (void)JS_ExecuteScript(cx, JS_GetGlobalObject(cx), script, &rval);
398#ifdef JS_DEBUG
399      fprintf(stderr,"**************\n%s correctly loaded\n**************\n",filename);
400#endif
401      return script;
402    }
403#ifdef JS_DEBUG
404    else
405      fprintf(stderr,"\n**************\nUnable to run %s\n**************\n",filename);
406#endif
407  }
408#ifdef JS_DEBUG
409  else
410    fprintf(stderr,"\n**************\nUnable to load %s\n**************\n",filename);
411#endif
412  return NULL;
413}
414
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 */
422JSObject* JSObject_FromMaps(JSContext *cx,maps* t){
423  JSObject* res=JS_NewObject(cx, NULL, NULL, NULL);
424  if(res==NULL)
425    fprintf(stderr,"Array Object is NULL!\n");
426  maps* tmp=t;
427  while(tmp!=NULL){
428    JSObject *pval=JSObject_FromMap(cx,tmp->content);
429    jsval pvalj=OBJECT_TO_JSVAL(pval);
430    JS_SetProperty(cx, res, tmp->name, &pvalj);
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
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 */
446JSObject* JSObject_FromMap(JSContext *cx,map* t){
447  JSObject* res=JS_NewObject(cx, NULL, NULL, NULL);
448  map* tmpm=t;
449  map* isArray=getMap(t,"isArray");
450  map* isBinary=getMap(t,"size");
451  map* tmap=getMapType(t);
452#ifdef JS_DEBUG
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);
457#endif
458  while(isArray==NULL && tmpm!=NULL){
459    jsval jsstr;
460    if((isBinary!=NULL && strncasecmp(tmpm->name,"value",5)==0))
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);
465#ifdef JS_DEBUG
466    fprintf(stderr,"[JS] %s => %s\n",tmpm->name,tmpm->value);
467#endif
468    tmpm=tmpm->next;
469  }
470  if(isArray!=NULL){
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  }
494  return res;
495}
496
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 */
504maps* mapsFromJSObject(JSContext *cx,jsval t){
505  maps *res=NULL;
506  maps *tres=NULL;
507  jsint oi=0;
508  JSObject* tt=JSVAL_TO_OBJECT(t);
509  if(JS_IsArrayObject(cx,tt)){
510#ifdef JS_DEBUG
511    fprintf(stderr,"Is finally an array !\n");
512#endif
513  }
514  else{
515#ifdef JS_DEBUG
516    fprintf(stderr,"Is not an array !\n");
517#endif
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);
530        char *tmp;
531        JSString *jsmsg;
532        size_t len1;
533        jsmsg = JS_ValueToString(cx,vp);
534        len1 = JS_GetStringLength(jsmsg);
535       
536        tmp=JS_EncodeString(cx,jsmsg);
537        tres=(maps*)malloc(MAPS_SIZE);
538        tres->name=zStrdup(tmp);
539        tres->content=NULL;
540        tres->next=NULL;
541
542        jsval nvp=JSVAL_NULL;
543        if((JS_GetProperty(cx, tt, tmp, &nvp)==JS_FALSE)){
544#ifdef JS_DEBUG
545          fprintf(stderr,"Enumerate id : %d => %s => No more value\n",oi,tmp);
546#endif
547        }
548        free(tmp);
549        JSObject *nvp1=JSVAL_TO_OBJECT(JSVAL_NULL);
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;
563               
564      }
565      JS_DestroyIdArray(cx,idp);
566    }
567  }
568
569  jsuint len;
570  JSBool hasLen=JS_GetArrayLength(cx, tt, &len);
571#ifdef JS_DEBUG
572  if(hasLen==JS_FALSE){
573    fprintf(stderr,"outputs array is empty\n");
574  }
575  fprintf(stderr,"outputs array length : %d\n",len);
576#endif
577  for(oi=0;hasLen && oi < len;oi++){
578#ifdef JS_DEBUG
579    fprintf(stderr,"outputs array length : %d step %d \n",len,oi);
580#endif
581    jsval tmp1;
582    JSBool hasElement=JS_GetElement(cx,tt,oi,&tmp1);
583    JSObject *otmp1=JSVAL_TO_OBJECT(tmp1);
584    JSIdArray *idp=JS_Enumerate(cx,otmp1);
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
591      tres=(maps*)malloc(MAPS_SIZE);
592      tres->name=NULL;
593      tres->content=NULL;
594      tres->next=NULL;
595
596      for (index=0,argNum=idp->length;index<argNum;index++) { 
597        jsval id = idp->vector[index];
598        jsval vp;
599        JS_IdToValue(cx,id,&vp);
600        char *tmp;
601        JSString *jsmsg;
602        size_t len1;
603        jsmsg = JS_ValueToString(cx,vp);
604        len1 = JS_GetStringLength(jsmsg);
605        tmp=JS_EncodeString(cx,jsmsg);
606#ifdef JS_DEBUG
607        fprintf(stderr,"Enumerate id : %d => %s\n",oi,tmp);
608#endif
609        jsval nvp=JSVAL_NULL;
610        if((JS_GetProperty(cx, JSVAL_TO_OBJECT(tmp1), tmp, &nvp)==JS_FALSE)){
611#ifdef JS_DEBUG
612          fprintf(stderr,"Enumerate id : %d => %s => No more value\n",oi,tmp);
613#endif
614        }
615        free(tmp);
616        if(JSVAL_IS_OBJECT(nvp)){
617#ifdef JS_DEBUG
618          fprintf(stderr,"JSVAL NVP IS OBJECT\n");
619#endif
620        }
621
622        JSObject *nvp1=JSVAL_TO_OBJECT(JSVAL_NULL);
623        JS_ValueToObject(cx,nvp,&nvp1);
624        jsval nvp1j=OBJECT_TO_JSVAL(nvp1);
625        if(JSVAL_IS_OBJECT(nvp1j)){
626          JSString *jsmsg1;
627          char *tmp1, *tmp2;
628          JSObject *nvp2=JSVAL_TO_OBJECT(JSVAL_NULL);
629          jsmsg1 = JS_ValueToString(cx,nvp1j);
630          len1 = JS_GetStringLength(jsmsg1);
631          tmp1=JS_EncodeString(cx,jsmsg1);
632          tmp2=JS_EncodeString(cx,jsmsg);
633#ifdef JS_DEBUG
634          fprintf(stderr,"JSVAL NVP1J IS OBJECT %s = %s\n",JS_EncodeString(cx,jsmsg),tmp1);
635#endif
636          if(strcasecmp(tmp1,"[object Object]")==0){
637            tres->name=zStrdup(tmp2);
638            tres->content=mapFromJSObject(cx,nvp1j);
639          }
640          else
641            if(strcasecmp(tmp2,"name")==0){
642              tres->name=zStrdup(tmp1);
643            }
644            else{
645              if(tres->content==NULL)
646                tres->content=createMap(tmp2,tmp1);
647              else
648                addToMap(tres->content,tmp2,tmp1);
649            }
650          free(tmp1);
651          free(tmp2);
652        }
653#ifdef JS_DEBUG
654        else
655          fprintf(stderr,"JSVAL NVP1J IS NOT OBJECT !!\n");
656#endif
657      }
658#ifdef JS_DEBUG
659      dumpMaps(tres);
660#endif
661      if(res==NULL)
662        res=dupMaps(&tres);
663      else
664        addMapsToMaps(&res,tres);
665      freeMaps(&tres);
666      free(tres);
667      tres=NULL;
668      JS_DestroyIdArray(cx,idp);
669    }
670  }
671#ifdef JS_DEBUG
672  dumpMaps(res);
673#endif
674  return res;
675}
676
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 */
684map* mapFromJSObject(JSContext *cx,jsval t){
685  map *res=NULL;
686  JSIdArray *idp=JS_Enumerate(cx,JSVAL_TO_OBJECT(t));
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++) { 
697      jsval id = idp->vector[index];
698      jsval vp;
699      JS_IdToValue(cx,id,&vp);
700      char *tmp, *tmp1;
701      JSString *jsmsg,*jsmsg1;
702      size_t len,len1;
703      jsmsg = JS_ValueToString(cx,vp);
704      len = JS_GetStringLength(jsmsg);
705      jsval nvp;
706      tmp=JS_EncodeString(cx,jsmsg);
707      JS_GetProperty(cx, JSVAL_TO_OBJECT(t), tmp, &nvp);
708      jsmsg1 = JS_ValueToString(cx,nvp);
709      len1 = JS_GetStringLength(jsmsg1);
710      tmp1=JS_EncodeString(cx,jsmsg1);
711#ifdef JS_DEBUG
712      fprintf(stderr,"Enumerate id : %d [ %s => %s ]\n",index,tmp,tmp1);
713#endif
714      if(res!=NULL){
715#ifdef JS_DEBUG
716        fprintf(stderr,"%s - %s\n",tmp,tmp1);
717#endif
718        addToMap(res,tmp,tmp1);
719      }
720      else{
721        res=createMap(tmp,tmp1);
722        res->next=NULL;
723      }
724      free(tmp);
725      free(tmp1);
726#ifdef JS_DEBUG
727      dumpMap(res);
728#endif
729    }
730    JS_DestroyIdArray(cx,idp);
731  }
732#ifdef JS_DEBUG
733  dumpMap(res);
734#endif
735  return res;
736}
737
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 */
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
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 */
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
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 */
800HINTERNET setHeader(HINTERNET* handle,JSContext *cx,JSObject *header){
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
815    handle->ihandle[handle->nb].header=NULL;
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
821      curl_easy_setopt(handle->ihandle[handle->nb].handle,CURLOPT_VERBOSE,1);
822      fprintf(stderr,"Element of array n° %d, value : %s\n",i,tmp1);
823#endif
824      handle->ihandle[handle->nb].header=curl_slist_append(handle->ihandle[handle->nb].header, tmp1);
825      free(tmp1);
826    }
827  }
828  else{
829    fprintf(stderr,"not an array !!!!!!!\n");
830  }
831  return *handle;
832}
833
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 */
844JSBool
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
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 */
864JSBool
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{
885    method=zStrdup("GET");
886    url=JSValToChar(cx,argv);
887  }
888  hInternet.waitingRequests[hInternet.nb]=strdup(url);
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))
897      setHeader(&hInternet,cx,header);
898#ifdef ULINET_DEBUG
899    fprintf(stderr,"BODY (%s)\n",body);
900#endif
901    InternetOpenUrl(&hInternet,hInternet.waitingRequests[hInternet.nb],body,strlen(body),
902                    INTERNET_FLAG_NO_CACHE_WRITE,0);   
903    processDownloads(&hInternet);
904    free(body);
905  }else{
906    if(argc==3){
907      char *body=JSValToChar(cx,&argv[2]);
908      InternetOpenUrl(&hInternet,hInternet.waitingRequests[hInternet.nb],body,strlen(body),
909                      INTERNET_FLAG_NO_CACHE_WRITE,0);
910      processDownloads(&hInternet);
911      free(body);
912    }else{
913      InternetOpenUrl(&hInternet,hInternet.waitingRequests[hInternet.nb],NULL,0,
914                      INTERNET_FLAG_NO_CACHE_WRITE,0);
915      processDownloads(&hInternet);
916    }
917  }
918  tmpValue=(char*)malloc((hInternet.ihandle[0].nDataLen+1)*sizeof(char));
919  InternetReadFile(hInternet.ihandle[0],(LPVOID)tmpValue,hInternet.ihandle[0].nDataLen,&dwRead);
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);
935  InternetCloseHandle(&hInternet);
936  JS_MaybeGC(cx);
937  return JS_TRUE;
938}
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
948 * @see setHeader,_updateStatus
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