Пример #1
0
/**
 * The function used as ZOOUpdateStatus from the JavaScript environment
 * (ZOO-API).
 *
 * @param cx the JavaScript context
 * @param argc the number of parameters
 * @param argv1 the parameter values
 * @return true
 * @see setHeader,_updateStatus
 */
JSBool
JSUpdateStatus(JSContext *cx, uintN argc, jsval *argv1)
{
  jsval *argv = JS_ARGV(cx,argv1);
  JS_MaybeGC(cx);
  int istatus=0;
  char *status=NULL;
  maps *conf;
  if(argc>2){
#ifdef JS_DEBUG
    fprintf(stderr,"Number of arguments used to call the function : %i",argc);
#endif
    return JS_FALSE;
  }
  conf=mapsFromJSObject(cx,argv[0]);
  if(JS_ValueToInt32(cx,argv[1],&istatus)==JS_TRUE){
    char tmpStatus[4];
    sprintf(tmpStatus,"%i",istatus);
    tmpStatus[3]=0;
    status=strdup(tmpStatus);
  }
  if(getMapFromMaps(conf,"lenv","status")!=NULL){
    if(status!=NULL){
      setMapInMaps(conf,"lenv","status",status);
      free(status);
    }
    else
      setMapInMaps(conf,"lenv","status","15");
    _updateStatus(conf);
  }
  freeMaps(&conf);
  free(conf);
  JS_MaybeGC(cx);
  return JS_TRUE;
}
Пример #2
0
/**
 * Verify if a url is available in the cache
 *
 * @param conf the maps containing the settings of the main.cfg file
 * @param request the url
 * @return the full name of the cached file if any, NULL in other case
 * @warning make sure to free resources returned by this function (if not NULL)
 */
char* isInCache(maps* conf,char* request){
  map* tmpM=getMapFromMaps(conf,"main","cacheDir");
  if(tmpM!=NULL){
    char* md5str=getMd5(request);
#ifdef DEBUG
    fprintf(stderr,"MD5STR : (%s)\n\n",md5str);
#endif
    char* fname=(char*)malloc(sizeof(char)*(strlen(tmpM->value)+strlen(md5str)+6));
    sprintf(fname,"%s/%s.zca",tmpM->value,md5str);
    struct stat f_status;
    int s=stat(fname, &f_status);
    if(s==0 && f_status.st_size>0){
      free(md5str);
      return fname;
    }
    free(md5str);
    free(fname);
  }
  return NULL;
}
Пример #3
0
/**
 * Cache a file for a given request.
 * For each cached file, the are two files stored, a .zca and a .zcm containing
 * the downloaded content and the mimeType respectively. 
 *
 * @param conf the maps containing the settings of the main.cfg file
 * @param request the url used too fetch the content
 * @param content the downloaded content
 * @param mimeType the content mimeType 
 * @param length the content size
 * @param filepath a buffer for storing the path of the cached file; may be NULL
 * @param max_path the size of the allocated filepath buffer  
 */
void addToCache(maps* conf,char* request,char* content,char* mimeType,int length, 
                char* filepath, size_t max_path){
  map* tmp=getMapFromMaps(conf,"main","cacheDir");
  if(tmp!=NULL){
    char* md5str=getMd5(request);
    char* fname=(char*)malloc(sizeof(char)*(strlen(tmp->value)+strlen(md5str)+6));
    sprintf(fname,"%s/%s.zca",tmp->value,md5str);
#ifdef DEBUG
    fprintf(stderr,"Cache list : %s\n",fname);
    fflush(stderr);
#endif
    FILE* fo=fopen(fname,"w+");
    if(fo==NULL){
#ifdef DEBUG
      fprintf (stderr, "Failed to open %s for writing: %s\n",fname, strerror(errno));
#endif
      filepath = NULL;	
      return;
    }
    fwrite(content,sizeof(char),length,fo);
    fclose(fo);
	
	if (filepath != NULL) {
		strncpy(filepath, fname, max_path);
	}	

    sprintf(fname,"%s/%s.zcm",tmp->value,md5str);
    fo=fopen(fname,"w+");
#ifdef DEBUG
    fprintf(stderr,"MIMETYPE: %s\n",mimeType);
#endif
    fwrite(mimeType,sizeof(char),strlen(mimeType),fo);
    fclose(fo);

    free(md5str);
    free(fname);
  }
  else {
	  filepath = NULL;
  }	  
}
Пример #4
0
/**
 * Update the ongoing status of a running service from the Ruby environment
 * (ZOO-API)
 *
 * @param argc the number of parameters
 * @param argv the parameter values given from the Ruby environment
 * @param obj the Ruby object on which we run the method
 * @return a new Ruby string containing the translated value
 * @see _updateStatus
 */
VALUE
RubyUpdateStatus(int argc, VALUE *argv, VALUE obj)
{
  maps* conf;
  VALUE confdict=argv[0];
  int istatus=argv[1];
  char* status;
  if (istatus < 0 || istatus > 100){
    fprintf(stderr,"Status must be a percentage.");
    return Qnil;
  }else{
     char tmpStatus[4];
     snprintf(tmpStatus, 4, "%i", istatus);
     status = zStrdup(tmpStatus);
  }
  /* now update the map */
  {
    VALUE lenv = rb_hash_aref(confdict,rb_str_new2("lenv"));
    if(TYPE(lenv)!=T_NIL){
      VALUE valobj=rb_str_new2(status);
      rb_hash_aset(lenv,rb_str_new2("status"),valobj);
    }
  }
  conf = mapsFromRubyHash(confdict);
  if (getMapFromMaps(conf,"lenv","status") != NULL){
    fprintf(stderr,"STATUS RETURNED : %s\n",status);
    if(status!=NULL){
      setMapInMaps(conf,"lenv","status",status);
      free(status);
    }
    else
      setMapInMaps(conf,"lenv","status","15");
    _updateStatus(conf);
  }
  freeMaps(&conf);
  free(conf);
  return Qnil;
}
Пример #5
0
/**
 * Load a JavaScript file then run the function corresponding to the service by
 * passing the conf, inputs and outputs parameters by value as JavaScript
 * Objects.
 *
 * @param main_conf the conf maps containing the main.cfg settings
 * @param request the map containing the HTTP request
 * @param s the service structure
 * @param inputs the maps containing the inputs
 * @param outputs the maps containing the outputs
 * @return SERVICE_SUCCEEDED or SERVICE_FAILED if the service run, -1 
 *  if the service failed to load or throw error at runtime.
 */
