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

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

Fix multiple values for the same identifier.

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