Subversion Repositories hibernate-spatial

Compare Revisions

Ignore whitespace Rev 1 → Rev 2

/trunk/hibernate-spatial/.classpath
New file
0,0 → 1,18
<?xml version="1.0" encoding="UTF-8"?>
<classpath>
<classpathentry kind="src" path="src/main/java"/>
<classpathentry kind="src" path="src/test/java"/>
<classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER"/>
<classpathentry kind="var" path="M2_REPO/commons-logging/commons-logging/1.0.4/commons-logging-1.0.4.jar" sourcepath="M2_REPO/commons-logging/commons-logging/1.0.4/commons-logging-1.0.4-sources.jar"/>
<classpathentry kind="var" path="M2_REPO/ehcache/ehcache/1.1/ehcache-1.1.jar" sourcepath="M2_REPO/ehcache/ehcache/1.1/ehcache-1.1-sources.jar"/>
<classpathentry kind="var" path="M2_REPO/asm/asm/1.5.3/asm-1.5.3.jar"/>
<classpathentry kind="var" path="M2_REPO/dom4j/dom4j/1.6.1/dom4j-1.6.1.jar" sourcepath="M2_REPO/dom4j/dom4j/1.6.1/dom4j-1.6.1-sources.jar"/>
<classpathentry kind="var" path="M2_REPO/org/hibernate/hibernate/3.1rc2/hibernate-3.1rc2.jar" sourcepath="/OSS_SRC/hibernate-3.2/src"/>
<classpathentry kind="var" path="M2_REPO/javax/transaction/jta/1.0.1B/jta-1.0.1B.jar"/>
<classpathentry kind="var" path="M2_REPO/org/hibernate/antlr/2.7.5H3/antlr-2.7.5H3.jar"/>
<classpathentry kind="var" path="M2_REPO/cglib/cglib/2.1_2/cglib-2.1_2.jar" sourcepath="M2_REPO/cglib/cglib/2.1_2/cglib-2.1_2-sources.jar"/>
<classpathentry kind="var" path="M2_REPO/junit/junit/4.1/junit-4.1.jar"/>
<classpathentry kind="var" path="M2_REPO/com/vividsolutions/jts/1.7.1/jts-1.7.1.jar"/>
<classpathentry kind="var" path="M2_REPO/commons-collections/commons-collections/2.1.1/commons-collections-2.1.1.jar" sourcepath="M2_REPO/commons-collections/commons-collections/2.1.1/commons-collections-2.1.1-sources.jar"/>
<classpathentry kind="output" path="target/classes"/>
</classpath>
/trunk/hibernate-spatial/.project
New file
0,0 → 1,13
<projectDescription>
<name>spatial</name>
<comment>Majas hibernate spatial</comment>
<projects/>
<buildSpec>
<buildCommand>
<name>org.eclipse.jdt.core.javabuilder</name>
</buildCommand>
</buildSpec>
<natures>
<nature>org.eclipse.jdt.core.javanature</nature>
</natures>
</projectDescription>
/trunk/hibernate-spatial/src/test/java/com/cadrie/hibernate/spatial/test/model/LineStringEntity.hbm.xml
New file
0,0 → 1,18
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<!-- Generated Aug 9, 2006 9:35:48 PM by Hibernate Tools 3.2.0.beta6a -->
<hibernate-mapping>
<class name="com.cadrie.hibernate.spatial.test.model.LineStringEntity" table="linestringtest">
<id name="id" type="long">
<column name="id" precision="65535" scale="65531" />
<generator class="increment"/>
</id>
<property name="name" type="string">
<column name="name" length="50"/>
</property>
<property name="geometry" type="com.cadrie.hibernate.spatial.GeometryUserType">
<column name="geom"/>
</property>
</class>
</hibernate-mapping>
Property changes:
Added: svn:executable
+
/trunk/hibernate-spatial/src/test/java/com/cadrie/hibernate/spatial/test/model/MultiPolygonEntity.java
New file
0,0 → 1,65
package com.cadrie.hibernate.spatial.test.model;
 
import com.vividsolutions.jts.geom.Geometry;
import com.vividsolutions.jts.geom.MultiPolygon;
 
/**
* Test class for testing Points
*/
public class MultiPolygonEntity {
 
// Fields
private static final long serialVersionUID = 1L;
 
private long id;
 
private String name;
 
private MultiPolygon geometry;
 
// Constructors
 
/** default constructor */
public MultiPolygonEntity() {
}
 
/** minimal constructor */
public MultiPolygonEntity(long id) {
this.id = id;
}
 
/** full constructor */
public MultiPolygonEntity(long id, String name, Geometry geom) {
this.id = id;
this.name = name;
this.geometry = (MultiPolygon) geom;
}
 
// Property accessors
public long getId() {
return this.id;
}
 
public void setId(long id) {
this.id = id;
}
 
public String getName() {
return this.name;
}
 
public void setName(String name) {
this.name = name;
}
 
public Geometry getGeometry() {
return this.geometry;
}
 
public void setGeometry(Geometry geom) {
this.geometry = (MultiPolygon) geom;
}
 
 
 
}
/trunk/hibernate-spatial/src/test/java/com/cadrie/hibernate/spatial/test/model/DataGenerator.java
New file
0,0 → 1,183
package com.cadrie.hibernate.spatial.test.model;
 
import java.lang.reflect.Constructor;
 
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.hibernate.cfg.Settings;
 
import com.vividsolutions.jts.geom.Coordinate;
import com.vividsolutions.jts.geom.Geometry;
import com.vividsolutions.jts.geom.GeometryFactory;
import com.vividsolutions.jts.geom.LineString;
import com.vividsolutions.jts.geom.LinearRing;
import com.vividsolutions.jts.geom.MultiLineString;
import com.vividsolutions.jts.geom.Polygon;
import com.vividsolutions.jts.geom.PrecisionModel;
 
/**
* Generates test data for the unit tests
*
* TODO : - generate polygons with holes.
* TODO : - add points, multipoints, multipolygons
*
*/
public class DataGenerator {
 
static final private int SIZE = 1000;
 
static final private double minCoordValue = 0.0d;
 
static final private double maxCoordValue = 100000.0d;
 
static final private int maxNumGeom = 10;
 
static final private int maxNumCoords = 20;
 
// create the geometryfactory, with floating-point precision model, and
// Belgian lambert
static final private GeometryFactory geomFactory = new GeometryFactory(
new PrecisionModel(), 31370);
 
public void generate() {
// set up hibernate and register Spatialtest as a persistent entity
Configuration config = new Configuration();
config.configure();
config.addClass(LineStringEntity.class);
config.addClass(MultiLineStringEntity.class);
config.addClass(PolygonEntity.class);
config.addClass(PointEntity.class);
config.addClass(MultiPointEntity.class);
config.addClass(MultiPolygonEntity.class);
 
Settings settings = config.buildSettings();
System.out.println("Generating Data for Dialect: "
+ settings.getDialect().getClass().getName());
// HBSpatialExtension.setDefaultSpatialDialect((SpatialDialect) settings
// .getDialect());
 
// build the session factory
SessionFactory factory = config.buildSessionFactory();
 
//generate the data
generateData(LineStringEntity.class, factory,new LineStringCreator());
generateData(MultiLineStringEntity.class, factory, new MultiLineStringCreator());
generateData(PolygonEntity.class, factory, new PolygonCreator());
factory.close();
 
}
 
private static void generateData(Class entityClass, SessionFactory factory, GeomCreator creator) {
Session session = factory.openSession();
 
Transaction tx = null;
try {
System.out.println("Writing " + entityClass.getSimpleName());
for (int i = 0; i < SIZE; i++) {
tx = session.beginTransaction();
Geometry geom = creator.create();
 
Constructor constructor = entityClass.getConstructor(new Class[]{ java.lang.Long.TYPE, String.class, Geometry.class});
Object entity = constructor.newInstance(new Object[]{i, "feature " + i, geom});
 
session.save(entity);
tx.commit();
}
} catch (Exception e) {
if (tx != null)
tx.rollback();
throw new RuntimeException("Failed loading data of type " + entityClass.getSimpleName(),e);
} finally {
session.close();
session = null;
}
}
 
private static double getRandomCoordinateValue() {
return (maxCoordValue - minCoordValue) * Math.random();
}
 
private static int getRandomNumGeoms() {
double dn = 1 + (maxNumGeom - 1) * Math.random();
int num = Math.round((float) dn);
return num;
}
 
private static int getRandomNumCoords(int minValue) {
double dn = minValue + (maxNumCoords - minValue) * Math.random();
int num = Math.round((float) dn);
return num;
}
 
private static Coordinate getRandomCoordinate() {
double x = getRandomCoordinateValue();
double y = getRandomCoordinateValue();
return new Coordinate(x, y);
}
 
interface GeomCreator<T extends Geometry>{
public T create();
}
 
private class LineStringCreator implements GeomCreator<LineString>{
public LineString create() {
 
int numCoords = getRandomNumCoords(2);
Coordinate[] coordinates = new Coordinate[numCoords];
for (int i = 0; i < numCoords; i++) {
coordinates[i] = getRandomCoordinate();
}
return geomFactory.createLineString(coordinates);
}
}
 
private class MultiLineStringCreator implements GeomCreator<MultiLineString>{
public MultiLineString create() {
//at least two linestrings, otherwise some databases like Oracle will
// store multilinestring as linestring in stead.
int numGeoms = 1 + getRandomNumGeoms();
LineStringCreator lsc = new LineStringCreator();
LineString[] lines = new LineString[numGeoms];
for (int i = 0; i < numGeoms; i++) {
lines[i] = lsc.create();
}
return geomFactory.createMultiLineString(lines);
}
}
// This create small boxes
// TODO -- find a better way to generate random linear rings
private class LinearRingCreator implements GeomCreator<LinearRing>{
public LinearRing create() {
 
int numCoords = 4;
Coordinate[] coordinates = new Coordinate[numCoords + 1];
 
coordinates[0] = getRandomCoordinate();
coordinates[1] = new Coordinate(coordinates[0].x,
coordinates[0].y + 10.0d);
coordinates[2] = new Coordinate(coordinates[0].x + 10.0d,
coordinates[0].y + 10.0d);
coordinates[3] = new Coordinate(coordinates[0].x + 10.0d,
coordinates[0].y);
coordinates[numCoords] = coordinates[0];
LinearRing lr = geomFactory.createLinearRing(coordinates);
return lr;
}
}
private class PolygonCreator implements GeomCreator<Polygon>{
public Polygon create() {
LinearRing lr = (new LinearRingCreator()).create();
Polygon pg = geomFactory.createPolygon(lr, null);
return pg;
}
}
 
// TO DO -- add polygons with holes!!
 
}
Property changes:
Added: svn:executable
+
/trunk/hibernate-spatial/src/test/java/com/cadrie/hibernate/spatial/test/model/MultiPointEntity.java
New file
0,0 → 1,65
package com.cadrie.hibernate.spatial.test.model;
 
