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

Last change on this file since 453 was 453, checked in by djay, 10 years ago

Add the optional Ruby Language Support to the ZOO-Kernel with an API similar to the Python ZOO-API. Small rewrite of Python support. Fix issue #86 and #87. Add usid in [lenv] section, this value is used to generate an unique identifier based on time and the process identifier. This usid is now used to name the stored result or the mapfile generated. Remove *some* warning messages displayed at compilation time.

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