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

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

Fix the two target for service_internal_java.obj, thanks to Farkas for his comment. FIx issue when outputing raster data to make sure that if there is no projection that the layer will be added to the mapfile.

  • Property svn:eol-style set to native
  • Property svn:mime-type set to text/x-csrc
File size: 32.4 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
376#ifndef WIN32
377                ,S_IRWXU | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH
378#endif
379                );
380    while(demo[i]!=NULL){
381      fprintf(stderr,"ZIP File content : %s\n",demo[i]);
382      char *tmpDs=(char*)malloc((strlen(dsName)+strlen(demo[i])+2)*sizeof(char));
383      sprintf(tmpDs,"%s/%s",dsName,demo[i]);
384      fprintf(stderr,"read : %s\n",tmpDs);
385     
386      VSILFILE* vsif=VSIFOpenL(tmpDs,"rb");
387      fprintf(stderr,"open : %s\n",tmpDs);
388      VSIFSeekL(vsif,0,SEEK_END);
389      int size=VSIFTellL(vsif);
390      fprintf(stderr,"size : %d\n",size);
391      VSIFSeekL(vsif,0,SEEK_SET);
392      char *vsifcontent=(char*) malloc((size+1)*sizeof(char));
393      VSIFReadL(vsifcontent,1,size,vsif);
394      char *fpath=(char*) malloc((strlen(sdsName)+strlen(demo[1])+2)*sizeof(char));
395      sprintf(fpath,"%s/%s",sdsName,demo[i]);
396      int f=open(fpath,O_WRONLY|O_CREAT,S_IRUSR|S_IWUSR|S_IRGRP|S_IWGRP|S_IROTH|S_IWOTH);
397      write(f,vsifcontent,size);
398      close(f);
399      chmod(fpath,S_IRWXU | S_IRGRP | S_IXGRP | S_IROTH);
400      char* tmpP=strstr(fpath,".shp");
401      if(tmpP==NULL)
402        tmpP=strstr(fpath,".SHP");
403      if(tmpP!=NULL){
404        fprintf(stderr,"*** DEBUG %s\n",strstr(tmpP,"."));
405        if( strcmp(tmpP,".shp")==0 || strcmp(tmpP,".SHP")==0 ){
406          tmpMap=getMap(output->content,"storage");
407          free(tmpMap->value);
408          tmpMap->value=(char*) malloc((strlen(fpath)+1)*sizeof(char));
409          sprintf(tmpMap->value,"%s",fpath);
410          pszDataSource=tmpMap->value;
411          fprintf(stderr,"*** DEBUG %s\n",pszDataSource);
412        }
413      }
414      VSIFCloseL(vsif);
415      i++;
416    }
417
418  }
419
420  OGRDataSourceH poDS = NULL;
421  OGRSFDriverH *poDriver = NULL;
422  poDS = OGROpen( pszDataSource, FALSE, poDriver );
423  if( poDS == NULL ){
424#ifdef DEBUGMS
425    fprintf(stderr,"Unable to access the DataSource %s\n",pszDataSource);
426#endif
427    setMapInMaps(conf,"lenv","message","Unable to open datasource in read only mode");
428    OGR_DS_Destroy(poDS);
429    OGRCleanupAll();
430#ifdef DEBUGMS
431    fprintf(stderr,"Unable to access the DataSource, exit! \n"); 
432#endif
433    return -1;
434  }
435
436  int iLayer = 0;
437  for( iLayer=0; iLayer < OGR_DS_GetLayerCount(poDS); iLayer++ ){
438    OGRLayerH poLayer = OGR_DS_GetLayer(poDS,iLayer);
439
440    if( poLayer == NULL ){
441#ifdef DEBUGMS
442      fprintf(stderr,"Unable to access the DataSource Layer \n");
443#endif
444      setMapInMaps(conf,"lenv","message","Unable to open datasource in read only mode");
445      return -1;
446    }
447
448    /**
449     * Add a new layer set name, data
450     */
451    if(msGrowMapLayers(m)==NULL){
452      return -1;
453    }
454    if(initLayer((m->layers[m->numlayers]), m) == -1){
455      return -1;
456    }
457
458    layerObj* myLayer=m->layers[m->numlayers];
459    dumpMaps(output);
460    myLayer->name = strdup(output->name);
461    myLayer->tileitem=NULL;
462    myLayer->data = strdup(OGR_L_GetName(poLayer));
463    myLayer->connection = strdup(pszDataSource);
464    myLayer->index = m->numlayers;
465    myLayer->dump = MS_TRUE;
466    myLayer->status = MS_ON;
467    msConnectLayer(myLayer,MS_OGR,pszDataSource);
468
469    /**
470     * Detect the Geometry Type or use Polygon
471     */
472    if(OGR_L_GetGeomType(poLayer) != wkbUnknown){
473      switch(OGR_L_GetGeomType(poLayer)){
474      case wkbPoint:
475      case wkbMultiPoint:
476      case wkbPoint25D:
477      case wkbMultiPoint25D:
478#ifdef DEBUGMS
479        fprintf(stderr,"POINT DataSource Layer \n");
480#endif
481        myLayer->type = MS_LAYER_POINT;
482        break;
483      case wkbLineString :
484      case wkbMultiLineString :
485      case wkbLineString25D:
486      case wkbMultiLineString25D:
487#ifdef DEBUGMS
488        fprintf(stderr,"LINE DataSource Layer \n");
489#endif
490        myLayer->type = MS_LAYER_LINE;
491        break;
492      case wkbPolygon:
493      case wkbMultiPolygon:
494      case wkbPolygon25D:
495      case wkbMultiPolygon25D:
496#ifdef DEBUGMS
497        fprintf(stderr,"POLYGON DataSource Layer \n");
498#endif
499        myLayer->type = MS_LAYER_POLYGON;
500        break;
501      default:
502        myLayer->type = MS_LAYER_POLYGON;
503        break;
504      }
505    }else
506      myLayer->type = MS_LAYER_POLYGON;
507
508    /**
509     * Detect spatial reference or use WGS84
510     */
511    OGRSpatialReferenceH srs=OGR_L_GetSpatialRef(poLayer);
512    if(srs!=NULL){
513      char *wkt=NULL;
514      OSRExportToWkt(srs,&wkt);
515      setSrsInformations(output,m,myLayer,wkt);
516    }
517    else{
518      addToMap(output->content,"crs","EPSG:4326");
519      addToMap(output->content,"crs_isGeographic","true");
520      msLoadProjectionStringEPSG(&m->projection,"EPSG:4326");
521      msInsertHashTable(&(m->web.metadata), "ows_srs", "EPSG:4326 EPSG:900913");
522      msInsertHashTable(&(myLayer->metadata), "ows_srs", "EPSG:4326 EPSG:900913");
523    }
524
525    map* crs=getMap(output->content,"crs");
526    map* isGeo=getMap(output->content,"crs_isGeographic");
527
528    OGREnvelope oExt;
529    if (OGR_L_GetExtent(poLayer,&oExt, TRUE) == OGRERR_NONE){
530      setMsExtent(output,m,myLayer,oExt.MinX, oExt.MinY, oExt.MaxX, oExt.MaxY);
531    }
532 
533    /**
534     * Detect the FID column or use the first attribute field as FID
535     */
536    char *fid=(char*)OGR_L_GetFIDColumn(poLayer);
537    if(strlen(fid)==0){
538      OGRFeatureDefnH def=OGR_L_GetLayerDefn(poLayer);
539      int fIndex=0;
540      for(fIndex=0;fIndex<OGR_FD_GetFieldCount(def);fIndex++){
541        OGRFieldDefnH fdef=OGR_FD_GetFieldDefn(def,fIndex);
542        fid=(char*)OGR_Fld_GetNameRef(fdef);
543        break;
544      }
545    }
546    msInsertHashTable(&(myLayer->metadata), "gml_featureid", fid);
547    msInsertHashTable(&(myLayer->metadata), "gml_include_items", "all");
548    msInsertHashTable(&(myLayer->metadata), "ows_name", output->name);
549    map* tmpMap=getMap(output->content,"title");
550    if(tmpMap!=NULL)
551      msInsertHashTable(&(myLayer->metadata), "ows_title", tmpMap->value);
552    else
553      msInsertHashTable(&(myLayer->metadata), "ows_title", "Default Title");
554
555    if(msGrowLayerClasses(myLayer) == NULL)
556      return -1;
557    if(initClass((myLayer->_class[myLayer->numclasses])) == -1)
558      return -1;
559    myLayer->_class[myLayer->numclasses]->type = myLayer->type;
560    if(msGrowClassStyles(myLayer->_class[myLayer->numclasses]) == NULL)
561      return -1;
562    if(initStyle(myLayer->_class[myLayer->numclasses]->styles[myLayer->_class[myLayer->numclasses]->numstyles]) == -1)
563      return -1;
564
565    /**
566     * Apply msStyle else fallback to the default style
567     */
568    tmpMap=getMap(output->content,"msStyle");
569    if(tmpMap!=NULL)
570      msUpdateStyleFromString(myLayer->_class[myLayer->numclasses]->styles[myLayer->_class[myLayer->numclasses]->numstyles],tmpMap->value,0);
571    else{
572      /**
573       * Set style
574       */
575      myLayer->_class[myLayer->numclasses]->styles[myLayer->_class[myLayer->numclasses]->numstyles]->color.red=125;
576      myLayer->_class[myLayer->numclasses]->styles[myLayer->_class[myLayer->numclasses]->numstyles]->color.green=125;
577      myLayer->_class[myLayer->numclasses]->styles[myLayer->_class[myLayer->numclasses]->numstyles]->color.blue=255;
578      myLayer->_class[myLayer->numclasses]->styles[myLayer->_class[myLayer->numclasses]->numstyles]->outlinecolor.red=80;
579      myLayer->_class[myLayer->numclasses]->styles[myLayer->_class[myLayer->numclasses]->numstyles]->outlinecolor.green=80;
580      myLayer->_class[myLayer->numclasses]->styles[myLayer->_class[myLayer->numclasses]->numstyles]->outlinecolor.blue=80;
581
582      /**
583       * Set specific style depending on type
584       */
585      if(myLayer->type == MS_LAYER_POLYGON)
586        myLayer->_class[myLayer->numclasses]->styles[myLayer->_class[myLayer->numclasses]->numstyles]->width=3;
587      if(myLayer->type == MS_LAYER_LINE){
588        myLayer->_class[myLayer->numclasses]->styles[myLayer->_class[myLayer->numclasses]->numstyles]->width=3;
589        myLayer->_class[myLayer->numclasses]->styles[myLayer->_class[myLayer->numclasses]->numstyles]->outlinewidth=1.5;
590      }
591      if(myLayer->type == MS_LAYER_POINT){
592        myLayer->_class[myLayer->numclasses]->styles[myLayer->_class[myLayer->numclasses]->numstyles]->symbol=1;
593        myLayer->_class[myLayer->numclasses]->styles[myLayer->_class[myLayer->numclasses]->numstyles]->size=15;
594      }
595
596    }
597    myLayer->_class[myLayer->numclasses]->numstyles++;
598    myLayer->numclasses++;
599    m->layerorder[m->numlayers] = m->numlayers;
600    m->numlayers++;
601
602  }
603
604  OGR_DS_Destroy(poDS);
605  OGRCleanupAll();
606
607  return 1;
608}
609
610
611int tryGdal(maps* conf,maps* output,mapObj* m){
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 %s \n",pszFilename);
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 %d\n",pszFilename,__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  const char *tRef=GDALGetProjectionRef( hDataset );
680  if( tRef != NULL && strlen(tRef)>0 ){
681    OGRSpatialReferenceH  hSRS;
682    char *pszProjection;
683    pszProjection = (char *) GDALGetProjectionRef( hDataset );
684#ifdef DEBUGMS
685    fprintf(stderr,"Accessing the DataSource %s\n",GDALGetProjectionRef( hDataset ));
686#endif
687    setSrsInformations(output,m,myLayer,pszProjection);
688    }
689
690
691  /**
692   * Set extent
693   */
694  if( GDALGetGeoTransform( hDataset, adfGeoTransform ) == CE_None ){
695    if( adfGeoTransform[2] == 0.0 && adfGeoTransform[4] == 0.0 ){
696
697      double minX = adfGeoTransform[0]
698        + adfGeoTransform[2] * GDALGetRasterYSize(hDataset);
699      double minY = adfGeoTransform[3]
700        + adfGeoTransform[5] * GDALGetRasterYSize(hDataset);
701
702      double maxX = adfGeoTransform[0]
703        + adfGeoTransform[1] * GDALGetRasterXSize(hDataset);
704      double maxY = adfGeoTransform[3]
705        + adfGeoTransform[4] * GDALGetRasterXSize(hDataset);
706
707       setMsExtent(output,m,myLayer,minX,minY,maxX,maxY);
708
709    }
710  }
711
712  /**
713   * Extract information about available bands to set the bandcount and the
714   * processing directive
715   */
716  char nBands[2];
717  int nBandsI=GDALGetRasterCount( hDataset );
718  sprintf(nBands,"%d",GDALGetRasterCount( hDataset ));
719  msInsertHashTable(&(myLayer->metadata), "ows_bandcount", nBands);
720  if(nBandsI>=3)
721    msLayerAddProcessing(myLayer,"BANDS=1,2,3");
722  else if(nBandsI>=2)
723    msLayerAddProcessing(myLayer,"BANDS=1,2");
724  else
725    msLayerAddProcessing(myLayer,"BANDS=1");
726
727  /**
728   * Name available Bands
729   */
730  char lBands[6];
731  char *nameBands=NULL;
732  for( iBand = 0; iBand < nBandsI; iBand++ ){
733    sprintf(lBands,"Band%d",iBand+1);
734    if(nameBands==NULL){
735      nameBands=(char*)malloc((strlen(lBands)+1)*sizeof(char));
736      sprintf(nameBands,"%s",lBands);
737    }else{
738      if(iBand<4){
739        char *tmpS=strdup(nameBands);
740        nameBands=(char*)realloc(nameBands,(strlen(nameBands)+strlen(lBands)+1)*sizeof(char));
741        sprintf(nameBands,"%s %s",tmpS,lBands);
742        free(tmpS);
743      }
744    }
745  }
746  msInsertHashTable(&(myLayer->metadata), "ows_bandnames", nameBands);
747 
748  /**
749   * Loops over metadata informations to setup specific informations
750   */
751  for( iBand = 0; iBand < nBandsI; iBand++ ){
752    int         bGotNodata, bSuccess;
753    double      adfCMinMax[2], dfNoData;
754    int         nBlockXSize, nBlockYSize, nMaskFlags;
755    double      dfMean, dfStdDev;
756    hBand = GDALGetRasterBand( hDataset, iBand+1 );
757
758    CPLErrorReset();
759    GDALComputeRasterMinMax( hBand, FALSE, adfCMinMax );
760    char tmpN[21];
761    sprintf(tmpN,"Band%d",iBand+1);
762    if (CPLGetLastErrorType() == CE_None){
763      char tmpMm[100];
764      sprintf(tmpMm,"%.3f %.3f",adfCMinMax[0],adfCMinMax[1]);
765      char tmpI[21];
766      sprintf(tmpI,"%s_interval",tmpN);
767      msInsertHashTable(&(myLayer->metadata), tmpI, tmpMm);
768
769      map* test=getMap(output->content,"msClassify");
770      if(test!=NULL && strncasecmp(test->value,"true",4)==0){
771        /**
772         * Classify one band raster pixel value using regular interval
773         */
774        int _tmpColors[10][3]={
775          {102,153,204},
776          {51,102,153},
777          {102,102,204},
778          {51,204,0},
779          {153,255,102},
780          {204,255,102},
781          {102,204,153},
782          {255,69,64},
783          {255,192,115},
784          {255,201,115}
785        };
786         
787        if(nBandsI==1){
788          double delta=adfCMinMax[1]-adfCMinMax[0];
789          double interval=delta/10;
790          double cstep=adfCMinMax[0];
791          for(i=0;i<10;i++){
792            /**
793             * Create a new class
794             */
795            if(msGrowLayerClasses(myLayer) == NULL)
796              return -1;
797            if(initClass((myLayer->_class[myLayer->numclasses])) == -1)
798              return -1;
799            myLayer->_class[myLayer->numclasses]->type = myLayer->type;
800            if(msGrowClassStyles(myLayer->_class[myLayer->numclasses]) == NULL)
801              return -1;
802            if(initStyle(myLayer->_class[myLayer->numclasses]->styles[myLayer->_class[myLayer->numclasses]->numstyles]) == -1)
803              return -1;
804           
805            /**
806             * Set class name
807             */
808            char className[7];
809            sprintf(className,"class%d",i);
810            myLayer->_class[myLayer->numclasses]->name=strdup(className);
811           
812            /**
813             * Set expression
814             */
815            char expression[1024];
816            if(i+1<10)
817              sprintf(expression,"([pixel]>=%.3f AND [pixel]<%.3f)",cstep,cstep+interval);
818            else
819              sprintf(expression,"([pixel]>=%.3f AND [pixel]<=%.3f)",cstep,cstep+interval);
820            msLoadExpressionString(&myLayer->_class[myLayer->numclasses]->expression,expression);
821           
822            /**
823             * Set color
824             */
825            myLayer->_class[myLayer->numclasses]->styles[myLayer->_class[myLayer->numclasses]->numstyles]->color.red=_tmpColors[i][0];
826            myLayer->_class[myLayer->numclasses]->styles[myLayer->_class[myLayer->numclasses]->numstyles]->color.green=_tmpColors[i][1];
827            myLayer->_class[myLayer->numclasses]->styles[myLayer->_class[myLayer->numclasses]->numstyles]->color.blue=_tmpColors[i][2];
828            cstep+=interval;
829            myLayer->_class[myLayer->numclasses]->numstyles++;
830            myLayer->numclasses++;
831           
832          }
833         
834          char tmpMm[100];
835          sprintf(tmpMm,"%.3f %.3f",adfCMinMax[0],adfCMinMax[1]);
836         
837        }
838      }
839    }
840    if( strlen(GDALGetRasterUnitType(hBand)) > 0 ){
841      char tmpU[21];
842      sprintf(tmpU,"%s_band_uom",tmpN);
843      msInsertHashTable(&(myLayer->metadata), tmpU, GDALGetRasterUnitType(hBand));
844    }
845
846  }
847
848  m->layerorder[m->numlayers] = m->numlayers;
849  m->numlayers++;
850  GDALClose( hDataset );
851  GDALDestroyDriverManager();
852  CPLCleanupTLS();
853  return 1;
854}
855
856/**
857 * Create a MapFile for WMS, WFS or WCS Service output
858 */
859void outputMapfile(maps* conf,maps* outputs){
860
861  /**
862   * Firs store the value on disk
863   */
864  map* mime=getMap(outputs->content,"mimeType");
865  char *ext="data";
866  if(mime!=NULL)
867    if(strncasecmp(mime->value,"application/json",16)==0)
868      ext="json";
869 
870  map* tmpMap=getMapFromMaps(conf,"main","dataPath");
871  map* sidMap=getMapFromMaps(conf,"lenv","sid");
872  char *pszDataSource=(char*)malloc((strlen(tmpMap->value)+strlen(sidMap->value)+strlen(outputs->name)+17)*sizeof(char));
873  sprintf(pszDataSource,"%s/ZOO_DATA_%s_%s.%s",tmpMap->value,outputs->name,sidMap->value,ext);
874  int f=open(pszDataSource,O_WRONLY|O_CREAT,S_IRUSR|S_IWUSR|S_IRGRP|S_IWGRP|S_IROTH|S_IWOTH);
875  map* sizeMap=getMap(outputs->content,"size");
876  map* vData=getMap(outputs->content,"value");
877  if(sizeMap!=NULL){
878    write(f,vData->value,atoi(sizeMap->value)*sizeof(char));
879  }
880  else{
881    write(f,vData->value,strlen(vData->value)*sizeof(char));
882  }
883  close(f);
884  //exit(-1);
885  addToMap(outputs->content,"storage",pszDataSource);
886
887  /*
888   * Create an empty map, set name, default size and extent
889   */
890  mapObj *myMap=msNewMapObj();
891  free(myMap->name);
892  myMap->name=strdup("ZOO-Project_WXS_Server");
893  msMapSetSize(myMap,2048,2048);
894  msMapSetExtent(myMap,-1,-1,1,1);
895 
896  /*
897   * Set imagepath and imageurl using tmpPath and tmpUrl from main.cfg
898   */
899  map *tmp1=getMapFromMaps(conf,"main","tmpPath");
900  myMap->web.imagepath=strdup(tmp1->value);
901  tmp1=getMapFromMaps(conf,"main","tmpUrl");
902  myMap->web.imageurl=strdup(tmp1->value);
903 
904  /*
905   * Define supported output formats
906   */
907  outputFormatObj *o1=msCreateDefaultOutputFormat(NULL,"AGG/PNG","png");
908  o1->imagemode=MS_IMAGEMODE_RGBA;
909  o1->transparent=MS_TRUE;
910  o1->inmapfile=MS_TRUE;
911  msAppendOutputFormat(myMap,msCloneOutputFormat(o1));
912  msFreeOutputFormat(o1);
913
914#ifdef USE_KML
915  outputFormatObj *o2=msCreateDefaultOutputFormat(NULL,"KML","kml");
916  o2->inmapfile=MS_TRUE; 
917  msAppendOutputFormat(myMap,msCloneOutputFormat(o2));
918  msFreeOutputFormat(o2);
919#endif
920
921  outputFormatObj *o3=msCreateDefaultOutputFormat(NULL,"GDAL/GTiff","tiff");
922  if(!o3)
923    fprintf(stderr,"Unable to initialize GDAL driver !\n");
924  else{
925    o3->imagemode=MS_IMAGEMODE_BYTE;
926    o3->inmapfile=MS_TRUE; 
927    msAppendOutputFormat(myMap,msCloneOutputFormat(o3));
928    msFreeOutputFormat(o3);
929  }
930
931  outputFormatObj *o4=msCreateDefaultOutputFormat(NULL,"GDAL/AAIGRID","grd");
932  if(!o4)
933    fprintf(stderr,"Unable to initialize GDAL driver !\n");
934  else{
935    o4->imagemode=MS_IMAGEMODE_INT16;
936    o4->inmapfile=MS_TRUE; 
937    msAppendOutputFormat(myMap,msCloneOutputFormat(o4));
938    msFreeOutputFormat(o4);
939  }
940
941#ifdef USE_CAIRO
942  outputFormatObj *o5=msCreateDefaultOutputFormat(NULL,"CAIRO/PNG","cairopng");
943  if(!o5)
944    fprintf(stderr,"Unable to initialize CAIRO driver !\n");
945  else{
946    o5->imagemode=MS_IMAGEMODE_RGBA;
947    o5->transparent=MS_TRUE;
948    o5->inmapfile=MS_TRUE;
949    msAppendOutputFormat(myMap,msCloneOutputFormat(o5));
950    msFreeOutputFormat(o5);
951  }
952#endif
953
954  /*
955   * Set default projection to EPSG:4326
956   */
957  msLoadProjectionStringEPSG(&myMap->projection,"EPSG:4326");
958  myMap->transparent=1;
959
960  /**
961   * Set metadata extracted from main.cfg file maps
962   */
963  maps* cursor=conf;
964  map* correspondance=getCorrespondance();
965  while(cursor!=NULL){
966    map* _cursor=cursor->content;
967    map* vMap;
968    while(_cursor!=NULL){
969      if((vMap=getMap(correspondance,_cursor->name))!=NULL){
970        if (msInsertHashTable(&(myMap->web.metadata), vMap->value, _cursor->value) == NULL){
971#ifdef DEBUGMS
972          fprintf(stderr,"Unable to add metadata");
973#endif
974          return;
975        }
976      }
977      _cursor=_cursor->next;
978    }
979    cursor=cursor->next;
980  }
981
982  /*
983   * Set mapserver PROJ_LIB/GDAL_DATA or any other config parameter from
984   * the main.cfg [mapserver] section if any
985   */
986  maps *tmp3=getMaps(conf,"mapserver");
987  if(tmp3!=NULL){
988    map* tmp4=tmp3->content;
989    while(tmp4!=NULL){
990      msSetConfigOption(myMap,tmp4->name,tmp4->value);
991      tmp4=tmp4->next;
992    }
993  }
994
995  /**
996   * Set a ows_rootlayer_title, 
997   */
998  if (msInsertHashTable(&(myMap->web.metadata), "ows_rootlayer_name", "ZOO_Project_Layer") == NULL){
999#ifdef DEBUGMS
1000    fprintf(stderr,"Unable to add metadata");
1001#endif
1002    return;
1003  }
1004  if (msInsertHashTable(&(myMap->web.metadata), "ows_rootlayer_title", "ZOO_Project_Layer") == NULL){
1005#ifdef DEBUGMS
1006    fprintf(stderr,"Unable to add metadata");
1007#endif
1008    return;
1009  }
1010
1011  /**
1012   * Enable all the WXS requests using ows_enable_request
1013   * see http://mapserver.org/trunk/development/rfc/ms-rfc-67.html
1014   */
1015  if (msInsertHashTable(&(myMap->web.metadata), "ows_enable_request", "*") == NULL){
1016#ifdef DEBUGMS
1017    fprintf(stderr,"Unable to add metadata");
1018#endif
1019    return;
1020  }
1021  msInsertHashTable(&(myMap->web.metadata), "ows_srs", "EPSG:4326");
1022
1023  if(tryOgr(conf,outputs,myMap)<0)
1024    if(tryGdal(conf,outputs,myMap)<0)
1025      return ;
1026
1027  tmp1=getMapFromMaps(conf,"main","dataPath");
1028  char *tmpPath=(char*)malloc((13+strlen(tmp1->value))*sizeof(char));
1029  sprintf(tmpPath,"%s/symbols.sym",tmp1->value);
1030  msInitSymbolSet(&myMap->symbolset);
1031  myMap->symbolset.filename=strdup(tmpPath);
1032  free(tmpPath);
1033
1034  map* sid=getMapFromMaps(conf,"lenv","sid");
1035  char *mapPath=
1036    (char*)malloc((16+strlen(outputs->name)+strlen(tmp1->value))*sizeof(char));
1037  sprintf(mapPath,"%s/%s_%s.map",tmp1->value,outputs->name,sid->value);
1038  msSaveMap(myMap,mapPath);
1039  msFreeMap(myMap);
1040}
1041
1042#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