import com.vividsolutions.jts.geom.Geometry;
import com.vividsolutions.jts.geom.MultiPoint;
 
/**
* Test class for testing Points
*/
public class MultiPointEntity {
 
// Fields
private static final long serialVersionUID = 1L;
 
private long id;
 
private String name;
 
private MultiPoint geometry;
 
// Constructors
 
/** default constructor */
public MultiPointEntity() {
}
 
/** minimal constructor */
public MultiPointEntity(long id) {
this.id = id;
}
 
/** full constructor */
public MultiPointEntity(long id, String name, Geometry geom) {
this.id = id;
this.name = name;
this.geometry = (MultiPoint) geom;
}
 
// Property accessors
public long getId() {
return this.id;
}
 
public void setId(long id) {
this.id = id;
}
 
public String getName() {
return this.name;
}
 
public void setName(String name) {
this.name = name;
}
 
public Geometry getGeometry() {
return this.geometry;
}
 
public void setGeometry(Geometry geom) {
this.geometry = (MultiPoint) geom;
}
 
 
 
}
/trunk/hibernate-spatial/src/test/java/com/cadrie/hibernate/spatial/test/model/MultiPolygonEntity.hbm.xml
New file
0,0 → 1,18
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<!-- Generated Aug 9, 2006 9:35:48 PM by Hibernate Tools 3.2.0.beta6a -->
<hibernate-mapping>
<class name="com.cadrie.hibernate.spatial.test.model.MultiPolygonEntity" table="multipolygontest">
<id name="id" type="long">
<column name="id" precision="65535" scale="65531" />
<generator class="increment" />
</id>
<property name="name" type="string">
<column name="name" length="50" />
</property>
<property name="geometry" type="com.cadrie.hibernate.spatial.GeometryUserType">
<column name="geom" />
</property>
</class>
</hibernate-mapping>
Property changes:
Added: svn:executable
+
/trunk/hibernate-spatial/src/test/java/com/cadrie/hibernate/spatial/test/model/PolygonEntity.java
New file
0,0 → 1,66
package com.cadrie.hibernate.spatial.test.model;
 
// Generated Aug 9, 2006 9:35:48 PM by Hibernate Tools 3.2.0.beta6a
 
import com.vividsolutions.jts.geom.Geometry;
import com.vividsolutions.jts.geom.Polygon;
 
/**
* Spatialtest generated by hbm2java
*/
public class PolygonEntity implements java.io.Serializable {
 
// Fields
 
private static final long serialVersionUID = 1L;
 
private long id;
 
private String name;
 
private Polygon geometry;
 
// Constructors
 
/** default constructor */
public PolygonEntity() {
}
 
/** minimal constructor */
public PolygonEntity(long id) {
this.id = id;
}
 
/** full constructor */
public PolygonEntity(long id, String name, Geometry geom) {
this.id = id;
this.name = name;
this.geometry = (Polygon)geom;
}
 
// Property accessors
public long getId() {
return this.id;
}
 
public void setId(long id) {
this.id = id;
}
 
public String getName() {
return this.name;
}
 
public void setName(String name) {
this.name = name;
}
 
public Geometry getGeometry() {
return this.geometry;
}
 
public void setGeometry(Geometry geom) {
this.geometry = (Polygon)geom;
}
 
}
/trunk/hibernate-spatial/src/test/java/com/cadrie/hibernate/spatial/test/model/MultiPointEntity.hbm.xml
New file
0,0 → 1,18
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<!-- Generated Aug 9, 2006 9:35:48 PM by Hibernate Tools 3.2.0.beta6a -->
<hibernate-mapping>
<class name="com.cadrie.hibernate.spatial.test.model.MultiPointEntity" table="multipointtest" >
<id name="id" type="long">
<column name="id" precision="65535" scale="65531" />
<generator class="increment"/>
</id>
<property name="name" type="string">
<column name="name" length="50"/>
</property>
<property name="geometry" type="com.cadrie.hibernate.spatial.GeometryUserType">
<column name="geom"/>
</property>
</class>
</hibernate-mapping>
Property changes:
Added: svn:executable
+
/trunk/hibernate-spatial/src/test/java/com/cadrie/hibernate/spatial/test/model/MultiLineStringEntity.java
New file
0,0 → 1,67
package com.cadrie.hibernate.spatial.test.model;
 
// Generated Aug 9, 2006 9:35:48 PM by Hibernate Tools 3.2.0.beta6a
 
import com.vividsolutions.jts.geom.Geometry;
import com.vividsolutions.jts.geom.MultiLineString;
 
/**
* Spatialtest generated by hbm2java
*/
public class MultiLineStringEntity implements java.io.Serializable {
 
// Fields
 
private static final long serialVersionUID = 1L;
 
private long id;
 
private String name;
 
private MultiLineString geometry;
 
// Constructors
 
/** default constructor */
public MultiLineStringEntity() {
}
 
/** minimal constructor */
public MultiLineStringEntity(long id) {
this.id = id;
}
 
/** full constructor */
public MultiLineStringEntity(long id, String name,
Geometry geom) {
this.id = id;
this.name = name;
this.geometry = (MultiLineString)geom;
}
 
// Property accessors
public long getId() {
return this.id;
}
 
public void setId(long id) {
this.id = id;
}
 
public String getName() {
return this.name;
}
 
public void setName(String name) {
this.name = name;
}
 
public Geometry getGeometry() {
return this.geometry;
}
 
public void setGeometry(MultiLineString geom) {
this.geometry = geom;
}
 
}
/trunk/hibernate-spatial/src/test/java/com/cadrie/hibernate/spatial/test/model/PointEntity.java
New file
0,0 → 1,65
package com.cadrie.hibernate.spatial.test.model;
 
import com.vividsolutions.jts.geom.Geometry;
import com.vividsolutions.jts.geom.Point;
 
/**
* Test class for testing Points
*/
public class PointEntity {
 
// Fields
private static final long serialVersionUID = 1L;
 
private long id;
 
private String name;
 
private Point geometry;
 
// Constructors
 
/** default constructor */
public PointEntity() {
}
 
/** minimal constructor */
public PointEntity(long id) {
this.id = id;
}
 
/** full constructor */
public PointEntity(long id, String name, Geometry geom) {
this.id = id;
this.name = name;
this.geometry = (Point) geom;
}
 
// Property accessors
public long getId() {
return this.id;
}
 
public void setId(long id) {
this.id = id;
}
 
public String getName() {
return this.name;
}
 
public void setName(String name) {
this.name = name;
}
 
public Geometry getGeometry() {
return this.geometry;
}
 
public void setGeometry(Geometry geom) {
this.geometry = (Point) geom;
}
 
 
 
}
/trunk/hibernate-spatial/src/test/java/com/cadrie/hibernate/spatial/test/model/PolygonEntity.hbm.xml
New file
0,0 → 1,18
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<!-- Generated Aug 9, 2006 9:35:48 PM by Hibernate Tools 3.2.0.beta6a -->
<hibernate-mapping>
<class name="com.cadrie.hibernate.spatial.test.model.PolygonEntity" table="polygontest">
<id name="id" type="long">
<column name="id" precision="65535" scale="65531" />
<generator class="increment" />
</id>
<property name="name" type="string">
<column name="name" length="50" />
</property>
<property name="geometry" type="com.cadrie.hibernate.spatial.GeometryUserType">
<column name="geom" />
</property>
</class>
</hibernate-mapping>
Property changes:
Added: svn:executable
+
/trunk/hibernate-spatial/src/test/java/com/cadrie/hibernate/spatial/test/model/MultiLineStringEntity.hbm.xml
New file
0,0 → 1,18
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<!-- Generated Aug 9, 2006 9:35:48 PM by Hibernate Tools 3.2.0.beta6a -->
<hibernate-mapping>
<class name="com.cadrie.hibernate.spatial.test.model.MultiLineStringEntity" table="multilinestringtest">
<id name="id" type="long">
<column name="id" precision="65535" scale="65531" />
<generator class="increment" />
</id>
<property name="name" type="string">
<column name="name" length="50" />
</property>
<property name="geometry" type="com.cadrie.hibernate.spatial.GeometryUserType">
<column name="geom" />
</property>
</class>
</hibernate-mapping>
Property changes:
Added: svn:executable
+
/trunk/hibernate-spatial/src/test/java/com/cadrie/hibernate/spatial/test/model/PointEntity.hbm.xml
New file
0,0 → 1,18
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<!-- Generated Aug 9, 2006 9:35:48 PM by Hibernate Tools 3.2.0.beta6a -->
<hibernate-mapping>
<class name="com.cadrie.hibernate.spatial.test.model.PointEntity" table="pointtest">
<id name="id" type="long">
<column name="id" precision="65535" scale="65531" />
<generator class="increment"/>
</id>
<property name="name" type="string">
<column name="name" length="50"/>
</property>
<property name="geometry" type="com.cadrie.hibernate.spatial.GeometryUserType">
<column name="geom"/>
</property>
</class>
</hibernate-mapping>
Property changes:
Added: svn:executable
+
/trunk/hibernate-spatial/src/test/java/com/cadrie/hibernate/spatial/test/model/LineStringEntity.java
New file
0,0 → 1,64
package com.cadrie.hibernate.spatial.test.model;
 
