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

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

Make raster classification optional.

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

Search

Context Navigation

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