geotools user guide


User Guide

The GeoTools User Guide provides tutorials introducing spatial conceptsproject background, and a reference section covering each module, plugin and extension.

Please report any issues with this documentation using the project issue tracker.

  • Create an Issue .

  • Known Documentation Issues (Issue Tracker)

  • Jody Garnett (Module Maintainer)

For small typos and source code corrections email the module maintainer above.

Version: 27-SNAPSHOT

  • GeoTools
    • Core Features
    • Supported Formats
    • Implemented Standards
  • Welcome
    • License
    • Communication and Support
    • GeoTools user list posting guide
    • Architecture
    • How to Use GeoTools
    • Use of Standards
    • Upgrade
    • Integration
    • Eclipse IDE Tips
    • NetBeans IDE Tips
    • GeoTools FAQ
  • Frequently Asked Questions
  • Building
    • Install Build Tools
    • Source Code
    • Using Maven
    • Using Git
    • Building FAQ
  • Tutorials
    • Quickstart
    • Feature Tutorial
    • Geometry CRS Tutorial
    • Query Tutorial
    • Image Tutorial
    • Coverage Processor Tutorial
    • Map Style Tutorial
    • Factory Tutorial
    • Function Tutorial
    • Process Tutorial
    • JAI-EXT Tutorial
    • ContentDataStore Tutorial
  • Library
    • OpenGIS
      • OpenGIS FAQ
      • Model
      • FeatureType
      • Feature
      • Filter
      • GridCoverage
      • ISO Geometry
      • Coordinate Systems
      • Symbology Encoding
      • Progress
      • Name and Record
      • Text
      • Parameter
      • Unit
    • JTS
      • JTS FAQ
      • Geometry
      • Testing equality of Geometry objects
      • Geometry Relationships
      • Point Set Theory and the DE-9IM Matrix
      • Geometry Operations
      • CoordinateFilter
      • Simplify
      • Snap a Point to a Line
      • Closing a LineString
      • Combine Geometry
    • Metadata
      • Metadata FAQ
      • Metadata Internals
      • Commons Pool
      • Metadata
      • GeoTools
      • Range
      • Text
      • Converter
      • URLs
    • Referencing
      • References
      • Maven
    • Coverage
      • Coverage FAQ
      • Internal
      • GridCoverage
      • ArcGrid Plugin
      • GeoTIFF Plugin
      • GrassRaster Plugin
      • Data structure of a raster map
      • Usage
      • Image Plugin
      • ImageIO-EXT GDAL Plugin
      • Mosaic Plugin
      • Image Pyramid Plugin
      • Example
      • Coverage MultiDimensional
      • GeoPackage Plugin
      • Coverage IO Plugin
      • GeoTIFF New Plugin
      • JP2K Plugin
      • NetCDF Plugin
      • Matlab Plugin
      • Coverage Tools
    • Main
      • Main FAQ
      • Internals
      • DataUtilities
      • Parameter
      • Filter
      • Function List
      • Feature
      • FeatureCollection
      • WKT Parser
      • Envelope
      • JTS Utility Class
      • Java2D Shape
      • DataStore
      • Repository
      • Style Layer Descriptor
    • Data
      • Data FAQ
      • Internals
      • DataStore
      • FeatureSource
      • MemoryDataStore
      • Exporting
      • Shapefile Plugin
      • OGR Plugin
      • Pregeneralized Plugin
      • Property Plugin
      • GeoPackage Plugin
      • MongoDB Plugin
      • CSV Plugin
      • KML Plugin
      • Solr Plugin
      • Elasticsearch Plugin
      • WFS-NG Plugin
    • JDBC
      • JDBC FAQ
      • Internals
      • JDBCDataStore
      • DB2 Plugin
      • H2 Plugin
      • HANA Plugin
      • MySQL Plugin
      • Oracle Plugin
      • PostGIS Plugin
      • SQL Server Plugin
      • Teradata Plugin
      • GeoPackage Plugin
      • Ingres Plugin
    • CQL
      • CQL FAQ
      • Internal
      • CQL
      • ECQL
    • XML
      • XML FAQ
      • Internals
      • Geometry
      • Filter
      • Style
      • Schema Resolving
    • Render
      • Render FAQ
      • GTRenderer to draw maps
      • Map data and display classes
      • Styling features for display
      • How to parse an SLD file
      • How to write a SLD file
      • Icon
      • WKT Marks
      • WKT Marks as Strokes
      • Chart Plugin
      • SVG Plugin
    • HTTP Clients
      • LoggingHttpClient
      • HTTPClient
      • HTTPResponse
      • HTTPClientFactory
  • Extensions
    • Application Schema Support
      • Application Schema DataAccess
      • Application Schema Resolver
      • Sample DataAccess
      • Application Schema Packages
    • Brewer
      • Brewer FAQ
      • Classifier
      • ColorBrewer
    • Complex Feature
      • Example
    • Graph
      • Graph Model
      • Graph
      • Building
      • Building a FeatureCollection from your Graph
      • Shortest Path
    • Vector grids
      • Polygon grids
      • Line grids
    • Mapbox Styles Module
      • Overview
      • Mapbox Style Specification
    • OGC
      • net.opengis.ows
      • net.opengis.wcs
      • net.opengis.wfs
      • net.opengis.wfsv
      • net.opengis.wps
      • org.w3.xlink
    • Tile client
      • Tile client
    • Transform plugin
      • Selecting attributes
      • Renaming attributes
      • Creating new attributes with expressions
    • WMS
      • WMS FAQ
      • WebMapServer
    • WMTS
      • WebMapTileServer
    • XSD
      • XSD-Core
      • XSD-FES
      • XSD-Filter
      • XSD GML2
      • XSD-GML3
      • XSD-KML
      • XSD OWS
      • XSD SLD
      • XSD WCS
      • XSD WFS
      • XSD WMS
      • XSD WPS
    • YSLD
      • YSLD Syntax
      • YSLD Grammar
      • Using YSLD
  • Unsupported
    • ArcGIS REST API DataStore
    • Cartographic CSS Plugin
    • GeoJSON Plugin
    • Process
    • Swing
    • SWT
    • WPS
    • Sample
    • GML geometry XML parsing support using StAX