import com.vividsolutions.jts.geom.Geometry;
import com.vividsolutions.jts.geom.LineString;
 
/**
* Test class for testing LineStrings
*/
public class LineStringEntity implements java.io.Serializable {
 
// Fields
 
private static final long serialVersionUID = 1L;
 
private long id;
 
private String name;
 
private LineString geometry;
 
// Constructors
 
/** default constructor */
public LineStringEntity() {
}
 
/** minimal constructor */
public LineStringEntity(long id) {
this.id = id;
}
 
/** full constructor */
public LineStringEntity(long id, String name, Geometry geom) {
this.id = id;
this.name = name;
this.geometry = (LineString) geom;
}
 
// Property accessors
public long getId() {
return this.id;
}
 
public void setId(long id) {
this.id = id;
}
 
public String getName() {
return this.name;
}
 
public void setName(String name) {
this.name = name;
}
 
public Geometry getGeometry() {
return this.geometry;
}
 
public void setGeometry(Geometry geom) {
this.geometry = (LineString) geom;
}
 
}
Property changes:
Added: svn:executable
+
/trunk/hibernate-spatial/src/test/java/com/cadrie/hibernate/spatial/test/TestSpatialQueries.java
New file
0,0 → 1,693
package com.cadrie.hibernate.spatial.test;
 
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Iterator;
import java.util.List;
 
import org.hibernate.Criteria;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.type.CustomType;
import org.hibernate.type.Type;
 
import com.cadrie.hibernate.spatial.GeometryUserType;
import com.cadrie.hibernate.spatial.criterion.SpatialRestrictions;
import com.cadrie.hibernate.spatial.test.model.LineStringEntity;
import com.cadrie.hibernate.spatial.test.model.MultiLineStringEntity;
import com.cadrie.hibernate.spatial.test.model.PolygonEntity;
import com.vividsolutions.jts.geom.Geometry;
import com.vividsolutions.jts.io.ParseException;
import com.vividsolutions.jts.io.WKTReader;
import static org.junit.Assert.*;
 
