geoserver源码学习与扩展——自动发布shapefile图层
geoserver通过工作空间Workspace-数据源DataStore-图层Layer管理地理数据,这些信息都通过Catalog进行组织和管理,要完成自动发布只需要在Catalog中增加相应的信息即可。
主要包括:1、添加数据源信息DataStore,使用默认工作空间;2、添加矢量要素信息FeatureTypeInfo,作为矢量数据源;3、添加图层信息LayerInfo,可设置使用样式,也可使用默认样式;
1 /** 2 * publish shape file to layer 3 * */ 4 private void publishShapeFile(File shpDir, String schemaName){ 5 final CatalogBuilder catalogBuilder = new CatalogBuilder(catalog); 6 7 //create FeatureSource 8 String shapePath = shpDir.getAbsolutePath() + "/" + schemaName + ".shp"; 9 ShapefileDataStoreFactory dataStoreFactory = new ShapefileDataStoreFactory(); 10 ShapefileDataStore sds = null; 11 try { 12 URL shpUrl = new File(shapePath).toURI().toURL(); 13 sds = (ShapefileDataStore)dataStoreFactory.createDataStore(shpUrl); 14 SimpleFeatureSource featureSource = sds.getFeatureSource(); 15 16 //check exist 17 DataStoreInfo dsInfo = catalog.getDataStoreByName(schemaName); 18 if(dsInfo == null){ 19 dsInfo = catalogBuilder.buildDataStore(schemaName); 20 dsInfo.setType("Shapefile"); 21 Map<String, Serializable> connectionParams = new HashMap<String, Serializable>(); 22 connectionParams.put("charset", sds.getCharset().toString()); 23 connectionParams.put("filetype", "shapefile"); 24 connectionParams.put("create spatial index", true); 25 connectionParams.put("memory mapped buffer", false); 26 connectionParams.put("timezone", "PRC"); 27 connectionParams.put("enable spatial index", true); 28 connectionParams.put("namespace", catalog.getDefaultNamespace().getURI()); 29 connectionParams.put("cache and reuse memory maps", true); 30 connectionParams.put("fstype", "shape"); 31 connectionParams.put("url", shpUrl.toString()); 32 dsInfo.getConnectionParameters().putAll(connectionParams); 33 catalog.save(dsInfo); 34 } 35 catalogBuilder.setStore(dsInfo); 36 37 //check exist 38 FeatureTypeInfo ftInfo = catalog.getFeatureTypeByDataStore(dsInfo, featureSource.getName().getLocalPart()); 39 if(ftInfo == null){ 40 ftInfo = catalogBuilder.buildFeatureType(featureSource); 41 catalogBuilder.setupBounds(ftInfo, featureSource); 42 catalog.add(ftInfo); 43 } 44 45 //check exist 46 LayerInfo lInfo = catalog.getLayerByName(ftInfo.getName()); 47 if(lInfo == null){ 48 lInfo = catalogBuilder.buildLayer(ftInfo); 49 //set custom style “ammeter” 50 StyleInfo styleInfo = catalog.getStyleByName("ammeter"); 51 if(styleInfo != null) 52 lInfo.setDefaultStyle(styleInfo); 53 54 catalog.add(lInfo); 55 } 56 57 } catch (Exception e) { 58 e.printStackTrace(); 59 }finally{ 60 sds.dispose(); 61 } 62 63 }