int zoo_js_support(maps** main_conf,map* request,service* s,maps **inputs,maps **outputs)
{
  /*maps* main=*main_conf;
  maps* _inputs=*inputs;
  maps* _outputs=*outputs;*/

  /* The class of the global object. */
  JSClass global_class= {
    "global", JSCLASS_GLOBAL_FLAGS,
    JS_PropertyStub, JS_PropertyStub, JS_PropertyStub, JS_StrictPropertyStub,
    JS_EnumerateStub, JS_ResolveStub, JS_ConvertStub, JS_FinalizeStub,
    JSCLASS_NO_OPTIONAL_MEMBERS
  };

  /* JS variables. */
  JSRuntime *rt;
  JSContext *cx;
  JSObject  *global;

  /* Create a JS runtime. */
  rt = JS_NewRuntime(8L * 1024L * 1024L);
  if (rt == NULL)
    return 1;
  
  /* Create a context. */
  cx = JS_NewContext(rt,8192);
  if (cx == NULL){
    return 1;
  }
  JS_SetOptions(cx, JSOPTION_VAROBJFIX | JSOPTION_JIT | JSOPTION_METHODJIT);
  JS_SetVersion(cx, JSVERSION_LATEST);
  JS_SetErrorReporter(cx, reportError);

  /* Create the global object. */
  global = JS_NewCompartmentAndGlobalObject(cx, &global_class, NULL);

  /* Populate the global object with the standard globals,
     like Object and Array. */
  if (!JS_InitStandardClasses(cx, global)){
    return 1;
  }

  /* Define specific function and global variable to share with JS runtime
   */
  jsval tmp=INT_TO_JSVAL(3);
  if (!JS_SetProperty(cx, global, "SERVICE_SUCCEEDED", &tmp))
    return 1;
  tmp=INT_TO_JSVAL(4);
  if (!JS_SetProperty(cx, global, "SERVICE_FAILED", &tmp))
    return 1;
  if (!JS_DefineFunction(cx, global, "ZOORequest", JSRequest, 4, 0))
    return 1;
  if (!JS_DefineFunction(cx, global, "ZOOTranslate", JSTranslate, 4, 0))
    return 1;
  if (!JS_DefineFunction(cx, global, "ZOOUpdateStatus", JSUpdateStatus, 2, 0))
    return 1;
  if (!JS_DefineFunction(cx, global, "alert", JSAlert, 2, 0))
    return 1;  
  if (!JS_DefineFunction(cx, global, "importScripts", JSLoadScripts, 1, 0))
    return 1;

  /**
   * Add private context object
   */
  void* cxPrivate = request;
  JS_SetContextPrivate(cx,cxPrivate);

  map* tmpm1=getMap(request,"metapath");
  char ntmp[1024];
  map* cwdMap=getMapFromMaps(*main_conf,"main","servicePath");
  if(cwdMap!=NULL)
    sprintf(ntmp,"%s",cwdMap->value);
  else
    getcwd(ntmp,1024);

  /**
   * Load the first part of the ZOO-API
   */
  char *api0=(char*)malloc((strlen(ntmp)+17)*sizeof(char));
  sprintf(api0,"%s/ZOO-proj4js.js",ntmp);
#ifdef JS_DEBUG
  fprintf(stderr,"Trying to load %s\n",api0);
#endif
  JSObject *api_script1=loadZooApiFile(cx,global,api0);
  free(api0);
  fflush(stderr);

  char *api1=(char*)malloc((strlen(ntmp)+13)*sizeof(char));
  sprintf(api1,"%s/ZOO-api.js",ntmp);
#ifdef JS_DEBUG
  fprintf(stderr,"Trying to load %s\n",api1);
#endif
  JSObject *api_script2=loadZooApiFile(cx,global,api1);
  free(api1);
  fflush(stderr);

  /* Your application code here. This may include JSAPI calls
     to create your own custom JS objects and run scripts. */
  //maps* out=*outputs;
  int res=SERVICE_FAILED;
  //maps* mc=*main_conf;
  map* tmpm2=getMap(s->content,"serviceProvider");

  char *filename=(char*)malloc(strlen(tmpm1->value)+strlen(tmpm2->value)+strlen(ntmp)+3);
  sprintf(filename,"%s/%s/%s",ntmp,tmpm1->value,tmpm2->value);
  filename[strlen(tmpm1->value)+strlen(tmpm2->value)+strlen(ntmp)+2]=0;
#ifdef JS_DEBUG
  fprintf(stderr,"FILENAME %s\n",filename);
#endif
  struct stat file_status;
  stat(filename, &file_status);
  //char *source=(char*)malloc(file_status.st_size);
  //uint16 lineno;
  jsval rval;
  JSBool ok ;
  JSObject *script = JS_CompileFile(cx, global, filename);
  if(script!=NULL){
    (void)JS_ExecuteScript(cx, global, script, &rval);
  }
  else{
    char tmp1[1024];
    sprintf(tmp1,"Unable to load JavaScript file %s",filename);
    free(filename);
    errorException(*main_conf,tmp1,"NoApplicableCode",NULL);
    JS_MaybeGC(cx);
    JS_DestroyContext(cx);
    JS_DestroyRuntime(rt);
    JS_ShutDown();
    return -1;
  }
  

  /* Call a function in obj's scope. */
  jsval argv[3];
  JSObject *jsargv1=JSObject_FromMaps(cx,*main_conf);
  argv[0] = OBJECT_TO_JSVAL(jsargv1);
  JSObject *jsargv2=JSObject_FromMaps(cx,*inputs);
  argv[1] = OBJECT_TO_JSVAL(jsargv2);
  JSObject *jsargv3=JSObject_FromMaps(cx,*outputs);
  argv[2] = OBJECT_TO_JSVAL(jsargv3);
  jsval rval1=JSVAL_NULL;
#ifdef JS_DEBUG
  fprintf(stderr, "object %p\n", (void *) argv[2]);
#endif

  ok = JS_CallFunctionName(cx, global, s->name, 3, argv, &rval1);

#ifdef JS_DEBUG
  fprintf(stderr, "object %p\n", (void *) argv[2]);
#endif

  JSObject *d;
  if (ok==JS_TRUE && JSVAL_IS_OBJECT(rval1)==JS_TRUE) {
#ifdef JS_DEBUG
    fprintf(stderr,"Function run sucessfully !\n");
#endif
    /* Should get a number back from the service function call. */
    ok = JS_ValueToObject(cx, rval1, &d);
  }else{
    /* Unable to run JS function */
    char tmp1[1024];
    if(strlen(dbg)==0)
      sprintf(dbg,"No result was found after the function call");
    sprintf(tmp1,"Unable to run %s from the JavaScript file %s : \n %s",s->name,filename,dbg);
#ifdef JS_DEBUG
    fprintf(stderr,"%s",tmp1);
#endif
    errorException(*main_conf,tmp1,"NoApplicableCode",NULL);
    free(filename);
    JS_MaybeGC(cx);
    JS_DestroyContext(cx);
    JS_DestroyRuntime(rt);
    JS_ShutDown();
    // Should return -1 here but the unallocation won't work from zoo_service_loader.c line 1847
    return -1;
  }

  //jsval t=OBJECT_TO_JSVAL(d);
  if(JS_IsArrayObject(cx,d)){
#ifdef JS_DEBUG
    fprintf(stderr,"An array was returned !\n");
#endif
    jsuint	 len;
    if((JS_GetArrayLength(cx, d, &len)==JS_FALSE)){
#ifdef JS_DEBUG
      fprintf(stderr,"outputs array is empty\n");
#endif
    }
    jsval tmp1;
    JSBool hasResult=JS_GetElement(cx,d,0,&tmp1);
    res=JSVAL_TO_INT(tmp1);
#ifdef JS_DEBUG
    fprintf(stderr," * %d * \n",res);
#endif
    if(res==SERVICE_SUCCEEDED){
      jsval tmp2;
      JSBool hasElement=JS_GetElement(cx,d,1,&tmp2);
      if(hasElement==JS_TRUE){
	freeMaps(outputs);
	free(*outputs);
	*outputs=mapsFromJSObject(cx,tmp2);
      }
    }else{
      jsval tmp3;
      JSBool hasConf=JS_GetElement(cx,d,1,&tmp3);
      if(hasConf==JS_TRUE){
	freeMaps(main_conf);
	free(*main_conf);
	*main_conf=mapsFromJSObject(cx,tmp3);
      }
    }

  }
  else{
#ifdef JS_DEBUG
    fprintf(stderr,"The service didn't return an array !\n");
#endif
    /**
     * Extract result
     */
    jsval tmp1;
    JSBool hasResult=JS_GetProperty(cx,d,"result",&tmp1);
    res=JSVAL_TO_INT(tmp1);

#ifdef JS_DEBUG
    fprintf(stderr," * %d * \n",res);
#endif
    /**
     * Extract outputs when available.
     */
    jsval tmp2;
    JSBool hasElement=JS_GetProperty(cx,d,"outputs",&tmp2);
    if(!JSVAL_IS_VOID(tmp2) && hasElement==JS_TRUE){
      freeMaps(outputs);
      free(*outputs);    
      *outputs=mapsFromJSObject(cx,tmp2);
    }
    JS_MaybeGC(cx);
#ifdef JS_DEBUG
    if(JSVAL_IS_VOID(tmp2))
      fprintf(stderr,"No outputs property returned\n");
    else{
      if(JS_IsArrayObject(cx,JSVAL_TO_OBJECT(tmp2)))
	fprintf(stderr,"outputs is an array as expected\n");
      else
	fprintf(stderr,"outputs is not an array as expected\n");
    }
    JS_MaybeGC(cx);
#endif

    /**
     * Extract conf when available.
     */
    jsval tmp3;
    JSBool hasConf=JS_GetProperty(cx,d,"conf",&tmp3);
    if(!JSVAL_IS_VOID(tmp3) && hasConf==JS_TRUE){
      freeMaps(main_conf);
      free(*main_conf);
      *main_conf=mapsFromJSObject(cx,tmp3);
    }
    JS_MaybeGC(cx);

#ifdef JS_DEBUG
    dumpMaps(*outputs);
#endif
  }
  /* Cleanup. */
  JS_MaybeGC(cx);
  JS_DestroyContext(cx);
  JS_DestroyRuntime(rt);
  JS_ShutDown();
  free(filename);
#ifdef JS_DEBUG
  fprintf(stderr,"Returned value %d\n",res);
#endif
  return res;
}
Пример #6
0
/**
 * Load a PHP script then run the function corresponding to the service by
 * passing the conf, inputs and outputs parameters by reference.
 *
 * @param main_conf the conf maps containing the main.cfg settings
 * @param request the map containing the HTTP request
 * @param s the service structure
 * @param real_inputs the maps containing the inputs
 * @param real_outputs the maps containing the outputs
 */