public class TestSpatialQueries {
 
private SessionFactory factory;
 
private Connection conn;
 
private Geometry jtsFilter = null;
 
private String filterPolygonString = "POLYGON((0.0 0.0, 25000.0 0.0, 25000.0 25000.0, 0.0 25000.0, 0.0 0.0))";
 
/**
* Allow users access to the SessionFactory
*
* @return the sessionfactory
*/
public SessionFactory getSessionFactory() {
return this.factory;
}
 
public void setUpBeforeClass(Connection conn) throws SQLException,
ClassNotFoundException, ParseException {
 
if (conn == null)
throw new RuntimeException("Empty connection passed.");
 
this.conn = conn;
 
// set up hibernate and register persistent entities
Configuration config = new Configuration();
config.configure();
config.addClass(LineStringEntity.class);
config.addClass(PolygonEntity.class);
config.addClass(MultiLineStringEntity.class);
 
// build the session factory
factory = config.buildSessionFactory();
 
// convert WKT string for filter to proper Geometry
WKTReader reader = new WKTReader();
jtsFilter = reader.read(filterPolygonString);
jtsFilter.setSRID(31370);
}
 
public void tearDownAfterClass() {
this.factory.close();
try {
this.conn.close();
} catch (SQLException e) {
throw new RuntimeException(e);
}
 
}
 
public void testLineStringFiltering(String sql) throws Exception {
 
Session session = null;
try {
// apply the filter using Hibernate
session = factory.openSession();
 
Criteria testCriteria = session
.createCriteria(LineStringEntity.class);
 
testCriteria.add(SpatialRestrictions.filter("geometry", jtsFilter));
 
List results = testCriteria.list();
 
// get the same results using JDBC - SQL directly;
 
PreparedStatement stmt = conn.prepareStatement(sql);
stmt.setString(1, this.filterPolygonString);
ResultSet rs = stmt.executeQuery();
rs.next();
int expected = rs.getInt(1);
System.out.println("overlap geometries = " + results.size());
// test whether they give the same results
assertEquals(expected, results.size());
} finally {
if (session != null) session.close();
}
 
}
 
public void testPolygonFiltering(String sql) throws Exception {
// apply the filter using Hibernate
Session session = null;
try{
session= factory.openSession();
 
Criteria testCriteria = session.createCriteria(PolygonEntity.class);
 
testCriteria.add(SpatialRestrictions.filter("geometry", jtsFilter));
 
List results = testCriteria.list();
 
// get the same results using JDBC - SQL directly;
PreparedStatement stmt = conn.prepareStatement(sql);
stmt.setString(1, this.filterPolygonString);
ResultSet rs = stmt.executeQuery();
rs.next();
int expected = rs.getInt(1);
 
// test whether they give the same results
assertEquals(expected, results.size());
} finally{
if (session != null)
session.close();
}
 
}
 
public void testMultiLineStringFiltering(String sql) throws Exception {
// apply the filter using Hibernate
Session session = null;
try{
session = factory.openSession();
 
Criteria testCriteria = session
.createCriteria(MultiLineStringEntity.class);
 
testCriteria.add(SpatialRestrictions.filter("geometry", jtsFilter));
 
List results = testCriteria.list();
 
// get the same results using JDBC - SQL directly;
PreparedStatement stmt = conn.prepareStatement(sql);
stmt.setString(1, this.filterPolygonString);
ResultSet rs = stmt.executeQuery();
rs.next();
int expected = rs.getInt(1);
 
// test whether they give the same results
assertEquals(expected, results.size());
} finally {
if (session != null)
session.close();
}
}
 
public void testHQLAsTextLineString() throws Exception {
Session session = null;
try{
session = factory.openSession();
 
Query q = session
.createQuery("select astext(l.geometry) from LineStringEntity as l");
int i = 0;
for (Iterator it = q.list().iterator(); it.hasNext() && i < 10; i++) {
String s = (String) it.next();
System.out.println(s);
}
} finally {
if (session != null) session.close();
}
}
 
public void testHQLDimensionLineString() throws Exception {
Session session = factory.openSession();
Query q = session
.createQuery("select dimension(l.geometry) from LineStringEntity as l where l.geometry is not null");
int i = 0;
for (Iterator it = q.list().iterator(); it.hasNext() && i < 10; i++) {
Integer dim = (Integer) it.next();
assertEquals(new Integer(1), dim);
}
 
q = session
.createQuery("select dimension(p.geometry) from PolygonEntity as p where p.geometry is not null");
i = 0;
for (Iterator it = q.list().iterator(); it.hasNext() && i < 10; i++) {
Integer dim = (Integer) it.next();
assertEquals(new Integer(2), dim);
}
 
session.close();
 
}
 
public void testHQLOverlapsLineString(String sql) throws Exception {
Session session = factory.openSession();
Query q = session
.createQuery("select overlaps(?,l.geometry) from LineStringEntity as l where l.geometry is not null");
Type GeometryType = new CustomType(GeometryUserType.class, null);
q.setParameter(0, jtsFilter, GeometryType);
int numOverlapping = 0;
for (Iterator it = q.list().iterator(); it.hasNext();) {
Boolean b = (Boolean) it.next();
if (b)
numOverlapping++;
}
 
PreparedStatement stmt = conn.prepareStatement(sql);
stmt.setString(1, this.filterPolygonString);
ResultSet rs = stmt.executeQuery();
rs.next();
int expected = rs.getInt(1);
assertEquals(expected, numOverlapping);
System.out.println("num. overlapping = " + numOverlapping);
session.close();
 
}
 
public void testHQLRelateLineString() throws Exception {
Session session = factory.openSession();
 
Query q = session
.createQuery("select count(*) from LineStringEntity l where relate(l.geometry, ?, 'TT*******') = true and l.geometry is not null");
Type geometryType = new CustomType(GeometryUserType.class, null);
q.setParameter(0, jtsFilter, geometryType);
Long cnt = (Long) q.list().get(0);
System.out.println("Related by 'TT*******' pattern = " + cnt);
}
 
public void testHQLIntersectsLineString(String sqlString) throws Exception {
Session session = factory.openSession();
Query q = session
.createQuery("select intersects(?,l.geometry) from LineStringEntity as l where l.geometry is not null");
Type geometryType = new CustomType(GeometryUserType.class, null);
q.setParameter(0, jtsFilter, geometryType);
long intersects = 0;
for (Iterator it = q.list().iterator(); it.hasNext();) {
Boolean b = (Boolean) it.next();
if (b)
intersects++;
}
 
q = session
.createQuery("select count(*) from LineStringEntity as l where intersects(l.geometry, ?) = true");
q.setParameter(0, jtsFilter, geometryType);
long altIntersects = (Long) q.list().get(0);
assertEquals(intersects, altIntersects);
 
PreparedStatement stmt = conn.prepareStatement(sqlString);
stmt.setString(1, this.filterPolygonString);
ResultSet rs = stmt.executeQuery();
rs.next();
int expected = rs.getInt(1);
assertEquals(expected, intersects);
System.out.println("num. intersects = " + intersects);
 
Query q2 = session
.createQuery("from LineStringEntity as l where intersects(?,l.geometry) = True");
q2.setParameter(0, jtsFilter, geometryType);
List l = q2.list();
assertEquals(expected, l.size());
 
session.close();
 
}
 
public void testHQLSRID() throws Exception {
Session session = factory.openSession();
Query q = session
.createQuery("select srid(l.geometry) from LineStringEntity as l where l.geometry is not null");
int i = 0;
for (Iterator it = q.list().iterator(); it.hasNext(); i++) {
Integer srid = (Integer) it.next();
assertEquals(31370, srid.intValue());
if (i == 0)
System.out.println("srid: " + srid);
}
session.close();
}
 
public void testHGLGeometryType() throws Exception {
System.out.println("Testing GeometryType");
Session session = factory.openSession();
Query q = session
.createQuery("select geometrytype(l.geometry) from LineStringEntity as l where l.geometry is not null");
int i = 0;
for (Iterator it = q.list().iterator(); it.hasNext(); i++) {
String gt = (String) it.next();
// if (i < 10)
// System.out.println(gt);
assertEquals("LINESTRING", gt);
}
q = session
.createQuery("select geometrytype(p.geometry) from PolygonEntity as p where p is not null");
i = 0;
for (Iterator it = q.list().iterator(); it.hasNext(); i++) {
String gt = (String) it.next();
if (i < 10)
System.out.println(gt);
assertEquals("POLYGON", gt);
}
session.close();
 
}
 
// TODO - test with database connection, because the getEnvelope()
// result differs from
// database envelope or MBR functions.
public void testHQLEnvelope() throws Exception {
Session session = factory.openSession();
testHQLEnvelope("LineStringEntity", session);
testHQLEnvelope("PolygonEntity", session);
session.close();
}
 
private void testHQLEnvelope(String entityName, Session session) {
Query q = session
.createQuery("select envelope(e.geometry), e.geometry from "
+ entityName + " as e where e.geometry is not null");
System.out.println("Envelope test for " + entityName);
System.out.println("------------------------------------");
int i = 0;
for (Iterator it = q.list().iterator(); it.hasNext() && i < 10; i++) {
Object[] geoms = (Object[]) it.next();
Geometry env = (Geometry) geoms[0];
Geometry g = (Geometry) geoms[1];
System.out.println("Env. = " + env.toText());
System.out.println(" PEnv = " + g.getEnvelope().toText());
 
assertTrue(g.getEnvelope().equalsExact(env));
}
}
 
public void testHQLIsEmpty(String sql) throws Exception {
Session session = factory.openSession();
Query q = session
.createQuery("select l.id, isempty(l.geometry) from LineStringEntity as l where l.geometry is not null");
PreparedStatement pstmt = conn.prepareStatement(sql);
 
for (Iterator it = q.list().iterator(); it.hasNext();) {
Object[] objs = (Object[]) it.next();
long id = (Long) objs[0];
Boolean isEmpty = (Boolean) objs[1];
pstmt.setLong(1, id);
ResultSet rs = pstmt.executeQuery();
rs.next();
Boolean expected = rs.getBoolean(1);
rs.close();
assertEquals(expected, isEmpty);
}
pstmt.close();
session.close();
}
 
public void testHQLIsSimple(String sql) throws Exception {
Session session = factory.openSession();
Query q = session
.createQuery("select l.id, issimple(l.geometry) from LineStringEntity as l where l.geometry is not null");
PreparedStatement pstmt = conn.prepareStatement(sql);
 
for (Iterator it = q.list().iterator(); it.hasNext();) {
Object[] objs = (Object[]) it.next();
long id = (Long) objs[0];
Boolean isSimple = (Boolean) objs[1];
pstmt.setLong(1, id);
ResultSet rs = pstmt.executeQuery();
rs.next();
Boolean expected = rs.getBoolean(1);
rs.close();
assertEquals(expected, isSimple);
}
pstmt.close();
session.close();
}
 
public void testHQLBoundary() throws Exception {
Session session = factory.openSession();
Query q = session
.createQuery("select p.geometry, boundary(p.geometry) from PolygonEntity as p where p.geometry is not null");
 
for (Iterator it = q.list().iterator(); it.hasNext();) {
Object[] objs = (Object[]) it.next();
Geometry geom = (Geometry) objs[0];
Geometry bound = (Geometry) objs[1];
assertTrue(geom.getBoundary().equals(bound));
}
session.close();
}
 
public void testHQLAsBinary(String sql) throws Exception {
Session session = factory.openSession();
Query q = session
.createQuery("select id, l.geometry, asbinary(l.geometry) from LineStringEntity as l where l.geometry is not null");
PreparedStatement pstmt = conn.prepareStatement(sql);
 
for (Iterator it = q.list().iterator(); it.hasNext();) {
Object[] objs = (Object[]) it.next();
long id = (Long) objs[0];
byte[] wkb = (byte[]) objs[2];
pstmt.setLong(1, id);
ResultSet rs = pstmt.executeQuery();
rs.next();
Object obj = rs.getBytes(1);
 
byte[] expected = (byte[]) obj;
rs.close();
for (int i = 0; i < expected.length; i++) {
assertEquals(expected[i], wkb[i]);
}
}
pstmt.close();
session.close();
}
 
public void testHQLDistance() throws Exception {
Session session = factory.openSession();
 
Query q = session
.createQuery("select distance(l.geometry, ?), l.geometry from LineStringEntity as l where l.geometry is not null");
Type geometryType = new CustomType(GeometryUserType.class, null);
q.setParameter(0, jtsFilter, geometryType);
int i = 0;
for (Iterator it = q.list().iterator(); it.hasNext() && i++ < 100;) {
Object[] objs = (Object[]) it.next();
Double distance = (Double) objs[0];
Geometry geom = (Geometry) objs[1];
System.out.println("Distance= " + distance);
assertEquals(geom.distance(jtsFilter), distance, 0.003);
}
 
session.close();
}
 
public void testHQLBuffer() throws Exception {
Session session = factory.openSession();
 
Query q = session
.createQuery("select p.geometry, buffer(p.geometry, 10.0) from PolygonEntity as p where p.geometry is not null");
int i = 0;
int cnt = 0;
for (Iterator it = q.list().iterator(); it.hasNext() && i++ < 100;) {
Object[] objs = (Object[]) it.next();
Geometry geom = (Geometry) objs[0];
Geometry buffer = (Geometry) objs[1];
 
Geometry jtsBuffer = geom.buffer(10.0);
 
buffer.normalize();
jtsBuffer.normalize();
if (approximateCoincident(jtsBuffer, buffer, 0.05))
cnt++;
else
System.out.println("Unequal buffer for geom: " + geom
+ "\n\t dbbuffer = " + buffer + "\n\t jtsbuffer = "
+ jtsBuffer);
}
assertTrue(cnt > 0);
System.out.println("Number of equal buffers= " + cnt);
session.close();
 
}
 
public void testHQLConvexHull() throws Exception {
Session session = factory.openSession();
 
Query q = session
.createQuery("select m.geometry, convexhull(m.geometry) from MultiLineStringEntity as m where m.geometry is not null");
int i = 0;
int cnt = 0;
for (Iterator it = q.list().iterator(); it.hasNext() && i++ < 100;) {
Object[] objs = (Object[]) it.next();
Geometry geom = (Geometry) objs[0];
Geometry cvh = (Geometry) objs[1];
 
// constraint on convexity
assertTrue("geometry not in its convex hull", cvh.contains(geom));
cvh.normalize();
 
Geometry jtsConvexHull = geom.convexHull();
jtsConvexHull.normalize();
if (jtsConvexHull.equalsExact(cvh, 0.5))
cnt++;
else
System.out.println("Unequal convex hull for geom: " + geom
+ "\n\t db conv. hull = " + cvh
+ "\n\t jts conv. hull = " + jtsConvexHull);
}
assertTrue(cnt > 0);
System.out.println("Number of equal convex hulls = " + cnt);
session.close();
 
}
 
public void testHQLDifference() throws Exception {
Session session = factory.openSession();
 
Query q = session
.createQuery("select e.id, e.geometry, difference(e.geometry, ?) from PolygonEntity as e where e.geometry is not null");
Type geometryType = new CustomType(GeometryUserType.class, null);
q.setParameter(0, jtsFilter, geometryType);
int i = 0;
int cnt = 0;
int cntEmpty = 0;
for (Iterator it = q.list().iterator(); it.hasNext() && i++ < 100;) {
Object[] objs = (Object[]) it.next();
Long id = (Long) objs[0];
Geometry geom = (Geometry) objs[1];
Geometry diff = (Geometry) objs[2];
// some databases give a null object if the difference is the
// null-set
if (diff == null || diff.isEmpty()) {
cntEmpty++;
continue;
}
diff.normalize();
 
Geometry jtsDiff = geom.difference(jtsFilter);
jtsDiff.normalize();
if (jtsDiff.equalsExact(diff, 0.5))
cnt++;
else
System.out.println("Unequal difference for geom: " + geom
+ "\n\t db difference = " + diff
+ "\n\t jts difference = " + jtsDiff);
}
assertTrue(cnt > 0);
System.out.println("Number of equal differences = " + cnt);
System.out.println("Number of empty or null difference results = "
+ cntEmpty);
session.close();
 
}
 
public void testHQLIntersection() throws Exception {
Session session = factory.openSession();
 
Query q = session
.createQuery("select e.id, e.geometry, intersection(e.geometry, ?) from PolygonEntity as e where e.geometry is not null");
Type geometryType = new CustomType(GeometryUserType.class, null);
q.setParameter(0, jtsFilter, geometryType);
int i = 0;
int cnt = 0;
int cntEmpty = 0;
for (Iterator it = q.list().iterator(); it.hasNext() && i++ < 100;) {
Object[] objs = (Object[]) it.next();
Long id = (Long) objs[0];
Geometry geom = (Geometry) objs[1];
Geometry intersect = (Geometry) objs[2];
// some databases give a null object if the difference is the
// null-set
if (intersect == null || intersect.isEmpty()) {
cntEmpty++;
continue;
}
intersect.normalize();
 
Geometry jtsIntersect = geom.intersection(jtsFilter);
jtsIntersect.normalize();
if (jtsIntersect.equalsExact(intersect, 0.5))
cnt++;
else
System.out.println("Unequal intersection for geom: " + geom
+ "\n\t db intersect = " + intersect
+ "\n\t jts intersect = " + jtsIntersect);
}
assertTrue(cnt > 0);
System.out.println("Number of equal intersects = " + cnt);
System.out.println("Number of empty or null intersect results = "
+ cntEmpty);
session.close();
 
}
 
public void testHQLSymDifference() throws Exception {
Session session = factory.openSession();
 
Query q = session
.createQuery("select e.id, e.geometry, symdifference(e.geometry, ?) from PolygonEntity as e where e.geometry is not null");
Type geometryType = new CustomType(GeometryUserType.class, null);
q.setParameter(0, jtsFilter, geometryType);
int i = 0;
int cnt = 0;
int cntEmpty = 0;
for (Iterator it = q.list().iterator(); it.hasNext() && i++ < 100;) {
Object[] objs = (Object[]) it.next();
Long id = (Long) objs[0];
Geometry geom = (Geometry) objs[1];
Geometry symDiff = (Geometry) objs[2];
// some databases give a null object if the difference is the
// null-set
if (symDiff == null || symDiff.isEmpty()) {
cntEmpty++;
continue;
}
symDiff.normalize();
 
Geometry jtsSymDiff = geom.symDifference(jtsFilter);
jtsSymDiff.normalize();
if (jtsSymDiff.equalsExact(symDiff, 0.5))
cnt++;
else
System.out.println("Unequal symdiff for geom (" + id + "): "
+ geom + "\n\t db symdiff = " + symDiff
+ "\n\t jts symdiff = " + jtsSymDiff);
}
assertTrue(cnt > 0);
System.out.println("Number of equal symdiffs = " + cnt);
System.out.println("Number of empty or null symdiff results = "
+ cntEmpty);
session.close();
 
}
 
public void testHQLUnion() throws Exception {
Session session = factory.openSession();
 
Query q = session
.createQuery("select e.id, e.geometry, geomunion(e.geometry, ?) from PolygonEntity as e where e.geometry is not null");
Type geometryType = new CustomType(GeometryUserType.class, null);
q.setParameter(0, jtsFilter, geometryType);
int i = 0;
int cnt = 0;
int cntEmpty = 0;
for (Iterator it = q.list().iterator(); it.hasNext() && i++ < 100;) {
Object[] objs = (Object[]) it.next();
Long id = (Long) objs[0];
Geometry geom = (Geometry) objs[1];
Geometry union = (Geometry) objs[2];
// some databases give a null object if the difference is the
// null-set
if (union == null || union.isEmpty()) {
cntEmpty++;
continue;
}
union.normalize();
 
Geometry jtsUnion = geom.union(jtsFilter);
jtsUnion.normalize();
if (jtsUnion.equalsExact(union, 0.5))
cnt++;
else
System.out.println("Unequal union for geom (" + id + "): "
+ geom + "\n\t db union = " + union
+ "\n\t jts union = " + jtsUnion);
}
assertTrue(cnt > 0);
System.out.println("Number of equal unions = " + cnt);
System.out.println("Number of empty or null union results = "
+ cntEmpty);
session.close();
 
}
 
/**
* Used to test if two geometries are approximately co-incident.
*
* @param g1
* @param g2
* @param tolerance
* acceptable relative error in
* @return
*/
private boolean approximateCoincident(Geometry g1, Geometry g2,
double tolerance) {
Geometry symdiff = null;
if (g1.getDimension() < 2 && g2.getDimension() < 2) {
g1 = g1.buffer(tolerance);
g2 = g2.buffer(tolerance);
symdiff = g1.symDifference(g2).buffer(tolerance);
} else {
symdiff = g1.symDifference(g2);
}
double relError = symdiff.getArea() / (g1.getArea() + g2.getArea());
return relError < tolerance;
 
}
 
}
/trunk/hibernate-spatial/src/test/java/com/cadrie/hibernate/spatial/test/TestCRUD.java
New file
0,0 → 1,131
package com.cadrie.hibernate.spatial.test;
 
