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

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

Fix typo.

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