https://docs.geotools.org/stable/userguide/index.html

GeoTools

GeoTools is an open source (LGPL) Java code library which provides standards compliant methods for the manipulation of geospatial data, for example to implement Geographic Information Systems. The GeoTools library data structures are based on Open Geospatial Consortium (OGC) specifications.

GeoTools是一个开源的Java代码库,提供标准的方法来支持地理数据的操作,例如实现了地理信息系统。GeoTools库的代码结构基于OGC的规范。

_images/geotools.png

GeoTools is used by a number of projects including web services, command line tools and desktop applications.

GeoTools被许多项目使用,包括web服务、命令行工具和桌面应用程序。

Core Features核心特征

  • Definition of interfaces for key spatial concepts and data structures定义关键空间概念和数据结构的接口

    • Integrated Geometry support provided by Java Topology Suite (JTS)Java拓扑套件(JTS)提供的集成几何支持

    • Attribute and spatial filters using OGC Filter Encoding specification使用OGC过滤器编码规范的属性和空间过滤器

  • A clean data access API supporting feature access, transaction support and locking between threads一个干净的数据访问API,支持功能访问、事务支持和线程间锁定

    • Access GIS data in many file formats and spatial databases以多种文件格式和空间数据库访问GIS数据

    • Coordinate reference system and transformation support坐标参考系与转换支持

    • Work with an extensive range of map projections使用范围广泛的地图投影

    • filter and analyze data in terms of spatial and non-spatial attributes根据空间和非空间属性过滤和分析数据

  • A stateless, low memory renderer, particularly useful in server-side environments.无状态、低内存的渲染器,在服务器端环境中特别有用。

    • compose and display maps with complex styling用复杂的样式组合和显示地图

    • vendor extensions for fine control of text labels and color blending用于文本标签和颜色混合精细控制的供应商扩展

  • Powerful schema assisted parsing technology using XML Schema to bind to GML content使用XML模式绑定到GML内容的强大模式辅助解析技术

    The parsing / encoding technology is provided with bindings for many OGC standards including GML, Filter, KML, SLD, and SE.解析/编码技术为许多OGC标准提供了绑定,包括GML、Filter、KML、SLD和SE。

  • GeoTools Plugins: open plug-in system allowing you to teach the library additional formatsGeoTools插件:开放式插件系统,允许您教授库的其他格式

    • Plug-ins for the ImageIO-EXT project allowing GeoTools to read additional raster formats from GDAL ImageIO EXT项目的插件,允许GeoTools从GDAL读取其他光栅格式

  • GeoTools Extensions GeoTools扩展

    Provide additional capabilities built using the spatial facilities of the core library.提供使用核心库的空间设施构建的附加功能。

    _images/extension.png

    Extensions provide graph and networking support (for finding the shortest path), validation, a web map server client, bindings for XML parsing and encoding and color brewer!

          扩展提供图形和网络支持(用于寻找最短路径)、验证、web地图服务器客户端、XML解析和编码的绑定,以及color brewer!

  • GeoTools Unsupported

    GeoTools also operates as part of a wider community with a staging area used to foster new talent and promote experimentation.

    Some highlights are swing support (used in our tutorials!), SWT, local and web process support, additional symbology, additional data formats, generation of grids and a couple of implementations of ISO Geometry.