import java.sql.SQLException;
 
import junit.framework.TestCase;
 
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
 
import com.cadrie.hibernate.spatial.test.model.LineStringEntity;
import com.cadrie.hibernate.spatial.test.model.MultiLineStringEntity;
import com.cadrie.hibernate.spatial.test.model.PolygonEntity;
import com.vividsolutions.jts.geom.Coordinate;
import com.vividsolutions.jts.geom.Geometry;
import com.vividsolutions.jts.geom.GeometryFactory;
import com.vividsolutions.jts.geom.PrecisionModel;
import com.vividsolutions.jts.io.ParseException;
 
/**
* @author maesenka
*
*/
public class TestCRUD extends TestCase {
 
private SessionFactory factory;
 
private final static int COORDARRAY_LENGTH = 100;
 
private GeometryFactory geomFactory = new GeometryFactory(
new PrecisionModel(PrecisionModel.FLOATING), 31370);
 
public void setUpBeforeClass() throws SQLException, ClassNotFoundException,
ParseException {
 
// set up hibernate and register Spatialtest as a persistent entity
System.out.println("Setting up Hibernate");
Configuration config = new Configuration();
config.configure();
config.addClass(LineStringEntity.class);
config.addClass(PolygonEntity.class);
config.addClass(MultiLineStringEntity.class);
 
// build the session factory
// Settings settings = config.buildSettings();
// SpatialExtension.setDefaultSpatialDialect((SpatialDialect)settings.getDialect());
factory = config.buildSessionFactory();
 
}
 
public void tearDownAfterClass() {
factory.close();
factory = null;
}
 
private long saveObject(Object obj) throws Exception {
Session session = factory.openSession();
 
Transaction tx = null;
long id = -1;
try {
tx = session.beginTransaction();
session.save(obj);
 
if (obj instanceof LineStringEntity)
id = ((LineStringEntity) obj).getId();
 
tx.commit();
} catch (Exception e) {
tx.rollback();
throw e;
} finally {
session.close();
}
return id;
}
 
private Object retrieveObject(Class clazz, long id) {
Session session = factory.openSession();
Object obj = session.get(clazz, id);
session.close();
return obj;
}
 
public void testSaveLineStringEntity() throws Exception {
LineStringEntity line = new LineStringEntity();
Coordinate[] coordinates = new Coordinate[COORDARRAY_LENGTH];
 
double startx = 4319.0;
double starty = 53255.0;
 
for (int i = 0; i < COORDARRAY_LENGTH; i++) {
coordinates[i] = new Coordinate(startx + i, starty + i);
}
 
Geometry geom = geomFactory.createLineString(coordinates);
line.setGeometry(geom);
line.setName("Added by TestCRUD");
long id = saveObject(line);
LineStringEntity retrieved = (LineStringEntity) retrieveObject(
LineStringEntity.class, id);
// check if we retrieve all the same stuff
assertTrue(line.getGeometry().equals(retrieved.getGeometry()));
// assertEquals(line.getGeometry(),
// retrieved.getGeometry()); DOES NOT WORK:
// AssertEquals doesn' t work because in JTS 1.7 Geometry has a
// method with signature boolean equals(Geometry) which does NOT override
// equals(Object). This last method is called from assertEquals.
 
assertEquals(line.getId(), retrieved.getId());
assertEquals(line.getName(), retrieved.getName());
}
 
public void testSaveNullLineStringEntity() throws Exception {
LineStringEntity line = new LineStringEntity();
line.setGeometry(null);
line.setName("Null geom Added by TestCRUD");
long id = saveObject(line);
 
// System.out.println("id: " + id);
 
LineStringEntity retrieved = (LineStringEntity) retrieveObject(
LineStringEntity.class, id);
// check if we retrieve a null geometry
assertNull(retrieved.getGeometry());
 
}
}
/trunk/hibernate-spatial/src/main/java/META-INF/MANIFEST.MF
New file
0,0 → 1,3
Manifest-Version: 1.0
Class-Path:
 
/trunk/hibernate-spatial/src/main/java/com/cadrie/hibernate/spatial/SpatialAnalysis.java
New file
0,0 → 1,19
package com.cadrie.hibernate.spatial;
 
