终于搞定GeoTools对PostGis的操作

      唉,这几天撒事情都没有做,就搞定了GeoTools的一些bug的删除。2.3版本问题比较多,上次在GT上和Richard聊天,他也对GeoTools目前的状况表示很是不满,但是为了PostGis的推广更顺利(毕竟,大多数使用Postgis的兄台还是在geotools平台上),很多时候很多事情都不是我们能决定的。。。所以只能自己动手去将GeoTools在文档中没有说清楚的,或者无法编译的程序根据新的API从新做一次。
     这几天搞定了GeoTools的PostgisDataStore操作。包含连接、读取、新建、插入等等。其实很多功能比如新建和插入都可以用SQL语句去完成,不过这样做对postgis即将推出的空间索引还是有很大影响的。所以我们没有使用SQL去完成这些工作。
   
/**/ /*
* POSTGEO
*/

package com.geotools.test;

/** */ /**
*
* CopyRight (C) All rights reserved.
* <p>
*
* WuHan Inpoint Information Technology Development,Inc.
* <p>
*
* Author sinoly
* <p>
* Project Name: PostGeo
*
*
@version 1.0 2006-11-13
*
* <p>
* Base on : JDK1.5
* <p>
*
*/

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.NoSuchElementException;

import org.apache.log4j.Logger;
import org.geotools.data.FeatureReader;
import org.geotools.data.FeatureResults;
import org.geotools.data.FeatureSource;
import org.geotools.data.FeatureStore;
import org.geotools.data.FeatureWriter;
import org.geotools.data.postgis.PostgisDataStore;
import org.geotools.data.postgis.PostgisDataStoreFactory;
import org.geotools.factory.FactoryRegistryException;
import org.geotools.feature.AttributeType;
import org.geotools.feature.AttributeTypeFactory;
import org.geotools.feature.Feature;
import org.geotools.feature.FeatureType;
import org.geotools.feature.FeatureTypeFactory;
import org.geotools.feature.IllegalAttributeException;
import org.geotools.feature.SchemaException;
import org.geotools.geometry.Geometry;

import com.vividsolutions.jts.geom.LineString;
import com.vividsolutions.jts.io.ParseException;
import com.vividsolutions.jts.io.WKTReader;