Supported Formats支持的格式

  • raster formats and data access栅格格式和数据获取

    • arcgrid

    • geotiff

    • grassraster

    • image ( JPEGTIFFGIFPNG ),

    • imageio-ext-gdal

    • imagemosaic

    • imagepyramid

    • JP2K

    • matlab

  • Database jdbc-ng support数据库支持jdbc-ng

    • db2

    • geopackage

    • hana

    • h2

    • mysql

    • oracle

    • postgis

    • sqlserver

    • teradata

  • Vector formats and data access矢量格式和数据获取

    • app-schema

    • csv

    • geojson

    • property

    • shapefile

    • wfs

  • XML Bindings XML绑定

    Java data structures and bindings provided for the following:以下的Java数据结构和绑定

    • xsd-core (xml simple types)

    • fes

    • filter

    • gml2

    • gml3

    • kml

    • ows

    • sld

    • wcs

    • wfs

    • wms

    • wmts

    • wps

    Additional Geometry, Filter and Style parser/encoders available for DOM and SAX applications.

          可用于DOM和SAX应用程序的其他几何体、过滤器和样式解析器/编码器。

Implemented Standards实现的标准

Support of numerous Open Geospatial Consortium (OGC) standards:支持大量的OGC标准:

  • OGC Style Layer Descriptor / Symbology Encoding data structures and rendering engine OGC风格的层描述符/符号编码数据结构和渲染引擎

  • OGC General Feature Model including Simple Feature support OGC通用功能模型,包括简单功能支持

  • OGC Grid Coverage representation of raster information 光栅信息的OGC网格覆盖表示

  • OGC Filter and Common Constraint Language (CQL) OGC过滤器和公共约束语言(CQL)

  • Clients for Web Feature Service, Web Map Service and experimental support for Web Process Service Web功能服务、Web地图服务和Web流程服务实验支持的客户端

  • ISO 19107 Geometry ISO 19107几何

Architecture软件架构

Having an understanding of how the GeoTools library is structured is helpful for sorting out what jars you need for your application.

了解GeoTools库的结构有助于分类应用程序所需的JAR。

This page introduces you to the parts of the GeoTools library and how they fit together. By including only the jars you need you can select just the right amount of GeoTools for your next project.

本页向您介绍GeoTools库的各个部分,以及它们是如何组合在一起的。通过只包含所需的JAR,您可以为下一个项目选择适当数量的GeoTools。

GeoTools Library

The GeoTools library forms a software “stack” with each jar building on the ideas and concepts defined in the previous one.

GeoTools库形成了一个软件“堆栈”,每个jar都基于上一个jar中定义的想法和概念。

../_images/geotools.png

Each layer of the “stack” is built on the ones below it:

“堆栈”的每一层都建立在它下面的层之上:

  • To use Referencing you need gt-opengisgt-referencing and gt-metadata 要使用引用,需要gt-opengis、gt-referencing和gt-metadata

  • To use Data you need gt-mainjtsgt-opengisgt-referencinggt-opengisgt-metadata要使用数据,您需要gt-main、jts、gt-opengis、gt-referencing、gt-opengis和gt-metadata

The maven tool can calculate the jars you need, please see the Eclipse or Netbeans quickstart for an example use.

maven工具可以计算您所需的JAR,请参阅Eclipse或Netbeans快速启动以获取示例使用。