int zoo_php_support(maps** main_conf,map* request,service* s,maps **real_inputs,maps **real_outputs){	
  maps* m=*main_conf;
  maps* inputs=*real_inputs;
  maps* outputs=*real_outputs;
    
  map* libp = getMapFromMaps(m, "main", "libPath");  
  int res=SERVICE_FAILED;

  map* tmp=getMap(s->content,"serviceProvider");
  if (tmp == NULL || tmp->value == NULL) {
	  return errorException(m, "Missing serviceProvider (library file)", "NoApplicableCode", NULL);
  }
  
  map* cwd=getMapFromMaps(m,"lenv","cwd");
#ifdef IGNORE_METAPATH
  map* mp = createMap("metapath", "");
#else  
  map* mp = getMap(request, "metapath");
#endif
  char *scriptName;
  
  if (libp != NULL && libp->value != NULL) {
	scriptName = (char*) malloc((strlen(libp->value) + strlen(tmp->value) + 2)*sizeof(char));
    sprintf (scriptName, "%s/%s", libp->value, tmp->value);	
  }
  else {	
    if(mp!=NULL && strlen(mp->value)>0){
      scriptName=(char*)malloc((strlen(cwd->value)+strlen(mp->value)+strlen(tmp->value)+3)*sizeof(char));
      sprintf(scriptName,"%s/%s/%s",cwd->value,mp->value,tmp->value);
    }else{
      scriptName=(char*)malloc((strlen(cwd->value)+strlen(tmp->value)+2)*sizeof(char));
      sprintf(scriptName,"%s/%s",cwd->value,tmp->value);
    }
  } 
  zend_file_handle iscript;
  iscript.type=ZEND_HANDLE_FD;
  iscript.opened_path=NULL;
  iscript.filename=tmp->value;
  iscript.free_filename=0;
  FILE* temp=fopen(scriptName,"rb");
  if(temp==NULL){
    char tmp1[1024];
    sprintf(tmp1,_("Unable to load the PHP file %s"),tmp->value);
    free(scriptName);
    return errorException(m,tmp1,"NoApplicableCode",NULL);
  }
  iscript.handle.fd=fileno(temp);

  php_embed_init(0,NULL PTSRMLS_CC);
   
  zend_try {
    zend_startup_module(&zoo_module_entry);
    php_execute_script(&iscript TSRMLS_CC);
    zval *iargs[3];
    zval iret, ifunc,ifile;
      
    ZVAL_STRING(&ifunc, s->name, 0);
    iargs[0] = php_Array_from_maps(*main_conf);
    iargs[1] = php_Array_from_maps(*real_inputs);
    iargs[2] = php_Array_from_maps(*real_outputs);
      
    if((res=call_user_function(EG(function_table), NULL, &ifunc, &iret, 3, iargs TSRMLS_CC))==SUCCESS){
      
      HashTable* t=HASH_OF(iargs[2]);
      HashTable* t1=HASH_OF(iargs[0]);
      freeMaps(real_outputs);
      free(*real_outputs);
      freeMaps(main_conf);
      free(*main_conf);
      *real_outputs=php_maps_from_Array(t);
      *main_conf=php_maps_from_Array(t1);

      res=Z_LVAL(iret);
    }else{
      free(scriptName);
      fclose(temp);
      return errorException(m,"Unable to process.","NoApplicableCode",NULL);;
    }
  } zend_catch { 
    free(scriptName);
    fclose(temp);
    return errorException(m,"Unable to process.","NoApplicableCode",NULL);;
  } zend_end_try();
  free(scriptName);
  fclose(temp);
  php_embed_shutdown(TSRMLS_C);

  return res;
}
Пример #7
0
int main(int argc, char *argv[])
{
  if (argc < 4){
    printf( "Usage: %s <servicename> <directory>|<definition_file> <REQUEST> [<functionname> <param_1>[...<param_n>]]\n", basename(argv[0]) );
    return 1;
  }
 
  map* outputs=NULL;
  /**
   * Parsing inputs (need a loop over all files in the service path !!)
   */
  maps* m;
  m=(maps*)malloc(MAP_SIZE);
  conf_read("main.cfg",m);
  map* tmpm=getMapFromMaps(m,"main","serverAddress");
  int toto=count(tmpm);
  //printf(" - %i \n",toto);

  if(tmpm!=NULL)
    SERVICE_URL=strdup(tmpm->value);
  else
    SERVICE_URL=DEFAULT_SERVICE_URL;

  service* s[100];
  service* s1;
  int scount=0;

  if(strcmp(argv[3],"GetCapabilities")==0){
    int i=0;
    struct dirent *dp;
    DIR *dirp = opendir(argv[1]);
    int t;
    xmlDocPtr doc = xmlNewDoc(BAD_CAST "1.0");
    xmlNodePtr n = printGetCapabilitiesHeader(doc,argv[2],m);
    
    int saved_stdout = dup(fileno(stdout));
    stdout = freopen("/dev/null" , "w" , stdout);
    while ((dp = readdir(dirp)) != NULL)
      if(strstr(dp->d_name,".zcfg")!=0){
	char toto1[1024];
	sprintf(toto1,"%s%s",argv[1],dp->d_name);
	char *toto=toto1;
	s1=(service*)malloc(sizeof(char*)+(MAP_SIZE*2)+(2*ELEMENTS_SIZE));
	//s[scount]=(service*)malloc(sizeof(service*));
	//#ifdef DEBUG
	fprintf(stderr,"#################\n%s\n#################\n",toto1);
	//printf("|(1)");
	//#endif
	t=getServiceFromFile(toto1,&s1);
	
	//printf("|(2)");
	printGetCapabilitiesForProcess(m,n,s1);
	/**
	 * Valgrind told us that there is an issue regarding a 
	 * "conditional jump or move depends on uninitialised value(s)" for
	 * freeIOType
	 */
	//freeService(&s1);
	scount++;
      }
    char buf[20];
    sprintf(buf, "/dev/fd/%d", saved_stdout);
    stdout = freopen(buf , "w" , stdout);

    printDocument(doc);
    fflush(stdout);
    free(m);
    return 0;
  }
  else{
    s1=(service*)malloc(sizeof(char*)+(MAP_SIZE*2)+(2*ELEMENTS_SIZE));
    //s[0]=(service*)malloc(sizeof(service*));
    int t=getServiceFromFile(argv[1],&s1);
    if(strcmp(argv[3],"DescribeProcess")==0){
      printDescribeProcessResponse(s1,argv[2]);
      //dumpMaps(m);
      //free(s1);
      return 0;
    }
    else
      if(strcmp(argv[3],"Execute")!=0){
	fprintf(stderr,"");
	//free(s);
	return 0;
      }
  }
  //dumpService(s);
  s[0]=s1;
  map* inputs=NULL;
  elements* c_inputs=s1->inputs;
  int j;
  for(j=0;j<argc-5;j++){
    //dumpElements(c_inputs);
    if(inputs!=NULL)
      addToMap(inputs,c_inputs->name,argv[j+5]);
    else
      inputs=createMap(c_inputs->name,argv[j+5]);
    if(c_inputs->next!=NULL || j+1>=argc-5)
      c_inputs=c_inputs->next;
    else{
      map* tmps=createMap("text","ERROR you provided more inputs than requested.");
      printExceptionReportResponse(m,tmps);
      //printf("ERROR you provided more inputs than requested.");
      return -1;
    }
#ifdef DEBUG
    printf("ARGV1 %d %s\n",j,inputs->value);
#endif
  }

#ifdef DEBUG
  dumpMap(inputs);
#endif

  const struct tm *tm;
  size_t len;
  time_t now;
  char *sDate;
  
  now = time ( NULL );
  tm = localtime ( &now );

  sDate = new char[TIME_SIZE];

  len = strftime ( sDate, TIME_SIZE, "%d-%B-%YT%I:%M:%SZ", tm );

#ifdef DEBUG
  printf("Trying to load %s\n", argv[2]);
#endif
  void* so = dlopen(argv[2], RTLD_LAZY);
  char *errstr;
  errstr = dlerror();
  if( so != NULL ) {
    typedef int (*execute_t)(map**,map**);
#ifdef DEBUG
    printf("Library loaded %s \n",errstr);
#endif
    execute_t execute=(execute_t)dlsym(so,argv[4]);
#ifdef DEBUG
    errstr = dlerror();
    printf("Function loaded %s\n",errstr);
#endif	

    /**
     * Need to check if we need to fork to load a status enabled 
     */
    char _toto[10];
    sprintf(_toto,"input_%i",argc-5);
    map* toto=getMap(inputs,_toto);
    if(strcmp(argv[argc-1],"bg")!=0){
#ifdef DEBUG
      printf("RUN IN NORMAL MODE \n");
#endif
      int res=execute(&inputs,&outputs);
#ifdef DEBUG
      printf("RUNNED IN NORMAL MODE \n");
      dumpMap(inputs);
      dumpMap(outputs);
#endif
      printProcessResponse(m,getpid(),s[0],argv[2],res,inputs,outputs);
    }
    else{
      pid_t   pid;
      int cpid=getpid();
      pid = fork ();
      if (pid > 0) {
	/**
	 * dady :
	 * set status to SERVICE_ACCEPTED
	 */
	printProcessResponse(m,pid,s[0],argv[2],SERVICE_ACCEPTED,inputs,outputs);
      }else if (pid == 0) {
	/* son */
	if (signal(SIGINT, sigint_handler) == SIG_ERR) {
	  printf("signal");
	  map* tmps=createMap("text","father received sigint.");
	  printExceptionReportResponse(m,tmps);
	  exit(1);
	}
#ifdef DEBUG
	printf("RUN IN BACKGROUND MODE \n");
#endif
	char tmp1[256];
	sprintf(tmp1,"service/temp/%s_%d.xml",argv[2],getpid());
	stdout = freopen(tmp1 , "w+" , stdout);
	/**
	 * set status to SERVICE_STARTED
	 */
	printProcessResponse(m,getpid(),s[0],argv[2],SERVICE_STARTED,inputs,outputs);
	fflush(stdout);
	rewind(stdout);
	int t=execute(&inputs,&outputs);
	/**
	 * set status to status code returned by the service function
	 */
	printProcessResponse(m,getpid(),s[0],argv[2],t,inputs,outputs);
      } else {
	/* error */
      }
    }
#ifdef DEBUG
    errstr = dlerror();
    printf("Function successfully loaded %s, unloading now.\n",errstr);
#endif
    dlclose(so);
  }
  else {
#ifdef DEBUG
    printf("C Library can't be loaded %s \n",errstr);
#endif
    python_support(m,s[0],argc,argv,inputs,outputs);
  }
  return 0;
}
Пример #8
0
/**
 * Load a Ruby file then run the function corresponding to the service by
 * passing the conf, inputs and outputs parameters by refernce as Ruby Hash.
 *
 * @param main_conf the conf maps containing the main.cfg settings
 * @param request the map containing the HTTP request
 * @param s the service structure
 * @param real_inputs the maps containing the inputs
 * @param real_outputs the maps containing the outputs
 * @return SERVICE_SUCCEEDED or SERVICE_FAILED if the service run, -1 
 *  if the service failed to load or throw error at runtime.
 */