public interface SpatialAnalysis {
public static int DISTANCE = 1;
public static int BUFFER = 2;
public static int CONVEXHULL = 3;
public static int INTERSECTION = 4;
public static int UNION = 5;
public static int DIFFERENCE = 6;
public static int SYMDIFFERENCE = 7;
 
}
/trunk/hibernate-spatial/src/main/java/com/cadrie/hibernate/spatial/SpatialDialect.java
New file
0,0 → 1,79
/**
* $Id: SpatialDialect.java 79 2007-02-01 18:03:43Z maesenka $
*
* This file is part of MAJAS (Mapping with Asynchronous JavaScript and ASVG). a
* framework for Rich Internet GIS Applications.
*
* Copyright © 2007 DFC Software Engineering, Belgium
* and K.U. Leuven LRD, Spatial Applications Division, Belgium
*
* MAJAS is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* MAJAS is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with gGIS; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
 
package com.cadrie.hibernate.spatial;
 
import org.hibernate.usertype.UserType;
 
/**
* @author Karel Maesen, K.U.Leuven R&D Divisie SADL
* @version $Id: SpatialDialect.java 79 2007-02-01 18:03:43Z maesenka $
*
* Describes the features of a spatially enabled dialect.
*
*/
public interface SpatialDialect {
 
/**
* Returns the SQL fragment for the SQL WHERE-clause when parsing
* <code>org.walkonweb.spatial.criterion.SpatialRelateExpression</code>s
* into prepared statements.
*
* If useFilter is specified, then a two-stage spatial query model is
* assumed (first stage using only spatial index; second stage
* performing exact comparisons between geometries). The returned
* SQL-fragement in that case should contains two input parameters. The
* first for setting the filter geometry, the second for the test
* geometry.
*
* @param columnName
* The name of the geometry-typed column to which the
* relation is applied
* @param spatialRelation
* The type of spatial relation (as defined in
* <code>org.walkonweb.spatial.SpatialRelation</code>).
* @param useFilter
* If true, the SpatialRelateExpression uses two-stage
* query model
* @return - SQL fragment for use in the SQL WHERE-clause.
*/
public String getSpatialRelateSQL(String columnName,
int spatialRelation, boolean useFilter);
 
/**
* Returns the SQL fragment for the SQL WHERE-expression when parsing
* <code>org.walkonweb.spatial.criterion.SpatialFilterExpression</code>s
* into prepared statements.
*
*
* @param columnName-
* the name of the geometry-typed column to which the
* filter is be applied.
* @return
*/
public String getSpatialFilterExpression(String columnName);
 
public UserType getGeometryUserType();
 
}
/trunk/hibernate-spatial/src/main/java/com/cadrie/hibernate/spatial/HBSpatialExtension.java
New file
0,0 → 1,155
/**
* $Id: HBSpatialExtension.java 79 2007-02-01 18:03:43Z maesenka $
*
* This file is part of MAJAS (Mapping with Asynchronous JavaScript and ASVG). a
* framework for Rich Internet GIS Applications.
*
* Copyright © 2007 DFC Software Engineering, Belgium
* and K.U. Leuven LRD, Spatial Applications Division, Belgium
*
* MAJAS is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* MAJAS is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with gGIS; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
 
package com.cadrie.hibernate.spatial;
 
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.util.Enumeration;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
 
import com.cadrie.hibernate.spatial.spi.SpatialDialectProvider;
 
/**
* This is the bootstrap class that is used to get an
* <code>SpatialDialect</code>.
*
* It also provides a default <code>SpatialDialect</code>.
* <code>GeometryUserTypes</code>s that do not have a <code>dialect</code>
* parameter use this default.
*
* The default <code>SpatialDialect</code> will be the first one that is
* returned by the <code>getDefaultDialect</code> method of the provider at
* least if it is non null.
*
* @author Karel Maesen
*/
public class HBSpatialExtension {
 
protected static Set<SpatialDialectProvider> providers = new HashSet<SpatialDialectProvider>();
 
private static SpatialDialect defaultSpatialDialect = null;
 
private static final Pattern nonCommentPattern = Pattern
.compile("^([^#]+)");
 
static {
 
ClassLoader loader = Thread.currentThread().getContextClassLoader();
Enumeration<URL> resources = null;
try {
resources = loader.getResources("META-INF/services/"
+ SpatialDialectProvider.class.getName());
Set<String> names = new HashSet<String>();
while (resources.hasMoreElements()) {
URL url = resources.nextElement();
InputStream is = url.openStream();
try {
names.addAll(providerNamesFromReader(new BufferedReader(
new InputStreamReader(is))));
} finally {
is.close();
}
}
 
for (String s : names) {
try {
SpatialDialectProvider provider = (SpatialDialectProvider) loader
.loadClass(s).newInstance();
// if no Default SpatialDialect, we ask the provider to
// set one.
if (defaultSpatialDialect == null)
setDefaultSpatialDialect(provider.getDefaultDialect());
providers.add(provider);
} catch (Exception e) {
throw new HibernateSpatialException(
"Problem loading provider class", e);
}
}
} catch (IOException e) {
throw new HibernateSpatialException("No "
+ SpatialDialectProvider.class.getName()
+ " found in META-INF/services", e);
}
 
}
 
/**
* Make sure nobody can instantiate this class
*/
private HBSpatialExtension() {
}
 
/**
* @param dialect
*/
public static void setDefaultSpatialDialect(SpatialDialect dialect) {
defaultSpatialDialect = dialect;
}
 
public static SpatialDialect getDefaultSpatialDialect() {
return defaultSpatialDialect;
}
 
public static SpatialDialect createSpatialDialect(String dialectName,
Map properties) {
SpatialDialect dialect = null;
for (SpatialDialectProvider provider : providers) {
dialect = provider.createSpatialDialect(dialectName, properties);
if (dialect != null) {
break;
}
}
if (dialect == null) {
throw new HibernateSpatialException(
"No SpatialDialect provider for persistenceUnit "
+ dialectName);
}
return dialect;
}
 
// Helper methods
 
private static Set<String> providerNamesFromReader(BufferedReader reader)
throws IOException {
Set<String> names = new HashSet<String>();
String line;
while ((line = reader.readLine()) != null) {
line = line.trim();
Matcher m = nonCommentPattern.matcher(line);
if (m.find()) {
names.add(m.group().trim());
}
}
return names;
}
 
}
/trunk/hibernate-spatial/src/main/java/com/cadrie/hibernate/spatial/AbstractDBGeometryType.java
New file
0,0 → 1,200
/**
* $Id$
*
* This file is part of MAJAS (Mapping with Asynchronous JavaScript and ASVG). a
* framework for Rich Internet GIS Applications.
*
* Copyright @ 2007 DFC Software Engineering, Belgium
* and K.U. Leuven LRD, Spatial Applications Division, Belgium
*
* MAJAS is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* MAJAS is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with gGIS; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
 
package com.cadrie.hibernate.spatial;
 
import java.io.Serializable;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Properties;
 
import org.hibernate.HibernateException;
import org.hibernate.usertype.ParameterizedType;
import org.hibernate.usertype.UserType;
 
import com.vividsolutions.jts.geom.Geometry;
 
/**
* @author Karel Maesen
*
* This type is a abstract base type for implemenating database specific user
* types for geometry types.
*
*/
public abstract class AbstractDBGeometryType implements UserType,
ParameterizedType {
 
/*
* (non-Javadoc)
*
* @see org.hibernate.usertype.UserType#assemble(java.io.Serializable,
* java.lang.Object)
*/
public Object assemble(Serializable cached, Object owner)
throws HibernateException {
return cached;
}
 
/*
* (non-Javadoc)
*
* @see org.hibernate.usertype.UserType#deepCopy(java.lang.Object)
*/
public Object deepCopy(Object value) throws HibernateException {
return value;
}
 
/*
* (non-Javadoc)
*
* @see org.hibernate.usertype.UserType#disassemble(java.lang.Object)
*/
public Serializable disassemble(Object value) throws HibernateException {
return (Serializable) value;
}
 
/*
* (non-Javadoc)
*
* @see org.hibernate.usertype.UserType#equals(java.lang.Object,
* java.lang.Object)
*/
public boolean equals(Object x, Object y) throws HibernateException {
if (x == y)
return true;
if (x == null || y == null)
return false;
return ((Geometry) x).equalsExact((Geometry) y);
}
 
/*
* (non-Javadoc)
*
* @see org.hibernate.usertype.UserType#hashCode(java.lang.Object)
*/
public int hashCode(Object x) throws HibernateException {
return x.hashCode();
}
 
/*
* (non-Javadoc)
*
* @see org.hibernate.usertype.UserType#isMutable()
*/
public boolean isMutable() {
return false;
}
 
/*
* (non-Javadoc)
*
* @see org.hibernate.usertype.UserType#nullSafeGet(java.sql.ResultSet,
* java.lang.String[], java.lang.Object)
*/
public Object nullSafeGet(ResultSet rs, String[] names, Object owner)
throws HibernateException, SQLException {
Object geomObj = rs.getObject(names[0]);
return convert2JTS(geomObj);
}
 
/**
* Converts the native database geometry object to a JTS Geometry
* object.
*
* Concrete subclasses should override this method.
*
* @param geomObj
* native database geometry object
* @return JTS Geometry
*/
public abstract Geometry convert2JTS(Object geomObj);
 
/*
* (non-Javadoc)
*
* @see org.hibernate.usertype.UserType#nullSafeSet(java.sql.PreparedStatement,
* java.lang.Object, int)
*/
public void nullSafeSet(PreparedStatement st, Object value, int index)
throws HibernateException, SQLException {
if (value == null) {
st.setNull(index, sqlTypes()[0]);
} else {
Geometry jtsGeom = (Geometry) value;
Object dbGeom = conv2DBGeometry(jtsGeom, st.getConnection());
st.setObject(index, dbGeom);
}
}
 
/**
* Converts a JTS geometry object to a native database geometry object.
*
* Concrete subclasses should override this method.
*
* @param geomObj
* JTS Geometry
* @return native database geometry object
*/
public abstract Object conv2DBGeometry(Geometry jtsGeom, Connection connection) ;
 
/*
* (non-Javadoc)
*
* @see org.hibernate.usertype.UserType#replace(java.lang.Object,
* java.lang.Object, java.lang.Object)
*/
public Object replace(Object original, Object target, Object owner)
throws HibernateException {
return original;
}
 
/*
* (non-Javadoc)
*
* @see org.hibernate.usertype.UserType#returnedClass()
*/
public Class returnedClass() {
return Geometry.class;
}
 
/*
* (non-Javadoc)
*
* @see org.hibernate.usertype.UserType#sqlTypes()
*
* This should be overriden by concrete subclasses
*/
public abstract int[] sqlTypes();
 
/*
* (non-Javadoc)
*
* @see org.hibernate.usertype.ParameterizedType#setParameterValues(java.util.Properties)
*/
public void setParameterValues(Properties parameters) {
}
 
}
/trunk/hibernate-spatial/src/main/java/com/cadrie/hibernate/spatial/SpatialRelation.java
New file
0,0 → 1,52
/**
* $Id: SpatialRelation.java 79 2007-02-01 18:03:43Z maesenka $
*
* This file is part of MAJAS (Mapping with Asynchronous JavaScript and ASVG). a
* framework for Rich Internet GIS Applications.
*
* Copyright © 2007 DFC Software Engineering, Belgium
* and K.U. Leuven LRD, Spatial Applications Division, Belgium
*
* MAJAS is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* MAJAS is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with gGIS; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
 
package com.cadrie.hibernate.spatial;
 
/**
* @author Karel Maesen, K.U.Leuven R&D Divisie SADL
*
* These spatial relations are all defined in "OpenGIS Simple Feature
* Specification for SQL, Rev. 1.1" of the Open Geospatial Consortium (OGC).
*
*/
public interface SpatialRelation {
 
public static int EQUALS = 0;
 
public static int DISJOINT = 1;
 
public static int TOUCHES = 2;
 
public static int CROSSES = 3;
 
public static int WITHIN = 4;
 
public static int OVERLAPS = 5;
 
public static int CONTAINS = 6;
 
public static int INTERSECTS = 7;
}
/trunk/hibernate-spatial/src/main/java/com/cadrie/hibernate/spatial/spi/SpatialDialectProvider.java
New file
0,0 → 1,62
/**
* $Id: SpatialDialectProvider.java 81 2007-02-01 18:04:54Z maesenka $
*
* This file is part of MAJAS (Mapping with Asynchronous JavaScript and ASVG). a
* framework for Rich Internet GIS Applications.
*
* Copyright © 2007 DFC Software Engineering, Belgium
* and K.U. Leuven LRD, Spatial Applications Division, Belgium
*
* MAJAS is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* MAJAS is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with gGIS; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
 
package com.cadrie.hibernate.spatial.spi;
 
import java.util.Map;
 
import com.cadrie.hibernate.spatial.SpatialDialect;
 
/**
* Interface that is implemented by a SpatialDialect Provider.
*
* A <class>SpatialDialectProvider</class> creates a SpatialDialect for one
* or more database systems. These databases are identified by a dialect string.
* Usually this is the fully qualified class name of an
* <code>org.hibernate.dialect.Dialect</code> or <code>SpatialDialect</code>
* implementation
*
* @author Karel Maesen
*
*/
 