Module

Purpose

gt-render

Implements of Java2D rendering engine to draw a map。Java2D绘制地图渲染引擎的实现

gt-jdbc

Implements for accessing spatial database。访问空间数据库的实现

gt-main

Implements for accessing spatial data。用于访问空间数据的实现

gt-xml

Implements of common spatial XML formats。通用空间XML格式的实现

gt-cql

Implements of Common Query Language for filters。过滤器通用查询语言的实现

gt-main

Interfaces for working with spatial information. Implements filter, feature, etc…用于处理空间信息的接口。实现过滤器、功能等…

jts

Definition and implementation of Geometry。几何的定义和实现

gt-coverage

Implementation for accessing raster information。访问光栅信息的实现

gt-referencing

Implementation of co-ordinate location and transformation。定位和坐标转换的实现

gt-metadata

Implementation of identification and description。识别和描述的实现

gt-opengis

Definition of interfaces for common spatial concepts。通用空间概念接口的定义

GeoTools Plugins GeoTools插件

GeoTools offers plug-ins to support additional data formats, different coordinate reference system authorities and so on.

GeoTools提供了支持其他数据格式、不同坐标参考系权限等的插件。

Module

JAR

Plugin

gt-render

   

gt-jdbc

gt-jdbc-db2

Geometry in DB2

 

gt-jdbc-h2

Pure Java “H2” database

 

gt-jdbc-mysql

Geometry in MySQL

 

gt-jdbc-oracle

Oracle SDO Geometry

 

gt-jdbc-postgis

PostgreSQL extension PostGIS

 

gt-jdbc-sqlserver

SQL Server

 

gt-jdbc-hana

SAP HANA

 

gt-jdbc-terasdata

Teradata

gt-main

gt-shape

Shapefile read/write support

 

gt-wfs

WFS read/write support

gt-xml

   

gt-cql

   

gt-main

   

jts

   

gt-coverage

gt-geotiff

GeoTIFF raster format

 

gt-arcgrid

arcgrid format

 

gt-mif

MIF format

 

gt-image

JPG, PNG, TIFF formats

gt-referencing

epsg-access .

Official EPSG database in Access

 

epsg-hsql

Pure Java port of EPSG database

 

epsg-wkt

Lightweight copy of EPSG codes

 

epsg-postgresql

PostgreSQL port of EPSG database

gt-metadata

   

gt-opengis

   

Usually at least one plug-in is needed for each layer for GeoTools to do something. As an example every time you use the referencing module please make sure you have an EPSG plugin around (or the referencing module will not know that “EPSG:4326” is the world as we know it).

通常每个层至少需要一个插件,GeoTools才能完成某些工作。例如,每次使用reference模块时,请确保您有一个EPSG插件(否则引用模块将不知道“EPSG:4326”是我们所知道的世界)。

GeoTools Extensions GeoTools扩展

We have gone a bit further and implemented some interesting “extensions” on top of the GeoTools library. These extensions provide additional capabilities that are built on top of GeoTools using the spatial facilities of the library.

我们更进一步,在GeoTools库的基础上实现了一些有趣的“扩展”。这些扩展提供了在GeoTools之上使用图书馆的空间设施构建的附加功能。

../_images/extension.png

The extensions are independent of each other offering and may be of use in your application. Here is a brief listing of the extensions at the time of writing.

这些扩展相互独立,可能会在您的应用程序中使用。以下是本文撰写时的扩展的简要列表。

JAR

Extension

gt-graph

Work with graph and network traversals

gt-validation

Quality assurance for spatial data

gt-wms

Web Map Server client

gt-xsd

Parsing/Encoding for common OGC schemas

gt-brewer

Generation of styles using color brewer

XML

To support the XML module in GeoTools we have bundled up several XML schemas in JAR form (to prevent needing to download them from the Internet each time they are needed). In addition these jars contain a generated Java data structure produced with the Eclipse Modeling Framework.

JAR

Schema

net.opengis.ows

open web services schema

net.opengis.wfs

web feature service

net.opengis.wps

web processing service schema

net.opengis.wcs

web coverage service schema

net.opengis.wfs

web feature service schema

org.w3.xlink

XLink schema