int zoo_ruby_support(maps** main_conf,map* request,service* s,maps **real_inputs,maps **real_outputs){
#if RUBY_API_VERSION_MAJOR >= 2 || RUBY_API_VERSION_MINOR == 9
  ruby_sysinit(&argc,&argv);
  RUBY_INIT_STACK;
#endif
  ruby_init();
  maps* m=*main_conf;
  maps* inputs=*real_inputs;
  maps* outputs=*real_outputs;
  map* tmp0=getMapFromMaps(*main_conf,"lenv","cwd");
  char *ntmp=tmp0->value;
  map* tmp=NULL;
  ruby_init_loadpath();
  ruby_script("ZOO_EMBEDDED_ENV");
  
  VALUE klass=rb_define_module("Zoo");
  rb_define_const(klass,"SERVICE_SUCCEEDED",INT2FIX(3));
  rb_define_const(klass,"SERVICE_FAILED",INT2FIX(4));
  typedef VALUE (*HOOK)(...);
  rb_define_module_function(klass,"Translate",reinterpret_cast<HOOK>(RubyTranslate),-1);
  rb_define_module_function(klass,"UpdateStatus",reinterpret_cast<HOOK>(RubyUpdateStatus),-1);

  int error = 0;
		
  ID rFunc=Qnil;
  tmp=getMap(s->content,"serviceProvider");
  if(tmp!=NULL){
#if RUBY_VERSION_MINOR == 8
    const char* script = ruby_sourcefile = rb_source_filename(tmp->value);
    rb_protect(LoadWrap, reinterpret_cast<VALUE>(script), &error);
#else
    rb_load_protect(rb_str_new2(tmp->value), 0, &error);
#endif
    if(error) {
      ruby_trace_error(m);
      return -1;
    }
#if RUBY_VERSION_MINOR == 8
    ruby_exec();
#else
    ruby_exec_node(NULL);
#endif
  }
  else{
    map* err=createMap("text","Unable to parse serviceProvider please check your zcfg file.");
    addToMap(err,"code","NoApplicableCode");
    printExceptionReportResponse(m,err);
    return -1;
  }
  int res=SERVICE_FAILED;
  rFunc=rb_intern(s->name);
  if(rFunc!=Qnil){
    VALUE arg1=RubyHash_FromMaps(m);
    VALUE arg2=RubyHash_FromMaps(inputs);
    VALUE arg3=RubyHash_FromMaps(outputs);
    VALUE rArgs[3]={arg1,arg2,arg3};
    if (!rArgs)
      return -1;
    struct my_callback data;
    data.obj=Qnil;
    data.method_id=rFunc;
    data.nargs=3;
    data.args[0]=rArgs[0];
    data.args[1]=rArgs[1];
    data.args[2]=rArgs[2];
    typedef VALUE (*HOOK)(VALUE);
    VALUE tres=rb_protect(reinterpret_cast<HOOK>(FunCallWrap),(VALUE)(&data),&error);
    if (TYPE(tres) == T_FIXNUM) {
      res=FIX2INT(tres);
      freeMaps(real_outputs);
      free(*real_outputs);
      freeMaps(main_conf);
      free(*main_conf);
      *main_conf=mapsFromRubyHash(arg1);
      *real_outputs=mapsFromRubyHash(arg3);
#ifdef DEBUG
      dumpMaps(*main_conf);
      dumpMaps(*real_outputs);
#endif
    }else{
      ruby_trace_error(m);
      res=-1;
    }
  }
  else{
    char tmpS[1024];
    sprintf(tmpS, "Cannot find the %s function in the %s file.\n", s->name, tmp->value);
    map* tmps=createMap("text",tmpS);
    printExceptionReportResponse(m,tmps);
    res=-1;
  }
  ruby_finalize();
  return res;
}
Пример #9
0
  int Delaunay(maps*& conf,maps*& inputs,maps*& outputs){
#ifdef DEBUG
    fprintf(stderr,"\nService internal print\nStarting\n");
#endif
    maps* cursor=inputs;
    OGRGeometryH geometry,res;
    int bufferDistance;
    map* tmpm=NULL;
    OGRRegisterAll();

    std::vector<Point> points;
    if(int res=parseInput(conf,inputs,&points,"/vsimem/tmp")!=SERVICE_SUCCEEDED)
      return res;

    DelaunayT T;
    T.insert(points.begin(), points.end());

    /* -------------------------------------------------------------------- */
    /*      Try opening the output datasource as an existing, writable      */
    /* -------------------------------------------------------------------- */
#if GDAL_VERSION_MAJOR >= 2
    GDALDataset *poODS;
    GDALDriverManager* poR=GetGDALDriverManager();
    GDALDriver          *poDriver = NULL;
#else
    OGRDataSource       *poODS;    
    OGRSFDriverRegistrar *poR = OGRSFDriverRegistrar::GetRegistrar();
    OGRSFDriver          *poDriver = NULL;
#endif
    int                  iDriver;
    map *tmpMap=getMapFromMaps(outputs,"Result","mimeType");
    const char *oDriver;
    oDriver="GeoJSON";
    if(tmpMap!=NULL){
      if(strcmp(tmpMap->value,"text/xml")==0){
	oDriver="GML";
      }
    }
    
    for( iDriver = 0;
	 iDriver < poR->GetDriverCount() && poDriver == NULL;
	 iDriver++ )
      {
#ifdef DEBUG
#if GDAL_VERSION_MAJOR >= 2
	fprintf(stderr,"D:%s\n",poR->GetDriver(iDriver)->GetDescription());
#else
	fprintf(stderr,"D:%s\n",poR->GetDriver(iDriver)->GetName());
#endif
#endif
	if( EQUAL(
#if GDAL_VERSION_MAJOR >= 2
		  poR->GetDriver(iDriver)->GetDescription()
#else
		  poR->GetDriver(iDriver)->GetName()
#endif
		  ,
		  oDriver) )
	  {
	    poDriver = poR->GetDriver(iDriver);
	  }
      }

    if( poDriver == NULL )
      {
	char emessage[8192];
	sprintf( emessage, "Unable to find driver `%s'.\n", oDriver );
	sprintf( emessage,  "%sThe following drivers are available:\n",emessage );
        
	for( iDriver = 0; iDriver < poR->GetDriverCount(); iDriver++ )
	  {
#if GDAL_VERSION_MAJOR >= 2
	    sprintf( emessage,  "%s  -> `%s'\n", emessage, poR->GetDriver(iDriver)->GetDescription() );
#else
	    sprintf( emessage,  "%s  -> `%s'\n", emessage, poR->GetDriver(iDriver)->GetName() );
#endif
	  }

	setMapInMaps(conf,"lenv","message",emessage);
	return SERVICE_FAILED;

      }

#if GDAL_VERSION_MAJOR >=2
    if( !CPLTestBool( CSLFetchNameValueDef(poDriver->GetMetadata(), GDAL_DCAP_CREATE, "FALSE") ) )
#else
    if( !poDriver->TestCapability( ODrCCreateDataSource ) )
#endif
      {
	char emessage[1024];
	sprintf( emessage,  "%s driver does not support data source creation.\n",
		 "json" );
	setMapInMaps(conf,"lenv","message",emessage);
	return SERVICE_FAILED;
      }

    /* -------------------------------------------------------------------- */
    /*      Create the output data source.                                  */
    /* -------------------------------------------------------------------- */
    char *pszDestDataSource=(char*)malloc(100);
    char **papszDSCO=NULL;
    sprintf(pszDestDataSource,"/vsimem/result_%d",getpid());
#if GDAL_VERSION_MAJOR >=2
    poODS = poDriver->Create( pszDestDataSource, 0, 0, 0, GDT_Unknown, papszDSCO );
#else
    poODS = poDriver->CreateDataSource( pszDestDataSource, papszDSCO );
#endif
    if( poODS == NULL ){
      char emessage[1024];      
      sprintf( emessage,  "%s driver failed to create %s\n", 
	       "json", pszDestDataSource );
      setMapInMaps(conf,"lenv","message",emessage);
      return SERVICE_FAILED;
    }

    /* -------------------------------------------------------------------- */
    /*      Create the layer.                                               */
    /* -------------------------------------------------------------------- */
    if( !poODS->TestCapability( ODsCCreateLayer ) )
      {
	char emessage[1024];
	sprintf( emessage, 
		 "Layer %s not found, and CreateLayer not supported by driver.", 
		 "Result" );
	setMapInMaps(conf,"lenv","message",emessage);
	return SERVICE_FAILED;
      }
    
    CPLErrorReset();
    
    OGRLayer *poDstLayer = poODS->CreateLayer( "Result", NULL,wkbPolygon,NULL);
    if( poDstLayer == NULL ){
      setMapInMaps(conf,"lenv","message","Layer creation failed.\n");
      return SERVICE_FAILED;
    }


    for(DelaunayT::Finite_faces_iterator fit = T.finite_faces_begin();
	fit != T.finite_faces_end(); ++fit) {
      DelaunayT::Face_handle face = fit;
      OGRFeatureH hFeature = OGR_F_Create( OGR_L_GetLayerDefn( poDstLayer ) );
      OGRGeometryH hCollection = OGR_G_CreateGeometry( wkbGeometryCollection );
      OGRGeometryH currLine=OGR_G_CreateGeometry(wkbLinearRing);
      OGRGeometryH currPoly=OGR_G_CreateGeometry(wkbPolygon);
      OGR_G_AddPoint_2D(currLine,T.triangle(face)[0].x(),T.triangle(face)[0].y());
      OGR_G_AddPoint_2D(currLine,T.triangle(face)[1].x(),T.triangle(face)[1].y());
      OGR_G_AddPoint_2D(currLine,T.triangle(face)[2].x(),T.triangle(face)[2].y());
      OGR_G_AddPoint_2D(currLine,T.triangle(face)[0].x(),T.triangle(face)[0].y());
      OGR_G_AddGeometryDirectly( currPoly, currLine ); 
      OGR_G_AddGeometryDirectly( hCollection, currPoly ); 
      OGR_F_SetGeometry( hFeature, hCollection ); 
      OGR_G_DestroyGeometry(hCollection);
      if( OGR_L_CreateFeature( poDstLayer, hFeature ) != OGRERR_NONE ){
	setMapInMaps(conf,"lenv","message","Failed to create feature in file.\n");
	return SERVICE_FAILED;
      }
      OGR_F_Destroy( hFeature );
    }
    OGR_DS_Destroy( poODS );

#ifdef DEBUG
    std::cerr << "The Voronoi diagram has " << ns << " finite edges "
	      << " and " << nr << " rays" << std::endl;
#endif

    char *res1=readVSIFile(conf,pszDestDataSource);
    if(res1==NULL)
      return SERVICE_FAILED;

    setMapInMaps(outputs,"Result","value",res1);
    free(res1);

    if(strcmp(oDriver,"GML")==0)
      setMapInMaps(outputs,"Result","mimeType","text/xml");
    else
      setMapInMaps(outputs,"Result","mimeType","application/json");

    setMapInMaps(outputs,"Result","encoding","UTF-8");
    OGRCleanupAll();
    
    return SERVICE_SUCCEEDED;
  }
