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

Last change on this file since 364 was 364, checked in by djay, 12 years ago

Update to make ZOO-Kernel able to compile and run from Windows Platforms. A special thanks to Espen Messel, Knut Landmark and Benrd Härtwig for providing many patches that I can successfully apply on the SVN source tree and to Farkas for continuing requesting for ZOO-Kernel to run on Windows platforms privately and through the ZOO-Discuss mailing list.

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