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

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

Small fix in MS Support, reproject extent to epsg:4326 when no authority name and code can be found. Thanks to Truong Xuan Quang for pointing this issue.

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