Пример #10
0
  int tindex(maps*& conf, maps*& inputs,maps*& outputs)
  {
    char *index_filename = NULL;
    const char *tile_index = "location";
    int		i_arg, ti_field;
    OGRDataSourceH hTileIndexDS;
    OGRLayerH hLayer = NULL;
    OGRFeatureDefnH hFDefn;
    int write_absolute_path = FALSE;
    char* current_path = NULL;
    int i;
    int nExistingFiles;
    int skip_different_projection = FALSE;
    char** existingFilesTab = NULL;
    int alreadyExistingProjectionRefValid = FALSE;
    char* alreadyExistingProjectionRef = NULL;
    char* index_filename_mod;
    int bExists;
    VSIStatBuf sStatBuf;

    /* Check that we are running against at least GDAL 1.4 */
    /* Note to developers : if we use newer API, please change the requirement */
    if (atoi(GDALVersionInfo("VERSION_NUM")) < 1400)
      {
	char tmp[1024];
        sprintf(tmp, "At least, GDAL >= 1.4.0 is required for this version of"
		"tindex, which was compiled against GDAL %s\n", GDAL_RELEASE_NAME);
        return SERVICE_FAILED;
      }

    GDALAllRegister();
    OGRRegisterAll();


    /* -------------------------------------------------------------------- */
    /*      Get the directory name to search for raster file to index.      */
    /* -------------------------------------------------------------------- */
    char *tmpDataDir;
    char *pszDataDir;
    map* tmpMap=getMapFromMaps(conf,"main","isTrial");      
    map* tmpMap1=getMapFromMaps(conf,"main","dataPath");
    map* tmpInputMap=getMapFromMaps(inputs,"dir","value");
    if(tmpMap!=NULL && strcasecmp(tmpMap->value,"true")==0){
      pszDataDir=(char*) malloc((strlen(tmpInputMap->value)+strlen(tmpMap1->value)+5+1)*sizeof(char));
      sprintf(pszDataDir,"%s/ftp/%s",tmpMap1->value,tmpInputMap->value);
    }else{
      pszDataDir=(char*) malloc(((strlen(tmpInputMap->value)+1)*sizeof(char)));
      sprintf(pszDataDir,"%s",tmpInputMap->value);
    }
    
    tmpMap=getMapFromMaps(inputs,"iname","value");
    tmpMap1=getMapFromMaps(inputs,"idir","value");
    map* tmpMap2=getMapFromMaps(conf,"main","dataPath");
    if(tmpMap!=NULL && tmpMap1!=NULL && tmpMap2!=NULL){
      index_filename = (char*) malloc((strlen(tmpMap->value)+strlen(tmpMap1->value)+strlen(tmpMap2->value)+12)*sizeof(char));
      sprintf(index_filename,"%s/dirs/%s/%s.shp",tmpMap2->value,tmpMap1->value,tmpMap->value);
    }
    fprintf(stderr,"Filename %s\n",index_filename);
    /* -------------------------------------------------------------------- */
    /*      Open or create the target shapefile and DBF file.               */
    /* -------------------------------------------------------------------- */
    index_filename_mod = CPLStrdup(CPLResetExtension(index_filename, "shp"));

    bExists = (VSIStat(index_filename_mod, &sStatBuf) == 0);
    if (!bExists)
      {
        CPLFree(index_filename_mod);
        index_filename_mod = CPLStrdup(CPLResetExtension(index_filename, "SHP"));
        bExists = (VSIStat(index_filename_mod, &sStatBuf) == 0);
      }
    CPLFree(index_filename_mod);

    if (bExists)
      {
        hTileIndexDS = OGROpen( index_filename, TRUE, NULL );
        if (hTileIndexDS != NULL)
	  {
            hLayer = OGR_DS_GetLayer(hTileIndexDS, 0);
	  }
      }
    else
      {
        OGRSFDriverH hDriver;
        const char* pszDriverName = "ESRI Shapefile";

        fprintf( stderr,"Creating new index file...\n" );
        hDriver = OGRGetDriverByName( pszDriverName );
        if( hDriver == NULL )
	  {
	    char msg[1024];
            sprintf( msg, "%s driver not available.", pszDriverName );
	    setMapInMaps(conf,"lenv","message",msg);
	    return SERVICE_FAILED;
	  }

        hTileIndexDS = OGR_Dr_CreateDataSource( hDriver, index_filename, NULL );
        if (hTileIndexDS)
	  {
            char* pszLayerName = CPLStrdup(CPLGetBasename(index_filename));
            OGRSpatialReferenceH hSpatialRef = NULL;
            GDALDatasetH hDS = GDALOpen( index_filename, GA_ReadOnly );
            if (hDS)
	      {
                const char* pszWKT = GDALGetProjectionRef(hDS);
                if (pszWKT != NULL && pszWKT[0] != '\0')
		  {
                    hSpatialRef = OSRNewSpatialReference(pszWKT);
		  }
                GDALClose(hDS);
	      }

	    DIR *dirp = opendir(pszDataDir);
	    if(dirp==NULL){
	      char tmp1[1024];
	      sprintf(tmp1,_ss("The specified path %s doesn't exist."),pszDataDir);
	      setMapInMaps(conf,"lenv","message",tmp1);
	      return SERVICE_FAILED;
	    }
	    char *res=NULL;
	    struct dirent *dp;
	    tmpMap=getMapFromMaps(inputs,"ext","value");
	    char *ext;
	    if(tmpMap!=NULL)
	      ext=tmpMap->value;
	    while ((dp = readdir(dirp)) != NULL){
	      if(strncmp(dp->d_name,".",1)!=0&&strncmp(dp->d_name,"..",2)!=0){
		char* argv=(char*) malloc((strlen(dp->d_name)+strlen(pszDataDir)+2)*sizeof(char));
		sprintf(argv,"%s/%s",pszDataDir,dp->d_name);
		GDALDatasetH hDS0 = GDALOpen( argv, GA_ReadOnly );
		if (hDS0)
		  {
		    const char* pszWKT = GDALGetProjectionRef(hDS0);
		    fprintf(stderr,"SRS %s \n",pszWKT);
		    if (pszWKT != NULL && pszWKT[0] != '\0')
		      {
			if (hSpatialRef)
			  OSRRelease(hSpatialRef);
			hSpatialRef = OSRNewSpatialReference(pszWKT);
		      }
		    GDALClose(hDS);
		  }
		break;
	      }
	    }
	    closedir(dirp);
            hLayer = OGR_DS_CreateLayer( hTileIndexDS, pszLayerName, hSpatialRef, wkbPolygon, NULL );
            CPLFree(pszLayerName);
            if (hSpatialRef)
	      OSRRelease(hSpatialRef);

            if (hLayer)
	      {
                OGRFieldDefnH hFieldDefn = OGR_Fld_Create( tile_index, OFTString );
                OGR_Fld_SetWidth( hFieldDefn, 255);
                OGR_L_CreateField( hLayer, hFieldDefn, TRUE );
                OGR_Fld_Destroy(hFieldDefn);
	      }
	  }
      }

    if( hTileIndexDS == NULL || hLayer == NULL )
      {
	char msg[1024];
        sprintf( msg, "Unable to open/create shapefile `%s'.", 
                 index_filename );
	setMapInMaps(conf,"lenv","message",msg);
      }

    hFDefn = OGR_L_GetLayerDefn(hLayer);

    for( ti_field = 0; ti_field < OGR_FD_GetFieldCount(hFDefn); ti_field++ )
      {
        OGRFieldDefnH hFieldDefn = OGR_FD_GetFieldDefn( hFDefn, ti_field );
        if( strcmp(OGR_Fld_GetNameRef(hFieldDefn), tile_index) == 0 )
	  break;
      }

    if( ti_field == OGR_FD_GetFieldCount(hFDefn) )
      {
	char msg[1024];
        sprintf( msg, "Unable to find field `%s' in DBF file `%s'.\n", 
                 tile_index, index_filename );
	setMapInMaps(conf,"lenv","message",msg);
	return SERVICE_FAILED;
      }

    /* Load in memory existing file names in SHP */
    nExistingFiles = OGR_L_GetFeatureCount(hLayer, FALSE);
    if (nExistingFiles)
      {
        OGRFeatureH hFeature;
        existingFilesTab = (char**)CPLMalloc(nExistingFiles * sizeof(char*));
        for(i=0;i<nExistingFiles;i++)
	  {
            hFeature = OGR_L_GetNextFeature(hLayer);
            existingFilesTab[i] = CPLStrdup(OGR_F_GetFieldAsString( hFeature, ti_field ));
            if (i == 0)
	      {
                GDALDatasetH hDS = GDALOpen(existingFilesTab[i], GA_ReadOnly );
                if (hDS)
		  {
                    alreadyExistingProjectionRefValid = TRUE;
                    alreadyExistingProjectionRef = CPLStrdup(GDALGetProjectionRef(hDS));
                    GDALClose(hDS);
		  }
	      }
            OGR_F_Destroy( hFeature );
	  }
      }

    if (write_absolute_path)
      {
        current_path = CPLGetCurrentDir();
        if (current_path == NULL)
	  {
            fprintf( stderr, "This system does not support the CPLGetCurrentDir call. "
		     "The option -write_absolute_path will have no effect\n");
            write_absolute_path = FALSE;
	  }
      }

      
    /* -------------------------------------------------------------------- */
    /*      loop over GDAL files, processing.                               */
    /* -------------------------------------------------------------------- */
    DIR *dirp = opendir(pszDataDir);
    if(dirp==NULL){
      char tmp1[1024];
      sprintf(tmp1,_ss("The specified path %s doesn't exist."),pszDataDir);
      setMapInMaps(conf,"lenv","message",tmp1);
      return SERVICE_FAILED;
    }
    char *res=NULL;
    struct dirent *dp;
    tmpMap=getMapFromMaps(inputs,"ext","value");
    char *ext;
    if(tmpMap!=NULL)
      ext=tmpMap->value;
    while ((dp = readdir(dirp)) != NULL){
      
      if(strlen(dp->d_name)>2 && strstr(dp->d_name,".")!=0 && strstr(dp->d_name,ext)>0){
	char* argv=(char*) malloc((strlen(dp->d_name)+strlen(pszDataDir)+2)*sizeof(char));
	sprintf(argv,"%s/%s",pszDataDir,dp->d_name);


        GDALDatasetH	hDS;
        double	        adfGeoTransform[6];
        double		adfX[5], adfY[5];
        int		nXSize, nYSize;
        char* fileNameToWrite;
        const char* projectionRef;
        VSIStatBuf sStatBuf;
        int k;
        OGRFeatureH hFeature;
        OGRGeometryH hPoly, hRing;

        /* Make sure it is a file before building absolute path name */
        if (write_absolute_path && CPLIsFilenameRelative( argv ) &&
            VSIStat( argv, &sStatBuf ) == 0)
	  {
            fileNameToWrite = CPLStrdup(CPLProjectRelativeFilename(current_path, argv));
	  }
        else
	  {
            fileNameToWrite = CPLStrdup(argv);
	  }

        /* Checks that file is not already in tileindex */
        for(i=0;i<nExistingFiles;i++)
	  {
            if (EQUAL(fileNameToWrite, existingFilesTab[i]))
	      {
                fprintf(stderr, "File %s is already in tileindex. Skipping it.\n",
                        fileNameToWrite);
                break;
	      }
	  }
        if (i != nExistingFiles)
	  {
            CPLFree(fileNameToWrite);
            continue;
	  }

        hDS = GDALOpen( argv, GA_ReadOnly );
        if( hDS == NULL )
	  {
            fprintf( stderr, "Unable to open %s, skipping.\n", 
                     argv );
            CPLFree(fileNameToWrite);
	    continue;
	  }

        GDALGetGeoTransform( hDS, adfGeoTransform );
        if( adfGeoTransform[0] == 0.0 
            && adfGeoTransform[1] == 1.0
            && adfGeoTransform[3] == 0.0
            && ABS(adfGeoTransform[5]) == 1.0 )
	  {
            fprintf( stderr, 
                     "It appears no georeferencing is available for\n"
                     "`%s', skipping.\n", 
                     argv );
            GDALClose( hDS );
            CPLFree(fileNameToWrite);
            continue;
	  }

        projectionRef = GDALGetProjectionRef(hDS);
        if (alreadyExistingProjectionRefValid)
	  {
            int projectionRefNotNull, alreadyExistingProjectionRefNotNull;
            projectionRefNotNull = projectionRef && projectionRef[0];
            alreadyExistingProjectionRefNotNull = alreadyExistingProjectionRef && alreadyExistingProjectionRef[0];
            if ((projectionRefNotNull &&
                 alreadyExistingProjectionRefNotNull &&
                 EQUAL(projectionRef, alreadyExistingProjectionRef) == 0) ||
                (projectionRefNotNull != alreadyExistingProjectionRefNotNull))
	      {
                fprintf(stderr, "Warning : %s is not using the same projection system as "
			"other files in the tileindex. This may cause problems when "
			"using it in MapServer for example.%s\n", argv,
			(skip_different_projection) ? " Skipping it" : "");
                if (skip_different_projection)
		  {
                    CPLFree(fileNameToWrite);
                    GDALClose( hDS );
                    continue;
		  }
	      }
	  }
        else
	  {
            alreadyExistingProjectionRefValid = TRUE;
            alreadyExistingProjectionRef = CPLStrdup(projectionRef);
	  }

        nXSize = GDALGetRasterXSize( hDS );
        nYSize = GDALGetRasterYSize( hDS );
        
        adfX[0] = adfGeoTransform[0] 
	  + 0 * adfGeoTransform[1] 
	  + 0 * adfGeoTransform[2];
        adfY[0] = adfGeoTransform[3] 
	  + 0 * adfGeoTransform[4] 
	  + 0 * adfGeoTransform[5];
        
        adfX[1] = adfGeoTransform[0] 
	  + nXSize * adfGeoTransform[1] 
	  + 0 * adfGeoTransform[2];
        adfY[1] = adfGeoTransform[3] 
	  + nXSize * adfGeoTransform[4] 
	  + 0 * adfGeoTransform[5];
        
        adfX[2] = adfGeoTransform[0] 
	  + nXSize * adfGeoTransform[1] 
	  + nYSize * adfGeoTransform[2];
        adfY[2] = adfGeoTransform[3] 
	  + nXSize * adfGeoTransform[4] 
	  + nYSize * adfGeoTransform[5];
        
        adfX[3] = adfGeoTransform[0] 
	  + 0 * adfGeoTransform[1] 
	  + nYSize * adfGeoTransform[2];
        adfY[3] = adfGeoTransform[3] 
	  + 0 * adfGeoTransform[4] 
	  + nYSize * adfGeoTransform[5];
        
        adfX[4] = adfGeoTransform[0] 
	  + 0 * adfGeoTransform[1] 
	  + 0 * adfGeoTransform[2];
        adfY[4] = adfGeoTransform[3] 
	  + 0 * adfGeoTransform[4] 
	  + 0 * adfGeoTransform[5];

        hFeature = OGR_F_Create( OGR_L_GetLayerDefn( hLayer ) );
        OGR_F_SetFieldString( hFeature, ti_field, fileNameToWrite );

        hPoly = OGR_G_CreateGeometry(wkbPolygon);
        hRing = OGR_G_CreateGeometry(wkbLinearRing);
        for(k=0;k<5;k++)
	  OGR_G_SetPoint_2D(hRing, k, adfX[k], adfY[k]);
        OGR_G_AddGeometryDirectly( hPoly, hRing );
        OGR_F_SetGeometryDirectly( hFeature, hPoly );

        if( OGR_L_CreateFeature( hLayer, hFeature ) != OGRERR_NONE )
	  {
	    fprintf( stderr, "Failed to create feature in shapefile.\n" );
	    break;
	  }

        OGR_F_Destroy( hFeature );

        
        CPLFree(fileNameToWrite);

        GDALClose( hDS );
      }
    }
    
    CPLFree(current_path);
    
    if (nExistingFiles)
      {
        for(i=0;i<nExistingFiles;i++)
	  {
            CPLFree(existingFilesTab[i]);
	  }
        CPLFree(existingFilesTab);
      }
    CPLFree(alreadyExistingProjectionRef);

    OGR_DS_Destroy( hTileIndexDS );
    
    GDALDestroyDriverManager();
    OGRCleanupAll();
    setMapInMaps(outputs,"Result","value","Tile index successfully created.");
    //CSLDestroy(argv);
    
    return SERVICE_SUCCEEDED;
  } 