These facilities are used by the XSD parser by way of a series of XSD plugins. These plugins indicating how to parse and encode additional content using Eclipse XSD library to parse XML schema documents and offer “bindings” showing how to parse and encode to Java classes such as String, Date, URL and Geometry.

XSD解析器通过一系列XSD插件使用这些功能。这些插件指示如何使用Eclipse XSD库解析XML模式文档并对其他内容进行解析和编码,并提供“绑定”,显示如何解析和编码到Java类,如字符串、日期、URL和几何体。

JAR

Bindings

gt-xsd-core

Basic types defined by XML schema

gt-xsd-fes

filter 2.0

gt-xsd-filter

filter (used by OGC CAT and WFS)

gt-xsd-kml

keyhole markup language

gt-xsd-wfs

web feature service

gt-xsd-wps

web processing service

gt-xsd-gml3

geographic markup language 3

gt-xsd-gml2

geographic markup language 2

gt-xsd-ows

open web services

gt-xsd-wcs

web coverage service

gt-xsd-wms

web map service

gt-xsd-sld

style layer descriptor

GeoTools Unsupported非官方的。。过期的。。不再支持的。。

There are also a number of “unsupported” plugins and extensions. These modules are not distributed by the project management committee as part of the GeoTools download, however they are available via maven or individual download.

Unsupported

Purpose

gt-swt

Standard widget toolkit interactive map

gt-swing

Swing interactive map

gt-oracle

retired oracle support

gt-postgis

retired PostGIS support

gt-db2

retired db2 support

gt-wps

Web Processing Service client

gt-process

Job system for spatial data

How to Use GeoTools

GeoTools provides an excellent series of tutorials to help you get started:

  • Quickstart

Adding GeoTools to your Application添加GeoTools到你的应用中

Maven (recommended):建议使用Maven:

The quickstart is written with the maven build system in mind. The maven build system is very good at sorting out dependencies between lots of little jars - and is the recommended way to start using GeoTools.

Both Eclipse and NetBeans offer maven integration, for details please review the Eclipse Quickstart and NetBeans quickstart.

Using maven in concert with your IDE, and looking over the pictures on this page is recommended.

Download:

Traditionally users just dump all the jars into their IDE and have a go, please be advised that some of the jars will be in conflict.

  1. Dump everything from a binary distribution of GeoTools into your IDE

  2. Remove all the jars that say epsg in them - except for the gt2-epsg jar.

  3. Ensure your JRE has JAI and ImageIO if you are doing raster work

  4. Ignore the rest of this page

For detailed step-by-step instructions review the Eclipse quickstart and Netbeans quickstart. Instructions for downloading and selecting jars are provided at the end of the document as an alternative.

Public API

As an open source library you are free to call any of the GeoTools classes needed for your application to be delivered on time.

However, GeoTools offers a clean approach which should cause the least amount of disruption to your code during library upgrades as GeoTools matures.

GeoTools cleanly separates out several groups of application programming interfaces (API) from the internal implementation of the library.

If you write your code against these interfaces they offer a stable target as the library upgrades. In the event these interfaces are changed (sometimes standards change on us) the interfaces will be deprecated for a single release cycle allowing you a chance to upgrade.

Interfaces for Concepts and Ideas概念的接口

Formally these interfaces come from three locations:

  • gt-opengis - interfaces backed by ISO and OGC standards (as explained in the Use of Standards page).

  • JTS Topology Suite - geometry library implementing the Simple Features for SQL (SFSQL) OGC standard.

  • gt-main - interfaces provided by GeoTools.

We also have one stalled work in progress:

  • gt-opengis has a set of ISO19107 geometry interfaces (anyone interested in curves and 3D?)

These interfaces represent spatial concepts and data structures in your application and are suitable for use in method signatures.

Classes for Implementation实现的类

While interfaces are used to represent the data structures employed by GeoTools, we also provide public classes to get the job done.

Public classes are provided for the purpose of:

  • Utility classes to make things easier to work with. Examples are the CQLDataUtilities and JTS classes. Each of these provide public methods to help you make the most of the services provided by GeoTools.

  • Helping glue the library together at runtime - an example is the FactoryFinders which allow you to look up available implementations on the CLASSPATH.

  • GeoTools “Extensions” provide additional services on top of the library and require additional public classes to make this happen. An example is the ColorBrewer class provided by gt-brewer.