public interface SpatialDialectProvider {
 
/**
* @param dialect
* Name of the persistence unit
* @param map
* A map of properties for use by the provider
* @return the SpatialDialect provided by the provider implementation
*/
public SpatialDialect createSpatialDialect(String dialect, Map map);
 
/**
* @return The Default Dialect provided by the implementation.
*
* Implementations should never return null for this method.
*/
public SpatialDialect getDefaultDialect();
 
}
/trunk/hibernate-spatial/src/main/java/com/cadrie/hibernate/spatial/GeometryUserType.java
New file
0,0 → 1,222
/**
* $Id: GeometryUserType.java 79 2007-02-01 18:03:43Z maesenka $
*
* This file is part of MAJAS (Mapping with Asynchronous JavaScript and ASVG). a
* framework for Rich Internet GIS Applications.
*
* Copyright © 2007 DFC Software Engineering, Belgium
* and K.U. Leuven LRD, Spatial Applications Division, Belgium
*
* MAJAS is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* MAJAS is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with gGIS; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
 
package com.cadrie.hibernate.spatial;
 
import java.io.Serializable;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Properties;
 
import org.hibernate.HibernateException;
import org.hibernate.usertype.ParameterizedType;
import org.hibernate.usertype.UserType;
 
/**
* This class ensures that Hibernate on top of PostgreSQL/PostGIS can work with
* the JTS <code>Geometry</code> type.
*
* To properly convert <code>Geometry</code> objects to database specific
* wrapper objects, acces is needed to a spatially enabled database dialect.
* This dialect can be specified as a parameter to the type. If no parameter is
* supplied, the default Dialect will be used (set in HBSpatialExtension).
*/
public class GeometryUserType implements UserType, ParameterizedType {
 
private Properties properties = null;
 
private SpatialDialect spatialDialect = null;
 
private UserType delegate = null;
 
public static String DIALECT_PARAM_NAME = "dialect";
 
private void configureDialect() {
if (properties == null) {
spatialDialect = HBSpatialExtension.getDefaultSpatialDialect();
} else {
spatialDialect = HBSpatialExtension.createSpatialDialect(properties
.getProperty(DIALECT_PARAM_NAME), properties);
}
if (spatialDialect == null) {
throw new HibernateSpatialException(
"No spatial Dialect could be created");
}
delegate = spatialDialect.getGeometryUserType();
}
 
/**
* @param arg0
* @param arg1
* @return
* @throws HibernateException
* @see org.hibernate.usertype.UserType#assemble(java.io.Serializable,
* java.lang.Object)
*/
public Object assemble(Serializable arg0, Object arg1)
throws HibernateException {
return delegate.assemble(arg0, arg1);
}
 
/**
* @param arg0
* @return
* @throws HibernateException
* @see org.hibernate.usertype.UserType#deepCopy(java.lang.Object)
*/
public Object deepCopy(Object arg0) throws HibernateException {
return delegate.deepCopy(arg0);
}
 
/**
* @param arg0
* @return
* @throws HibernateException
* @see org.hibernate.usertype.UserType#disassemble(java.lang.Object)
*/
public Serializable disassemble(Object arg0) throws HibernateException {
return delegate.disassemble(arg0);
}
 
/**
* @param arg0
* @param arg1
* @return
* @throws HibernateException
* @see org.hibernate.usertype.UserType#equals(java.lang.Object,
* java.lang.Object)
*/
public boolean equals(Object arg0, Object arg1) throws HibernateException {
return delegate.equals(arg0, arg1);
}
 
/**
* @param obj
* @return
* @see java.lang.Object#equals(java.lang.Object)
*/
public boolean equals(Object obj) {
return delegate.equals(obj);
}
 
/**
* @return
* @see java.lang.Object#hashCode()
*/
public int hashCode() {
return delegate.hashCode();
}
 
/**
* @param arg0
* @return
* @throws HibernateException
* @see org.hibernate.usertype.UserType#hashCode(java.lang.Object)
*/
public int hashCode(Object arg0) throws HibernateException {
return delegate.hashCode(arg0);
}
 
/**
* @return
* @see org.hibernate.usertype.UserType#isMutable()
*/
public boolean isMutable() {
return delegate.isMutable();
}
 
/**
* @param arg0
* @param arg1
* @param arg2
* @return
* @throws HibernateException
* @throws SQLException
* @see org.hibernate.usertype.UserType#nullSafeGet(java.sql.ResultSet,
* java.lang.String[], java.lang.Object)
*/
public Object nullSafeGet(ResultSet arg0, String[] arg1, Object arg2)
throws HibernateException, SQLException {
return delegate.nullSafeGet(arg0, arg1, arg2);
}
 
/**
* @param arg0
* @param arg1
* @param arg2
* @throws HibernateException
* @throws SQLException
* @see org.hibernate.usertype.UserType#nullSafeSet(java.sql.PreparedStatement,
* java.lang.Object, int)
*/
public void nullSafeSet(PreparedStatement arg0, Object arg1, int arg2)
throws HibernateException, SQLException {
delegate.nullSafeSet(arg0, arg1, arg2);
}
 
/**
* @param arg0
* @param arg1
* @param arg2
* @return
* @throws HibernateException
* @see org.hibernate.usertype.UserType#replace(java.lang.Object,
* java.lang.Object, java.lang.Object)
*/
public Object replace(Object arg0, Object arg1, Object arg2)
throws HibernateException {
return delegate.replace(arg0, arg1, arg2);
}
 
/**
* @return
* @see org.hibernate.usertype.UserType#returnedClass()
*/
public Class returnedClass() {
return delegate.returnedClass();
}
 
/**
* @return
* @see org.hibernate.usertype.UserType#sqlTypes()
*/
public int[] sqlTypes() {
return delegate.sqlTypes();
}
 
/**
* @return
* @see java.lang.Object#toString()
*/
public String toString() {
return delegate.toString();
}
 
public void setParameterValues(Properties properties) {
this.properties = properties;
configureDialect();
}
 
}
/trunk/hibernate-spatial/src/main/java/com/cadrie/hibernate/spatial/HibernateSpatialException.java
New file
0,0 → 1,49
/**
* $Id: HibernateSpatialException.java 79 2007-02-01 18:03:43Z maesenka $
*
* This file is part of MAJAS (Mapping with Asynchronous JavaScript and ASVG). a
* framework for Rich Internet GIS Applications.
*
* Copyright © 2007 DFC Software Engineering, Belgium
* and K.U. Leuven LRD, Spatial Applications Division, Belgium
*
* MAJAS is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* MAJAS is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with gGIS; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
 
package com.cadrie.hibernate.spatial;
 
/**
*
*/
public class HibernateSpatialException extends RuntimeException {
 
/**
* generated serialVersionUID
*/
private static final long serialVersionUID = -2153256823661407568L;
 
public HibernateSpatialException(String msg) {
super(msg);
}
 
public HibernateSpatialException(Throwable cause) {
super(cause);
}
 
public HibernateSpatialException(String msg, Throwable cause) {
super(msg, cause);
}
 
}
/trunk/hibernate-spatial/src/main/java/com/cadrie/hibernate/spatial/criterion/SpatialFilter.java
New file
0,0 → 1,78
/**
* $Id: SpatialFilter.java 80 2007-02-01 18:04:02Z maesenka $
*
* This file is part of MAJAS (Mapping with Asynchronous JavaScript and ASVG). a
* framework for Rich Internet GIS Applications.
*
* Copyright © 2007 DFC Software Engineering, Belgium
* and K.U. Leuven LRD, Spatial Applications Division, Belgium
*
* MAJAS is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* MAJAS is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with gGIS; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
 
package com.cadrie.hibernate.spatial.criterion;
 
import org.hibernate.Criteria;
import org.hibernate.HibernateException;
import org.hibernate.criterion.CriteriaQuery;
import org.hibernate.criterion.Criterion;
import org.hibernate.dialect.Dialect;
import org.hibernate.engine.SessionFactoryImplementor;
import org.hibernate.engine.TypedValue;
 
import com.cadrie.hibernate.spatial.SpatialDialect;
import com.vividsolutions.jts.geom.Geometry;
 
/**
* An implementation for a simple spatial filter. This <code>Criterion</code>
* restricts the resultset to those features whose bounding box overlaps the
* filter geometry. It is intended for quick, but inexact spatial queries.
*
*/
public class SpatialFilter implements Criterion {
 
private static final long serialVersionUID = 1L;
 
private String propertyName = null;
 
private Geometry filter = null;
 
public SpatialFilter(String propertyName, Geometry filter) {
this.propertyName = propertyName;
this.filter = filter;
}
 
public TypedValue[] getTypedValues(Criteria criteria,
CriteriaQuery criteriaQuery) throws HibernateException {
return new TypedValue[] { criteriaQuery.getTypedValue(criteria,
propertyName, filter) };
}
 
public String toSqlString(Criteria criteria, CriteriaQuery criteriaQuery)
throws HibernateException {
SessionFactoryImplementor factory = criteriaQuery.getFactory();
String[] columns = criteriaQuery.getColumnsUsingProjection(criteria,
this.propertyName);
Dialect dialect = factory.getDialect();
if (dialect instanceof SpatialDialect) {
SpatialDialect seDialect = (SpatialDialect) dialect;
return seDialect.getSpatialFilterExpression(columns[0]);
} else
throw new IllegalStateException(
"Dialect must be spatially enabled dialect");
 
}
 
}
/trunk/hibernate-spatial/src/main/java/com/cadrie/hibernate/spatial/criterion/SpatialRestrictions.java
New file
0,0 → 1,103
/**
* $Id: SpatialRestrictions.java 80 2007-02-01 18:04:02Z maesenka $
*
* This file is part of MAJAS (Mapping with Asynchronous JavaScript and ASVG). a
* framework for Rich Internet GIS Applications.
*
* Copyright © 2007 DFC Software Engineering, Belgium
* and K.U. Leuven LRD, Spatial Applications Division, Belgium
*
* MAJAS is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* MAJAS is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with gGIS; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
 
package com.cadrie.hibernate.spatial.criterion;
 
import com.cadrie.hibernate.spatial.SpatialRelation;
import com.vividsolutions.jts.geom.Geometry;
 
/**
* Static Factory Class for creating spatial criterion types.
*
* <p>
* The criterion types created by this class implement the spatial query
* expressions of the OpenGIS Simple Features Specification for SQL, Revision
* 1.1.
*
* In addition, it provides for a simple spatial <code>filter</code> that
* works mostly using the spatial index. This corresponds to the Oracle
* Spatial's "SDO_FILTER" function, or the "&&" operator of PostGIS.
* </p>
*
*
*
*/
public class SpatialRestrictions {
 
SpatialRestrictions() {
}
 
public static SpatialRelateExpression eq(String propertyName,
Geometry filter, Geometry value) {
return new SpatialRelateExpression(propertyName, filter, value,
SpatialRelation.EQUALS);
}
 
public static SpatialRelateExpression within(String propertyName,
Geometry filter, Geometry value) {
return new SpatialRelateExpression(propertyName, filter, value,
SpatialRelation.WITHIN);
}
 
public static SpatialRelateExpression contains(String propertyName,
Geometry filter, Geometry value) {
return new SpatialRelateExpression(propertyName, filter, value,
SpatialRelation.CONTAINS);
}
 
public static SpatialRelateExpression crosses(String propertyName,
Geometry filter, Geometry value) {
return new SpatialRelateExpression(propertyName, filter, value,
SpatialRelation.CROSSES);
}
 
public static SpatialRelateExpression disjoint(String propertyName,
Geometry filter, Geometry value) {
return new SpatialRelateExpression(propertyName, filter, value,
SpatialRelation.DISJOINT);
}
 
public static SpatialRelateExpression intersects(String propertyName,
Geometry filter, Geometry value) {
return new SpatialRelateExpression(propertyName, filter, value,
SpatialRelation.INTERSECTS);
}
 
public static SpatialRelateExpression overlaps(String propertyName,
Geometry filter, Geometry value) {
return new SpatialRelateExpression(propertyName, filter, value,
SpatialRelation.OVERLAPS);
}
 
public static SpatialRelateExpression touches(String propertyName,
Geometry filter, Geometry value) {
return new SpatialRelateExpression(propertyName, filter, value,
SpatialRelation.TOUCHES);
}
 
public static SpatialFilter filter(String propertyName, Geometry filter) {
return new SpatialFilter(propertyName, filter);
}
 
}
/trunk/hibernate-spatial/src/main/java/com/cadrie/hibernate/spatial/criterion/SpatialRelateExpression.java
New file
0,0 → 1,122
/**
* $Id: SpatialRelateExpression.java 80 2007-02-01 18:04:02Z maesenka $
*
* This file is part of MAJAS (Mapping with Asynchronous JavaScript and ASVG). a
* framework for Rich Internet GIS Applications.
*
* Copyright © 2007 DFC Software Engineering, Belgium
* and K.U. Leuven LRD, Spatial Applications Division, Belgium
*
* MAJAS is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* MAJAS is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with gGIS; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
 
package com.cadrie.hibernate.spatial.criterion;
 
import org.hibernate.Criteria;
import org.hibernate.HibernateException;
import org.hibernate.criterion.CriteriaQuery;
import org.hibernate.criterion.Criterion;
import org.hibernate.dialect.Dialect;
import org.hibernate.engine.SessionFactoryImplementor;
import org.hibernate.engine.TypedValue;
 
import com.cadrie.hibernate.spatial.SpatialDialect;
import com.vividsolutions.jts.geom.Geometry;
 
/**
* An implementation of the <code>Criterion</code> interface that implements
* spatial queries: queries to the effect that a geometry property has a
* specific spatial relation to a test geometry
*
*
*/
public class SpatialRelateExpression implements Criterion {
 
/**
* The geometry property
*/
private String propertyName = null;
 
/**
* The test geometry
*/
private Geometry value = null;
 
/**
* An optional (bounding box) filter geometry.
*/
private Geometry filter = null;
 
/**
* The spatial relation that is queried for.
*/
private int spatialRelation = -1;
 
private static final long serialVersionUID = 1L;
 
public SpatialRelateExpression(String propertyName, Geometry filter,
Geometry value, int spatialRelation) {
this.propertyName = propertyName;
this.spatialRelation = spatialRelation;
this.filter = filter;
this.value = value;
}
 
/*
* (non-Javadoc)
*
* @see org.hibernate.criterion.Criterion#getTypedValues(org.hibernate.Criteria,
* org.hibernate.criterion.CriteriaQuery)
*/
public TypedValue[] getTypedValues(Criteria criteria,
CriteriaQuery criteriaQuery) throws HibernateException {
if (filter != null)
return new TypedValue[] {
criteriaQuery.getTypedValue(criteria, propertyName, filter),
criteriaQuery.getTypedValue(criteria, propertyName, value) };
else
return new TypedValue[] { criteriaQuery.getTypedValue(criteria,
propertyName, value) };
}
 
/*
* (non-Javadoc)
*
* @see org.hibernate.criterion.Criterion#toSqlString(org.hibernate.Criteria,
* org.hibernate.criterion.CriteriaQuery)
*/
public String toSqlString(Criteria criteria, CriteriaQuery criteriaQuery)
throws HibernateException {
SessionFactoryImplementor factory = criteriaQuery.getFactory();
String[] columns = criteriaQuery.getColumnsUsingProjection(criteria,
this.propertyName);
Dialect dialect = factory.getDialect();
if (dialect instanceof SpatialDialect) {
SpatialDialect seDialect = (SpatialDialect) dialect;
if (filter != null) {
return seDialect.getSpatialRelateSQL(columns[0],
spatialRelation, true);
} else {
return seDialect.getSpatialRelateSQL(columns[0],
spatialRelation, false);
}
 
} else {
throw new IllegalStateException(
"Dialect must be spatially enabled dialect");
}
}
 
}
/trunk/hibernate-spatial/pom.xml
New file
0,0 → 1,83
<?xml version="1.0" encoding="UTF-8"?>
<project>
<modelVersion>4.0.0</modelVersion>
<groupId>com.cadrie.hibernate</groupId>
<artifactId>hibernate-spatial</artifactId>
<version>0.9</version>
<name>Majas hibernate spatial Extension</name>
<description>Majas hibernate spatial</description>
<url>http://www.cadrie.com/projects/hibernate/spatial</url>
<packaging>pom</packaging>
<modules>
<module>../hibernate-spatial-postgis</module>
<module>../hibernate-spatial-oracle</module>
</modules>
<scm>
<connection>scm:svn:https://www.cadrie.com/svn/majas/trunk/hibernate-spatial</connection>
<developerConnection>scm:svn:https://www.cadrie.com/svn/majas/trunk/hibernate-spatial</developerConnection>
<url>scm:svn:https://www.cadrie.com/svn/majas/trunk/hibernate-spatial</url>
</scm>
<licenses>
<license>
<name>GNU General Public License (GPL), v2</name>
<url>http://www.gnu.org/licenses/gpl.html</url>
<distribution>repo</distribution>
</license>
</licenses>
<organization>
<name>Caffeine-Driven Enterprises</name>
<url>http://www.cadrie.com</url>
</organization>
<dependencies>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate</artifactId>
<version>3.2.2.ga</version>
</dependency>
<dependency>
<groupId>com.vividsolutions</groupId>
<artifactId>jts</artifactId>
<version>1.7.1</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.1</version>
</dependency>
</dependencies>
<distributionManagement>
<site>
<id>Hibernate Spatial site</id>
<name>Hibernate Spatial</name>
<url>scp://www.cadrie.com/var/www/www.cadrie.com/htdocs/projects/majas/hibernate/spatial</url>
</site>
</distributionManagement>
<developers>
<developer>
<id>jandm</id>
<name>Jan De Moerlose</name>
<email>jan.demoerlose@cadrie.com</email>
<roles>
<role>Architect</role>
<role>Lead Developer</role>
</roles>
</developer>
<developer>
<id>maesenka</id>
<name>Karel Maesen</name>
<email>karel.maesen@cadrie.com</email>
<roles>
<role>Architect</role>
<role>Lead Developer</role>
</roles>
</developer>
<developer>
<id>pieterdg</id>
<name>Pieter De Graef</name>
<email>pieter.degraef@cadrie.com</email>
<roles>
<role>Developer</role>
</roles>
</developer>
</developers>
</project>
/trunk/hibernate-spatial/.settings/org.eclipse.core.resources.prefs
New file
0,0 → 1,3
#Tue Mar 13 15:33:16 CET 2007
eclipse.preferences.version=1
encoding/<project>=UTF-8