Пример #11
0
  int getSymbols(maps*& conf,maps*& inputs,maps*& outputs)
  {
    FT_Error error = FT_Init_FreeType( &library ); 
    map* tmpMap4Path=getMapFromMaps(conf,"main","dataPath");
    map* tmpMap=getMapFromMaps(inputs,"ttf","value");
    char ttfFile[1024];
    sprintf(ttfFile,"%s/fonts/%s",tmpMap4Path->value,tmpMap->value);
    fprintf(stderr,"File to open : %s\n",ttfFile);
    error = FT_New_Face( library, ttfFile, 0, &face ); 
    if ( error == FT_Err_Unknown_File_Format ){ 
      setMapInMaps(conf,"lenv","message","Error unknow format");
      return SERVICE_FAILED;
    }
    else if ( error ) {
      setMapInMaps(conf,"lenv","message","Unable to load the specified file");
      return SERVICE_FAILED;
    }
    //int *charcodes=(int *)malloc(face->num_glyphs*sizeof(int));
  
  
    //printf("%d|",face->num_glyphs);

    int n;
    FT_CharMap found = 0; 
    FT_CharMap charmap; 
    int disp=0;
    char *charCodes=NULL;
    for ( n = 0; n < face->num_charmaps; n++ ) { 
      charmap = face->charmaps[n];
      //printf("\nplatform_id : %d ; encoding_id %d\n",charmap->platform_id,charmap->encoding_id);
      found = charmap; 
      error = FT_Set_Charmap( face, found ); 	

      FT_UInt  agindex;
      FT_ULong  charcode;
      charcode=FT_Get_First_Char(face,&agindex);
      int count=1;
      if(agindex==0){
	setMapInMaps(conf,"lenv","message","Unable to find anything in your font file");
	return SERVICE_FAILED;
      }
      else{
	char tmp[100];
	if(charCodes==NULL){
	  sprintf(tmp,"%d",charcode);
	  charCodes=(char*)malloc((strlen(tmp)+2)*sizeof(char));
	  sprintf(charCodes,"[%s",tmp);
	}else{
	  sprintf(tmp,",%d",charcode);
	  char *tmp2=strdup(charCodes);
	  charCodes=(char*)realloc(charCodes,(strlen(tmp2)+strlen(tmp)+1)*sizeof(char));
	  memcpy(charCodes+strlen(tmp2),tmp,strlen(tmp)+1);
	  free(tmp2);
	}

	while ( agindex != 0 )                                            
	  {   
	    charcode = FT_Get_Next_Char( face, charcode, &agindex );
	    if(agindex != 0 ){
	      char tmp1[100];
	      sprintf(tmp1,",%d",charcode);
	      char *tmp2=strdup(charCodes);
	      charCodes=(char*)realloc(charCodes,(strlen(tmp2)+strlen(tmp1)+1)*sizeof(char));
	      memcpy(charCodes+strlen(tmp2),tmp1,strlen(tmp1)+1);
	      free(tmp2);
	    }
	  }	
      }
    }
    char *tmp2=strdup(charCodes);
    charCodes=(char*)realloc(charCodes,(strlen(tmp2)+2)*sizeof(char));
    memcpy(charCodes+strlen(tmp2),"]",2);
    free(tmp2);
    //printf("\n**%s**\n",charCodes);
  
    setMapInMaps(outputs,"Result","value",charCodes);
    return SERVICE_SUCCEEDED;
  }
