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

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

Fix typo on sprintf.

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