You can make use of public classes in these modules directly, in all cases they are utilities to get the job done. These classes are suitable for use in your import section. There is no need to use these classes in your method signatures as they do not represent data structures.

Factories for Creation创建的工厂

Interfaces only define what a data structure should look like, and do not provide a way to create an object. In Java the work around is to provide a “factory” that provides “create” methods which you can use instead of new.

GeoTools provides Factory classes allowing you to create the various objects used by the library, such as Features, Styles, Filters, CoordinateReferencingSystems, and DataStores.

GeoTools provides a FactoryFinder system to locate the available factory implementations on the CLASSPATH. By using a FactoryFinder your code can be built to function using only interfaces.

For more information review the page How to Create Something which outlines how to locate an appropriate implementation at runtime.

Separation of Concerns

While you could find and use each of the various Factory implementations directly this would introduce a dependency between your code and that exact implementation. This idea of depending on a specific implementation makes your code brittle with respect to change, and prevents you from taking advantage of a better implementation when it is made available in the future.

Bad practice with direct dependency on ShapeFileDataStoreFactory:

ShapefileDataStoreFactory factory = new ShapefileDataStoreFactory();
ShapeFileDataStore = factory.createDataStore( file );

This code example would have been fine for GeoTools 2.1, however for GeoTools 2.2 an “indexed” shapefile datastore was created with far better performance.

Here is a replacement that allows GeoTools to return an indexed datastore if one is available:

DataStore dataStore = DataStoreFinder.getDataStore( file );

The DataStoreFinder class looks up all the DataStoreFactory implementations available on the CLASSPATH and sorts out which one can make a DataStore to access the provided file.

How to Create

Code leveraging GeoTools usually works against the Java interfaces only but interfaces in Java don’t provide any way to create actual objects. GeoTools therefore provides Factories which are concrete implementations through whose interface users can create actual GeoTools objects such as FeaturesStylesFiltersDataStores, and MathTransforms.

This page explains how to use the FactoryFinder system to find the appropriate Factory implementations to instantiate particular objects. The section page will show alternative approaches to obtain and use a particular implementation of an appropriate DataStore interface; those examples show the utility of the FactoryFinder system.

Creating in GeoTools

To create an implementation (and not get your hands dirty by depending on a specific class) Java developers are asked to use a Factory. Other languages like Scala allow the definition of a constructors as part of the interface itself.

In GeoTools we use a FactoryFinder to look for a factory implementation on the classpath.

Here is a quick example showing how to create and use a Filter:

FilterFactory2 factory = CommonFactoryFinder.getFilterFactory2( null );
Filter filter = factory.less( factory.property( "size" ), factory.literal( 2 ) );

if( filter.evaulate( feature )){
   System.out.println( feature.getId() + " had a size larger than 2" );
}

In this example we:

  1. Found an object which implements the GeoAPI FilterFactory2 interface using a FactoryFinder.

    (CommonFactoryFinder gave us FilterFactoryImpl in this case)

  2. Used the Factory to produce our Instance.

    (FilterFactoryImpl.less(..) method was used to create a PropertyIsLessThan Filter)

  3. Used the instance to accomplish something.

    (we used the filter to check the size of a Feature )

FactoryFinder Reference

There is a loose naming convention where we try and have a clear progression from interface name, factory name to factory finder name.

However in practice we found it useful to gather many of the common factories together into a common class for lookup.

CommonFactoryFinder

  • FilterFactory

  • StyleFactory

  • Function

  • FileDataStore - factory used to work with file data stores

  • FeatureFactory - factory used to create features

  • FeatureTypeFactory - factory used to create feature type description

  • FeatureCollections - factory used to create feature collection

For access to feature (i.e. vector) information:

  • DataAccessFinder - listing DataAccessFactory for working with feature data

  • DataStoreFinder - lists DataStoreFactorySpi limited to simple features

  • FileDataStoreFinder - Create of FileDataStoreFactorySpi instances limited to file formats

For access to coverage (i.e. raster) information:

  • GridFormatFinder - access to GridFormatFactorySpi supporting raster formats

  • CoverageFactoryFinder - access to GridCoverageFactory

JTSFactoryFinder - used to create JTS GeometryFactory and PercisionModel

  • GeometryFactory

  • PrecisionModel