Пример #12
0
  int Gdal_Contour(maps*& conf,maps*& inputs,maps*& outputs)
#endif
{
    fprintf(stderr,"DEBUG HELLO %f %d\n",__FILE__,__LINE__);
    fflush(stderr);
    GDALDatasetH	hSrcDS;
    int i, b3D = FALSE, bNoDataSet = FALSE, bIgnoreNoData = FALSE;
    int nBandIn = 1;
    double dfInterval = 0.0, dfNoData = 0.0, dfOffset = 0.0;
    const char *pszSrcFilename = NULL;
    const char *pszDstFilename = NULL;
    const char *pszElevAttrib = NULL;
    const char *pszFormat = "ESRI Shapefile";
    char        **papszDSCO = NULL, **papszLCO = NULL;
    double adfFixedLevels[1000];
    int    nFixedLevelCount = 0;
    const char *pszNewLayerName = "contour";
    int bQuiet = FALSE;
    GDALProgressFunc pfnProgress = NULL;
    fprintf(stderr,"DEBUG HELLO %f %d\n",__FILE__,__LINE__);
    fflush(stderr);
#ifndef ZOO_SERVICE
    /* Check that we are running against at least GDAL 1.4 */
    /* Note to developers : if we use newer API, please change the requirement */
    if (atoi(GDALVersionInfo("VERSION_NUM")) < 1400)
    {
        fprintf(stderr, "At least, GDAL >= 1.4.0 is required for this version of %s, "
                "which was compiled against GDAL %s\n", argv[0], GDAL_RELEASE_NAME);
        exit(1);
    }
#endif
    GDALAllRegister();
    OGRRegisterAll();

#ifndef ZOO_SERVICE
    argc = GDALGeneralCmdLineProcessor( argc, &argv, 0 );

/* -------------------------------------------------------------------- */
/*      Parse arguments.                                                */
/* -------------------------------------------------------------------- */
    for( i = 1; i < argc; i++ )
    {
        if( EQUAL(argv[i], "--utility_version") )
        {
            printf("%s was compiled against GDAL %s and is running against GDAL %s\n",
                   argv[0], GDAL_RELEASE_NAME, GDALVersionInfo("RELEASE_NAME"));
            return 0;
        }
        else if( EQUAL(argv[i], "--help") )
            Usage();
        else if( EQUAL(argv[i],"-a") )
        {
            CHECK_HAS_ENOUGH_ADDITIONAL_ARGS(1);
            pszElevAttrib = argv[++i];
        }
        else if( EQUAL(argv[i],"-off") )
        {
            CHECK_HAS_ENOUGH_ADDITIONAL_ARGS(1);
            dfOffset = atof(argv[++i]);
        }
        else if( EQUAL(argv[i],"-i") )
        {
            CHECK_HAS_ENOUGH_ADDITIONAL_ARGS(1);
            dfInterval = atof(argv[++i]);
        }
        else if( EQUAL(argv[i],"-fl") )
        {
            if( i >= argc-1 )
                Usage(CPLSPrintf("%s option requires at least 1 argument", argv[i]));
            while( i < argc-1 
                   && nFixedLevelCount 
                             < (int)(sizeof(adfFixedLevels)/sizeof(double))
                   && ArgIsNumeric(argv[i+1]) )
                adfFixedLevels[nFixedLevelCount++] = atof(argv[++i]);
        }
        else if( EQUAL(argv[i],"-b") )
        {
            CHECK_HAS_ENOUGH_ADDITIONAL_ARGS(1);
            nBandIn = atoi(argv[++i]);
        }
        else if( EQUAL(argv[i],"-f") )
        {
            CHECK_HAS_ENOUGH_ADDITIONAL_ARGS(1);
            pszFormat = argv[++i];
        }
        else if( EQUAL(argv[i],"-dsco") )
        {
            CHECK_HAS_ENOUGH_ADDITIONAL_ARGS(1);
            papszDSCO = CSLAddString(papszDSCO, argv[++i] );
        }
        else if( EQUAL(argv[i],"-lco") )
        {
            CHECK_HAS_ENOUGH_ADDITIONAL_ARGS(1);
            papszLCO = CSLAddString(papszLCO, argv[++i] );
        }
        else if( EQUAL(argv[i],"-3d")  )
        {
            b3D = TRUE;
        }
        else if( EQUAL(argv[i],"-snodata") )
        {
            CHECK_HAS_ENOUGH_ADDITIONAL_ARGS(1);
            bNoDataSet = TRUE;
            dfNoData = atof(argv[++i]);
        }
        else if( EQUAL(argv[i],"-nln") )
        {
            CHECK_HAS_ENOUGH_ADDITIONAL_ARGS(1);
            pszNewLayerName = argv[++i];
        }
        else if( EQUAL(argv[i],"-inodata") )
        {
            bIgnoreNoData = TRUE;
        }
        else if ( EQUAL(argv[i],"-q") || EQUAL(argv[i],"-quiet") )
        {
            bQuiet = TRUE;
        }
        else if( pszSrcFilename == NULL )
        {
            pszSrcFilename = argv[i];
        }
        else if( pszDstFilename == NULL )
        {
            pszDstFilename = argv[i];
        }
        else
            Usage("Too many command options.");
    }
#else
    bQuiet = TRUE;
    bIgnoreNoData = TRUE;
    map* tmpMap=NULL;
    tmpMap=NULL;
    tmpMap=getMapFromMaps(inputs,"a","value");
    if(tmpMap!=NULL && strncmp(tmpMap->value,"NULL",4)!=0){
      pszElevAttrib = strdup(tmpMap->value);
    }
    tmpMap=getMapFromMaps(inputs,"off","value");
    if(tmpMap!=NULL && strncmp(tmpMap->value,"NULL",4)!=0){
      dfOffset = atof(tmpMap->value);
    }
    tmpMap=getMapFromMaps(inputs,"i","value");
    if(tmpMap!=NULL && strncmp(tmpMap->value,"NULL",4)!=0){
      dfInterval = atof(tmpMap->value);
    }
    tmpMap=getMapFromMaps(inputs,"b","value");
    if(tmpMap!=NULL && strncmp(tmpMap->value,"NULL",4)!=0){
      nBandIn = atoi(tmpMap->value);
    }
    tmpMap=getMapFromMaps(inputs,"InputDSN","value");
    if(tmpMap!=NULL && strncmp(tmpMap->value,"NULL",4)!=0){
      pszSrcFilename = strdup(tmpMap->value);
    }
    tmpMap=getMapFromMaps(inputs,"OutputDSN","value");
    if(tmpMap!=NULL && strncmp(tmpMap->value,"NULL",4)!=0){
      pszDstFilename = strdup(tmpMap->value);
    }
#endif
    if( dfInterval == 0.0 && nFixedLevelCount == 0 )
    {
        Usage("Neither -i nor -fl are specified.");
    }

    if (pszSrcFilename == NULL)
    {
        Usage("Missing source filename.");
    }

    if (pszDstFilename == NULL)
    {
        Usage("Missing destination filename.");
    }
    
    if (!bQuiet)
        pfnProgress = GDALTermProgress;

/* -------------------------------------------------------------------- */
/*      Open source raster file.                                        */
/* -------------------------------------------------------------------- */
    GDALRasterBandH hBand;

    hSrcDS = GDALOpen( pszSrcFilename, GA_ReadOnly );
    if( hSrcDS == NULL ){
#ifndef ZOO_SERVICE
        exit( 2 );
#else
	setMapInMaps(conf,"lenv","message","Unable to open the file");
#endif
    }
    hBand = GDALGetRasterBand( hSrcDS, nBandIn );
    if( hBand == NULL )
    {
#ifndef ZOO_SERVICE
        CPLError( CE_Failure, CPLE_AppDefined, 
                  "Band %d does not exist on dataset.", 
                  nBandIn );
        exit(2);
#else
	char tmp[1024];
	sprintf(tmp,"Band %d does not exist on dataset.",nBandIn);
	setMapInMaps(conf,"lenv","message",tmp);
	return SERVICE_FAILED;
#endif
    }

    if( !bNoDataSet && !bIgnoreNoData )
        dfNoData = GDALGetRasterNoDataValue( hBand, &bNoDataSet );

/* -------------------------------------------------------------------- */
/*      Try to get a coordinate system from the raster.                 */
/* -------------------------------------------------------------------- */
    OGRSpatialReferenceH hSRS = NULL;

    const char *pszWKT = GDALGetProjectionRef( hSrcDS );

    if( pszWKT != NULL && strlen(pszWKT) != 0 )
        hSRS = OSRNewSpatialReference( pszWKT );

/* -------------------------------------------------------------------- */
/*      Create the outputfile.                                          */
/* -------------------------------------------------------------------- */
    OGRDataSourceH hDS;
    OGRSFDriverH hDriver = OGRGetDriverByName( pszFormat );
    OGRFieldDefnH hFld;
    OGRLayerH hLayer;

    if( hDriver == NULL )
    {
#ifndef ZOO_SERVICE
        fprintf( stderr, "Unable to find format driver named %s.\n", 
                 pszFormat );
        exit( 10 );
#else
	char tmp[1024];
        sprintf( tmp, "Unable to find format driver named %s.\n", pszFormat );	
	setMapInMaps(conf,"lenv","message",tmp);
	return SERVICE_FAILED;
#endif
    }

    hDS = OGR_Dr_CreateDataSource( hDriver, pszDstFilename, papszDSCO );
    if( hDS == NULL ){
#ifndef ZOO_SERVICE
        exit( 1 );
#else
	setMapInMaps(conf,"lenv","message","Unable to create the file");
	return SERVICE_FAILED;
#endif
    }

    hLayer = OGR_DS_CreateLayer( hDS, pszNewLayerName, hSRS, 
                                 b3D ? wkbLineString25D : wkbLineString,
                                 papszLCO );
    if( hLayer == NULL )
        exit( 1 );

    hFld = OGR_Fld_Create( "ID", OFTInteger );
    OGR_Fld_SetWidth( hFld, 8 );
    OGR_L_CreateField( hLayer, hFld, FALSE );
    OGR_Fld_Destroy( hFld );

    if( pszElevAttrib )
    {
        hFld = OGR_Fld_Create( pszElevAttrib, OFTReal );
        OGR_Fld_SetWidth( hFld, 12 );
        OGR_Fld_SetPrecision( hFld, 3 );
        OGR_L_CreateField( hLayer, hFld, FALSE );
        OGR_Fld_Destroy( hFld );
    }

/* -------------------------------------------------------------------- */
/*      Invoke.                                                         */
/* -------------------------------------------------------------------- */
    CPLErr eErr;
    
    eErr = GDALContourGenerate( hBand, dfInterval, dfOffset, 
                         nFixedLevelCount, adfFixedLevels,
                         bNoDataSet, dfNoData, hLayer, 
                         OGR_FD_GetFieldIndex( OGR_L_GetLayerDefn( hLayer ), 
                                               "ID" ), 
                         (pszElevAttrib == NULL) ? -1 :
                                 OGR_FD_GetFieldIndex( OGR_L_GetLayerDefn( hLayer ), 
                                                       pszElevAttrib ), 
                         pfnProgress, NULL );

    OGR_DS_Destroy( hDS );
    GDALClose( hSrcDS );

    if (hSRS)
        OSRDestroySpatialReference( hSRS );

#ifndef ZOO_SERVICE
    CSLDestroy( argv );
    CSLDestroy( papszDSCO );
    CSLDestroy( papszLCO );
    GDALDestroyDriverManager();
    OGRCleanupAll();
    return 0;
#else
    GDALDestroyDriverManager();
    OGRCleanupAll();
    char tmp[1024];
    sprintf(tmp,"File %s successfully created.",pszDstFilename);
    setMapInMaps(outputs,"Result","value",tmp);
    return SERVICE_SUCCEEDED;
#endif
}
Пример #13
0
/**
 * Try to load file from cache or download a remote file if not in cache
 *
 * @param m the maps containing the settings of the main.cfg file
 * @param content the map to update
 * @param hInternet the HINTERNET pointer
 * @param url the url to fetch
 * @return 0
 */
