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

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

Code cleanup, description of some functon included in the code, addition of support for multiple error output, beter internal gesture of MapArray?.

  • Property svn:eol-style set to native
  • Property svn:mime-type set to text/x-csrc
File size: 22.4 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.h"
26
27#ifndef JSCLASS_GLOBAL_FLAGS
28#define JSCLSAS_GLOBAL_FLAGS 0
29#endif
30
31static char dbg[1024];
32
33JSBool
34JSAlert(JSContext *cx, uintN argc, jsval *argv1)
35{
36  jsval *argv = JS_ARGV(cx,argv1);
37  int i=0;
38  JS_MaybeGC(cx);
39  for(i=0;i<argc;i++){
40    JSString* jsmsg = JS_ValueToString(cx,argv[i]);
41    char *tmp=JS_EncodeString(cx,jsmsg);
42    fprintf(stderr,"[ZOO-API:JS] %s\n",tmp);
43    free(tmp);
44  }
45  JS_MaybeGC(cx);
46 
47  return JS_TRUE;
48}
49
50JSBool
51JSLoadScripts(JSContext *cx, uintN argc, jsval *argv1)
52{
53  //map* request = JS_GetContextPrivate(cx);
54  //map* tmpm1=getMap(request,"metapath");
55  JS_MaybeGC(cx);
56
57  char ntmp[1024];
58  getcwd(ntmp,1024);
59
60  jsval *argv = JS_ARGV(cx,argv1);
61  int i=0;
62  JS_MaybeGC(cx);
63  for(i=0;i<argc;i++){
64    JSString* jsmsg = JS_ValueToString(cx,argv[i]);
65    char *filename = JSValToChar(cx,&argv[i]);
66    char *api0=(char*)malloc((strlen(ntmp)+strlen(filename)+2)*sizeof(char));
67    sprintf(api0,"%s/%s",ntmp,filename);
68#ifdef JS_DEBUG
69    fprintf(stderr,"Trying to load %s\n",api0);
70    fflush(stderr);
71#endif
72    JSObject *api_script1=loadZooApiFile(cx,JS_GetGlobalObject(cx),api0);
73    free(api0);
74  }
75  JS_MaybeGC(cx);
76  JS_SET_RVAL(cx, argv1, JSVAL_VOID);
77 
78  return JS_TRUE;
79}
80
81
82int zoo_js_support(maps** main_conf,map* request,service* s,
83                   maps **inputs,maps **outputs)
84{
85  maps* main=*main_conf;
86  maps* _inputs=*inputs;
87  maps* _outputs=*outputs;
88
89  /* The class of the global object. */
90  JSClass global_class= {
91    "global", JSCLASS_GLOBAL_FLAGS,
92    JS_PropertyStub, JS_PropertyStub, JS_PropertyStub, JS_StrictPropertyStub,
93    JS_EnumerateStub, JS_ResolveStub, JS_ConvertStub, JS_FinalizeStub,
94    JSCLASS_NO_OPTIONAL_MEMBERS
95  };
96
97  /* JS variables. */
98  JSRuntime *rt;
99  JSContext *cx;
100  JSObject  *global;
101
102  /* Create a JS runtime. */
103  rt = JS_NewRuntime(8L * 1024L * 1024L);
104  if (rt == NULL)
105    return 1;
106 
107  /* Create a context. */
108  cx = JS_NewContext(rt,8192);
109  if (cx == NULL){
110    return 1;
111  }
112  JS_SetOptions(cx, JSOPTION_VAROBJFIX | JSOPTION_JIT | JSOPTION_METHODJIT);
113  JS_SetVersion(cx, JSVERSION_LATEST);
114  JS_SetErrorReporter(cx, reportError);
115
116  /* Create the global object. */
117  global = JS_NewCompartmentAndGlobalObject(cx, &global_class, NULL);
118
119  /* Populate the global object with the standard globals,
120     like Object and Array. */
121  if (!JS_InitStandardClasses(cx, global)){
122    return 1;
123  }
124
125  /* Define specific function and global variable to share with JS runtime
126   */
127  jsval tmp=INT_TO_JSVAL(3);
128  if (!JS_SetProperty(cx, global, "SERVICE_SUCCEEDED", &tmp))
129    return 1;
130  tmp=INT_TO_JSVAL(4);
131  if (!JS_SetProperty(cx, global, "SERVICE_FAILED", &tmp))
132    return 1;
133  if (!JS_DefineFunction(cx, global, "ZOORequest", JSRequest, 4, 0))
134    return 1;
135  if (!JS_DefineFunction(cx, global, "ZOOTranslate", JSTranslate, 4, 0))
136    return 1;
137  if (!JS_DefineFunction(cx, global, "ZOOUpdateStatus", JSUpdateStatus, 2, 0))
138    return 1;
139  if (!JS_DefineFunction(cx, global, "alert", JSAlert, 2, 0))
140    return 1; 
141  if (!JS_DefineFunction(cx, global, "importScripts", JSLoadScripts, 1, 0))
142    return 1;
143
144  /**
145   * Add private context object
146   */
147  void* cxPrivate = request;
148  JS_SetContextPrivate(cx,cxPrivate);
149
150  map* tmpm1=getMap(request,"metapath");
151  char ntmp[1024];
152  getcwd(ntmp,1024);
153
154  /**
155   * Load the first part of the ZOO-API
156   */
157  char *api0=(char*)malloc((strlen(ntmp)+17)*sizeof(char));
158  sprintf(api0,"%s/ZOO-proj4js.js",ntmp);
159#ifdef JS_DEBUG
160  fprintf(stderr,"Trying to load %s\n",api0);
161#endif
162  JSObject *api_script1=loadZooApiFile(cx,global,api0);
163  free(api0);
164  fflush(stderr);
165
166  char *api1=(char*)malloc((strlen(ntmp)+13)*sizeof(char));
167  sprintf(api1,"%s/ZOO-api.js",ntmp);
168#ifdef JS_DEBUG
169  fprintf(stderr,"Trying to load %s\n",api1);
170#endif
171  JSObject *api_script2=loadZooApiFile(cx,global,api1);
172  free(api1);
173  fflush(stderr);
174
175  /* Your application code here. This may include JSAPI calls
176     to create your own custom JS objects and run scripts. */
177  maps* out=*outputs;
178  int res=SERVICE_FAILED;
179  maps* mc=*main_conf;
180  map* tmpm2=getMap(s->content,"serviceProvider");
181
182  char *filename=(char*)malloc(strlen(tmpm1->value)+strlen(tmpm2->value)+strlen(ntmp)+3);
183  sprintf(filename,"%s/%s/%s",ntmp,tmpm1->value,tmpm2->value);
184  filename[strlen(tmpm1->value)+strlen(tmpm2->value)+strlen(ntmp)+2]=0;
185#ifdef JS_DEBUG
186  fprintf(stderr,"FILENAME %s\n",filename);
187#endif
188  struct stat file_status;
189  stat(filename, &file_status);
190  //char *source=(char*)malloc(file_status.st_size);
191  uint16 lineno;
192  jsval rval;
193  JSBool ok ;
194  JSObject *script = JS_CompileFile(cx, global, filename);
195  if(script!=NULL){
196    (void)JS_ExecuteScript(cx, global, script, &rval);
197  }
198  else{
199    char tmp1[1024];
200    sprintf(tmp1,"Unable to load JavaScript file %s",filename);
201    free(filename);
202    errorException(*main_conf,tmp1,"NoApplicableCode",NULL);
203    JS_MaybeGC(cx);
204    JS_DestroyContext(cx);
205    JS_DestroyRuntime(rt);
206    JS_ShutDown();
207    return -1;
208  }
209 
210
211  /* Call a function in obj's scope. */
212  jsval argv[3];
213  JSObject *jsargv1=JSObject_FromMaps(cx,*main_conf);
214  argv[0] = OBJECT_TO_JSVAL(jsargv1);
215  JSObject *jsargv2=JSObject_FromMaps(cx,*inputs);
216  argv[1] = OBJECT_TO_JSVAL(jsargv2);
217  JSObject *jsargv3=JSObject_FromMaps(cx,*outputs);
218  argv[2] = OBJECT_TO_JSVAL(jsargv3);
219  jsval rval1=JSVAL_NULL;
220#ifdef JS_DEBUG
221  fprintf(stderr, "object %p\n", (void *) argv[2]);
222#endif
223
224  ok = JS_CallFunctionName(cx, global, s->name, 3, argv, &rval1);
225
226#ifdef JS_DEBUG
227  fprintf(stderr, "object %p\n", (void *) argv[2]);
228#endif
229
230  JSObject *d;
231  if (ok==JS_TRUE && JSVAL_IS_OBJECT(rval1)==JS_TRUE) {
232#ifdef JS_DEBUG
233    fprintf(stderr,"Function run sucessfully !\n");
234#endif
235    /* Should get a number back from the service function call. */
236    ok = JS_ValueToObject(cx, rval1, &d);
237  }else{
238    /* Unable to run JS function */
239    char tmp1[1024];
240    if(strlen(dbg)==0)
241      sprintf(dbg,"No result was found after the function call");
242    sprintf(tmp1,"Unable to run %s from the JavaScript file %s : \n %s",s->name,filename,dbg);
243#ifdef JS_DEBUG
244    fprintf(stderr,"%s",tmp1);
245#endif
246    errorException(*main_conf,tmp1,"NoApplicableCode",NULL);
247    free(filename);
248    JS_MaybeGC(cx);
249    JS_DestroyContext(cx);
250    JS_DestroyRuntime(rt);
251    JS_ShutDown();
252    // Should return -1 here but the unallocation won't work from zoo_service_loader.c line 1847
253    return -1;
254  }
255
256  jsval t=OBJECT_TO_JSVAL(d);
257  if(JS_IsArrayObject(cx,d)){
258#ifdef JS_DEBUG
259    fprintf(stderr,"An array was returned !\n");
260#endif
261    jsuint       len;
262    if((JS_GetArrayLength(cx, d, &len)==JS_FALSE)){
263#ifdef JS_DEBUG
264      fprintf(stderr,"outputs array is empty\n");
265#endif
266    }
267    jsval tmp1;
268    JSBool hasResult=JS_GetElement(cx,d,0,&tmp1);
269    res=JSVAL_TO_INT(tmp1);
270#ifdef JS_DEBUG
271    fprintf(stderr," * %d * \n",res);
272#endif
273    if(res==SERVICE_SUCCEEDED){
274      jsval tmp2;
275      JSBool hasElement=JS_GetElement(cx,d,1,&tmp2);
276      if(hasElement==JS_TRUE){
277        freeMaps(outputs);
278        free(*outputs);
279        *outputs=mapsFromJSObject(cx,tmp2);
280      }
281    }else{
282      jsval tmp3;
283      JSBool hasConf=JS_GetElement(cx,d,1,&tmp3);
284      if(hasConf==JS_TRUE){
285        freeMaps(main_conf);
286        free(*main_conf);
287        *main_conf=mapsFromJSObject(cx,tmp3);
288      }
289    }
290
291  }
292  else{
293#ifdef JS_DEBUG
294    fprintf(stderr,"The service didn't return an array !\n");
295#endif
296    /**
297     * Extract result
298     */
299    jsval tmp1;
300    JSBool hasResult=JS_GetProperty(cx,d,"result",&tmp1);
301    res=JSVAL_TO_INT(tmp1);
302
303#ifdef JS_DEBUG
304    fprintf(stderr," * %d * \n",res);
305#endif
306    /**
307     * Extract outputs when available.
308     */
309    jsval tmp2;
310    JSBool hasElement=JS_GetProperty(cx,d,"outputs",&tmp2);
311    if(!JSVAL_IS_VOID(tmp2) && hasElement==JS_TRUE){
312      freeMaps(outputs);
313      free(*outputs);   
314      *outputs=mapsFromJSObject(cx,tmp2);
315    }
316    JS_MaybeGC(cx);
317#ifdef JS_DEBUG
318    if(JSVAL_IS_VOID(tmp2))
319      fprintf(stderr,"No outputs property returned\n");
320    else{
321      if(JS_IsArrayObject(cx,JSVAL_TO_OBJECT(tmp2)))
322        fprintf(stderr,"outputs is an array as expected\n");
323      else
324        fprintf(stderr,"outputs is not an array as expected\n");
325    }
326    JS_MaybeGC(cx);
327#endif
328
329    /**
330     * Extract conf when available.
331     */
332    jsval tmp3;
333    JSBool hasConf=JS_GetProperty(cx,d,"conf",&tmp3);
334    if(!JSVAL_IS_VOID(tmp3) && hasConf==JS_TRUE){
335      freeMaps(main_conf);
336      free(*main_conf);
337      *main_conf=mapsFromJSObject(cx,tmp3);
338    }
339    JS_MaybeGC(cx);
340
341#ifdef JS_DEBUG
342    dumpMaps(*outputs);
343#endif
344  }
345  /* Cleanup. */
346  JS_MaybeGC(cx);
347  JS_DestroyContext(cx);
348  JS_DestroyRuntime(rt);
349  JS_ShutDown();
350  free(filename);
351#ifdef JS_DEBUG
352  fprintf(stderr,"Returned value %d\n",res);
353#endif
354  return res;
355}
356
357JSObject * loadZooApiFile(JSContext *cx,JSObject  *global, char* filename){
358  struct stat api_status;
359  int s=stat(filename, &api_status);
360  if(s==0){
361    jsval rval;
362    JSBool ok ;
363    JSObject *script = JS_CompileFile(cx, JS_GetGlobalObject(cx), filename);
364    if(script!=NULL){
365      (void)JS_ExecuteScript(cx, JS_GetGlobalObject(cx), script, &rval);
366#ifdef JS_DEBUG
367      fprintf(stderr,"**************\n%s correctly loaded\n**************\n",filename);
368#endif
369      return script;
370    }
371#ifdef JS_DEBUG
372    else
373      fprintf(stderr,"\n**************\nUnable to run %s\n**************\n",filename);
374#endif
375  }
376#ifdef JS_DEBUG
377  else
378    fprintf(stderr,"\n**************\nUnable to load %s\n**************\n",filename);
379#endif
380  return NULL;
381}
382
383JSObject* JSObject_FromMaps(JSContext *cx,maps* t){
384
385  JSObject* res=JS_NewObject(cx, NULL, NULL, NULL);
386  //JSObject *res = JS_NewArrayObject(cx, 0, NULL);
387  if(res==NULL)
388    fprintf(stderr,"Array Object is NULL!\n");
389  maps* tmp=t;
390  while(tmp!=NULL){
391    jsuint len;
392    JSObject* res1=JS_NewObject(cx, NULL, NULL, NULL);
393    JSObject *pval=JSObject_FromMap(cx,tmp->content);
394    jsval pvalj=OBJECT_TO_JSVAL(pval);
395    JS_SetProperty(cx, res, tmp->name, &pvalj);
396#ifdef JS_DEBUG
397    fprintf(stderr,"Length of the Array %d, element : %s added \n",len,tmp->name);
398#endif
399    tmp=tmp->next;
400  } 
401  return res;
402}
403
404JSObject* JSObject_FromMap(JSContext *cx,map* t){
405  JSObject* res=JS_NewObject(cx, NULL, NULL, NULL);
406  jsval resf =  OBJECT_TO_JSVAL(res);
407  map* tmpm=t;
408  map* isArray=getMap(t,"isArray");
409  map* isBinary=getMap(t,"size");
410  map* tmap=getMapType(t);
411#ifdef JS_DEBUG
412  if(tmap==NULL)
413    fprintf(stderr,"tmap is null !\n");
414  else
415    fprintf(stderr,"tmap is not null ! (%s = %s)\n",tmap->name,tmap->value);
416#endif
417  while(tmpm!=NULL){
418    jsval jsstr;
419    if((isArray==NULL && isBinary!=NULL && strncasecmp(tmpm->name,"value",5)==0))
420      jsstr = STRING_TO_JSVAL(JS_NewStringCopyN(cx,tmpm->value,atoi(isBinary->value)));
421    else
422      jsstr = STRING_TO_JSVAL(JS_NewStringCopyN(cx,tmpm->value,strlen(tmpm->value)));
423    JS_SetProperty(cx, res, tmpm->name,&jsstr);
424#ifdef JS_DEBUG
425    fprintf(stderr,"[JS] %s => %s\n",tmpm->name,tmpm->value);
426#endif
427    tmpm=tmpm->next;
428  }
429  if(isArray!=NULL){
430    map* len=getMap(t,"length");
431    int cnt=atoi(len->value);
432    JSObject* values=JS_NewArrayObject( cx, cnt, NULL );
433    JSObject* mvalues=JS_NewArrayObject( cx, cnt, NULL );
434    map *tmpm1,*tmpm2;
435    int i=0;
436    for(i=0;i<cnt;i++){
437      tmpm1=getMapArray(t,"value",i);
438      tmpm2=getMapArray(t,tmap->name,i);
439      if(tmpm1!=NULL){
440        jsval jsstr = STRING_TO_JSVAL(JS_NewStringCopyN(cx,tmpm1->value,strlen(tmpm1->value)));
441        JS_SetElement( cx, values, i, &jsstr );
442      }
443      if(tmpm2!=NULL){
444        jsval jsstr = STRING_TO_JSVAL(JS_NewStringCopyN(cx,tmpm2->value,strlen(tmpm2->value)));
445        JS_SetElement( cx, mvalues, i, &jsstr );
446      }
447    }
448    jsval jvalues=OBJECT_TO_JSVAL(values);
449    jsval jmvalues=OBJECT_TO_JSVAL(mvalues);
450    JS_SetProperty(cx, res,"value",&jvalues);
451    JS_SetProperty(cx, res,tmap->name,&jmvalues);
452  }
453  return res;
454}
455
456maps* mapsFromJSObject(JSContext *cx,jsval t){
457  maps *res=NULL;
458  maps *tres=NULL;
459  jsint oi=0;
460  JSObject* tt=JSVAL_TO_OBJECT(t);
461  if(JS_IsArrayObject(cx,tt)){
462#ifdef JS_DEBUG
463    fprintf(stderr,"Is finally an array !\n");
464#endif
465  }
466  else{
467#ifdef JS_DEBUG
468    fprintf(stderr,"Is not an array !\n");
469#endif
470    JSIdArray *idp=JS_Enumerate(cx,tt);
471    if(idp!=NULL) {
472      int index;
473      jsdouble argNum;
474#ifdef JS_DEBUG
475      fprintf(stderr,"Properties length :  %d \n",idp->length);
476#endif
477     
478      for (index=0,argNum=idp->length;index<argNum;index++) { 
479        jsval id = idp->vector[index];
480        jsval vp;
481        JSString* str; 
482        JS_IdToValue(cx,id,&vp);
483        char *c, *tmp;
484        JSString *jsmsg;
485        size_t len1;
486        jsmsg = JS_ValueToString(cx,vp);
487        len1 = JS_GetStringLength(jsmsg);
488       
489        tmp=JS_EncodeString(cx,jsmsg);
490        tres=(maps*)malloc(MAPS_SIZE);
491        tres->name=zStrdup(tmp);
492        tres->content=NULL;
493        tres->next=NULL;
494
495        jsval nvp=JSVAL_NULL;
496        if((JS_GetProperty(cx, tt, tmp, &nvp)==JS_FALSE)){
497#ifdef JS_DEBUG
498          fprintf(stderr,"Enumerate id : %d => %s => No more value\n",oi,tmp);
499#endif
500        }
501        free(tmp);
502        JSObject *nvp1=JSVAL_TO_OBJECT(JSVAL_NULL);
503        JS_ValueToObject(cx,nvp,&nvp1);
504        jsval nvp1j=OBJECT_TO_JSVAL(nvp1);
505        if(JSVAL_IS_OBJECT(nvp1j)){
506          tres->content=mapFromJSObject(cx,nvp1j);
507        }
508
509        if(res==NULL)
510          res=dupMaps(&tres);
511        else
512          addMapsToMaps(&res,tres);
513        freeMaps(&tres);
514        free(tres);
515        tres=NULL;
516               
517      }
518      JS_DestroyIdArray(cx,idp);
519    }
520  }
521
522  jsuint len;
523  JSBool hasLen=JS_GetArrayLength(cx, tt, &len);
524#ifdef JS_DEBUG
525  if(hasLen==JS_FALSE){
526    fprintf(stderr,"outputs array is empty\n");
527  }
528  fprintf(stderr,"outputs array length : %d\n",len);
529#endif
530  for(oi=0;oi < len;oi++){
531#ifdef JS_DEBUG
532    fprintf(stderr,"outputs array length : %d step %d \n",len,oi);
533#endif
534    jsval tmp1;
535    JSBool hasElement=JS_GetElement(cx,tt,oi,&tmp1);
536    JSObject *otmp1=JSVAL_TO_OBJECT(tmp1);
537    JSIdArray *idp=JS_Enumerate(cx,otmp1);
538    if(idp!=NULL) {
539      int index;
540      jsdouble argNum;
541#ifdef JS_DEBUG
542      fprintf(stderr,"Properties length :  %d \n",idp->length);
543#endif
544      tres=(maps*)malloc(MAPS_SIZE);
545      tres->name=NULL;
546      tres->content=NULL;
547      tres->next=NULL;
548
549      for (index=0,argNum=idp->length;index<argNum;index++) { 
550        jsval id = idp->vector[index];
551        jsval vp;
552        JSString* str; 
553        JS_IdToValue(cx,id,&vp);
554        char *c, *tmp;
555        JSString *jsmsg;
556        size_t len1;
557        jsmsg = JS_ValueToString(cx,vp);
558        len1 = JS_GetStringLength(jsmsg);
559        tmp=JS_EncodeString(cx,jsmsg);
560#ifdef JS_DEBUG
561        fprintf(stderr,"Enumerate id : %d => %s\n",oi,tmp);
562#endif
563        jsval nvp=JSVAL_NULL;
564        if((JS_GetProperty(cx, JSVAL_TO_OBJECT(tmp1), tmp, &nvp)==JS_FALSE)){
565#ifdef JS_DEBUG
566          fprintf(stderr,"Enumerate id : %d => %s => No more value\n",oi,tmp);
567#endif
568        }
569        free(tmp);
570        if(JSVAL_IS_OBJECT(nvp)){
571#ifdef JS_DEBUG
572          fprintf(stderr,"JSVAL NVP IS OBJECT\n");
573#endif
574        }
575
576        JSObject *nvp1=JSVAL_TO_OBJECT(JSVAL_NULL);
577        JS_ValueToObject(cx,nvp,&nvp1);
578        jsval nvp1j=OBJECT_TO_JSVAL(nvp1);
579        if(JSVAL_IS_OBJECT(nvp1j)){
580          JSString *jsmsg1;
581          char *tmp1, *tmp2;
582          JSObject *nvp2=JSVAL_TO_OBJECT(JSVAL_NULL);
583          jsmsg1 = JS_ValueToString(cx,nvp1j);
584          len1 = JS_GetStringLength(jsmsg1);
585          tmp1=JS_EncodeString(cx,jsmsg1);
586          tmp2=JS_EncodeString(cx,jsmsg);
587#ifdef JS_DEBUG
588          fprintf(stderr,"JSVAL NVP1J IS OBJECT %s = %s\n",JS_EncodeString(cx,jsmsg),tmp1);
589#endif
590          if(strcasecmp(tmp1,"[object Object]")==0){
591            tres->name=zStrdup(tmp2);
592            tres->content=mapFromJSObject(cx,nvp1j);
593          }
594          else
595            if(strcasecmp(tmp2,"name")==0){
596              tres->name=zStrdup(tmp1);
597            }
598            else{
599              if(tres->content==NULL)
600                tres->content=createMap(tmp2,tmp1);
601              else
602                addToMap(tres->content,tmp2,tmp1);
603            }
604          free(tmp1);
605          free(tmp2);
606        }
607#ifdef JS_DEBUG
608        else
609          fprintf(stderr,"JSVAL NVP1J IS NOT OBJECT !!\n");
610#endif
611      }
612#ifdef JS_DEBUG
613      dumpMaps(tres);
614#endif
615      if(res==NULL)
616        res=dupMaps(&tres);
617      else
618        addMapsToMaps(&res,tres);
619      freeMaps(&tres);
620      free(tres);
621      tres=NULL;
622      JS_DestroyIdArray(cx,idp);
623    }
624  }
625#ifdef JS_DEBUG
626  dumpMaps(res);
627#endif
628  return res;
629}
630
631map* mapFromJSObject(JSContext *cx,jsval t){
632  map *res=NULL;
633  JSIdArray *idp=JS_Enumerate(cx,JSVAL_TO_OBJECT(t));
634#ifdef JS_DEBUG
635  fprintf(stderr,"Properties %p\n",(void*)t);
636#endif
637  if(idp!=NULL) {
638    int index;
639    jsdouble argNum;
640#ifdef JS_DEBUG
641    fprintf(stderr,"Properties length :  %d \n",idp->length);
642#endif
643    for (index=0,argNum=idp->length;index<argNum;index++) { 
644      jsval id = idp->vector[index];
645      jsval vp;
646      JSString* str; 
647      JS_IdToValue(cx,id,&vp);
648      char *c, *tmp, *tmp1;
649      JSString *jsmsg,*jsmsg1;
650      size_t len,len1;
651      jsmsg = JS_ValueToString(cx,vp);
652      len = JS_GetStringLength(jsmsg);
653      jsval nvp;
654      tmp=JS_EncodeString(cx,jsmsg);
655      JS_GetProperty(cx, JSVAL_TO_OBJECT(t), tmp, &nvp);
656      jsmsg1 = JS_ValueToString(cx,nvp);
657      len1 = JS_GetStringLength(jsmsg1);
658      tmp1=JS_EncodeString(cx,jsmsg1);
659#ifdef JS_DEBUG
660      fprintf(stderr,"Enumerate id : %d [ %s => %s ]\n",index,tmp,tmp1);
661#endif
662      if(res!=NULL){
663#ifdef JS_DEBUG
664        fprintf(stderr,"%s - %s\n",tmp,tmp1);
665#endif
666        addToMap(res,tmp,tmp1);
667      }
668      else{
669        res=createMap(tmp,tmp1);
670        res->next=NULL;
671      }
672      free(tmp);
673      free(tmp1);
674#ifdef JS_DEBUG
675      dumpMap(res);
676#endif
677    }
678    JS_DestroyIdArray(cx,idp);
679  }
680#ifdef JS_DEBUG
681  dumpMap(res);
682#endif
683  return res;
684}
685
686/* The error reporter callback. */
687void reportError(JSContext *cx, const char *message, JSErrorReport *report)
688{
689  sprintf(dbg,"%s:%u:%s\n",
690          report->filename ? report->filename : "<no filename>",
691          (unsigned int) report->lineno,
692          message);
693#ifdef JS_DEBUG
694  fprintf(stderr,"%s",dbg);
695#endif
696  fflush(stderr);
697}
698
699char* JSValToChar(JSContext* context, jsval* arg) {
700  char *c;
701  char *tmp;
702  JSString *jsmsg;
703  size_t len;
704  int i;
705  if(!JSVAL_IS_STRING(*arg)) {
706    return NULL;
707  }
708  jsmsg = JS_ValueToString(context,*arg);
709  len = JS_GetStringLength(jsmsg);
710  tmp = JS_EncodeString(context,jsmsg);
711  c = (char*)malloc((len+1)*sizeof(char));
712  c[len] = '\0';
713#ifdef ULINET_DEBUG
714  fprintf(stderr,"%d \n",len);
715#endif
716  for(i = 0;i < len;i++) {
717    c[i] = tmp[i];
718    c[i+1] = 0;
719  }
720#ifdef ULINET_DEBUG
721  fprintf(stderr,"%s \n",c);
722#endif
723  return c;
724}
725
726HINTERNET setHeader(HINTERNET* handle,JSContext *cx,JSObject *header){
727  jsuint length=0;
728  jsint i=0;
729  char *tmp1;
730#ifdef ULINET_DEBUG
731  fprintf(stderr,"setHeader\n");
732#endif
733  if(JS_IsArrayObject(cx,header)){
734#ifdef ULINET_DEBUG
735    fprintf(stderr,"header is an array\n");
736#endif
737    JS_GetArrayLength(cx,header,&length);
738#ifdef ULINET_DEBUG
739    fprintf(stderr,"header is an array of %d elements\n",length);
740#endif
741    handle->ihandle[handle->nb].header=NULL;
742    for(i=0;i<length;i++){
743      jsval tmp;
744      JS_GetElement(cx,header,i,&tmp);
745      tmp1=JSValToChar(cx,&tmp);
746#ifdef ULINET_DEBUG
747      curl_easy_setopt(handle->ihandle[handle->nb].handle,CURLOPT_VERBOSE,1);
748      fprintf(stderr,"Element of array n° %d, value : %s\n",i,tmp1);
749#endif
750      handle->ihandle[handle->nb].header=curl_slist_append(handle->ihandle[handle->nb].header, tmp1);
751      free(tmp1);
752    }
753  }
754  else{
755    fprintf(stderr,"not an array !!!!!!!\n");
756  }
757  return *handle;
758}
759
760JSBool
761JSTranslate(JSContext *cx, uintN argc, jsval *argv1)
762{
763  jsval *argv = JS_ARGV(cx,argv1);
764  char *str=JSValToChar(cx,&argv[0]);
765  char *tmpValue=_ss(str);
766  JS_SET_RVAL(cx, argv1,STRING_TO_JSVAL(JS_NewStringCopyN(cx,tmpValue,strlen(tmpValue)))); 
767  JS_MaybeGC(cx);
768  return JS_TRUE;
769}
770
771JSBool
772JSRequest(JSContext *cx, uintN argc, jsval *argv1)
773{
774  jsval *argv = JS_ARGV(cx,argv1);
775  HINTERNET hInternet;
776  HINTERNET res;
777  HINTERNET res1;
778  JSObject *header;
779  char *url;
780  char *method;
781  char* tmpValue;
782  size_t dwRead;
783  int i=0;
784  JS_MaybeGC(cx);
785  hInternet=InternetOpen("ZooWPSClient\0",
786                         INTERNET_OPEN_TYPE_PRECONFIG,
787                         NULL,NULL, 0);
788  if(!CHECK_INET_HANDLE(hInternet))
789    return JS_FALSE;
790  if(argc>=2){
791    method=JSValToChar(cx,&argv[0]);
792    url=JSValToChar(cx,&argv[1]);
793  }
794  else{
795    method=zStrdup("GET");
796    url=JSValToChar(cx,argv);
797  }
798  hInternet.waitingRequests[hInternet.nb]=strdup(url);
799  if(argc==4){
800    char *body;
801    body=JSValToChar(cx,&argv[2]);
802    header=JSVAL_TO_OBJECT(argv[3]);
803#ifdef ULINET_DEBUG
804    fprintf(stderr,"URL (%s) \nBODY (%s)\n",url,body);
805#endif
806    if(JS_IsArrayObject(cx,header))
807      setHeader(&hInternet,cx,header);
808#ifdef ULINET_DEBUG
809    fprintf(stderr,"BODY (%s)\n",body);
810#endif
811    InternetOpenUrl(&hInternet,hInternet.waitingRequests[hInternet.nb],body,strlen(body),
812                    INTERNET_FLAG_NO_CACHE_WRITE,0);   
813    processDownloads(&hInternet);
814    free(body);
815  }else{
816    if(argc==3){
817      char *body=JSValToChar(cx,&argv[2]);
818      InternetOpenUrl(&hInternet,hInternet.waitingRequests[hInternet.nb],body,strlen(body),
819                      INTERNET_FLAG_NO_CACHE_WRITE,0);
820      processDownloads(&hInternet);
821      free(body);
822    }else{
823      InternetOpenUrl(&hInternet,hInternet.waitingRequests[hInternet.nb],NULL,0,
824                      INTERNET_FLAG_NO_CACHE_WRITE,0);
825      processDownloads(&hInternet);
826    }
827  }
828  tmpValue=(char*)malloc((hInternet.ihandle[0].nDataLen+1)*sizeof(char));
829  InternetReadFile(hInternet.ihandle[0],(LPVOID)tmpValue,hInternet.ihandle[0].nDataLen,&dwRead);
830#ifdef ULINET_DEBUG
831  fprintf(stderr,"content downloaded (%d) (%s) \n",dwRead,tmpValue);
832#endif
833  if(dwRead==0){
834    JS_SET_RVAL(cx, argv1,STRING_TO_JSVAL(JS_NewStringCopyN(cx,"Unable to access the file.",strlen("Unable to access the file."))));
835    return JS_TRUE;
836  }
837
838#ifdef ULINET_DEBUG
839  fprintf(stderr,"content downloaded (%d) (%s) \n",dwRead,tmpValue);
840#endif
841  JS_SET_RVAL(cx, argv1,STRING_TO_JSVAL(JS_NewStringCopyN(cx,tmpValue,strlen(tmpValue))));
842  free(url);
843  if(argc>=2)
844    free(method);
845  InternetCloseHandle(&hInternet);
846  JS_MaybeGC(cx);
847  return JS_TRUE;
848}
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