public class GetPostgisData {
   
private static final Logger LOGGER = Logger.getLogger("org.geotools.postgis");

   
static PostgisDataStore pgDatastore;
   
static PostgisDataStoreFactory factory=new PostgisDataStoreFactory();
   
static FeatureSource fsBC;
    @SuppressWarnings(
"unchecked")
   
private static void ConnPostGis(String dbtype,String URL,int port,String database,
        String user,String password)
{
        Map params
= new HashMap();
        params.put(
"dbtype", "postgis");
        params.put(
"host", URL);
        params.put(
"port", new Integer(port));
        params.put(
"database", database);
        params.put(
"user", user);
        params.put(
"passwd", password);       
       
try {
            pgDatastore
=(PostgisDataStore) factory.createDataStore( params );
           
if(pgDatastore!=null){
                System.out.println(
"系统连接到位于:"+URL+"的空间数据库"+database+"成功!");
            }
else{
                System.out.println(
"系统连接到位于:"+URL+"的空间数据库"+database+"失败!请检查相关参数");
            }

        }
catch (IOException e) {
            e.printStackTrace();
            System.out.println(
"系统连接到位于:"+URL+"的空间数据库"+database+"失败!请检查相关参数");
        }

    }


   
//读取指定类型名的地理特征
    public static void getFeatureSource(String sourceName){
       
try {
            fsBC
= pgDatastore.getFeatureSource(sourceName);
           
//System.out.println(fsBC.getFeatures().size());
        }
catch (IOException e) {
            e.printStackTrace();
        }
       
    }

   
//取得POSTGIS中所有的地理图层
    public static void getAllLayers(){
       
try {
            String[] typeName
= pgDatastore.getTypeNames();
           
for(int i=0;i<typeName.length;i++){
                System.out.println(typeName[i]);
            }

        }
catch (IOException e) {
            e.printStackTrace();
        }

    }

   
//获取图层地理元素属性(Feature Attribute)
    public static void getAttribute(){
        FeatureType ftBC
=fsBC.getSchema();
        System.out.println(ftBC.getAttributeCount());
       
for (int i = 0; i < ftBC.getAttributeCount(); i++) {
            AttributeType at
= ftBC.getAttributeType( i );
           
//判断属性类型是否为可分配的几何对象
            if (!Geometry.class.isAssignableFrom(at.getType()))
                System.out.print(at.getType()
+ "\t");
        }

        System.out.println();
       
for (int i = 0; i < ftBC.getAttributeCount(); i++) {
            AttributeType at
= ftBC.getAttributeType( i );
           
if (!Geometry.class.isAssignableFrom(at.getType()))
                System.out.print(at.getName()
+ "\t");
        }

    }

   
   
//从数据容器中读取所有的特征属性
    @SuppressWarnings("deprecation")
   
public static void PostGisReading(){
       
try {
            FeatureResults fsRU
= fsBC.getFeatures();
            FeatureReader reader
= fsRU.reader();
           
while (reader.hasNext()) {
                Feature feature;
               
try {
                    feature
= reader.next();
                    System.out.print(feature.getID()
+ "\t");
                   
for (int i = 0; i < feature.getNumberOfAttributes(); i++) {
                        Object attribute
= feature.getAttribute( i );
                       
if (!(attribute instanceof Geometry))
                            System.out.print(attribute
+ "\t");
                    }

                    System.out.println();
                }
catch (NoSuchElementException e) {
                    e.printStackTrace();
                }
catch (IllegalAttributeException e) {
                    e.printStackTrace();
                }

            }

            reader.close();
        }
catch (IOException e1) {
            e1.printStackTrace();
        }

    }

   
   
//添加特征值到新的特征对象中。等同于新建一个postgis数据表并向其中插入数据
    @SuppressWarnings("deprecation")
   
public static void createFeatures(){
       
try {
            AttributeType geom
= AttributeTypeFactory.newAttributeType("the_geom",LineString.class);
            AttributeType name
= AttributeTypeFactory.newAttributeType("name",String.class);
            FeatureType ftRoad
= FeatureTypeFactory.newFeatureType
                                (
new AttributeType[] {geom,name}, "tem_road");
            WKTReader wktReader
= new WKTReader();
           
try {
                LineString geometry
= (LineString) wktReader.read("LINESTRING (0 0, 10 10)");
                String roadName
="武络路";
                pgDatastore.createSchema(ftRoad);
                FeatureWriter aWriter
= pgDatastore.getFeatureWriter("tem_road",
                        ((FeatureStore) pgDatastore.getFeatureSource(
"tem_road")).getTransaction());
               
/** *//**如有批量导入数据要求,可使用 org.geotools.data.FeatureStore */
                Feature aNewFeature
= aWriter.next();
                aNewFeature.setAttribute(
"the_geom",geometry);
                aNewFeature.setAttribute(
"name", roadName);
                aWriter.write();
                aWriter.close();
            }
catch (ParseException e) {
                e.printStackTrace();
            }
catch (IllegalAttributeException e) {
                e.printStackTrace();
            }
catch (IOException e) {
                e.printStackTrace();
            }

        }
catch (FactoryRegistryException e) {
            e.printStackTrace();
        }
catch (SchemaException e) {
            e.printStackTrace();
        }

    }

   
   
//添加Feature到已知的图层之中
    public static void insertFeatures(String featurename){
        WKTReader wktReader
= new WKTReader();
       
try {
            LineString geometry
= (LineString) wktReader.read("LINESTRING (10 10, 20 20)");
            String roadName
="珞瑜路";
            FeatureSource source
= pgDatastore.getFeatureSource(featurename);
            FeatureWriter aWriter
= pgDatastore.getFeatureWriterAppend(featurename,((FeatureStore) source).getTransaction());
           
/** *//**如有批量导入数据要求,可使用 org.geotools.data.FeatureStore */
            Feature feature
= aWriter.next();
           
try {
                feature.setAttribute(
"the_geom",geometry);
                feature.setAttribute(
"name", roadName);
            }
catch (IllegalAttributeException e) {
               
// TODO 自动生成 catch 块
                e.printStackTrace();
            }

            aWriter.write();
            aWriter.close();
        }
catch (ParseException e1) {
           
// TODO 自动生成 catch 块
            e1.printStackTrace();
        }
catch (IOException e) {
           
// TODO 自动生成 catch 块
            e.printStackTrace();
        }


    }

   
   
public static void main(String[] args) throws IOException{
        ConnPostGis(
"","localhost",5432,"navigation","root","to0124@c");
       
/**//*读取空间库中所有图层*/
        getAllLayers();
       
/**//*读取roads图层的空间库,取得FeatureSource对象,
         * getAttribute()方法用于读取此图层所定义的所有的属性
         * 并通过PostGisReading()方法读取此图层中所有信息
*/

        getFeatureSource(
"roads");
        getAttribute();
        PostGisReading();
       
/**//*在空间库中新建一个schema并向表中插入数据*/
        createFeatures();
       
/**//*向tem_road图层的空间库中插入一条新的记录*/
        insertFeatures(
"tem_road");
       
/**//*修改空间库记录*/
    }

}


      目前对GeoTools真的有些失望。。。不过作为一个开源中间件,它做到目前这个地位真的除了它推出比较早以外,还得感谢开源社区的帮助,2006年10月份推出的2.2版本其中对WMS中图层的渲染效率的大幅提升就是得益与Richard兄台的绝妙建议。自己也希望能向Richard学习,一个43岁的丹麦程序员,真的让人真的体会到什么叫“Open Mind”。。。过年期间的事情也有了眉目,着力修正shp2pqsql的问题。目前随post安装版推出的这个程序还是有些bug,在中文编码以及容错方面都需要提高。
  • 2
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
org.geotools org.geotools.arcsde org.geotools.arcsde.data org.geotools.arcsde.data.versioning org.geotools.arcsde.data.view org.geotools.arcsde.filter org.geotools.arcsde.gce org.geotools.arcsde.gce.band org.geotools.arcsde.gce.imageio org.geotools.arcsde.gce.producer org.geotools.arcsde.pool org.geotools.axis org.geotools.brewer.color org.geotools.coverage org.geotools.coverage.grid org.geotools.coverage.grid.io org.geotools.coverage.grid.io.imageio org.geotools.coverage.io org.geotools.coverage.processing org.geotools.coverage.processing.operation org.geotools.data org.geotools.data.collection org.geotools.data.crs org.geotools.data.db2 org.geotools.data.db2.filter org.geotools.data.dir org.geotools.data.gml org.geotools.data.gpx org.geotools.data.gpx.temporal org.geotools.data.h2 org.geotools.data.jdbc org.geotools.data.jdbc.attributeio org.geotools.data.jdbc.datasource org.geotools.data.jdbc.fidmapper org.geotools.data.jdbc.referencing org.geotools.data.memory org.geotools.data.mif org.geotools.data.mysql org.geotools.data.oracle org.geotools.data.oracle.attributeio org.geotools.data.oracle.referencing org.geotools.data.oracle.sdo org.geotools.data.ows org.geotools.data.postgis org.geotools.data.postgis.attributeio org.geotools.data.postgis.collection org.geotools.data.postgis.fidmapper org.geotools.data.postgis.referencing org.geotools.data.property org.geotools.data.shapefile org.geotools.data.shapefile.dbf org.geotools.data.shapefile.indexed org.geotools.data.shapefile.indexed.attribute org.geotools.data.shapefile.prj org.geotools.data.shapefile.shp org.geotools.data.shapefile.shp.xml org.geotools.data.store org.geotools.data.tiger org.geotools.data.view org.geotools.data.vpf org.geotools.data.vpf.exc org.geotools.data.vpf.file org.geotools.data.vpf.ifc org.geotools.data.vpf.io org.geotools.data.vpf.readers org.geotools.data.vpf.util org.geotools.data.wfs org.geotools.data.wms org.geotools.data.wms.request org.geotools.data.wms.response org.geotools.data.wms.xml org.geotools.demo org.geotools.demo.data org.geotools.demo.example org.geotools.demo.features org.geotools.demo.geometry org.geotools.demo.introduction org.geotools.demo.jts org.geotools.demo.libraryJTS org.geotools.demo.main org.geotools.demo.mappane org.geotools.demo.metadata.example org.geotools.demo.postgis org.geotools.demo.swing org.geotools.demo.swing.process org.geotools.demo.widgets org.geotools.demo.xml org.geotools.display.canvas org.geotools.display.canvas.map org.geotools.display.event org.geotools.display.geom org.geotools.display.style org.geotools.factory org.geotools.feature org.geotools.feature.collection org.geotools.feature.simple org.geotools.feature.type org.geotools.feature.visitor org.geotools.filter org.geotools.filter.capability org.geotools.filter.expression org.geotools.filter.function org.geotools.filter.function.math org.geotools.filter.identity org.geotools.filter.parser org.geotools.filter.spatial org.geotools.filter.text.cql2 org.geotools.filter.text.txt org.geotools.filter.v1_0 org.geotools.filter.v1_0.capabilities org.geotools.filter.v1_1 org.geotools.filter.v1_1.capabilities org.geotools.filter.visitor org.geotools.gce.arcgrid org.geotools.gce.geotiff org.geotools.gce.geotiff.crs_adapters org.geotools.gce.geotiff.IIOMetadataAdpaters org.geotools.gce.geotiff.IIOMetadataAdpaters.utils org.geotools.gce.geotiff.IIOMetadataAdpaters.utils.codes org.geotools.gce.gtopo30 org.geotools.gce.image org.geotools.gce.imagemosaic org.geotools.gce.imagepyramid org.geotools.geometry org.geotools.geometry.array org.geotools.geometry.coordinatesequence org.geotools.geometry.iso org.geotools.geometry.iso.aggregate org.geotools.geometry.iso.complex org.geotools.geometry.iso.coordinate org.geotools.geometry.iso.index org.geotools.geometry.iso.index.quadtree org.geotools.geometry.iso.io org.geotools.geometry.iso.io.wkt org.geotools.geometry.iso.operation org.geotools.geometry.iso.operation.overlay org.geotools.geometry.iso.operation.relate org.geotools.geometry.iso.primitive org.geotools.geometry.iso.root org.geotools.geometry.iso.topograph2D org.geotools.geometry.iso.topograph2D.index org.geotools.geometry.iso.topograph2D.util org.geotools.geometry.iso.util org.geotools.geometry.iso.util.algorithm2D org.geotools.geometry.iso.util.algorithmND org.geotools.geometry.iso.util.elem2D org.geotools.geometry.iso.util.interpolation org.geotools.geometry.iso.util.topology org.geotools.geometry.jts org.geotools.geometry.jts.coordinatesequence org.geotools.geometry.jts.spatialschema org.geotools.geometry.jts.spatialschema.geometry org.geotools.geometry.jts.spatialschema.geometry.aggregate org.geotools.geometry.jts.spatialschema.geometry.complex org.geotools.geometry.jts.spatialschema.geometry.geometry org.geotools.geometry.jts.spatialschema.geometry.primitive org.geotools.geometry.text org.geotools.gml org.geotools.gml.producer org.geotools.gml2 org.geotools.gml2.bindings org.geotools.gml3 org.geotools.gml3.bindings org.geotools.gml3.bindings.smil org.geotools.gml3.smil org.geotools.gpx org.geotools.gpx.bean org.geotools.gpx.binding org.geotools.graph.build org.geotools.graph.build.basic org.geotools.graph.build.feature org.geotools.graph.build.line org.geotools.graph.build.opt org.geotools.graph.build.polygon org.geotools.graph.io org.geotools.graph.io.standard org.geotools.graph.path org.geotools.graph.structure org.geotools.graph.structure.basic org.geotools.graph.structure.line org.geotools.graph.structure.opt org.geotools.graph.traverse org.geotools.graph.traverse.basic org.geotools.graph.traverse.standard org.geotools.graph.util org.geotools.graph.util.delaunay org.geotools.graph.util.geom org.geotools.graph.util.graph org.geotools.gui.headless org.geotools.gui.swing org.geotools.gui.swing.contexttree org.geotools.gui.swing.contexttree.column org.geotools.gui.swing.contexttree.node org.geotools.gui.swing.contexttree.popup org.geotools.gui.swing.contexttree.renderer org.geotools.gui.swing.crschooser org.geotools.gui.swing.datachooser org.geotools.gui.swing.datachooser.model org.geotools.gui.swing.demo org.geotools.gui.swing.event org.geotools.gui.swing.filter org.geotools.gui.swing.icon org.geotools.gui.swing.image org.geotools.gui.swing.map.map2d org.geotools.gui.swing.map.map2d.control org.geotools.gui.swing.map.map2d.decoration org.geotools.gui.swing.map.map2d.event org.geotools.gui.swing.map.map2d.handler org.geotools.gui.swing.map.map2d.listener org.geotools.gui.swing.map.map2d.strategy org.geotools.gui.swing.misc org.geotools.gui.swing.misc.filter org.geotools.gui.swing.misc.Render org.geotools.gui.swing.process org.geotools.gui.swing.propertyedit org.geotools.gui.swing.propertyedit.filterproperty org.geotools.gui.swing.propertyedit.model org.geotools.gui.swing.propertyedit.styleproperty org.geotools.gui.swing.referencing org.geotools.gui.swing.style org.geotools.gui.swing.style.sld org.geotools.gui.swing.table org.geotools.gui.swing.tree org.geotools.image org.geotools.image.io org.geotools.image.io.metadata org.geotools.image.io.mosaic org.geotools.image.io.netcdf org.geotools.image.io.stream org.geotools.image.io.text org.geotools.image.jai org.geotools.image.palette org.geotools.index org.geotools.index.quadtree org.geotools.index.quadtree.fs org.geotools.index.rtree org.geotools.index.rtree.cachefs org.geotools.index.rtree.database org.geotools.index.rtree.database.mysql org.geotools.index.rtree.fs org.geotools.index.rtree.memory org.geotools.io org.geotools.jdbc org.geotools.kml org.geotools.kml.bindings org.geotools.legend org.geotools.map org.geotools.map.event org.geotools.math org.geotools.measure org.geotools.metadata org.geotools.metadata.iso org.geotools.metadata.iso.citation org.geotools.metadata.iso.constraint org.geotools.metadata.iso.content org.geotools.metadata.iso.distribution org.geotools.metadata.iso.extent org.geotools.metadata.iso.identification org.geotools.metadata.iso.lineage org.geotools.metadata.iso.maintenance org.geotools.metadata.iso.quality org.geotools.metadata.iso.spatial org.geotools.metadata.sql org.geotools.nature org.geotools.openoffice org.geotools.ows org.geotools.ows.bindings org.geotools.ows.v1_1 org.geotools.parameter org.geotools.process org.geotools.process.impl org.geotools.process.literal org.geotools.referencing org.geotools.referencing.crs org.geotools.referencing.cs org.geotools.referencing.datum org.geotools.referencing.example org.geotools.referencing.factory org.geotools.referencing.factory.epsg org.geotools.referencing.factory.wms org.geotools.referencing.operation org.geotools.referencing.operation.builder org.geotools.referencing.operation.matrix org.geotools.referencing.operation.projection org.geotools.referencing.operation.transform org.geotools.referencing.piecewise org.geotools.referencing.wkt org.geotools.renderer org.geotools.renderer.i18n org.geotools.renderer.lite org.geotools.renderer.lite.gridcoverage2d org.geotools.renderer.shape org.geotools.renderer.shape.shapehandler.jts org.geotools.renderer.shape.shapehandler.simple org.geotools.renderer.style org.geotools.repository org.geotools.repository.adaptable org.geotools.repository.defaults org.geotools.repository.postgis org.geotools.repository.property org.geotools.repository.shapefile org.geotools.repository.styling org.geotools.repository.wfs org.geotools.repository.wms org.geotools.sld org.geotools.sld.bindings org.geotools.styling org.geotools.styling.visitor org.geotools.svg org.geotools.test org.geotools.text org.geotools.text.filter org.geotools.util org.geotools.util.logging org.geotools.utils org.geotools.utils.coveragetiler org.geotools.utils.imagemosaic org.geotools.utils.imageoverviews org.geotools.utils.imagepyramid org.geotools.utils.progress org.geotools.validation org.geotools.validation.attributes org.geotools.validation.dto org.geotools.validation.network org.geotools.validation.relate org.geotools.validation.spatial org.geotools.validation.xml org.geotools.wfs org.geotools.wfs.bindings org.geotools.wfs.protocol org.geotools.wfs.v_1_0_0.data org.geotools.wfs.v_1_1_0.data org.geotools.xlink org.geotools.xml org.geotools.xml.filter org.geotools.xml.gml org.geotools.xml.handlers org.geotools.xml.handlers.xsi org.geotools.xml.impl org.geotools.xml.impl.jxpath org.geotools.xml.schema org.geotools.xml.schema.impl org.geotools.xml.styling org.geotools.xml.test org.geotools.xml.transform org.geotools.xml.wfs org.geotools.xml.xLink org.geotools.xml.xsi org.geotools.xs org.geotools.xs.bindings org.geotools.xs.facets
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值