source: trunk/zoo-project/zoo-kernel/service_internal_ms.c @ 370

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

Add the capability to use a specific Python version by detecting if python-VERS-config exists or if python-config-VERS exists. Add NEED_STRCASESTR to nmake.opt for MapServer? support. Fix for the name of layer class on Unix/Windows?. Provide definition of strcasestr if and only if MapServer? was not activated.

  • Property svn:eol-style set to native
  • Property svn:mime-type set to text/x-csrc
File size: 32.5 KB
Line 
1#ifdef USE_MS
2#ifndef WIN32
3#define CLASS class
4#else
5#define CLASS _class
6#endif
7#include "service_internal_ms.h"
8
9/**
10 * Map composed by a main.cfg maps name as key and the corresponding
11 * MapServer Mafile Metadata name to use
12 * see doc from here :
13 *  - http://mapserver.org/ogc/wms_server.html
14 *  - http://mapserver.org/ogc/wfs_server.html
15 *  - http://mapserver.org/ogc/wcs_server.html
16 */
17map* getCorrespondance(){
18  map* res=createMap("encoding","ows_encoding");
19  addToMap(res,"abstract","ows_abstract");
20  addToMap(res,"title","ows_title");
21  addToMap(res,"keywords","ows_keywordlist");
22  addToMap(res,"fees","ows_fees");
23  addToMap(res,"accessConstraints","ows_accessconstraints");
24  addToMap(res,"providerName","ows_attribution_title");
25  addToMap(res,"providerSite","ows_service_onlineresource");
26  addToMap(res,"individualName","ows_contactperson");
27  addToMap(res,"positionName","ows_contactposition");
28  addToMap(res,"providerName","ows_contactorganization");
29  addToMap(res,"role","ows_role");
30  addToMap(res,"addressType","ows_addresstype");
31  addToMap(res,"addressCity","ows_city");
32  addToMap(res,"addressDeliveryPoint","ows_address");
33  addToMap(res,"addressPostalCode","ows_postcode");
34  addToMap(res,"addressAdministrativeArea","ows_stateorprovince");
35  addToMap(res,"addressCountry","ows_country");
36  addToMap(res,"phoneVoice","ows_contactvoicetelephone");
37  addToMap(res,"phoneFacsimile","ows_contactfacsimiletelephone");
38  addToMap(res,"addressElectronicMailAddress","ows_contactelectronicmailaddress");
39  // Missing Madatory Informations
40  addToMap(res,"hoursOfService","ows_hoursofservice");
41  addToMap(res,"contactInstructions","ows_contactinstructions");
42  return res;
43}
44
45void setMapSize(maps* output,double minx,double miny,double maxx,double maxy){
46  double maxWidth=640;
47  double maxHeight=480;
48  double deltaX=maxx-minx;
49  double deltaY=maxy-miny;
50  double qWidth;
51  qWidth=maxWidth/deltaX;
52  double qHeight;
53  qHeight=maxHeight/deltaY;
54#ifdef DEBUGMS
55  fprintf(stderr,"deltaX : %.15f \ndeltaY : %.15f\n",deltaX,deltaY);
56  fprintf(stderr,"qWidth : %.15f \nqHeight : %.15f\n",qWidth,qHeight);
57#endif
58
59  double width=deltaX*qWidth;
60  double height=height=deltaY*qWidth;
61  if(deltaX<deltaY){
62    width=deltaX*qHeight;
63    height=deltaY*qHeight;
64  }
65  if(height<0)
66    height=-height;
67  if(width<0)
68    width=-width;
69  char sWidth[1024];
70  char sHeight[1024];
71  sprintf(sWidth,"%.3f",width);
72  sprintf(sHeight,"%.3f",height);
73#ifdef DEBUGMS
74  fprintf(stderr,"sWidth : %.15f \nsHeight : %.15f\n",sWidth,sHeight);
75#endif
76  if(output!=NULL){
77    addToMap(output->content,"width",sWidth);
78    addToMap(output->content,"height",sHeight);
79  }
80}
81
82void setReferenceUrl(maps* m,maps* tmpI){
83  //dumpMaps(tmpI);
84  outputMapfile(m,tmpI);
85  map *msUrl=getMapFromMaps(m,"main","mapserverAddress");
86  map *msOgcVersion=getMapFromMaps(m,"main","msOgcVersion");
87  map *dataPath=getMapFromMaps(m,"main","dataPath");
88  map *sid=getMapFromMaps(m,"lenv","sid");
89  map* format=getMap(tmpI->content,"mimeType");
90  map* rformat=getMap(tmpI->content,"requestedMimeType");
91  map* width=getMap(tmpI->content,"width");
92  map* height=getMap(tmpI->content,"height");
93  map* protoMap=getMap(tmpI->content,"msOgc");
94  map* versionMap=getMap(tmpI->content,"msOgcVersion");
95  char options[3][5][25]={
96    {"WMS","1.3.0","GetMap","layers=%s","wms_extent"},
97    {"WFS","1.1.0","GetFeature","typename=%s","wms_extent"},
98    {"WCS","1.1.0","GetCoverage","coverage=%s","wcs_extent"}
99  };
100  int proto=0;
101  if(rformat==NULL){
102    rformat=getMap(tmpI->content,"mimeType");
103  }
104  if(strncasecmp(rformat->value,"text/xml",8)==0)
105    proto=1;
106  if(strncasecmp(rformat->value,"image/tiff",10)==0)
107    proto=2;
108  if(protoMap!=NULL)
109    if(strncasecmp(protoMap->value,"WMS",3)==0)
110      proto=0;
111    else if(strncasecmp(protoMap->value,"WFS",3)==0)
112      proto=1;
113    else 
114      proto=2;
115 
116  char *protoVersion=options[proto][1];
117  if(proto==1){
118    if(msOgcVersion!=NULL)
119      protoVersion=msOgcVersion->value;
120    if(versionMap!=NULL)
121      protoVersion=versionMap->value;
122  }
123
124  map* extent=getMap(tmpI->content,options[proto][4]);
125  map* crs=getMap(tmpI->content,"crs");
126  char layers[128];
127  sprintf(layers,options[proto][3],tmpI->name);
128
129  char* webService_url=(char*)malloc((strlen(msUrl->value)+strlen(format->value)+strlen(tmpI->name)+strlen(width->value)+strlen(height->value)+strlen(extent->value)+256)*sizeof(char));
130
131  if(proto>0){
132    sprintf(webService_url,
133            "%s?map=%s/%s_%s.map&request=%s&service=%s&version=%s&%s&format=%s&bbox=%s&crs=%s",
134            msUrl->value,
135            dataPath->value,
136            tmpI->name,
137            sid->value,
138            options[proto][2],
139            options[proto][0],
140            protoVersion,
141            layers,
142            rformat->value,
143            extent->value,
144            crs->value
145            );
146  }
147  else{
148    sprintf(webService_url,
149            "%s?map=%s/%s_%s.map&request=%s&service=%s&version=%s&%s&width=%s&height=%s&format=%s&bbox=%s&crs=%s",
150            msUrl->value,
151            dataPath->value,
152            tmpI->name,
153            sid->value,
154            options[proto][2],
155            options[proto][0],
156            protoVersion,
157            layers,
158            width->value,
159            height->value,
160            rformat->value,
161            extent->value,
162            crs->value
163            );
164  }
165  addToMap(tmpI->content,"Reference",webService_url);
166
167}
168
169/**
170 * Set projection using Authority Code and Name if available or fallback to
171 * proj4 definition if available or fallback to default EPSG:4326
172 */
173void setSrsInformations(maps* output,mapObj* m,layerObj* myLayer,
174                        char* pszProjection){
175  OGRSpatialReferenceH  hSRS;
176  map* msSrs=NULL;
177  hSRS = OSRNewSpatialReference(NULL);
178  if( pszProjection!=NULL && strlen(pszProjection)>1 &&
179      OSRImportFromWkt( hSRS, &pszProjection ) == CE_None ){
180    char *proj4Str=NULL;
181    if(OSRGetAuthorityName(hSRS,NULL)!=NULL && 
182       OSRGetAuthorityCode(hSRS,NULL)!=NULL){
183      char tmpSrs[20];
184      sprintf(tmpSrs,"%s:%s",
185              OSRGetAuthorityName(hSRS,NULL),OSRGetAuthorityCode(hSRS,NULL));
186      msLoadProjectionStringEPSG(&m->projection,tmpSrs);
187      msLoadProjectionStringEPSG(&myLayer->projection,tmpSrs);
188     
189      char tmpSrss[256];
190      sprintf(tmpSrss,"EPSG:4326 EPSG:900913 %s",tmpSrs);
191
192      msInsertHashTable(&(m->web.metadata), "ows_srs", tmpSrss);
193      msInsertHashTable(&(myLayer->metadata), "ows_srs", tmpSrss);
194
195#ifdef DEBUGMS
196      fprintf(stderr,"isGeo %b\n\n",OSRIsGeographic(hSRS)==TRUE);
197#endif
198      if(output!=NULL){
199        if(OSRIsGeographic(hSRS)==TRUE)
200          addToMap(output->content,"crs_isGeographic","true");
201        else
202          addToMap(output->content,"crs_isGeographic","false");
203        addToMap(output->content,"crs",tmpSrs);
204      }
205    }
206    else{
207      OSRExportToProj4(hSRS,&proj4Str);
208      if(proj4Str!=NULL){
209#ifdef DEBUGMS
210        fprintf(stderr,"PROJ (%s)\n",proj4Str);
211#endif
212        msLoadProjectionString(&(m->projection),proj4Str);
213        msLoadProjectionString(&(myLayer->projection),proj4Str);
214        if(output!=NULL){ 
215          if(OSRIsGeographic(hSRS)==TRUE)
216            addToMap(output->content,"crs_isGeographic","true");
217          else
218            addToMap(output->content,"crs_isGeographic","false");
219        }
220      }
221      else{
222        msLoadProjectionStringEPSG(&m->projection,"EPSG:4326");
223        msLoadProjectionStringEPSG(&myLayer->projection,"EPSG:4326");
224        if(output!=NULL){
225          addToMap(output->content,"crs_isGeographic","true");
226        }
227      }
228      if(output!=NULL){
229        addToMap(output->content,"crs","EPSG:4326");
230        addToMap(output->content,"real_extent","true");
231      }
232      msInsertHashTable(&(m->web.metadata),"ows_srs", "EPSG:4326 EPSG:900913");
233      msInsertHashTable(&(myLayer->metadata),"ows_srs","EPSG:4326 EPSG:900913");
234
235
236    }
237  }
238  else{
239    if(output!=NULL){
240      msSrs=getMap(output->content,"msSrs");
241    }
242    if(msSrs!=NULL){
243      msLoadProjectionStringEPSG(&m->projection,msSrs->value);
244      msLoadProjectionStringEPSG(&myLayer->projection,msSrs->value);
245      char tmpSrs[128];
246      sprintf(tmpSrs,"%s EPSG:4326 EPSG:900913",msSrs);
247      msInsertHashTable(&(m->web.metadata),"ows_srs",tmpSrs);
248      msInsertHashTable(&(myLayer->metadata),"ows_srs",tmpSrs);
249    }else{
250      msLoadProjectionStringEPSG(&m->projection,"EPSG:4326");
251      msLoadProjectionStringEPSG(&myLayer->projection,"EPSG:4326");
252      msInsertHashTable(&(m->web.metadata),"ows_srs","EPSG:4326 EPSG:900913");
253      msInsertHashTable(&(myLayer->metadata),"ows_srs","EPSG:4326 EPSG:900913");
254    }
255    if(output!=NULL){
256      addToMap(output->content,"crs",msSrs->value);
257      addToMap(output->content,"crs_isGeographic","true");
258    }
259  }
260
261  OSRDestroySpatialReference( hSRS );
262}
263
264void setMsExtent(maps* output,mapObj* m,layerObj* myLayer,
265                 double minX,double minY,double maxX,double maxY){
266  msMapSetExtent(m,minX,minY,maxX,maxY);
267#ifdef DEBUGMS
268  fprintf(stderr,"Extent %.15f %.15f %.15f %.15f\n",minX,minY,maxX,maxY);
269#endif
270  char tmpExtent[1024];
271  sprintf(tmpExtent,"%.15f %.15f %.15f %.15f",minX,minY,maxX,maxY);
272#ifdef DEBUGMS
273  fprintf(stderr,"Extent %s\n",tmpExtent);
274#endif
275  msInsertHashTable(&(myLayer->metadata), "ows_extent", tmpExtent);
276 
277  if(output!=NULL){
278
279    map* test=getMap(output->content,"real_extent");
280    if(test!=NULL){
281      pointObj min, max;
282      projectionObj tempSrs;
283
284      min.x = m->extent.minx;
285      min.y = m->extent.miny;
286      max.x = m->extent.maxx;
287      max.y = m->extent.maxy;
288      char tmpSrsStr[1024];
289
290
291      msInitProjection(&tempSrs);
292      msLoadProjectionStringEPSG(&tempSrs,"EPSG:4326");
293
294      msProjectPoint(&(m->projection),&tempSrs,&min);
295      msProjectPoint(&m->projection,&tempSrs,&max);
296     
297      sprintf(tmpExtent,"%.3f,%.3f,%.3f,%.3f",min.y,min.x,max.y,max.x);
298      map* isGeo=getMap(output->content,"crs_isGeographic");
299      fprintf(stderr,"isGeo = %s\n",isGeo->value);
300      if(isGeo!=NULL && strcasecmp("true",isGeo->value)==0)
301        sprintf(tmpExtent,"%f,%f,%f,%f", minY,minX, maxY, maxX);
302      addToMap(output->content,"wms_extent",tmpExtent);
303      sprintf(tmpSrsStr,"%.3f,%.3f,%.3f,%.3f",min.x,min.y,max.x,max.y);
304      addToMap(output->content,"wcs_extent",tmpExtent);
305      //dumpMap(output->content);
306
307    }else{
308      sprintf(tmpExtent,"%f,%f,%f,%f",minX, minY, maxX, maxY);
309      map* isGeo=getMap(output->content,"crs_isGeographic");
310      fprintf(stderr,"isGeo = %s\n",isGeo->value);
311      if(isGeo!=NULL && strcasecmp("true",isGeo->value)==0)
312        sprintf(tmpExtent,"%f,%f,%f,%f", minY,minX, maxY, maxX);
313      addToMap(output->content,"wms_extent",tmpExtent); 
314      sprintf(tmpExtent,"%.3f,%.3f,%.3f,%.3f",minX,minY,maxX,maxY);
315      addToMap(output->content,"wcs_extent",tmpExtent);
316     
317    }
318
319  }
320
321  setMapSize(output,minX,minY,maxX,maxY);
322}
323
324int tryOgr(maps* conf,maps* output,mapObj* m){
325
326  map* tmpMap=getMap(output->content,"storage");
327  char *pszDataSource=tmpMap->value;
328
329  /**
330   * Try to open the DataSource using OGR
331   */
332  OGRRegisterAll();
333  /**
334   * Try to load the file as ZIP
335   */
336
337  OGRDataSourceH poDS1 = NULL;
338  OGRSFDriverH *poDriver1 = NULL;
339  char *dsName=(char*)malloc((8+strlen(pszDataSource)+1)*sizeof(char));
340  char *odsName=strdup(pszDataSource);
341  char *sdsName=strdup(pszDataSource);
342  char *demo=strstr(odsName,".");
343  sdsName[strlen(sdsName)-(strlen(demo)-1)]='d';
344  sdsName[strlen(sdsName)-(strlen(demo)-2)]='i';
345  sdsName[strlen(sdsName)-(strlen(demo)-3)]='r';
346  sdsName[strlen(sdsName)-(strlen(demo)-4)]=0;
347
348  odsName[strlen(odsName)-(strlen(demo)-1)]='z';
349  odsName[strlen(odsName)-(strlen(demo)-2)]='i';
350  odsName[strlen(odsName)-(strlen(demo)-3)]='p';
351  odsName[strlen(odsName)-(strlen(demo)-4)]=0;
352  sprintf(dsName,"/vsizip/%s",odsName);
353
354#ifdef DEBUGMS
355  fprintf(stderr,"Try loading %s, %s, %s\n",dsName,odsName,dsName);
356#endif
357
358  FILE* file = fopen(pszDataSource, "rb");
359  FILE* fileZ = fopen(odsName, "wb");
360  fseek(file, 0, SEEK_END);
361  unsigned long fileLen=ftell(file);
362  fseek(file, 0, SEEK_SET);
363  char *buffer=(char *)malloc(fileLen+1);
364  fread(buffer, fileLen, 1, file);
365  fwrite(buffer,fileLen, 1, fileZ);
366  fclose(file);
367  fclose(fileZ);
368  free(buffer);
369  fprintf(stderr,"Try loading %s",dsName);
370  poDS1 = OGROpen( dsName, FALSE, poDriver1 );
371  if( poDS1 == NULL ){
372    fprintf(stderr,"Unable to access the DataSource as ZIP File\n");
373    setMapInMaps(conf,"lenv","message","Unable to open datasource in read only mode");
374    OGR_DS_Destroy(poDS1);
375  }else{
376    fprintf(stderr,"The DataSource is a  ZIP File\n");
377    char** demo=VSIReadDir(dsName);
378    int i=0;
379    mkdir(sdsName
380#ifndef WIN32
381                ,S_IRWXU | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH
382#endif
383                );
384    while(demo[i]!=NULL){
385      fprintf(stderr,"ZIP File content : %s\n",demo[i]);
386      char *tmpDs=(char*)malloc((strlen(dsName)+strlen(demo[i])+2)*sizeof(char));
387      sprintf(tmpDs,"%s/%s",dsName,demo[i]);
388      fprintf(stderr,"read : %s\n",tmpDs);
389     
390      VSILFILE* vsif=VSIFOpenL(tmpDs,"rb");
391      fprintf(stderr,"open : %s\n",tmpDs);
392      VSIFSeekL(vsif,0,SEEK_END);
393      int size=VSIFTellL(vsif);
394      fprintf(stderr,"size : %d\n",size);
395      VSIFSeekL(vsif,0,SEEK_SET);
396      char *vsifcontent=(char*) malloc((size+1)*sizeof(char));
397      VSIFReadL(vsifcontent,1,size,vsif);
398      char *fpath=(char*) malloc((strlen(sdsName)+strlen(demo[1])+2)*sizeof(char));
399      sprintf(fpath,"%s/%s",sdsName,demo[i]);
400      int f=open(fpath,O_WRONLY|O_CREAT,S_IRUSR|S_IWUSR|S_IRGRP|S_IWGRP|S_IROTH|S_IWOTH);
401      write(f,vsifcontent,size);
402      close(f);
403      chmod(fpath,S_IRWXU | S_IRGRP | S_IXGRP | S_IROTH);
404      char* tmpP=strstr(fpath,".shp");
405      if(tmpP==NULL)
406        tmpP=strstr(fpath,".SHP");
407      if(tmpP!=NULL){
408        fprintf(stderr,"*** DEBUG %s\n",strstr(tmpP,"."));
409        if( strcmp(tmpP,".shp")==0 || strcmp(tmpP,".SHP")==0 ){
410          tmpMap=getMap(output->content,"storage");
411          free(tmpMap->value);
412          tmpMap->value=(char*) malloc((strlen(fpath)+1)*sizeof(char));
413          sprintf(tmpMap->value,"%s",fpath);
414          pszDataSource=tmpMap->value;
415          fprintf(stderr,"*** DEBUG %s\n",pszDataSource);
416        }
417      }
418      VSIFCloseL(vsif);
419      i++;
420    }
421
422  }
423
424  OGRDataSourceH poDS = NULL;
425  OGRSFDriverH *poDriver = NULL;
426  poDS = OGROpen( pszDataSource, FALSE, poDriver );
427  if( poDS == NULL ){
428#ifdef DEBUGMS
429    fprintf(stderr,"Unable to access the DataSource %s\n",pszDataSource);
430#endif
431    setMapInMaps(conf,"lenv","message","Unable to open datasource in read only mode");
432    OGR_DS_Destroy(poDS);
433    OGRCleanupAll();
434#ifdef DEBUGMS
435    fprintf(stderr,"Unable to access the DataSource, exit! \n"); 
436#endif
437    return -1;
438  }
439
440  int iLayer = 0;
441  for( iLayer=0; iLayer < OGR_DS_GetLayerCount(poDS); iLayer++ ){
442    OGRLayerH poLayer = OGR_DS_GetLayer(poDS,iLayer);
443
444    if( poLayer == NULL ){
445#ifdef DEBUGMS
446      fprintf(stderr,"Unable to access the DataSource Layer \n");
447#endif
448      setMapInMaps(conf,"lenv","message","Unable to open datasource in read only mode");
449      return -1;
450    }
451
452    /**
453     * Add a new layer set name, data
454     */
455    if(msGrowMapLayers(m)==NULL){
456      return -1;
457    }
458    if(initLayer((m->layers[m->numlayers]), m) == -1){
459      return -1;
460    }
461
462    layerObj* myLayer=m->layers[m->numlayers];
463    dumpMaps(output);
464    myLayer->name = strdup(output->name);
465    myLayer->tileitem=NULL;
466    myLayer->data = strdup(OGR_L_GetName(poLayer));
467    myLayer->connection = strdup(pszDataSource);
468    myLayer->index = m->numlayers;
469    myLayer->dump = MS_TRUE;
470    myLayer->status = MS_ON;
471    msConnectLayer(myLayer,MS_OGR,pszDataSource);
472
473    /**
474     * Detect the Geometry Type or use Polygon
475     */
476    if(OGR_L_GetGeomType(poLayer) != wkbUnknown){
477      switch(OGR_L_GetGeomType(poLayer)){
478      case wkbPoint:
479      case wkbMultiPoint:
480      case wkbPoint25D:
481      case wkbMultiPoint25D:
482#ifdef DEBUGMS
483        fprintf(stderr,"POINT DataSource Layer \n");
484#endif
485        myLayer->type = MS_LAYER_POINT;
486        break;
487      case wkbLineString :
488      case wkbMultiLineString :
489      case wkbLineString25D:
490      case wkbMultiLineString25D:
491#ifdef DEBUGMS
492        fprintf(stderr,"LINE DataSource Layer \n");
493#endif
494        myLayer->type = MS_LAYER_LINE;
495        break;
496      case wkbPolygon:
497      case wkbMultiPolygon:
498      case wkbPolygon25D:
499      case wkbMultiPolygon25D:
500#ifdef DEBUGMS
501        fprintf(stderr,"POLYGON DataSource Layer \n");
502#endif
503        myLayer->type = MS_LAYER_POLYGON;
504        break;
505      default:
506        myLayer->type = MS_LAYER_POLYGON;
507        break;
508      }
509    }else
510      myLayer->type = MS_LAYER_POLYGON;
511
512    /**
513     * Detect spatial reference or use WGS84
514     */
515    OGRSpatialReferenceH srs=OGR_L_GetSpatialRef(poLayer);
516    if(srs!=NULL){
517      char *wkt=NULL;
518      OSRExportToWkt(srs,&wkt);
519      setSrsInformations(output,m,myLayer,wkt);
520    }
521    else{
522      addToMap(output->content,"crs","EPSG:4326");
523      addToMap(output->content,"crs_isGeographic","true");
524      msLoadProjectionStringEPSG(&m->projection,"EPSG:4326");
525      msInsertHashTable(&(m->web.metadata), "ows_srs", "EPSG:4326 EPSG:900913");
526      msInsertHashTable(&(myLayer->metadata), "ows_srs", "EPSG:4326 EPSG:900913");
527    }
528
529    map* crs=getMap(output->content,"crs");
530    map* isGeo=getMap(output->content,"crs_isGeographic");
531
532    OGREnvelope oExt;
533    if (OGR_L_GetExtent(poLayer,&oExt, TRUE) == OGRERR_NONE){
534      setMsExtent(output,m,myLayer,oExt.MinX, oExt.MinY, oExt.MaxX, oExt.MaxY);
535    }
536 
537    /**
538     * Detect the FID column or use the first attribute field as FID
539     */
540    char *fid=(char*)OGR_L_GetFIDColumn(poLayer);
541    if(strlen(fid)==0){
542      OGRFeatureDefnH def=OGR_L_GetLayerDefn(poLayer);
543      int fIndex=0;
544      for(fIndex=0;fIndex<OGR_FD_GetFieldCount(def);fIndex++){
545        OGRFieldDefnH fdef=OGR_FD_GetFieldDefn(def,fIndex);
546        fid=(char*)OGR_Fld_GetNameRef(fdef);
547        break;
548      }
549    }
550    msInsertHashTable(&(myLayer->metadata), "gml_featureid", fid);
551    msInsertHashTable(&(myLayer->metadata), "gml_include_items", "all");
552    msInsertHashTable(&(myLayer->metadata), "ows_name", output->name);
553    map* tmpMap=getMap(output->content,"title");
554    if(tmpMap!=NULL)
555      msInsertHashTable(&(myLayer->metadata), "ows_title", tmpMap->value);
556    else
557      msInsertHashTable(&(myLayer->metadata), "ows_title", "Default Title");
558
559    if(msGrowLayerClasses(myLayer) == NULL)
560      return -1;
561    if(initClass((myLayer->CLASS[myLayer->numclasses])) == -1)
562      return -1;
563    myLayer->CLASS[myLayer->numclasses]->type = myLayer->type;
564    if(msGrowClassStyles(myLayer->CLASS[myLayer->numclasses]) == NULL)
565      return -1;
566    if(initStyle(myLayer->CLASS[myLayer->numclasses]->styles[myLayer->CLASS[myLayer->numclasses]->numstyles]) == -1)
567      return -1;
568
569    /**
570     * Apply msStyle else fallback to the default style
571     */
572    tmpMap=getMap(output->content,"msStyle");
573    if(tmpMap!=NULL)
574      msUpdateStyleFromString(myLayer->CLASS[myLayer->numclasses]->styles[myLayer->CLASS[myLayer->numclasses]->numstyles],tmpMap->value,0);
575    else{
576      /**
577       * Set style
578       */
579      myLayer->CLASS[myLayer->numclasses]->styles[myLayer->CLASS[myLayer->numclasses]->numstyles]->color.red=125;
580      myLayer->CLASS[myLayer->numclasses]->styles[myLayer->CLASS[myLayer->numclasses]->numstyles]->color.green=125;
581      myLayer->CLASS[myLayer->numclasses]->styles[myLayer->CLASS[myLayer->numclasses]->numstyles]->color.blue=255;
582      myLayer->CLASS[myLayer->numclasses]->styles[myLayer->CLASS[myLayer->numclasses]->numstyles]->outlinecolor.red=80;
583      myLayer->CLASS[myLayer->numclasses]->styles[myLayer->CLASS[myLayer->numclasses]->numstyles]->outlinecolor.green=80;
584      myLayer->CLASS[myLayer->numclasses]->styles[myLayer->CLASS[myLayer->numclasses]->numstyles]->outlinecolor.blue=80;
585
586      /**
587       * Set specific style depending on type
588       */
589      if(myLayer->type == MS_LAYER_POLYGON)
590        myLayer->CLASS[myLayer->numclasses]->styles[myLayer->CLASS[myLayer->numclasses]->numstyles]->width=3;
591      if(myLayer->type == MS_LAYER_LINE){
592        myLayer->CLASS[myLayer->numclasses]->styles[myLayer->CLASS[myLayer->numclasses]->numstyles]->width=3;
593        myLayer->CLASS[myLayer->numclasses]->styles[myLayer->CLASS[myLayer->numclasses]->numstyles]->outlinewidth=1.5;
594      }
595      if(myLayer->type == MS_LAYER_POINT){
596        myLayer->CLASS[myLayer->numclasses]->styles[myLayer->CLASS[myLayer->numclasses]->numstyles]->symbol=1;
597        myLayer->CLASS[myLayer->numclasses]->styles[myLayer->CLASS[myLayer->numclasses]->numstyles]->size=15;
598      }
599
600    }
601    myLayer->CLASS[myLayer->numclasses]->numstyles++;
602    myLayer->numclasses++;
603    m->layerorder[m->numlayers] = m->numlayers;
604    m->numlayers++;
605
606  }
607
608  OGR_DS_Destroy(poDS);
609  OGRCleanupAll();
610
611  return 1;
612}
613
614
615int tryGdal(maps* conf,maps* output,mapObj* m){
616  map* tmpMap=getMap(output->content,"storage");
617  char *pszFilename=tmpMap->value;
618  GDALDatasetH hDataset;
619  GDALRasterBandH hBand;
620  double adfGeoTransform[6];
621  int i, iBand;
622 
623  /**
624   * Try to open the DataSource using GDAL
625   */
626  GDALAllRegister();
627  hDataset = GDALOpen( pszFilename, GA_ReadOnly );
628  if( hDataset == NULL ){
629#ifdef DEBUGMS
630    fprintf(stderr,"Unable to access the DataSource %s \n",pszFilename);
631#endif
632    setMapInMaps(conf,"lenv","message","gdalinfo failed - unable to open");
633    GDALDestroyDriverManager();
634    return -1;
635  }
636#ifdef DEBUGMS
637    fprintf(stderr,"Accessing the DataSource %s %d\n",pszFilename,__LINE__);
638#endif
639
640  /**
641   * Add a new layer set name, data
642   */
643  if(msGrowMapLayers(m)==NULL){
644    return -1;
645  }
646  if(initLayer((m->layers[m->numlayers]), m) == -1){
647    return -1;
648  }
649
650  layerObj* myLayer=m->layers[m->numlayers];
651  myLayer->name = strdup(output->name);
652  myLayer->tileitem=NULL;
653  myLayer->data = strdup(pszFilename);
654  myLayer->index = m->numlayers;
655  myLayer->dump = MS_TRUE;
656  myLayer->status = MS_ON;
657  myLayer->type = MS_LAYER_RASTER;
658
659  char *title=output->name;
660  tmpMap=getMap(output->content,"title");
661  if(tmpMap!=NULL)
662    title=tmpMap->value;
663  char *abstract=output->name;
664  tmpMap=getMap(output->content,"abstract");
665  if(tmpMap!=NULL)
666    abstract=tmpMap->value;
667  msInsertHashTable(&(myLayer->metadata), "ows_label", title);
668  msInsertHashTable(&(myLayer->metadata), "ows_title", title);
669  msInsertHashTable(&(myLayer->metadata), "ows_abstract", abstract);
670  msInsertHashTable(&(myLayer->metadata), "ows_rangeset_name", output->name);
671  msInsertHashTable(&(myLayer->metadata), "ows_rangeset_label", title);
672
673  /**
674   * Set Map Size to the raster size
675   */
676  m->width=GDALGetRasterXSize( hDataset );
677  m->height=GDALGetRasterYSize( hDataset );
678 
679  /**
680   * Set projection using Authority Code and Name if available or fallback to
681   * proj4 definition if available or fallback to default EPSG:4326
682   */
683  const char *tRef=GDALGetProjectionRef( hDataset );
684  if( tRef != NULL && strlen(tRef)>0 ){
685    OGRSpatialReferenceH  hSRS;
686    char *pszProjection;
687    pszProjection = (char *) GDALGetProjectionRef( hDataset );
688#ifdef DEBUGMS
689    fprintf(stderr,"Accessing the DataSource %s\n",GDALGetProjectionRef( hDataset ));
690#endif
691    setSrsInformations(output,m,myLayer,pszProjection);
692    }
693
694
695  /**
696   * Set extent
697   */
698  if( GDALGetGeoTransform( hDataset, adfGeoTransform ) == CE_None ){
699    if( adfGeoTransform[2] == 0.0 && adfGeoTransform[4] == 0.0 ){
700
701      double minX = adfGeoTransform[0]
702        + adfGeoTransform[2] * GDALGetRasterYSize(hDataset);
703      double minY = adfGeoTransform[3]
704        + adfGeoTransform[5] * GDALGetRasterYSize(hDataset);
705
706      double maxX = adfGeoTransform[0]
707        + adfGeoTransform[1] * GDALGetRasterXSize(hDataset);
708      double maxY = adfGeoTransform[3]
709        + adfGeoTransform[4] * GDALGetRasterXSize(hDataset);
710
711       setMsExtent(output,m,myLayer,minX,minY,maxX,maxY);
712
713    }
714  }
715
716  /**
717   * Extract information about available bands to set the bandcount and the
718   * processing directive
719   */
720  char nBands[2];
721  int nBandsI=GDALGetRasterCount( hDataset );
722  sprintf(nBands,"%d",GDALGetRasterCount( hDataset ));
723  msInsertHashTable(&(myLayer->metadata), "ows_bandcount", nBands);
724  if(nBandsI>=3)
725    msLayerAddProcessing(myLayer,"BANDS=1,2,3");
726  else if(nBandsI>=2)
727    msLayerAddProcessing(myLayer,"BANDS=1,2");
728  else
729    msLayerAddProcessing(myLayer,"BANDS=1");
730
731  /**
732   * Name available Bands
733   */
734  char lBands[6];
735  char *nameBands=NULL;
736  for( iBand = 0; iBand < nBandsI; iBand++ ){
737    sprintf(lBands,"Band%d",iBand+1);
738    if(nameBands==NULL){
739      nameBands=(char*)malloc((strlen(lBands)+1)*sizeof(char));
740      sprintf(nameBands,"%s",lBands);
741    }else{
742      if(iBand<4){
743        char *tmpS=strdup(nameBands);
744        nameBands=(char*)realloc(nameBands,(strlen(nameBands)+strlen(lBands)+1)*sizeof(char));
745        sprintf(nameBands,"%s %s",tmpS,lBands);
746        free(tmpS);
747      }
748    }
749  }
750  msInsertHashTable(&(myLayer->metadata), "ows_bandnames", nameBands);
751 
752  /**
753   * Loops over metadata informations to setup specific informations
754   */
755  for( iBand = 0; iBand < nBandsI; iBand++ ){
756    int         bGotNodata, bSuccess;
757    double      adfCMinMax[2], dfNoData;
758    int         nBlockXSize, nBlockYSize, nMaskFlags;
759    double      dfMean, dfStdDev;
760    hBand = GDALGetRasterBand( hDataset, iBand+1 );
761
762    CPLErrorReset();
763    GDALComputeRasterMinMax( hBand, FALSE, adfCMinMax );
764    char tmpN[21];
765    sprintf(tmpN,"Band%d",iBand+1);
766    if (CPLGetLastErrorType() == CE_None){
767      char tmpMm[100];
768      sprintf(tmpMm,"%.3f %.3f",adfCMinMax[0],adfCMinMax[1]);
769      char tmpI[21];
770      sprintf(tmpI,"%s_interval",tmpN);
771      msInsertHashTable(&(myLayer->metadata), tmpI, tmpMm);
772
773      map* test=getMap(output->content,"msClassify");
774      if(test!=NULL && strncasecmp(test->value,"true",4)==0){
775        /**
776         * Classify one band raster pixel value using regular interval
777         */
778        int _tmpColors[10][3]={
779          {102,153,204},
780          {51,102,153},
781          {102,102,204},
782          {51,204,0},
783          {153,255,102},
784          {204,255,102},
785          {102,204,153},
786          {255,69,64},
787          {255,192,115},
788          {255,201,115}
789        };
790         
791        if(nBandsI==1){
792          double delta=adfCMinMax[1]-adfCMinMax[0];
793          double interval=delta/10;
794          double cstep=adfCMinMax[0];
795          for(i=0;i<10;i++){
796            /**
797             * Create a new class
798             */
799            if(msGrowLayerClasses(myLayer) == NULL)
800              return -1;
801            if(initClass((myLayer->CLASS[myLayer->numclasses])) == -1)
802              return -1;
803            myLayer->CLASS[myLayer->numclasses]->type = myLayer->type;
804            if(msGrowClassStyles(myLayer->CLASS[myLayer->numclasses]) == NULL)
805              return -1;
806            if(initStyle(myLayer->CLASS[myLayer->numclasses]->styles[myLayer->CLASS[myLayer->numclasses]->numstyles]) == -1)
807              return -1;
808           
809            /**
810             * Set class name
811             */
812            char className[7];
813            sprintf(className,"class%d",i);
814            myLayer->CLASS[myLayer->numclasses]->name=strdup(className);
815           
816            /**
817             * Set expression
818             */
819            char expression[1024];
820            if(i+1<10)
821              sprintf(expression,"([pixel]>=%.3f AND [pixel]<%.3f)",cstep,cstep+interval);
822            else
823              sprintf(expression,"([pixel]>=%.3f AND [pixel]<=%.3f)",cstep,cstep+interval);
824            msLoadExpressionString(&myLayer->CLASS[myLayer->numclasses]->expression,expression);
825           
826            /**
827             * Set color
828             */
829            myLayer->CLASS[myLayer->numclasses]->styles[myLayer->CLASS[myLayer->numclasses]->numstyles]->color.red=_tmpColors[i][0];
830            myLayer->CLASS[myLayer->numclasses]->styles[myLayer->CLASS[myLayer->numclasses]->numstyles]->color.green=_tmpColors[i][1];
831            myLayer->CLASS[myLayer->numclasses]->styles[myLayer->CLASS[myLayer->numclasses]->numstyles]->color.blue=_tmpColors[i][2];
832            cstep+=interval;
833            myLayer->CLASS[myLayer->numclasses]->numstyles++;
834            myLayer->numclasses++;
835           
836          }
837         
838          char tmpMm[100];
839          sprintf(tmpMm,"%.3f %.3f",adfCMinMax[0],adfCMinMax[1]);
840         
841        }
842      }
843    }
844    if( strlen(GDALGetRasterUnitType(hBand)) > 0 ){
845      char tmpU[21];
846      sprintf(tmpU,"%s_band_uom",tmpN);
847      msInsertHashTable(&(myLayer->metadata), tmpU, GDALGetRasterUnitType(hBand));
848    }
849
850  }
851
852  m->layerorder[m->numlayers] = m->numlayers;
853  m->numlayers++;
854  GDALClose( hDataset );
855  GDALDestroyDriverManager();
856  CPLCleanupTLS();
857  return 1;
858}
859
860/**
861 * Create a MapFile for WMS, WFS or WCS Service output
862 */
863void outputMapfile(maps* conf,maps* outputs){
864
865  /**
866   * Firs store the value on disk
867   */
868  map* mime=getMap(outputs->content,"mimeType");
869  char *ext="data";
870  if(mime!=NULL)
871    if(strncasecmp(mime->value,"application/json",16)==0)
872      ext="json";
873 
874  map* tmpMap=getMapFromMaps(conf,"main","dataPath");
875  map* sidMap=getMapFromMaps(conf,"lenv","sid");
876  char *pszDataSource=(char*)malloc((strlen(tmpMap->value)+strlen(sidMap->value)+strlen(outputs->name)+17)*sizeof(char));
877  sprintf(pszDataSource,"%s/ZOO_DATA_%s_%s.%s",tmpMap->value,outputs->name,sidMap->value,ext);
878  int f=open(pszDataSource,O_WRONLY|O_CREAT,S_IRUSR|S_IWUSR|S_IRGRP|S_IWGRP|S_IROTH|S_IWOTH);
879  map* sizeMap=getMap(outputs->content,"size");
880  map* vData=getMap(outputs->content,"value");
881  if(sizeMap!=NULL){
882    write(f,vData->value,atoi(sizeMap->value)*sizeof(char));
883  }
884  else{
885    write(f,vData->value,strlen(vData->value)*sizeof(char));
886  }
887  close(f);
888  //exit(-1);
889  addToMap(outputs->content,"storage",pszDataSource);
890
891  /*
892   * Create an empty map, set name, default size and extent
893   */
894  mapObj *myMap=msNewMapObj();
895  free(myMap->name);
896  myMap->name=strdup("ZOO-Project_WXS_Server");
897  msMapSetSize(myMap,2048,2048);
898  msMapSetExtent(myMap,-1,-1,1,1);
899 
900  /*
901   * Set imagepath and imageurl using tmpPath and tmpUrl from main.cfg
902   */
903  map *tmp1=getMapFromMaps(conf,"main","tmpPath");
904  myMap->web.imagepath=strdup(tmp1->value);
905  tmp1=getMapFromMaps(conf,"main","tmpUrl");
906  myMap->web.imageurl=strdup(tmp1->value);
907 
908  /*
909   * Define supported output formats
910   */
911  outputFormatObj *o1=msCreateDefaultOutputFormat(NULL,"AGG/PNG","png");
912  o1->imagemode=MS_IMAGEMODE_RGBA;
913  o1->transparent=MS_TRUE;
914  o1->inmapfile=MS_TRUE;
915  msAppendOutputFormat(myMap,msCloneOutputFormat(o1));
916  msFreeOutputFormat(o1);
917
918#ifdef USE_KML
919  outputFormatObj *o2=msCreateDefaultOutputFormat(NULL,"KML","kml");
920  o2->inmapfile=MS_TRUE; 
921  msAppendOutputFormat(myMap,msCloneOutputFormat(o2));
922  msFreeOutputFormat(o2);
923#endif
924
925  outputFormatObj *o3=msCreateDefaultOutputFormat(NULL,"GDAL/GTiff","tiff");
926  if(!o3)
927    fprintf(stderr,"Unable to initialize GDAL driver !\n");
928  else{
929    o3->imagemode=MS_IMAGEMODE_BYTE;
930    o3->inmapfile=MS_TRUE; 
931    msAppendOutputFormat(myMap,msCloneOutputFormat(o3));
932    msFreeOutputFormat(o3);
933  }
934
935  outputFormatObj *o4=msCreateDefaultOutputFormat(NULL,"GDAL/AAIGRID","grd");
936  if(!o4)
937    fprintf(stderr,"Unable to initialize GDAL driver !\n");
938  else{
939    o4->imagemode=MS_IMAGEMODE_INT16;
940    o4->inmapfile=MS_TRUE; 
941    msAppendOutputFormat(myMap,msCloneOutputFormat(o4));
942    msFreeOutputFormat(o4);
943  }
944
945#ifdef USE_CAIRO
946  outputFormatObj *o5=msCreateDefaultOutputFormat(NULL,"CAIRO/PNG","cairopng");
947  if(!o5)
948    fprintf(stderr,"Unable to initialize CAIRO driver !\n");
949  else{
950    o5->imagemode=MS_IMAGEMODE_RGBA;
951    o5->transparent=MS_TRUE;
952    o5->inmapfile=MS_TRUE;
953    msAppendOutputFormat(myMap,msCloneOutputFormat(o5));
954    msFreeOutputFormat(o5);
955  }
956#endif
957
958  /*
959   * Set default projection to EPSG:4326
960   */
961  msLoadProjectionStringEPSG(&myMap->projection,"EPSG:4326");
962  myMap->transparent=1;
963
964  /**
965   * Set metadata extracted from main.cfg file maps
966   */
967  maps* cursor=conf;
968  map* correspondance=getCorrespondance();
969  while(cursor!=NULL){
970    map* _cursor=cursor->content;
971    map* vMap;
972    while(_cursor!=NULL){
973      if((vMap=getMap(correspondance,_cursor->name))!=NULL){
974        if (msInsertHashTable(&(myMap->web.metadata), vMap->value, _cursor->value) == NULL){
975#ifdef DEBUGMS
976          fprintf(stderr,"Unable to add metadata");
977#endif
978          return;
979        }
980      }
981      _cursor=_cursor->next;
982    }
983    cursor=cursor->next;
984  }
985
986  /*
987   * Set mapserver PROJ_LIB/GDAL_DATA or any other config parameter from
988   * the main.cfg [mapserver] section if any
989   */
990  maps *tmp3=getMaps(conf,"mapserver");
991  if(tmp3!=NULL){
992    map* tmp4=tmp3->content;
993    while(tmp4!=NULL){
994      msSetConfigOption(myMap,tmp4->name,tmp4->value);
995      tmp4=tmp4->next;
996    }
997  }
998
999  /**
1000   * Set a ows_rootlayer_title, 
1001   */
1002  if (msInsertHashTable(&(myMap->web.metadata), "ows_rootlayer_name", "ZOO_Project_Layer") == NULL){
1003#ifdef DEBUGMS
1004    fprintf(stderr,"Unable to add metadata");
1005#endif
1006    return;
1007  }
1008  if (msInsertHashTable(&(myMap->web.metadata), "ows_rootlayer_title", "ZOO_Project_Layer") == NULL){
1009#ifdef DEBUGMS
1010    fprintf(stderr,"Unable to add metadata");
1011#endif
1012    return;
1013  }
1014
1015  /**
1016   * Enable all the WXS requests using ows_enable_request
1017   * see http://mapserver.org/trunk/development/rfc/ms-rfc-67.html
1018   */
1019  if (msInsertHashTable(&(myMap->web.metadata), "ows_enable_request", "*") == NULL){
1020#ifdef DEBUGMS
1021    fprintf(stderr,"Unable to add metadata");
1022#endif
1023    return;
1024  }
1025  msInsertHashTable(&(myMap->web.metadata), "ows_srs", "EPSG:4326");
1026
1027  if(tryOgr(conf,outputs,myMap)<0)
1028    if(tryGdal(conf,outputs,myMap)<0)
1029      return ;
1030
1031  tmp1=getMapFromMaps(conf,"main","dataPath");
1032  char *tmpPath=(char*)malloc((13+strlen(tmp1->value))*sizeof(char));
1033  sprintf(tmpPath,"%s/symbols.sym",tmp1->value);
1034  msInitSymbolSet(&myMap->symbolset);
1035  myMap->symbolset.filename=strdup(tmpPath);
1036  free(tmpPath);
1037
1038  map* sid=getMapFromMaps(conf,"lenv","sid");
1039  char *mapPath=
1040    (char*)malloc((16+strlen(outputs->name)+strlen(tmp1->value))*sizeof(char));
1041  sprintf(mapPath,"%s/%s_%s.map",tmp1->value,outputs->name,sid->value);
1042  msSaveMap(myMap,mapPath);
1043  msFreeMap(myMap);
1044}
1045
1046#endif
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