ReferencingFactoryFinder - used to list referencing factories

  • DatumFactory

  • CSFactory

  • DatumAuthorityFactory

  • CSAuthorityFactory

  • CRSAuthorityFactory

  • MathTransformFactory

  • CoordinateOperationFactory

  • CoordinateOperationAuthorityFactory

Where to get a Factory

It really depends on your application, depending on your environment you may locate a factory by either:

  • Using a GeoTools FactoryFinder. Most factory finders are provided by the main module. They will hunt down an implementation on the CLASSPATH for you to use.

  • Use of “Container” - you may find an implementation provided as part of your application container (especially for a Java EE application). You can take this approach in normal applications with a container implementation like Spring, or PicoContainer

  • Use of “JNDI” - your application may also store an implementation in JNDI (this approach is often used to locate a DataSource in a JEE application)

  • Direct use of a known factory. You can always create a new Factory yourself and make use of it to create interfaces.

  • Direct use of an implementation. You may decide to duck the factory game completely and make use of a specific implementation using new.

These examples will usually use a factory finder of some sort. For the details please review the How to Find a Factory page.

FactoryFinder

While the use of Factories has become common place (especially in development environments like Spring). GeoTools has its own FactoryFinder classes, unique to project, which is how the library looks up what plugins are available for use.

These facilities are also available for use in your own application.

FactoryFinder uses the “built-in” Java plug-in system known as Factory Service Provide Interface. This technique allows a jar to indicate what services it makes available (in this case implementations of a factory interface).

To make this easier to use we have a series of utility classes called FactoryFinders. These classes work as a match maker - looking around at what is available on the CLASSPATH. They will perform the “search” and locate the implementation you need.

Here is an example:

FilterFactory filterFactory = CommonFactoryFinder.getFilterFactory( null );

About FactorySPI

The FactorySPI system is the out of the box plug in system that ships with Java. That is why we like it - we are sure you already are using the Java software after all. The SPI part is pronounced “spy” and stands for Service, Provider, Interface.

The FactorySPI system has a look on your CLASSPATH and locates implementations of a requested service scattered around all the jars you have. It does this by looking in the jar MANIFEST folder in a services directory.

Factory SPI is a runtime plugin system; so your application can “discover” and use new abilities that GeoTools provides over time. As our shapefile support gets better and better your application will notice and make use of the best implementation for the job.

If you are curious you can make use of the FactorySPI system yourself to locate anything we got going on in GeoTools:

Hints hints = GeoTools.getDefaultHints();
FactoryRegistry registry = new FactoryCreator(Arrays.asList(new Class[] {FilterFactory.class,}));
Iterator i = registry.getServiceProviders( FilterFactory.class, null, hints );
while( i.hasNext() ){
    FilterFactory factory = (FilterFactory) i.next();
}

Notes:

  • keep your FactoryRegistry around, hold it in a static field or global lookup service such as JNDI.

  • The registry usually creates one instance (the first time you ask) and will return it to you again next time

  • Specifically it will create you one instance per configuration (i.e. that Hints object), so if you ask again using the same hints you will get the same instance back

Think of FactoryRegistry keeping instances as singletons for you. In the same manner as it is a Java best practice (when making a singleton) to “partition” by ThreadGroup (so different applets use different singletons). FactoryRegistry does not follow this practice - it uses Hints to “partition” - so two applets that are configured the same will end up using the same FilterFactory.

Application specific Alternatives

Here are a couple of alternatives for stitching together your application.

Container

A container is a great way to take care of a lot of the boiler plate code involved in working with factories. Much of this documentation will use PicoContainer (just because it is small), while many real world applications use the Spring container.

A container is basically a Map where you can look up instances. In common use the instances are factories, and what makes a container valuable is its ability automate the process of “wiring up” the factories together.

Popular techniques:

  • reflection - picocontainer looks the constructors using reflection to see if any of the required parameters are available

  • configuration - Spring uses a big XML file marking how each factory is created

The other nice thing is the container can put off creating the factories until you actually ask for them.:

