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

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

Add support for multiple inputs values for the same identifier.

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