int loadRemoteFile(maps** m,map** content,HINTERNET* hInternet,char *url){
  char* fcontent = NULL;
  char* cached=isInCache(*m,url);
  char *mimeType=NULL;
  int fsize=0;

  map* t=getMap(*content,"xlink:href");
  if(t==NULL){
    t=getMap((*content),"href");
    addToMap(*content,"xlink:href",url);
  }

  if(cached!=NULL){

    struct stat f_status;
    int s=stat(cached, &f_status);
    if(s==0){
      fcontent=(char*)malloc(sizeof(char)*(f_status.st_size+1));
      FILE* f=fopen(cached,"rb");
      fread(fcontent,f_status.st_size,1,f);
      fsize=f_status.st_size;
      fcontent[fsize]=0;
      fclose(f);
      addToMap(*content,"cache_file",cached);
    }
    cached[strlen(cached)-1]='m';
    s=stat(cached, &f_status);
    if(s==0){
      mimeType=(char*)malloc(sizeof(char)*(f_status.st_size+1));
      FILE* f=fopen(cached,"rb");
      fread(mimeType,f_status.st_size,1,f);
      mimeType[f_status.st_size]=0;
      fclose(f);
    }

  }else{    
    addRequestToQueue(m,hInternet,url,true);
    return 0;
  }
  if(fsize==0){
    return errorException(*m, _("Unable to download the file."), "InternalError",NULL);
  }
  if(mimeType!=NULL){
    addToMap(*content,"fmimeType",mimeType);
  }

  map* tmpMap=getMapOrFill(content,"value","");
    
  free(tmpMap->value);
  tmpMap->value=(char*)malloc((fsize+1)*sizeof(char));
  if(tmpMap->value==NULL || fcontent == NULL)
    return errorException(*m, _("Unable to allocate memory"), "InternalError",NULL);
  memcpy(tmpMap->value,fcontent,(fsize+1)*sizeof(char));

  char ltmp1[256];
  sprintf(ltmp1,"%d",fsize);
  addToMap(*content,"size",ltmp1);
  if(cached==NULL){
    addToCache(*m,url,fcontent,mimeType,fsize, NULL, 0);
  }
  else{
    addToMap(*content,"isCached","true");
    map* tmp=getMapFromMaps(*m,"main","cacheDir");
    if(tmp!=NULL){
      map *c=getMap((*content),"xlink:href");
      char* md5str=getMd5(c->value);
      char* fname=(char*)malloc(sizeof(char)*(strlen(tmp->value)+strlen(md5str)+6));
      sprintf(fname,"%s/%s.zca",tmp->value,md5str);
      addToMap(*content,"cache_file",fname);
      free(fname);
    }
  }
  free(fcontent);
  free(mimeType);
  free(cached);
  return 0;
}
Пример #14
0
/**
 * Read the downloaded file for a specific input
 *
 * @param m the maps containing the settings of the main.cfg file
 * @param in the input
 * @param index the input index
 * @param hInternet the internet connection
 * @param error the error map pointer
 * @return 0 in case of success, -1 in case of failure
 */
int readCurrentInput(maps** m,maps** in,int* index,HINTERNET* hInternet,map** error){
  map* tmp1;
  char sindex[5];
  maps* content=*in;
  map* length=getMap(content->content,"length");
  int shouldClean=-1;
  if(length==NULL){
    length=createMap("length","1");
    shouldClean=1;
  }
  for(int i=0;i<atoi(length->value);i++){
    char* fcontent;
    char *mimeType=NULL;
    int fsize=0;
    char cname[15];
    char vname[11];
    char vname1[11];
    char sname[9];
    char mname[15];
    char icname[14];
    char xname[16];
    char oname[12];
    if(*index>0)
      sprintf(vname1,"value_%d",*index);
    else
      sprintf(vname1,"value");
    
    if(i>0){
      tmp1=getMap(content->content,cname);
      sprintf(cname,"cache_file_%d",i);
      sprintf(vname,"value_%d",i);
      sprintf(sname,"size_%d",i);
      sprintf(mname,"mimeType_%d",i);
      sprintf(icname,"isCached_%d",i);
      sprintf(xname,"Reference_%d",i);
      sprintf(oname,"Order_%d",i);
    }else{
      sprintf(cname,"cache_file");
      sprintf(vname,"value");
      sprintf(sname,"size");
      sprintf(mname,"mimeType");
      sprintf(icname,"isCached");
      sprintf(xname,"Reference");
      sprintf(oname,"Order");
    }
    
    map* tmap=getMap(content->content,oname);
    sprintf(sindex,"%d",*index+1);
    if((tmp1=getMap(content->content,xname))!=NULL && tmap!=NULL && strcasecmp(tmap->value,sindex)==0){
      
      if(getMap(content->content,icname)==NULL){
	fcontent=(char*)malloc((hInternet->ihandle[*index].nDataLen+1)*sizeof(char));
	if(fcontent == NULL){
	  errorException(*m, _("Unable to allocate memory"), "InternalError",NULL);
	  return -1;
	}
	size_t dwRead;
	InternetReadFile(hInternet->ihandle[*index], 
			 (LPVOID)fcontent, 
			 hInternet->ihandle[*index].nDataLen, 
			 &dwRead);
	fcontent[hInternet->ihandle[*index].nDataLen]=0;
	fsize=hInternet->ihandle[*index].nDataLen;
	if(hInternet->ihandle[*index].mimeType==NULL)
	  mimeType=zStrdup("none");
	else
	  mimeType=zStrdup(hInternet->ihandle[*index].mimeType);	      
	
	map* tmpMap=getMapOrFill(&(*in)->content,vname,"");
	free(tmpMap->value);
	tmpMap->value=(char*)malloc((fsize+1)*sizeof(char));
	if(tmpMap->value==NULL){
	  return errorException(*m, _("Unable to allocate memory"), "InternalError",NULL);
	}
	memcpy(tmpMap->value,fcontent,(fsize+1)*sizeof(char));
	if(hInternet->ihandle[*index].code!=200){
	  const char *error_rep_str=_("Unable to download the file for the input <%s>, response code was : %d.");
	  char *error_msg=(char*)malloc((strlen(error_rep_str)+strlen(content->name)+4)*sizeof(char));
	  sprintf(error_msg,error_rep_str,content->name,hInternet->ihandle[*index].code);
	  if(*error==NULL){
	    *error=createMap("text",error_msg);
	    addToMap(*error,"locator",content->name);
	    addToMap(*error,"code","InvalidParameterValue");
	  }else{
	    int nb=1;
	    map* tmpMap=getMap(*error,"length");
	    if(tmpMap!=NULL)
	      nb=atoi(tmpMap->value);
	    setMapArray(*error,"text",nb,error_msg);
	    setMapArray(*error,"locator",nb,content->name);
	    setMapArray(*error,"code",nb,"InvalidParameterValue");
	  }
	  return -1;
	}
	
	char ltmp1[256];
	sprintf(ltmp1,"%d",fsize);
	map* tmp=getMapFromMaps(*m,"main","cacheDir");
	if(tmp!=NULL){
	  char* md5str=getMd5(tmp1->value);
	  char* fname=(char*)malloc(sizeof(char)*(strlen(tmp->value)+strlen(md5str)+6));
	  sprintf(fname,"%s/%s.zca",tmp->value,md5str);
	  addToMap((*in)->content,cname,fname);
	  free(fname);
	}
	addToMap((*in)->content,sname,ltmp1);
	addToMap((*in)->content,mname,mimeType);
	addToCache(*m,tmp1->value,fcontent,mimeType,fsize, NULL, 0);
	free(fcontent);
	free(mimeType);
	*index++;
	
      }
    }
  }
  if(shouldClean>0){
    freeMap(&length);
    free(length);
  }
  return 0;
}