container.registerImplementationClass( PositionFactory.class, PositionFactoryImpl.class );
container.registerImplementationClass( CoordinateFactory.class, CoordinateFactoryImpl.class );
container.registerImplementationClass( PrimitiveFactory.class, PrimitiveFactoryImpl.class );
container.registerImplementationClass( ComplexFactory.class, ComplexFactoryImpl.class );
container.registerImplementationClass( AggregateFactory.class AggregateFactoryImpl.class );

container.registerInstance( CoordinateReferenceSystem.class, CRS.decode("EPSG:4326") );

WKTParser parser = (WKTParser) container.newInstance( WKTParser.class );

In the above example the WKTParser needs to be constructed with a PositionFactoryCoordinateFactoryPrimitiveFactory and ComplexFactory. Each one of these factories can only be constructed for a specific CoordinateReferenceSystem.

If we were not using a container to manage our factories it would of taken three times the number of lines of code just to set up a WKTParser.

JNDI

If you are writing a Java EE Application there is a big global map in the sky called InitialContext. Literally this is a map you can do look up by name and find Java instances in. It is so global in fact that the instances will be shared between applications.

This idea of a global cross application map is great for configuration and common services. If you are working with a Java EE application you will often find such things as:

  • CRSAuthorityFactory registered for any code wanting to use the referencing module

  • a database listed under the Name “jdbc/EPSG” used to hold the EPSG tables

  • GeometryFactory, or FeatureTypeFactory and so on …

Here is the GeoTools code that looks up a DataSource for an EPSG authority:

Context context = JNDI.getInitialContext(null);
DataSource source = (DataSource) context.lookup("jdbc/EPSG");

The JNDI interfaces are shipped with Java; and two implementations are provided (one to talk to LDAP directories such as organizations deploy for email address information, and another for configuration information stored on the file system with your JRE).

The difference between JNDI and a Container:

  • JNDI is not a container - it is an interface that ships with Java that lets you ask things of a “directory service”.

    A Java EE Application Server runs programs in a “container” and part of the “container configuration” is making sure that JNDI is set up and pointing to the Services (i.e. global variables) that the Application Server makes available to all applications.

    This same directory service can be used by you to share global variables between applications. Some things like the CRSAuthority can be treated as a “utility” and it makes sense to only have one of them for use from several applications at once.

Because making use of an application container is a good idea, and too hard to set up. There are a lot of alternative “light weight” containers available. Examples include picocontainer, JBoss container, Spring container and many many more. These containers focus on the storing of global variables (and making a lot of the difficult configuration automatic - like what factory needs to be created first).

Direct use of Factory

Sometimes you just need to go ahead and code it like you mean it. The GeoTools plugin system does have its place and purpose; but if you know exactly what you are doing; or want to test an exact situation you can dodge the plugin system and do the work by hand.

You can just use a specific factory that is known to you:

DataStoreFactorySpi factory = new ShapefileDataStoreFactory();

File file = new File("example.shp");
Map map = Collections.singletonMap( "url", file.toURL() );

DataStore dataStore = factory.createDataStore( map );

You are depending on a specific class here (so it is not a real plug-in based solution in which GeoTools can find you the best implementation for the job). There is a good chance however that the factory will set you up with a pretty good implementation.

  • Factory classes are Public in Name Only

    Factory classes are only public because we have to (so the factory finders can call them) - some programming environments such as OSGi will take special care to prevent you making direct use of these classes.

    If you are working on the uDig project you may find that class loader settings have prevented you from directly referring to one of these factory classes.

You can provide a “hint” asking the Factory Finder to retrieve you a specific instance:

Hints hints = new Hints( Hints.FILTER_FACTORY, "org.geotools.filter.StrictFactory" );
FilterFactory filterFactory = CommonFactoryFinder.getFilterFactory( hints );

You can skip the whole Factory madness and just do normal Java coding:

File file = new File("example.shp");
URI namespace = new URI("refractions");
ShapefileDataStore shapefile = new ShapefileDataStore( example.toURL());
shapefile.setNamespace(namespace);
shapefile.setMemoryMapped(true);

You are depending on a exact class here, violating the plug-in system and so on. Chances are that GeoTools should not let you do this (by making the constructor package visible and forcing you to use the associated DataStoreFactory instead).

This option is fine for quick hacks, you may find that the ShapefileDataStore has additional methods (to handle such things as forcing the prj file to be rewritten):

shapefile.forceSchemaCRS( CRS.decode( "EPSG:4326" ) );