HHH-6510 Minor cleanups; code formatting changed to Hibernate conventions.

This commit is contained in:
Karel Maesen 2011-07-27 19:18:47 +02:00 committed by Steve Ebersole
parent 812da6e7cd
commit 79d02e2f9d
72 changed files with 8528 additions and 7376 deletions

View File

@ -29,6 +29,7 @@
package org.hibernate.spatial; package org.hibernate.spatial;
import com.vividsolutions.jts.geom.Geometry; import com.vividsolutions.jts.geom.Geometry;
import org.hibernate.type.AbstractSingleColumnStandardBasicType; import org.hibernate.type.AbstractSingleColumnStandardBasicType;
/** /**
@ -38,29 +39,29 @@
*/ */
public class GeometryType extends AbstractSingleColumnStandardBasicType<Geometry> { public class GeometryType extends AbstractSingleColumnStandardBasicType<Geometry> {
public static final GeometryType INSTANCE = new GeometryType(); public static final GeometryType INSTANCE = new GeometryType();
@Override @Override
public String[] getRegistrationKeys() { public String[] getRegistrationKeys() {
return new String[]{ return new String[] {
com.vividsolutions.jts.geom.Geometry.class.getCanonicalName(), com.vividsolutions.jts.geom.Geometry.class.getCanonicalName(),
com.vividsolutions.jts.geom.Point.class.getCanonicalName(), com.vividsolutions.jts.geom.Point.class.getCanonicalName(),
com.vividsolutions.jts.geom.Polygon.class.getCanonicalName(), com.vividsolutions.jts.geom.Polygon.class.getCanonicalName(),
com.vividsolutions.jts.geom.MultiPolygon.class.getCanonicalName(), com.vividsolutions.jts.geom.MultiPolygon.class.getCanonicalName(),
com.vividsolutions.jts.geom.LineString.class.getCanonicalName(), com.vividsolutions.jts.geom.LineString.class.getCanonicalName(),
com.vividsolutions.jts.geom.MultiLineString.class.getCanonicalName(), com.vividsolutions.jts.geom.MultiLineString.class.getCanonicalName(),
com.vividsolutions.jts.geom.MultiPoint.class.getCanonicalName(), com.vividsolutions.jts.geom.MultiPoint.class.getCanonicalName(),
com.vividsolutions.jts.geom.GeometryCollection.class.getCanonicalName() com.vividsolutions.jts.geom.GeometryCollection.class.getCanonicalName()
}; };
} }
public GeometryType() { public GeometryType() {
super(SpatialGeometrySqlTypeDescriptor.INSTANCE, SpatialGeometryJavaTypeDescriptor.INSTANCE); super( SpatialGeometrySqlTypeDescriptor.INSTANCE, SpatialGeometryJavaTypeDescriptor.INSTANCE );
} }
@Override @Override
public String getName() { public String getName() {
return "Geometry"; return "Geometry";
} }
} }

View File

@ -28,18 +28,23 @@
*/ */
package org.hibernate.spatial; package org.hibernate.spatial;
import org.hibernate.spatial.helper.GeometryFactoryHelper;
import org.hibernate.spatial.cfg.HSConfiguration;
import org.hibernate.spatial.helper.PropertyFileReader;
import org.hibernate.spatial.mgeom.MGeometryFactory;
import org.hibernate.spatial.spi.SpatialDialectProvider;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException; import java.io.IOException;
import java.io.InputStream; import java.io.InputStream;
import java.net.URL; import java.net.URL;
import java.util.*; import java.util.ArrayList;
import java.util.Enumeration;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.hibernate.spatial.cfg.HSConfiguration;
import org.hibernate.spatial.helper.GeometryFactoryHelper;
import org.hibernate.spatial.helper.PropertyFileReader;
import org.hibernate.spatial.mgeom.MGeometryFactory;
import org.hibernate.spatial.spi.SpatialDialectProvider;
/** /**
* This is the bootstrap class that is used to get an * This is the bootstrap class that is used to get an
@ -59,179 +64,196 @@
//TODO -- this should be moved to the //TODO -- this should be moved to the
public class HBSpatialExtension { public class HBSpatialExtension {
protected static List<SpatialDialectProvider> providers = new ArrayList<SpatialDialectProvider>(); protected static List<SpatialDialectProvider> providers = new ArrayList<SpatialDialectProvider>();
private static final Logger log = LoggerFactory.getLogger(HBSpatialExtension.class); private static final Logger log = LoggerFactory.getLogger( HBSpatialExtension.class );
private static SpatialDialect defaultSpatialDialect = null; private static SpatialDialect defaultSpatialDialect = null;
private static final String DIALECT_PROP_NAME = "hibernate.spatial.dialect"; private static final String DIALECT_PROP_NAME = "hibernate.spatial.dialect";
private static HSConfiguration configuration = null; private static HSConfiguration configuration = null;
private static MGeometryFactory defaultGeomFactory = new MGeometryFactory(); private static MGeometryFactory defaultGeomFactory = new MGeometryFactory();
private static boolean configured = false; private static boolean configured = false;
static { static {
log.info("Initializing HBSpatialExtension"); log.info( "Initializing HBSpatialExtension" );
ClassLoader loader = Thread.currentThread().getContextClassLoader(); ClassLoader loader = Thread.currentThread().getContextClassLoader();
Enumeration<URL> resources = null; Enumeration<URL> resources = null;
try { try {
resources = loader.getResources("META-INF/services/" resources = loader.getResources(
+ SpatialDialectProvider.class.getName()); "META-INF/services/"
Set<String> names = new HashSet<String>(); + SpatialDialectProvider.class.getName()
while (resources.hasMoreElements()) { );
URL url = resources.nextElement(); Set<String> names = new HashSet<String>();
InputStream is = url.openStream(); while ( resources.hasMoreElements() ) {
try { URL url = resources.nextElement();
names.addAll(providerNamesFromReader(is)); InputStream is = url.openStream();
} finally { try {
is.close(); names.addAll( providerNamesFromReader( is ) );
} }
} finally {
is.close();
}
}
for (String s : names) { for ( String s : names ) {
try { try {
log.info("Attempting to load Hibernate Spatial Provider " log.info(
+ s); "Attempting to load Hibernate Spatial Provider "
SpatialDialectProvider provider = (SpatialDialectProvider) loader + s
.loadClass(s).newInstance(); );
providers.add(provider); SpatialDialectProvider provider = (SpatialDialectProvider) loader
} catch (Exception e) { .loadClass( s ).newInstance();
throw new HibernateSpatialException( providers.add( provider );
"Problem loading provider class", e); }
} catch ( Exception e ) {
throw new HibernateSpatialException(
"Problem loading provider class", e
);
}
} }
} catch (IOException e) { }
throw new HibernateSpatialException("No " catch ( IOException e ) {
+ SpatialDialectProvider.class.getName() throw new HibernateSpatialException(
+ " found in META-INF/services", e); "No "
} + SpatialDialectProvider.class.getName()
+ " found in META-INF/services", e
);
}
// configuration - check if there is a system property // configuration - check if there is a system property
String dialectProp = System.getProperty(DIALECT_PROP_NAME); String dialectProp = System.getProperty( DIALECT_PROP_NAME );
if (dialectProp != null) { if ( dialectProp != null ) {
HSConfiguration hsConfig = new HSConfiguration(); HSConfiguration hsConfig = new HSConfiguration();
hsConfig.setDefaultDialect(dialectProp); hsConfig.setDefaultDialect( dialectProp );
setConfiguration(hsConfig); setConfiguration( hsConfig );
} }
// configuration - load the config file // configuration - load the config file
log.info("Checking for default configuration file."); log.info( "Checking for default configuration file." );
HSConfiguration hsConfig = new HSConfiguration(); HSConfiguration hsConfig = new HSConfiguration();
if (hsConfig.configure()) { if ( hsConfig.configure() ) {
configuration = hsConfig; configuration = hsConfig;
} }
} }
/** /**
* Make sure nobody can instantiate this class * Make sure nobody can instantiate this class
*/ */
private HBSpatialExtension() { private HBSpatialExtension() {
} }
public static void setConfiguration(HSConfiguration c) { public static void setConfiguration(HSConfiguration c) {
log.info("Setting configuration object:" + c); log.info( "Setting configuration object:" + c );
configuration = c; configuration = c;
//if the HSExtension has already been initialized, //if the HSExtension has already been initialized,
//then it should be reconfigured. //then it should be reconfigured.
if (configured == true) { if ( configured == true ) {
forceConfigure(); forceConfigure();
} }
} }
private static synchronized void configure() { private static synchronized void configure() {
// // do nothing if already configured // // do nothing if already configured
if (configured) { if ( configured ) {
return; return;
} }
configured = true; configured = true;
forceConfigure(); forceConfigure();
} }
private static void forceConfigure() { private static void forceConfigure() {
// if no configuration object, take the first dialect that is available. // if no configuration object, take the first dialect that is available.
if (configuration == null) { if ( configuration == null ) {
return; return;
} else { }
log.info("Configuring HBSpatialExtension from " else {
+ configuration.getSource()); log.info(
String dialectName = configuration.getDefaultDialect(); "Configuring HBSpatialExtension from "
if (dialectName != null) { + configuration.getSource()
SpatialDialect dialect = createSpatialDialect(dialectName); );
if (dialect != null) { String dialectName = configuration.getDefaultDialect();
log.info("Setting Spatial Dialect to : " + dialectName); if ( dialectName != null ) {
setDefaultSpatialDialect(dialect); SpatialDialect dialect = createSpatialDialect( dialectName );
} if ( dialect != null ) {
} log.info( "Setting Spatial Dialect to : " + dialectName );
setDefaultSpatialDialect( dialect );
}
}
// trying to create a defaultGeometryFactory // trying to create a defaultGeometryFactory
log.info("Creating default Geometry Factory"); log.info( "Creating default Geometry Factory" );
defaultGeomFactory = GeometryFactoryHelper defaultGeomFactory = GeometryFactoryHelper
.createGeometryFactory(configuration); .createGeometryFactory( configuration );
} }
if (defaultSpatialDialect == null) { if ( defaultSpatialDialect == null ) {
log.warn("Hibernate Spatial Configured but no spatial dialect"); log.warn( "Hibernate Spatial Configured but no spatial dialect" );
} else { }
log.info("Hibernate Spatial configured. Using dialect: " else {
+ defaultSpatialDialect.getClass().getCanonicalName()); log.info(
} "Hibernate Spatial configured. Using dialect: "
} + defaultSpatialDialect.getClass().getCanonicalName()
);
}
}
public static HSConfiguration getConfiguration() { public static HSConfiguration getConfiguration() {
return configuration; return configuration;
} }
/** /**
* @param dialect * @param dialect
*/ */
private static void setDefaultSpatialDialect(SpatialDialect dialect) { private static void setDefaultSpatialDialect(SpatialDialect dialect) {
defaultSpatialDialect = dialect; defaultSpatialDialect = dialect;
} }
public static SpatialDialect getDefaultSpatialDialect() { public static SpatialDialect getDefaultSpatialDialect() {
configure(); configure();
return defaultSpatialDialect; return defaultSpatialDialect;
} }
public static SpatialDialect createSpatialDialect(String dialectName) { public static SpatialDialect createSpatialDialect(String dialectName) {
SpatialDialect dialect = null; SpatialDialect dialect = null;
for (SpatialDialectProvider provider : providers) { for ( SpatialDialectProvider provider : providers ) {
dialect = provider.createSpatialDialect(dialectName); dialect = provider.createSpatialDialect( dialectName );
if (dialect != null) { if ( dialect != null ) {
break; break;
} }
} }
if (dialect == null) { if ( dialect == null ) {
throw new HibernateSpatialException( throw new HibernateSpatialException(
"No SpatialDialect provider for persistenceUnit " "No SpatialDialect provider for persistenceUnit "
+ dialectName); + dialectName
} );
return dialect; }
} return dialect;
}
//TODO -- this is not thread-safe! //TODO -- this is not thread-safe!
//find another way to initialize //find another way to initialize
public static MGeometryFactory getDefaultGeomFactory() { public static MGeometryFactory getDefaultGeomFactory() {
configure(); configure();
return defaultGeomFactory; return defaultGeomFactory;
} }
// Helper methods // Helper methods
private static Set<String> providerNamesFromReader(InputStream is) private static Set<String> providerNamesFromReader(InputStream is)
throws IOException { throws IOException {
PropertyFileReader reader = new PropertyFileReader(is); PropertyFileReader reader = new PropertyFileReader( is );
return reader.getNonCommentLines(); return reader.getNonCommentLines();
} }
} }

View File

@ -3,7 +3,7 @@
* *
* This file is part of Hibernate Spatial, an extension to the * This file is part of Hibernate Spatial, an extension to the
* hibernate ORM solution for geographic data. * hibernate ORM solution for geographic data.
* *
* Copyright © 2007 Geovise BVBA * Copyright © 2007 Geovise BVBA
* Copyright © 2007 K.U. Leuven LRD, Spatial Applications Division, Belgium * Copyright © 2007 K.U. Leuven LRD, Spatial Applications Division, Belgium
* *
@ -30,7 +30,7 @@
/** /**
* Exception for Hibernate Spatial * Exception for Hibernate Spatial
* *
* @author Karel Maesen * @author Karel Maesen
*/ */
public class HibernateSpatialException extends RuntimeException { public class HibernateSpatialException extends RuntimeException {
@ -41,15 +41,15 @@ public class HibernateSpatialException extends RuntimeException {
private static final long serialVersionUID = -2153256823661407568L; private static final long serialVersionUID = -2153256823661407568L;
public HibernateSpatialException(String msg) { public HibernateSpatialException(String msg) {
super(msg); super( msg );
} }
public HibernateSpatialException(Throwable cause) { public HibernateSpatialException(Throwable cause) {
super(cause); super( cause );
} }
public HibernateSpatialException(String msg, Throwable cause) { public HibernateSpatialException(String msg, Throwable cause) {
super(msg, cause); super( msg, cause );
} }
} }

View File

@ -31,6 +31,6 @@
*/ */
public interface SpatialAggregate { public interface SpatialAggregate {
public static final int EXTENT = 1; public static final int EXTENT = 1;
} }

View File

@ -31,18 +31,18 @@
*/ */
public interface SpatialAnalysis { public interface SpatialAnalysis {
public static int DISTANCE = 1; public static int DISTANCE = 1;
public static int BUFFER = 2; public static int BUFFER = 2;
public static int CONVEXHULL = 3; public static int CONVEXHULL = 3;
public static int INTERSECTION = 4; public static int INTERSECTION = 4;
public static int UNION = 5; public static int UNION = 5;
public static int DIFFERENCE = 6; public static int DIFFERENCE = 6;
public static int SYMDIFFERENCE = 7; public static int SYMDIFFERENCE = 7;
} }

View File

@ -33,78 +33,85 @@
*/ */
public interface SpatialDialect extends Serializable { public interface SpatialDialect extends Serializable {
/** /**
* Returns the SQL fragment for the SQL WHERE-clause when parsing * Returns the SQL fragment for the SQL WHERE-clause when parsing
* <code>org.hibernatespatial.criterion.SpatialRelateExpression</code>s * <code>org.hibernatespatial.criterion.SpatialRelateExpression</code>s
* into prepared statements. * into prepared statements.
* <p/> * <p/>
* *
* @param columnName The name of the geometry-typed column to which the relation is * @param columnName The name of the geometry-typed column to which the relation is
* applied * applied
* @param spatialRelation The type of spatial relation (as defined in * @param spatialRelation The type of spatial relation (as defined in
* <code>SpatialRelation</code>). * <code>SpatialRelation</code>).
* @return SQL fragment for use in the SQL WHERE-clause. *
*/ * @return SQL fragment for use in the SQL WHERE-clause.
public String getSpatialRelateSQL(String columnName, int spatialRelation); */
public String getSpatialRelateSQL(String columnName, int spatialRelation);
/** /**
* Returns the SQL fragment for the SQL WHERE-expression when parsing * Returns the SQL fragment for the SQL WHERE-expression when parsing
* <code>org.hibernate.spatial.criterion.SpatialFilterExpression</code>s * <code>org.hibernate.spatial.criterion.SpatialFilterExpression</code>s
* into prepared statements. * into prepared statements.
* *
* @param columnName- the name of the geometry-typed column to which the filter is * @param columnName- the name of the geometry-typed column to which the filter is
* be applied. * be applied.
* @return *
*/ * @return
public String getSpatialFilterExpression(String columnName); */
public String getSpatialFilterExpression(String columnName);
/** /**
* @param columnName the name of the Geometry property * @param columnName the name of the Geometry property
* @param aggregation the type of <code>SpatialAggregate</code> * @param aggregation the type of <code>SpatialAggregate</code>
* @return the SQL fragment for the projection *
*/ * @return the SQL fragment for the projection
public String getSpatialAggregateSQL(String columnName, int aggregation); */
public String getSpatialAggregateSQL(String columnName, int aggregation);
/** /**
* Returns the SQL fragment when parsing a <code>DWithinExpression</code>. * Returns the SQL fragment when parsing a <code>DWithinExpression</code>.
* *
* @param columnName the geometry column to test against * @param columnName the geometry column to test against
* @return *
*/ * @return
public String getDWithinSQL(String columnName); */
public String getDWithinSQL(String columnName);
/** /**
* Returns the SQL fragment when parsing an <code>HavingSridExpression</code>. * Returns the SQL fragment when parsing an <code>HavingSridExpression</code>.
* *
* @param columnName the geometry column to test against * @param columnName the geometry column to test against
* @return *
*/ * @return
public String getHavingSridSQL(String columnName); */
public String getHavingSridSQL(String columnName);
/** /**
* Returns the SQL fragment when parsing a <code>IsEmptyExpression</code> or * Returns the SQL fragment when parsing a <code>IsEmptyExpression</code> or
* <code>IsNotEmpty</code> expression. * <code>IsNotEmpty</code> expression.
* *
* @param columnName the geometry column * @param columnName the geometry column
* @param isEmpty whether the geometry is tested for empty or non-empty * @param isEmpty whether the geometry is tested for empty or non-empty
* @return *
*/ * @return
public String getIsEmptySQL(String columnName, boolean isEmpty); */
public String getIsEmptySQL(String columnName, boolean isEmpty);
/** /**
* Returns true if this <code>SpatialDialect</code> supports a specific filtering function. * Returns true if this <code>SpatialDialect</code> supports a specific filtering function.
* <p/> * <p/>
* This is intended to signal DB-support for fast window queries, or MBR-overlap queries * This is intended to signal DB-support for fast window queries, or MBR-overlap queries
*/ */
public boolean supportsFiltering(); public boolean supportsFiltering();
/** /**
* Does this dialect supports the specified <code>SpatialFunction</code>. * Does this dialect supports the specified <code>SpatialFunction</code>.
* *
* @param function <code>SpatialFunction</code> * @param function <code>SpatialFunction</code>
* @return true if this <code>SpatialDialect</code> supports the spatial function specified by the function parameter. *
*/ * @return true if this <code>SpatialDialect</code> supports the spatial function specified by the function parameter.
public boolean supports(SpatialFunction function); */
public boolean supports(SpatialFunction function);
} }

View File

@ -35,40 +35,40 @@
*/ */
public enum SpatialFunction { public enum SpatialFunction {
dimension("SFS 1.1"), dimension( "SFS 1.1" ),
geometrytype("SFS 1.1"), geometrytype( "SFS 1.1" ),
srid("SFS 1.1"), srid( "SFS 1.1" ),
envelope("SFS 1.1"), envelope( "SFS 1.1" ),
astext("SFS 1.1"), astext( "SFS 1.1" ),
asbinary("SFS 1.1"), asbinary( "SFS 1.1" ),
isempty("SFS 1.1"), isempty( "SFS 1.1" ),
issimple("SFS 1.1"), issimple( "SFS 1.1" ),
boundary("SFS 1.1"), boundary( "SFS 1.1" ),
equals("SFS 1.1"), equals( "SFS 1.1" ),
disjoint("SFS 1.1"), disjoint( "SFS 1.1" ),
intersects("SFS 1.1"), intersects( "SFS 1.1" ),
touches("SFS 1.1"), touches( "SFS 1.1" ),
crosses("SFS 1.1"), crosses( "SFS 1.1" ),
within("SFS 1.1"), within( "SFS 1.1" ),
contains("SFS 1.1"), contains( "SFS 1.1" ),
overlaps("SFS 1.1"), overlaps( "SFS 1.1" ),
relate("SFS 1.1"), relate( "SFS 1.1" ),
distance("SFS 1.1"), distance( "SFS 1.1" ),
buffer("SFS 1.1"), buffer( "SFS 1.1" ),
convexhull("SFS 1.1"), convexhull( "SFS 1.1" ),
intersection("SFS 1.1"), intersection( "SFS 1.1" ),
geomunion("SFS 1.1"), //is actually UNION but this conflicts with SQL UNION construct geomunion( "SFS 1.1" ), //is actually UNION but this conflicts with SQL UNION construct
difference("SFS 1.1"), difference( "SFS 1.1" ),
symdifference("SFS 1.1"), symdifference( "SFS 1.1" ),
//the distance within function - dwithin(geom, geom, distance) : boolean) //the distance within function - dwithin(geom, geom, distance) : boolean)
dwithin("common"), dwithin( "common" ),
//the transform function - transform(geom, epsg-code): geometry //the transform function - transform(geom, epsg-code): geometry
transform("common"); transform( "common" );
private final String description; private final String description;
SpatialFunction(String specification) { SpatialFunction(String specification) {
this.description = specification; this.description = specification;
} }
} }

View File

@ -3,6 +3,7 @@
import com.vividsolutions.jts.geom.Geometry; import com.vividsolutions.jts.geom.Geometry;
import com.vividsolutions.jts.io.ParseException; import com.vividsolutions.jts.io.ParseException;
import com.vividsolutions.jts.io.WKTReader; import com.vividsolutions.jts.io.WKTReader;
import org.hibernate.type.descriptor.WrapperOptions; import org.hibernate.type.descriptor.WrapperOptions;
import org.hibernate.type.descriptor.java.AbstractTypeDescriptor; import org.hibernate.type.descriptor.java.AbstractTypeDescriptor;
import org.hibernate.type.descriptor.java.JavaTypeDescriptor; import org.hibernate.type.descriptor.java.JavaTypeDescriptor;
@ -14,35 +15,36 @@
public class SpatialGeometryJavaTypeDescriptor extends AbstractTypeDescriptor<Geometry> { public class SpatialGeometryJavaTypeDescriptor extends AbstractTypeDescriptor<Geometry> {
public static final JavaTypeDescriptor<Geometry> INSTANCE = new SpatialGeometryJavaTypeDescriptor(Geometry.class); public static final JavaTypeDescriptor<Geometry> INSTANCE = new SpatialGeometryJavaTypeDescriptor( Geometry.class );
protected SpatialGeometryJavaTypeDescriptor(Class<Geometry> type) { protected SpatialGeometryJavaTypeDescriptor(Class<Geometry> type) {
super(type); super( type );
} }
@Override @Override
public String toString(Geometry value) { public String toString(Geometry value) {
return value.toText(); return value.toText();
} }
@Override @Override
public Geometry fromString(String string) { public Geometry fromString(String string) {
WKTReader reader = new WKTReader(); WKTReader reader = new WKTReader();
try { try {
return reader.read(string); return reader.read( string );
} catch (ParseException e) { }
throw new RuntimeException(String.format("Can't parse string %s as WKT",string)); catch ( ParseException e ) {
} throw new RuntimeException( String.format( "Can't parse string %s as WKT", string ) );
} }
}
@Override @Override
public <X> X unwrap(Geometry value, Class<X> type, WrapperOptions options) { public <X> X unwrap(Geometry value, Class<X> type, WrapperOptions options) {
return null; //To change body of implemented methods use File | Settings | File Templates. return null; //To change body of implemented methods use File | Settings | File Templates.
} }
@Override @Override
public <X> Geometry wrap(X value, WrapperOptions options) { public <X> Geometry wrap(X value, WrapperOptions options) {
return null; //To change body of implemented methods use File | Settings | File Templates. return null; //To change body of implemented methods use File | Settings | File Templates.
} }
} }

View File

@ -1,12 +1,12 @@
package org.hibernate.spatial; package org.hibernate.spatial;
import java.sql.Types;
import org.hibernate.type.descriptor.ValueBinder; import org.hibernate.type.descriptor.ValueBinder;
import org.hibernate.type.descriptor.ValueExtractor; import org.hibernate.type.descriptor.ValueExtractor;
import org.hibernate.type.descriptor.java.JavaTypeDescriptor; import org.hibernate.type.descriptor.java.JavaTypeDescriptor;
import org.hibernate.type.descriptor.sql.SqlTypeDescriptor; import org.hibernate.type.descriptor.sql.SqlTypeDescriptor;
import java.sql.Types;
/** /**
* A generic <code>SqlTypeDescriptor</code>, intended to be remapped * A generic <code>SqlTypeDescriptor</code>, intended to be remapped
* by the spatial dialect. * by the spatial dialect.
@ -16,28 +16,28 @@
*/ */
public class SpatialGeometrySqlTypeDescriptor implements SqlTypeDescriptor { public class SpatialGeometrySqlTypeDescriptor implements SqlTypeDescriptor {
public static final SpatialGeometrySqlTypeDescriptor INSTANCE = new SpatialGeometrySqlTypeDescriptor(); public static final SpatialGeometrySqlTypeDescriptor INSTANCE = new SpatialGeometrySqlTypeDescriptor();
@Override @Override
public int getSqlType() { public int getSqlType() {
return Types.STRUCT; //this works only for postgis! return Types.STRUCT; //this works only for postgis!
//sqltype remapping issue: HHH-6074 needs to be resolved first. //sqltype remapping issue: HHH-6074 needs to be resolved first.
// return Types.OTHER; // return Types.OTHER;
} }
@Override @Override
public boolean canBeRemapped() { public boolean canBeRemapped() {
return true; return true;
} }
@Override @Override
public <X> ValueBinder<X> getBinder(JavaTypeDescriptor<X> javaTypeDescriptor) { public <X> ValueBinder<X> getBinder(JavaTypeDescriptor<X> javaTypeDescriptor) {
throw new UnsupportedOperationException(); throw new UnsupportedOperationException();
} }
@Override @Override
public <X> ValueExtractor<X> getExtractor(JavaTypeDescriptor<X> javaTypeDescriptor) { public <X> ValueExtractor<X> getExtractor(JavaTypeDescriptor<X> javaTypeDescriptor) {
throw new UnsupportedOperationException(); throw new UnsupportedOperationException();
} }
} }

View File

@ -36,23 +36,23 @@
*/ */
public interface SpatialRelation { public interface SpatialRelation {
public static int EQUALS = 0; public static int EQUALS = 0;
public static int DISJOINT = 1; public static int DISJOINT = 1;
public static int TOUCHES = 2; public static int TOUCHES = 2;
public static int CROSSES = 3; public static int CROSSES = 3;
public static int WITHIN = 4; public static int WITHIN = 4;
public static int OVERLAPS = 5; public static int OVERLAPS = 5;
public static int CONTAINS = 6; public static int CONTAINS = 6;
public static int INTERSECTS = 7; public static int INTERSECTS = 7;
@Deprecated @Deprecated
public static int FILTER = 8; public static int FILTER = 8;
} }

View File

@ -3,7 +3,7 @@
* *
* This file is part of Hibernate Spatial, an extension to the * This file is part of Hibernate Spatial, an extension to the
* hibernate ORM solution for geographic data. * hibernate ORM solution for geographic data.
* *
* Copyright © 2007 Geovise BVBA * Copyright © 2007 Geovise BVBA
* *
* This work was partially supported by the European Commission, * This work was partially supported by the European Commission,
@ -34,29 +34,28 @@
import java.net.URL; import java.net.URL;
import java.util.Properties; import java.util.Properties;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.dom4j.Document; import org.dom4j.Document;
import org.dom4j.DocumentException; import org.dom4j.DocumentException;
import org.dom4j.Element; import org.dom4j.Element;
import org.dom4j.io.SAXReader; import org.dom4j.io.SAXReader;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.hibernate.cfg.Configuration; import org.hibernate.cfg.Configuration;
/** /**
* Configuration information for the Hibernate Spatial Extension. * Configuration information for the Hibernate Spatial Extension.
* *
* @author Karel Maesen * @author Karel Maesen
*
*
*/ */
public class HSConfiguration extends Properties { public class HSConfiguration extends Properties {
/** /**
* *
*/ */
private static final long serialVersionUID = 1L; private static final long serialVersionUID = 1L;
private static Logger logger = LoggerFactory.getLogger(HSConfiguration.class); private static Logger logger = LoggerFactory.getLogger( HSConfiguration.class );
private String source = "runtime configuration object"; private String source = "runtime configuration object";
@ -67,85 +66,91 @@ public HSConfiguration() {
} }
public String getDefaultDialect() { public String getDefaultDialect() {
return getProperty(HSProperty.DEFAULT_DIALECT.toString()); return getProperty( HSProperty.DEFAULT_DIALECT.toString() );
} }
public void setDefaultDialect(String dialect) { public void setDefaultDialect(String dialect) {
setProperty(HSProperty.DEFAULT_DIALECT, dialect); setProperty( HSProperty.DEFAULT_DIALECT, dialect );
} }
public String getPrecisionModel() { public String getPrecisionModel() {
return getProperty(HSProperty.PRECISION_MODEL.toString()); return getProperty( HSProperty.PRECISION_MODEL.toString() );
} }
public void setPrecisionModel(String precisionModel) { public void setPrecisionModel(String precisionModel) {
setProperty(HSProperty.PRECISION_MODEL, precisionModel); setProperty( HSProperty.PRECISION_MODEL, precisionModel );
} }
public String getPrecisionModelScale() { public String getPrecisionModelScale() {
return getProperty(HSProperty.PRECISION_MODEL_SCALE.toString()); return getProperty( HSProperty.PRECISION_MODEL_SCALE.toString() );
} }
public void setPrecisionModelScale(String scale) { public void setPrecisionModelScale(String scale) {
setProperty(HSProperty.PRECISION_MODEL_SCALE, scale); setProperty( HSProperty.PRECISION_MODEL_SCALE, scale );
} }
protected String getProperty(HSProperty property) { protected String getProperty(HSProperty property) {
return getProperty(property.toString()); return getProperty( property.toString() );
} }
protected void setProperty(HSProperty property, String value) { protected void setProperty(HSProperty property, String value) {
setProperty(property.toString(), value); setProperty( property.toString(), value );
} }
/** /**
* Derives the configuration from the Hibernate Configuration object. * Derives the configuration from the Hibernate Configuration object.
* *
* @param hibernateConfig * @param hibernateConfig Hibernate Configuration object
* Hibernate Configuration object *
* @return true, if the configuration is successfull. * @return true, if the configuration is successfull.
*/ */
public boolean configure(Configuration hibernateConfig) { public boolean configure(Configuration hibernateConfig) {
String dialect = hibernateConfig.getProperty("hibernate.dialect"); String dialect = hibernateConfig.getProperty( "hibernate.dialect" );
setProperty(HSProperty.DEFAULT_DIALECT, dialect); setProperty( HSProperty.DEFAULT_DIALECT, dialect );
return true; return true;
} }
/** /**
* Gets the configuriation from the hibernate-spatail.cfg.xml file on the * Gets the configuriation from the hibernate-spatail.cfg.xml file on the
* classpath. * classpath.
* *
* @return true if the configuration is successfull; * @return true if the configuration is successfull;
*/ */
public boolean configure() { public boolean configure() {
return configure("hibernate-spatial.cfg.xml"); return configure( "hibernate-spatial.cfg.xml" );
} }
/** /**
* Gets the configuriation from the specified file. * Gets the configuriation from the specified file.
* *
* @param resource * @param resource the configuration file
* the configuration file *
* @return true if the configuration is successfull; * @return true if the configuration is successfull;
*/ */
public boolean configure(File resource) { public boolean configure(File resource) {
logger.info("Attempting to configuring from file: " logger.info(
+ resource.getName()); "Attempting to configuring from file: "
+ resource.getName()
);
try { try {
this.source = resource.getAbsolutePath(); this.source = resource.getAbsolutePath();
return doConfigure(new FileInputStream(resource)); return doConfigure( new FileInputStream( resource ) );
} catch (FileNotFoundException e) { }
logger.warn("could not find file: " + resource + "."); catch ( FileNotFoundException e ) {
} catch (DocumentException e) { logger.warn( "could not find file: " + resource + "." );
logger.warn("Failed to load configuration file: " + resource }
+ ".\nCause:" + e.getMessage()); catch ( DocumentException e ) {
logger.warn(
"Failed to load configuration file: " + resource
+ ".\nCause:" + e.getMessage()
);
} }
return false; return false;
} }
/** /**
* The source file or URL for this configuration. * The source file or URL for this configuration.
* *
* @return The source name (file or URL). * @return The source name (file or URL).
*/ */
public String getSource() { public String getSource() {
@ -154,27 +159,32 @@ public String getSource() {
/** /**
* Gets the configuriation from the specified file on the class path. * Gets the configuriation from the specified file on the class path.
* *
* @param resource * @param resource the configuration file
* the configuration file *
* @return true if the configuration is successfull; * @return true if the configuration is successfull;
*/ */
public boolean configure(String resource) { public boolean configure(String resource) {
logger.debug("Attempting to load configuration from file: " + resource); logger.debug( "Attempting to load configuration from file: " + resource );
ClassLoader classLoader = Thread.currentThread() ClassLoader classLoader = Thread.currentThread()
.getContextClassLoader(); .getContextClassLoader();
try { try {
URL url = classLoader.getResource(resource); URL url = classLoader.getResource( resource );
if (url == null) { if ( url == null ) {
logger.info("No configuration file " + resource logger.info(
+ " on the classpath."); "No configuration file " + resource
+ " on the classpath."
);
return false; return false;
} }
this.source = url.getFile(); this.source = url.getFile();
return doConfigure(url.openStream()); return doConfigure( url.openStream() );
} catch (Exception e) { }
logger.warn("Failed to load configuration file: " + resource catch ( Exception e ) {
+ ".\nCause:" + e.getMessage()); logger.warn(
"Failed to load configuration file: " + resource
+ ".\nCause:" + e.getMessage()
);
} }
return false; return false;
} }
@ -182,24 +192,26 @@ public boolean configure(String resource) {
private boolean doConfigure(InputStream stream) throws DocumentException { private boolean doConfigure(InputStream stream) throws DocumentException {
try { try {
SAXReader reader = new SAXReader(); SAXReader reader = new SAXReader();
Document configDoc = reader.read(stream); Document configDoc = reader.read( stream );
Element root = configDoc.getRootElement(); Element root = configDoc.getRootElement();
for (HSProperty hsprop : HSProperties) { for ( HSProperty hsprop : HSProperties ) {
Element propEl = root.element(hsprop.toString().toLowerCase()); Element propEl = root.element( hsprop.toString().toLowerCase() );
if (propEl != null) { if ( propEl != null ) {
setProperty(hsprop, propEl.getText()); setProperty( hsprop, propEl.getText() );
} }
} }
return true; return true;
} finally { }
finally {
try { try {
stream.close(); stream.close();
} catch (Exception e) { }
catch ( Exception e ) {
} // Can't do anything about this. } // Can't do anything about this.
} }
} }
public String toString(){ public String toString() {
return this.source; return this.source;
} }

View File

@ -3,7 +3,7 @@
* *
* This file is part of Hibernate Spatial, an extension to the * This file is part of Hibernate Spatial, an extension to the
* hibernate ORM solution for geographic data. * hibernate ORM solution for geographic data.
* *
* Copyright © 2007 Geovise BVBA * Copyright © 2007 Geovise BVBA
* *
* This work was partially supported by the European Commission, * This work was partially supported by the European Commission,
@ -30,9 +30,8 @@
/** /**
* This enum contains the configurable properties of the Hibernate Spatial * This enum contains the configurable properties of the Hibernate Spatial
* Extension. * Extension.
* *
* @author Karel Maesen * @author Karel Maesen
*
*/ */
public enum HSProperty { public enum HSProperty {

View File

@ -28,6 +28,7 @@
package org.hibernate.spatial.criterion; package org.hibernate.spatial.criterion;
import com.vividsolutions.jts.geom.Geometry; import com.vividsolutions.jts.geom.Geometry;
import org.hibernate.Criteria; import org.hibernate.Criteria;
import org.hibernate.EntityMode; import org.hibernate.EntityMode;
import org.hibernate.HibernateException; import org.hibernate.HibernateException;
@ -45,28 +46,28 @@
public class DWithinExpression implements Criterion { public class DWithinExpression implements Criterion {
private final String propertyName; private final String propertyName;
private final Geometry geometry; private final Geometry geometry;
private final double distance; private final double distance;
public DWithinExpression(String propertyName, Geometry geometry, double distance) { public DWithinExpression(String propertyName, Geometry geometry, double distance) {
this.propertyName = propertyName; this.propertyName = propertyName;
this.geometry = geometry; this.geometry = geometry;
this.distance = distance; this.distance = distance;
} }
public String toSqlString(Criteria criteria, CriteriaQuery criteriaQuery) throws HibernateException { public String toSqlString(Criteria criteria, CriteriaQuery criteriaQuery) throws HibernateException {
String column = ExpressionUtil.findColumn(propertyName, criteria, criteriaQuery); String column = ExpressionUtil.findColumn( propertyName, criteria, criteriaQuery );
SpatialDialect spatialDialect = ExpressionUtil.getSpatialDialect(criteriaQuery, SpatialFunction.dwithin); SpatialDialect spatialDialect = ExpressionUtil.getSpatialDialect( criteriaQuery, SpatialFunction.dwithin );
return spatialDialect.getDWithinSQL(column); return spatialDialect.getDWithinSQL( column );
} }
public TypedValue[] getTypedValues(Criteria criteria, CriteriaQuery criteriaQuery) throws HibernateException { public TypedValue[] getTypedValues(Criteria criteria, CriteriaQuery criteriaQuery) throws HibernateException {
return new TypedValue[]{ return new TypedValue[] {
criteriaQuery.getTypedValue(criteria, propertyName, geometry), criteriaQuery.getTypedValue( criteria, propertyName, geometry ),
new TypedValue(StandardBasicTypes.DOUBLE, Double.valueOf(distance), EntityMode.POJO) new TypedValue( StandardBasicTypes.DOUBLE, Double.valueOf( distance ), EntityMode.POJO )
}; };
} }
} }

View File

@ -42,22 +42,23 @@
*/ */
public class ExpressionUtil { public class ExpressionUtil {
public static SpatialDialect getSpatialDialect(CriteriaQuery criteriaQuery, SpatialFunction function) { public static SpatialDialect getSpatialDialect(CriteriaQuery criteriaQuery, SpatialFunction function) {
Dialect dialect = criteriaQuery.getFactory().getDialect(); Dialect dialect = criteriaQuery.getFactory().getDialect();
if (!(dialect instanceof SpatialDialect)) { if ( !( dialect instanceof SpatialDialect ) ) {
throw new HibernateException("A spatial expression requires a spatial dialect."); throw new HibernateException( "A spatial expression requires a spatial dialect." );
} }
SpatialDialect spatialDialect = (SpatialDialect) dialect; SpatialDialect spatialDialect = (SpatialDialect) dialect;
if (!spatialDialect.supports(function)) { if ( !spatialDialect.supports( function ) ) {
throw new HibernateException(function + " function not supported by this dialect"); throw new HibernateException( function + " function not supported by this dialect" );
} }
return spatialDialect; return spatialDialect;
} }
public static String findColumn(String propertyName, Criteria criteria, CriteriaQuery criteriaQuery) { public static String findColumn(String propertyName, Criteria criteria, CriteriaQuery criteriaQuery) {
String[] columns = criteriaQuery.findColumns(propertyName, criteria); String[] columns = criteriaQuery.findColumns( propertyName, criteria );
if (columns.length != 1) if ( columns.length != 1 ) {
throw new HibernateException("Spatial Expression may only be used with single-column properties"); throw new HibernateException( "Spatial Expression may only be used with single-column properties" );
return columns[0]; }
} return columns[0];
}
} }

View File

@ -33,9 +33,9 @@
import org.hibernate.criterion.CriteriaQuery; import org.hibernate.criterion.CriteriaQuery;
import org.hibernate.criterion.Criterion; import org.hibernate.criterion.Criterion;
import org.hibernate.engine.spi.TypedValue; import org.hibernate.engine.spi.TypedValue;
import org.hibernate.type.StandardBasicTypes;
import org.hibernate.spatial.SpatialDialect; import org.hibernate.spatial.SpatialDialect;
import org.hibernate.spatial.SpatialFunction; import org.hibernate.spatial.SpatialFunction;
import org.hibernate.type.StandardBasicTypes;
/** /**
* @author Karel Maesen, Geovise BVBA * @author Karel Maesen, Geovise BVBA
@ -43,24 +43,24 @@
*/ */
public class HavingSridExpression implements Criterion { public class HavingSridExpression implements Criterion {
private final String propertyName; private final String propertyName;
private final int srid; private final int srid;
public HavingSridExpression(String propertyName, int srid) { public HavingSridExpression(String propertyName, int srid) {
this.propertyName = propertyName; this.propertyName = propertyName;
this.srid = srid; this.srid = srid;
} }
public String toSqlString(Criteria criteria, CriteriaQuery criteriaQuery) throws HibernateException { public String toSqlString(Criteria criteria, CriteriaQuery criteriaQuery) throws HibernateException {
String column = ExpressionUtil.findColumn(propertyName, criteria, criteriaQuery); String column = ExpressionUtil.findColumn( propertyName, criteria, criteriaQuery );
SpatialDialect spatialDialect = ExpressionUtil.getSpatialDialect(criteriaQuery, SpatialFunction.srid); SpatialDialect spatialDialect = ExpressionUtil.getSpatialDialect( criteriaQuery, SpatialFunction.srid );
return spatialDialect.getHavingSridSQL(column); return spatialDialect.getHavingSridSQL( column );
} }
public TypedValue[] getTypedValues(Criteria criteria, CriteriaQuery criteriaQuery) throws HibernateException { public TypedValue[] getTypedValues(Criteria criteria, CriteriaQuery criteriaQuery) throws HibernateException {
return new TypedValue[]{ return new TypedValue[] {
new TypedValue(StandardBasicTypes.INTEGER, Integer.valueOf(srid), EntityMode.POJO) new TypedValue( StandardBasicTypes.INTEGER, Integer.valueOf( srid ), EntityMode.POJO )
}; };
} }
} }

View File

@ -1,4 +1,3 @@
/* /*
* This file is part of Hibernate Spatial, an extension to the * This file is part of Hibernate Spatial, an extension to the
* hibernate ORM solution for geographic data. * hibernate ORM solution for geographic data.
@ -42,24 +41,24 @@
*/ */
public class IsEmptyExpression implements Criterion { public class IsEmptyExpression implements Criterion {
private final static TypedValue[] NO_VALUES = new TypedValue[0]; private final static TypedValue[] NO_VALUES = new TypedValue[0];
private final String propertyName; private final String propertyName;
private final boolean isEmpty; private final boolean isEmpty;
public IsEmptyExpression(String propertyName, boolean isEmpty) { public IsEmptyExpression(String propertyName, boolean isEmpty) {
this.propertyName = propertyName; this.propertyName = propertyName;
this.isEmpty = isEmpty; this.isEmpty = isEmpty;
} }
public String toSqlString(Criteria criteria, CriteriaQuery criteriaQuery) throws HibernateException { public String toSqlString(Criteria criteria, CriteriaQuery criteriaQuery) throws HibernateException {
String column = ExpressionUtil.findColumn(propertyName, criteria, criteriaQuery); String column = ExpressionUtil.findColumn( propertyName, criteria, criteriaQuery );
SpatialDialect spatialDialect = ExpressionUtil.getSpatialDialect(criteriaQuery, SpatialFunction.isempty); SpatialDialect spatialDialect = ExpressionUtil.getSpatialDialect( criteriaQuery, SpatialFunction.isempty );
return spatialDialect.getIsEmptySQL(column, isEmpty); return spatialDialect.getIsEmptySQL( column, isEmpty );
} }
public TypedValue[] getTypedValues(Criteria criteria, CriteriaQuery criteriaQuery) throws HibernateException { public TypedValue[] getTypedValues(Criteria criteria, CriteriaQuery criteriaQuery) throws HibernateException {
return NO_VALUES; return NO_VALUES;
} }
} }

View File

@ -3,7 +3,7 @@
* *
* This file is part of Hibernate Spatial, an extension to the * This file is part of Hibernate Spatial, an extension to the
* hibernate ORM solution for geographic data. * hibernate ORM solution for geographic data.
* *
* Copyright © 2007 Geovise BVBA * Copyright © 2007 Geovise BVBA
* Copyright © 2007 K.U. Leuven LRD, Spatial Applications Division, Belgium * Copyright © 2007 K.U. Leuven LRD, Spatial Applications Division, Belgium
* *
@ -30,6 +30,7 @@
import com.vividsolutions.jts.geom.Envelope; import com.vividsolutions.jts.geom.Envelope;
import com.vividsolutions.jts.geom.Geometry; import com.vividsolutions.jts.geom.Geometry;
import org.hibernate.Criteria; import org.hibernate.Criteria;
import org.hibernate.HibernateException; import org.hibernate.HibernateException;
import org.hibernate.criterion.CriteriaQuery; import org.hibernate.criterion.CriteriaQuery;
@ -44,7 +45,7 @@
* An implementation for a simple spatial filter. This <code>Criterion</code> * An implementation for a simple spatial filter. This <code>Criterion</code>
* restricts the resultset to those features whose bounding box overlaps the * restricts the resultset to those features whose bounding box overlaps the
* filter geometry. It is intended for quick, but inexact spatial queries. * filter geometry. It is intended for quick, but inexact spatial queries.
* *
* @author Karel Maesen * @author Karel Maesen
*/ */
public class SpatialFilter implements Criterion { public class SpatialFilter implements Criterion {
@ -62,28 +63,37 @@ public SpatialFilter(String propertyName, Geometry filter) {
public SpatialFilter(String propertyName, Envelope envelope, int SRID) { public SpatialFilter(String propertyName, Envelope envelope, int SRID) {
this.propertyName = propertyName; this.propertyName = propertyName;
this.filter = EnvelopeAdapter.toPolygon(envelope, SRID); this.filter = EnvelopeAdapter.toPolygon( envelope, SRID );
} }
public TypedValue[] getTypedValues(Criteria criteria, public TypedValue[] getTypedValues(Criteria criteria,
CriteriaQuery criteriaQuery) throws HibernateException { CriteriaQuery criteriaQuery) throws HibernateException {
return new TypedValue[] { criteriaQuery.getTypedValue(criteria, return new TypedValue[] {
propertyName, filter) }; criteriaQuery.getTypedValue(
criteria,
propertyName, filter
)
};
} }
public String toSqlString(Criteria criteria, CriteriaQuery criteriaQuery) public String toSqlString(Criteria criteria, CriteriaQuery criteriaQuery)
throws HibernateException { throws HibernateException {
SessionFactoryImplementor factory = criteriaQuery.getFactory(); SessionFactoryImplementor factory = criteriaQuery.getFactory();
String[] columns = criteriaQuery.getColumnsUsingProjection(criteria, String[] columns = criteriaQuery.getColumnsUsingProjection(
this.propertyName); criteria,
this.propertyName
);
Dialect dialect = factory.getDialect(); Dialect dialect = factory.getDialect();
if (dialect instanceof SpatialDialect) { if ( dialect instanceof SpatialDialect ) {
SpatialDialect seDialect = (SpatialDialect) dialect; SpatialDialect seDialect = (SpatialDialect) dialect;
return seDialect.getSpatialFilterExpression(columns[0]); return seDialect.getSpatialFilterExpression( columns[0] );
} else }
else {
throw new IllegalStateException( throw new IllegalStateException(
"Dialect must be spatially enabled dialect"); "Dialect must be spatially enabled dialect"
);
}
} }

View File

@ -3,7 +3,7 @@
* *
* This file is part of Hibernate Spatial, an extension to the * This file is part of Hibernate Spatial, an extension to the
* hibernate ORM solution for geographic data. * hibernate ORM solution for geographic data.
* *
* Copyright © 2007 Geovise BVBA * Copyright © 2007 Geovise BVBA
* *
* This work was partially supported by the European Commission, * This work was partially supported by the European Commission,
@ -40,7 +40,6 @@
/** /**
* @author Karel Maesen * @author Karel Maesen
*
*/ */
public class SpatialProjections { public class SpatialProjections {
@ -48,25 +47,34 @@ public static Projection extent(final String propertyName) {
return new SimpleProjection() { return new SimpleProjection() {
public Type[] getTypes(Criteria criteria, public Type[] getTypes(Criteria criteria,
CriteriaQuery criteriaQuery) throws HibernateException { CriteriaQuery criteriaQuery) throws HibernateException {
return new Type[] { criteriaQuery.getType(criteria, return new Type[] {
propertyName) }; criteriaQuery.getType(
criteria,
propertyName
)
};
} }
public String toSqlString(Criteria criteria, int position, public String toSqlString(Criteria criteria, int position,
CriteriaQuery criteriaQuery) throws HibernateException { CriteriaQuery criteriaQuery) throws HibernateException {
StringBuilder stbuf = new StringBuilder(); StringBuilder stbuf = new StringBuilder();
SessionFactoryImplementor factory = criteriaQuery.getFactory(); SessionFactoryImplementor factory = criteriaQuery.getFactory();
String[] columns = criteriaQuery.getColumnsUsingProjection( String[] columns = criteriaQuery.getColumnsUsingProjection(
criteria, propertyName); criteria, propertyName
);
Dialect dialect = factory.getDialect(); Dialect dialect = factory.getDialect();
if (dialect instanceof SpatialDialect) { if ( dialect instanceof SpatialDialect ) {
SpatialDialect seDialect = (SpatialDialect) dialect; SpatialDialect seDialect = (SpatialDialect) dialect;
stbuf.append(seDialect.getSpatialAggregateSQL(columns[0], stbuf.append(
SpatialAggregate.EXTENT)); seDialect.getSpatialAggregateSQL(
stbuf.append(" as y").append(position).append('_'); columns[0],
SpatialAggregate.EXTENT
)
);
stbuf.append( " as y" ).append( position ).append( '_' );
return stbuf.toString(); return stbuf.toString();
} }
return null; return null;

View File

@ -29,6 +29,7 @@
package org.hibernate.spatial.criterion; package org.hibernate.spatial.criterion;
import com.vividsolutions.jts.geom.Geometry; import com.vividsolutions.jts.geom.Geometry;
import org.hibernate.Criteria; import org.hibernate.Criteria;
import org.hibernate.HibernateException; import org.hibernate.HibernateException;
import org.hibernate.criterion.CriteriaQuery; import org.hibernate.criterion.CriteriaQuery;
@ -47,65 +48,75 @@
*/ */
public class SpatialRelateExpression implements Criterion { public class SpatialRelateExpression implements Criterion {
/** /**
* The geometry property * The geometry property
*/ */
private String propertyName = null; private String propertyName = null;
/** /**
* The test geometry * The test geometry
*/ */
private Geometry value = null; private Geometry value = null;
/** /**
* The spatial relation that is queried for. * The spatial relation that is queried for.
*/ */
private int spatialRelation = -1; private int spatialRelation = -1;
private static final long serialVersionUID = 1L; private static final long serialVersionUID = 1L;
public SpatialRelateExpression(String propertyName, public SpatialRelateExpression(String propertyName,
Geometry value, int spatialRelation) { Geometry value, int spatialRelation) {
this.propertyName = propertyName; this.propertyName = propertyName;
this.spatialRelation = spatialRelation; this.spatialRelation = spatialRelation;
this.value = value; this.value = value;
} }
/* /*
* (non-Javadoc) * (non-Javadoc)
* *
* @see org.hibernate.criterion.Criterion#getTypedValues(org.hibernate.Criteria, * @see org.hibernate.criterion.Criterion#getTypedValues(org.hibernate.Criteria,
* org.hibernate.criterion.CriteriaQuery) * org.hibernate.criterion.CriteriaQuery)
*/ */
public TypedValue[] getTypedValues(Criteria criteria, public TypedValue[] getTypedValues(Criteria criteria,
CriteriaQuery criteriaQuery) throws HibernateException { CriteriaQuery criteriaQuery) throws HibernateException {
return new TypedValue[]{criteriaQuery.getTypedValue(criteria, return new TypedValue[] {
propertyName, value)}; criteriaQuery.getTypedValue(
criteria,
propertyName, value
)
};
} }
/* /*
* (non-Javadoc) * (non-Javadoc)
* *
* @see org.hibernate.criterion.Criterion#toSqlString(org.hibernate.Criteria, * @see org.hibernate.criterion.Criterion#toSqlString(org.hibernate.Criteria,
* org.hibernate.criterion.CriteriaQuery) * org.hibernate.criterion.CriteriaQuery)
*/ */
public String toSqlString(Criteria criteria, CriteriaQuery criteriaQuery) public String toSqlString(Criteria criteria, CriteriaQuery criteriaQuery)
throws HibernateException { throws HibernateException {
SessionFactoryImplementor factory = criteriaQuery.getFactory(); SessionFactoryImplementor factory = criteriaQuery.getFactory();
String[] columns = criteriaQuery.getColumnsUsingProjection(criteria, String[] columns = criteriaQuery.getColumnsUsingProjection(
this.propertyName); criteria,
Dialect dialect = factory.getDialect(); this.propertyName
if (dialect instanceof SpatialDialect) { );
SpatialDialect seDialect = (SpatialDialect) dialect; Dialect dialect = factory.getDialect();
return seDialect.getSpatialRelateSQL(columns[0], if ( dialect instanceof SpatialDialect ) {
spatialRelation); SpatialDialect seDialect = (SpatialDialect) dialect;
} else { return seDialect.getSpatialRelateSQL(
throw new IllegalStateException( columns[0],
"Dialect must be spatially enabled dialect"); spatialRelation
} );
} }
else {
throw new IllegalStateException(
"Dialect must be spatially enabled dialect"
);
}
}
} }

View File

@ -30,6 +30,7 @@
import com.vividsolutions.jts.geom.Envelope; import com.vividsolutions.jts.geom.Envelope;
import com.vividsolutions.jts.geom.Geometry; import com.vividsolutions.jts.geom.Geometry;
import org.hibernate.criterion.Criterion; import org.hibernate.criterion.Criterion;
import org.hibernate.spatial.SpatialRelation; import org.hibernate.spatial.SpatialRelation;
@ -50,100 +51,117 @@
*/ */
public class SpatialRestrictions { public class SpatialRestrictions {
SpatialRestrictions() { SpatialRestrictions() {
} }
public static SpatialRelateExpression eq(String propertyName, Geometry value) { public static SpatialRelateExpression eq(String propertyName, Geometry value) {
return new SpatialRelateExpression(propertyName, value, return new SpatialRelateExpression(
SpatialRelation.EQUALS); propertyName, value,
} SpatialRelation.EQUALS
);
}
public static SpatialRelateExpression within(String propertyName, Geometry value) { public static SpatialRelateExpression within(String propertyName, Geometry value) {
return new SpatialRelateExpression(propertyName, value, return new SpatialRelateExpression(
SpatialRelation.WITHIN); propertyName, value,
} SpatialRelation.WITHIN
);
}
public static SpatialRelateExpression contains(String propertyName, Geometry value) { public static SpatialRelateExpression contains(String propertyName, Geometry value) {
return new SpatialRelateExpression(propertyName, value, return new SpatialRelateExpression(
SpatialRelation.CONTAINS); propertyName, value,
} SpatialRelation.CONTAINS
);
}
public static SpatialRelateExpression crosses(String propertyName, Geometry value) { public static SpatialRelateExpression crosses(String propertyName, Geometry value) {
return new SpatialRelateExpression(propertyName, value, return new SpatialRelateExpression(
SpatialRelation.CROSSES); propertyName, value,
} SpatialRelation.CROSSES
);
}
public static SpatialRelateExpression disjoint(String propertyName, Geometry value) { public static SpatialRelateExpression disjoint(String propertyName, Geometry value) {
return new SpatialRelateExpression(propertyName, value, return new SpatialRelateExpression(
SpatialRelation.DISJOINT); propertyName, value,
} SpatialRelation.DISJOINT
);
}
public static SpatialRelateExpression intersects(String propertyName, Geometry value) { public static SpatialRelateExpression intersects(String propertyName, Geometry value) {
return new SpatialRelateExpression(propertyName, value, return new SpatialRelateExpression(
SpatialRelation.INTERSECTS); propertyName, value,
} SpatialRelation.INTERSECTS
);
}
public static SpatialRelateExpression overlaps(String propertyName, Geometry value) { public static SpatialRelateExpression overlaps(String propertyName, Geometry value) {
return new SpatialRelateExpression(propertyName, value, return new SpatialRelateExpression(
SpatialRelation.OVERLAPS); propertyName, value,
} SpatialRelation.OVERLAPS
);
}
public static SpatialRelateExpression touches(String propertyName, Geometry value) { public static SpatialRelateExpression touches(String propertyName, Geometry value) {
return new SpatialRelateExpression(propertyName, value, return new SpatialRelateExpression(
SpatialRelation.TOUCHES); propertyName, value,
} SpatialRelation.TOUCHES
);
}
public static SpatialFilter filter(String propertyName, Geometry filter) { public static SpatialFilter filter(String propertyName, Geometry filter) {
return new SpatialFilter(propertyName, filter); return new SpatialFilter( propertyName, filter );
} }
public static SpatialFilter filter(String propertyName, Envelope envelope, public static SpatialFilter filter(String propertyName, Envelope envelope,
int SRID) { int SRID) {
return new SpatialFilter(propertyName, envelope, SRID); return new SpatialFilter( propertyName, envelope, SRID );
} }
public static Criterion distanceWithin(String propertyName, Geometry geometry, double distance) { public static Criterion distanceWithin(String propertyName, Geometry geometry, double distance) {
return new DWithinExpression(propertyName, geometry, distance); return new DWithinExpression( propertyName, geometry, distance );
} }
public static Criterion havingSRID(String propertyName, int srid) { public static Criterion havingSRID(String propertyName, int srid) {
return new HavingSridExpression(propertyName, srid); return new HavingSridExpression( propertyName, srid );
} }
public static Criterion isEmpty(String propertyName) { public static Criterion isEmpty(String propertyName) {
return new IsEmptyExpression(propertyName, true); return new IsEmptyExpression( propertyName, true );
} }
public static Criterion isNotEmpty(String propertyName) { public static Criterion isNotEmpty(String propertyName) {
return new IsEmptyExpression(propertyName, false); return new IsEmptyExpression( propertyName, false );
} }
public static Criterion spatialRestriction(int relation, public static Criterion spatialRestriction(int relation,
String propertyName, Geometry value) { String propertyName, Geometry value) {
switch (relation) { switch ( relation ) {
case SpatialRelation.CONTAINS: case SpatialRelation.CONTAINS:
return contains(propertyName, value); return contains( propertyName, value );
case SpatialRelation.CROSSES: case SpatialRelation.CROSSES:
return crosses(propertyName, value); return crosses( propertyName, value );
case SpatialRelation.DISJOINT: case SpatialRelation.DISJOINT:
return disjoint(propertyName, value); return disjoint( propertyName, value );
case SpatialRelation.INTERSECTS: case SpatialRelation.INTERSECTS:
return intersects(propertyName, value); return intersects( propertyName, value );
case SpatialRelation.EQUALS: case SpatialRelation.EQUALS:
return eq(propertyName, value); return eq( propertyName, value );
case SpatialRelation.FILTER: case SpatialRelation.FILTER:
return filter(propertyName, value); return filter( propertyName, value );
case SpatialRelation.OVERLAPS: case SpatialRelation.OVERLAPS:
return overlaps(propertyName, value); return overlaps( propertyName, value );
case SpatialRelation.TOUCHES: case SpatialRelation.TOUCHES:
return touches(propertyName, value); return touches( propertyName, value );
case SpatialRelation.WITHIN: case SpatialRelation.WITHIN:
return within(propertyName, value); return within( propertyName, value );
default: default:
throw new IllegalArgumentException( throw new IllegalArgumentException(
"Non-existant spatial relation passed."); "Non-existant spatial relation passed."
} );
} }
}
} }

View File

@ -1,12 +1,12 @@
package org.hibernate.spatial.dialect.postgis; package org.hibernate.spatial.dialect.postgis;
import java.sql.Types;
import org.hibernate.type.descriptor.ValueBinder; import org.hibernate.type.descriptor.ValueBinder;
import org.hibernate.type.descriptor.ValueExtractor; import org.hibernate.type.descriptor.ValueExtractor;
import org.hibernate.type.descriptor.java.JavaTypeDescriptor; import org.hibernate.type.descriptor.java.JavaTypeDescriptor;
import org.hibernate.type.descriptor.sql.SqlTypeDescriptor; import org.hibernate.type.descriptor.sql.SqlTypeDescriptor;
import java.sql.Types;
/** /**
* @author Karel Maesen, Geovise BVBA * @author Karel Maesen, Geovise BVBA
* creation-date: 7/27/11 * creation-date: 7/27/11
@ -14,25 +14,25 @@
public class PGGeometryTypeDescriptor implements SqlTypeDescriptor { public class PGGeometryTypeDescriptor implements SqlTypeDescriptor {
public static final SqlTypeDescriptor INSTANCE = new PGGeometryTypeDescriptor(); public static final SqlTypeDescriptor INSTANCE = new PGGeometryTypeDescriptor();
@Override @Override
public int getSqlType() { public int getSqlType() {
return Types.STRUCT; return Types.STRUCT;
} }
@Override @Override
public boolean canBeRemapped() { public boolean canBeRemapped() {
return false; return false;
} }
@Override @Override
public <X> ValueBinder<X> getBinder(final JavaTypeDescriptor<X> javaTypeDescriptor) { public <X> ValueBinder<X> getBinder(final JavaTypeDescriptor<X> javaTypeDescriptor) {
return new PGGeometryValueBinder(); return (ValueBinder<X>) new PGGeometryValueBinder();
} }
@Override @Override
public <X> ValueExtractor<X> getExtractor(final JavaTypeDescriptor<X> javaTypeDescriptor) { public <X> ValueExtractor<X> getExtractor(final JavaTypeDescriptor<X> javaTypeDescriptor) {
return new PGGeometryValueExtractor(); return (ValueExtractor<X>) new PGGeometryValueExtractor();
} }
} }

View File

@ -1,239 +1,289 @@
package org.hibernate.spatial.dialect.postgis; package org.hibernate.spatial.dialect.postgis;
import com.vividsolutions.jts.geom.Coordinate;
import com.vividsolutions.jts.geom.Geometry;
import com.vividsolutions.jts.geom.GeometryFactory;
import org.hibernate.spatial.HBSpatialExtension;
import org.hibernate.spatial.mgeom.MCoordinate;
import org.hibernate.spatial.mgeom.MGeometry;
import org.hibernate.spatial.mgeom.MGeometryFactory;
import org.hibernate.type.descriptor.ValueBinder;
import org.hibernate.type.descriptor.WrapperOptions;
import org.postgis.*;
import java.sql.Connection; import java.sql.Connection;
import java.sql.PreparedStatement; import java.sql.PreparedStatement;
import java.sql.SQLException; import java.sql.SQLException;
import java.sql.Types; import java.sql.Types;
import com.vividsolutions.jts.geom.Coordinate;
import com.vividsolutions.jts.geom.Geometry;
import com.vividsolutions.jts.geom.GeometryFactory;
import org.postgis.GeometryCollection;
import org.postgis.LineString;
import org.postgis.LinearRing;
import org.postgis.MultiLineString;
import org.postgis.MultiPoint;
import org.postgis.MultiPolygon;
import org.postgis.PGgeometry;
import org.postgis.Point;
import org.postgis.Polygon;
import org.hibernate.spatial.HBSpatialExtension;
import org.hibernate.spatial.mgeom.MCoordinate;
import org.hibernate.spatial.mgeom.MGeometry;
import org.hibernate.spatial.mgeom.MGeometryFactory;
import org.hibernate.type.descriptor.ValueBinder;
import org.hibernate.type.descriptor.WrapperOptions;
/** /**
* @author Karel Maesen, Geovise BVBA * @author Karel Maesen, Geovise BVBA
* creation-date: 7/27/11 * creation-date: 7/27/11
*/ */
public class PGGeometryValueBinder implements ValueBinder { public class PGGeometryValueBinder implements ValueBinder<Geometry> {
@Override @Override
public void bind(PreparedStatement st, Object value, int index, WrapperOptions options) throws SQLException { public void bind(PreparedStatement st, Geometry value, int index, WrapperOptions options) throws SQLException {
if (value == null) { if ( value == null ) {
st.setNull(index, Types.STRUCT); st.setNull( index, Types.STRUCT );
} else {
Geometry jtsGeom = (Geometry) value;
Object dbGeom = toJTS(jtsGeom, st.getConnection());
st.setObject(index, dbGeom);
} }
} else {
Geometry jtsGeom = (Geometry) value;
Object dbGeom = toNative( jtsGeom, st.getConnection() );
st.setObject( index, dbGeom );
}
}
public MGeometryFactory getGeometryFactory(){ public MGeometryFactory getGeometryFactory() {
return HBSpatialExtension.getDefaultGeomFactory(); return HBSpatialExtension.getDefaultGeomFactory();
} }
/**
* Converts a JTS <code>Geometry</code> to a native geometry object.
*
* @param jtsGeom JTS Geometry to convert
* @param connection the current database connection
*
* @return native database geometry object corresponding to jtsGeom.
*/
private Object toNative(Geometry jtsGeom, Connection connection) {
org.postgis.Geometry geom = null;
jtsGeom = forceEmptyToGeometryCollection( jtsGeom );
if ( jtsGeom instanceof com.vividsolutions.jts.geom.Point ) {
geom = convertJTSPoint( (com.vividsolutions.jts.geom.Point) jtsGeom );
}
else if ( jtsGeom instanceof com.vividsolutions.jts.geom.LineString ) {
geom = convertJTSLineString( (com.vividsolutions.jts.geom.LineString) jtsGeom );
}
else if ( jtsGeom instanceof com.vividsolutions.jts.geom.MultiLineString ) {
geom = convertJTSMultiLineString( (com.vividsolutions.jts.geom.MultiLineString) jtsGeom );
}
else if ( jtsGeom instanceof com.vividsolutions.jts.geom.Polygon ) {
geom = convertJTSPolygon( (com.vividsolutions.jts.geom.Polygon) jtsGeom );
}
else if ( jtsGeom instanceof com.vividsolutions.jts.geom.MultiPoint ) {
geom = convertJTSMultiPoint( (com.vividsolutions.jts.geom.MultiPoint) jtsGeom );
}
else if ( jtsGeom instanceof com.vividsolutions.jts.geom.MultiPolygon ) {
geom = convertJTSMultiPolygon( (com.vividsolutions.jts.geom.MultiPolygon) jtsGeom );
}
else if ( jtsGeom instanceof com.vividsolutions.jts.geom.GeometryCollection ) {
geom = convertJTSGeometryCollection( (com.vividsolutions.jts.geom.GeometryCollection) jtsGeom );
}
/** if ( geom != null ) {
* Converts a JTS <code>Geometry</code> to a native geometry object. return new PGgeometry( geom );
* }
* @param jtsGeom JTS Geometry to convert else {
* @param connection the current database connection throw new UnsupportedOperationException(
* @return native database geometry object corresponding to jtsGeom. "Conversion of "
*/ + jtsGeom.getClass().getSimpleName()
public Object toJTS(Geometry jtsGeom, Connection connection) { + " to PGgeometry not supported"
org.postgis.Geometry geom = null; );
jtsGeom = forceEmptyToGeometryCollection(jtsGeom); }
if (jtsGeom instanceof com.vividsolutions.jts.geom.Point) { }
geom = convertJTSPoint((com.vividsolutions.jts.geom.Point) jtsGeom);
} else if (jtsGeom instanceof com.vividsolutions.jts.geom.LineString) {
geom = convertJTSLineString((com.vividsolutions.jts.geom.LineString) jtsGeom);
} else if (jtsGeom instanceof com.vividsolutions.jts.geom.MultiLineString) {
geom = convertJTSMultiLineString((com.vividsolutions.jts.geom.MultiLineString) jtsGeom);
} else if (jtsGeom instanceof com.vividsolutions.jts.geom.Polygon) {
geom = convertJTSPolygon((com.vividsolutions.jts.geom.Polygon) jtsGeom);
} else if (jtsGeom instanceof com.vividsolutions.jts.geom.MultiPoint) {
geom = convertJTSMultiPoint((com.vividsolutions.jts.geom.MultiPoint) jtsGeom);
} else if (jtsGeom instanceof com.vividsolutions.jts.geom.MultiPolygon) {
geom = convertJTSMultiPolygon((com.vividsolutions.jts.geom.MultiPolygon) jtsGeom);
} else if (jtsGeom instanceof com.vividsolutions.jts.geom.GeometryCollection) {
geom = convertJTSGeometryCollection((com.vividsolutions.jts.geom.GeometryCollection) jtsGeom);
}
if (geom != null) //Postgis treats every empty geometry as an empty geometrycollection
return new PGgeometry(geom);
else
throw new UnsupportedOperationException("Conversion of "
+ jtsGeom.getClass().getSimpleName()
+ " to PGgeometry not supported");
}
//Postgis treats every empty geometry as an empty geometrycollection private Geometry forceEmptyToGeometryCollection(Geometry jtsGeom) {
Geometry forced = jtsGeom;
if ( forced.isEmpty() ) {
GeometryFactory factory = jtsGeom.getFactory();
if ( factory == null ) {
factory = HBSpatialExtension.getDefaultGeomFactory();
}
forced = factory.createGeometryCollection( null );
forced.setSRID( jtsGeom.getSRID() );
}
return forced;
}
private Geometry forceEmptyToGeometryCollection(Geometry jtsGeom) { private MultiPolygon convertJTSMultiPolygon(
Geometry forced = jtsGeom; com.vividsolutions.jts.geom.MultiPolygon multiPolygon) {
if (forced.isEmpty()) { Polygon[] pgPolygons = new Polygon[multiPolygon.getNumGeometries()];
GeometryFactory factory = jtsGeom.getFactory(); for ( int i = 0; i < pgPolygons.length; i++ ) {
if (factory == null) { pgPolygons[i] = convertJTSPolygon(
factory = HBSpatialExtension.getDefaultGeomFactory(); (com.vividsolutions.jts.geom.Polygon) multiPolygon
} .getGeometryN( i )
forced = factory.createGeometryCollection(null); );
forced.setSRID(jtsGeom.getSRID()); }
} MultiPolygon mpg = new MultiPolygon( pgPolygons );
return forced; mpg.setSrid( multiPolygon.getSRID() );
} return mpg;
}
private MultiPolygon convertJTSMultiPolygon( private MultiPoint convertJTSMultiPoint(
com.vividsolutions.jts.geom.MultiPolygon multiPolygon) { com.vividsolutions.jts.geom.MultiPoint multiPoint) {
Polygon[] pgPolygons = new Polygon[multiPolygon.getNumGeometries()]; Point[] pgPoints = new Point[multiPoint.getNumGeometries()];
for (int i = 0; i < pgPolygons.length; i++) { for ( int i = 0; i < pgPoints.length; i++ ) {
pgPolygons[i] = convertJTSPolygon((com.vividsolutions.jts.geom.Polygon) multiPolygon pgPoints[i] = convertJTSPoint(
.getGeometryN(i)); (com.vividsolutions.jts.geom.Point) multiPoint
} .getGeometryN( i )
MultiPolygon mpg = new MultiPolygon(pgPolygons); );
mpg.setSrid(multiPolygon.getSRID()); }
return mpg; MultiPoint mp = new MultiPoint( pgPoints );
} mp.setSrid( multiPoint.getSRID() );
return mp;
}
private MultiPoint convertJTSMultiPoint( private Polygon convertJTSPolygon(
com.vividsolutions.jts.geom.MultiPoint multiPoint) { com.vividsolutions.jts.geom.Polygon jtsPolygon) {
Point[] pgPoints = new Point[multiPoint.getNumGeometries()]; int numRings = jtsPolygon.getNumInteriorRing();
for (int i = 0; i < pgPoints.length; i++) { org.postgis.LinearRing[] rings = new org.postgis.LinearRing[numRings + 1];
pgPoints[i] = convertJTSPoint((com.vividsolutions.jts.geom.Point) multiPoint rings[0] = convertJTSLineStringToLinearRing(
.getGeometryN(i)); jtsPolygon
} .getExteriorRing()
MultiPoint mp = new MultiPoint(pgPoints); );
mp.setSrid(multiPoint.getSRID()); for ( int i = 0; i < numRings; i++ ) {
return mp; rings[i + 1] = convertJTSLineStringToLinearRing(
} jtsPolygon
.getInteriorRingN( i )
);
}
Polygon polygon = new org.postgis.Polygon( rings );
polygon.setSrid( jtsPolygon.getSRID() );
return polygon;
}
private Polygon convertJTSPolygon( private LinearRing convertJTSLineStringToLinearRing(
com.vividsolutions.jts.geom.Polygon jtsPolygon) { com.vividsolutions.jts.geom.LineString lineString) {
int numRings = jtsPolygon.getNumInteriorRing(); LinearRing lr = new org.postgis.LinearRing(
org.postgis.LinearRing[] rings = new org.postgis.LinearRing[numRings + 1]; toPoints(
rings[0] = convertJTSLineStringToLinearRing(jtsPolygon lineString
.getExteriorRing()); .getCoordinates()
for (int i = 0; i < numRings; i++) { )
rings[i + 1] = convertJTSLineStringToLinearRing(jtsPolygon );
.getInteriorRingN(i)); lr.setSrid( lineString.getSRID() );
} return lr;
Polygon polygon = new org.postgis.Polygon(rings); }
polygon.setSrid(jtsPolygon.getSRID());
return polygon;
}
private LinearRing convertJTSLineStringToLinearRing( private LineString convertJTSLineString(
com.vividsolutions.jts.geom.LineString lineString) { com.vividsolutions.jts.geom.LineString string) {
LinearRing lr = new org.postgis.LinearRing(toPoints(lineString LineString ls = new org.postgis.LineString(
.getCoordinates())); toPoints(
lr.setSrid(lineString.getSRID()); string
return lr; .getCoordinates()
} )
);
if ( string instanceof MGeometry ) {
ls.haveMeasure = true;
}
ls.setSrid( string.getSRID() );
return ls;
}
private LineString convertJTSLineString( private MultiLineString convertJTSMultiLineString(
com.vividsolutions.jts.geom.LineString string) { com.vividsolutions.jts.geom.MultiLineString string) {
LineString ls = new org.postgis.LineString(toPoints(string org.postgis.LineString[] lines = new org.postgis.LineString[string
.getCoordinates())); .getNumGeometries()];
if (string instanceof MGeometry) { for ( int i = 0; i < string.getNumGeometries(); i++ ) {
ls.haveMeasure = true; lines[i] = new org.postgis.LineString(
} toPoints(
ls.setSrid(string.getSRID()); string.getGeometryN(
return ls; i
} ).getCoordinates()
)
);
}
MultiLineString mls = new MultiLineString( lines );
if ( string instanceof MGeometry ) {
mls.haveMeasure = true;
}
mls.setSrid( string.getSRID() );
return mls;
}
private MultiLineString convertJTSMultiLineString( private Point convertJTSPoint(com.vividsolutions.jts.geom.Point point) {
com.vividsolutions.jts.geom.MultiLineString string) { org.postgis.Point pgPoint = new org.postgis.Point();
org.postgis.LineString[] lines = new org.postgis.LineString[string pgPoint.srid = point.getSRID();
.getNumGeometries()]; pgPoint.x = point.getX();
for (int i = 0; i < string.getNumGeometries(); i++) { pgPoint.y = point.getY();
lines[i] = new org.postgis.LineString(toPoints(string.getGeometryN( Coordinate coordinate = point.getCoordinate();
i).getCoordinates())); if ( Double.isNaN( coordinate.z ) ) {
} pgPoint.dimension = 2;
MultiLineString mls = new MultiLineString(lines); }
if (string instanceof MGeometry) { else {
mls.haveMeasure = true; pgPoint.z = coordinate.z;
} pgPoint.dimension = 3;
mls.setSrid(string.getSRID()); }
return mls; pgPoint.haveMeasure = false;
} if ( coordinate instanceof MCoordinate && !Double.isNaN( ( (MCoordinate) coordinate ).m ) ) {
pgPoint.m = ( (MCoordinate) coordinate ).m;
pgPoint.haveMeasure = true;
}
return pgPoint;
}
private Point convertJTSPoint(com.vividsolutions.jts.geom.Point point) { private GeometryCollection convertJTSGeometryCollection(
org.postgis.Point pgPoint = new org.postgis.Point(); com.vividsolutions.jts.geom.GeometryCollection collection) {
pgPoint.srid = point.getSRID(); com.vividsolutions.jts.geom.Geometry currentGeom;
pgPoint.x = point.getX(); org.postgis.Geometry[] pgCollections = new org.postgis.Geometry[collection
pgPoint.y = point.getY(); .getNumGeometries()];
Coordinate coordinate = point.getCoordinate(); for ( int i = 0; i < pgCollections.length; i++ ) {
if (Double.isNaN(coordinate.z)) { currentGeom = collection.getGeometryN( i );
pgPoint.dimension = 2; currentGeom = forceEmptyToGeometryCollection( currentGeom );
} else { if ( currentGeom.getClass() == com.vividsolutions.jts.geom.LineString.class ) {
pgPoint.z = coordinate.z; pgCollections[i] = convertJTSLineString( (com.vividsolutions.jts.geom.LineString) currentGeom );
pgPoint.dimension = 3; }
} else if ( currentGeom.getClass() == com.vividsolutions.jts.geom.LinearRing.class ) {
pgPoint.haveMeasure = false; pgCollections[i] = convertJTSLineStringToLinearRing( (com.vividsolutions.jts.geom.LinearRing) currentGeom );
if (coordinate instanceof MCoordinate && !Double.isNaN(((MCoordinate) coordinate).m)) { }
pgPoint.m = ((MCoordinate) coordinate).m; else if ( currentGeom.getClass() == com.vividsolutions.jts.geom.MultiLineString.class ) {
pgPoint.haveMeasure = true; pgCollections[i] = convertJTSMultiLineString( (com.vividsolutions.jts.geom.MultiLineString) currentGeom );
} }
return pgPoint; else if ( currentGeom.getClass() == com.vividsolutions.jts.geom.MultiPoint.class ) {
} pgCollections[i] = convertJTSMultiPoint( (com.vividsolutions.jts.geom.MultiPoint) currentGeom );
}
private GeometryCollection convertJTSGeometryCollection( else if ( currentGeom.getClass() == com.vividsolutions.jts.geom.MultiPolygon.class ) {
com.vividsolutions.jts.geom.GeometryCollection collection) { pgCollections[i] = convertJTSMultiPolygon( (com.vividsolutions.jts.geom.MultiPolygon) currentGeom );
com.vividsolutions.jts.geom.Geometry currentGeom; }
org.postgis.Geometry[] pgCollections = new org.postgis.Geometry[collection else if ( currentGeom.getClass() == com.vividsolutions.jts.geom.Point.class ) {
.getNumGeometries()]; pgCollections[i] = convertJTSPoint( (com.vividsolutions.jts.geom.Point) currentGeom );
for (int i = 0; i < pgCollections.length; i++) { }
currentGeom = collection.getGeometryN(i); else if ( currentGeom.getClass() == com.vividsolutions.jts.geom.Polygon.class ) {
currentGeom = forceEmptyToGeometryCollection(currentGeom); pgCollections[i] = convertJTSPolygon( (com.vividsolutions.jts.geom.Polygon) currentGeom );
if (currentGeom.getClass() == com.vividsolutions.jts.geom.LineString.class) { }
pgCollections[i] = convertJTSLineString((com.vividsolutions.jts.geom.LineString) currentGeom); else if ( currentGeom.getClass() == com.vividsolutions.jts.geom.GeometryCollection.class ) {
} else if (currentGeom.getClass() == com.vividsolutions.jts.geom.LinearRing.class) { pgCollections[i] = convertJTSGeometryCollection( (com.vividsolutions.jts.geom.GeometryCollection) currentGeom );
pgCollections[i] = convertJTSLineStringToLinearRing((com.vividsolutions.jts.geom.LinearRing) currentGeom); }
} else if (currentGeom.getClass() == com.vividsolutions.jts.geom.MultiLineString.class) { }
pgCollections[i] = convertJTSMultiLineString((com.vividsolutions.jts.geom.MultiLineString) currentGeom); GeometryCollection gc = new GeometryCollection( pgCollections );
} else if (currentGeom.getClass() == com.vividsolutions.jts.geom.MultiPoint.class) { gc.setSrid( collection.getSRID() );
pgCollections[i] = convertJTSMultiPoint((com.vividsolutions.jts.geom.MultiPoint) currentGeom); return gc;
} else if (currentGeom.getClass() == com.vividsolutions.jts.geom.MultiPolygon.class) { }
pgCollections[i] = convertJTSMultiPolygon((com.vividsolutions.jts.geom.MultiPolygon) currentGeom);
} else if (currentGeom.getClass() == com.vividsolutions.jts.geom.Point.class) {
pgCollections[i] = convertJTSPoint((com.vividsolutions.jts.geom.Point) currentGeom);
} else if (currentGeom.getClass() == com.vividsolutions.jts.geom.Polygon.class) {
pgCollections[i] = convertJTSPolygon((com.vividsolutions.jts.geom.Polygon) currentGeom);
} else if (currentGeom.getClass() == com.vividsolutions.jts.geom.GeometryCollection.class) {
pgCollections[i] = convertJTSGeometryCollection((com.vividsolutions.jts.geom.GeometryCollection) currentGeom);
}
}
GeometryCollection gc = new GeometryCollection(pgCollections);
gc.setSrid(collection.getSRID());
return gc;
}
private Point[] toPoints(Coordinate[] coordinates) { private Point[] toPoints(Coordinate[] coordinates) {
Point[] points = new Point[coordinates.length]; Point[] points = new Point[coordinates.length];
for (int i = 0; i < coordinates.length; i++) { for ( int i = 0; i < coordinates.length; i++ ) {
Coordinate c = coordinates[i]; Coordinate c = coordinates[i];
Point pt; Point pt;
if (Double.isNaN(c.z)) { if ( Double.isNaN( c.z ) ) {
pt = new Point(c.x, c.y); pt = new Point( c.x, c.y );
} else { }
pt = new Point(c.x, c.y, c.z); else {
} pt = new Point( c.x, c.y, c.z );
if (c instanceof MCoordinate) { }
MCoordinate mc = (MCoordinate) c; if ( c instanceof MCoordinate ) {
if (!Double.isNaN(mc.m)) { MCoordinate mc = (MCoordinate) c;
pt.setM(mc.m); if ( !Double.isNaN( mc.m ) ) {
} pt.setM( mc.m );
} }
points[i] = pt; }
} points[i] = pt;
return points; }
} return points;
}
} }

View File

@ -1,231 +1,274 @@
package org.hibernate.spatial.dialect.postgis; package org.hibernate.spatial.dialect.postgis;
import java.sql.ResultSet;
import java.sql.SQLException;
import com.vividsolutions.jts.geom.Coordinate; import com.vividsolutions.jts.geom.Coordinate;
import com.vividsolutions.jts.geom.Geometry; import com.vividsolutions.jts.geom.Geometry;
import org.postgis.GeometryCollection;
import org.postgis.MultiLineString;
import org.postgis.MultiPoint;
import org.postgis.MultiPolygon;
import org.postgis.PGboxbase;
import org.postgis.PGgeometry;
import org.postgis.Point;
import org.postgis.Polygon;
import org.hibernate.spatial.HBSpatialExtension; import org.hibernate.spatial.HBSpatialExtension;
import org.hibernate.spatial.mgeom.MCoordinate; import org.hibernate.spatial.mgeom.MCoordinate;
import org.hibernate.spatial.mgeom.MGeometryFactory; import org.hibernate.spatial.mgeom.MGeometryFactory;
import org.hibernate.spatial.mgeom.MLineString; import org.hibernate.spatial.mgeom.MLineString;
import org.hibernate.type.descriptor.ValueExtractor; import org.hibernate.type.descriptor.ValueExtractor;
import org.hibernate.type.descriptor.WrapperOptions; import org.hibernate.type.descriptor.WrapperOptions;
import org.postgis.*;
import java.sql.ResultSet;
import java.sql.SQLException;
/** /**
* @author Karel Maesen, Geovise BVBA * @author Karel Maesen, Geovise BVBA
* creation-date: 7/27/11 * creation-date: 7/27/11
*/ */
public class PGGeometryValueExtractor implements ValueExtractor { public class PGGeometryValueExtractor implements ValueExtractor<Geometry> {
@Override
public Object extract(ResultSet rs, String name, WrapperOptions options) throws SQLException {
Object geomObj = rs.getObject(name);
return toJTS(geomObj);
}
public MGeometryFactory getGeometryFactory() { @Override
return HBSpatialExtension.getDefaultGeomFactory(); public Geometry extract(ResultSet rs, String name, WrapperOptions options) throws SQLException {
} Object geomObj = rs.getObject( name );
return toJTS( geomObj );
}
public Geometry toJTS(Object object) { public MGeometryFactory getGeometryFactory() {
if (object == null) return HBSpatialExtension.getDefaultGeomFactory();
return null; }
// in some cases, Postgis returns not PGgeometry objects public Geometry toJTS(Object object) {
// but org.postgis.Geometry instances. if ( object == null ) {
// This has been observed when retrieving GeometryCollections return null;
// as the result of an SQL-operation such as Union. }
if (object instanceof org.postgis.Geometry) {
object = new PGgeometry((org.postgis.Geometry) object);
}
if (object instanceof PGgeometry) { // in some cases, Postgis returns not PGgeometry objects
PGgeometry geom = (PGgeometry) object; // but org.postgis.Geometry instances.
com.vividsolutions.jts.geom.Geometry out = null; // This has been observed when retrieving GeometryCollections
switch (geom.getGeoType()) { // as the result of an SQL-operation such as Union.
case org.postgis.Geometry.POINT: if ( object instanceof org.postgis.Geometry ) {
out = convertPoint((org.postgis.Point) geom.getGeometry()); object = new PGgeometry( (org.postgis.Geometry) object );
break; }
case org.postgis.Geometry.LINESTRING:
out = convertLineString((org.postgis.LineString) geom
.getGeometry());
break;
case org.postgis.Geometry.POLYGON:
out = convertPolygon((org.postgis.Polygon) geom.getGeometry());
break;
case org.postgis.Geometry.MULTILINESTRING:
out = convertMultiLineString((org.postgis.MultiLineString) geom
.getGeometry());
break;
case org.postgis.Geometry.MULTIPOINT:
out = convertMultiPoint((org.postgis.MultiPoint) geom
.getGeometry());
break;
case org.postgis.Geometry.MULTIPOLYGON:
out = convertMultiPolygon((org.postgis.MultiPolygon) geom
.getGeometry());
break;
case org.postgis.Geometry.GEOMETRYCOLLECTION:
out = convertGeometryCollection((org.postgis.GeometryCollection) geom
.getGeometry());
break;
default:
throw new RuntimeException("Unknown type of PGgeometry");
}
out.setSRID(geom.getGeometry().srid);
return out;
} else if (object instanceof org.postgis.PGboxbase) {
return convertBox((org.postgis.PGboxbase) object);
} else {
throw new IllegalArgumentException("Can't convert object of type "
+ object.getClass().getCanonicalName());
} if ( object instanceof PGgeometry ) {
PGgeometry geom = (PGgeometry) object;
com.vividsolutions.jts.geom.Geometry out = null;
switch ( geom.getGeoType() ) {
case org.postgis.Geometry.POINT:
out = convertPoint( (org.postgis.Point) geom.getGeometry() );
break;
case org.postgis.Geometry.LINESTRING:
out = convertLineString(
(org.postgis.LineString) geom
.getGeometry()
);
break;
case org.postgis.Geometry.POLYGON:
out = convertPolygon( (org.postgis.Polygon) geom.getGeometry() );
break;
case org.postgis.Geometry.MULTILINESTRING:
out = convertMultiLineString(
(org.postgis.MultiLineString) geom
.getGeometry()
);
break;
case org.postgis.Geometry.MULTIPOINT:
out = convertMultiPoint(
(org.postgis.MultiPoint) geom
.getGeometry()
);
break;
case org.postgis.Geometry.MULTIPOLYGON:
out = convertMultiPolygon(
(org.postgis.MultiPolygon) geom
.getGeometry()
);
break;
case org.postgis.Geometry.GEOMETRYCOLLECTION:
out = convertGeometryCollection(
(org.postgis.GeometryCollection) geom
.getGeometry()
);
break;
default:
throw new RuntimeException( "Unknown type of PGgeometry" );
}
out.setSRID( geom.getGeometry().srid );
return out;
}
else if ( object instanceof org.postgis.PGboxbase ) {
return convertBox( (org.postgis.PGboxbase) object );
}
else {
throw new IllegalArgumentException(
"Can't convert object of type "
+ object.getClass().getCanonicalName()
);
} }
private Geometry convertBox(PGboxbase box) { }
Point ll = box.getLLB();
Point ur = box.getURT();
Coordinate[] ringCoords = new Coordinate[5];
if (box instanceof org.postgis.PGbox2d) {
ringCoords[0] = new Coordinate(ll.x, ll.y);
ringCoords[1] = new Coordinate(ur.x, ll.y);
ringCoords[2] = new Coordinate(ur.x, ur.y);
ringCoords[3] = new Coordinate(ll.x, ur.y);
ringCoords[4] = new Coordinate(ll.x, ll.y);
} else {
ringCoords[0] = new Coordinate(ll.x, ll.y, ll.z);
ringCoords[1] = new Coordinate(ur.x, ll.y, ll.z);
ringCoords[2] = new Coordinate(ur.x, ur.y, ur.z);
ringCoords[3] = new Coordinate(ll.x, ur.y, ur.z);
ringCoords[4] = new Coordinate(ll.x, ll.y, ll.z);
}
com.vividsolutions.jts.geom.LinearRing shell = getGeometryFactory()
.createLinearRing(ringCoords);
return getGeometryFactory().createPolygon(shell, null);
}
private Geometry convertGeometryCollection(GeometryCollection collection) { private Geometry convertBox(PGboxbase box) {
org.postgis.Geometry[] geometries = collection.getGeometries(); Point ll = box.getLLB();
com.vividsolutions.jts.geom.Geometry[] jtsGeometries = new com.vividsolutions.jts.geom.Geometry[geometries.length]; Point ur = box.getURT();
for (int i = 0; i < geometries.length; i++) { Coordinate[] ringCoords = new Coordinate[5];
jtsGeometries[i] = toJTS(geometries[i]); if ( box instanceof org.postgis.PGbox2d ) {
//TODO - refactor this so the following line is not necessary ringCoords[0] = new Coordinate( ll.x, ll.y );
jtsGeometries[i].setSRID(0); // convert2JTS sets SRIDs, but constituent geometries in a collection must have srid == 0 ringCoords[1] = new Coordinate( ur.x, ll.y );
} ringCoords[2] = new Coordinate( ur.x, ur.y );
com.vividsolutions.jts.geom.GeometryCollection jtsGCollection = getGeometryFactory() ringCoords[3] = new Coordinate( ll.x, ur.y );
.createGeometryCollection(jtsGeometries); ringCoords[4] = new Coordinate( ll.x, ll.y );
return jtsGCollection; }
} else {
ringCoords[0] = new Coordinate( ll.x, ll.y, ll.z );
ringCoords[1] = new Coordinate( ur.x, ll.y, ll.z );
ringCoords[2] = new Coordinate( ur.x, ur.y, ur.z );
ringCoords[3] = new Coordinate( ll.x, ur.y, ur.z );
ringCoords[4] = new Coordinate( ll.x, ll.y, ll.z );
}
com.vividsolutions.jts.geom.LinearRing shell = getGeometryFactory()
.createLinearRing( ringCoords );
return getGeometryFactory().createPolygon( shell, null );
}
private Geometry convertMultiPolygon(MultiPolygon pgMultiPolygon) { private Geometry convertGeometryCollection(GeometryCollection collection) {
com.vividsolutions.jts.geom.Polygon[] polygons = new com.vividsolutions.jts.geom.Polygon[pgMultiPolygon org.postgis.Geometry[] geometries = collection.getGeometries();
.numPolygons()]; com.vividsolutions.jts.geom.Geometry[] jtsGeometries = new com.vividsolutions.jts.geom.Geometry[geometries.length];
for ( int i = 0; i < geometries.length; i++ ) {
jtsGeometries[i] = toJTS( geometries[i] );
//TODO - refactor this so the following line is not necessary
jtsGeometries[i].setSRID( 0 ); // convert2JTS sets SRIDs, but constituent geometries in a collection must have srid == 0
}
com.vividsolutions.jts.geom.GeometryCollection jtsGCollection = getGeometryFactory()
.createGeometryCollection( jtsGeometries );
return jtsGCollection;
}
for (int i = 0; i < polygons.length; i++) { private Geometry convertMultiPolygon(MultiPolygon pgMultiPolygon) {
Polygon pgPolygon = pgMultiPolygon.getPolygon(i); com.vividsolutions.jts.geom.Polygon[] polygons = new com.vividsolutions.jts.geom.Polygon[pgMultiPolygon
polygons[i] = (com.vividsolutions.jts.geom.Polygon) convertPolygon(pgPolygon); .numPolygons()];
}
com.vividsolutions.jts.geom.MultiPolygon out = getGeometryFactory() for ( int i = 0; i < polygons.length; i++ ) {
.createMultiPolygon(polygons); Polygon pgPolygon = pgMultiPolygon.getPolygon( i );
return out; polygons[i] = (com.vividsolutions.jts.geom.Polygon) convertPolygon( pgPolygon );
} }
private Geometry convertMultiPoint(MultiPoint pgMultiPoint) { com.vividsolutions.jts.geom.MultiPolygon out = getGeometryFactory()
com.vividsolutions.jts.geom.Point[] points = new com.vividsolutions.jts.geom.Point[pgMultiPoint .createMultiPolygon( polygons );
.numPoints()]; return out;
}
for (int i = 0; i < points.length; i++) { private Geometry convertMultiPoint(MultiPoint pgMultiPoint) {
points[i] = convertPoint(pgMultiPoint.getPoint(i)); com.vividsolutions.jts.geom.Point[] points = new com.vividsolutions.jts.geom.Point[pgMultiPoint
} .numPoints()];
com.vividsolutions.jts.geom.MultiPoint out = getGeometryFactory()
.createMultiPoint(points);
out.setSRID(pgMultiPoint.srid);
return out;
}
private com.vividsolutions.jts.geom.Geometry convertMultiLineString( for ( int i = 0; i < points.length; i++ ) {
MultiLineString mlstr) { points[i] = convertPoint( pgMultiPoint.getPoint( i ) );
com.vividsolutions.jts.geom.MultiLineString out; }
if (mlstr.haveMeasure) { com.vividsolutions.jts.geom.MultiPoint out = getGeometryFactory()
MLineString[] lstrs = new MLineString[mlstr.numLines()]; .createMultiPoint( points );
for (int i = 0; i < mlstr.numLines(); i++) { out.setSRID( pgMultiPoint.srid );
MCoordinate[] coordinates = toJTSCoordinates(mlstr.getLine(i) return out;
.getPoints()); }
lstrs[i] = getGeometryFactory().createMLineString(coordinates);
}
out = getGeometryFactory().createMultiMLineString(lstrs);
} else {
com.vividsolutions.jts.geom.LineString[] lstrs = new com.vividsolutions.jts.geom.LineString[mlstr
.numLines()];
for (int i = 0; i < mlstr.numLines(); i++) {
lstrs[i] = getGeometryFactory().createLineString(
toJTSCoordinates(mlstr.getLine(i).getPoints()));
}
out = getGeometryFactory().createMultiLineString(lstrs);
}
return out;
}
protected com.vividsolutions.jts.geom.Geometry convertPolygon( private com.vividsolutions.jts.geom.Geometry convertMultiLineString(
Polygon polygon) { MultiLineString mlstr) {
com.vividsolutions.jts.geom.LinearRing shell = getGeometryFactory() com.vividsolutions.jts.geom.MultiLineString out;
.createLinearRing( if ( mlstr.haveMeasure ) {
toJTSCoordinates(polygon.getRing(0).getPoints())); MLineString[] lstrs = new MLineString[mlstr.numLines()];
com.vividsolutions.jts.geom.Polygon out = null; for ( int i = 0; i < mlstr.numLines(); i++ ) {
if (polygon.numRings() > 1) { MCoordinate[] coordinates = toJTSCoordinates(
com.vividsolutions.jts.geom.LinearRing[] rings = new com.vividsolutions.jts.geom.LinearRing[polygon mlstr.getLine( i )
.numRings() - 1]; .getPoints()
for (int r = 1; r < polygon.numRings(); r++) { );
rings[r - 1] = getGeometryFactory().createLinearRing( lstrs[i] = getGeometryFactory().createMLineString( coordinates );
toJTSCoordinates(polygon.getRing(r).getPoints())); }
} out = getGeometryFactory().createMultiMLineString( lstrs );
out = getGeometryFactory().createPolygon(shell, rings); }
} else { else {
out = getGeometryFactory().createPolygon(shell, null); com.vividsolutions.jts.geom.LineString[] lstrs = new com.vividsolutions.jts.geom.LineString[mlstr
} .numLines()];
return out; for ( int i = 0; i < mlstr.numLines(); i++ ) {
} lstrs[i] = getGeometryFactory().createLineString(
toJTSCoordinates( mlstr.getLine( i ).getPoints() )
);
}
out = getGeometryFactory().createMultiLineString( lstrs );
}
return out;
}
protected com.vividsolutions.jts.geom.Point convertPoint(Point pnt) { protected com.vividsolutions.jts.geom.Geometry convertPolygon(
com.vividsolutions.jts.geom.Point g = getGeometryFactory().createPoint( Polygon polygon) {
this.toJTSCoordinate(pnt)); com.vividsolutions.jts.geom.LinearRing shell = getGeometryFactory()
return g; .createLinearRing(
} toJTSCoordinates( polygon.getRing( 0 ).getPoints() )
);
com.vividsolutions.jts.geom.Polygon out = null;
if ( polygon.numRings() > 1 ) {
com.vividsolutions.jts.geom.LinearRing[] rings = new com.vividsolutions.jts.geom.LinearRing[polygon
.numRings() - 1];
for ( int r = 1; r < polygon.numRings(); r++ ) {
rings[r - 1] = getGeometryFactory().createLinearRing(
toJTSCoordinates( polygon.getRing( r ).getPoints() )
);
}
out = getGeometryFactory().createPolygon( shell, rings );
}
else {
out = getGeometryFactory().createPolygon( shell, null );
}
return out;
}
protected com.vividsolutions.jts.geom.LineString convertLineString( protected com.vividsolutions.jts.geom.Point convertPoint(Point pnt) {
org.postgis.LineString lstr) { com.vividsolutions.jts.geom.Point g = getGeometryFactory().createPoint(
com.vividsolutions.jts.geom.LineString out = lstr.haveMeasure ? getGeometryFactory() this.toJTSCoordinate( pnt )
.createMLineString(toJTSCoordinates(lstr.getPoints())) );
: getGeometryFactory().createLineString( return g;
toJTSCoordinates(lstr.getPoints())); }
return out;
}
private MCoordinate[] toJTSCoordinates(Point[] points) { protected com.vividsolutions.jts.geom.LineString convertLineString(
MCoordinate[] coordinates = new MCoordinate[points.length]; org.postgis.LineString lstr) {
for (int i = 0; i < points.length; i++) { com.vividsolutions.jts.geom.LineString out = lstr.haveMeasure ? getGeometryFactory()
coordinates[i] = this.toJTSCoordinate(points[i]); .createMLineString( toJTSCoordinates( lstr.getPoints() ) )
} : getGeometryFactory().createLineString(
return coordinates; toJTSCoordinates( lstr.getPoints() )
} );
return out;
}
private MCoordinate toJTSCoordinate(Point pt) { private MCoordinate[] toJTSCoordinates(Point[] points) {
MCoordinate mc; MCoordinate[] coordinates = new MCoordinate[points.length];
if (pt.dimension == 2) { for ( int i = 0; i < points.length; i++ ) {
mc = pt.haveMeasure ? MCoordinate.create2dWithMeasure(pt.getX(), pt coordinates[i] = this.toJTSCoordinate( points[i] );
.getY(), pt.getM()) : MCoordinate.create2d(pt.getX(), pt }
.getY()); return coordinates;
} else { }
mc = pt.haveMeasure ? MCoordinate.create3dWithMeasure(pt.getX(), pt
.getY(), pt.getZ(), pt.getM()) : MCoordinate.create3d(pt private MCoordinate toJTSCoordinate(Point pt) {
.getX(), pt.getY(), pt.getZ()); MCoordinate mc;
} if ( pt.dimension == 2 ) {
return mc; mc = pt.haveMeasure ? MCoordinate.create2dWithMeasure(
} pt.getX(), pt
.getY(), pt.getM()
) : MCoordinate.create2d(
pt.getX(), pt
.getY()
);
}
else {
mc = pt.haveMeasure ? MCoordinate.create3dWithMeasure(
pt.getX(), pt
.getY(), pt.getZ(), pt.getM()
) : MCoordinate.create3d(
pt
.getX(), pt.getY(), pt.getZ()
);
}
return mc;
}
} }

View File

@ -31,7 +31,12 @@
import org.hibernate.dialect.PostgreSQLDialect; import org.hibernate.dialect.PostgreSQLDialect;
import org.hibernate.dialect.function.StandardSQLFunction; import org.hibernate.dialect.function.StandardSQLFunction;
import org.hibernate.spatial.*; import org.hibernate.spatial.GeometryType;
import org.hibernate.spatial.SpatialAggregate;
import org.hibernate.spatial.SpatialDialect;
import org.hibernate.spatial.SpatialFunction;
import org.hibernate.spatial.SpatialGeometrySqlTypeDescriptor;
import org.hibernate.spatial.SpatialRelation;
import org.hibernate.type.StandardBasicTypes; import org.hibernate.type.StandardBasicTypes;
import org.hibernate.type.descriptor.sql.SqlTypeDescriptor; import org.hibernate.type.descriptor.sql.SqlTypeDescriptor;
@ -44,155 +49,266 @@
public class PostgisDialect extends PostgreSQLDialect implements SpatialDialect { public class PostgisDialect extends PostgreSQLDialect implements SpatialDialect {
public PostgisDialect() { public PostgisDialect() {
super(); super();
registerTypesAndFunctions(); registerTypesAndFunctions();
} }
protected void registerTypesAndFunctions() { protected void registerTypesAndFunctions() {
registerColumnType(java.sql.Types.STRUCT, "geometry"); registerColumnType( java.sql.Types.STRUCT, "geometry" );
// registering OGC functions // registering OGC functions
// (spec_simplefeatures_sql_99-04.pdf) // (spec_simplefeatures_sql_99-04.pdf)
// section 2.1.1.1 // section 2.1.1.1
// Registerfunction calls for registering geometry functions: // Registerfunction calls for registering geometry functions:
// first argument is the OGC standard functionname, second the name as // first argument is the OGC standard functionname, second the name as
// it occurs in the spatial dialect // it occurs in the spatial dialect
registerFunction("dimension", new StandardSQLFunction("st_dimension", registerFunction(
StandardBasicTypes.INTEGER)); "dimension", new StandardSQLFunction(
registerFunction("geometrytype", new StandardSQLFunction( "st_dimension",
"st_geometrytype", StandardBasicTypes.STRING)); StandardBasicTypes.INTEGER
registerFunction("srid", new StandardSQLFunction("st_srid", )
StandardBasicTypes.INTEGER)); );
registerFunction("envelope", new StandardSQLFunction("st_envelope", registerFunction(
GeometryType.INSTANCE)); "geometrytype", new StandardSQLFunction(
registerFunction("astext", new StandardSQLFunction("st_astext", "st_geometrytype", StandardBasicTypes.STRING
StandardBasicTypes.STRING)); )
registerFunction("asbinary", new StandardSQLFunction("st_asbinary", );
StandardBasicTypes.BINARY)); registerFunction(
registerFunction("isempty", new StandardSQLFunction("st_isempty", "srid", new StandardSQLFunction(
StandardBasicTypes.BOOLEAN)); "st_srid",
registerFunction("issimple", new StandardSQLFunction("st_issimple", StandardBasicTypes.INTEGER
StandardBasicTypes.BOOLEAN)); )
registerFunction("boundary", new StandardSQLFunction("st_boundary", );
GeometryType.INSTANCE)); registerFunction(
"envelope", new StandardSQLFunction(
"st_envelope",
GeometryType.INSTANCE
)
);
registerFunction(
"astext", new StandardSQLFunction(
"st_astext",
StandardBasicTypes.STRING
)
);
registerFunction(
"asbinary", new StandardSQLFunction(
"st_asbinary",
StandardBasicTypes.BINARY
)
);
registerFunction(
"isempty", new StandardSQLFunction(
"st_isempty",
StandardBasicTypes.BOOLEAN
)
);
registerFunction(
"issimple", new StandardSQLFunction(
"st_issimple",
StandardBasicTypes.BOOLEAN
)
);
registerFunction(
"boundary", new StandardSQLFunction(
"st_boundary",
GeometryType.INSTANCE
)
);
// Register functions for spatial relation constructs // Register functions for spatial relation constructs
registerFunction("overlaps", new StandardSQLFunction("st_overlaps", registerFunction(
StandardBasicTypes.BOOLEAN)); "overlaps", new StandardSQLFunction(
registerFunction("intersects", new StandardSQLFunction("st_intersects", "st_overlaps",
StandardBasicTypes.BOOLEAN)); StandardBasicTypes.BOOLEAN
registerFunction("equals", new StandardSQLFunction("st_equals", )
StandardBasicTypes.BOOLEAN)); );
registerFunction("contains", new StandardSQLFunction("st_contains", registerFunction(
StandardBasicTypes.BOOLEAN)); "intersects", new StandardSQLFunction(
registerFunction("crosses", new StandardSQLFunction("st_crosses", "st_intersects",
StandardBasicTypes.BOOLEAN)); StandardBasicTypes.BOOLEAN
registerFunction("disjoint", new StandardSQLFunction("st_disjoint", )
StandardBasicTypes.BOOLEAN)); );
registerFunction("touches", new StandardSQLFunction("st_touches", registerFunction(
StandardBasicTypes.BOOLEAN)); "equals", new StandardSQLFunction(
registerFunction("within", new StandardSQLFunction("st_within", "st_equals",
StandardBasicTypes.BOOLEAN)); StandardBasicTypes.BOOLEAN
registerFunction("relate", new StandardSQLFunction("st_relate", )
StandardBasicTypes.BOOLEAN)); );
registerFunction(
"contains", new StandardSQLFunction(
"st_contains",
StandardBasicTypes.BOOLEAN
)
);
registerFunction(
"crosses", new StandardSQLFunction(
"st_crosses",
StandardBasicTypes.BOOLEAN
)
);
registerFunction(
"disjoint", new StandardSQLFunction(
"st_disjoint",
StandardBasicTypes.BOOLEAN
)
);
registerFunction(
"touches", new StandardSQLFunction(
"st_touches",
StandardBasicTypes.BOOLEAN
)
);
registerFunction(
"within", new StandardSQLFunction(
"st_within",
StandardBasicTypes.BOOLEAN
)
);
registerFunction(
"relate", new StandardSQLFunction(
"st_relate",
StandardBasicTypes.BOOLEAN
)
);
// register the spatial analysis functions // register the spatial analysis functions
registerFunction("distance", new StandardSQLFunction("st_distance", registerFunction(
StandardBasicTypes.DOUBLE)); "distance", new StandardSQLFunction(
registerFunction("buffer", new StandardSQLFunction("st_buffer", "st_distance",
GeometryType.INSTANCE)); StandardBasicTypes.DOUBLE
registerFunction("convexhull", new StandardSQLFunction("st_convexhull", )
GeometryType.INSTANCE)); );
registerFunction("difference", new StandardSQLFunction("st_difference", registerFunction(
GeometryType.INSTANCE)); "buffer", new StandardSQLFunction(
registerFunction("intersection", new StandardSQLFunction( "st_buffer",
"st_intersection", new GeometryType())); GeometryType.INSTANCE
registerFunction("symdifference", )
new StandardSQLFunction("st_symdifference", GeometryType.INSTANCE)); );
registerFunction("geomunion", new StandardSQLFunction("st_union", registerFunction(
GeometryType.INSTANCE)); "convexhull", new StandardSQLFunction(
"st_convexhull",
GeometryType.INSTANCE
)
);
registerFunction(
"difference", new StandardSQLFunction(
"st_difference",
GeometryType.INSTANCE
)
);
registerFunction(
"intersection", new StandardSQLFunction(
"st_intersection", new GeometryType()
)
);
registerFunction(
"symdifference",
new StandardSQLFunction( "st_symdifference", GeometryType.INSTANCE )
);
registerFunction(
"geomunion", new StandardSQLFunction(
"st_union",
GeometryType.INSTANCE
)
);
//register Spatial Aggregate function //register Spatial Aggregate function
registerFunction("extent", new StandardSQLFunction("extent", registerFunction(
GeometryType.INSTANCE)); "extent", new StandardSQLFunction(
"extent",
GeometryType.INSTANCE
)
);
//other common functions //other common functions
registerFunction("dwithin", new StandardSQLFunction("st_dwithin", registerFunction(
StandardBasicTypes.BOOLEAN)); "dwithin", new StandardSQLFunction(
registerFunction("transform", new StandardSQLFunction("st_transform", "st_dwithin",
GeometryType.INSTANCE)); StandardBasicTypes.BOOLEAN
} )
);
registerFunction(
"transform", new StandardSQLFunction(
"st_transform",
GeometryType.INSTANCE
)
);
}
@Override @Override
public SqlTypeDescriptor remapSqlTypeDescriptor(SqlTypeDescriptor sqlTypeDescriptor) { public SqlTypeDescriptor remapSqlTypeDescriptor(SqlTypeDescriptor sqlTypeDescriptor) {
if (sqlTypeDescriptor instanceof SpatialGeometrySqlTypeDescriptor) { if ( sqlTypeDescriptor instanceof SpatialGeometrySqlTypeDescriptor ) {
return PGGeometryTypeDescriptor.INSTANCE; return PGGeometryTypeDescriptor.INSTANCE;
} }
return super.remapSqlTypeDescriptor(sqlTypeDescriptor); return super.remapSqlTypeDescriptor( sqlTypeDescriptor );
} }
public String getSpatialRelateSQL(String columnName, int spatialRelation) { public String getSpatialRelateSQL(String columnName, int spatialRelation) {
switch (spatialRelation) { switch ( spatialRelation ) {
case SpatialRelation.WITHIN: case SpatialRelation.WITHIN:
return " ST_within(" + columnName + ",?)"; return " ST_within(" + columnName + ",?)";
case SpatialRelation.CONTAINS: case SpatialRelation.CONTAINS:
return " ST_contains(" + columnName + ", ?)"; return " ST_contains(" + columnName + ", ?)";
case SpatialRelation.CROSSES: case SpatialRelation.CROSSES:
return " ST_crosses(" + columnName + ", ?)"; return " ST_crosses(" + columnName + ", ?)";
case SpatialRelation.OVERLAPS: case SpatialRelation.OVERLAPS:
return " ST_overlaps(" + columnName + ", ?)"; return " ST_overlaps(" + columnName + ", ?)";
case SpatialRelation.DISJOINT: case SpatialRelation.DISJOINT:
return " ST_disjoint(" + columnName + ", ?)"; return " ST_disjoint(" + columnName + ", ?)";
case SpatialRelation.INTERSECTS: case SpatialRelation.INTERSECTS:
return " ST_intersects(" + columnName return " ST_intersects(" + columnName
+ ", ?)"; + ", ?)";
case SpatialRelation.TOUCHES: case SpatialRelation.TOUCHES:
return " ST_touches(" + columnName + ", ?)"; return " ST_touches(" + columnName + ", ?)";
case SpatialRelation.EQUALS: case SpatialRelation.EQUALS:
return " ST_equals(" + columnName + ", ?)"; return " ST_equals(" + columnName + ", ?)";
default: default:
throw new IllegalArgumentException( throw new IllegalArgumentException(
"Spatial relation is not known by this dialect"); "Spatial relation is not known by this dialect"
} );
}
} }
public String getDWithinSQL(String columnName) { public String getDWithinSQL(String columnName) {
return "ST_DWithin(" + columnName + ",?,?)"; return "ST_DWithin(" + columnName + ",?,?)";
} }
public String getHavingSridSQL(String columnName) { public String getHavingSridSQL(String columnName) {
return "( ST_srid(" + columnName + ") = ?)"; return "( ST_srid(" + columnName + ") = ?)";
} }
public String getIsEmptySQL(String columnName, boolean isEmpty) { public String getIsEmptySQL(String columnName, boolean isEmpty) {
String emptyExpr = " ST_IsEmpty(" + columnName + ") "; String emptyExpr = " ST_IsEmpty(" + columnName + ") ";
return isEmpty ? emptyExpr : "( NOT " + emptyExpr + ")"; return isEmpty ? emptyExpr : "( NOT " + emptyExpr + ")";
} }
public String getSpatialFilterExpression(String columnName) { public String getSpatialFilterExpression(String columnName) {
return "(" + columnName + " && ? ) "; return "(" + columnName + " && ? ) ";
} }
public String getSpatialAggregateSQL(String columnName, int aggregation) { public String getSpatialAggregateSQL(String columnName, int aggregation) {
switch (aggregation) { switch ( aggregation ) {
case SpatialAggregate.EXTENT: case SpatialAggregate.EXTENT:
StringBuilder stbuf = new StringBuilder(); StringBuilder stbuf = new StringBuilder();
stbuf.append("extent(").append(columnName).append(")"); stbuf.append( "extent(" ).append( columnName ).append( ")" );
return stbuf.toString(); return stbuf.toString();
default: default:
throw new IllegalArgumentException("Aggregation of type " throw new IllegalArgumentException(
+ aggregation + " are not supported by this dialect"); "Aggregation of type "
} + aggregation + " are not supported by this dialect"
} );
}
}
public boolean supportsFiltering() { public boolean supportsFiltering() {
return true; return true;
} }
public boolean supports(SpatialFunction function) { public boolean supports(SpatialFunction function) {
return (getFunctions().get(function.toString()) != null); return ( getFunctions().get( function.toString() ) != null );
} }
} }

View File

@ -2,143 +2,248 @@
import org.hibernate.dialect.function.StandardSQLFunction; import org.hibernate.dialect.function.StandardSQLFunction;
import org.hibernate.spatial.GeometryType; import org.hibernate.spatial.GeometryType;
import org.hibernate.type.StandardBasicTypes;
import org.hibernate.spatial.SpatialFunction; import org.hibernate.spatial.SpatialFunction;
import org.hibernate.spatial.SpatialRelation; import org.hibernate.spatial.SpatialRelation;
import org.hibernate.type.StandardBasicTypes;
/** /**
* @author Karel Maesen, Geovise BVBA * @author Karel Maesen, Geovise BVBA
* creation-date: Dec 18, 2010 * creation-date: Dec 18, 2010
*/ */
public class PostgisNoSQLMM extends PostgisDialect { public class PostgisNoSQLMM extends PostgisDialect {
@Override @Override
protected void registerTypesAndFunctions() { protected void registerTypesAndFunctions() {
registerColumnType(java.sql.Types.STRUCT, "geometry"); registerColumnType( java.sql.Types.STRUCT, "geometry" );
// registering OGC functions // registering OGC functions
// (spec_simplefeatures_sql_99-04.pdf) // (spec_simplefeatures_sql_99-04.pdf)
// section 2.1.1.1 // section 2.1.1.1
// Registerfunction calls for registering geometry functions: // Registerfunction calls for registering geometry functions:
// first argument is the OGC standard functionname, second the name as // first argument is the OGC standard functionname, second the name as
// it occurs in the spatial dialect // it occurs in the spatial dialect
registerFunction("dimension", new StandardSQLFunction("dimension", registerFunction(
StandardBasicTypes.INTEGER)); "dimension", new StandardSQLFunction(
registerFunction("geometrytype", new StandardSQLFunction( "dimension",
"geometrytype", StandardBasicTypes.STRING)); StandardBasicTypes.INTEGER
registerFunction("srid", new StandardSQLFunction("srid", )
StandardBasicTypes.INTEGER)); );
registerFunction("envelope", new StandardSQLFunction("envelope", registerFunction(
new GeometryType())); "geometrytype", new StandardSQLFunction(
registerFunction("astext", new StandardSQLFunction("astext", "geometrytype", StandardBasicTypes.STRING
StandardBasicTypes.STRING)); )
registerFunction("asbinary", new StandardSQLFunction("asbinary", );
StandardBasicTypes.BINARY)); registerFunction(
registerFunction("isempty", new StandardSQLFunction("isempty", "srid", new StandardSQLFunction(
StandardBasicTypes.BOOLEAN)); "srid",
registerFunction("issimple", new StandardSQLFunction("issimple", StandardBasicTypes.INTEGER
StandardBasicTypes.BOOLEAN)); )
registerFunction("boundary", new StandardSQLFunction("boundary", );
new GeometryType())); registerFunction(
"envelope", new StandardSQLFunction(
"envelope",
new GeometryType()
)
);
registerFunction(
"astext", new StandardSQLFunction(
"astext",
StandardBasicTypes.STRING
)
);
registerFunction(
"asbinary", new StandardSQLFunction(
"asbinary",
StandardBasicTypes.BINARY
)
);
registerFunction(
"isempty", new StandardSQLFunction(
"isempty",
StandardBasicTypes.BOOLEAN
)
);
registerFunction(
"issimple", new StandardSQLFunction(
"issimple",
StandardBasicTypes.BOOLEAN
)
);
registerFunction(
"boundary", new StandardSQLFunction(
"boundary",
new GeometryType()
)
);
// Register functions for spatial relation constructs // Register functions for spatial relation constructs
registerFunction("overlaps", new StandardSQLFunction("overlaps", registerFunction(
StandardBasicTypes.BOOLEAN)); "overlaps", new StandardSQLFunction(
registerFunction("intersects", new StandardSQLFunction("intersects", "overlaps",
StandardBasicTypes.BOOLEAN)); StandardBasicTypes.BOOLEAN
registerFunction("equals", new StandardSQLFunction("equals", )
StandardBasicTypes.BOOLEAN)); );
registerFunction("contains", new StandardSQLFunction("contains", registerFunction(
StandardBasicTypes.BOOLEAN)); "intersects", new StandardSQLFunction(
registerFunction("crosses", new StandardSQLFunction("crosses", "intersects",
StandardBasicTypes.BOOLEAN)); StandardBasicTypes.BOOLEAN
registerFunction("disjoint", new StandardSQLFunction("disjoint", )
StandardBasicTypes.BOOLEAN)); );
registerFunction("touches", new StandardSQLFunction("touches", registerFunction(
StandardBasicTypes.BOOLEAN)); "equals", new StandardSQLFunction(
registerFunction("within", new StandardSQLFunction("within", "equals",
StandardBasicTypes.BOOLEAN)); StandardBasicTypes.BOOLEAN
registerFunction("relate", new StandardSQLFunction("relate", )
StandardBasicTypes.BOOLEAN)); );
registerFunction(
"contains", new StandardSQLFunction(
"contains",
StandardBasicTypes.BOOLEAN
)
);
registerFunction(
"crosses", new StandardSQLFunction(
"crosses",
StandardBasicTypes.BOOLEAN
)
);
registerFunction(
"disjoint", new StandardSQLFunction(
"disjoint",
StandardBasicTypes.BOOLEAN
)
);
registerFunction(
"touches", new StandardSQLFunction(
"touches",
StandardBasicTypes.BOOLEAN
)
);
registerFunction(
"within", new StandardSQLFunction(
"within",
StandardBasicTypes.BOOLEAN
)
);
registerFunction(
"relate", new StandardSQLFunction(
"relate",
StandardBasicTypes.BOOLEAN
)
);
// register the spatial analysis functions // register the spatial analysis functions
registerFunction("distance", new StandardSQLFunction("distance", registerFunction(
StandardBasicTypes.DOUBLE)); "distance", new StandardSQLFunction(
registerFunction("buffer", new StandardSQLFunction("buffer", "distance",
GeometryType.INSTANCE)); StandardBasicTypes.DOUBLE
registerFunction("convexhull", new StandardSQLFunction("convexhull", )
GeometryType.INSTANCE)); );
registerFunction("difference", new StandardSQLFunction("difference", registerFunction(
GeometryType.INSTANCE)); "buffer", new StandardSQLFunction(
registerFunction("intersection", new StandardSQLFunction( "buffer",
"intersection", new GeometryType())); GeometryType.INSTANCE
registerFunction("symdifference", )
new StandardSQLFunction("symdifference", GeometryType.INSTANCE)); );
registerFunction("geomunion", new StandardSQLFunction("geomunion", registerFunction(
GeometryType.INSTANCE)); "convexhull", new StandardSQLFunction(
"convexhull",
GeometryType.INSTANCE
)
);
registerFunction(
"difference", new StandardSQLFunction(
"difference",
GeometryType.INSTANCE
)
);
registerFunction(
"intersection", new StandardSQLFunction(
"intersection", new GeometryType()
)
);
registerFunction(
"symdifference",
new StandardSQLFunction( "symdifference", GeometryType.INSTANCE )
);
registerFunction(
"geomunion", new StandardSQLFunction(
"geomunion",
GeometryType.INSTANCE
)
);
//register Spatial Aggregate function //register Spatial Aggregate function
registerFunction("extent", new StandardSQLFunction("extent", registerFunction(
GeometryType.INSTANCE)); "extent", new StandardSQLFunction(
"extent",
GeometryType.INSTANCE
)
);
//other common spatial functions //other common spatial functions
registerFunction("transform", new StandardSQLFunction("transform", registerFunction(
GeometryType.INSTANCE)); "transform", new StandardSQLFunction(
} "transform",
GeometryType.INSTANCE
)
);
}
@Override @Override
public String getDWithinSQL(String columnName) { public String getDWithinSQL(String columnName) {
return "( dwithin(" + columnName + ",?,?) )"; return "( dwithin(" + columnName + ",?,?) )";
} }
@Override @Override
public String getHavingSridSQL(String columnName) { public String getHavingSridSQL(String columnName) {
return "( srid(" + columnName + ") = ?)"; return "( srid(" + columnName + ") = ?)";
} }
@Override @Override
public String getIsEmptySQL(String columnName, boolean isEmpty) { public String getIsEmptySQL(String columnName, boolean isEmpty) {
String emptyExpr = "( isempty(" + columnName + ")) "; String emptyExpr = "( isempty(" + columnName + ")) ";
return isEmpty ? emptyExpr : "not " + emptyExpr; return isEmpty ? emptyExpr : "not " + emptyExpr;
} }
public String getSpatialRelateSQL(String columnName, int spatialRelation, public String getSpatialRelateSQL(String columnName, int spatialRelation,
boolean hasFilter) { boolean hasFilter) {
switch (spatialRelation) { switch ( spatialRelation ) {
case SpatialRelation.WITHIN: case SpatialRelation.WITHIN:
return hasFilter ? "(" + columnName + " && ? AND within(" return hasFilter ? "(" + columnName + " && ? AND within("
+ columnName + ", ?))" : " within(" + columnName + ",?)"; + columnName + ", ?))" : " within(" + columnName + ",?)";
case SpatialRelation.CONTAINS: case SpatialRelation.CONTAINS:
return hasFilter ? "(" + columnName + " && ? AND contains(" return hasFilter ? "(" + columnName + " && ? AND contains("
+ columnName + ", ?))" : " contains(" + columnName + ", ?)"; + columnName + ", ?))" : " contains(" + columnName + ", ?)";
case SpatialRelation.CROSSES: case SpatialRelation.CROSSES:
return hasFilter ? "(" + columnName + " && ? AND crosses(" return hasFilter ? "(" + columnName + " && ? AND crosses("
+ columnName + ", ?))" : " crosses(" + columnName + ", ?)"; + columnName + ", ?))" : " crosses(" + columnName + ", ?)";
case SpatialRelation.OVERLAPS: case SpatialRelation.OVERLAPS:
return hasFilter ? "(" + columnName + " && ? AND overlaps(" return hasFilter ? "(" + columnName + " && ? AND overlaps("
+ columnName + ", ?))" : " overlaps(" + columnName + ", ?)"; + columnName + ", ?))" : " overlaps(" + columnName + ", ?)";
case SpatialRelation.DISJOINT: case SpatialRelation.DISJOINT:
return hasFilter ? "(" + columnName + " && ? AND disjoint(" return hasFilter ? "(" + columnName + " && ? AND disjoint("
+ columnName + ", ?))" : " disjoint(" + columnName + ", ?)"; + columnName + ", ?))" : " disjoint(" + columnName + ", ?)";
case SpatialRelation.INTERSECTS: case SpatialRelation.INTERSECTS:
return hasFilter ? "(" + columnName + " && ? AND intersects(" return hasFilter ? "(" + columnName + " && ? AND intersects("
+ columnName + ", ?))" : " intersects(" + columnName + columnName + ", ?))" : " intersects(" + columnName
+ ", ?)"; + ", ?)";
case SpatialRelation.TOUCHES: case SpatialRelation.TOUCHES:
return hasFilter ? "(" + columnName + " && ? AND touches(" return hasFilter ? "(" + columnName + " && ? AND touches("
+ columnName + ", ?))" : " touches(" + columnName + ", ?)"; + columnName + ", ?))" : " touches(" + columnName + ", ?)";
case SpatialRelation.EQUALS: case SpatialRelation.EQUALS:
return hasFilter ? "(" + columnName + " && ? AND equals(" return hasFilter ? "(" + columnName + " && ? AND equals("
+ columnName + ", ?))" : " equals(" + columnName + ", ?)"; + columnName + ", ?))" : " equals(" + columnName + ", ?)";
default: default:
throw new IllegalArgumentException( throw new IllegalArgumentException(
"Spatial relation is not known by this dialect"); "Spatial relation is not known by this dialect"
} );
}
} }
@Override @Override
public boolean supports(SpatialFunction function) { public boolean supports(SpatialFunction function) {
return super.supports(function); return super.supports( function );
} }
} }

View File

@ -3,7 +3,7 @@
* *
* This file is part of Hibernate Spatial, an extension to the * This file is part of Hibernate Spatial, an extension to the
* hibernate ORM solution for geographic data. * hibernate ORM solution for geographic data.
* *
* Copyright © 2007 Geovise BVBA * Copyright © 2007 Geovise BVBA
* Copyright © 2007 K.U. Leuven LRD, Spatial Applications Division, Belgium * Copyright © 2007 K.U. Leuven LRD, Spatial Applications Division, Belgium
* *
@ -41,15 +41,15 @@ public class EnvelopeAdapter {
static public Polygon toPolygon(Envelope env, int SRID) { static public Polygon toPolygon(Envelope env, int SRID) {
Coordinate[] coords = new Coordinate[5]; Coordinate[] coords = new Coordinate[5];
coords[0] = new Coordinate(env.getMinX(), env.getMinY()); coords[0] = new Coordinate( env.getMinX(), env.getMinY() );
coords[1] = new Coordinate(env.getMinX(), env.getMaxY()); coords[1] = new Coordinate( env.getMinX(), env.getMaxY() );
coords[2] = new Coordinate(env.getMaxX(), env.getMaxY()); coords[2] = new Coordinate( env.getMaxX(), env.getMaxY() );
coords[3] = new Coordinate(env.getMaxX(), env.getMinY()); coords[3] = new Coordinate( env.getMaxX(), env.getMinY() );
coords[4] = new Coordinate(env.getMinX(), env.getMinY()); coords[4] = new Coordinate( env.getMinX(), env.getMinY() );
LinearRing shell = geomFactory.createLinearRing(coords); LinearRing shell = geomFactory.createLinearRing( coords );
Polygon pg = geomFactory.createPolygon(shell, null); Polygon pg = geomFactory.createPolygon( shell, null );
pg.setSRID(SRID); pg.setSRID( SRID );
return pg; return pg;
} }

View File

@ -3,7 +3,7 @@
* *
* This file is part of Hibernate Spatial, an extension to the * This file is part of Hibernate Spatial, an extension to the
* hibernate ORM solution for geographic data. * hibernate ORM solution for geographic data.
* *
* Copyright © 2008 Geovise BVBA * Copyright © 2008 Geovise BVBA
* *
* This library is free software; you can redistribute it and/or * This library is free software; you can redistribute it and/or
@ -27,16 +27,15 @@
/** /**
* This exception is thrown when Hibernate Spatial fails to find a required * This exception is thrown when Hibernate Spatial fails to find a required
* resource. * resource.
* *
* @author maesenka * @author maesenka
*
*/ */
public class FinderException extends Exception { public class FinderException extends Exception {
private static final long serialVersionUID = 1L; private static final long serialVersionUID = 1L;
public FinderException(String msg) { public FinderException(String msg) {
super(msg); super( msg );
} }
} }

View File

@ -3,7 +3,7 @@
* *
* This file is part of Hibernate Spatial, an extension to the * This file is part of Hibernate Spatial, an extension to the
* hibernate ORM solution for geographic data. * hibernate ORM solution for geographic data.
* *
* Copyright © 2008 Geovise BVBA * Copyright © 2008 Geovise BVBA
* *
* This library is free software; you can redistribute it and/or * This library is free software; you can redistribute it and/or
@ -28,24 +28,22 @@
* A <code>FinderStrategy</code> is used to find a specific feature. It is * A <code>FinderStrategy</code> is used to find a specific feature. It is
* useful in cases where reflection is used to determine some property of a * useful in cases where reflection is used to determine some property of a
* class. * class.
* *
* @param <T> the return type of the <code>find</code> method
* @param <S> the type of subject
*
* @author Karel Maesen * @author Karel Maesen
*
* @param <T>
* the return type of the <code>find</code> method
* @param <S>
* the type of subject
*/ */
public interface FinderStrategy<T, S> { public interface FinderStrategy<T, S> {
/** /**
* Find a feature or property of a subject * Find a feature or property of a subject
* *
* @param subject * @param subject the object that is being searched
* the object that is being searched *
* @return the object sought * @return the object sought
* @throws FinderException *
* thrown when the feature can be found; * @throws FinderException thrown when the feature can be found;
*/ */
public T find(S subject) throws FinderException; public T find(S subject) throws FinderException;

View File

@ -24,13 +24,14 @@
*/ */
package org.hibernate.spatial.helper; package org.hibernate.spatial.helper;
import java.util.Map;
import com.vividsolutions.jts.geom.PrecisionModel; import com.vividsolutions.jts.geom.PrecisionModel;
import org.hibernate.spatial.cfg.HSProperty;
import org.hibernate.spatial.mgeom.MGeometryFactory;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import java.util.Map; import org.hibernate.spatial.cfg.HSProperty;
import org.hibernate.spatial.mgeom.MGeometryFactory;
/** /**
* Factory for creating a <code>GeometryFactory</code> given a map of * Factory for creating a <code>GeometryFactory</code> given a map of
@ -40,46 +41,59 @@
*/ */
public class GeometryFactoryHelper { public class GeometryFactoryHelper {
private static Logger logger = LoggerFactory.getLogger(GeometryFactoryHelper.class); private static Logger logger = LoggerFactory.getLogger( GeometryFactoryHelper.class );
public static MGeometryFactory createGeometryFactory(Map map) { public static MGeometryFactory createGeometryFactory(Map map) {
if (map == null) { if ( map == null ) {
return new MGeometryFactory(); return new MGeometryFactory();
} }
String precisionModelName = null; String precisionModelName = null;
Double scale = null; Double scale = null;
if (map.containsKey(HSProperty.PRECISION_MODEL.toString())) { if ( map.containsKey( HSProperty.PRECISION_MODEL.toString() ) ) {
precisionModelName = (String) map.get(HSProperty.PRECISION_MODEL precisionModelName = (String) map.get(
.toString()); HSProperty.PRECISION_MODEL
} .toString()
if (map.containsKey(HSProperty.PRECISION_MODEL_SCALE.toString())) { );
scale = Double.parseDouble(((String) map }
.get(HSProperty.PRECISION_MODEL_SCALE.toString()))); if ( map.containsKey( HSProperty.PRECISION_MODEL_SCALE.toString() ) ) {
} scale = Double.parseDouble(
if (scale != null && !scale.isNaN() && precisionModelName != null ( (String) map
&& precisionModelName.equalsIgnoreCase("FIXED")) { .get( HSProperty.PRECISION_MODEL_SCALE.toString() ) )
return new MGeometryFactory(new PrecisionModel(scale)); );
} }
if (precisionModelName == null) { if ( scale != null && !scale.isNaN() && precisionModelName != null
return new MGeometryFactory(); && precisionModelName.equalsIgnoreCase( "FIXED" ) ) {
} return new MGeometryFactory( new PrecisionModel( scale ) );
if (precisionModelName.equalsIgnoreCase("FIXED")) { }
return new MGeometryFactory( if ( precisionModelName == null ) {
new PrecisionModel(PrecisionModel.FIXED)); return new MGeometryFactory();
} }
if (precisionModelName.equalsIgnoreCase("FLOATING")) { if ( precisionModelName.equalsIgnoreCase( "FIXED" ) ) {
return new MGeometryFactory(new PrecisionModel( return new MGeometryFactory(
PrecisionModel.FLOATING)); new PrecisionModel( PrecisionModel.FIXED )
} );
if (precisionModelName.equalsIgnoreCase("FLOATING_SINGLE")) { }
return new MGeometryFactory(new PrecisionModel( if ( precisionModelName.equalsIgnoreCase( "FLOATING" ) ) {
PrecisionModel.FLOATING_SINGLE)); return new MGeometryFactory(
} new PrecisionModel(
logger.warn("Configured for PrecisionModel: " + precisionModelName PrecisionModel.FLOATING
+ " but don't know how to instantiate."); )
logger.warn("Reverting to default GeometryModel"); );
return new MGeometryFactory(); }
} if ( precisionModelName.equalsIgnoreCase( "FLOATING_SINGLE" ) ) {
return new MGeometryFactory(
new PrecisionModel(
PrecisionModel.FLOATING_SINGLE
)
);
}
logger.warn(
"Configured for PrecisionModel: " + precisionModelName
+ " but don't know how to instantiate."
);
logger.warn( "Reverting to default GeometryModel" );
return new MGeometryFactory();
}
} }

View File

@ -1,27 +1,27 @@
package org.hibernate.spatial.helper; package org.hibernate.spatial.helper;
import com.vividsolutions.jts.geom.Geometry;
import org.hibernate.metadata.ClassMetadata; import org.hibernate.metadata.ClassMetadata;
import org.hibernate.type.Type; import org.hibernate.type.Type;
import com.vividsolutions.jts.geom.Geometry;
/** /**
* This <code>FinderStrategy</code> implementation returns the first * This <code>FinderStrategy</code> implementation returns the first
* geometry-valued property. * geometry-valued property.
*
*/ */
public class GeometryPropertyFinder implements FinderStrategy<String, ClassMetadata> { public class GeometryPropertyFinder implements FinderStrategy<String, ClassMetadata> {
public String find(ClassMetadata metadata) throws FinderException { public String find(ClassMetadata metadata) throws FinderException {
for (String prop : metadata.getPropertyNames()) { for ( String prop : metadata.getPropertyNames() ) {
Type type = metadata.getPropertyType(prop); Type type = metadata.getPropertyType( prop );
if (Geometry.class.isAssignableFrom(type.getReturnedClass())) { if ( Geometry.class.isAssignableFrom( type.getReturnedClass() ) ) {
return prop; return prop;
} }
} }
throw new FinderException( throw new FinderException(
"Could not find a Geometry-valued property in " "Could not find a Geometry-valued property in "
+ metadata.getEntityName()); + metadata.getEntityName()
);
} }
} }

View File

@ -3,7 +3,7 @@
* *
* This file is part of Hibernate Spatial, an extension to the * This file is part of Hibernate Spatial, an extension to the
* hibernate ORM solution for geographic data. * hibernate ORM solution for geographic data.
* *
* Copyright © 2007 Geovise BVBA * Copyright © 2007 Geovise BVBA
* Copyright © 2007 K.U. Leuven LRD, Spatial Applications Division, Belgium * Copyright © 2007 K.U. Leuven LRD, Spatial Applications Division, Belgium
* *
@ -43,19 +43,18 @@
/** /**
* Helper class to read settings and properties files. * Helper class to read settings and properties files.
* *
* @author Karel Maesen * @author Karel Maesen
*
*/ */
public class PropertyFileReader { public class PropertyFileReader {
private static final Logger log = LoggerFactory.getLogger(PropertyFileReader.class); private static final Logger log = LoggerFactory.getLogger( PropertyFileReader.class );
/** /**
* pattern for comment lines. If it matches, it is a comment. * pattern for comment lines. If it matches, it is a comment.
*/ */
private static final Pattern nonCommentPattern = Pattern private static final Pattern nonCommentPattern = Pattern
.compile("^([^#]+)"); .compile( "^([^#]+)" );
private InputStream is = null; private InputStream is = null;
@ -64,28 +63,30 @@ public PropertyFileReader(InputStream is) {
} }
public Properties getProperties() throws IOException { public Properties getProperties() throws IOException {
if (is == null) if ( is == null ) {
return null; return null;
}
Properties props = new Properties(); Properties props = new Properties();
props.load(is); props.load( is );
return props; return props;
} }
/** /**
* Returns the non-comment lines in a file. * Returns the non-comment lines in a file.
* *
* @return set of non-comment strings. * @return set of non-comment strings.
*
* @throws IOException * @throws IOException
*/ */
public Set<String> getNonCommentLines() throws IOException { public Set<String> getNonCommentLines() throws IOException {
Set<String> lines = new HashSet<String>(); Set<String> lines = new HashSet<String>();
String line; String line;
BufferedReader reader = new BufferedReader(new InputStreamReader(is)); BufferedReader reader = new BufferedReader( new InputStreamReader( is ) );
while ((line = reader.readLine()) != null) { while ( ( line = reader.readLine() ) != null ) {
line = line.trim(); line = line.trim();
Matcher m = nonCommentPattern.matcher(line); Matcher m = nonCommentPattern.matcher( line );
if (m.find()) { if ( m.find() ) {
lines.add(m.group().trim()); lines.add( m.group().trim() );
} }
} }
return lines; return lines;
@ -94,8 +95,9 @@ public Set<String> getNonCommentLines() throws IOException {
public void close() { public void close() {
try { try {
this.is.close(); this.is.close();
} catch (IOException e) { }
log.warn("Exception when closing PropertyFileReader: " + e); catch ( IOException e ) {
log.warn( "Exception when closing PropertyFileReader: " + e );
} }
} }

View File

@ -12,13 +12,13 @@
*/ */
public class SpatialIntegrator implements Integrator { public class SpatialIntegrator implements Integrator {
@Override @Override
public void integrate(Configuration configuration, SessionFactoryImplementor sessionFactory, SessionFactoryServiceRegistry serviceRegistry) { public void integrate(Configuration configuration, SessionFactoryImplementor sessionFactory, SessionFactoryServiceRegistry serviceRegistry) {
sessionFactory.getTypeResolver().registerTypeOverride(GeometryType.INSTANCE); sessionFactory.getTypeResolver().registerTypeOverride( GeometryType.INSTANCE );
} }
@Override @Override
public void disintegrate(SessionFactoryImplementor sessionFactory, SessionFactoryServiceRegistry serviceRegistry) { public void disintegrate(SessionFactoryImplementor sessionFactory, SessionFactoryServiceRegistry serviceRegistry) {
//do nothing. //do nothing.
} }
} }

View File

@ -33,69 +33,71 @@
//TODO: This class should be removed. //TODO: This class should be removed.
public final class DoubleComparator { public final class DoubleComparator {
private final static int radix = computeRadix(); private final static int radix = computeRadix();
private final static double machinePrecision = computeMachinePrecision(); private final static double machinePrecision = computeMachinePrecision();
private final static double defaultNumericalPrecision = Math private final static double defaultNumericalPrecision = Math
.sqrt(machinePrecision); .sqrt( machinePrecision );
private static int computeRadix() { private static int computeRadix() {
int radix = 0; int radix = 0;
double a = 1.0d; double a = 1.0d;
double tmp1, tmp2; double tmp1, tmp2;
do { do {
a += a; a += a;
tmp1 = a + 1.0d; tmp1 = a + 1.0d;
tmp2 = tmp1 - a; tmp2 = tmp1 - a;
} while (tmp2 - 1.0d != 0.0d); } while ( tmp2 - 1.0d != 0.0d );
double b = 1.0d; double b = 1.0d;
while (radix == 0) { while ( radix == 0 ) {
b += b; b += b;
tmp1 = a + b; tmp1 = a + b;
radix = (int) (tmp1 - a); radix = (int) ( tmp1 - a );
} }
return radix; return radix;
} }
public static int getRadix() { public static int getRadix() {
return radix; return radix;
} }
private static double computeMachinePrecision() { private static double computeMachinePrecision() {
double floatingRadix = getRadix(); double floatingRadix = getRadix();
double inverseRadix = 1.0d / floatingRadix; double inverseRadix = 1.0d / floatingRadix;
double machinePrecision = 1.0d; double machinePrecision = 1.0d;
double tmp = 1.0d + machinePrecision; double tmp = 1.0d + machinePrecision;
while (tmp - 1.0d != 0.0) { while ( tmp - 1.0d != 0.0 ) {
machinePrecision *= inverseRadix; machinePrecision *= inverseRadix;
tmp = 1.0d + machinePrecision; tmp = 1.0d + machinePrecision;
} }
return machinePrecision; return machinePrecision;
} }
public static double getMachinePrecision() { public static double getMachinePrecision() {
return machinePrecision; return machinePrecision;
} }
public static double defaultNumericalPrecision() { public static double defaultNumericalPrecision() {
return defaultNumericalPrecision; return defaultNumericalPrecision;
} }
public static boolean equals(double a, double b) { public static boolean equals(double a, double b) {
return equals(a, b, defaultNumericalPrecision()); return equals( a, b, defaultNumericalPrecision() );
} }
public static boolean equals(double a, double b, double precision) { public static boolean equals(double a, double b, double precision) {
double norm = Math.max(Math.abs(a), Math.abs(b)); double norm = Math.max( Math.abs( a ), Math.abs( b ) );
boolean result = norm < precision || Math.abs(a - b) < precision * norm; boolean result = norm < precision || Math.abs( a - b ) < precision * norm;
return result || (Double.isNaN(a) && Double.isNaN(b)); return result || ( Double.isNaN( a ) && Double.isNaN( b ) );
} }
public static void main(String[] args) { public static void main(String[] args) {
System.out.println("Machine precision = " + getMachinePrecision()); System.out.println( "Machine precision = " + getMachinePrecision() );
System.out.println("Radix = " + getRadix()); System.out.println( "Radix = " + getRadix() );
System.out.println("default numerical precision = " System.out.println(
+ defaultNumericalPrecision()); "default numerical precision = "
} + defaultNumericalPrecision()
);
}
} }

View File

@ -24,56 +24,57 @@
*/ */
package org.hibernate.spatial.mgeom; package org.hibernate.spatial.mgeom;
import java.util.ArrayList;
import java.util.List;
import com.vividsolutions.jts.geom.Coordinate; import com.vividsolutions.jts.geom.Coordinate;
import com.vividsolutions.jts.geom.CoordinateSequence; import com.vividsolutions.jts.geom.CoordinateSequence;
import com.vividsolutions.jts.geom.Geometry; import com.vividsolutions.jts.geom.Geometry;
import com.vividsolutions.jts.geom.Point; import com.vividsolutions.jts.geom.Point;
import java.util.ArrayList;
import java.util.List;
public class EventLocator { public class EventLocator {
/** /**
* Returns the point on the specified MGeometry where its measure equals the specified position. * Returns the point on the specified MGeometry where its measure equals the specified position.
* *
* @return a Point Geometry * @return a Point Geometry
* @throws MGeometryException *
*/ * @throws MGeometryException
public static Point getPointGeometry(MGeometry lrs, double position) */
throws MGeometryException { public static Point getPointGeometry(MGeometry lrs, double position)
if (lrs == null) { throws MGeometryException {
throw new MGeometryException("Non-null MGeometry parameter is required."); if ( lrs == null ) {
} throw new MGeometryException( "Non-null MGeometry parameter is required." );
Coordinate c = lrs.getCoordinateAtM(position); }
Point pnt = lrs.getFactory().createPoint(c); Coordinate c = lrs.getCoordinateAtM( position );
copySRID(lrs.asGeometry(), pnt); Point pnt = lrs.getFactory().createPoint( c );
return pnt; copySRID( lrs.asGeometry(), pnt );
} return pnt;
}
public static MultiMLineString getLinearGeometry(MGeometry lrs, public static MultiMLineString getLinearGeometry(MGeometry lrs,
double begin, double end) throws MGeometryException { double begin, double end) throws MGeometryException {
if (lrs == null) { if ( lrs == null ) {
throw new MGeometryException("Non-null MGeometry parameter is required."); throw new MGeometryException( "Non-null MGeometry parameter is required." );
} }
MGeometryFactory factory = (MGeometryFactory) lrs.getFactory(); MGeometryFactory factory = (MGeometryFactory) lrs.getFactory();
CoordinateSequence[] cs = lrs.getCoordinatesBetween(begin, end); CoordinateSequence[] cs = lrs.getCoordinatesBetween( begin, end );
List<MLineString> linestrings = new ArrayList<MLineString>(cs.length); List<MLineString> linestrings = new ArrayList<MLineString>( cs.length );
for (int i = 0; i < cs.length; i++) { for ( int i = 0; i < cs.length; i++ ) {
MLineString ml; MLineString ml;
if (cs[i].size() >= 2) { if ( cs[i].size() >= 2 ) {
ml = factory.createMLineString(cs[i]); ml = factory.createMLineString( cs[i] );
linestrings.add(ml); linestrings.add( ml );
} }
} }
MultiMLineString result = factory.createMultiMLineString(linestrings.toArray(new MLineString[linestrings.size()])); MultiMLineString result = factory.createMultiMLineString( linestrings.toArray( new MLineString[linestrings.size()] ) );
copySRID(lrs.asGeometry(), result.asGeometry()); copySRID( lrs.asGeometry(), result.asGeometry() );
return result; return result;
} }
public static void copySRID(Geometry source, Geometry target) { public static void copySRID(Geometry source, Geometry target) {
target.setSRID(source.getSRID()); target.setSRID( source.getSRID() );
} }
} }

View File

@ -3,7 +3,7 @@
* *
* This file is part of Hibernate Spatial, an extension to the * This file is part of Hibernate Spatial, an extension to the
* hibernate ORM solution for geographic data. * hibernate ORM solution for geographic data.
* *
* Copyright © 2007 Geovise BVBA * Copyright © 2007 Geovise BVBA
* Copyright © 2007 K.U. Leuven LRD, Spatial Applications Division, Belgium * Copyright © 2007 K.U. Leuven LRD, Spatial Applications Division, Belgium
* *
@ -40,12 +40,12 @@
* While this class extends the Coordinate class, it can be used seamlessly as a * While this class extends the Coordinate class, it can be used seamlessly as a
* substitute in the event that the Measure value is not used. In these cases * substitute in the event that the Measure value is not used. In these cases
* the Measure value shall simply be Double.NaN * the Measure value shall simply be Double.NaN
* *
* @see com.vividsolutions.jts.geom.Coordinate * @see com.vividsolutions.jts.geom.Coordinate
*/ */
public class MCoordinate extends Coordinate { public class MCoordinate extends Coordinate {
/** /**
* *
*/ */
private static final long serialVersionUID = 1L; private static final long serialVersionUID = 1L;
@ -60,25 +60,27 @@ public MCoordinate() {
} }
public MCoordinate(double x, double y, double z, double m) { public MCoordinate(double x, double y, double z, double m) {
super(x, y, z); super( x, y, z );
this.m = m; this.m = m;
} }
public MCoordinate(double x, double y) { public MCoordinate(double x, double y) {
super(x, y); super( x, y );
m = Double.NaN; m = Double.NaN;
} }
public MCoordinate(Coordinate coord) { public MCoordinate(Coordinate coord) {
super(coord); super( coord );
if (coord instanceof MCoordinate) if ( coord instanceof MCoordinate ) {
m = ((MCoordinate) coord).m; m = ( (MCoordinate) coord ).m;
else }
else {
m = Double.NaN; m = Double.NaN;
}
} }
public MCoordinate(MCoordinate coord) { public MCoordinate(MCoordinate coord) {
super(coord); super( coord );
m = coord.m; m = coord.m;
} }
@ -92,22 +94,22 @@ public MCoordinate(MCoordinate coord) {
* imply the desired ordinate in the case where one is using a 2 dimensional * imply the desired ordinate in the case where one is using a 2 dimensional
* geometry with a measure value. Therefore, these constants are highly * geometry with a measure value. Therefore, these constants are highly
* recommended. * recommended.
* *
* @param ordinateIndex * @param ordinateIndex the desired ordinate index.
* the desired ordinate index. *
* @return the value of stored in the ordinate index. Incorrect or unused * @return the value of stored in the ordinate index. Incorrect or unused
* indexes shall return Double.NaN * indexes shall return Double.NaN
*/ */
public double getOrdinate(int ordinateIndex) { public double getOrdinate(int ordinateIndex) {
switch (ordinateIndex) { switch ( ordinateIndex ) {
case CoordinateSequence.X: case CoordinateSequence.X:
return this.x; return this.x;
case CoordinateSequence.Y: case CoordinateSequence.Y:
return this.y; return this.y;
case CoordinateSequence.Z: case CoordinateSequence.Z:
return this.z; return this.z;
case CoordinateSequence.M: case CoordinateSequence.M:
return this.m; return this.m;
} }
return Double.NaN; return Double.NaN;
} }
@ -116,48 +118,46 @@ public double getOrdinate(int ordinateIndex) {
* TODO: I'd like to see this method added to the base Coordinate class Sets * TODO: I'd like to see this method added to the base Coordinate class Sets
* the value for a given ordinate. This should be specified using the * the value for a given ordinate. This should be specified using the
* CoordinateSequence ordinate index constants. * CoordinateSequence ordinate index constants.
* *
* @param ordinateIndex * @param ordinateIndex the desired ordinate index.
* the desired ordinate index. * @param value the new ordinate value
* @param value *
* the new ordinate value * @throws IllegalArgumentException if the ordinateIndex value is incorrect
* @throws IllegalArgumentException
* if the ordinateIndex value is incorrect
* @see #getOrdinate(int) * @see #getOrdinate(int)
*/ */
public void setOrdinate(int ordinateIndex, double value) { public void setOrdinate(int ordinateIndex, double value) {
switch (ordinateIndex) { switch ( ordinateIndex ) {
case CoordinateSequence.X: case CoordinateSequence.X:
this.x = value; this.x = value;
break; break;
case CoordinateSequence.Y: case CoordinateSequence.Y:
this.y = value; this.y = value;
break; break;
case CoordinateSequence.Z: case CoordinateSequence.Z:
this.z = value; this.z = value;
break; break;
case CoordinateSequence.M: case CoordinateSequence.M:
this.m = value; this.m = value;
break; break;
default: default:
throw new IllegalArgumentException("invalid ordinateIndex"); throw new IllegalArgumentException( "invalid ordinateIndex" );
} }
} }
public boolean equals2DWithMeasure(Coordinate other) { public boolean equals2DWithMeasure(Coordinate other) {
boolean result = this.equals2D(other); boolean result = this.equals2D( other );
if (result) { if ( result ) {
MCoordinate mc = convertCoordinate(other); MCoordinate mc = convertCoordinate( other );
result = (Double.compare(this.m, mc.m) == 0); result = ( Double.compare( this.m, mc.m ) == 0 );
} }
return result; return result;
} }
public boolean equals3DWithMeasure(Coordinate other) { public boolean equals3DWithMeasure(Coordinate other) {
boolean result = this.equals3D(other); boolean result = this.equals3D( other );
if (result) { if ( result ) {
MCoordinate mc = convertCoordinate(other); MCoordinate mc = convertCoordinate( other );
result = (Double.compare(this.m, mc.m) == 0); result = ( Double.compare( this.m, mc.m ) == 0 );
} }
return result; return result;
} }
@ -173,9 +173,10 @@ public boolean equals3DWithMeasure(Coordinate other) {
* @see com.vividsolutions.jts.geom.Coordinate#equals(java.lang.Object) * @see com.vividsolutions.jts.geom.Coordinate#equals(java.lang.Object)
*/ */
public boolean equals(Object other) { public boolean equals(Object other) {
if (other instanceof Coordinate) { if ( other instanceof Coordinate ) {
return equals2D((Coordinate) other); return equals2D( (Coordinate) other );
} else { }
else {
return false; return false;
} }
} }
@ -189,85 +190,79 @@ public String toString() {
* coordinate is already an instance of an MCoordinate, then it is simply * coordinate is already an instance of an MCoordinate, then it is simply
* returned. In cases where it is converted, the measure value of the * returned. In cases where it is converted, the measure value of the
* coordinate is initialized to Double.NaN. * coordinate is initialized to Double.NaN.
* *
* @param coordinate * @param coordinate The coordinate to be converted
* The coordinate to be converted *
* @return an instance of MCoordinate corresponding to the * @return an instance of MCoordinate corresponding to the
* <code>coordinate</code> parameter * <code>coordinate</code> parameter
*/ */
public static MCoordinate convertCoordinate(Coordinate coordinate) { public static MCoordinate convertCoordinate(Coordinate coordinate) {
if (coordinate == null) if ( coordinate == null ) {
return null; return null;
if (coordinate instanceof MCoordinate) }
if ( coordinate instanceof MCoordinate ) {
return (MCoordinate) coordinate; return (MCoordinate) coordinate;
return new MCoordinate(coordinate); }
return new MCoordinate( coordinate );
} }
/** /**
* A convenience method for creating a MCoordinate instance where there are * A convenience method for creating a MCoordinate instance where there are
* only 2 coordinates and an lrs measure value. The z value of the * only 2 coordinates and an lrs measure value. The z value of the
* coordinate shall be set to Double.NaN * coordinate shall be set to Double.NaN
* *
* @param x * @param x the x coordinate value
* the x coordinate value * @param y the y coordinate value
* @param y * @param m the lrs measure value
* the y coordinate value *
* @param m
* the lrs measure value
* @return The constructed MCoordinate value * @return The constructed MCoordinate value
*/ */
public static MCoordinate create2dWithMeasure(double x, double y, double m) { public static MCoordinate create2dWithMeasure(double x, double y, double m) {
return new MCoordinate(x, y, Double.NaN, m); return new MCoordinate( x, y, Double.NaN, m );
} }
/** /**
* A convenience method for creating a MCoordinate instance where there are * A convenience method for creating a MCoordinate instance where there are
* only 2 coordinates and an lrs measure value. The z and m value of the * only 2 coordinates and an lrs measure value. The z and m value of the
* coordinate shall be set to Double.NaN * coordinate shall be set to Double.NaN
* *
* @param x * @param x the x coordinate value
* the x coordinate value * @param y the y coordinate value
* @param y *
* the y coordinate value
* @return The constructed MCoordinate value * @return The constructed MCoordinate value
*/ */
public static MCoordinate create2d(double x, double y) { public static MCoordinate create2d(double x, double y) {
return new MCoordinate(x, y, Double.NaN, Double.NaN); return new MCoordinate( x, y, Double.NaN, Double.NaN );
} }
/** /**
* A convenience method for creating a MCoordinate instance where there are * A convenience method for creating a MCoordinate instance where there are
* 3 coordinates and an lrs measure value. * 3 coordinates and an lrs measure value.
* *
* @param x * @param x the x coordinate value
* the x coordinate value * @param y the y coordinate value
* @param y * @param z the z coordinate value
* the y coordinate value * @param m the lrs measure value
* @param z *
* the z coordinate value
* @param m
* the lrs measure value
* @return The constructed MCoordinate value * @return The constructed MCoordinate value
*/ */
public static MCoordinate create3dWithMeasure(double x, double y, double z, public static MCoordinate create3dWithMeasure(double x, double y, double z,
double m) { double m) {
return new MCoordinate(x, y, z, m); return new MCoordinate( x, y, z, m );
} }
/** /**
* A convenience method for creating a MCoordinate instance where there are * A convenience method for creating a MCoordinate instance where there are
* 3 coordinates but no lrs measure value. The m value of the coordinate * 3 coordinates but no lrs measure value. The m value of the coordinate
* shall be set to Double.NaN * shall be set to Double.NaN
* *
* @param x * @param x the x coordinate value
* the x coordinate value * @param y the y coordinate value
* @param y * @param z the z coordinate value
* the y coordinate value *
* @param z
* the z coordinate value
* @return The constructed MCoordinate value * @return The constructed MCoordinate value
*/ */
public static MCoordinate create3d(double x, double y, double z) { public static MCoordinate create3d(double x, double y, double z) {
return new MCoordinate(x, y, z, Double.NaN); return new MCoordinate( x, y, z, Double.NaN );
} }
} }

View File

@ -3,7 +3,7 @@
* *
* This file is part of Hibernate Spatial, an extension to the * This file is part of Hibernate Spatial, an extension to the
* hibernate ORM solution for geographic data. * hibernate ORM solution for geographic data.
* *
* Copyright © 2007 Geovise BVBA * Copyright © 2007 Geovise BVBA
* Copyright © 2007 K.U. Leuven LRD, Spatial Applications Division, Belgium * Copyright © 2007 K.U. Leuven LRD, Spatial Applications Division, Belgium
* *
@ -28,12 +28,12 @@
*/ */
package org.hibernate.spatial.mgeom; package org.hibernate.spatial.mgeom;
import com.vividsolutions.jts.geom.CoordinateSequence;
import com.vividsolutions.jts.geom.Coordinate;
import com.vividsolutions.jts.geom.Envelope;
import java.io.Serializable; import java.io.Serializable;
import com.vividsolutions.jts.geom.Coordinate;
import com.vividsolutions.jts.geom.CoordinateSequence;
import com.vividsolutions.jts.geom.Envelope;
/** /**
* Implements the CoordinateSequence interface. In this implementation, * Implements the CoordinateSequence interface. In this implementation,
* Coordinates returned by #toArray and #get are live -- parties that change * Coordinates returned by #toArray and #get are live -- parties that change
@ -41,7 +41,7 @@
*/ */
public class MCoordinateSequence implements CoordinateSequence, Serializable { public class MCoordinateSequence implements CoordinateSequence, Serializable {
/** /**
* *
*/ */
private static final long serialVersionUID = 1L; private static final long serialVersionUID = 1L;
@ -49,16 +49,16 @@ public class MCoordinateSequence implements CoordinateSequence, Serializable {
public static MCoordinate[] copy(Coordinate[] coordinates) { public static MCoordinate[] copy(Coordinate[] coordinates) {
MCoordinate[] copy = new MCoordinate[coordinates.length]; MCoordinate[] copy = new MCoordinate[coordinates.length];
for (int i = 0; i < coordinates.length; i++) { for ( int i = 0; i < coordinates.length; i++ ) {
copy[i] = new MCoordinate(coordinates[i]); copy[i] = new MCoordinate( coordinates[i] );
} }
return copy; return copy;
} }
public static MCoordinate[] copy(CoordinateSequence coordSeq) { public static MCoordinate[] copy(CoordinateSequence coordSeq) {
MCoordinate[] copy = new MCoordinate[coordSeq.size()]; MCoordinate[] copy = new MCoordinate[coordSeq.size()];
for (int i = 0; i < coordSeq.size(); i++) { for ( int i = 0; i < coordSeq.size(); i++ ) {
copy[i] = new MCoordinate(coordSeq.getCoordinate(i)); copy[i] = new MCoordinate( coordSeq.getCoordinate( i ) );
} }
return copy; return copy;
} }
@ -66,7 +66,7 @@ public static MCoordinate[] copy(CoordinateSequence coordSeq) {
/** /**
* Copy constructor -- simply aliases the input array, for better * Copy constructor -- simply aliases the input array, for better
* performance. * performance.
* *
* @param coordinates * @param coordinates
*/ */
public MCoordinateSequence(MCoordinate[] coordinates) { public MCoordinateSequence(MCoordinate[] coordinates) {
@ -77,32 +77,31 @@ public MCoordinateSequence(MCoordinate[] coordinates) {
* Constructor that makes a copy of an array of Coordinates. Always makes a * Constructor that makes a copy of an array of Coordinates. Always makes a
* copy of the input array, since the actual class of the Coordinates in the * copy of the input array, since the actual class of the Coordinates in the
* input array may be different from MCoordinate. * input array may be different from MCoordinate.
* *
* @param copyCoords * @param copyCoords
*/ */
public MCoordinateSequence(Coordinate[] copyCoords) { public MCoordinateSequence(Coordinate[] copyCoords) {
coordinates = copy(copyCoords); coordinates = copy( copyCoords );
} }
/** /**
* Constructor that makes a copy of a CoordinateSequence. * Constructor that makes a copy of a CoordinateSequence.
* *
* @param coordSeq * @param coordSeq
*/ */
public MCoordinateSequence(CoordinateSequence coordSeq) { public MCoordinateSequence(CoordinateSequence coordSeq) {
coordinates = copy(coordSeq); coordinates = copy( coordSeq );
} }
/** /**
* Constructs a sequence of a given size, populated with new * Constructs a sequence of a given size, populated with new
* {@link MCoordinate}s. * {@link MCoordinate}s.
* *
* @param size * @param size the size of the sequence to create
* the size of the sequence to create
*/ */
public MCoordinateSequence(int size) { public MCoordinateSequence(int size) {
coordinates = new MCoordinate[size]; coordinates = new MCoordinate[size];
for (int i = 0; i < size; i++) { for ( int i = 0; i < size; i++ ) {
coordinates[i] = new MCoordinate(); coordinates[i] = new MCoordinate();
} }
} }
@ -122,12 +121,12 @@ public Coordinate getCoordinate(int i) {
* @see com.vividsolutions.jts.geom.CoordinateSequence#getCoordinateCopy(int) * @see com.vividsolutions.jts.geom.CoordinateSequence#getCoordinateCopy(int)
*/ */
public Coordinate getCoordinateCopy(int index) { public Coordinate getCoordinateCopy(int index) {
return new Coordinate(coordinates[index]); return new Coordinate( coordinates[index] );
} }
/** /**
* @see com.vividsolutions.jts.geom.CoordinateSequence#getCoordinate(int, * @see com.vividsolutions.jts.geom.CoordinateSequence#getCoordinate(int,
* com.vividsolutions.jts.geom.Coordinate) * com.vividsolutions.jts.geom.Coordinate)
*/ */
public void getCoordinate(int index, Coordinate coord) { public void getCoordinate(int index, Coordinate coord) {
coord.x = coordinates[index].x; coord.x = coordinates[index].x;
@ -156,51 +155,51 @@ public double getM(int index) {
} }
/** /**
* @see com.vividsolutions.jts.geom.CoordinateSequence#getOrdinate(int,int) * @see com.vividsolutions.jts.geom.CoordinateSequence#getOrdinate(int, int)
*/ */
public double getOrdinate(int index, int ordinateIndex) { public double getOrdinate(int index, int ordinateIndex) {
switch (ordinateIndex) { switch ( ordinateIndex ) {
case CoordinateSequence.X: case CoordinateSequence.X:
return coordinates[index].x; return coordinates[index].x;
case CoordinateSequence.Y: case CoordinateSequence.Y:
return coordinates[index].y; return coordinates[index].y;
case CoordinateSequence.Z: case CoordinateSequence.Z:
return coordinates[index].z; return coordinates[index].z;
case CoordinateSequence.M: case CoordinateSequence.M:
return coordinates[index].m; return coordinates[index].m;
} }
return Double.NaN; return Double.NaN;
} }
/** /**
* @see com.vividsolutions.jts.geom.CoordinateSequence#setOrdinate(int,int,double) * @see com.vividsolutions.jts.geom.CoordinateSequence#setOrdinate(int, int, double)
*/ */
public void setOrdinate(int index, int ordinateIndex, double value) { public void setOrdinate(int index, int ordinateIndex, double value) {
switch (ordinateIndex) { switch ( ordinateIndex ) {
case CoordinateSequence.X: case CoordinateSequence.X:
coordinates[index].x = value; coordinates[index].x = value;
break; break;
case CoordinateSequence.Y: case CoordinateSequence.Y:
coordinates[index].y = value; coordinates[index].y = value;
break; break;
case CoordinateSequence.Z: case CoordinateSequence.Z:
coordinates[index].z = value; coordinates[index].z = value;
break; break;
case CoordinateSequence.M: case CoordinateSequence.M:
coordinates[index].m = value; coordinates[index].m = value;
break; break;
default: default:
throw new IllegalArgumentException("invalid ordinateIndex"); throw new IllegalArgumentException( "invalid ordinateIndex" );
} }
} }
public Object clone() { public Object clone() {
MCoordinate[] cloneCoordinates = new MCoordinate[size()]; MCoordinate[] cloneCoordinates = new MCoordinate[size()];
for (int i = 0; i < coordinates.length; i++) { for ( int i = 0; i < coordinates.length; i++ ) {
cloneCoordinates[i] = (MCoordinate) coordinates[i].clone(); cloneCoordinates[i] = (MCoordinate) coordinates[i].clone();
} }
return new MCoordinateSequence(cloneCoordinates); return new MCoordinateSequence( cloneCoordinates );
} }
public int size() { public int size() {
@ -212,21 +211,22 @@ public Coordinate[] toCoordinateArray() {
} }
public Envelope expandEnvelope(Envelope env) { public Envelope expandEnvelope(Envelope env) {
for (int i = 0; i < coordinates.length; i++) { for ( int i = 0; i < coordinates.length; i++ ) {
env.expandToInclude(coordinates[i]); env.expandToInclude( coordinates[i] );
} }
return env; return env;
} }
public String toString() { public String toString() {
StringBuffer strBuf = new StringBuffer(); StringBuffer strBuf = new StringBuffer();
strBuf.append("MCoordinateSequence ["); strBuf.append( "MCoordinateSequence [" );
for (int i = 0; i < coordinates.length; i++) { for ( int i = 0; i < coordinates.length; i++ ) {
if (i > 0) if ( i > 0 ) {
strBuf.append(", "); strBuf.append( ", " );
strBuf.append(coordinates[i]); }
strBuf.append( coordinates[i] );
} }
strBuf.append("]"); strBuf.append( "]" );
return strBuf.toString(); return strBuf.toString();
} }
} }

View File

@ -3,7 +3,7 @@
* *
* This file is part of Hibernate Spatial, an extension to the * This file is part of Hibernate Spatial, an extension to the
* hibernate ORM solution for geographic data. * hibernate ORM solution for geographic data.
* *
* Copyright © 2007 Geovise BVBA * Copyright © 2007 Geovise BVBA
* Copyright © 2007 K.U. Leuven LRD, Spatial Applications Division, Belgium * Copyright © 2007 K.U. Leuven LRD, Spatial Applications Division, Belgium
* *
@ -42,7 +42,7 @@ public class MCoordinateSequenceFactory implements CoordinateSequenceFactory,
Serializable { Serializable {
/** /**
* *
*/ */
private static final long serialVersionUID = 1L; private static final long serialVersionUID = 1L;
@ -65,22 +65,24 @@ public static MCoordinateSequenceFactory instance() {
*/ */
public CoordinateSequence create(Coordinate[] coordinates) { public CoordinateSequence create(Coordinate[] coordinates) {
return coordinates instanceof MCoordinate[] ? new MCoordinateSequence( return coordinates instanceof MCoordinate[] ? new MCoordinateSequence(
(MCoordinate[]) coordinates) : new MCoordinateSequence( (MCoordinate[]) coordinates
coordinates); ) : new MCoordinateSequence(
coordinates
);
} }
public CoordinateSequence create(CoordinateSequence coordSeq) { public CoordinateSequence create(CoordinateSequence coordSeq) {
return new MCoordinateSequence(coordSeq); return new MCoordinateSequence( coordSeq );
} }
/** /**
* Creates a MCoordinateSequence instance initialized to the size parameter. * Creates a MCoordinateSequence instance initialized to the size parameter.
* Note that the dimension argument is ignored. * Note that the dimension argument is ignored.
* *
* @see com.vividsolutions.jts.geom.CoordinateSequenceFactory#create(int,int) * @see com.vividsolutions.jts.geom.CoordinateSequenceFactory#create(int, int)
*/ */
public CoordinateSequence create(int size, int dimension) { public CoordinateSequence create(int size, int dimension) {
return new MCoordinateSequence(size); return new MCoordinateSequence( size );
} }
} }

View File

@ -3,7 +3,7 @@
* *
* This file is part of Hibernate Spatial, an extension to the * This file is part of Hibernate Spatial, an extension to the
* hibernate ORM solution for geographic data. * hibernate ORM solution for geographic data.
* *
* Copyright © 2007 Geovise BVBA * Copyright © 2007 Geovise BVBA
* Copyright © 2007 K.U. Leuven LRD, Spatial Applications Division, Belgium * Copyright © 2007 K.U. Leuven LRD, Spatial Applications Division, Belgium
* *
@ -28,16 +28,16 @@
*/ */
package org.hibernate.spatial.mgeom; package org.hibernate.spatial.mgeom;
import java.io.Serializable;
import com.vividsolutions.jts.geom.Coordinate; import com.vividsolutions.jts.geom.Coordinate;
import com.vividsolutions.jts.geom.GeometryFactory;
import com.vividsolutions.jts.geom.CoordinateSequence; import com.vividsolutions.jts.geom.CoordinateSequence;
import com.vividsolutions.jts.geom.Geometry; import com.vividsolutions.jts.geom.Geometry;
import com.vividsolutions.jts.geom.GeometryFactory;
import java.io.Serializable;
/** /**
* Defines geometries that carry measures in their CoordinateSequence. * Defines geometries that carry measures in their CoordinateSequence.
* *
* @author Karel Maesen * @author Karel Maesen
*/ */
@ -65,19 +65,18 @@ public interface MGeometry extends Cloneable, Serializable {
/** /**
* Returns the measure value at the Coordinate * Returns the measure value at the Coordinate
* *
* @param c * @param c the Coordinate for which the measure value is sought
* the Coordinate for which the measure value is sought * @param tolerance distance to the MGeometry within which Coordinate c has to lie
* @param tolerance *
* distance to the MGeometry within which Coordinate c has to lie
* @return the measure value if Coordinate c is within tolerance of the * @return the measure value if Coordinate c is within tolerance of the
* Geometry, else Double.NaN * Geometry, else Double.NaN
* <p> * <p>
* When the geometry is a ring or is self-intersecting more * When the geometry is a ring or is self-intersecting more
* coordinates may be determined by one coordinate. In that case, * coordinates may be determined by one coordinate. In that case,
* the lowest measure is returned. * the lowest measure is returned.
* @throws MGeometryException *
* when this MGeometry is not monotone * @throws MGeometryException when this MGeometry is not monotone
*/ */
public double getMatCoordinate(Coordinate c, double tolerance) public double getMatCoordinate(Coordinate c, double tolerance)
throws MGeometryException; throws MGeometryException;
@ -85,58 +84,57 @@ public double getMatCoordinate(Coordinate c, double tolerance)
/** /**
* Builds measures along the Geometry based on the length from the beginning * Builds measures along the Geometry based on the length from the beginning
* (first coordinate) of the Geometry. * (first coordinate) of the Geometry.
* *
* @param keepBeginMeasure - * @param keepBeginMeasure -
* if true, the measure of the first coordinate is maintained and * if true, the measure of the first coordinate is maintained and
* used as start value, unless this measure is Double.NaN * used as start value, unless this measure is Double.NaN
*/ */
public void measureOnLength(boolean keepBeginMeasure); public void measureOnLength(boolean keepBeginMeasure);
/** /**
* Returns the Coordinate along the Geometry at the measure value * Returns the Coordinate along the Geometry at the measure value
* *
* @param m * @param m measure value
* measure value *
* @return the Coordinate if m is on the MGeometry otherwise null * @return the Coordinate if m is on the MGeometry otherwise null
* @throws MGeometryException *
* when MGeometry is not monotone * @throws MGeometryException when MGeometry is not monotone
*/ */
public Coordinate getCoordinateAtM(double m) throws MGeometryException; public Coordinate getCoordinateAtM(double m) throws MGeometryException;
/** /**
* Returns the coordinatesequence(s) containing all coordinates between the * Returns the coordinatesequence(s) containing all coordinates between the
* begin and end measures. * begin and end measures.
* *
* @param begin * @param begin begin measure
* begin measure * @param end end measure
* @param end *
* end measure
* @return an array containing all coordinatesequences in order between * @return an array containing all coordinatesequences in order between
* begin and end. Each CoordinateSequence covers a contiguous * begin and end. Each CoordinateSequence covers a contiguous
* stretch of the MGeometry. * stretch of the MGeometry.
* @throws MGeometryException *
* when this MGeometry is not monotone * @throws MGeometryException when this MGeometry is not monotone
*/ */
public CoordinateSequence[] getCoordinatesBetween(double begin, double end) public CoordinateSequence[] getCoordinatesBetween(double begin, double end)
throws MGeometryException; throws MGeometryException;
/** /**
* Returns the GeometryFactory of the MGeometry * Returns the GeometryFactory of the MGeometry
* *
* @return the GeometryFactory of this MGeometry * @return the GeometryFactory of this MGeometry
*/ */
public GeometryFactory getFactory(); public GeometryFactory getFactory();
/** /**
* Returns the minimum M-value of the MGeometry * Returns the minimum M-value of the MGeometry
* *
* @return the minimum M-value * @return the minimum M-value
*/ */
public double getMinM(); public double getMinM();
/** /**
* Returns the maximum M-value of the MGeometry * Returns the maximum M-value of the MGeometry
* *
* @return the maximum M-value * @return the maximum M-value
*/ */
public double getMaxM(); public double getMaxM();
@ -155,7 +153,7 @@ public CoordinateSequence[] getCoordinatesBetween(double begin, double end)
* <li> [0,1,1,2,3] - Non-strict Monotone Increasing * <li> [0,1,1,2,3] - Non-strict Monotone Increasing
* <li> [5,3,3,0] - Non-strict Monotone Decreasing * <li> [5,3,3,0] - Non-strict Monotone Decreasing
* </ul> * </ul>
* *
* @return true if the coordinates in the CoordinateSequence of the geometry * @return true if the coordinates in the CoordinateSequence of the geometry
* are monotone. * are monotone.
*/ */
@ -175,13 +173,13 @@ public CoordinateSequence[] getCoordinatesBetween(double begin, double end)
// */ // */
// public boolean isStrictMonotone(); // public boolean isStrictMonotone();
/** /**
* Returns this <code>MGeometry</code> as a <code>Geometry</code>. * Returns this <code>MGeometry</code> as a <code>Geometry</code>.
* *
* Modifying the returned <code>Geometry</code> will result in internal state changes. * Modifying the returned <code>Geometry</code> will result in internal state changes.
* *
* @return this object as a Geometry. * @return this object as a Geometry.
*/ */
public Geometry asGeometry(); public Geometry asGeometry();
} }

View File

@ -3,7 +3,7 @@
* *
* This file is part of Hibernate Spatial, an extension to the * This file is part of Hibernate Spatial, an extension to the
* hibernate ORM solution for geographic data. * hibernate ORM solution for geographic data.
* *
* Copyright © 2007 Geovise BVBA * Copyright © 2007 Geovise BVBA
* Copyright © 2007 K.U. Leuven LRD, Spatial Applications Division, Belgium * Copyright © 2007 K.U. Leuven LRD, Spatial Applications Division, Belgium
* *
@ -30,13 +30,11 @@
/** /**
* @author Karel Maesen * @author Karel Maesen
*
*
*/ */
public class MGeometryException extends Exception { public class MGeometryException extends Exception {
/** /**
* *
*/ */
private static final long serialVersionUID = 1L; private static final long serialVersionUID = 1L;
@ -50,7 +48,7 @@ public class MGeometryException extends Exception {
private final int type; private final int type;
public MGeometryException(String s) { public MGeometryException(String s) {
super(s); super( s );
type = 0; type = 0;
} }
@ -59,8 +57,8 @@ public MGeometryException(int type) {
this.type = type; this.type = type;
} }
public MGeometryException(int type, String msg) { public MGeometryException(int type, String msg) {
super(msg); super( msg );
this.type = type; this.type = type;
} }

View File

@ -3,7 +3,7 @@
* *
* This file is part of Hibernate Spatial, an extension to the * This file is part of Hibernate Spatial, an extension to the
* hibernate ORM solution for geographic data. * hibernate ORM solution for geographic data.
* *
* Copyright © 2007 Geovise BVBA * Copyright © 2007 Geovise BVBA
* Copyright © 2007 K.U. Leuven LRD, Spatial Applications Division, Belgium * Copyright © 2007 K.U. Leuven LRD, Spatial Applications Division, Belgium
* *
@ -28,77 +28,83 @@
*/ */
package org.hibernate.spatial.mgeom; package org.hibernate.spatial.mgeom;
import com.vividsolutions.jts.geom.*; import com.vividsolutions.jts.geom.CoordinateSequence;
import com.vividsolutions.jts.geom.GeometryFactory;
import com.vividsolutions.jts.geom.PrecisionModel;
/** /**
* Extension of the GeometryFactory for constructing Geometries with Measure * Extension of the GeometryFactory for constructing Geometries with Measure
* support. * support.
* *
* @see com.vividsolutions.jts.geom.GeometryFactory * @see com.vividsolutions.jts.geom.GeometryFactory
*/ */
public class MGeometryFactory extends GeometryFactory { public class MGeometryFactory extends GeometryFactory {
/** /**
* *
*/ */
private static final long serialVersionUID = 1L; private static final long serialVersionUID = 1L;
public MGeometryFactory(PrecisionModel precisionModel, int SRID, public MGeometryFactory(PrecisionModel precisionModel, int SRID,
MCoordinateSequenceFactory coordinateSequenceFactory) { MCoordinateSequenceFactory coordinateSequenceFactory) {
super(precisionModel, SRID, coordinateSequenceFactory); super( precisionModel, SRID, coordinateSequenceFactory );
} }
public MGeometryFactory(MCoordinateSequenceFactory coordinateSequenceFactory) { public MGeometryFactory(MCoordinateSequenceFactory coordinateSequenceFactory) {
super(coordinateSequenceFactory); super( coordinateSequenceFactory );
} }
public MGeometryFactory(PrecisionModel precisionModel) { public MGeometryFactory(PrecisionModel precisionModel) {
this(precisionModel, 0, MCoordinateSequenceFactory.instance()); this( precisionModel, 0, MCoordinateSequenceFactory.instance() );
} }
public MGeometryFactory(PrecisionModel precisionModel, int SRID) { public MGeometryFactory(PrecisionModel precisionModel, int SRID) {
this(precisionModel, SRID, MCoordinateSequenceFactory.instance()); this( precisionModel, SRID, MCoordinateSequenceFactory.instance() );
} }
public MGeometryFactory() { public MGeometryFactory() {
this(new PrecisionModel(), 0); this( new PrecisionModel(), 0 );
} }
/** /**
* Constructs a MLineString using the given Coordinates; a null or empty * Constructs a MLineString using the given Coordinates; a null or empty
* array will create an empty MLineString. * array will create an empty MLineString.
* *
* @param coordinates * @param coordinates array of MCoordinate defining this geometry's vertices
* array of MCoordinate defining this geometry's vertices *
* @see #createLineString(com.vividsolutions.jts.geom.Coordinate[])
* @return An instance of MLineString containing the coordinates * @return An instance of MLineString containing the coordinates
*
* @see #createLineString(com.vividsolutions.jts.geom.Coordinate[])
*/ */
public MLineString createMLineString(MCoordinate[] coordinates) { public MLineString createMLineString(MCoordinate[] coordinates) {
return createMLineString(coordinates != null ? getCoordinateSequenceFactory() return createMLineString(
.create(coordinates) coordinates != null ? getCoordinateSequenceFactory()
: null); .create( coordinates )
: null
);
} }
public MultiMLineString createMultiMLineString(MLineString[] mlines, public MultiMLineString createMultiMLineString(MLineString[] mlines,
double mGap) { double mGap) {
return new MultiMLineString(mlines, mGap, this); return new MultiMLineString( mlines, mGap, this );
} }
public MultiMLineString createMultiMLineString(MLineString[] mlines) { public MultiMLineString createMultiMLineString(MLineString[] mlines) {
return new MultiMLineString(mlines, 0.0d, this); return new MultiMLineString( mlines, 0.0d, this );
} }
/** /**
* Creates a MLineString using the given CoordinateSequence; a null or empty * Creates a MLineString using the given CoordinateSequence; a null or empty
* CoordinateSequence will create an empty MLineString. * CoordinateSequence will create an empty MLineString.
* *
* @param coordinates * @param coordinates a CoordinateSequence possibly empty, or null
* a CoordinateSequence possibly empty, or null *
* @return An MLineString instance based on the <code>coordinates</code> * @return An MLineString instance based on the <code>coordinates</code>
*
* @see #createLineString(com.vividsolutions.jts.geom.CoordinateSequence) * @see #createLineString(com.vividsolutions.jts.geom.CoordinateSequence)
*/ */
public MLineString createMLineString(CoordinateSequence coordinates) { public MLineString createMLineString(CoordinateSequence coordinates) {
return new MLineString(coordinates, this); return new MLineString( coordinates, this );
} }
} }

View File

@ -24,256 +24,273 @@
*/ */
package org.hibernate.spatial.mgeom; package org.hibernate.spatial.mgeom;
import com.vividsolutions.jts.geom.*; import com.vividsolutions.jts.geom.Coordinate;
import com.vividsolutions.jts.geom.CoordinateSequence;
import com.vividsolutions.jts.geom.Geometry;
import com.vividsolutions.jts.geom.GeometryFactory;
import com.vividsolutions.jts.geom.MultiLineString;
public class MultiMLineString extends MultiLineString implements MGeometry { public class MultiMLineString extends MultiLineString implements MGeometry {
/** /**
* *
*/ */
private static final long serialVersionUID = 1L; private static final long serialVersionUID = 1L;
private final double mGap; // difference in m between end of one part and private final double mGap; // difference in m between end of one part and
private boolean monotone = false; private boolean monotone = false;
private boolean strictMonotone = false; private boolean strictMonotone = false;
/** /**
* @param MlineStrings the <code>MLineString</code>s for this * @param MlineStrings the <code>MLineString</code>s for this
* <code>MultiMLineString</code>, or <code>null</code> or an * <code>MultiMLineString</code>, or <code>null</code> or an
* empty array to create the empty geometry. Elements may be * empty array to create the empty geometry. Elements may be
* empty <code>LineString</code>s, but not <code>null</code>s. * empty <code>LineString</code>s, but not <code>null</code>s.
*/ */
public MultiMLineString(MLineString[] MlineStrings, double mGap, public MultiMLineString(MLineString[] MlineStrings, double mGap,
GeometryFactory factory) { GeometryFactory factory) {
super(MlineStrings, factory); super( MlineStrings, factory );
this.mGap = mGap; this.mGap = mGap;
determineMonotone(); determineMonotone();
} }
/** /**
* TODO Improve this, and add more unit tests * TODO Improve this, and add more unit tests
*/ */
private void determineMonotone() { private void determineMonotone() {
this.monotone = true; this.monotone = true;
this.strictMonotone = true; this.strictMonotone = true;
if (this.isEmpty()) { if ( this.isEmpty() ) {
return; return;
} }
int mdir = MGeometry.CONSTANT; int mdir = MGeometry.CONSTANT;
for (int i = 0; i < this.geometries.length; i++) { for ( int i = 0; i < this.geometries.length; i++ ) {
MLineString ml = (MLineString) this.geometries[0]; MLineString ml = (MLineString) this.geometries[0];
if (!ml.isEmpty()) { if ( !ml.isEmpty() ) {
mdir = ml.getMeasureDirection(); mdir = ml.getMeasureDirection();
break; break;
} }
} }
for (int i = 0; i < this.geometries.length; i++) { for ( int i = 0; i < this.geometries.length; i++ ) {
MLineString ml = (MLineString) this.geometries[i]; MLineString ml = (MLineString) this.geometries[i];
if (ml.isEmpty()) continue; if ( ml.isEmpty() ) {
// check whether mlinestrings are all pointing in same direction, continue;
// and }
// are monotone // check whether mlinestrings are all pointing in same direction,
if (!ml.isMonotone(false) // and
|| (ml.getMeasureDirection() != mdir && !(ml // are monotone
.getMeasureDirection() == MGeometry.CONSTANT))) { if ( !ml.isMonotone( false )
this.monotone = false; || ( ml.getMeasureDirection() != mdir && !( ml
break; .getMeasureDirection() == MGeometry.CONSTANT ) ) ) {
} this.monotone = false;
break;
}
if (!ml.isMonotone(true) || (ml.getMeasureDirection() != mdir)) { if ( !ml.isMonotone( true ) || ( ml.getMeasureDirection() != mdir ) ) {
this.strictMonotone = false; this.strictMonotone = false;
break; break;
} }
// check whether the geometry measures do not overlap or // check whether the geometry measures do not overlap or
// are inconsistent with previous parts // are inconsistent with previous parts
if (i > 0) { if ( i > 0 ) {
MLineString mlp = (MLineString) this.geometries[i - 1]; MLineString mlp = (MLineString) this.geometries[i - 1];
if (mdir == MGeometry.INCREASING) { if ( mdir == MGeometry.INCREASING ) {
if (mlp.getMaxM() > ml.getMinM()) { if ( mlp.getMaxM() > ml.getMinM() ) {
monotone = false; monotone = false;
} else if (mlp.getMaxM() >= ml.getMinM()) { }
strictMonotone = false; else if ( mlp.getMaxM() >= ml.getMinM() ) {
} strictMonotone = false;
} else { }
if (mlp.getMinM() < ml.getMaxM()) { }
monotone = false; else {
} else if (mlp.getMinM() <= ml.getMaxM()) { if ( mlp.getMinM() < ml.getMaxM() ) {
strictMonotone = false; monotone = false;
} }
} else if ( mlp.getMinM() <= ml.getMaxM() ) {
strictMonotone = false;
}
}
} }
} }
if (!monotone) { if ( !monotone ) {
this.strictMonotone = false; this.strictMonotone = false;
} }
} }
protected void geometryChangedAction() { protected void geometryChangedAction() {
determineMonotone(); determineMonotone();
} }
public String getGeometryType() { public String getGeometryType() {
return "MultiMLineString"; return "MultiMLineString";
} }
public double getMGap() { public double getMGap() {
return this.mGap; return this.mGap;
} }
public double getMatCoordinate(Coordinate co, double tolerance) public double getMatCoordinate(Coordinate co, double tolerance)
throws MGeometryException { throws MGeometryException {
if (!this.isMonotone(false)) { if ( !this.isMonotone( false ) ) {
throw new MGeometryException( throw new MGeometryException(
MGeometryException.OPERATION_REQUIRES_MONOTONE); MGeometryException.OPERATION_REQUIRES_MONOTONE
} );
}
double mval = Double.NaN; double mval = Double.NaN;
double dist = Double.POSITIVE_INFINITY; double dist = Double.POSITIVE_INFINITY;
com.vividsolutions.jts.geom.Point p = this.getFactory().createPoint(co); com.vividsolutions.jts.geom.Point p = this.getFactory().createPoint( co );
// find points within tolerance for getMatCoordinate // find points within tolerance for getMatCoordinate
for (int i = 0; i < this.getNumGeometries(); i++) { for ( int i = 0; i < this.getNumGeometries(); i++ ) {
MLineString ml = (MLineString) this.getGeometryN(i); MLineString ml = (MLineString) this.getGeometryN( i );
// go to next MLineString if the input point is beyond tolerance // go to next MLineString if the input point is beyond tolerance
if (ml.distance(p) > tolerance) if ( ml.distance( p ) > tolerance ) {
continue; continue;
}
MCoordinate mc = ml.getClosestPoint(co, tolerance); MCoordinate mc = ml.getClosestPoint( co, tolerance );
if (mc != null) { if ( mc != null ) {
double d = mc.distance(co); double d = mc.distance( co );
if (d <= tolerance && d < dist) { if ( d <= tolerance && d < dist ) {
dist = d; dist = d;
mval = mc.m; mval = mc.m;
} }
} }
} }
return mval; return mval;
} }
public Object clone() { public Object clone() {
MultiLineString ml = (MultiLineString) super.clone(); MultiLineString ml = (MultiLineString) super.clone();
return ml; return ml;
} }
public void measureOnLength(boolean keepBeginMeasure) { public void measureOnLength(boolean keepBeginMeasure) {
double startM = 0.0; double startM = 0.0;
for (int i = 0; i < this.getNumGeometries(); i++) { for ( int i = 0; i < this.getNumGeometries(); i++ ) {
MLineString ml = (MLineString) this.getGeometryN(i); MLineString ml = (MLineString) this.getGeometryN( i );
if (i == 0) { if ( i == 0 ) {
ml.measureOnLength(keepBeginMeasure); ml.measureOnLength( keepBeginMeasure );
} else { }
ml.measureOnLength(false); else {
} ml.measureOnLength( false );
if (startM != 0.0) { }
ml.shiftMeasure(startM); if ( startM != 0.0 ) {
} ml.shiftMeasure( startM );
startM += ml.getLength() + mGap; }
} startM += ml.getLength() + mGap;
this.geometryChanged(); }
} this.geometryChanged();
}
/* /*
* (non-Javadoc) * (non-Javadoc)
* *
* @see org.hibernate.spatial.mgeom.MGeometry#getCoordinateAtM(double) * @see org.hibernate.spatial.mgeom.MGeometry#getCoordinateAtM(double)
*/ */
public Coordinate getCoordinateAtM(double m) throws MGeometryException { public Coordinate getCoordinateAtM(double m) throws MGeometryException {
if (!this.isMonotone(false)) { if ( !this.isMonotone( false ) ) {
throw new MGeometryException( throw new MGeometryException(
MGeometryException.OPERATION_REQUIRES_MONOTONE); MGeometryException.OPERATION_REQUIRES_MONOTONE
} );
}
Coordinate c = null; Coordinate c = null;
for (int i = 0; i < this.getNumGeometries(); i++) { for ( int i = 0; i < this.getNumGeometries(); i++ ) {
MGeometry mg = (MGeometry) this.getGeometryN(i); MGeometry mg = (MGeometry) this.getGeometryN( i );
c = mg.getCoordinateAtM(m); c = mg.getCoordinateAtM( m );
if (c != null) { if ( c != null ) {
return c; return c;
} }
} }
return null; return null;
} }
public CoordinateSequence[] getCoordinatesBetween(double begin, double end) public CoordinateSequence[] getCoordinatesBetween(double begin, double end)
throws MGeometryException { throws MGeometryException {
if (!this.isMonotone(false)) { if ( !this.isMonotone( false ) ) {
throw new MGeometryException( throw new MGeometryException(
MGeometryException.OPERATION_REQUIRES_MONOTONE, MGeometryException.OPERATION_REQUIRES_MONOTONE,
"Operation requires geometry with monotonic measures"); "Operation requires geometry with monotonic measures"
} );
}
if (this.isEmpty()) if ( this.isEmpty() ) {
return null; return null;
}
java.util.ArrayList<CoordinateSequence> ar = new java.util.ArrayList<CoordinateSequence>(); java.util.ArrayList<CoordinateSequence> ar = new java.util.ArrayList<CoordinateSequence>();
for (int i = 0; i < this.getNumGeometries(); i++) { for ( int i = 0; i < this.getNumGeometries(); i++ ) {
MLineString ml = (MLineString) this.getGeometryN(i); MLineString ml = (MLineString) this.getGeometryN( i );
for (CoordinateSequence cs : ml.getCoordinatesBetween(begin, end)) { for ( CoordinateSequence cs : ml.getCoordinatesBetween( begin, end ) ) {
if (cs.size() > 0) { if ( cs.size() > 0 ) {
ar.add(cs); ar.add( cs );
} }
} }
} }
return ar.toArray(new CoordinateSequence[ar.size()]); return ar.toArray( new CoordinateSequence[ar.size()] );
} }
/* /*
* (non-Javadoc) * (non-Javadoc)
* *
* @see org.hibernate.spatial.mgeom.MGeometry#getMinM() * @see org.hibernate.spatial.mgeom.MGeometry#getMinM()
*/ */
public double getMinM() { public double getMinM() {
double minM = Double.POSITIVE_INFINITY; double minM = Double.POSITIVE_INFINITY;
for (int i = 0; i < this.getNumGeometries(); i++) { for ( int i = 0; i < this.getNumGeometries(); i++ ) {
MLineString ml = (MLineString) this.getGeometryN(i); MLineString ml = (MLineString) this.getGeometryN( i );
double d = ml.getMinM(); double d = ml.getMinM();
if (d < minM) if ( d < minM ) {
minM = d; minM = d;
} }
return minM; }
} return minM;
}
/* /*
* (non-Javadoc) * (non-Javadoc)
* *
* @see org.hibernate.spatial.mgeom.MGeometry#getMaxM() * @see org.hibernate.spatial.mgeom.MGeometry#getMaxM()
*/ */
public double getMaxM() { public double getMaxM() {
double maxM = Double.NEGATIVE_INFINITY; double maxM = Double.NEGATIVE_INFINITY;
for (int i = 0; i < this.getNumGeometries(); i++) { for ( int i = 0; i < this.getNumGeometries(); i++ ) {
MLineString ml = (MLineString) this.getGeometryN(i); MLineString ml = (MLineString) this.getGeometryN( i );
double d = ml.getMaxM(); double d = ml.getMaxM();
if (d > maxM) if ( d > maxM ) {
maxM = d; maxM = d;
} }
return maxM; }
} return maxM;
}
/* /*
* (non-Javadoc) * (non-Javadoc)
* *
* @see org.hibernate.spatial.mgeom.MGeometry#isMonotone() * @see org.hibernate.spatial.mgeom.MGeometry#isMonotone()
*/ */
public boolean isMonotone(boolean strictMonotone) { public boolean isMonotone(boolean strictMonotone) {
return strictMonotone ? this.strictMonotone : monotone; return strictMonotone ? this.strictMonotone : monotone;
} }
public Geometry asGeometry() { public Geometry asGeometry() {
return this; return this;
} }
} }

View File

@ -40,31 +40,32 @@
public interface SpatialDialectProvider { public interface SpatialDialectProvider {
/** /**
* create Spatial Dialect with the provided name. * create Spatial Dialect with the provided name.
* *
* @param dialect Name of the dialect to create. * @param dialect Name of the dialect to create.
* @return a SpatialDialect *
*/ * @return a SpatialDialect
public SpatialDialect createSpatialDialect(String dialect); */
public SpatialDialect createSpatialDialect(String dialect);
/** /**
* Returns the default dialect for this provider. * Returns the default dialect for this provider.
* *
* @return The Default Dialect provided by the implementation. * @return The Default Dialect provided by the implementation.
* <p/> * <p/>
* Implementations should never return null for this method. * Implementations should never return null for this method.
*/ */
public SpatialDialect getDefaultDialect(); public SpatialDialect getDefaultDialect();
/** /**
* Returns the Dialect names * Returns the Dialect names
* <p/> * <p/>
* This method must return the canonical class names of the Spatialdialect * This method must return the canonical class names of the Spatialdialect
* implementations that this provider provides. * implementations that this provider provides.
* *
* @return array of dialect names. * @return array of dialect names.
*/ */
public String[] getSupportedDialects(); public String[] getSupportedDialects();
} }

View File

@ -1,6 +1,11 @@
package org.hibernate.spatial.util; package org.hibernate.spatial.util;
import java.sql.*; import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
/** /**
* @author Karel Maesen, Geovise BVBA * @author Karel Maesen, Geovise BVBA
@ -9,111 +14,116 @@
public class MetadataInspector { public class MetadataInspector {
static String driver; static String driver;
static String dbURI; static String dbURI;
static String userName; static String userName;
static String passWord; static String passWord;
static String table; static String table;
public static void main(String[] args) throws Exception { public static void main(String[] args) throws Exception {
readArgs(args); readArgs( args );
// Connection reference // Connection reference
Connection conn = null; Connection conn = null;
try { try {
// Load database driver // Load database driver
try { try {
Class.forName(driver); Class.forName( driver );
} catch (Exception e) { }
System.err.println(e); catch ( Exception e ) {
System.exit(1); System.err.println( e );
} System.exit( 1 );
}
// Make connection // Make connection
conn = DriverManager.getConnection(dbURI, userName, passWord); conn = DriverManager.getConnection( dbURI, userName, passWord );
Statement stmt = conn.createStatement(); Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * from " + table); ResultSet rs = stmt.executeQuery( "SELECT * from " + table );
// Get the ResultSet meta data // Get the ResultSet meta data
ResultSetMetaData rmd = rs.getMetaData(); ResultSetMetaData rmd = rs.getMetaData();
rs.next(); rs.next();
if (rmd == null) { if ( rmd == null ) {
System.out.println("ResultSet meta data not available"); System.out.println( "ResultSet meta data not available" );
} else { }
else {
int columnCount = rmd.getColumnCount(); int columnCount = rmd.getColumnCount();
// Display number of Columns in the ResultSet // Display number of Columns in the ResultSet
System.out.println("Number of Columns in the table : " + columnCount); System.out.println( "Number of Columns in the table : " + columnCount );
for (int i = 1; i <= columnCount; i++) { for ( int i = 1; i <= columnCount; i++ ) {
// Display number of Column name // Display number of Column name
System.out.println("Column Name : " + rmd.getColumnName(i)); System.out.println( "Column Name : " + rmd.getColumnName( i ) );
// Display number of Column Type // Display number of Column Type
System.out.println("Column TypeName : " + rmd.getColumnTypeName(i)); System.out.println( "Column TypeName : " + rmd.getColumnTypeName( i ) );
System.out.println("Column type : " + rmd.getColumnType(i)); System.out.println( "Column type : " + rmd.getColumnType( i ) );
Object o = rs.getObject(i); Object o = rs.getObject( i );
System.out.println("Column object class: " + o.getClass().getName()); System.out.println( "Column object class: " + o.getClass().getName() );
// Display if Column can be NOT NULL // Display if Column can be NOT NULL
switch (rmd.isNullable(i)) { switch ( rmd.isNullable( i ) ) {
case ResultSetMetaData.columnNoNulls: case ResultSetMetaData.columnNoNulls:
System.out.println(" NOT NULL"); System.out.println( " NOT NULL" );
break; break;
case ResultSetMetaData.columnNullable: case ResultSetMetaData.columnNullable:
System.out.println(" NULLABLE"); System.out.println( " NULLABLE" );
break; break;
case ResultSetMetaData.columnNullableUnknown: case ResultSetMetaData.columnNullableUnknown:
System.out.println(" NULLABLE Unkown"); System.out.println( " NULLABLE Unkown" );
} }
System.out.println(); System.out.println();
} }
} }
} finally { }
finally {
// Close connection // Close connection
if (conn != null) { if ( conn != null ) {
try { try {
conn.close(); conn.close();
} catch (SQLException ex) { }
System.out.println("Error in closing Conection"); catch ( SQLException ex ) {
} System.out.println( "Error in closing Conection" );
} }
} }
} }
}
// private static String getJavaJDBCTypeName(int type){ // private static String getJavaJDBCTypeName(int type){
// //
// } // }
private static void readArgs(String[] args) { private static void readArgs(String[] args) {
try { try {
driver = args[0]; driver = args[0];
dbURI = args[1]; dbURI = args[1];
userName = args[2]; userName = args[2];
passWord = args[3]; passWord = args[3];
table = args[4]; table = args[4];
} catch (Exception e) { }
System.out.printf("Usage: metadataInspector <driver> <dbUri> <userName> <passWord> <table>"); catch ( Exception e ) {
System.exit(1); System.out.printf( "Usage: metadataInspector <driver> <dbUri> <userName> <passWord> <table>" );
} System.exit( 1 );
}
} }
} }

View File

@ -1,20 +1,28 @@
package org.hibernate.spatial; package org.hibernate.spatial;
import com.vividsolutions.jts.geom.Geometry;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.hibernate.spatial.test.*;
import org.hibernate.testing.junit4.BaseCoreFunctionalTestCase;
import org.slf4j.Logger;
import java.sql.Connection; import java.sql.Connection;
import java.sql.SQLException; import java.sql.SQLException;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import static org.junit.Assert.*; import com.vividsolutions.jts.geom.Geometry;
import org.slf4j.Logger;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.hibernate.spatial.test.AbstractExpectationsFactory;
import org.hibernate.spatial.test.DataSourceUtils;
import org.hibernate.spatial.test.GeometryEquality;
import org.hibernate.spatial.test.TestData;
import org.hibernate.spatial.test.TestSupport;
import org.hibernate.testing.junit4.BaseCoreFunctionalTestCase;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
/** /**
* @author Karel Maesen, Geovise BVBA * @author Karel Maesen, Geovise BVBA
@ -22,141 +30,157 @@
*/ */
public abstract class SpatialFunctionalTestCase extends BaseCoreFunctionalTestCase { public abstract class SpatialFunctionalTestCase extends BaseCoreFunctionalTestCase {
protected TestData testData; protected TestData testData;
protected DataSourceUtils dataSourceUtils; protected DataSourceUtils dataSourceUtils;
protected GeometryEquality geometryEquality; protected GeometryEquality geometryEquality;
protected AbstractExpectationsFactory expectationsFactory; protected AbstractExpectationsFactory expectationsFactory;
public void insertTestData() { public void insertTestData() {
try { try {
dataSourceUtils.insertTestData(testData); dataSourceUtils.insertTestData( testData );
} catch (SQLException e) { }
throw new RuntimeException(e); catch ( SQLException e ) {
} throw new RuntimeException( e );
} }
}
public void deleteAllTestEntities() { public void deleteAllTestEntities() {
Session session = null; Session session = null;
Transaction tx = null; Transaction tx = null;
try { try {
session = openSession(); session = openSession();
tx = session.beginTransaction(); tx = session.beginTransaction();
String hql = "delete from GeomEntity"; String hql = "delete from GeomEntity";
Query q = session.createQuery(hql); Query q = session.createQuery( hql );
q.executeUpdate(); q.executeUpdate();
tx.commit(); tx.commit();
} catch (Exception e) { }
if (tx != null) tx.rollback(); catch ( Exception e ) {
} finally { if ( tx != null ) {
if (session != null) session.close(); tx.rollback();
} }
} }
finally {
if ( session != null ) {
session.close();
}
}
}
public void prepareTest() { public void prepareTest() {
try { try {
TestSupport tsFactory = TestSupportFactories.instance().getTestSupportFactory(getDialect()); TestSupport tsFactory = TestSupportFactories.instance().getTestSupportFactory( getDialect() );
Configuration cfg = configuration(); Configuration cfg = configuration();
dataSourceUtils = tsFactory.createDataSourceUtil(cfg); dataSourceUtils = tsFactory.createDataSourceUtil( cfg );
expectationsFactory = tsFactory.createExpectationsFactory(dataSourceUtils); expectationsFactory = tsFactory.createExpectationsFactory( dataSourceUtils );
testData = tsFactory.createTestData(this); testData = tsFactory.createTestData( this );
geometryEquality = tsFactory.createGeometryEquality(); geometryEquality = tsFactory.createGeometryEquality();
dataSourceUtils.afterCreateSchema(); dataSourceUtils.afterCreateSchema();
} catch (Exception e) { }
throw new RuntimeException(e); catch ( Exception e ) {
} throw new RuntimeException( e );
} }
}
public void cleanupTest() throws SQLException { public void cleanupTest() throws SQLException {
dataSourceUtils.close(); dataSourceUtils.close();
} }
public Connection getConnection() throws SQLException { public Connection getConnection() throws SQLException {
return dataSourceUtils.getConnection(); return dataSourceUtils.getConnection();
} }
public String getBaseForMappings() { public String getBaseForMappings() {
// return "org/hibernatespatial/test/"; // return "org/hibernatespatial/test/";
return ""; return "";
} }
public String[] getMappings() { public String[] getMappings() {
return new String[]{"GeomEntity.hbm.xml"}; return new String[] { "GeomEntity.hbm.xml" };
} }
/** /**
* Returns true if the spatial dialect supports the specified function * Returns true if the spatial dialect supports the specified function
* *
* @param spatialFunction * @param spatialFunction
* @return *
*/ * @return
public boolean isSupportedByDialect(SpatialFunction spatialFunction) { */
SpatialDialect dialect = (SpatialDialect) getDialect(); public boolean isSupportedByDialect(SpatialFunction spatialFunction) {
return dialect.supports(spatialFunction); SpatialDialect dialect = (SpatialDialect) getDialect();
} return dialect.supports( spatialFunction );
}
/** /**
* Supports true if the spatial dialect supports filtering (e.g. ST_overlap, MBROverlap, SDO_FILTER) * Supports true if the spatial dialect supports filtering (e.g. ST_overlap, MBROverlap, SDO_FILTER)
* *
* @return * @return
*/ */
public boolean dialectSupportsFiltering() { public boolean dialectSupportsFiltering() {
SpatialDialect dialect = (SpatialDialect) getDialect(); SpatialDialect dialect = (SpatialDialect) getDialect();
return dialect.supportsFiltering(); return dialect.supportsFiltering();
} }
abstract protected Logger getLogger(); abstract protected Logger getLogger();
/** /**
* Adds the query results to a Map. * Adds the query results to a Map.
* <p/> * <p/>
* Each row is added as a Map entry with the first column the key, * Each row is added as a Map entry with the first column the key,
* and the second the value. It is assumed that the first column is an * and the second the value. It is assumed that the first column is an
* identifier of a type assignable to Integer. * identifier of a type assignable to Integer.
* *
* @param result map of * @param result map of
* @param query the source Query * @param query the source Query
* @param <T> type of the second column in the query results * @param <T> type of the second column in the query results
*/ */
protected <T> void addQueryResults(Map<Integer, T> result, Query query) { protected <T> void addQueryResults(Map<Integer, T> result, Query query) {
List<Object[]> rows = (List<Object[]>) query.list(); List<Object[]> rows = (List<Object[]>) query.list();
if (rows.size() == 0) { if ( rows.size() == 0 ) {
getLogger().warn("No results returned for query!!"); getLogger().warn( "No results returned for query!!" );
} }
for (Object[] row : rows) { for ( Object[] row : rows ) {
Integer id = (Integer) row[0]; Integer id = (Integer) row[0];
T val = (T) row[1]; T val = (T) row[1];
result.put(id, val); result.put( id, val );
} }
} }
protected <T> void compare(Map<Integer, T> expected, Map<Integer, T> received) { protected <T> void compare(Map<Integer, T> expected, Map<Integer, T> received) {
for (Integer id : expected.keySet()) { for ( Integer id : expected.keySet() ) {
getLogger().debug("Case :" + id); getLogger().debug( "Case :" + id );
getLogger().debug("expected: " + expected.get(id)); getLogger().debug( "expected: " + expected.get( id ) );
getLogger().debug("received: " + received.get(id)); getLogger().debug( "received: " + received.get( id ) );
compare(id, expected.get(id), received.get(id)); compare( id, expected.get( id ), received.get( id ) );
} }
} }
protected void compare(Integer id, Object expected, Object received) { protected void compare(Integer id, Object expected, Object received) {
assertTrue(expected != null || (expected == null && received == null)); assertTrue( expected != null || ( expected == null && received == null ) );
if (expected instanceof byte[]) { if ( expected instanceof byte[] ) {
assertArrayEquals("Failure on testsuite-suite for case " + id, (byte[]) expected, (byte[]) received); assertArrayEquals( "Failure on testsuite-suite for case " + id, (byte[]) expected, (byte[]) received );
} else if (expected instanceof Geometry) { }
if (!(received instanceof Geometry)) else if ( expected instanceof Geometry ) {
fail("Expected a Geometry, but received an object of type " + received.getClass().getCanonicalName()); if ( !( received instanceof Geometry ) ) {
assertTrue("Failure on testsuite-suite for case " + id, geometryEquality.test((Geometry) expected, (Geometry) received)); fail( "Expected a Geometry, but received an object of type " + received.getClass().getCanonicalName() );
}
assertTrue(
"Failure on testsuite-suite for case " + id,
geometryEquality.test( (Geometry) expected, (Geometry) received )
);
} else { }
if (expected instanceof Long) { else {
assertEquals("Failure on testsuite-suite for case " + id, ((Long) expected).intValue(), received); if ( expected instanceof Long ) {
} else { assertEquals( "Failure on testsuite-suite for case " + id, ( (Long) expected ).intValue(), received );
assertEquals("Failure on testsuite-suite for case " + id, expected, received); }
} else {
} assertEquals( "Failure on testsuite-suite for case " + id, expected, received );
} }
}
}
} }

View File

@ -25,335 +25,403 @@
package org.hibernate.spatial; package org.hibernate.spatial;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;
import com.vividsolutions.jts.geom.Geometry; import com.vividsolutions.jts.geom.Geometry;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.junit.Test; import org.junit.Test;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import java.sql.SQLException; import org.hibernate.Query;
import java.util.HashMap; import org.hibernate.Session;
import java.util.Map; import org.hibernate.Transaction;
/** /**
* @author Karel Maesen, Geovise BVBA * @author Karel Maesen, Geovise BVBA
*/ */
public class TestSpatialFunctions extends SpatialFunctionalTestCase { public class TestSpatialFunctions extends SpatialFunctionalTestCase {
private static Logger LOGGER = LoggerFactory.getLogger(TestSpatialFunctions.class); private static Logger LOGGER = LoggerFactory.getLogger( TestSpatialFunctions.class );
public void prepareTest() { public void prepareTest() {
super.prepareTest(); super.prepareTest();
insertTestData(); insertTestData();
} }
protected Logger getLogger() { protected Logger getLogger() {
return LOGGER; return LOGGER;
} }
@Test @Test
public void testSpatialFunctions() throws Exception { public void testSpatialFunctions() throws Exception {
dimension(); dimension();
astext(); astext();
asbinary(); asbinary();
geometrytype(); geometrytype();
srid(); srid();
issimple(); issimple();
isempty(); isempty();
boundary(); boundary();
envelope(); envelope();
within(); within();
equals(); equals();
crosses(); crosses();
contains(); contains();
disjoint(); disjoint();
intersects(); intersects();
overlaps(); overlaps();
touches(); touches();
relate(); relate();
distance(); distance();
buffer(); buffer();
convexhull(); convexhull();
intersection(); intersection();
difference(); difference();
symdifference(); symdifference();
geomunion(); geomunion();
dwithin(); dwithin();
transform(); transform();
} }
public void dimension() throws SQLException { public void dimension() throws SQLException {
if (!isSupportedByDialect(SpatialFunction.dimension)) return; if ( !isSupportedByDialect( SpatialFunction.dimension ) ) {
Map<Integer, Integer> dbexpected = expectationsFactory.getDimension(); return;
String hql = "SELECT id, dimension(geom) FROM GeomEntity"; }
retrieveHQLResultsAndCompare(dbexpected, hql); Map<Integer, Integer> dbexpected = expectationsFactory.getDimension();
} String hql = "SELECT id, dimension(geom) FROM GeomEntity";
retrieveHQLResultsAndCompare( dbexpected, hql );
}
public void astext() throws SQLException { public void astext() throws SQLException {
if (!isSupportedByDialect(SpatialFunction.astext)) return; if ( !isSupportedByDialect( SpatialFunction.astext ) ) {
Map<Integer, String> dbexpected = expectationsFactory.getAsText(); return;
String hql = "SELECT id, astext(geom) from GeomEntity"; }
retrieveHQLResultsAndCompare(dbexpected, hql); Map<Integer, String> dbexpected = expectationsFactory.getAsText();
} String hql = "SELECT id, astext(geom) from GeomEntity";
retrieveHQLResultsAndCompare( dbexpected, hql );
}
public void asbinary() throws SQLException { public void asbinary() throws SQLException {
if (!isSupportedByDialect(SpatialFunction.asbinary)) return; if ( !isSupportedByDialect( SpatialFunction.asbinary ) ) {
Map<Integer, byte[]> dbexpected = expectationsFactory.getAsBinary(); return;
String hql = "SELECT id, asbinary(geom) from GeomEntity"; }
retrieveHQLResultsAndCompare(dbexpected, hql); Map<Integer, byte[]> dbexpected = expectationsFactory.getAsBinary();
} String hql = "SELECT id, asbinary(geom) from GeomEntity";
retrieveHQLResultsAndCompare( dbexpected, hql );
}
public void geometrytype() throws SQLException { public void geometrytype() throws SQLException {
if (!isSupportedByDialect(SpatialFunction.geometrytype)) return; if ( !isSupportedByDialect( SpatialFunction.geometrytype ) ) {
Map<Integer, String> dbexpected = expectationsFactory.getGeometryType(); return;
String hql = "SELECT id, geometrytype(geom) from GeomEntity"; }
retrieveHQLResultsAndCompare(dbexpected, hql); Map<Integer, String> dbexpected = expectationsFactory.getGeometryType();
} String hql = "SELECT id, geometrytype(geom) from GeomEntity";
retrieveHQLResultsAndCompare( dbexpected, hql );
}
public void srid() throws SQLException { public void srid() throws SQLException {
if (!isSupportedByDialect(SpatialFunction.srid)) return; if ( !isSupportedByDialect( SpatialFunction.srid ) ) {
Map<Integer, Integer> dbexpected = expectationsFactory.getSrid(); return;
String hql = "SELECT id, srid(geom) from GeomEntity"; }
retrieveHQLResultsAndCompare(dbexpected, hql); Map<Integer, Integer> dbexpected = expectationsFactory.getSrid();
} String hql = "SELECT id, srid(geom) from GeomEntity";
retrieveHQLResultsAndCompare( dbexpected, hql );
}
public void issimple() throws SQLException { public void issimple() throws SQLException {
if (!isSupportedByDialect(SpatialFunction.issimple)) return; if ( !isSupportedByDialect( SpatialFunction.issimple ) ) {
Map<Integer, Boolean> dbexpected = expectationsFactory.getIsSimple(); return;
String hql = "SELECT id, issimple(geom) from GeomEntity"; }
retrieveHQLResultsAndCompare(dbexpected, hql); Map<Integer, Boolean> dbexpected = expectationsFactory.getIsSimple();
} String hql = "SELECT id, issimple(geom) from GeomEntity";
retrieveHQLResultsAndCompare( dbexpected, hql );
}
public void isempty() throws SQLException { public void isempty() throws SQLException {
if (!isSupportedByDialect(SpatialFunction.isempty)) return; if ( !isSupportedByDialect( SpatialFunction.isempty ) ) {
Map<Integer, Boolean> dbexpected = expectationsFactory.getIsEmpty(); return;
String hql = "SELECT id, isEmpty(geom) from GeomEntity"; }
retrieveHQLResultsAndCompare(dbexpected, hql); Map<Integer, Boolean> dbexpected = expectationsFactory.getIsEmpty();
} String hql = "SELECT id, isEmpty(geom) from GeomEntity";
retrieveHQLResultsAndCompare( dbexpected, hql );
}
public void boundary() throws SQLException { public void boundary() throws SQLException {
if (!isSupportedByDialect(SpatialFunction.boundary)) return; if ( !isSupportedByDialect( SpatialFunction.boundary ) ) {
Map<Integer, Geometry> dbexpected = expectationsFactory.getBoundary(); return;
String hql = "SELECT id, boundary(geom) from GeomEntity"; }
retrieveHQLResultsAndCompare(dbexpected, hql); Map<Integer, Geometry> dbexpected = expectationsFactory.getBoundary();
} String hql = "SELECT id, boundary(geom) from GeomEntity";
retrieveHQLResultsAndCompare( dbexpected, hql );
}
public void envelope() throws SQLException { public void envelope() throws SQLException {
if (!isSupportedByDialect(SpatialFunction.envelope)) return; if ( !isSupportedByDialect( SpatialFunction.envelope ) ) {
Map<Integer, Geometry> dbexpected = expectationsFactory.getEnvelope(); return;
String hql = "SELECT id, envelope(geom) from GeomEntity"; }
retrieveHQLResultsAndCompare(dbexpected, hql); Map<Integer, Geometry> dbexpected = expectationsFactory.getEnvelope();
} String hql = "SELECT id, envelope(geom) from GeomEntity";
retrieveHQLResultsAndCompare( dbexpected, hql );
}
public void within() throws SQLException { public void within() throws SQLException {
if (!isSupportedByDialect(SpatialFunction.within)) return; if ( !isSupportedByDialect( SpatialFunction.within ) ) {
Map<Integer, Boolean> dbexpected = expectationsFactory.getWithin(expectationsFactory.getTestPolygon()); return;
String hql = "SELECT id, within(geom, :filter) from GeomEntity where within(geom, :filter) = true and srid(geom) = 4326"; }
Map<String, Object> params = createQueryParams("filter", expectationsFactory.getTestPolygon()); Map<Integer, Boolean> dbexpected = expectationsFactory.getWithin( expectationsFactory.getTestPolygon() );
retrieveHQLResultsAndCompare(dbexpected, hql, params); String hql = "SELECT id, within(geom, :filter) from GeomEntity where within(geom, :filter) = true and srid(geom) = 4326";
} Map<String, Object> params = createQueryParams( "filter", expectationsFactory.getTestPolygon() );
retrieveHQLResultsAndCompare( dbexpected, hql, params );
}
public void equals() throws SQLException { public void equals() throws SQLException {
if (!isSupportedByDialect(SpatialFunction.equals)) return; if ( !isSupportedByDialect( SpatialFunction.equals ) ) {
Map<Integer, Boolean> dbexpected = expectationsFactory.getEquals(expectationsFactory.getTestPolygon()); return;
String hql = "SELECT id, equals(geom, :filter) from GeomEntity where equals(geom, :filter) = true and srid(geom) = 4326"; }
Map<String, Object> params = createQueryParams("filter", expectationsFactory.getTestPolygon()); Map<Integer, Boolean> dbexpected = expectationsFactory.getEquals( expectationsFactory.getTestPolygon() );
retrieveHQLResultsAndCompare(dbexpected, hql, params); String hql = "SELECT id, equals(geom, :filter) from GeomEntity where equals(geom, :filter) = true and srid(geom) = 4326";
} Map<String, Object> params = createQueryParams( "filter", expectationsFactory.getTestPolygon() );
retrieveHQLResultsAndCompare( dbexpected, hql, params );
}
public void crosses() throws SQLException { public void crosses() throws SQLException {
if (!isSupportedByDialect(SpatialFunction.crosses)) return; if ( !isSupportedByDialect( SpatialFunction.crosses ) ) {
Map<Integer, Boolean> dbexpected = expectationsFactory.getCrosses(expectationsFactory.getTestPolygon()); return;
String hql = "SELECT id, crosses(geom, :filter) from GeomEntity where crosses(geom, :filter) = true and srid(geom) = 4326"; }
Map<String, Object> params = createQueryParams("filter", expectationsFactory.getTestPolygon()); Map<Integer, Boolean> dbexpected = expectationsFactory.getCrosses( expectationsFactory.getTestPolygon() );
retrieveHQLResultsAndCompare(dbexpected, hql, params); String hql = "SELECT id, crosses(geom, :filter) from GeomEntity where crosses(geom, :filter) = true and srid(geom) = 4326";
Map<String, Object> params = createQueryParams( "filter", expectationsFactory.getTestPolygon() );
retrieveHQLResultsAndCompare( dbexpected, hql, params );
} }
public void contains() throws SQLException { public void contains() throws SQLException {
if (!isSupportedByDialect(SpatialFunction.contains)) return; if ( !isSupportedByDialect( SpatialFunction.contains ) ) {
Map<Integer, Boolean> dbexpected = expectationsFactory.getContains(expectationsFactory.getTestPolygon()); return;
String hql = "SELECT id, contains(geom, :filter) from GeomEntity where contains(geom, :filter) = true and srid(geom) = 4326"; }
Map<String, Object> params = createQueryParams("filter", expectationsFactory.getTestPolygon()); Map<Integer, Boolean> dbexpected = expectationsFactory.getContains( expectationsFactory.getTestPolygon() );
retrieveHQLResultsAndCompare(dbexpected, hql, params); String hql = "SELECT id, contains(geom, :filter) from GeomEntity where contains(geom, :filter) = true and srid(geom) = 4326";
} Map<String, Object> params = createQueryParams( "filter", expectationsFactory.getTestPolygon() );
retrieveHQLResultsAndCompare( dbexpected, hql, params );
}
public void disjoint() throws SQLException { public void disjoint() throws SQLException {
if (!isSupportedByDialect(SpatialFunction.disjoint)) return; if ( !isSupportedByDialect( SpatialFunction.disjoint ) ) {
Map<Integer, Boolean> dbexpected = expectationsFactory.getDisjoint(expectationsFactory.getTestPolygon()); return;
String hql = "SELECT id, disjoint(geom, :filter) from GeomEntity where disjoint(geom, :filter) = true and srid(geom) = 4326"; }
Map<String, Object> params = createQueryParams("filter", expectationsFactory.getTestPolygon()); Map<Integer, Boolean> dbexpected = expectationsFactory.getDisjoint( expectationsFactory.getTestPolygon() );
retrieveHQLResultsAndCompare(dbexpected, hql, params); String hql = "SELECT id, disjoint(geom, :filter) from GeomEntity where disjoint(geom, :filter) = true and srid(geom) = 4326";
} Map<String, Object> params = createQueryParams( "filter", expectationsFactory.getTestPolygon() );
retrieveHQLResultsAndCompare( dbexpected, hql, params );
}
public void intersects() throws SQLException { public void intersects() throws SQLException {
if (!isSupportedByDialect(SpatialFunction.intersects)) return; if ( !isSupportedByDialect( SpatialFunction.intersects ) ) {
Map<Integer, Boolean> dbexpected = expectationsFactory.getIntersects(expectationsFactory.getTestPolygon()); return;
String hql = "SELECT id, intersects(geom, :filter) from GeomEntity where intersects(geom, :filter) = true and srid(geom) = 4326"; }
Map<String, Object> params = createQueryParams("filter", expectationsFactory.getTestPolygon()); Map<Integer, Boolean> dbexpected = expectationsFactory.getIntersects( expectationsFactory.getTestPolygon() );
retrieveHQLResultsAndCompare(dbexpected, hql, params); String hql = "SELECT id, intersects(geom, :filter) from GeomEntity where intersects(geom, :filter) = true and srid(geom) = 4326";
} Map<String, Object> params = createQueryParams( "filter", expectationsFactory.getTestPolygon() );
retrieveHQLResultsAndCompare( dbexpected, hql, params );
}
public void overlaps() throws SQLException { public void overlaps() throws SQLException {
if (!isSupportedByDialect(SpatialFunction.overlaps)) return; if ( !isSupportedByDialect( SpatialFunction.overlaps ) ) {
Map<Integer, Boolean> dbexpected = expectationsFactory.getOverlaps(expectationsFactory.getTestPolygon()); return;
String hql = "SELECT id, overlaps(geom, :filter) from GeomEntity where overlaps(geom, :filter) = true and srid(geom) = 4326"; }
Map<String, Object> params = createQueryParams("filter", expectationsFactory.getTestPolygon()); Map<Integer, Boolean> dbexpected = expectationsFactory.getOverlaps( expectationsFactory.getTestPolygon() );
retrieveHQLResultsAndCompare(dbexpected, hql, params); String hql = "SELECT id, overlaps(geom, :filter) from GeomEntity where overlaps(geom, :filter) = true and srid(geom) = 4326";
} Map<String, Object> params = createQueryParams( "filter", expectationsFactory.getTestPolygon() );
retrieveHQLResultsAndCompare( dbexpected, hql, params );
}
public void touches() throws SQLException { public void touches() throws SQLException {
if (!isSupportedByDialect(SpatialFunction.touches)) return; if ( !isSupportedByDialect( SpatialFunction.touches ) ) {
String hql = "SELECT id, touches(geom, :filter) from GeomEntity where touches(geom, :filter) = true and srid(geom) = 4326"; return;
Map<Integer, Boolean> dbexpected = expectationsFactory.getTouches(expectationsFactory.getTestPolygon()); }
Map<String, Object> params = createQueryParams("filter", expectationsFactory.getTestPolygon()); String hql = "SELECT id, touches(geom, :filter) from GeomEntity where touches(geom, :filter) = true and srid(geom) = 4326";
retrieveHQLResultsAndCompare(dbexpected, hql, params); Map<Integer, Boolean> dbexpected = expectationsFactory.getTouches( expectationsFactory.getTestPolygon() );
} Map<String, Object> params = createQueryParams( "filter", expectationsFactory.getTestPolygon() );
retrieveHQLResultsAndCompare( dbexpected, hql, params );
}
public void relate() throws SQLException { public void relate() throws SQLException {
if (!isSupportedByDialect(SpatialFunction.relate)) return; if ( !isSupportedByDialect( SpatialFunction.relate ) ) {
String matrix = "T*T***T**"; return;
Map<Integer, Boolean> dbexpected = expectationsFactory.getRelate(expectationsFactory.getTestPolygon(), matrix); }
String hql = "SELECT id, relate(geom, :filter, :matrix) from GeomEntity where relate(geom, :filter, :matrix) = true and srid(geom) = 4326"; String matrix = "T*T***T**";
Map<String, Object> params = createQueryParams("filter", expectationsFactory.getTestPolygon()); Map<Integer, Boolean> dbexpected = expectationsFactory.getRelate(
params.put("matrix", matrix); expectationsFactory.getTestPolygon(),
retrieveHQLResultsAndCompare(dbexpected, hql, params); matrix
);
String hql = "SELECT id, relate(geom, :filter, :matrix) from GeomEntity where relate(geom, :filter, :matrix) = true and srid(geom) = 4326";
Map<String, Object> params = createQueryParams( "filter", expectationsFactory.getTestPolygon() );
params.put( "matrix", matrix );
retrieveHQLResultsAndCompare( dbexpected, hql, params );
matrix = "FF*FF****"; matrix = "FF*FF****";
dbexpected = expectationsFactory.getRelate(expectationsFactory.getTestPolygon(), matrix); dbexpected = expectationsFactory.getRelate( expectationsFactory.getTestPolygon(), matrix );
params.put("matrix", matrix); params.put( "matrix", matrix );
retrieveHQLResultsAndCompare(dbexpected, hql, params); retrieveHQLResultsAndCompare( dbexpected, hql, params );
} }
public void distance() throws SQLException { public void distance() throws SQLException {
if (!isSupportedByDialect(SpatialFunction.distance)) return; if ( !isSupportedByDialect( SpatialFunction.distance ) ) {
Map<Integer, Double> dbexpected = expectationsFactory.getDistance(expectationsFactory.getTestPolygon()); return;
String hql = "SELECT id, distance(geom, :filter) from GeomEntity where srid(geom) = 4326"; }
Map<String, Object> params = createQueryParams("filter", expectationsFactory.getTestPolygon()); Map<Integer, Double> dbexpected = expectationsFactory.getDistance( expectationsFactory.getTestPolygon() );
retrieveHQLResultsAndCompare(dbexpected, hql, params); String hql = "SELECT id, distance(geom, :filter) from GeomEntity where srid(geom) = 4326";
} Map<String, Object> params = createQueryParams( "filter", expectationsFactory.getTestPolygon() );
retrieveHQLResultsAndCompare( dbexpected, hql, params );
}
public void buffer() throws SQLException { public void buffer() throws SQLException {
if (!isSupportedByDialect(SpatialFunction.buffer)) return; if ( !isSupportedByDialect( SpatialFunction.buffer ) ) {
Map<Integer, Geometry> dbexpected = expectationsFactory.getBuffer(Double.valueOf(1.0)); return;
String hql = "SELECT id, buffer(geom, :distance) from GeomEntity where srid(geom) = 4326"; }
Map<String, Object> params = createQueryParams("distance", Double.valueOf(1.0)); Map<Integer, Geometry> dbexpected = expectationsFactory.getBuffer( Double.valueOf( 1.0 ) );
retrieveHQLResultsAndCompare(dbexpected, hql, params); String hql = "SELECT id, buffer(geom, :distance) from GeomEntity where srid(geom) = 4326";
Map<String, Object> params = createQueryParams( "distance", Double.valueOf( 1.0 ) );
retrieveHQLResultsAndCompare( dbexpected, hql, params );
} }
public void convexhull() throws SQLException { public void convexhull() throws SQLException {
if (!isSupportedByDialect(SpatialFunction.convexhull)) return; if ( !isSupportedByDialect( SpatialFunction.convexhull ) ) {
Map<Integer, Geometry> dbexpected = expectationsFactory.getConvexHull(expectationsFactory.getTestPolygon()); return;
String hql = "SELECT id, convexhull(geomunion(geom, :polygon)) from GeomEntity where srid(geom) = 4326"; }
Map<String, Object> params = createQueryParams("polygon", expectationsFactory.getTestPolygon()); Map<Integer, Geometry> dbexpected = expectationsFactory.getConvexHull( expectationsFactory.getTestPolygon() );
retrieveHQLResultsAndCompare(dbexpected, hql, params); String hql = "SELECT id, convexhull(geomunion(geom, :polygon)) from GeomEntity where srid(geom) = 4326";
Map<String, Object> params = createQueryParams( "polygon", expectationsFactory.getTestPolygon() );
retrieveHQLResultsAndCompare( dbexpected, hql, params );
} }
public void intersection() throws SQLException { public void intersection() throws SQLException {
if (!isSupportedByDialect(SpatialFunction.intersection)) return; if ( !isSupportedByDialect( SpatialFunction.intersection ) ) {
Map<Integer, Geometry> dbexpected = expectationsFactory.getIntersection(expectationsFactory.getTestPolygon()); return;
String hql = "SELECT id, intersection(geom, :polygon) from GeomEntity where srid(geom) = 4326"; }
Map<String, Object> params = createQueryParams("polygon", expectationsFactory.getTestPolygon()); Map<Integer, Geometry> dbexpected = expectationsFactory.getIntersection( expectationsFactory.getTestPolygon() );
retrieveHQLResultsAndCompare(dbexpected, hql, params); String hql = "SELECT id, intersection(geom, :polygon) from GeomEntity where srid(geom) = 4326";
} Map<String, Object> params = createQueryParams( "polygon", expectationsFactory.getTestPolygon() );
retrieveHQLResultsAndCompare( dbexpected, hql, params );
}
public void difference() throws SQLException { public void difference() throws SQLException {
if (!isSupportedByDialect(SpatialFunction.difference)) return; if ( !isSupportedByDialect( SpatialFunction.difference ) ) {
Map<Integer, Geometry> dbexpected = expectationsFactory.getDifference(expectationsFactory.getTestPolygon()); return;
String hql = "SELECT id, difference(geom, :polygon) from GeomEntity where srid(geom) = 4326"; }
Map<String, Object> params = createQueryParams("polygon", expectationsFactory.getTestPolygon()); Map<Integer, Geometry> dbexpected = expectationsFactory.getDifference( expectationsFactory.getTestPolygon() );
retrieveHQLResultsAndCompare(dbexpected, hql, params); String hql = "SELECT id, difference(geom, :polygon) from GeomEntity where srid(geom) = 4326";
} Map<String, Object> params = createQueryParams( "polygon", expectationsFactory.getTestPolygon() );
retrieveHQLResultsAndCompare( dbexpected, hql, params );
}
public void symdifference() throws SQLException { public void symdifference() throws SQLException {
if (!isSupportedByDialect(SpatialFunction.symdifference)) return; if ( !isSupportedByDialect( SpatialFunction.symdifference ) ) {
Map<Integer, Geometry> dbexpected = expectationsFactory.getSymDifference(expectationsFactory.getTestPolygon()); return;
String hql = "SELECT id, symdifference(geom, :polygon) from GeomEntity where srid(geom) = 4326"; }
Map<String, Object> params = createQueryParams("polygon", expectationsFactory.getTestPolygon()); Map<Integer, Geometry> dbexpected = expectationsFactory.getSymDifference( expectationsFactory.getTestPolygon() );
retrieveHQLResultsAndCompare(dbexpected, hql, params); String hql = "SELECT id, symdifference(geom, :polygon) from GeomEntity where srid(geom) = 4326";
} Map<String, Object> params = createQueryParams( "polygon", expectationsFactory.getTestPolygon() );
retrieveHQLResultsAndCompare( dbexpected, hql, params );
}
public void geomunion() throws SQLException { public void geomunion() throws SQLException {
if (!isSupportedByDialect(SpatialFunction.geomunion)) return; if ( !isSupportedByDialect( SpatialFunction.geomunion ) ) {
Map<Integer, Geometry> dbexpected = expectationsFactory.getGeomUnion(expectationsFactory.getTestPolygon()); return;
String hql = "SELECT id, geomunion(geom, :polygon) from GeomEntity where srid(geom) = 4326"; }
Map<String, Object> params = createQueryParams("polygon", expectationsFactory.getTestPolygon()); Map<Integer, Geometry> dbexpected = expectationsFactory.getGeomUnion( expectationsFactory.getTestPolygon() );
retrieveHQLResultsAndCompare(dbexpected, hql, params); String hql = "SELECT id, geomunion(geom, :polygon) from GeomEntity where srid(geom) = 4326";
} Map<String, Object> params = createQueryParams( "polygon", expectationsFactory.getTestPolygon() );
retrieveHQLResultsAndCompare( dbexpected, hql, params );
}
public void dwithin() throws SQLException { public void dwithin() throws SQLException {
if (!isSupportedByDialect(SpatialFunction.dwithin)) return; if ( !isSupportedByDialect( SpatialFunction.dwithin ) ) {
double distance = 30.0; return;
Map<Integer, Boolean> dbexpected = expectationsFactory.getDwithin(expectationsFactory.getTestPoint(), distance); }
String hql = "SELECT id, dwithin(geom, :filter, :distance) from GeomEntity where dwithin(geom, :filter, :distance) = true and srid(geom) = 4326"; double distance = 30.0;
Map<String, Object> params = createQueryParams("filter", expectationsFactory.getTestPoint()); Map<Integer, Boolean> dbexpected = expectationsFactory.getDwithin(
params.put("distance", 30.0); expectationsFactory.getTestPoint(),
retrieveHQLResultsAndCompare(dbexpected, hql, params); distance
} );
String hql = "SELECT id, dwithin(geom, :filter, :distance) from GeomEntity where dwithin(geom, :filter, :distance) = true and srid(geom) = 4326";
Map<String, Object> params = createQueryParams( "filter", expectationsFactory.getTestPoint() );
params.put( "distance", 30.0 );
retrieveHQLResultsAndCompare( dbexpected, hql, params );
}
public void transform() throws SQLException { public void transform() throws SQLException {
if (!isSupportedByDialect(SpatialFunction.transform)) return; if ( !isSupportedByDialect( SpatialFunction.transform ) ) {
int epsg = 4324; return;
Map<Integer, Geometry> dbexpected = expectationsFactory.getTransform(epsg); }
String hql = "SELECT id, transform(geom, :epsg) from GeomEntity where srid(geom) = 4326"; int epsg = 4324;
Map<String, Object> params = createQueryParams("epsg", Integer.valueOf(epsg)); Map<Integer, Geometry> dbexpected = expectationsFactory.getTransform( epsg );
retrieveHQLResultsAndCompare(dbexpected, hql, params); String hql = "SELECT id, transform(geom, :epsg) from GeomEntity where srid(geom) = 4326";
Map<String, Object> params = createQueryParams( "epsg", Integer.valueOf( epsg ) );
retrieveHQLResultsAndCompare( dbexpected, hql, params );
} }
public <T> void retrieveHQLResultsAndCompare(Map<Integer, T> dbexpected, String hql) { public <T> void retrieveHQLResultsAndCompare(Map<Integer, T> dbexpected, String hql) {
retrieveHQLResultsAndCompare(dbexpected, hql, null); retrieveHQLResultsAndCompare( dbexpected, hql, null );
} }
protected <T> void retrieveHQLResultsAndCompare(Map<Integer, T> dbexpected, String hql, Map<String, Object> params) { protected <T> void retrieveHQLResultsAndCompare(Map<Integer, T> dbexpected, String hql, Map<String, Object> params) {
Map<Integer, T> hsreceived = new HashMap<Integer, T>(); Map<Integer, T> hsreceived = new HashMap<Integer, T>();
doInSession(hql, hsreceived, params); doInSession( hql, hsreceived, params );
compare(dbexpected, hsreceived); compare( dbexpected, hsreceived );
} }
private Map<String, Object> createQueryParams(String filterParamName, Object value) { private Map<String, Object> createQueryParams(String filterParamName, Object value) {
Map<String, Object> params = new HashMap<String, Object>(); Map<String, Object> params = new HashMap<String, Object>();
params.put(filterParamName, value); params.put( filterParamName, value );
return params; return params;
} }
private <T> void doInSession(String hql, Map<Integer, T> result, Map<String, Object> params) { private <T> void doInSession(String hql, Map<Integer, T> result, Map<String, Object> params) {
Session session = null; Session session = null;
Transaction tx = null; Transaction tx = null;
try { try {
session = openSession(); session = openSession();
tx = session.beginTransaction(); tx = session.beginTransaction();
Query query = session.createQuery(hql); Query query = session.createQuery( hql );
setParameters(params, query); setParameters( params, query );
addQueryResults(result, query); addQueryResults( result, query );
} finally { }
if (tx != null) tx.rollback(); finally {
if (session != null) session.close(); if ( tx != null ) {
} tx.rollback();
} }
if ( session != null ) {
session.close();
}
}
}
private void setParameters(Map<String, Object> params, Query query) { private void setParameters(Map<String, Object> params, Query query) {
if (params == null) return; if ( params == null ) {
for (String param : params.keySet()) { return;
Object value = params.get(param); }
for ( String param : params.keySet() ) {
Object value = params.get( param );
// if (value instanceof Geometry) { // if (value instanceof Geometry) {
// query.setParameter(param, value, GeometryType.TYPE); // query.setParameter(param, value, GeometryType.TYPE);
// } else { // } else {
query.setParameter(param, value); query.setParameter( param, value );
// } // }
} }
} }
} }

View File

@ -25,186 +25,225 @@
package org.hibernate.spatial; package org.hibernate.spatial;
import java.sql.SQLException;
import java.util.List;
import java.util.Map;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.hibernate.Criteria; import org.hibernate.Criteria;
import org.hibernate.Session; import org.hibernate.Session;
import org.hibernate.Transaction; import org.hibernate.Transaction;
import org.hibernate.criterion.Criterion; import org.hibernate.criterion.Criterion;
import org.hibernate.spatial.criterion.SpatialRestrictions; import org.hibernate.spatial.criterion.SpatialRestrictions;
import org.hibernate.spatial.test.GeomEntity; import org.hibernate.spatial.test.GeomEntity;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.sql.SQLException;
import java.util.List;
import java.util.Map;
import static junit.framework.Assert.assertEquals; import static junit.framework.Assert.assertEquals;
import static org.junit.Assert.fail; import static org.junit.Assert.fail;
public class TestSpatialRestrictions extends SpatialFunctionalTestCase { public class TestSpatialRestrictions extends SpatialFunctionalTestCase {
private static Logger LOGGER = LoggerFactory.getLogger(TestSpatialRestrictions.class); private static Logger LOGGER = LoggerFactory.getLogger( TestSpatialRestrictions.class );
public void prepareTest() {
super.prepareTest();
try {
dataSourceUtils.insertTestData( testData );
}
catch ( SQLException e ) {
throw new RuntimeException( e );
}
}
public void prepareTest() { protected Logger getLogger() {
super.prepareTest(); return LOGGER;
try { }
dataSourceUtils.insertTestData(testData);
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
protected Logger getLogger() { @Test
return LOGGER; public void testRestrictions() throws Exception {
} within();
filter();
contains();
crosses();
touches();
disjoint();
eq();
intersects();
overlaps();
dwithin();
havingSRID();
isEmpty();
isNotEmpty();
}
@Test public void within() throws SQLException {
public void testRestrictions() throws Exception { if ( !isSupportedByDialect( SpatialFunction.within ) ) {
within(); return;
filter(); }
contains(); Map<Integer, Boolean> dbexpected = expectationsFactory.getWithin( expectationsFactory.getTestPolygon() );
crosses(); Criterion spatialCriterion = SpatialRestrictions.within( "geom", expectationsFactory.getTestPolygon() );
touches(); retrieveAndCompare( dbexpected, spatialCriterion );
disjoint(); }
eq();
intersects();
overlaps();
dwithin();
havingSRID();
isEmpty();
isNotEmpty();
}
public void within() throws SQLException { public void filter() throws SQLException {
if (!isSupportedByDialect(SpatialFunction.within)) return; if ( !dialectSupportsFiltering() ) {
Map<Integer, Boolean> dbexpected = expectationsFactory.getWithin(expectationsFactory.getTestPolygon()); return;
Criterion spatialCriterion = SpatialRestrictions.within("geom", expectationsFactory.getTestPolygon()); }
retrieveAndCompare(dbexpected, spatialCriterion); Map<Integer, Boolean> dbexpected = expectationsFactory.getFilter( expectationsFactory.getTestPolygon() );
} Criterion spatialCriterion = SpatialRestrictions.filter( "geom", expectationsFactory.getTestPolygon() );
retrieveAndCompare( dbexpected, spatialCriterion );
}
public void filter() throws SQLException { public void contains() throws SQLException {
if (!dialectSupportsFiltering()) return; if ( !isSupportedByDialect( SpatialFunction.contains ) ) {
Map<Integer, Boolean> dbexpected = expectationsFactory.getFilter(expectationsFactory.getTestPolygon()); return;
Criterion spatialCriterion = SpatialRestrictions.filter("geom", expectationsFactory.getTestPolygon()); }
retrieveAndCompare(dbexpected, spatialCriterion); Map<Integer, Boolean> dbexpected = expectationsFactory.getContains( expectationsFactory.getTestPolygon() );
} Criterion spatialCriterion = SpatialRestrictions.contains( "geom", expectationsFactory.getTestPolygon() );
retrieveAndCompare( dbexpected, spatialCriterion );
}
public void contains() throws SQLException { public void crosses() throws SQLException {
if (!isSupportedByDialect(SpatialFunction.contains)) return; if ( !isSupportedByDialect( SpatialFunction.crosses ) ) {
Map<Integer, Boolean> dbexpected = expectationsFactory.getContains(expectationsFactory.getTestPolygon()); return;
Criterion spatialCriterion = SpatialRestrictions.contains("geom", expectationsFactory.getTestPolygon()); }
retrieveAndCompare(dbexpected, spatialCriterion); Map<Integer, Boolean> dbexpected = expectationsFactory.getCrosses( expectationsFactory.getTestPolygon() );
} Criterion spatialCriterion = SpatialRestrictions.crosses( "geom", expectationsFactory.getTestPolygon() );
retrieveAndCompare( dbexpected, spatialCriterion );
}
public void crosses() throws SQLException { public void touches() throws SQLException {
if (!isSupportedByDialect(SpatialFunction.crosses)) return; if ( !isSupportedByDialect( SpatialFunction.touches ) ) {
Map<Integer, Boolean> dbexpected = expectationsFactory.getCrosses(expectationsFactory.getTestPolygon()); return;
Criterion spatialCriterion = SpatialRestrictions.crosses("geom", expectationsFactory.getTestPolygon()); }
retrieveAndCompare(dbexpected, spatialCriterion); Map<Integer, Boolean> dbexpected = expectationsFactory.getTouches( expectationsFactory.getTestPolygon() );
} Criterion spatialCriterion = SpatialRestrictions.touches( "geom", expectationsFactory.getTestPolygon() );
retrieveAndCompare( dbexpected, spatialCriterion );
}
public void touches() throws SQLException { public void disjoint() throws SQLException {
if (!isSupportedByDialect(SpatialFunction.touches)) return; if ( !isSupportedByDialect( SpatialFunction.disjoint ) ) {
Map<Integer, Boolean> dbexpected = expectationsFactory.getTouches(expectationsFactory.getTestPolygon()); return;
Criterion spatialCriterion = SpatialRestrictions.touches("geom", expectationsFactory.getTestPolygon()); }
retrieveAndCompare(dbexpected, spatialCriterion); Map<Integer, Boolean> dbexpected = expectationsFactory.getDisjoint( expectationsFactory.getTestPolygon() );
} Criterion spatialCriterion = SpatialRestrictions.disjoint( "geom", expectationsFactory.getTestPolygon() );
retrieveAndCompare( dbexpected, spatialCriterion );
}
public void disjoint() throws SQLException { public void eq() throws SQLException {
if (!isSupportedByDialect(SpatialFunction.disjoint)) return; if ( !isSupportedByDialect( SpatialFunction.equals ) ) {
Map<Integer, Boolean> dbexpected = expectationsFactory.getDisjoint(expectationsFactory.getTestPolygon()); return;
Criterion spatialCriterion = SpatialRestrictions.disjoint("geom", expectationsFactory.getTestPolygon()); }
retrieveAndCompare(dbexpected, spatialCriterion); Map<Integer, Boolean> dbexpected = expectationsFactory.getEquals( expectationsFactory.getTestPolygon() );
} Criterion spatialCriterion = SpatialRestrictions.eq( "geom", expectationsFactory.getTestPolygon() );
retrieveAndCompare( dbexpected, spatialCriterion );
}
public void eq() throws SQLException { public void intersects() throws SQLException {
if (!isSupportedByDialect(SpatialFunction.equals)) return; if ( !isSupportedByDialect( SpatialFunction.intersects ) ) {
Map<Integer, Boolean> dbexpected = expectationsFactory.getEquals(expectationsFactory.getTestPolygon()); return;
Criterion spatialCriterion = SpatialRestrictions.eq("geom", expectationsFactory.getTestPolygon()); }
retrieveAndCompare(dbexpected, spatialCriterion); Map<Integer, Boolean> dbexpected = expectationsFactory.getIntersects( expectationsFactory.getTestPolygon() );
} Criterion spatialCriterion = SpatialRestrictions.intersects( "geom", expectationsFactory.getTestPolygon() );
retrieveAndCompare( dbexpected, spatialCriterion );
}
public void intersects() throws SQLException { public void overlaps() throws SQLException {
if (!isSupportedByDialect(SpatialFunction.intersects)) return; if ( !isSupportedByDialect( SpatialFunction.overlaps ) ) {
Map<Integer, Boolean> dbexpected = expectationsFactory.getIntersects(expectationsFactory.getTestPolygon()); return;
Criterion spatialCriterion = SpatialRestrictions.intersects("geom", expectationsFactory.getTestPolygon()); }
retrieveAndCompare(dbexpected, spatialCriterion); Map<Integer, Boolean> dbexpected = expectationsFactory.getOverlaps( expectationsFactory.getTestPolygon() );
} Criterion spatialCriterion = SpatialRestrictions.overlaps( "geom", expectationsFactory.getTestPolygon() );
retrieveAndCompare( dbexpected, spatialCriterion );
}
public void overlaps() throws SQLException { public void dwithin() throws SQLException {
if (!isSupportedByDialect(SpatialFunction.overlaps)) return; if ( !isSupportedByDialect( SpatialFunction.dwithin ) ) {
Map<Integer, Boolean> dbexpected = expectationsFactory.getOverlaps(expectationsFactory.getTestPolygon()); return;
Criterion spatialCriterion = SpatialRestrictions.overlaps("geom", expectationsFactory.getTestPolygon()); }
retrieveAndCompare(dbexpected, spatialCriterion); Map<Integer, Boolean> dbexpected = expectationsFactory.getDwithin( expectationsFactory.getTestPoint(), 30.0 );
} Criterion spatialCriterion = SpatialRestrictions.distanceWithin(
"geom",
expectationsFactory.getTestPoint(),
30.0
);
retrieveAndCompare( dbexpected, spatialCriterion );
}
public void dwithin() throws SQLException { public void isEmpty() throws SQLException {
if (!isSupportedByDialect(SpatialFunction.dwithin)) return; if ( !isSupportedByDialect( SpatialFunction.isempty ) ) {
Map<Integer, Boolean> dbexpected = expectationsFactory.getDwithin(expectationsFactory.getTestPoint(), 30.0); return;
Criterion spatialCriterion = SpatialRestrictions.distanceWithin("geom", expectationsFactory.getTestPoint(), 30.0); }
retrieveAndCompare(dbexpected, spatialCriterion); Map<Integer, Boolean> dbexpected = expectationsFactory.getIsEmpty();
} Criterion spatialCriterion = SpatialRestrictions.isEmpty( "geom" );
retrieveAndCompare( dbexpected, spatialCriterion );
}
public void isEmpty() throws SQLException { public void isNotEmpty() throws SQLException {
if (!isSupportedByDialect(SpatialFunction.isempty)) return; if ( !isSupportedByDialect( SpatialFunction.isempty ) ) {
Map<Integer, Boolean> dbexpected = expectationsFactory.getIsEmpty(); return;
Criterion spatialCriterion = SpatialRestrictions.isEmpty("geom"); }
retrieveAndCompare(dbexpected, spatialCriterion); Map<Integer, Boolean> dbexpected = expectationsFactory.getIsNotEmpty();
} Criterion spatialCriterion = SpatialRestrictions.isNotEmpty( "geom" );
retrieveAndCompare( dbexpected, spatialCriterion );
public void isNotEmpty() throws SQLException { }
if (!isSupportedByDialect(SpatialFunction.isempty)) return;
Map<Integer, Boolean> dbexpected = expectationsFactory.getIsNotEmpty();
Criterion spatialCriterion = SpatialRestrictions.isNotEmpty("geom");
retrieveAndCompare(dbexpected, spatialCriterion);
}
public void havingSRID() throws SQLException { public void havingSRID() throws SQLException {
if (!isSupportedByDialect(SpatialFunction.srid)) return; if ( !isSupportedByDialect( SpatialFunction.srid ) ) {
Map<Integer, Boolean> dbexpected = expectationsFactory.havingSRID(4326); return;
Criterion spatialCriterion = SpatialRestrictions.havingSRID("geom", 4326); }
retrieveAndCompare(dbexpected, spatialCriterion); Map<Integer, Boolean> dbexpected = expectationsFactory.havingSRID( 4326 );
dbexpected = expectationsFactory.havingSRID(31370); Criterion spatialCriterion = SpatialRestrictions.havingSRID( "geom", 4326 );
spatialCriterion = SpatialRestrictions.havingSRID("geom", 31370); retrieveAndCompare( dbexpected, spatialCriterion );
retrieveAndCompare(dbexpected, spatialCriterion); dbexpected = expectationsFactory.havingSRID( 31370 );
} spatialCriterion = SpatialRestrictions.havingSRID( "geom", 31370 );
retrieveAndCompare( dbexpected, spatialCriterion );
}
private void retrieveAndCompare(Map<Integer, Boolean> dbexpected, Criterion spatialCriterion) { private void retrieveAndCompare(Map<Integer, Boolean> dbexpected, Criterion spatialCriterion) {
Session session = null; Session session = null;
Transaction tx = null; Transaction tx = null;
try { try {
session = openSession(); session = openSession();
tx = session.beginTransaction(); tx = session.beginTransaction();
Criteria criteria = session.createCriteria(GeomEntity.class); Criteria criteria = session.createCriteria( GeomEntity.class );
criteria.add(spatialCriterion); criteria.add( spatialCriterion );
compare(dbexpected, criteria.list()); compare( dbexpected, criteria.list() );
} finally { }
if (tx != null) tx.rollback(); finally {
if (session != null) session.close(); if ( tx != null ) {
} tx.rollback();
} }
if ( session != null ) {
session.close();
}
}
}
private void compare(Map<Integer, Boolean> dbexpected, List list) { private void compare(Map<Integer, Boolean> dbexpected, List list) {
int cnt = 0; int cnt = 0;
for (Integer id : dbexpected.keySet()) { for ( Integer id : dbexpected.keySet() ) {
if (dbexpected.get(id)) { if ( dbexpected.get( id ) ) {
cnt++; cnt++;
if (!findInList(id, (List<GeomEntity>) list)) if ( !findInList( id, (List<GeomEntity>) list ) ) {
fail(String.format("Expected object with id= %d, but not found in result", id)); fail( String.format( "Expected object with id= %d, but not found in result", id ) );
} }
} }
assertEquals(cnt, list.size()); }
LOGGER.info(String.format("Found %d objects within testsuite-suite polygon.", cnt)); assertEquals( cnt, list.size() );
} LOGGER.info( String.format( "Found %d objects within testsuite-suite polygon.", cnt ) );
}
private boolean findInList(Integer id, List<GeomEntity> list) { private boolean findInList(Integer id, List<GeomEntity> list) {
for (GeomEntity entity : list) { for ( GeomEntity entity : list ) {
if (entity.getId() == id) return true; if ( entity.getId() == id ) {
} return true;
return false; }
} }
return false;
}
} }

View File

@ -25,20 +25,21 @@
package org.hibernate.spatial; package org.hibernate.spatial;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.vividsolutions.jts.geom.Geometry; import com.vividsolutions.jts.geom.Geometry;
import com.vividsolutions.jts.io.ParseException; import com.vividsolutions.jts.io.ParseException;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.hibernate.Criteria; import org.hibernate.Criteria;
import org.hibernate.Session; import org.hibernate.Session;
import org.hibernate.Transaction; import org.hibernate.Transaction;
import org.hibernate.spatial.test.GeomEntity; import org.hibernate.spatial.test.GeomEntity;
import org.hibernate.spatial.test.TestDataElement; import org.hibernate.spatial.test.TestDataElement;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static junit.framework.Assert.assertEquals; import static junit.framework.Assert.assertEquals;
import static org.junit.Assert.assertNull; import static org.junit.Assert.assertNull;
@ -50,124 +51,152 @@
*/ */
public class TestStoreRetrieve extends SpatialFunctionalTestCase { public class TestStoreRetrieve extends SpatialFunctionalTestCase {
private static Logger LOGGER = LoggerFactory.getLogger(TestStoreRetrieve.class); private static Logger LOGGER = LoggerFactory.getLogger( TestStoreRetrieve.class );
protected Logger getLogger() { protected Logger getLogger() {
return LOGGER; return LOGGER;
} }
@Test @Test
public void testStoreRetrieve() throws ParseException { public void testStoreRetrieve() throws ParseException {
Map<Integer, GeomEntity> stored = new HashMap<Integer, GeomEntity>(); Map<Integer, GeomEntity> stored = new HashMap<Integer, GeomEntity>();
//check whether we retrieve exactly what we store //check whether we retrieve exactly what we store
storeTestObjects(stored); storeTestObjects( stored );
retrieveAndCompare(stored); retrieveAndCompare( stored );
deleteAllTestEntities(); deleteAllTestEntities();
//check if we can store null-geometries //check if we can store null-geometries
storeNullGeometry(); storeNullGeometry();
//check if we can retrieve null-geometries //check if we can retrieve null-geometries
retrieveNullGeometry(); retrieveNullGeometry();
} }
private void retrieveAndCompare(Map<Integer, GeomEntity> stored) { private void retrieveAndCompare(Map<Integer, GeomEntity> stored) {
int id = -1; int id = -1;
Transaction tx = null; Transaction tx = null;
Session session = null; Session session = null;
try { try {
session = openSession(); session = openSession();
tx = session.beginTransaction(); tx = session.beginTransaction();
for (GeomEntity storedEntity : stored.values()) { for ( GeomEntity storedEntity : stored.values() ) {
id = storedEntity.getId(); id = storedEntity.getId();
GeomEntity retrievedEntity = (GeomEntity) session.get(GeomEntity.class, id); GeomEntity retrievedEntity = (GeomEntity) session.get( GeomEntity.class, id );
Geometry retrievedGeometry = retrievedEntity.getGeom(); Geometry retrievedGeometry = retrievedEntity.getGeom();
Geometry storedGeometry = storedEntity.getGeom(); Geometry storedGeometry = storedEntity.getGeom();
String msg = createFailureMessage(storedEntity.getId(), storedGeometry, retrievedGeometry); String msg = createFailureMessage( storedEntity.getId(), storedGeometry, retrievedGeometry );
assertTrue(msg, geometryEquality.test(storedGeometry, retrievedGeometry)); assertTrue( msg, geometryEquality.test( storedGeometry, retrievedGeometry ) );
} }
tx.commit(); tx.commit();
} catch (Exception e) { }
if (tx != null) tx.rollback(); catch ( Exception e ) {
throw new RuntimeException(String.format("Failure on case: %d", id), e); if ( tx != null ) {
} tx.rollback();
finally { }
if (session != null) session.close(); throw new RuntimeException( String.format( "Failure on case: %d", id ), e );
} }
} finally {
if ( session != null ) {
session.close();
}
}
}
private String createFailureMessage(int id, Geometry storedGeometry, Geometry retrievedGeometry) { private String createFailureMessage(int id, Geometry storedGeometry, Geometry retrievedGeometry) {
String expectedText = (storedGeometry != null ? storedGeometry.toText() : "NULL"); String expectedText = ( storedGeometry != null ? storedGeometry.toText() : "NULL" );
String retrievedText = (retrievedGeometry != null ? retrievedGeometry.toText() : "NULL"); String retrievedText = ( retrievedGeometry != null ? retrievedGeometry.toText() : "NULL" );
return String.format("Equality testsuite-suite failed for %d.\nExpected: %s\nReceived:%s", id, expectedText, retrievedText); return String.format(
} "Equality testsuite-suite failed for %d.\nExpected: %s\nReceived:%s",
id,
expectedText,
retrievedText
);
}
private void storeTestObjects(Map<Integer, GeomEntity> stored) { private void storeTestObjects(Map<Integer, GeomEntity> stored) {
Session session = null; Session session = null;
Transaction tx = null; Transaction tx = null;
int id = -1; int id = -1;
try { try {
session = openSession(); session = openSession();
// Every testsuite-suite instance is committed seperately // Every testsuite-suite instance is committed seperately
// to improve feedback in case of failure // to improve feedback in case of failure
for (TestDataElement element : testData) { for ( TestDataElement element : testData ) {
id = element.id; id = element.id;
tx = session.beginTransaction(); tx = session.beginTransaction();
GeomEntity entity = GeomEntity.createFrom(element); GeomEntity entity = GeomEntity.createFrom( element );
stored.put(entity.getId(), entity); stored.put( entity.getId(), entity );
session.save(entity); session.save( entity );
tx.commit(); tx.commit();
} }
} catch (Exception e) { }
if (tx != null) tx.rollback(); catch ( Exception e ) {
throw new RuntimeException("Failed storing testsuite-suite object with id:" + id, e); if ( tx != null ) {
} finally { tx.rollback();
if (session != null) session.close(); }
} throw new RuntimeException( "Failed storing testsuite-suite object with id:" + id, e );
} }
finally {
if ( session != null ) {
session.close();
}
}
}
private void storeNullGeometry() { private void storeNullGeometry() {
GeomEntity entity = null; GeomEntity entity = null;
Session session = null; Session session = null;
Transaction tx = null; Transaction tx = null;
try { try {
session = openSession(); session = openSession();
tx = session.beginTransaction(); tx = session.beginTransaction();
entity = new GeomEntity(); entity = new GeomEntity();
entity.setId(1); entity.setId( 1 );
entity.setType("NULL OBJECT"); entity.setType( "NULL OBJECT" );
session.save(entity); session.save( entity );
tx.commit(); tx.commit();
} catch (Exception e) { }
if (tx != null) tx.rollback(); catch ( Exception e ) {
throw new RuntimeException("Failed storing testsuite-suite object with id:" + entity.getId(), e); if ( tx != null ) {
} finally { tx.rollback();
if (session != null) session.close(); }
} throw new RuntimeException( "Failed storing testsuite-suite object with id:" + entity.getId(), e );
} }
finally {
if ( session != null ) {
session.close();
}
}
}
private void retrieveNullGeometry() { private void retrieveNullGeometry() {
Transaction tx = null; Transaction tx = null;
Session session = null; Session session = null;
try { try {
session = openSession(); session = openSession();
tx = session.beginTransaction(); tx = session.beginTransaction();
Criteria criteria = session.createCriteria(GeomEntity.class); Criteria criteria = session.createCriteria( GeomEntity.class );
List<GeomEntity> retrieved = criteria.list(); List<GeomEntity> retrieved = criteria.list();
assertEquals("Expected exactly one result", 1, retrieved.size()); assertEquals( "Expected exactly one result", 1, retrieved.size() );
GeomEntity entity = retrieved.get(0); GeomEntity entity = retrieved.get( 0 );
assertNull(entity.getGeom()); assertNull( entity.getGeom() );
tx.commit(); tx.commit();
} catch (Exception e) { }
if (tx != null) tx.rollback(); catch ( Exception e ) {
throw new RuntimeException(e); if ( tx != null ) {
} finally { tx.rollback();
if (session != null) session.close(); }
} throw new RuntimeException( e );
} }
finally {
if ( session != null ) {
session.close();
}
}
}
} }

View File

@ -10,38 +10,42 @@
*/ */
public class TestSupportFactories { public class TestSupportFactories {
private static TestSupportFactories instance = new TestSupportFactories(); private static TestSupportFactories instance = new TestSupportFactories();
public static TestSupportFactories instance() { public static TestSupportFactories instance() {
return instance; return instance;
} }
private TestSupportFactories() { private TestSupportFactories() {
} }
public TestSupport getTestSupportFactory(Dialect dialect) throws ClassNotFoundException, InstantiationException, IllegalAccessException { public TestSupport getTestSupportFactory(Dialect dialect)
if (dialect == null) throw new IllegalArgumentException("Dialect argument is required."); throws ClassNotFoundException, InstantiationException, IllegalAccessException {
String testSupportFactoryClassName = getSupportFactoryClassName(dialect); if ( dialect == null ) {
return instantiate(testSupportFactoryClassName); throw new IllegalArgumentException( "Dialect argument is required." );
}
String testSupportFactoryClassName = getSupportFactoryClassName( dialect );
return instantiate( testSupportFactoryClassName );
} }
private TestSupport instantiate(String testSupportFactoryClassName) throws ClassNotFoundException, IllegalAccessException, InstantiationException { private TestSupport instantiate(String testSupportFactoryClassName)
ClassLoader cloader = getClassLoader(); throws ClassNotFoundException, IllegalAccessException, InstantiationException {
Class<TestSupport> cl = (Class<TestSupport>) (cloader.loadClass(testSupportFactoryClassName)); ClassLoader cloader = getClassLoader();
return cl.newInstance(); Class<TestSupport> cl = (Class<TestSupport>) ( cloader.loadClass( testSupportFactoryClassName ) );
} return cl.newInstance();
}
private ClassLoader getClassLoader() { private ClassLoader getClassLoader() {
return this.getClass().getClassLoader(); return this.getClass().getClassLoader();
} }
private static String getSupportFactoryClassName(Dialect dialect) { private static String getSupportFactoryClassName(Dialect dialect) {
String canonicalName = dialect.getClass().getCanonicalName(); String canonicalName = dialect.getClass().getCanonicalName();
if ("org.hibernate.spatial.dialect.postgis.PostgisDialect".equals(canonicalName)) { if ( "org.hibernate.spatial.dialect.postgis.PostgisDialect".equals( canonicalName ) ) {
return "org.hibernate.spatial.dialect.postgis.PostgisTestSupport"; return "org.hibernate.spatial.dialect.postgis.PostgisTestSupport";
} }
// if ("org.hibernate.spatial.geodb.GeoDBDialect".equals(canonicalName)) { // if ("org.hibernate.spatial.geodb.GeoDBDialect".equals(canonicalName)) {
// return "org.hibernate.spatial.geodb.GeoDBSupport"; // return "org.hibernate.spatial.geodb.GeoDBSupport";
// } // }
@ -55,8 +59,8 @@ private static String getSupportFactoryClassName(Dialect dialect) {
// if ("org.hibernatespatial.oracle.OracleSpatial10gDialect".equals(canonicalName)) { // if ("org.hibernatespatial.oracle.OracleSpatial10gDialect".equals(canonicalName)) {
// return "org.hibernatespatial.oracle.OracleSDOTestSupport"; // return "org.hibernatespatial.oracle.OracleSDOTestSupport";
// } // }
throw new IllegalArgumentException("Dialect not known in test suite"); throw new IllegalArgumentException( "Dialect not known in test suite" );
} }
} }

View File

@ -6,25 +6,27 @@
public class HSConfigurationTest { public class HSConfigurationTest {
@Test @Test
public void testConfigureFailure() { public void testConfigureFailure() {
HSConfiguration config = new HSConfiguration(); HSConfiguration config = new HSConfiguration();
config.configure("non-existing-file"); config.configure( "non-existing-file" );
} }
@Test @Test
public void testConfigureFile() { public void testConfigureFile() {
HSConfiguration config = new HSConfiguration(); HSConfiguration config = new HSConfiguration();
config.configure("test.cfg.xml"); config.configure( "test.cfg.xml" );
testResults(config); testResults( config );
} }
private void testResults(HSConfiguration config) { private void testResults(HSConfiguration config) {
assertEquals("org.hibernate.spatial.postgis.PostgisDialect", config assertEquals(
.getDefaultDialect()); "org.hibernate.spatial.postgis.PostgisDialect", config
assertEquals("FIXED", config.getPrecisionModel()); .getDefaultDialect()
assertEquals("5", config.getPrecisionModelScale()); );
} assertEquals( "FIXED", config.getPrecisionModel() );
assertEquals( "5", config.getPrecisionModelScale() );
}
} }

View File

@ -27,6 +27,7 @@
import com.vividsolutions.jts.geom.Geometry; import com.vividsolutions.jts.geom.Geometry;
import com.vividsolutions.jts.geom.Point; import com.vividsolutions.jts.geom.Point;
import org.hibernate.spatial.test.AbstractExpectationsFactory; import org.hibernate.spatial.test.AbstractExpectationsFactory;
import org.hibernate.spatial.test.DataSourceUtils; import org.hibernate.spatial.test.DataSourceUtils;
import org.hibernate.spatial.test.NativeSQLStatement; import org.hibernate.spatial.test.NativeSQLStatement;
@ -38,199 +39,217 @@
*/ */
public class PostgisExpectationsFactory extends AbstractExpectationsFactory { public class PostgisExpectationsFactory extends AbstractExpectationsFactory {
private final PGGeometryValueExtractor decoder = new PGGeometryValueExtractor(); private final PGGeometryValueExtractor decoder = new PGGeometryValueExtractor();
public PostgisExpectationsFactory(DataSourceUtils utils) { public PostgisExpectationsFactory(DataSourceUtils utils) {
super(utils); super( utils );
} }
@Override @Override
protected NativeSQLStatement createNativeTouchesStatement(Geometry geom) { protected NativeSQLStatement createNativeTouchesStatement(Geometry geom) {
return createNativeSQLStatementAllWKTParams( return createNativeSQLStatementAllWKTParams(
"select t.id, st_touches(t.geom, ST_GeomFromText(?, 4326)) from GeomTest t where st_touches(t.geom, ST_geomFromText(?, 4326)) = 'true' and st_srid(t.geom) = 4326", "select t.id, st_touches(t.geom, ST_GeomFromText(?, 4326)) from GeomTest t where st_touches(t.geom, ST_geomFromText(?, 4326)) = 'true' and st_srid(t.geom) = 4326",
geom.toText()); geom.toText()
} );
}
@Override @Override
protected NativeSQLStatement createNativeOverlapsStatement(Geometry geom) { protected NativeSQLStatement createNativeOverlapsStatement(Geometry geom) {
return createNativeSQLStatementAllWKTParams( return createNativeSQLStatementAllWKTParams(
"select t.id, st_overlaps(t.geom, ST_GeomFromText(?, 4326)) from GeomTest t where st_overlaps(t.geom, ST_GeomFromText(?, 4326)) = 'true' and ST_SRID(t.geom) = 4326", "select t.id, st_overlaps(t.geom, ST_GeomFromText(?, 4326)) from GeomTest t where st_overlaps(t.geom, ST_GeomFromText(?, 4326)) = 'true' and ST_SRID(t.geom) = 4326",
geom.toText()); geom.toText()
} );
}
@Override @Override
protected NativeSQLStatement createNativeRelateStatement(Geometry geom, String matrix) { protected NativeSQLStatement createNativeRelateStatement(Geometry geom, String matrix) {
String sql = "select t.id, st_relate(t.geom, ST_GeomFromText(?, 4326), '" + matrix + "' ) from GeomTest t where st_relate(t.geom, ST_GeomFromText(?, 4326), '" + matrix + "') = 'true' and ST_SRID(t.geom) = 4326"; String sql = "select t.id, st_relate(t.geom, ST_GeomFromText(?, 4326), '" + matrix + "' ) from GeomTest t where st_relate(t.geom, ST_GeomFromText(?, 4326), '" + matrix + "') = 'true' and ST_SRID(t.geom) = 4326";
return createNativeSQLStatementAllWKTParams(sql, geom.toText()); return createNativeSQLStatementAllWKTParams( sql, geom.toText() );
} }
@Override @Override
protected NativeSQLStatement createNativeDwithinStatement(Point geom, double distance) { protected NativeSQLStatement createNativeDwithinStatement(Point geom, double distance) {
String sql = "select t.id, st_dwithin(t.geom, ST_GeomFromText(?, 4326), " + distance + " ) from GeomTest t where st_dwithin(t.geom, ST_GeomFromText(?, 4326), " + distance + ") = 'true' and ST_SRID(t.geom) = 4326"; String sql = "select t.id, st_dwithin(t.geom, ST_GeomFromText(?, 4326), " + distance + " ) from GeomTest t where st_dwithin(t.geom, ST_GeomFromText(?, 4326), " + distance + ") = 'true' and ST_SRID(t.geom) = 4326";
return createNativeSQLStatementAllWKTParams(sql, geom.toText()); return createNativeSQLStatementAllWKTParams( sql, geom.toText() );
} }
@Override @Override
protected NativeSQLStatement createNativeIntersectsStatement(Geometry geom) { protected NativeSQLStatement createNativeIntersectsStatement(Geometry geom) {
return createNativeSQLStatementAllWKTParams( return createNativeSQLStatementAllWKTParams(
"select t.id, st_intersects(t.geom, ST_GeomFromText(?, 4326)) from GeomTest t where st_intersects(t.geom, ST_GeomFromText(?, 4326)) = 'true' and ST_SRID(t.geom) = 4326", "select t.id, st_intersects(t.geom, ST_GeomFromText(?, 4326)) from GeomTest t where st_intersects(t.geom, ST_GeomFromText(?, 4326)) = 'true' and ST_SRID(t.geom) = 4326",
geom.toText()); geom.toText()
} );
}
@Override @Override
protected NativeSQLStatement createNativeFilterStatement(Geometry geom) { protected NativeSQLStatement createNativeFilterStatement(Geometry geom) {
return createNativeSQLStatementAllWKTParams( return createNativeSQLStatementAllWKTParams(
"select t.id, t.geom && ST_GeomFromText(?, 4326) from GeomTest t where st_intersects(t.geom, ST_GeomFromText(?, 4326)) = 'true' and ST_SRID(t.geom) = 4326", "select t.id, t.geom && ST_GeomFromText(?, 4326) from GeomTest t where st_intersects(t.geom, ST_GeomFromText(?, 4326)) = 'true' and ST_SRID(t.geom) = 4326",
geom.toText()); geom.toText()
} );
}
@Override @Override
protected NativeSQLStatement createNativeDistanceStatement(Geometry geom) { protected NativeSQLStatement createNativeDistanceStatement(Geometry geom) {
return createNativeSQLStatementAllWKTParams( return createNativeSQLStatementAllWKTParams(
"select t.id, st_distance(t.geom, ST_GeomFromText(?, 4326)) from GeomTest t where ST_SRID(t.geom) = 4326", "select t.id, st_distance(t.geom, ST_GeomFromText(?, 4326)) from GeomTest t where ST_SRID(t.geom) = 4326",
geom.toText()); geom.toText()
} );
}
@Override @Override
protected NativeSQLStatement createNativeDimensionSQL() { protected NativeSQLStatement createNativeDimensionSQL() {
return createNativeSQLStatement("select id, st_dimension(geom) from geomtest"); return createNativeSQLStatement( "select id, st_dimension(geom) from geomtest" );
} }
@Override @Override
protected NativeSQLStatement createNativeBufferStatement(Double distance) { protected NativeSQLStatement createNativeBufferStatement(Double distance) {
return createNativeSQLStatement("select t.id, st_buffer(t.geom,?) from GeomTest t where ST_SRID(t.geom) = 4326", new Object[]{distance}); return createNativeSQLStatement(
} "select t.id, st_buffer(t.geom,?) from GeomTest t where ST_SRID(t.geom) = 4326",
new Object[] { distance }
);
}
@Override @Override
protected NativeSQLStatement createNativeConvexHullStatement(Geometry geom) { protected NativeSQLStatement createNativeConvexHullStatement(Geometry geom) {
return createNativeSQLStatementAllWKTParams( return createNativeSQLStatementAllWKTParams(
"select t.id, st_convexhull(st_union(t.geom, ST_GeomFromText(?, 4326))) from GeomTest t where ST_SRID(t.geom) = 4326", "select t.id, st_convexhull(st_union(t.geom, ST_GeomFromText(?, 4326))) from GeomTest t where ST_SRID(t.geom) = 4326",
geom.toText()); geom.toText()
} );
}
@Override @Override
protected NativeSQLStatement createNativeIntersectionStatement(Geometry geom) { protected NativeSQLStatement createNativeIntersectionStatement(Geometry geom) {
return createNativeSQLStatementAllWKTParams( return createNativeSQLStatementAllWKTParams(
"select t.id, st_intersection(t.geom, ST_GeomFromText(?, 4326)) from GeomTest t where ST_SRID(t.geom) = 4326", "select t.id, st_intersection(t.geom, ST_GeomFromText(?, 4326)) from GeomTest t where ST_SRID(t.geom) = 4326",
geom.toText()); geom.toText()
} );
}
@Override @Override
protected NativeSQLStatement createNativeDifferenceStatement(Geometry geom) { protected NativeSQLStatement createNativeDifferenceStatement(Geometry geom) {
return createNativeSQLStatementAllWKTParams( return createNativeSQLStatementAllWKTParams(
"select t.id, st_difference(t.geom, ST_GeomFromText(?, 4326)) from GeomTest t where ST_SRID(t.geom) = 4326", "select t.id, st_difference(t.geom, ST_GeomFromText(?, 4326)) from GeomTest t where ST_SRID(t.geom) = 4326",
geom.toText()); geom.toText()
} );
}
@Override @Override
protected NativeSQLStatement createNativeSymDifferenceStatement(Geometry geom) { protected NativeSQLStatement createNativeSymDifferenceStatement(Geometry geom) {
return createNativeSQLStatementAllWKTParams( return createNativeSQLStatementAllWKTParams(
"select t.id, st_symdifference(t.geom, ST_GeomFromText(?, 4326)) from GeomTest t where ST_SRID(t.geom) = 4326", "select t.id, st_symdifference(t.geom, ST_GeomFromText(?, 4326)) from GeomTest t where ST_SRID(t.geom) = 4326",
geom.toText()); geom.toText()
} );
}
@Override @Override
protected NativeSQLStatement createNativeGeomUnionStatement(Geometry geom) { protected NativeSQLStatement createNativeGeomUnionStatement(Geometry geom) {
return createNativeSQLStatementAllWKTParams( return createNativeSQLStatementAllWKTParams(
"select t.id, st_union(t.geom, ST_GeomFromText(?, 4326)) from GeomTest t where ST_SRID(t.geom) = 4326", "select t.id, st_union(t.geom, ST_GeomFromText(?, 4326)) from GeomTest t where ST_SRID(t.geom) = 4326",
geom.toText()); geom.toText()
} );
}
@Override @Override
protected NativeSQLStatement createNativeTransformStatement(int epsg) { protected NativeSQLStatement createNativeTransformStatement(int epsg) {
return createNativeSQLStatement( return createNativeSQLStatement(
"select t.id, st_transform(t.geom," + epsg + ") from GeomTest t where ST_SRID(t.geom) = 4326" "select t.id, st_transform(t.geom," + epsg + ") from GeomTest t where ST_SRID(t.geom) = 4326"
); );
} }
@Override @Override
protected NativeSQLStatement createNativeHavingSRIDStatement(int srid) { protected NativeSQLStatement createNativeHavingSRIDStatement(int srid) {
return createNativeSQLStatement("select t.id, (st_srid(t.geom) = " + srid + ") from GeomTest t where ST_SRID(t.geom) = " + srid); return createNativeSQLStatement( "select t.id, (st_srid(t.geom) = " + srid + ") from GeomTest t where ST_SRID(t.geom) = " + srid );
} }
@Override @Override
protected NativeSQLStatement createNativeAsTextStatement() { protected NativeSQLStatement createNativeAsTextStatement() {
return createNativeSQLStatement("select id, st_astext(geom) from geomtest"); return createNativeSQLStatement( "select id, st_astext(geom) from geomtest" );
} }
@Override @Override
protected NativeSQLStatement createNativeSridStatement() { protected NativeSQLStatement createNativeSridStatement() {
return createNativeSQLStatement("select id, ST_SRID(geom) from geomtest"); return createNativeSQLStatement( "select id, ST_SRID(geom) from geomtest" );
} }
@Override @Override
protected NativeSQLStatement createNativeIsSimpleStatement() { protected NativeSQLStatement createNativeIsSimpleStatement() {
return createNativeSQLStatement("select id, st_issimple(geom) from geomtest"); return createNativeSQLStatement( "select id, st_issimple(geom) from geomtest" );
} }
@Override @Override
protected NativeSQLStatement createNativeIsEmptyStatement() { protected NativeSQLStatement createNativeIsEmptyStatement() {
return createNativeSQLStatement("select id, st_isempty(geom) from geomtest"); return createNativeSQLStatement( "select id, st_isempty(geom) from geomtest" );
} }
@Override @Override
protected NativeSQLStatement createNativeIsNotEmptyStatement() { protected NativeSQLStatement createNativeIsNotEmptyStatement() {
return createNativeSQLStatement("select id, not st_isempty(geom) from geomtest"); return createNativeSQLStatement( "select id, not st_isempty(geom) from geomtest" );
} }
@Override @Override
protected NativeSQLStatement createNativeBoundaryStatement() { protected NativeSQLStatement createNativeBoundaryStatement() {
return createNativeSQLStatement("select id, st_boundary(geom) from geomtest"); return createNativeSQLStatement( "select id, st_boundary(geom) from geomtest" );
} }
@Override @Override
protected NativeSQLStatement createNativeEnvelopeStatement() { protected NativeSQLStatement createNativeEnvelopeStatement() {
return createNativeSQLStatement("select id, st_envelope(geom) from geomtest"); return createNativeSQLStatement( "select id, st_envelope(geom) from geomtest" );
} }
@Override @Override
protected NativeSQLStatement createNativeAsBinaryStatement() { protected NativeSQLStatement createNativeAsBinaryStatement() {
return createNativeSQLStatement("select id, st_asbinary(geom) from geomtest"); return createNativeSQLStatement( "select id, st_asbinary(geom) from geomtest" );
} }
@Override @Override
protected NativeSQLStatement createNativeGeometryTypeStatement() { protected NativeSQLStatement createNativeGeometryTypeStatement() {
return createNativeSQLStatement("select id, st_GeometryType(geom) from geomtest"); return createNativeSQLStatement( "select id, st_GeometryType(geom) from geomtest" );
} }
@Override @Override
protected NativeSQLStatement createNativeWithinStatement(Geometry geom) { protected NativeSQLStatement createNativeWithinStatement(Geometry geom) {
return createNativeSQLStatementAllWKTParams( return createNativeSQLStatementAllWKTParams(
"select t.id, st_within(t.geom, ST_GeomFromText(?, 4326)) from GeomTest t where st_within(t.geom, ST_GeomFromText(?, 4326)) = 'true' and ST_SRID(t.geom) = 4326", "select t.id, st_within(t.geom, ST_GeomFromText(?, 4326)) from GeomTest t where st_within(t.geom, ST_GeomFromText(?, 4326)) = 'true' and ST_SRID(t.geom) = 4326",
geom.toText()); geom.toText()
} );
}
@Override @Override
protected NativeSQLStatement createNativeEqualsStatement(Geometry geom) { protected NativeSQLStatement createNativeEqualsStatement(Geometry geom) {
return createNativeSQLStatementAllWKTParams( return createNativeSQLStatementAllWKTParams(
"select t.id, st_equals(t.geom, ST_GeomFromText(?, 4326)) from GeomTest t where st_equals(t.geom, ST_GeomFromText(?, 4326)) = 'true' and ST_SRID(t.geom) = 4326", "select t.id, st_equals(t.geom, ST_GeomFromText(?, 4326)) from GeomTest t where st_equals(t.geom, ST_GeomFromText(?, 4326)) = 'true' and ST_SRID(t.geom) = 4326",
geom.toText()); geom.toText()
} );
}
@Override @Override
protected NativeSQLStatement createNativeCrossesStatement(Geometry geom) { protected NativeSQLStatement createNativeCrossesStatement(Geometry geom) {
return createNativeSQLStatementAllWKTParams( return createNativeSQLStatementAllWKTParams(
"select t.id, st_crosses(t.geom, ST_GeomFromText(?, 4326)) from GeomTest t where st_crosses(t.geom, ST_GeomFromText(?, 4326)) = 'true' and ST_SRID(t.geom) = 4326", "select t.id, st_crosses(t.geom, ST_GeomFromText(?, 4326)) from GeomTest t where st_crosses(t.geom, ST_GeomFromText(?, 4326)) = 'true' and ST_SRID(t.geom) = 4326",
geom.toText()); geom.toText()
} );
}
@Override @Override
protected NativeSQLStatement createNativeContainsStatement(Geometry geom) { protected NativeSQLStatement createNativeContainsStatement(Geometry geom) {
return createNativeSQLStatementAllWKTParams( return createNativeSQLStatementAllWKTParams(
"select t.id, st_contains(t.geom, ST_GeomFromText(?, 4326)) from GeomTest t where st_contains(t.geom, ST_GeomFromText(?, 4326)) = 'true' and ST_SRID(t.geom) = 4326", "select t.id, st_contains(t.geom, ST_GeomFromText(?, 4326)) from GeomTest t where st_contains(t.geom, ST_GeomFromText(?, 4326)) = 'true' and ST_SRID(t.geom) = 4326",
geom.toText()); geom.toText()
} );
}
@Override @Override
protected NativeSQLStatement createNativeDisjointStatement(Geometry geom) { protected NativeSQLStatement createNativeDisjointStatement(Geometry geom) {
return createNativeSQLStatementAllWKTParams( return createNativeSQLStatementAllWKTParams(
"select t.id, st_disjoint(t.geom, ST_GeomFromText(?, 4326)) from GeomTest t where st_disjoint(t.geom, ST_GeomFromText(?, 4326)) = 'true' and ST_SRID(t.geom) = 4326", "select t.id, st_disjoint(t.geom, ST_GeomFromText(?, 4326)) from GeomTest t where st_disjoint(t.geom, ST_GeomFromText(?, 4326)) = 'true' and ST_SRID(t.geom) = 4326",
geom.toText()); geom.toText()
} );
}
@Override @Override
protected Geometry decode(Object o) { protected Geometry decode(Object o) {
return decoder.toJTS(o); return decoder.toJTS( o );
} }
} }

View File

@ -35,9 +35,15 @@
*/ */
public class PostgisExpressionTemplate implements SQLExpressionTemplate { public class PostgisExpressionTemplate implements SQLExpressionTemplate {
final String SQL_TEMPLATE = "insert into geomtest values (%d, '%s', GeomFromText('%s', %d))"; final String SQL_TEMPLATE = "insert into geomtest values (%d, '%s', GeomFromText('%s', %d))";
public String toInsertSql(TestDataElement testDataElement) { public String toInsertSql(TestDataElement testDataElement) {
return String.format(SQL_TEMPLATE, testDataElement.id, testDataElement.type, testDataElement.wkt, testDataElement.srid); return String.format(
} SQL_TEMPLATE,
testDataElement.id,
testDataElement.type,
testDataElement.wkt,
testDataElement.srid
);
}
} }

View File

@ -1,7 +1,11 @@
package org.hibernate.spatial.dialect.postgis; package org.hibernate.spatial.dialect.postgis;
import org.hibernate.spatial.test.*; import org.hibernate.spatial.test.AbstractExpectationsFactory;
import org.hibernate.spatial.test.DataSourceUtils;
import org.hibernate.spatial.test.SQLExpressionTemplate;
import org.hibernate.spatial.test.TestData;
import org.hibernate.spatial.test.TestSupport;
import org.hibernate.testing.junit4.BaseCoreFunctionalTestCase; import org.hibernate.testing.junit4.BaseCoreFunctionalTestCase;
/** /**
@ -11,22 +15,22 @@
public class PostgisTestSupport extends TestSupport { public class PostgisTestSupport extends TestSupport {
public TestData createTestData(BaseCoreFunctionalTestCase testcase) { public TestData createTestData(BaseCoreFunctionalTestCase testcase) {
if (testcase.getClass().getCanonicalName().contains("TestSpatialFunctions") || if ( testcase.getClass().getCanonicalName().contains( "TestSpatialFunctions" ) ||
testcase.getClass().getCanonicalName().contains("TestSpatialRestrictions")) { testcase.getClass().getCanonicalName().contains( "TestSpatialRestrictions" ) ) {
return TestData.fromFile("postgis-functions-test.xml"); return TestData.fromFile( "postgis-functions-test.xml" );
} }
return TestData.fromFile("test-data-set.xml"); return TestData.fromFile( "test-data-set.xml" );
} }
public AbstractExpectationsFactory createExpectationsFactory(DataSourceUtils dataSourceUtils) { public AbstractExpectationsFactory createExpectationsFactory(DataSourceUtils dataSourceUtils) {
return new PostgisExpectationsFactory(dataSourceUtils); return new PostgisExpectationsFactory( dataSourceUtils );
} }
@Override @Override
public SQLExpressionTemplate getSQLExpressionTemplate() { public SQLExpressionTemplate getSQLExpressionTemplate() {
return new org.hibernate.spatial.dialect.postgis.PostgisExpressionTemplate(); return new org.hibernate.spatial.dialect.postgis.PostgisExpressionTemplate();
} }
} }

View File

@ -1,10 +1,11 @@
package org.hibernate.spatial.dialect.postgis.unittests; package org.hibernate.spatial.dialect.postgis.unittests;
import junit.framework.TestCase; import junit.framework.TestCase;
import org.junit.Test;
import org.hibernate.spatial.SpatialDialect; import org.hibernate.spatial.SpatialDialect;
import org.hibernate.spatial.SpatialFunction; import org.hibernate.spatial.SpatialFunction;
import org.hibernate.spatial.dialect.postgis.PostgisDialect; import org.hibernate.spatial.dialect.postgis.PostgisDialect;
import org.junit.Test;
/** /**
* Tests support for * Tests support for
@ -14,12 +15,12 @@
*/ */
public class PostgisDialectTest extends TestCase { public class PostgisDialectTest extends TestCase {
SpatialDialect dialect = new PostgisDialect(); SpatialDialect dialect = new PostgisDialect();
@Test @Test
public void testSupports() throws Exception { public void testSupports() throws Exception {
for (SpatialFunction sf : SpatialFunction.values()) { for ( SpatialFunction sf : SpatialFunction.values() ) {
assertTrue("Dialect doesn't support " + sf, dialect.supports(sf)); assertTrue( "Dialect doesn't support " + sf, dialect.supports( sf ) );
} }
} }
} }

View File

@ -25,19 +25,28 @@
package org.hibernate.spatial.test; package org.hibernate.spatial.test;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.StringWriter;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import javax.sql.DataSource;
import com.vividsolutions.jts.geom.Geometry; import com.vividsolutions.jts.geom.Geometry;
import com.vividsolutions.jts.io.ParseException; import com.vividsolutions.jts.io.ParseException;
import org.apache.commons.dbcp.BasicDataSource; import org.apache.commons.dbcp.BasicDataSource;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import javax.sql.DataSource;
import java.io.*;
import java.sql.*;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
/** /**
* <p>Unit testsuite-suite support class.</p> * <p>Unit testsuite-suite support class.</p>
* *
@ -46,298 +55,338 @@
public class DataSourceUtils { public class DataSourceUtils {
private static Logger LOGGER = LoggerFactory.getLogger(DataSourceUtils.class); private static Logger LOGGER = LoggerFactory.getLogger( DataSourceUtils.class );
private final SQLExpressionTemplate sqlExpressionTemplate; private final SQLExpressionTemplate sqlExpressionTemplate;
private final String jdbcDriver; private final String jdbcDriver;
private final String jdbcUrl; private final String jdbcUrl;
private final String jdbcUser; private final String jdbcUser;
private final String jdbcPass; private final String jdbcPass;
private DataSource dataSource; private DataSource dataSource;
/** /**
* Constructor for the DataSourceUtils object. * Constructor for the DataSourceUtils object.
* <p/> * <p/>
* <p>The following entities are required in the property file: * <p>The following entities are required in the property file:
* <il> * <il>
* <li> jdbcUrl: jdbc connection URL</li> * <li> jdbcUrl: jdbc connection URL</li>
* <li> dbUsername: username for the database</li> * <li> dbUsername: username for the database</li>
* <li> dbPassword: password for the database</li> * <li> dbPassword: password for the database</li>
* <li> driver: fully-qualified class name for the JDBC Driver</li> * <li> driver: fully-qualified class name for the JDBC Driver</li>
* </il> * </il>
* *
* @param jdbcDriver * @param jdbcDriver
* @param jdbcUrl * @param jdbcUrl
* @param jdbcUser * @param jdbcUser
* @param jdbcPass * @param jdbcPass
* @param sqlExpressionTemplate SQLExpressionTemplate object that generates SQL statements for this database * @param sqlExpressionTemplate SQLExpressionTemplate object that generates SQL statements for this database
*/ */
public DataSourceUtils(String jdbcDriver, String jdbcUrl, String jdbcUser, String jdbcPass, SQLExpressionTemplate sqlExpressionTemplate) { public DataSourceUtils(String jdbcDriver, String jdbcUrl, String jdbcUser, String jdbcPass, SQLExpressionTemplate sqlExpressionTemplate) {
this.jdbcDriver = jdbcDriver; this.jdbcDriver = jdbcDriver;
this.jdbcUrl = jdbcUrl; this.jdbcUrl = jdbcUrl;
this.jdbcUser = jdbcUser; this.jdbcUser = jdbcUser;
this.jdbcPass = jdbcPass; this.jdbcPass = jdbcPass;
this.sqlExpressionTemplate = sqlExpressionTemplate; this.sqlExpressionTemplate = sqlExpressionTemplate;
createBasicDataSource(); createBasicDataSource();
} }
/** /**
* Constructor using a properties file * Constructor using a properties file
* *
* @param propertyFile * @param propertyFile
* @param template * @param template
*/ */
public DataSourceUtils(String propertyFile, SQLExpressionTemplate template) { public DataSourceUtils(String propertyFile, SQLExpressionTemplate template) {
Properties properties = readProperties(propertyFile); Properties properties = readProperties( propertyFile );
this.jdbcUrl = properties.getProperty("jdbcUrl"); this.jdbcUrl = properties.getProperty( "jdbcUrl" );
this.jdbcDriver = properties.getProperty("jdbcDriver"); this.jdbcDriver = properties.getProperty( "jdbcDriver" );
this.jdbcUser = properties.getProperty("jdbcUser"); this.jdbcUser = properties.getProperty( "jdbcUser" );
this.jdbcPass = properties.getProperty("jdbcPass"); this.jdbcPass = properties.getProperty( "jdbcPass" );
this.sqlExpressionTemplate = template; this.sqlExpressionTemplate = template;
createBasicDataSource(); createBasicDataSource();
} }
private Properties readProperties(String propertyFile) { private Properties readProperties(String propertyFile) {
InputStream is = null; InputStream is = null;
try { try {
is = Thread.currentThread().getContextClassLoader().getResourceAsStream(propertyFile); is = Thread.currentThread().getContextClassLoader().getResourceAsStream( propertyFile );
if (is == null) throw new RuntimeException(String.format("File %s not found on classpath.", propertyFile)); if ( is == null ) {
Properties properties = new Properties(); throw new RuntimeException( String.format( "File %s not found on classpath.", propertyFile ) );
properties.load(is); }
return properties; Properties properties = new Properties();
} catch (IOException e) { properties.load( is );
throw (new RuntimeException(e)); return properties;
} finally { }
if (is != null) try { catch ( IOException e ) {
is.close(); throw ( new RuntimeException( e ) );
} catch (IOException e) { }
//nothing to do finally {
} if ( is != null ) {
} try {
} is.close();
}
catch ( IOException e ) {
//nothing to do
}
}
}
}
private void createBasicDataSource() { private void createBasicDataSource() {
BasicDataSource bds = new BasicDataSource(); BasicDataSource bds = new BasicDataSource();
bds.setDriverClassName(jdbcDriver); bds.setDriverClassName( jdbcDriver );
bds.setUrl(jdbcUrl); bds.setUrl( jdbcUrl );
bds.setUsername(jdbcUser); bds.setUsername( jdbcUser );
bds.setPassword(jdbcPass); bds.setPassword( jdbcPass );
dataSource = bds; dataSource = bds;
} }
/** /**
* Closes the connections to the database. * Closes the connections to the database.
* *
* @throws SQLException * @throws SQLException
*/ */
public void close() throws SQLException { public void close() throws SQLException {
((BasicDataSource) dataSource).close(); ( (BasicDataSource) dataSource ).close();
} }
/** /**
* Returns a DataSource for the configured database. * Returns a DataSource for the configured database.
* *
* @return a DataSource * @return a DataSource
*/ */
public DataSource getDataSource() { public DataSource getDataSource() {
return dataSource; return dataSource;
} }
/** /**
* Returns a JDBC connection to the database * Returns a JDBC connection to the database
* *
* @return a JDBC Connection object * @return a JDBC Connection object
* @throws SQLException *
*/ * @throws SQLException
public Connection getConnection() throws SQLException { */
Connection cn = getDataSource().getConnection(); public Connection getConnection() throws SQLException {
cn.setAutoCommit(false); Connection cn = getDataSource().getConnection();
return cn; cn.setAutoCommit( false );
} return cn;
}
/** /**
* Delete all testsuite-suite data from the database * Delete all testsuite-suite data from the database
* *
* @throws SQLException * @throws SQLException
*/ */
public void deleteTestData() throws SQLException { public void deleteTestData() throws SQLException {
Connection cn = null; Connection cn = null;
try { try {
cn = getDataSource().getConnection(); cn = getDataSource().getConnection();
cn.setAutoCommit(false); cn.setAutoCommit( false );
PreparedStatement pmt = cn.prepareStatement("delete from GEOMTEST"); PreparedStatement pmt = cn.prepareStatement( "delete from GEOMTEST" );
if (!pmt.execute()) { if ( !pmt.execute() ) {
int updateCount = pmt.getUpdateCount(); int updateCount = pmt.getUpdateCount();
LOGGER.info("Removing " + updateCount + " rows."); LOGGER.info( "Removing " + updateCount + " rows." );
} }
cn.commit(); cn.commit();
pmt.close(); pmt.close();
} finally { }
try { finally {
if (cn != null) cn.close(); try {
} catch (SQLException e) { if ( cn != null ) {
// nothing to do cn.close();
} }
} }
} catch ( SQLException e ) {
// nothing to do
}
}
}
public void insertTestData(TestData testData) throws SQLException { public void insertTestData(TestData testData) throws SQLException {
Connection cn = null; Connection cn = null;
try { try {
cn = getDataSource().getConnection(); cn = getDataSource().getConnection();
cn.setAutoCommit(false); cn.setAutoCommit( false );
Statement stmt = cn.createStatement(); Statement stmt = cn.createStatement();
for (TestDataElement testDataElement : testData) { for ( TestDataElement testDataElement : testData ) {
String sql = sqlExpressionTemplate.toInsertSql(testDataElement); String sql = sqlExpressionTemplate.toInsertSql( testDataElement );
LOGGER.debug("adding stmt: " + sql); LOGGER.debug( "adding stmt: " + sql );
stmt.addBatch(sql); stmt.addBatch( sql );
} }
int[] insCounts = stmt.executeBatch(); int[] insCounts = stmt.executeBatch();
cn.commit(); cn.commit();
stmt.close(); stmt.close();
LOGGER.info("Loaded " + sum(insCounts) + " rows."); LOGGER.info( "Loaded " + sum( insCounts ) + " rows." );
} finally { }
try { finally {
if (cn != null) cn.close(); try {
} catch (SQLException e) { if ( cn != null ) {
// nothing to do cn.close();
} }
} }
} catch ( SQLException e ) {
// nothing to do
}
}
}
/** /**
* Parses the content of a file into an executable SQL statement. * Parses the content of a file into an executable SQL statement.
* *
* @param fileName name of a file containing SQL-statements * @param fileName name of a file containing SQL-statements
* @return *
* @throws IOException * @return
*/ *
public String parseSqlIn(String fileName) throws IOException { * @throws IOException
InputStream is = Thread.currentThread().getContextClassLoader().getResourceAsStream(fileName); */
if (is == null) { public String parseSqlIn(String fileName) throws IOException {
throw new RuntimeException("File " + fileName + " not found on Classpath."); InputStream is = Thread.currentThread().getContextClassLoader().getResourceAsStream( fileName );
} if ( is == null ) {
try { throw new RuntimeException( "File " + fileName + " not found on Classpath." );
BufferedReader reader = new BufferedReader( }
new InputStreamReader(is)); try {
BufferedReader reader = new BufferedReader(
new InputStreamReader( is )
);
StringWriter sw = new StringWriter(); StringWriter sw = new StringWriter();
BufferedWriter writer = new BufferedWriter(sw); BufferedWriter writer = new BufferedWriter( sw );
for (int c = reader.read(); c != -1; c = reader.read()) { for ( int c = reader.read(); c != -1; c = reader.read() ) {
writer.write(c); writer.write( c );
} }
writer.flush(); writer.flush();
return sw.toString(); return sw.toString();
} finally { }
if (is != null) { finally {
is.close(); if ( is != null ) {
} is.close();
} }
} }
}
/** /**
* Executes a SQL statement. * Executes a SQL statement.
* <p/> * <p/>
* This is used e.g. to drop/create a spatial index, or update the * This is used e.g. to drop/create a spatial index, or update the
* geometry metadata statements. * geometry metadata statements.
* *
* @param sql the (native) SQL Statement to execute * @param sql the (native) SQL Statement to execute
* @throws SQLException *
*/ * @throws SQLException
public void executeStatement(String sql) throws SQLException { */
Connection cn = null; public void executeStatement(String sql) throws SQLException {
try { Connection cn = null;
cn = getDataSource().getConnection(); try {
cn.setAutoCommit(false); cn = getDataSource().getConnection();
PreparedStatement statement = cn.prepareStatement(sql); cn.setAutoCommit( false );
LOGGER.info("Executing statement: " + sql); PreparedStatement statement = cn.prepareStatement( sql );
statement.execute(); LOGGER.info( "Executing statement: " + sql );
cn.commit(); statement.execute();
statement.close(); cn.commit();
} finally { statement.close();
try { }
if (cn != null) cn.close(); finally {
} catch (SQLException e) { try {
} //do nothing. if ( cn != null ) {
} cn.close();
} }
}
catch ( SQLException e ) {
} //do nothing.
}
}
/** /**
* Operations to fully initialize the * Operations to fully initialize the
*/ */
public void afterCreateSchema() { public void afterCreateSchema() {
} }
/** /**
* Return the geometries of the testsuite-suite objects as raw (i.e. undecoded) objects from the database. * Return the geometries of the testsuite-suite objects as raw (i.e. undecoded) objects from the database.
* *
* @param type type of geometry * @param type type of geometry
* @return map of identifier, undecoded geometry object *
*/ * @return map of identifier, undecoded geometry object
public Map<Integer, Object> rawDbObjects(String type) { */
Map<Integer, Object> map = new HashMap<Integer, Object>(); public Map<Integer, Object> rawDbObjects(String type) {
Connection cn = null; Map<Integer, Object> map = new HashMap<Integer, Object>();
try { Connection cn = null;
cn = getDataSource().getConnection(); try {
PreparedStatement pstmt = cn.prepareStatement("select id, geom from geomtest where type = ? order by id"); cn = getDataSource().getConnection();
pstmt.setString(1, type); PreparedStatement pstmt = cn.prepareStatement( "select id, geom from geomtest where type = ? order by id" );
ResultSet results = pstmt.executeQuery(); pstmt.setString( 1, type );
while (results.next()) { ResultSet results = pstmt.executeQuery();
Integer id = results.getInt(1); while ( results.next() ) {
Object obj = results.getObject(2); Integer id = results.getInt( 1 );
map.put(id, obj); Object obj = results.getObject( 2 );
} map.put( id, obj );
}
} catch (SQLException e) { }
e.printStackTrace(); catch ( SQLException e ) {
} finally { e.printStackTrace();
try { }
if (cn != null) cn.close(); finally {
} catch (SQLException e) { try {
// nothing we can do. if ( cn != null ) {
} cn.close();
} }
return map; }
catch ( SQLException e ) {
// nothing we can do.
}
}
return map;
} }
/** /**
* Returns the JTS geometries that are expected of a decoding of the testsuite-suite object's geometry. * Returns the JTS geometries that are expected of a decoding of the testsuite-suite object's geometry.
* <p/> * <p/>
* <p>This method reads the WKT of the testsuite-suite objects and returns the result.</p> * <p>This method reads the WKT of the testsuite-suite objects and returns the result.</p>
* *
* @param type type of geometry * @param type type of geometry
* @return map of identifier and JTS geometry *
*/ * @return map of identifier and JTS geometry
public Map<Integer, Geometry> expectedGeoms(String type, TestData testData) { */
Map<Integer, Geometry> result = new HashMap<Integer, Geometry>(); public Map<Integer, Geometry> expectedGeoms(String type, TestData testData) {
EWKTReader parser = new EWKTReader(); Map<Integer, Geometry> result = new HashMap<Integer, Geometry>();
for (TestDataElement testDataElement : testData) { EWKTReader parser = new EWKTReader();
if (testDataElement.type.equalsIgnoreCase(type)) { for ( TestDataElement testDataElement : testData ) {
try { if ( testDataElement.type.equalsIgnoreCase( type ) ) {
result.put(testDataElement.id, parser.read(testDataElement.wkt)); try {
} catch (ParseException e) { result.put( testDataElement.id, parser.read( testDataElement.wkt ) );
System.out.println(String.format("Parsing WKT fails for case %d : %s", testDataElement.id, testDataElement.wkt)); }
throw new RuntimeException(e); catch ( ParseException e ) {
} System.out
} .println(
} String.format(
return result; "Parsing WKT fails for case %d : %s",
} testDataElement.id,
testDataElement.wkt
)
);
throw new RuntimeException( e );
}
}
}
return result;
}
private static int sum(int[] insCounts) { private static int sum(int[] insCounts) {
int result = 0; int result = 0;
for (int idx = 0; idx < insCounts.length; idx++) { for ( int idx = 0; idx < insCounts.length; idx++ ) {
result += insCounts[idx]; result += insCounts[idx];
} }
return result; return result;
} }
} }

View File

@ -33,61 +33,67 @@
*/ */
public class GeomEntity implements TestFeature { public class GeomEntity implements TestFeature {
private Integer id; private Integer id;
private String type; private String type;
private Geometry geom; private Geometry geom;
public Integer getId() { public Integer getId() {
return id; return id;
} }
public void setId(Integer id) { public void setId(Integer id) {
this.id = id; this.id = id;
} }
public String getType() { public String getType() {
return type; return type;
} }
public void setType(String type) { public void setType(String type) {
this.type = type; this.type = type;
} }
public Geometry getGeom() { public Geometry getGeom() {
return geom; return geom;
} }
public void setGeom(Geometry geom) { public void setGeom(Geometry geom) {
this.geom = geom; this.geom = geom;
} }
public static GeomEntity createFrom(TestDataElement element) throws ParseException { public static GeomEntity createFrom(TestDataElement element) throws ParseException {
EWKTReader reader = new EWKTReader(); EWKTReader reader = new EWKTReader();
GeomEntity result = new GeomEntity(); GeomEntity result = new GeomEntity();
result.setId(element.id); result.setId( element.id );
Geometry geom = reader.read(element.wkt); Geometry geom = reader.read( element.wkt );
geom.setSRID(element.srid); geom.setSRID( element.srid );
result.setGeom(geom); result.setGeom( geom );
result.setType(element.type); result.setType( element.type );
return result; return result;
} }
@Override @Override
public boolean equals(Object o) { public boolean equals(Object o) {
if (this == o) return true; if ( this == o ) {
if (o == null || getClass() != o.getClass()) return false; return true;
}
if ( o == null || getClass() != o.getClass() ) {
return false;
}
GeomEntity geomEntity = (GeomEntity) o; GeomEntity geomEntity = (GeomEntity) o;
if (id != geomEntity.id) return false; if ( id != geomEntity.id ) {
return false;
}
return true; return true;
} }
@Override @Override
public int hashCode() { public int hashCode() {
return id; return id;
} }
} }

View File

@ -28,6 +28,7 @@
import com.vividsolutions.jts.geom.Coordinate; import com.vividsolutions.jts.geom.Coordinate;
import com.vividsolutions.jts.geom.Geometry; import com.vividsolutions.jts.geom.Geometry;
import com.vividsolutions.jts.geom.GeometryCollection; import com.vividsolutions.jts.geom.GeometryCollection;
import org.hibernate.spatial.mgeom.MCoordinate; import org.hibernate.spatial.mgeom.MCoordinate;
/** /**
@ -38,59 +39,83 @@
*/ */
public class GeometryEquality { public class GeometryEquality {
public boolean test(Geometry geom1, Geometry geom2) { public boolean test(Geometry geom1, Geometry geom2) {
if (geom1 == null) return geom2 == null; if ( geom1 == null ) {
if (geom1.isEmpty()) return geom2.isEmpty() && geom1.getSRID() == geom2.getSRID(); return geom2 == null;
if (geom1 instanceof GeometryCollection) { }
if (!(geom2 instanceof GeometryCollection)) return false; if ( geom1.isEmpty() ) {
GeometryCollection expectedCollection = (GeometryCollection) geom1; return geom2.isEmpty() && geom1.getSRID() == geom2.getSRID();
GeometryCollection receivedCollection = (GeometryCollection) geom2; }
for (int partIndex = 0; partIndex < expectedCollection.getNumGeometries(); partIndex++) { if ( geom1 instanceof GeometryCollection ) {
Geometry partExpected = expectedCollection.getGeometryN(partIndex); if ( !( geom2 instanceof GeometryCollection ) ) {
Geometry partReceived = receivedCollection.getGeometryN(partIndex); return false;
if (!test(partExpected, partReceived)) return false; }
} GeometryCollection expectedCollection = (GeometryCollection) geom1;
return true; GeometryCollection receivedCollection = (GeometryCollection) geom2;
} else { for ( int partIndex = 0; partIndex < expectedCollection.getNumGeometries(); partIndex++ ) {
return testSimpleGeometryEquality(geom1, geom2); Geometry partExpected = expectedCollection.getGeometryN( partIndex );
} Geometry partReceived = receivedCollection.getGeometryN( partIndex );
} if ( !test( partExpected, partReceived ) ) {
return false;
}
}
return true;
}
else {
return testSimpleGeometryEquality( geom1, geom2 );
}
}
/** /**
* Test whether two geometries, not of type GeometryCollection are equal. * Test whether two geometries, not of type GeometryCollection are equal.
* *
* @param geom1 * @param geom1
* @param geom2 * @param geom2
* @return *
*/ * @return
protected boolean testSimpleGeometryEquality(Geometry geom1, Geometry geom2) { */
//return geom1.equals(geom2); protected boolean testSimpleGeometryEquality(Geometry geom1, Geometry geom2) {
return testTypeAndVertexEquality(geom1, geom2) && geom1.getSRID() == geom2.getSRID(); //return geom1.equals(geom2);
} return testTypeAndVertexEquality( geom1, geom2 ) && geom1.getSRID() == geom2.getSRID();
}
protected boolean testTypeAndVertexEquality(Geometry geom1, Geometry geom2) { protected boolean testTypeAndVertexEquality(Geometry geom1, Geometry geom2) {
if (!geom1.getGeometryType().equals(geom2.getGeometryType())) return false; if ( !geom1.getGeometryType().equals( geom2.getGeometryType() ) ) {
if (geom1.getNumGeometries() != geom2.getNumGeometries()) return false; return false;
if (geom1.getNumPoints() != geom2.getNumPoints()) return false; }
Coordinate[] coordinates1 = geom1.getCoordinates(); if ( geom1.getNumGeometries() != geom2.getNumGeometries() ) {
Coordinate[] coordinates2 = geom2.getCoordinates(); return false;
for (int i = 0; i < coordinates1.length; i++) { }
Coordinate c1 = coordinates1[i]; if ( geom1.getNumPoints() != geom2.getNumPoints() ) {
Coordinate c2 = coordinates2[i]; return false;
if (!testCoordinateEquality(c1, c2)) return false; }
} Coordinate[] coordinates1 = geom1.getCoordinates();
return true; Coordinate[] coordinates2 = geom2.getCoordinates();
} for ( int i = 0; i < coordinates1.length; i++ ) {
Coordinate c1 = coordinates1[i];
Coordinate c2 = coordinates2[i];
if ( !testCoordinateEquality( c1, c2 ) ) {
return false;
}
}
return true;
}
private boolean testCoordinateEquality(Coordinate c1, Coordinate c2) { private boolean testCoordinateEquality(Coordinate c1, Coordinate c2) {
if (c1 instanceof MCoordinate) { if ( c1 instanceof MCoordinate ) {
if (!(c2 instanceof MCoordinate)) return false; if ( !( c2 instanceof MCoordinate ) ) {
MCoordinate mc1 = (MCoordinate) c1; return false;
MCoordinate mc2 = (MCoordinate) c2; }
if (!Double.isNaN(mc1.m) && mc1.m != mc2.m) return false; MCoordinate mc1 = (MCoordinate) c1;
} MCoordinate mc2 = (MCoordinate) c2;
if (!Double.isNaN(c1.z) && c1.z != c2.z) return false; if ( !Double.isNaN( mc1.m ) && mc1.m != mc2.m ) {
return c1.x == c2.x && c1.y == c2.y; return false;
} }
}
if ( !Double.isNaN( c1.z ) && c1.z != c2.z ) {
return false;
}
return c1.x == c2.x && c1.y == c2.y;
}
} }

View File

@ -38,12 +38,14 @@
*/ */
public interface NativeSQLStatement { public interface NativeSQLStatement {
/** /**
* create a PreparedStatement from the specified connection * create a PreparedStatement from the specified connection
* *
* @param connection Connection to the database. * @param connection Connection to the database.
* @return *
* @throws SQLException * @return
*/ *
public PreparedStatement prepare(Connection connection) throws SQLException; * @throws SQLException
*/
public PreparedStatement prepare(Connection connection) throws SQLException;
} }

View File

@ -33,12 +33,13 @@
*/ */
public interface SQLExpressionTemplate { public interface SQLExpressionTemplate {
/** /**
* Returns an insert SQL statement for the specified <code>TestDataElement</code> * Returns an insert SQL statement for the specified <code>TestDataElement</code>
* *
* @param testDataElement * @param testDataElement
* @return an insert SQL for testDataElement *
*/ * @return an insert SQL for testDataElement
public String toInsertSql(TestDataElement testDataElement); */
public String toInsertSql(TestDataElement testDataElement);
} }

View File

@ -29,10 +29,14 @@
package org.hibernate.spatial.test; package org.hibernate.spatial.test;
import com.vividsolutions.jts.geom.Coordinate; import com.vividsolutions.jts.geom.Coordinate;
import org.hibernate.spatial.Circle;
import org.junit.Test; import org.junit.Test;
import static org.junit.Assert.*; import org.hibernate.spatial.Circle;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
/** /**
* Test functionality of Circle class Date: Oct 15, 2007 * Test functionality of Circle class Date: Oct 15, 2007
@ -41,156 +45,164 @@
*/ */
public class TestCircle { public class TestCircle {
@Test @Test
public void testCreateCircle() { public void testCreateCircle() {
Coordinate center = (new Coordinate(0, 0)); Coordinate center = ( new Coordinate( 0, 0 ) );
double radius = 5; double radius = 5;
Coordinate p1 = new Coordinate(3, 4); Coordinate p1 = new Coordinate( 3, 4 );
Coordinate p2 = new Coordinate(0, 5); Coordinate p2 = new Coordinate( 0, 5 );
Coordinate p3 = new Coordinate(-3, 4); Coordinate p3 = new Coordinate( -3, 4 );
Circle c0 = new Circle(center, radius); Circle c0 = new Circle( center, radius );
Circle c1 = new Circle(p1, p2, p3); Circle c1 = new Circle( p1, p2, p3 );
assertEquals(c0, c1); assertEquals( c0, c1 );
assertTrue(Double.compare(c1.getRadius(), radius) == 0); assertTrue( Double.compare( c1.getRadius(), radius ) == 0 );
assertTrue(c1.getCenter().equals2D(center)); assertTrue( c1.getCenter().equals2D( center ) );
double distance = c1.distanceFromCenter(p3); double distance = c1.distanceFromCenter( p3 );
assertTrue(Double.compare(c1.getRadius(), distance) == 0); assertTrue( Double.compare( c1.getRadius(), distance ) == 0 );
} }
@Test @Test
public void testNormalize() { public void testNormalize() {
double actual, expected = 0; double actual, expected = 0;
double angleIncr = Math.PI / 4; // increment by 45 degrees double angleIncr = Math.PI / 4; // increment by 45 degrees
double twoPi = Math.PI * 2; double twoPi = Math.PI * 2;
int factor = 8; int factor = 8;
for (int i = 0; i <= factor; i++) { for ( int i = 0; i <= factor; i++ ) {
expected = i * angleIncr; expected = i * angleIncr;
actual = (Circle.normalizeAngle(expected)); actual = ( Circle.normalizeAngle( expected ) );
assertEquals(actual, expected, Math.ulp(expected)); assertEquals( actual, expected, Math.ulp( expected ) );
double degrees = Math.toDegrees(actual); double degrees = Math.toDegrees( actual );
assertTrue(actual <= twoPi); assertTrue( actual <= twoPi );
assertTrue(degrees <= 360); assertTrue( degrees <= 360 );
} }
factor = -8; factor = -8;
double testAngle; double testAngle;
for (int i = -1; i >= factor; i--) { for ( int i = -1; i >= factor; i-- ) {
testAngle = i * angleIncr; testAngle = i * angleIncr;
expected = twoPi + (i * angleIncr); expected = twoPi + ( i * angleIncr );
actual = (Circle.normalizeAngle(testAngle)); actual = ( Circle.normalizeAngle( testAngle ) );
assertEquals(actual, expected, Math.ulp(expected)); assertEquals( actual, expected, Math.ulp( expected ) );
double degrees = Math.toDegrees(actual); double degrees = Math.toDegrees( actual );
assertTrue(actual <= Math.PI * 2); assertTrue( actual <= Math.PI * 2 );
assertTrue(degrees <= 360); assertTrue( degrees <= 360 );
} }
// couple extra boundary cases // couple extra boundary cases
expected = 0; expected = 0;
actual = Circle.normalizeAngle(twoPi * 8); actual = Circle.normalizeAngle( twoPi * 8 );
assertEquals(expected, actual, Math.ulp(expected)); assertEquals( expected, actual, Math.ulp( expected ) );
testAngle = angleIncr + twoPi; testAngle = angleIncr + twoPi;
expected = angleIncr; expected = angleIncr;
actual = Circle.normalizeAngle(testAngle); actual = Circle.normalizeAngle( testAngle );
assertEquals(expected, actual, Math.ulp(expected)); assertEquals( expected, actual, Math.ulp( expected ) );
testAngle = angleIncr - twoPi; testAngle = angleIncr - twoPi;
expected = angleIncr; expected = angleIncr;
actual = Circle.normalizeAngle(testAngle); actual = Circle.normalizeAngle( testAngle );
assertEquals(expected, actual, Math.ulp(expected)); assertEquals( expected, actual, Math.ulp( expected ) );
} }
@Test @Test
public void testAngleDifference() { public void testAngleDifference() {
double a1 = Math.PI / 8; double a1 = Math.PI / 8;
double a2 = Math.PI / 4; double a2 = Math.PI / 4;
double diff = Circle.subtractAngles(a1, a2); double diff = Circle.subtractAngles( a1, a2 );
assertTrue(diff < Math.PI); assertTrue( diff < Math.PI );
diff = Circle.subtractAngles(a2, a1); diff = Circle.subtractAngles( a2, a1 );
assertTrue(diff > Math.PI); assertTrue( diff > Math.PI );
} }
@Test @Test
public void testMajorArc() { public void testMajorArc() {
Coordinate expectedCenter = new Coordinate(3, 0); Coordinate expectedCenter = new Coordinate( 3, 0 );
double expectedRadius = 5; double expectedRadius = 5;
Coordinate p1 = new Coordinate(0, 4); Coordinate p1 = new Coordinate( 0, 4 );
Coordinate p2 = new Coordinate(8, 0); Coordinate p2 = new Coordinate( 8, 0 );
Coordinate p3 = new Coordinate(0, -4); Coordinate p3 = new Coordinate( 0, -4 );
Circle c = new Circle(p1, p2, p3); Circle c = new Circle( p1, p2, p3 );
assertTrue(c.getCenter().equals2D(expectedCenter)); assertTrue( c.getCenter().equals2D( expectedCenter ) );
assertTrue(Double.compare(c.getRadius(), expectedRadius) == 0); assertTrue( Double.compare( c.getRadius(), expectedRadius ) == 0 );
} }
@Test @Test
public void testArcDirection() { public void testArcDirection() {
Coordinate[] coords = new Coordinate[]{new Coordinate(0, 5), Coordinate[] coords = new Coordinate[] {
new Coordinate(3, 4), new Coordinate(5, 0), new Coordinate( 0, 5 ),
new Coordinate(3, -4), new Coordinate(0, -5), new Coordinate( 3, 4 ), new Coordinate( 5, 0 ),
new Coordinate(-3, -4), new Coordinate(-5, 0), new Coordinate( 3, -4 ), new Coordinate( 0, -5 ),
new Coordinate(-3, 4)}; new Coordinate( -3, -4 ), new Coordinate( -5, 0 ),
for (int i = 0; i < coords.length; i++) { new Coordinate( -3, 4 )
Coordinate p1 = coords[i]; };
Coordinate p2 = coords[(i + 1) % coords.length]; for ( int i = 0; i < coords.length; i++ ) {
Coordinate p3 = coords[(i + 2) % coords.length]; Coordinate p1 = coords[i];
Circle c = new Circle(p1, p2, p3); Coordinate p2 = coords[( i + 1 ) % coords.length];
Circle.Arc a = c.createArc(p1, p2, p3); Coordinate p3 = coords[( i + 2 ) % coords.length];
assertTrue("Failed Points:" + p1 + ", " + p2 + ", " + p3, a Circle c = new Circle( p1, p2, p3 );
.isClockwise()); Circle.Arc a = c.createArc( p1, p2, p3 );
} assertTrue(
"Failed Points:" + p1 + ", " + p2 + ", " + p3, a
.isClockwise()
);
}
for (int i = 0; i < coords.length; i++) { for ( int i = 0; i < coords.length; i++ ) {
Coordinate p3 = coords[i]; Coordinate p3 = coords[i];
Coordinate p2 = coords[(i + 1) % coords.length]; Coordinate p2 = coords[( i + 1 ) % coords.length];
Coordinate p1 = coords[(i + 2) % coords.length]; Coordinate p1 = coords[( i + 2 ) % coords.length];
Circle c = new Circle(p1, p2, p3); Circle c = new Circle( p1, p2, p3 );
Circle.Arc a = c.createArc(p1, p2, p3); Circle.Arc a = c.createArc( p1, p2, p3 );
assertFalse("Failed Points:" + p1 + ", " + p2 + ", " + p3, a assertFalse(
.isClockwise()); "Failed Points:" + p1 + ", " + p2 + ", " + p3, a
} .isClockwise()
} );
}
}
@Test @Test
public void testLinearize() { public void testLinearize() {
Coordinate p1 = new Coordinate(5, 0); Coordinate p1 = new Coordinate( 5, 0 );
Coordinate p2 = new Coordinate(4, 3); Coordinate p2 = new Coordinate( 4, 3 );
Coordinate p3 = new Coordinate(4, -3); Coordinate p3 = new Coordinate( 4, -3 );
Circle c = new Circle(p1, p2, p3); Circle c = new Circle( p1, p2, p3 );
Coordinate[] results = c.linearizeArc(p3, p2, p1, c.getRadius() * 0.01); Coordinate[] results = c.linearizeArc( p3, p2, p1, c.getRadius() * 0.01 );
assertNotNull(results); assertNotNull( results );
assertTrue(results.length > 0); assertTrue( results.length > 0 );
for (Coordinate coord : results) { for ( Coordinate coord : results ) {
double error = c.getRadius() - c.distanceFromCenter(coord); double error = c.getRadius() - c.distanceFromCenter( coord );
assertTrue(Double.compare(error, 0.0001) < 0); assertTrue( Double.compare( error, 0.0001 ) < 0 );
} }
} }
@Test @Test
public void testLinearizeCircle() { public void testLinearizeCircle() {
Coordinate p1 = new Coordinate(5, 0); Coordinate p1 = new Coordinate( 5, 0 );
Coordinate p2 = new Coordinate(4, 3); Coordinate p2 = new Coordinate( 4, 3 );
Coordinate p3 = new Coordinate(4, -3); Coordinate p3 = new Coordinate( 4, -3 );
Circle c = new Circle(p1, p2, p3); Circle c = new Circle( p1, p2, p3 );
Coordinate[] results = c.linearizeArc(p1, p2, p1, Coordinate[] results = c.linearizeArc(
(c.getRadius() * 0.01)); p1, p2, p1,
for (Coordinate coord : results) { ( c.getRadius() * 0.01 )
double error = c.getRadius() - c.distanceFromCenter(coord); );
assertTrue(Double.compare(error, 0.0001) < 0); for ( Coordinate coord : results ) {
} double error = c.getRadius() - c.distanceFromCenter( coord );
assertTrue( Double.compare( error, 0.0001 ) < 0 );
}
} }
} }

View File

@ -40,124 +40,124 @@
*/ */
public class TestData implements List<TestDataElement> { public class TestData implements List<TestDataElement> {
private List<TestDataElement> testDataElements; private List<TestDataElement> testDataElements;
private InputStream in; private InputStream in;
protected TestData() { protected TestData() {
} }
; ;
public int size() { public int size() {
return testDataElements.size(); return testDataElements.size();
} }
public boolean isEmpty() { public boolean isEmpty() {
return testDataElements.isEmpty(); return testDataElements.isEmpty();
} }
public boolean contains(Object o) { public boolean contains(Object o) {
return testDataElements.contains(o); return testDataElements.contains( o );
} }
public Iterator<TestDataElement> iterator() { public Iterator<TestDataElement> iterator() {
return testDataElements.iterator(); return testDataElements.iterator();
} }
public Object[] toArray() { public Object[] toArray() {
return testDataElements.toArray(); return testDataElements.toArray();
} }
public <T> T[] toArray(T[] a) { public <T> T[] toArray(T[] a) {
return testDataElements.toArray(a); return testDataElements.toArray( a );
} }
public boolean add(TestDataElement testDataElement) { public boolean add(TestDataElement testDataElement) {
return testDataElements.add(testDataElement); return testDataElements.add( testDataElement );
} }
public boolean remove(Object o) { public boolean remove(Object o) {
return testDataElements.remove(o); return testDataElements.remove( o );
} }
public boolean containsAll(Collection<?> c) { public boolean containsAll(Collection<?> c) {
return testDataElements.containsAll(c); return testDataElements.containsAll( c );
} }
public boolean addAll(Collection<? extends TestDataElement> c) { public boolean addAll(Collection<? extends TestDataElement> c) {
return testDataElements.addAll(c); return testDataElements.addAll( c );
} }
public boolean addAll(int index, Collection<? extends TestDataElement> c) { public boolean addAll(int index, Collection<? extends TestDataElement> c) {
return testDataElements.addAll(index, c); return testDataElements.addAll( index, c );
} }
public boolean removeAll(Collection<?> c) { public boolean removeAll(Collection<?> c) {
return testDataElements.removeAll(c); return testDataElements.removeAll( c );
} }
public boolean retainAll(Collection<?> c) { public boolean retainAll(Collection<?> c) {
return testDataElements.retainAll(c); return testDataElements.retainAll( c );
} }
public void clear() { public void clear() {
testDataElements.clear(); testDataElements.clear();
} }
public boolean equals(Object o) { public boolean equals(Object o) {
return testDataElements.equals(o); return testDataElements.equals( o );
} }
public int hashCode() { public int hashCode() {
return testDataElements.hashCode(); return testDataElements.hashCode();
} }
public TestDataElement get(int index) { public TestDataElement get(int index) {
return testDataElements.get(index); return testDataElements.get( index );
} }
public TestDataElement set(int index, TestDataElement element) { public TestDataElement set(int index, TestDataElement element) {
return testDataElements.set(index, element); return testDataElements.set( index, element );
} }
public void add(int index, TestDataElement element) { public void add(int index, TestDataElement element) {
testDataElements.add(index, element); testDataElements.add( index, element );
} }
public TestDataElement remove(int index) { public TestDataElement remove(int index) {
return testDataElements.remove(index); return testDataElements.remove( index );
} }
public int indexOf(Object o) { public int indexOf(Object o) {
return testDataElements.indexOf(o); return testDataElements.indexOf( o );
} }
public int lastIndexOf(Object o) { public int lastIndexOf(Object o) {
return testDataElements.lastIndexOf(o); return testDataElements.lastIndexOf( o );
} }
public ListIterator<TestDataElement> listIterator() { public ListIterator<TestDataElement> listIterator() {
return testDataElements.listIterator(); return testDataElements.listIterator();
} }
public ListIterator<TestDataElement> listIterator(int index) { public ListIterator<TestDataElement> listIterator(int index) {
return testDataElements.listIterator(index); return testDataElements.listIterator( index );
} }
public List<TestDataElement> subList(int fromIndex, int toIndex) { public List<TestDataElement> subList(int fromIndex, int toIndex) {
return testDataElements.subList(fromIndex, toIndex); return testDataElements.subList( fromIndex, toIndex );
} }
public static TestData fromFile(String fileName) { public static TestData fromFile(String fileName) {
TestDataReader reader = new TestDataReader(); TestDataReader reader = new TestDataReader();
return fromFile(fileName, reader); return fromFile( fileName, reader );
} }
public static TestData fromFile(String fileName, TestDataReader reader) { public static TestData fromFile(String fileName, TestDataReader reader) {
List<TestDataElement> elements = reader.read(fileName); List<TestDataElement> elements = reader.read( fileName );
TestData testData = new TestData(); TestData testData = new TestData();
testData.testDataElements = elements; testData.testDataElements = elements;
return testData; return testData;
} }
} }

View File

@ -33,17 +33,17 @@
public class TestDataElement { public class TestDataElement {
final public String wkt; final public String wkt;
final public int id; final public int id;
final public int srid; final public int srid;
final public String type; final public String type;
protected TestDataElement(int id, String type, String wkt, int srid) { protected TestDataElement(int id, String type, String wkt, int srid) {
this.wkt = wkt; this.wkt = wkt;
this.id = id; this.id = id;
this.type = type; this.type = type;
this.srid = srid; this.srid = srid;
} }
} }

View File

@ -25,51 +25,56 @@
package org.hibernate.spatial.test; package org.hibernate.spatial.test;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import java.io.InputStream; import java.io.InputStream;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Iterator; import java.util.Iterator;
import java.util.List; import java.util.List;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
public class TestDataReader { public class TestDataReader {
public List<TestDataElement> read(String fileName) { public List<TestDataElement> read(String fileName) {
if (fileName == null) throw new RuntimeException("Null testsuite-suite data file specified."); if ( fileName == null ) {
List<TestDataElement> testDataElements = new ArrayList<TestDataElement>(); throw new RuntimeException( "Null testsuite-suite data file specified." );
SAXReader reader = new SAXReader(); }
try { List<TestDataElement> testDataElements = new ArrayList<TestDataElement>();
Document document = reader.read(getInputStream(fileName)); SAXReader reader = new SAXReader();
addDataElements(document, testDataElements); try {
} catch (DocumentException e) { Document document = reader.read( getInputStream( fileName ) );
throw new RuntimeException(e); addDataElements( document, testDataElements );
} }
return testDataElements; catch ( DocumentException e ) {
} throw new RuntimeException( e );
}
return testDataElements;
}
protected void addDataElements(Document document, List<TestDataElement> testDataElements) { protected void addDataElements(Document document, List<TestDataElement> testDataElements) {
Element root = document.getRootElement(); Element root = document.getRootElement();
for (Iterator it = root.elementIterator(); it.hasNext();) { for ( Iterator it = root.elementIterator(); it.hasNext(); ) {
Element element = (Element) it.next(); Element element = (Element) it.next();
addDataElement(element, testDataElements); addDataElement( element, testDataElements );
} }
} }
protected void addDataElement(Element element, List<TestDataElement> testDataElements) { protected void addDataElement(Element element, List<TestDataElement> testDataElements) {
int id = Integer.valueOf(element.selectSingleNode("id").getText()); int id = Integer.valueOf( element.selectSingleNode( "id" ).getText() );
String type = element.selectSingleNode("type").getText(); String type = element.selectSingleNode( "type" ).getText();
String wkt = element.selectSingleNode("wkt").getText(); String wkt = element.selectSingleNode( "wkt" ).getText();
int srid = Integer.valueOf(element.selectSingleNode("srid").getText()); int srid = Integer.valueOf( element.selectSingleNode( "srid" ).getText() );
TestDataElement testDataElement = new TestDataElement(id, type, wkt, srid); TestDataElement testDataElement = new TestDataElement( id, type, wkt, srid );
testDataElements.add(testDataElement); testDataElements.add( testDataElement );
} }
protected InputStream getInputStream(String fileName) { protected InputStream getInputStream(String fileName) {
InputStream is = Thread.currentThread().getContextClassLoader().getResourceAsStream(fileName); InputStream is = Thread.currentThread().getContextClassLoader().getResourceAsStream( fileName );
if (is == null) throw new RuntimeException(String.format("File %s not found on classpath.", fileName)); if ( is == null ) {
return is; throw new RuntimeException( String.format( "File %s not found on classpath.", fileName ) );
} }
return is;
}
} }

View File

@ -11,12 +11,12 @@
*/ */
public interface TestFeature { public interface TestFeature {
public Integer getId(); public Integer getId();
public void setId(Integer id); public void setId(Integer id);
public Geometry getGeom(); public Geometry getGeom();
public void setGeom(Geometry geom); public void setGeom(Geometry geom);
} }

View File

@ -10,36 +10,36 @@
*/ */
public abstract class TestSupport { public abstract class TestSupport {
protected Configuration configuration; protected Configuration configuration;
public DataSourceUtils createDataSourceUtil(Configuration configuration) { public DataSourceUtils createDataSourceUtil(Configuration configuration) {
this.configuration = configuration; this.configuration = configuration;
return new DataSourceUtils(driver(), url(), user(), passwd(), getSQLExpressionTemplate()); return new DataSourceUtils( driver(), url(), user(), passwd(), getSQLExpressionTemplate() );
} }
public GeometryEquality createGeometryEquality() { public GeometryEquality createGeometryEquality() {
return new GeometryEquality(); return new GeometryEquality();
} }
public abstract TestData createTestData(BaseCoreFunctionalTestCase testcase); public abstract TestData createTestData(BaseCoreFunctionalTestCase testcase);
public abstract AbstractExpectationsFactory createExpectationsFactory(DataSourceUtils dataSourceUtils); public abstract AbstractExpectationsFactory createExpectationsFactory(DataSourceUtils dataSourceUtils);
public abstract SQLExpressionTemplate getSQLExpressionTemplate(); public abstract SQLExpressionTemplate getSQLExpressionTemplate();
protected String driver() { protected String driver() {
return configuration.getProperty("hibernate.connection.driver_class"); return configuration.getProperty( "hibernate.connection.driver_class" );
} }
protected String url() { protected String url() {
return configuration.getProperty("hibernate.connection.url"); return configuration.getProperty( "hibernate.connection.url" );
} }
protected String user() { protected String user() {
return configuration.getProperty("hibernate.connection.username"); return configuration.getProperty( "hibernate.connection.username" );
} }
protected String passwd() { protected String passwd() {
return configuration.getProperty("hibernate.connection.password"); return configuration.getProperty( "hibernate.connection.password" );
} }
} }

View File

@ -32,6 +32,7 @@
import com.vividsolutions.jts.geom.CoordinateSequence; import com.vividsolutions.jts.geom.CoordinateSequence;
import com.vividsolutions.jts.geom.GeometryFactory; import com.vividsolutions.jts.geom.GeometryFactory;
import junit.framework.TestCase; import junit.framework.TestCase;
import org.hibernate.spatial.mgeom.MCoordinate; import org.hibernate.spatial.mgeom.MCoordinate;
import org.hibernate.spatial.mgeom.MCoordinateSequenceFactory; import org.hibernate.spatial.mgeom.MCoordinateSequenceFactory;
import org.hibernate.spatial.mgeom.MLineString; import org.hibernate.spatial.mgeom.MLineString;
@ -42,144 +43,164 @@
*/ */
public class MultiMLineStringTest extends TestCase { public class MultiMLineStringTest extends TestCase {
private final MCoordinateSequenceFactory mcfactory = MCoordinateSequenceFactory private final MCoordinateSequenceFactory mcfactory = MCoordinateSequenceFactory
.instance(); .instance();
private final GeometryFactory geomfactory = new GeometryFactory(mcfactory); private final GeometryFactory geomfactory = new GeometryFactory( mcfactory );
protected MLineString ml1; protected MLineString ml1;
protected MLineString ml2; protected MLineString ml2;
protected MultiMLineString mm1; protected MultiMLineString mm1;
protected MultiMLineString mmsimple; protected MultiMLineString mmsimple;
protected MCoordinate lastco; protected MCoordinate lastco;
public static void main(String[] args) { public static void main(String[] args) {
junit.textui.TestRunner.run(MultiMLineStringTest.class); junit.textui.TestRunner.run( MultiMLineStringTest.class );
} }
/* /*
* @see TestCase#setUp() * @see TestCase#setUp()
*/ */
protected void setUp() throws Exception { protected void setUp() throws Exception {
super.setUp(); super.setUp();
MCoordinate mc0 = new MCoordinate(0.0, 0.0, 0.0, 0.0); MCoordinate mc0 = new MCoordinate( 0.0, 0.0, 0.0, 0.0 );
MCoordinate mc1 = new MCoordinate(1.0, 0.0, 0.0, 0.1); MCoordinate mc1 = new MCoordinate( 1.0, 0.0, 0.0, 0.1 );
MCoordinate mc2 = new MCoordinate(1.0, 1.0, 0.0, 0.2); MCoordinate mc2 = new MCoordinate( 1.0, 1.0, 0.0, 0.2 );
MCoordinate mc3 = new MCoordinate(5.0, 1.0, 0.0, 0.3); MCoordinate mc3 = new MCoordinate( 5.0, 1.0, 0.0, 0.3 );
MCoordinate mc4 = new MCoordinate(5.0, 3.0, 0.0, 0.4); MCoordinate mc4 = new MCoordinate( 5.0, 3.0, 0.0, 0.4 );
lastco = mc4; lastco = mc4;
MCoordinate[] m1 = {mc0, mc1, mc2}; MCoordinate[] m1 = { mc0, mc1, mc2 };
MCoordinate[] m2 = {mc3, mc4}; MCoordinate[] m2 = { mc3, mc4 };
CoordinateSequence mseq1 = mcfactory.create(m1); CoordinateSequence mseq1 = mcfactory.create( m1 );
ml1 = new MLineString(mseq1, geomfactory); ml1 = new MLineString( mseq1, geomfactory );
CoordinateSequence mseq2 = mcfactory.create(m2); CoordinateSequence mseq2 = mcfactory.create( m2 );
ml2 = new MLineString(mseq2, geomfactory); ml2 = new MLineString( mseq2, geomfactory );
mmsimple = new MultiMLineString(new MLineString[]{ml1}, 0.1, mmsimple = new MultiMLineString(
geomfactory); new MLineString[] { ml1 }, 0.1,
mm1 = new MultiMLineString(new MLineString[]{ml1, ml2}, 0.1, geomfactory
geomfactory); );
mm1 = new MultiMLineString(
new MLineString[] { ml1, ml2 }, 0.1,
geomfactory
);
} }
/* /*
* @see TestCase#tearDown() * @see TestCase#tearDown()
*/ */
protected void tearDown() throws Exception { protected void tearDown() throws Exception {
super.tearDown(); super.tearDown();
} }
public void testMaxM() { public void testMaxM() {
assertEquals(0.4, mm1.getMaxM(), 0.000001); assertEquals( 0.4, mm1.getMaxM(), 0.000001 );
} }
/* /*
* Class under testsuite-suite for java.lang.String getGeometryType() * Class under testsuite-suite for java.lang.String getGeometryType()
*/ */
public void testGetGeometryType() { public void testGetGeometryType() {
assertTrue("wrong type reported", mm1.getGeometryType() assertTrue(
.equalsIgnoreCase("multimlinestring")); "wrong type reported", mm1.getGeometryType()
} .equalsIgnoreCase( "multimlinestring" )
);
}
public void testGetDimension() { public void testGetDimension() {
// TODO Implement getDimension(). // TODO Implement getDimension().
} }
public void testGetBoundary() { public void testGetBoundary() {
// TODO Implement getBoundary(). // TODO Implement getBoundary().
} }
public void testGetBoundaryDimension() { public void testGetBoundaryDimension() {
// TODO Implement getBoundaryDimension(). // TODO Implement getBoundaryDimension().
} }
/* /*
* Class under testsuite-suite for boolean * Class under testsuite-suite for boolean
* equalsExact(com.vividsolutions.jts.geom.Geometry, double) * equalsExact(com.vividsolutions.jts.geom.Geometry, double)
*/ */
public void testEqualsExactGeometrydouble() { public void testEqualsExactGeometrydouble() {
// TODO Implement equalsExact(). // TODO Implement equalsExact().
} }
/* /*
* Class under testsuite-suite for void * Class under testsuite-suite for void
* MultiLineString(com.vividsolutions.jts.geom.LineString[], * MultiLineString(com.vividsolutions.jts.geom.LineString[],
* com.vividsolutions.jts.geom.PrecisionModel, int) * com.vividsolutions.jts.geom.PrecisionModel, int)
*/ */
public void testMultiLineStringLineStringArrayPrecisionModelint() { public void testMultiLineStringLineStringArrayPrecisionModelint() {
// TODO Implement MultiLineString(). // TODO Implement MultiLineString().
} }
/* /*
* Class under testsuite-suite for void * Class under testsuite-suite for void
* MultiLineString(com.vividsolutions.jts.geom.LineString[], * MultiLineString(com.vividsolutions.jts.geom.LineString[],
* com.vividsolutions.jts.geom.GeometryFactory) * com.vividsolutions.jts.geom.GeometryFactory)
*/ */
public void testMultiLineStringLineStringArrayGeometryFactory() { public void testMultiLineStringLineStringArrayGeometryFactory() {
// TODO Implement MultiLineString(). // TODO Implement MultiLineString().
} }
public void testIsClosed() { public void testIsClosed() {
// TODO Implement isClosed(). // TODO Implement isClosed().
} }
public void testClone() { public void testClone() {
// TODO implement // TODO implement
} }
public void testInterpolate() { public void testInterpolate() {
mm1.measureOnLength(false); mm1.measureOnLength( false );
Coordinate[] ca = mm1.getCoordinates(); Coordinate[] ca = mm1.getCoordinates();
assertTrue("co 0 not OK", ((MCoordinate) ca[0]).m == 0.0); assertTrue( "co 0 not OK", ( (MCoordinate) ca[0] ).m == 0.0 );
assertTrue("co 1 not OK", assertTrue(
Math.abs(((MCoordinate) ca[1]).m - 1.0) < 0.00001); "co 1 not OK",
assertTrue("co 2 not OK", Math.abs( ( (MCoordinate) ca[1] ).m - 1.0 ) < 0.00001
Math.abs(((MCoordinate) ca[2]).m - 2.0) < 0.00001); );
assertTrue("co 3 not OK", Math.abs(((MCoordinate) ca[3]).m assertTrue(
- (2.0 + mm1.getMGap())) < 0.00001); "co 2 not OK",
assertTrue("co 4 not OK", Math.abs(((MCoordinate) ca[4]).m Math.abs( ( (MCoordinate) ca[2] ).m - 2.0 ) < 0.00001
- (4.0 + mm1.getMGap())) < 0.00001); );
assertTrue(
"co 3 not OK", Math.abs(
( (MCoordinate) ca[3] ).m
- ( 2.0 + mm1.getMGap() )
) < 0.00001
);
assertTrue(
"co 4 not OK", Math.abs(
( (MCoordinate) ca[4] ).m
- ( 4.0 + mm1.getMGap() )
) < 0.00001
);
double dist = mm1.getLength(); double dist = mm1.getLength();
dist += (mm1.getNumGeometries() - 1) * mm1.getMGap(); dist += ( mm1.getNumGeometries() - 1 ) * mm1.getMGap();
assertTrue("interpolation not consistent with distance", Math assertTrue(
.abs(((MCoordinate) ca[4]).m - dist) < 0.00001); "interpolation not consistent with distance", Math
.abs( ( (MCoordinate) ca[4] ).m - dist ) < 0.00001
);
} }
} }

View File

@ -27,94 +27,102 @@
import com.vividsolutions.jts.geom.Coordinate; import com.vividsolutions.jts.geom.Coordinate;
import com.vividsolutions.jts.geom.PrecisionModel; import com.vividsolutions.jts.geom.PrecisionModel;
import org.hibernate.spatial.mgeom.*;
import org.junit.Before; import org.junit.Before;
import org.junit.Test; import org.junit.Test;
import org.hibernate.spatial.mgeom.EventLocator;
import org.hibernate.spatial.mgeom.MCoordinate;
import org.hibernate.spatial.mgeom.MCoordinateSequenceFactory;
import org.hibernate.spatial.mgeom.MGeometryException;
import org.hibernate.spatial.mgeom.MGeometryFactory;
import org.hibernate.spatial.mgeom.MLineString;
import org.hibernate.spatial.mgeom.MultiMLineString;
import static junit.framework.Assert.assertEquals; import static junit.framework.Assert.assertEquals;
import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNotNull;
public class TestEventLocator { public class TestEventLocator {
private PrecisionModel prec = new PrecisionModel(PrecisionModel.FIXED); private PrecisionModel prec = new PrecisionModel( PrecisionModel.FIXED );
private MGeometryFactory mgeomFactory = new MGeometryFactory( private MGeometryFactory mgeomFactory = new MGeometryFactory(
MCoordinateSequenceFactory.instance()); MCoordinateSequenceFactory.instance()
);
private MultiMLineString incrML; private MultiMLineString incrML;
@Before @Before
public void setUp() { public void setUp() {
MCoordinate[] coordinates = new MCoordinate[]{ MCoordinate[] coordinates = new MCoordinate[] {
MCoordinate.create2dWithMeasure(0.0, 0.0, 0.0), MCoordinate.create2dWithMeasure( 0.0, 0.0, 0.0 ),
MCoordinate.create2dWithMeasure(1.0, 0.0, 1.0), MCoordinate.create2dWithMeasure( 1.0, 0.0, 1.0 ),
MCoordinate.create2dWithMeasure(2.0, 0.0, 2.0), MCoordinate.create2dWithMeasure( 2.0, 0.0, 2.0 ),
MCoordinate.create2dWithMeasure(3.0, 0.0, 3.0), MCoordinate.create2dWithMeasure( 3.0, 0.0, 3.0 ),
MCoordinate.create2dWithMeasure(4.0, 0.0, 4.0) MCoordinate.create2dWithMeasure( 4.0, 0.0, 4.0 )
}; };
MLineString line1 = mgeomFactory.createMLineString(coordinates); MLineString line1 = mgeomFactory.createMLineString( coordinates );
MCoordinate[] coordinates2 = new MCoordinate[]{ MCoordinate[] coordinates2 = new MCoordinate[] {
MCoordinate.create2dWithMeasure(5.0, 0.0, 5.0), MCoordinate.create2dWithMeasure( 5.0, 0.0, 5.0 ),
MCoordinate.create2dWithMeasure(6.0, 0.0, 6.0), MCoordinate.create2dWithMeasure( 6.0, 0.0, 6.0 ),
MCoordinate.create2dWithMeasure(7.0, 0.0, 7.0), MCoordinate.create2dWithMeasure( 7.0, 0.0, 7.0 ),
}; };
MLineString line2 = mgeomFactory.createMLineString(coordinates2); MLineString line2 = mgeomFactory.createMLineString( coordinates2 );
MCoordinate[] coordinates3 = new MCoordinate[]{ MCoordinate[] coordinates3 = new MCoordinate[] {
MCoordinate.create2dWithMeasure(9.0, 0.0, 9.0), MCoordinate.create2dWithMeasure( 9.0, 0.0, 9.0 ),
MCoordinate.create2dWithMeasure(10.0, 0.0, 10.0), MCoordinate.create2dWithMeasure( 10.0, 0.0, 10.0 ),
MCoordinate.create2dWithMeasure(11.0, 0.0, 11.0), MCoordinate.create2dWithMeasure( 11.0, 0.0, 11.0 ),
}; };
MLineString line3 = mgeomFactory.createMLineString(coordinates2); MLineString line3 = mgeomFactory.createMLineString( coordinates2 );
incrML = mgeomFactory.createMultiMLineString(new MLineString[]{line1, line2}); incrML = mgeomFactory.createMultiMLineString( new MLineString[] { line1, line2 } );
} }
@Test @Test
public void test_event_starts_at_end_of_component() throws MGeometryException { public void test_event_starts_at_end_of_component() throws MGeometryException {
MultiMLineString result = EventLocator.getLinearGeometry(incrML, 4.0, 5.5); MultiMLineString result = EventLocator.getLinearGeometry( incrML, 4.0, 5.5 );
assertNotNull(result); assertNotNull( result );
assertEquals(1, result.getNumGeometries()); assertEquals( 1, result.getNumGeometries() );
assertEquals(2, result.getCoordinates().length); assertEquals( 2, result.getCoordinates().length );
Coordinate[] coordinates = result.getCoordinates(); Coordinate[] coordinates = result.getCoordinates();
assertEquals(MCoordinate.create2dWithMeasure(5.0, 0.0, 5.0), (MCoordinate) coordinates[0]); assertEquals( MCoordinate.create2dWithMeasure( 5.0, 0.0, 5.0 ), (MCoordinate) coordinates[0] );
assertEquals(MCoordinate.create2dWithMeasure(5.5, 0.0, 5.5), (MCoordinate) coordinates[1]); assertEquals( MCoordinate.create2dWithMeasure( 5.5, 0.0, 5.5 ), (MCoordinate) coordinates[1] );
} }
@Test @Test
public void test_event_ends_at_begin_of_component() throws MGeometryException { public void test_event_ends_at_begin_of_component() throws MGeometryException {
MultiMLineString result = EventLocator.getLinearGeometry(incrML, 3.0, 5.0); MultiMLineString result = EventLocator.getLinearGeometry( incrML, 3.0, 5.0 );
assertNotNull(result); assertNotNull( result );
assertEquals(1, result.getNumGeometries()); assertEquals( 1, result.getNumGeometries() );
assertEquals(2, result.getCoordinates().length); assertEquals( 2, result.getCoordinates().length );
Coordinate[] coordinates = result.getCoordinates(); Coordinate[] coordinates = result.getCoordinates();
assertEquals(MCoordinate.create2dWithMeasure(3.0, 0.0, 3.0), (MCoordinate) coordinates[0]); assertEquals( MCoordinate.create2dWithMeasure( 3.0, 0.0, 3.0 ), (MCoordinate) coordinates[0] );
assertEquals(MCoordinate.create2dWithMeasure(4.0, 0.0, 4.0), (MCoordinate) coordinates[1]); assertEquals( MCoordinate.create2dWithMeasure( 4.0, 0.0, 4.0 ), (MCoordinate) coordinates[1] );
} }
@Test @Test
public void test_event_ends_at_end_of_component() throws MGeometryException { public void test_event_ends_at_end_of_component() throws MGeometryException {
MultiMLineString result = EventLocator.getLinearGeometry(incrML, 4.5, 7.0); MultiMLineString result = EventLocator.getLinearGeometry( incrML, 4.5, 7.0 );
assertNotNull(result); assertNotNull( result );
assertEquals(1, result.getNumGeometries()); assertEquals( 1, result.getNumGeometries() );
assertEquals(3, result.getCoordinates().length); assertEquals( 3, result.getCoordinates().length );
Coordinate[] coordinates = result.getCoordinates(); Coordinate[] coordinates = result.getCoordinates();
assertEquals(MCoordinate.create2dWithMeasure(5.0, 0.0, 5.0), (MCoordinate) coordinates[0]); assertEquals( MCoordinate.create2dWithMeasure( 5.0, 0.0, 5.0 ), (MCoordinate) coordinates[0] );
assertEquals(MCoordinate.create2dWithMeasure(6.0, 0.0, 6.0), (MCoordinate) coordinates[1]); assertEquals( MCoordinate.create2dWithMeasure( 6.0, 0.0, 6.0 ), (MCoordinate) coordinates[1] );
assertEquals(MCoordinate.create2dWithMeasure(7.0, 0.0, 7.0), (MCoordinate) coordinates[2]); assertEquals( MCoordinate.create2dWithMeasure( 7.0, 0.0, 7.0 ), (MCoordinate) coordinates[2] );
} }
@Test @Test
public void test_locator_result_has_same_srid_as_input_mgeometry() throws MGeometryException { public void test_locator_result_has_same_srid_as_input_mgeometry() throws MGeometryException {
incrML.setSRID(123); incrML.setSRID( 123 );
MultiMLineString result = EventLocator.getLinearGeometry(incrML, 4.5, 7.0); MultiMLineString result = EventLocator.getLinearGeometry( incrML, 4.5, 7.0 );
assertEquals(123, result.getSRID()); assertEquals( 123, result.getSRID() );
} }
} }

View File

@ -28,485 +28,492 @@
import com.vividsolutions.jts.geom.Coordinate; import com.vividsolutions.jts.geom.Coordinate;
import com.vividsolutions.jts.geom.CoordinateSequence; import com.vividsolutions.jts.geom.CoordinateSequence;
import com.vividsolutions.jts.geom.PrecisionModel; import com.vividsolutions.jts.geom.PrecisionModel;
import org.hibernate.spatial.mgeom.*;
import org.junit.Before; import org.junit.Before;
import org.junit.Test; import org.junit.Test;
import org.hibernate.spatial.mgeom.MCoordinate;
import org.hibernate.spatial.mgeom.MCoordinateSequenceFactory;
import org.hibernate.spatial.mgeom.MGeometryException;
import org.hibernate.spatial.mgeom.MGeometryFactory;
import org.hibernate.spatial.mgeom.MLineString;
import static junit.framework.Assert.assertEquals; import static junit.framework.Assert.assertEquals;
import static junit.framework.Assert.fail; import static junit.framework.Assert.fail;
public class TestMLineStringGetCoordinatesBetween { public class TestMLineStringGetCoordinatesBetween {
MLineString incrLine; MLineString incrLine;
MLineString decLine; MLineString decLine;
MLineString emptyLine; MLineString emptyLine;
MLineString nonMonotoneLine; MLineString nonMonotoneLine;
MLineString partiallyConstantIncreasing; MLineString partiallyConstantIncreasing;
MLineString partiallyConstantDecreasing; MLineString partiallyConstantDecreasing;
private PrecisionModel prec = new PrecisionModel(PrecisionModel.FIXED); private PrecisionModel prec = new PrecisionModel( PrecisionModel.FIXED );
private MGeometryFactory mgeomFactory = new MGeometryFactory( private MGeometryFactory mgeomFactory = new MGeometryFactory(
MCoordinateSequenceFactory.instance()); MCoordinateSequenceFactory.instance()
);
@Before
public void setUp() { @Before
public void setUp() {
MCoordinate[] coordinates = new MCoordinate[]{
MCoordinate.create2dWithMeasure(0.0, 0.0, 0.0), MCoordinate[] coordinates = new MCoordinate[] {
MCoordinate.create2dWithMeasure(1.0, 0.0, 1.0), MCoordinate.create2dWithMeasure( 0.0, 0.0, 0.0 ),
MCoordinate.create2dWithMeasure(2.0, 0.0, 2.0), MCoordinate.create2dWithMeasure( 1.0, 0.0, 1.0 ),
MCoordinate.create2dWithMeasure(3.0, 0.0, 3.0), MCoordinate.create2dWithMeasure( 2.0, 0.0, 2.0 ),
MCoordinate.create2dWithMeasure(4.0, 0.0, 4.0) MCoordinate.create2dWithMeasure( 3.0, 0.0, 3.0 ),
}; MCoordinate.create2dWithMeasure( 4.0, 0.0, 4.0 )
incrLine = mgeomFactory.createMLineString(coordinates); };
incrLine = mgeomFactory.createMLineString( coordinates );
coordinates = new MCoordinate[]{
MCoordinate.create2dWithMeasure(4.0, 0.0, 4.0), coordinates = new MCoordinate[] {
MCoordinate.create2dWithMeasure(3.0, 0.0, 3.0), MCoordinate.create2dWithMeasure( 4.0, 0.0, 4.0 ),
MCoordinate.create2dWithMeasure(2.0, 0.0, 2.0), MCoordinate.create2dWithMeasure( 3.0, 0.0, 3.0 ),
MCoordinate.create2dWithMeasure(1.0, 0.0, 1.0), MCoordinate.create2dWithMeasure( 2.0, 0.0, 2.0 ),
MCoordinate.create2dWithMeasure(0.0, 0.0, 0.0) MCoordinate.create2dWithMeasure( 1.0, 0.0, 1.0 ),
}; MCoordinate.create2dWithMeasure( 0.0, 0.0, 0.0 )
decLine = mgeomFactory.createMLineString(coordinates); };
decLine = mgeomFactory.createMLineString( coordinates );
coordinates = new MCoordinate[]{
MCoordinate.create2dWithMeasure(0.0, 0.0, 1.0), coordinates = new MCoordinate[] {
MCoordinate.create2dWithMeasure(1.0, 0.0, 3.0), MCoordinate.create2dWithMeasure( 0.0, 0.0, 1.0 ),
MCoordinate.create2dWithMeasure(2.0, 0.0, 2.0), MCoordinate.create2dWithMeasure( 1.0, 0.0, 3.0 ),
MCoordinate.create2dWithMeasure(3.0, 0.0, 5.0), MCoordinate.create2dWithMeasure( 2.0, 0.0, 2.0 ),
MCoordinate.create2dWithMeasure(4.0, 0.0, 1.5) MCoordinate.create2dWithMeasure( 3.0, 0.0, 5.0 ),
}; MCoordinate.create2dWithMeasure( 4.0, 0.0, 1.5 )
nonMonotoneLine = mgeomFactory.createMLineString(coordinates); };
nonMonotoneLine = mgeomFactory.createMLineString( coordinates );
coordinates = new MCoordinate[]{
MCoordinate.create2dWithMeasure(0.0, 0.0, 0.0), coordinates = new MCoordinate[] {
MCoordinate.create2dWithMeasure(1.0, 0.0, 1.0), MCoordinate.create2dWithMeasure( 0.0, 0.0, 0.0 ),
MCoordinate.create2dWithMeasure(2.0, 0.0, 2.0), MCoordinate.create2dWithMeasure( 1.0, 0.0, 1.0 ),
MCoordinate.create2dWithMeasure(3.0, 0.0, 2.0), MCoordinate.create2dWithMeasure( 2.0, 0.0, 2.0 ),
MCoordinate.create2dWithMeasure(4.0, 0.0, 3.0), MCoordinate.create2dWithMeasure( 3.0, 0.0, 2.0 ),
MCoordinate.create2dWithMeasure(5.0, 0.0, 4.0) MCoordinate.create2dWithMeasure( 4.0, 0.0, 3.0 ),
}; MCoordinate.create2dWithMeasure( 5.0, 0.0, 4.0 )
partiallyConstantIncreasing = mgeomFactory.createMLineString(coordinates); };
partiallyConstantIncreasing = mgeomFactory.createMLineString( coordinates );
coordinates = new MCoordinate[]{
MCoordinate.create2dWithMeasure(5.0, 0.0, 4.0), coordinates = new MCoordinate[] {
MCoordinate.create2dWithMeasure(4.0, 0.0, 3.0), MCoordinate.create2dWithMeasure( 5.0, 0.0, 4.0 ),
MCoordinate.create2dWithMeasure(3.0, 0.0, 2.0), MCoordinate.create2dWithMeasure( 4.0, 0.0, 3.0 ),
MCoordinate.create2dWithMeasure(2.0, 0.0, 2.0), MCoordinate.create2dWithMeasure( 3.0, 0.0, 2.0 ),
MCoordinate.create2dWithMeasure(1.0, 0.0, 1.0), MCoordinate.create2dWithMeasure( 2.0, 0.0, 2.0 ),
MCoordinate.create2dWithMeasure(0.0, 0.0, 0.0) MCoordinate.create2dWithMeasure( 1.0, 0.0, 1.0 ),
}; MCoordinate.create2dWithMeasure( 0.0, 0.0, 0.0 )
partiallyConstantDecreasing = mgeomFactory.createMLineString(coordinates); };
partiallyConstantDecreasing = mgeomFactory.createMLineString( coordinates );
}
}
@Test
public void test_measure_inside_monotone_increasing() throws MGeometryException { @Test
CoordinateSequence[] result; public void test_measure_inside_monotone_increasing() throws MGeometryException {
result = incrLine.getCoordinatesBetween(0.5, 3.5); CoordinateSequence[] result;
assertEquals(1, result.length); result = incrLine.getCoordinatesBetween( 0.5, 3.5 );
Coordinate[] crds = result[0].toCoordinateArray(); assertEquals( 1, result.length );
assertEquals(5, crds.length); Coordinate[] crds = result[0].toCoordinateArray();
assertEquals(MCoordinate.create2dWithMeasure(0.5, 0.0, 0.5), crds[0]); assertEquals( 5, crds.length );
assertEquals(MCoordinate.create2dWithMeasure(3.5, 0.0, 3.5), crds[crds.length - 1]); assertEquals( MCoordinate.create2dWithMeasure( 0.5, 0.0, 0.5 ), crds[0] );
assertEquals( MCoordinate.create2dWithMeasure( 3.5, 0.0, 3.5 ), crds[crds.length - 1] );
result = incrLine.getCoordinatesBetween(1.0, 3.0);
assertEquals(1, result.length); result = incrLine.getCoordinatesBetween( 1.0, 3.0 );
crds = result[0].toCoordinateArray(); assertEquals( 1, result.length );
assertEquals(3, crds.length); crds = result[0].toCoordinateArray();
assertEquals(MCoordinate.create2dWithMeasure(1.0, 0.0, 1.0), crds[0]); assertEquals( 3, crds.length );
assertEquals(MCoordinate.create2dWithMeasure(2.0, 0.0, 2.0), crds[1]); assertEquals( MCoordinate.create2dWithMeasure( 1.0, 0.0, 1.0 ), crds[0] );
assertEquals(MCoordinate.create2dWithMeasure(3.0, 0.0, 3.0), crds[2]); assertEquals( MCoordinate.create2dWithMeasure( 2.0, 0.0, 2.0 ), crds[1] );
assertEquals( MCoordinate.create2dWithMeasure( 3.0, 0.0, 3.0 ), crds[2] );
result = incrLine.getCoordinatesBetween(0.0, 4.0);
assertEquals(1, result.length); result = incrLine.getCoordinatesBetween( 0.0, 4.0 );
crds = result[0].toCoordinateArray(); assertEquals( 1, result.length );
assertEquals(5, crds.length); crds = result[0].toCoordinateArray();
assertEquals(MCoordinate.create2dWithMeasure(0.0, 0.0, 0.0), crds[0]); assertEquals( 5, crds.length );
assertEquals(MCoordinate.create2dWithMeasure(1.0, 0.0, 1.0), crds[1]); assertEquals( MCoordinate.create2dWithMeasure( 0.0, 0.0, 0.0 ), crds[0] );
assertEquals(MCoordinate.create2dWithMeasure(4.0, 0.0, 4.0), crds[4]); assertEquals( MCoordinate.create2dWithMeasure( 1.0, 0.0, 1.0 ), crds[1] );
assertEquals( MCoordinate.create2dWithMeasure( 4.0, 0.0, 4.0 ), crds[4] );
result = incrLine.getCoordinatesBetween(0.5, 1.5);
assertEquals(1, result.length); result = incrLine.getCoordinatesBetween( 0.5, 1.5 );
crds = result[0].toCoordinateArray(); assertEquals( 1, result.length );
assertEquals(3, crds.length); crds = result[0].toCoordinateArray();
assertEquals(MCoordinate.create2dWithMeasure(0.5, 0.0, 0.5), crds[0]); assertEquals( 3, crds.length );
assertEquals(MCoordinate.create2dWithMeasure(1.5, 0.0, 1.5), crds[crds.length - 1]); assertEquals( MCoordinate.create2dWithMeasure( 0.5, 0.0, 0.5 ), crds[0] );
assertEquals( MCoordinate.create2dWithMeasure( 1.5, 0.0, 1.5 ), crds[crds.length - 1] );
result = incrLine.getCoordinatesBetween(3.5, 4.0);
assertEquals(1, result.length); result = incrLine.getCoordinatesBetween( 3.5, 4.0 );
crds = result[0].toCoordinateArray(); assertEquals( 1, result.length );
assertEquals(2, crds.length); crds = result[0].toCoordinateArray();
assertEquals(MCoordinate.create2dWithMeasure(3.5, 0.0, 3.5), crds[0]); assertEquals( 2, crds.length );
assertEquals(MCoordinate.create2dWithMeasure(4.0, 0.0, 4.5), crds[crds.length - 1]); assertEquals( MCoordinate.create2dWithMeasure( 3.5, 0.0, 3.5 ), crds[0] );
assertEquals( MCoordinate.create2dWithMeasure( 4.0, 0.0, 4.5 ), crds[crds.length - 1] );
result = incrLine.getCoordinatesBetween(3.5, 3.7);
assertEquals(1, result.length); result = incrLine.getCoordinatesBetween( 3.5, 3.7 );
crds = result[0].toCoordinateArray(); assertEquals( 1, result.length );
assertEquals(2, crds.length); crds = result[0].toCoordinateArray();
assertEquals(MCoordinate.create2dWithMeasure(3.5, 0.0, 3.5), crds[0]); assertEquals( 2, crds.length );
assertEquals(MCoordinate.create2dWithMeasure(3.7, 0.0, 3.7), crds[1]); assertEquals( MCoordinate.create2dWithMeasure( 3.5, 0.0, 3.5 ), crds[0] );
assertEquals( MCoordinate.create2dWithMeasure( 3.7, 0.0, 3.7 ), crds[1] );
result = incrLine.getCoordinatesBetween(0.5, 0.7);
assertEquals(1, result.length); result = incrLine.getCoordinatesBetween( 0.5, 0.7 );
crds = result[0].toCoordinateArray(); assertEquals( 1, result.length );
assertEquals(2, crds.length); crds = result[0].toCoordinateArray();
assertEquals(MCoordinate.create2dWithMeasure(0.5, 0.0, 0.5), crds[0]); assertEquals( 2, crds.length );
assertEquals(MCoordinate.create2dWithMeasure(0.7, 0.0, 0.7), crds[1]); assertEquals( MCoordinate.create2dWithMeasure( 0.5, 0.0, 0.5 ), crds[0] );
assertEquals( MCoordinate.create2dWithMeasure( 0.7, 0.0, 0.7 ), crds[1] );
result = incrLine.getCoordinatesBetween(-0.5, 0.7);
assertEquals(1, result.length); result = incrLine.getCoordinatesBetween( -0.5, 0.7 );
crds = result[0].toCoordinateArray(); assertEquals( 1, result.length );
assertEquals(2, crds.length); crds = result[0].toCoordinateArray();
assertEquals(MCoordinate.create2dWithMeasure(0.0, 0.0, 0.0), crds[0]); assertEquals( 2, crds.length );
assertEquals(MCoordinate.create2dWithMeasure(0.7, 0.0, 0.7), crds[1]); assertEquals( MCoordinate.create2dWithMeasure( 0.0, 0.0, 0.0 ), crds[0] );
assertEquals( MCoordinate.create2dWithMeasure( 0.7, 0.0, 0.7 ), crds[1] );
result = incrLine.getCoordinatesBetween(3.5, 4.7);
assertEquals(1, result.length); result = incrLine.getCoordinatesBetween( 3.5, 4.7 );
crds = result[0].toCoordinateArray(); assertEquals( 1, result.length );
assertEquals(2, crds.length); crds = result[0].toCoordinateArray();
assertEquals(MCoordinate.create2dWithMeasure(3.5, 0.0, 3.5), crds[0]); assertEquals( 2, crds.length );
assertEquals(MCoordinate.create2dWithMeasure(4.0, 0.0, 4.0), crds[1]); assertEquals( MCoordinate.create2dWithMeasure( 3.5, 0.0, 3.5 ), crds[0] );
} assertEquals( MCoordinate.create2dWithMeasure( 4.0, 0.0, 4.0 ), crds[1] );
}
@Test
public void test_measure_inside_partially_constant_increasing() throws MGeometryException { @Test
CoordinateSequence[] result; public void test_measure_inside_partially_constant_increasing() throws MGeometryException {
result = partiallyConstantIncreasing.getCoordinatesBetween(0.5, 2.5); CoordinateSequence[] result;
assertEquals(1, result.length); result = partiallyConstantIncreasing.getCoordinatesBetween( 0.5, 2.5 );
Coordinate[] crds = result[0].toCoordinateArray(); assertEquals( 1, result.length );
assertEquals(5, crds.length); Coordinate[] crds = result[0].toCoordinateArray();
assertEquals(MCoordinate.create2dWithMeasure(0.5, 0.0, 0.5), crds[0]); assertEquals( 5, crds.length );
assertEquals(MCoordinate.create2dWithMeasure(3.5, 0.0, 2.5), crds[crds.length - 1]); assertEquals( MCoordinate.create2dWithMeasure( 0.5, 0.0, 0.5 ), crds[0] );
assertEquals( MCoordinate.create2dWithMeasure( 3.5, 0.0, 2.5 ), crds[crds.length - 1] );
result = partiallyConstantIncreasing.getCoordinatesBetween(1.0, 3.0);
assertEquals(1, result.length); result = partiallyConstantIncreasing.getCoordinatesBetween( 1.0, 3.0 );
crds = result[0].toCoordinateArray(); assertEquals( 1, result.length );
assertEquals(4, crds.length); crds = result[0].toCoordinateArray();
assertEquals(MCoordinate.create2dWithMeasure(1.0, 0.0, 1.0), crds[0]); assertEquals( 4, crds.length );
assertEquals(MCoordinate.create2dWithMeasure(2.0, 0.0, 2.0), crds[1]); assertEquals( MCoordinate.create2dWithMeasure( 1.0, 0.0, 1.0 ), crds[0] );
assertEquals(MCoordinate.create2dWithMeasure(4.0, 0.0, 3.0), crds[3]); assertEquals( MCoordinate.create2dWithMeasure( 2.0, 0.0, 2.0 ), crds[1] );
assertEquals( MCoordinate.create2dWithMeasure( 4.0, 0.0, 3.0 ), crds[3] );
result = partiallyConstantIncreasing.getCoordinatesBetween(0.0, 4.0);
assertEquals(1, result.length); result = partiallyConstantIncreasing.getCoordinatesBetween( 0.0, 4.0 );
crds = result[0].toCoordinateArray(); assertEquals( 1, result.length );
assertEquals(6, crds.length); crds = result[0].toCoordinateArray();
assertEquals(MCoordinate.create2dWithMeasure(0.0, 0.0, 0.0), crds[0]); assertEquals( 6, crds.length );
assertEquals(MCoordinate.create2dWithMeasure(1.0, 0.0, 1.0), crds[1]); assertEquals( MCoordinate.create2dWithMeasure( 0.0, 0.0, 0.0 ), crds[0] );
assertEquals(MCoordinate.create2dWithMeasure(5.0, 0.0, 4.0), crds[5]); assertEquals( MCoordinate.create2dWithMeasure( 1.0, 0.0, 1.0 ), crds[1] );
assertEquals( MCoordinate.create2dWithMeasure( 5.0, 0.0, 4.0 ), crds[5] );
result = partiallyConstantIncreasing.getCoordinatesBetween(0.5, 1.5);
assertEquals(1, result.length); result = partiallyConstantIncreasing.getCoordinatesBetween( 0.5, 1.5 );
crds = result[0].toCoordinateArray(); assertEquals( 1, result.length );
assertEquals(3, crds.length); crds = result[0].toCoordinateArray();
assertEquals(MCoordinate.create2dWithMeasure(0.5, 0.0, 0.5), crds[0]); assertEquals( 3, crds.length );
assertEquals(MCoordinate.create2dWithMeasure(1.5, 0.0, 1.5), crds[crds.length - 1]); assertEquals( MCoordinate.create2dWithMeasure( 0.5, 0.0, 0.5 ), crds[0] );
assertEquals( MCoordinate.create2dWithMeasure( 1.5, 0.0, 1.5 ), crds[crds.length - 1] );
result = partiallyConstantIncreasing.getCoordinatesBetween(1.5, 2.5);
assertEquals(1, result.length); result = partiallyConstantIncreasing.getCoordinatesBetween( 1.5, 2.5 );
crds = result[0].toCoordinateArray(); assertEquals( 1, result.length );
assertEquals(4, crds.length); crds = result[0].toCoordinateArray();
assertEquals(MCoordinate.create2dWithMeasure(1.5, 0.0, 1.5), crds[0]); assertEquals( 4, crds.length );
assertEquals(MCoordinate.create2dWithMeasure(3.5, 0.0, 2.5), crds[crds.length - 1]); assertEquals( MCoordinate.create2dWithMeasure( 1.5, 0.0, 1.5 ), crds[0] );
assertEquals( MCoordinate.create2dWithMeasure( 3.5, 0.0, 2.5 ), crds[crds.length - 1] );
result = partiallyConstantIncreasing.getCoordinatesBetween(3.5, 4.0);
assertEquals(1, result.length); result = partiallyConstantIncreasing.getCoordinatesBetween( 3.5, 4.0 );
crds = result[0].toCoordinateArray(); assertEquals( 1, result.length );
assertEquals(2, crds.length); crds = result[0].toCoordinateArray();
assertEquals(MCoordinate.create2dWithMeasure(4.5, 0.0, 3.5), crds[0]); assertEquals( 2, crds.length );
assertEquals(MCoordinate.create2dWithMeasure(5.0, 0.0, 4.0), crds[crds.length - 1]); assertEquals( MCoordinate.create2dWithMeasure( 4.5, 0.0, 3.5 ), crds[0] );
assertEquals( MCoordinate.create2dWithMeasure( 5.0, 0.0, 4.0 ), crds[crds.length - 1] );
result = partiallyConstantIncreasing.getCoordinatesBetween(3.5, 3.7);
assertEquals(1, result.length); result = partiallyConstantIncreasing.getCoordinatesBetween( 3.5, 3.7 );
crds = result[0].toCoordinateArray(); assertEquals( 1, result.length );
assertEquals(2, crds.length); crds = result[0].toCoordinateArray();
assertEquals(MCoordinate.create2dWithMeasure(4.5, 0.0, 3.5), crds[0]); assertEquals( 2, crds.length );
assertEquals(MCoordinate.create2dWithMeasure(4.7, 0.0, 3.7), crds[1]); assertEquals( MCoordinate.create2dWithMeasure( 4.5, 0.0, 3.5 ), crds[0] );
assertEquals( MCoordinate.create2dWithMeasure( 4.7, 0.0, 3.7 ), crds[1] );
result = partiallyConstantIncreasing.getCoordinatesBetween(0.5, 0.7);
assertEquals(1, result.length); result = partiallyConstantIncreasing.getCoordinatesBetween( 0.5, 0.7 );
crds = result[0].toCoordinateArray(); assertEquals( 1, result.length );
assertEquals(2, crds.length); crds = result[0].toCoordinateArray();
assertEquals(MCoordinate.create2dWithMeasure(0.5, 0.0, 0.5), crds[0]); assertEquals( 2, crds.length );
assertEquals(MCoordinate.create2dWithMeasure(0.7, 0.0, 0.7), crds[1]); assertEquals( MCoordinate.create2dWithMeasure( 0.5, 0.0, 0.5 ), crds[0] );
assertEquals( MCoordinate.create2dWithMeasure( 0.7, 0.0, 0.7 ), crds[1] );
result = partiallyConstantIncreasing.getCoordinatesBetween(-0.5, 0.7);
assertEquals(1, result.length); result = partiallyConstantIncreasing.getCoordinatesBetween( -0.5, 0.7 );
crds = result[0].toCoordinateArray(); assertEquals( 1, result.length );
assertEquals(2, crds.length); crds = result[0].toCoordinateArray();
assertEquals(MCoordinate.create2dWithMeasure(0.0, 0.0, 0.0), crds[0]); assertEquals( 2, crds.length );
assertEquals(MCoordinate.create2dWithMeasure(0.7, 0.0, 0.7), crds[1]); assertEquals( MCoordinate.create2dWithMeasure( 0.0, 0.0, 0.0 ), crds[0] );
assertEquals( MCoordinate.create2dWithMeasure( 0.7, 0.0, 0.7 ), crds[1] );
result = partiallyConstantIncreasing.getCoordinatesBetween(3.5, 4.7);
assertEquals(1, result.length); result = partiallyConstantIncreasing.getCoordinatesBetween( 3.5, 4.7 );
crds = result[0].toCoordinateArray(); assertEquals( 1, result.length );
assertEquals(2, crds.length); crds = result[0].toCoordinateArray();
assertEquals(MCoordinate.create2dWithMeasure(4.5, 0.0, 3.5), crds[0]); assertEquals( 2, crds.length );
assertEquals(MCoordinate.create2dWithMeasure(5.0, 0.0, 4.0), crds[1]); assertEquals( MCoordinate.create2dWithMeasure( 4.5, 0.0, 3.5 ), crds[0] );
} assertEquals( MCoordinate.create2dWithMeasure( 5.0, 0.0, 4.0 ), crds[1] );
}
@Test
public void test_measures_monotone_decreasing() throws MGeometryException { @Test
CoordinateSequence[] result; public void test_measures_monotone_decreasing() throws MGeometryException {
result = decLine.getCoordinatesBetween(0.5, 3.5); CoordinateSequence[] result;
assertEquals(1, result.length); result = decLine.getCoordinatesBetween( 0.5, 3.5 );
Coordinate[] crds = result[0].toCoordinateArray(); assertEquals( 1, result.length );
assertEquals(5, crds.length); Coordinate[] crds = result[0].toCoordinateArray();
assertEquals(MCoordinate.create2dWithMeasure(3.5, 0.0, 3.5), crds[0]); assertEquals( 5, crds.length );
assertEquals(MCoordinate.create2dWithMeasure(0.5, 0.0, 0.5), crds[crds.length - 1]); assertEquals( MCoordinate.create2dWithMeasure( 3.5, 0.0, 3.5 ), crds[0] );
assertEquals( MCoordinate.create2dWithMeasure( 0.5, 0.0, 0.5 ), crds[crds.length - 1] );
result = decLine.getCoordinatesBetween(1.0, 3.0);
assertEquals(1, result.length); result = decLine.getCoordinatesBetween( 1.0, 3.0 );
crds = result[0].toCoordinateArray(); assertEquals( 1, result.length );
assertEquals(3, crds.length); crds = result[0].toCoordinateArray();
assertEquals(MCoordinate.create2dWithMeasure(3.0, 0.0, 3.0), crds[0]); assertEquals( 3, crds.length );
assertEquals(MCoordinate.create2dWithMeasure(2.0, 0.0, 2.0), crds[1]); assertEquals( MCoordinate.create2dWithMeasure( 3.0, 0.0, 3.0 ), crds[0] );
assertEquals(MCoordinate.create2dWithMeasure(1.0, 0.0, 1.0), crds[2]); assertEquals( MCoordinate.create2dWithMeasure( 2.0, 0.0, 2.0 ), crds[1] );
assertEquals( MCoordinate.create2dWithMeasure( 1.0, 0.0, 1.0 ), crds[2] );
result = decLine.getCoordinatesBetween(0.0, 4.0);
assertEquals(1, result.length); result = decLine.getCoordinatesBetween( 0.0, 4.0 );
crds = result[0].toCoordinateArray(); assertEquals( 1, result.length );
assertEquals(5, crds.length); crds = result[0].toCoordinateArray();
assertEquals(MCoordinate.create2dWithMeasure(4.0, 0.0, 4.0), crds[0]); assertEquals( 5, crds.length );
assertEquals(MCoordinate.create2dWithMeasure(3.0, 0.0, 3.0), crds[1]); assertEquals( MCoordinate.create2dWithMeasure( 4.0, 0.0, 4.0 ), crds[0] );
assertEquals(MCoordinate.create2dWithMeasure(0.0, 0.0, 0.0), crds[4]); assertEquals( MCoordinate.create2dWithMeasure( 3.0, 0.0, 3.0 ), crds[1] );
assertEquals( MCoordinate.create2dWithMeasure( 0.0, 0.0, 0.0 ), crds[4] );
result = decLine.getCoordinatesBetween(0.5, 1.5);
assertEquals(1, result.length); result = decLine.getCoordinatesBetween( 0.5, 1.5 );
crds = result[0].toCoordinateArray(); assertEquals( 1, result.length );
assertEquals(3, crds.length); crds = result[0].toCoordinateArray();
assertEquals(MCoordinate.create2dWithMeasure(1.5, 0.0, 1.5), crds[0]); assertEquals( 3, crds.length );
assertEquals(MCoordinate.create2dWithMeasure(0.5, 0.0, 0.5), crds[crds.length - 1]); assertEquals( MCoordinate.create2dWithMeasure( 1.5, 0.0, 1.5 ), crds[0] );
assertEquals( MCoordinate.create2dWithMeasure( 0.5, 0.0, 0.5 ), crds[crds.length - 1] );
result = decLine.getCoordinatesBetween(3.5, 4.0);
assertEquals(1, result.length); result = decLine.getCoordinatesBetween( 3.5, 4.0 );
crds = result[0].toCoordinateArray(); assertEquals( 1, result.length );
assertEquals(2, crds.length); crds = result[0].toCoordinateArray();
assertEquals(MCoordinate.create2dWithMeasure(4.0, 0.0, 4.0), crds[0]); assertEquals( 2, crds.length );
assertEquals(MCoordinate.create2dWithMeasure(3.5, 0.0, 3.5), crds[crds.length - 1]); assertEquals( MCoordinate.create2dWithMeasure( 4.0, 0.0, 4.0 ), crds[0] );
assertEquals( MCoordinate.create2dWithMeasure( 3.5, 0.0, 3.5 ), crds[crds.length - 1] );
result = decLine.getCoordinatesBetween(3.5, 3.7);
assertEquals(1, result.length); result = decLine.getCoordinatesBetween( 3.5, 3.7 );
crds = result[0].toCoordinateArray(); assertEquals( 1, result.length );
assertEquals(2, crds.length); crds = result[0].toCoordinateArray();
assertEquals(MCoordinate.create2dWithMeasure(3.7, 0.0, 3.7), crds[0]); assertEquals( 2, crds.length );
assertEquals(MCoordinate.create2dWithMeasure(3.5, 0.0, 3.5), crds[1]); assertEquals( MCoordinate.create2dWithMeasure( 3.7, 0.0, 3.7 ), crds[0] );
assertEquals( MCoordinate.create2dWithMeasure( 3.5, 0.0, 3.5 ), crds[1] );
result = decLine.getCoordinatesBetween(0.5, 0.7);
assertEquals(1, result.length); result = decLine.getCoordinatesBetween( 0.5, 0.7 );
crds = result[0].toCoordinateArray(); assertEquals( 1, result.length );
assertEquals(2, crds.length); crds = result[0].toCoordinateArray();
assertEquals(MCoordinate.create2dWithMeasure(0.7, 0.0, 0.7), crds[0]); assertEquals( 2, crds.length );
assertEquals(MCoordinate.create2dWithMeasure(0.5, 0.0, 0.5), crds[1]); assertEquals( MCoordinate.create2dWithMeasure( 0.7, 0.0, 0.7 ), crds[0] );
assertEquals( MCoordinate.create2dWithMeasure( 0.5, 0.0, 0.5 ), crds[1] );
result = decLine.getCoordinatesBetween(-0.5, 0.7);
assertEquals(1, result.length); result = decLine.getCoordinatesBetween( -0.5, 0.7 );
crds = result[0].toCoordinateArray(); assertEquals( 1, result.length );
assertEquals(2, crds.length); crds = result[0].toCoordinateArray();
assertEquals(MCoordinate.create2dWithMeasure(0.7, 0.0, 0.7), crds[0]); assertEquals( 2, crds.length );
assertEquals(MCoordinate.create2dWithMeasure(0.0, 0.0, 0.0), crds[1]); assertEquals( MCoordinate.create2dWithMeasure( 0.7, 0.0, 0.7 ), crds[0] );
assertEquals( MCoordinate.create2dWithMeasure( 0.0, 0.0, 0.0 ), crds[1] );
result = decLine.getCoordinatesBetween(3.5, 4.7);
assertEquals(1, result.length); result = decLine.getCoordinatesBetween( 3.5, 4.7 );
crds = result[0].toCoordinateArray(); assertEquals( 1, result.length );
assertEquals(2, crds.length); crds = result[0].toCoordinateArray();
assertEquals(MCoordinate.create2dWithMeasure(3.5, 0.0, 3.5), crds[1]); assertEquals( 2, crds.length );
assertEquals(MCoordinate.create2dWithMeasure(4.0, 0.0, 4.0), crds[0]); assertEquals( MCoordinate.create2dWithMeasure( 3.5, 0.0, 3.5 ), crds[1] );
} assertEquals( MCoordinate.create2dWithMeasure( 4.0, 0.0, 4.0 ), crds[0] );
}
@Test
public void test_measures_partially_constant_decreasing() throws MGeometryException { @Test
CoordinateSequence[] result; public void test_measures_partially_constant_decreasing() throws MGeometryException {
result = partiallyConstantDecreasing.getCoordinatesBetween(0.5, 3.5); CoordinateSequence[] result;
assertEquals(1, result.length); result = partiallyConstantDecreasing.getCoordinatesBetween( 0.5, 3.5 );
Coordinate[] crds = result[0].toCoordinateArray(); assertEquals( 1, result.length );
assertEquals(6, crds.length); Coordinate[] crds = result[0].toCoordinateArray();
assertEquals(MCoordinate.create2dWithMeasure(4.5, 0.0, 3.5), crds[0]); assertEquals( 6, crds.length );
assertEquals(MCoordinate.create2dWithMeasure(0.5, 0.0, 0.5), crds[crds.length - 1]); assertEquals( MCoordinate.create2dWithMeasure( 4.5, 0.0, 3.5 ), crds[0] );
assertEquals( MCoordinate.create2dWithMeasure( 0.5, 0.0, 0.5 ), crds[crds.length - 1] );
result = partiallyConstantDecreasing.getCoordinatesBetween(1.0, 3.0);
assertEquals(1, result.length); result = partiallyConstantDecreasing.getCoordinatesBetween( 1.0, 3.0 );
crds = result[0].toCoordinateArray(); assertEquals( 1, result.length );
assertEquals(4, crds.length); crds = result[0].toCoordinateArray();
assertEquals(MCoordinate.create2dWithMeasure(4.0, 0.0, 3.0), crds[0]); assertEquals( 4, crds.length );
assertEquals(MCoordinate.create2dWithMeasure(3.0, 0.0, 2.0), crds[1]); assertEquals( MCoordinate.create2dWithMeasure( 4.0, 0.0, 3.0 ), crds[0] );
assertEquals(MCoordinate.create2dWithMeasure(2.0, 0.0, 2.0), crds[2]); assertEquals( MCoordinate.create2dWithMeasure( 3.0, 0.0, 2.0 ), crds[1] );
assertEquals(MCoordinate.create2dWithMeasure(1.0, 0.0, 1.0), crds[3]); assertEquals( MCoordinate.create2dWithMeasure( 2.0, 0.0, 2.0 ), crds[2] );
assertEquals( MCoordinate.create2dWithMeasure( 1.0, 0.0, 1.0 ), crds[3] );
result = partiallyConstantDecreasing.getCoordinatesBetween(0.0, 4.0);
assertEquals(1, result.length); result = partiallyConstantDecreasing.getCoordinatesBetween( 0.0, 4.0 );
crds = result[0].toCoordinateArray(); assertEquals( 1, result.length );
assertEquals(6, crds.length); crds = result[0].toCoordinateArray();
assertEquals(MCoordinate.create2dWithMeasure(5.0, 0.0, 4.0), crds[0]); assertEquals( 6, crds.length );
assertEquals(MCoordinate.create2dWithMeasure(4.0, 0.0, 3.0), crds[1]); assertEquals( MCoordinate.create2dWithMeasure( 5.0, 0.0, 4.0 ), crds[0] );
assertEquals(MCoordinate.create2dWithMeasure(0.0, 0.0, 0.0), crds[5]); assertEquals( MCoordinate.create2dWithMeasure( 4.0, 0.0, 3.0 ), crds[1] );
assertEquals( MCoordinate.create2dWithMeasure( 0.0, 0.0, 0.0 ), crds[5] );
result = partiallyConstantDecreasing.getCoordinatesBetween(0.5, 1.5);
assertEquals(1, result.length); result = partiallyConstantDecreasing.getCoordinatesBetween( 0.5, 1.5 );
crds = result[0].toCoordinateArray(); assertEquals( 1, result.length );
assertEquals(3, crds.length); crds = result[0].toCoordinateArray();
assertEquals(MCoordinate.create2dWithMeasure(1.5, 0.0, 1.5), crds[0]); assertEquals( 3, crds.length );
assertEquals(MCoordinate.create2dWithMeasure(0.5, 0.0, 0.5), crds[crds.length - 1]); assertEquals( MCoordinate.create2dWithMeasure( 1.5, 0.0, 1.5 ), crds[0] );
assertEquals( MCoordinate.create2dWithMeasure( 0.5, 0.0, 0.5 ), crds[crds.length - 1] );
result = partiallyConstantDecreasing.getCoordinatesBetween(1.5, 2.5);
assertEquals(1, result.length); result = partiallyConstantDecreasing.getCoordinatesBetween( 1.5, 2.5 );
crds = result[0].toCoordinateArray(); assertEquals( 1, result.length );
assertEquals(4, crds.length); crds = result[0].toCoordinateArray();
assertEquals(MCoordinate.create2dWithMeasure(3.5, 0.0, 2.5), crds[0]); assertEquals( 4, crds.length );
assertEquals(MCoordinate.create2dWithMeasure(3.0, 0.0, 2.0), crds[1]); assertEquals( MCoordinate.create2dWithMeasure( 3.5, 0.0, 2.5 ), crds[0] );
assertEquals(MCoordinate.create2dWithMeasure(2.0, 0.0, 2.0), crds[2]); assertEquals( MCoordinate.create2dWithMeasure( 3.0, 0.0, 2.0 ), crds[1] );
assertEquals(MCoordinate.create2dWithMeasure(1.5, 0.0, 1.5), crds[3]); assertEquals( MCoordinate.create2dWithMeasure( 2.0, 0.0, 2.0 ), crds[2] );
assertEquals( MCoordinate.create2dWithMeasure( 1.5, 0.0, 1.5 ), crds[3] );
result = partiallyConstantDecreasing.getCoordinatesBetween(3.5, 4.0);
assertEquals(1, result.length); result = partiallyConstantDecreasing.getCoordinatesBetween( 3.5, 4.0 );
crds = result[0].toCoordinateArray(); assertEquals( 1, result.length );
assertEquals(2, crds.length); crds = result[0].toCoordinateArray();
assertEquals(MCoordinate.create2dWithMeasure(5.0, 0.0, 4.0), crds[0]); assertEquals( 2, crds.length );
assertEquals(MCoordinate.create2dWithMeasure(4.5, 0.0, 3.5), crds[crds.length - 1]); assertEquals( MCoordinate.create2dWithMeasure( 5.0, 0.0, 4.0 ), crds[0] );
assertEquals( MCoordinate.create2dWithMeasure( 4.5, 0.0, 3.5 ), crds[crds.length - 1] );
result = partiallyConstantDecreasing.getCoordinatesBetween(3.5, 3.7);
assertEquals(1, result.length); result = partiallyConstantDecreasing.getCoordinatesBetween( 3.5, 3.7 );
crds = result[0].toCoordinateArray(); assertEquals( 1, result.length );
assertEquals(2, crds.length); crds = result[0].toCoordinateArray();
assertEquals(MCoordinate.create2dWithMeasure(4.7, 0.0, 3.7), crds[0]); assertEquals( 2, crds.length );
assertEquals(MCoordinate.create2dWithMeasure(4.5, 0.0, 3.5), crds[1]); assertEquals( MCoordinate.create2dWithMeasure( 4.7, 0.0, 3.7 ), crds[0] );
assertEquals( MCoordinate.create2dWithMeasure( 4.5, 0.0, 3.5 ), crds[1] );
result = partiallyConstantDecreasing.getCoordinatesBetween(0.5, 0.7);
assertEquals(1, result.length); result = partiallyConstantDecreasing.getCoordinatesBetween( 0.5, 0.7 );
crds = result[0].toCoordinateArray(); assertEquals( 1, result.length );
assertEquals(2, crds.length); crds = result[0].toCoordinateArray();
assertEquals(MCoordinate.create2dWithMeasure(0.7, 0.0, 0.7), crds[0]); assertEquals( 2, crds.length );
assertEquals(MCoordinate.create2dWithMeasure(0.5, 0.0, 0.5), crds[1]); assertEquals( MCoordinate.create2dWithMeasure( 0.7, 0.0, 0.7 ), crds[0] );
assertEquals( MCoordinate.create2dWithMeasure( 0.5, 0.0, 0.5 ), crds[1] );
result = partiallyConstantDecreasing.getCoordinatesBetween(-0.5, 0.7);
assertEquals(1, result.length); result = partiallyConstantDecreasing.getCoordinatesBetween( -0.5, 0.7 );
crds = result[0].toCoordinateArray(); assertEquals( 1, result.length );
assertEquals(2, crds.length); crds = result[0].toCoordinateArray();
assertEquals(MCoordinate.create2dWithMeasure(0.7, 0.0, 0.7), crds[0]); assertEquals( 2, crds.length );
assertEquals(MCoordinate.create2dWithMeasure(0.0, 0.0, 0.0), crds[1]); assertEquals( MCoordinate.create2dWithMeasure( 0.7, 0.0, 0.7 ), crds[0] );
assertEquals( MCoordinate.create2dWithMeasure( 0.0, 0.0, 0.0 ), crds[1] );
result = partiallyConstantDecreasing.getCoordinatesBetween(3.5, 4.7);
assertEquals(1, result.length); result = partiallyConstantDecreasing.getCoordinatesBetween( 3.5, 4.7 );
crds = result[0].toCoordinateArray(); assertEquals( 1, result.length );
assertEquals(2, crds.length); crds = result[0].toCoordinateArray();
assertEquals(MCoordinate.create2dWithMeasure(4.5, 0.0, 3.5), crds[1]); assertEquals( 2, crds.length );
assertEquals(MCoordinate.create2dWithMeasure(5.0, 0.0, 4.0), crds[0]); assertEquals( MCoordinate.create2dWithMeasure( 4.5, 0.0, 3.5 ), crds[1] );
} assertEquals( MCoordinate.create2dWithMeasure( 5.0, 0.0, 4.0 ), crds[0] );
}
@Test
public void test_measure_outside_monotone_increasing() throws MGeometryException { @Test
CoordinateSequence[] result; public void test_measure_outside_monotone_increasing() throws MGeometryException {
result = incrLine.getCoordinatesBetween(-1.5, -0.5); CoordinateSequence[] result;
assertEquals(1, result.length); result = incrLine.getCoordinatesBetween( -1.5, -0.5 );
assertEquals(0, result[0].size()); assertEquals( 1, result.length );
assertEquals( 0, result[0].size() );
result = incrLine.getCoordinatesBetween(10.0, 20.0);
assertEquals(1, result.length); result = incrLine.getCoordinatesBetween( 10.0, 20.0 );
assertEquals(0, result[0].size()); assertEquals( 1, result.length );
} assertEquals( 0, result[0].size() );
}
@Test
public void test_measure_outside_monotone_decreasing() throws MGeometryException { @Test
CoordinateSequence[] result; public void test_measure_outside_monotone_decreasing() throws MGeometryException {
result = decLine.getCoordinatesBetween(-1.5, -0.5); CoordinateSequence[] result;
assertEquals(1, result.length); result = decLine.getCoordinatesBetween( -1.5, -0.5 );
assertEquals(0, result[0].size()); assertEquals( 1, result.length );
assertEquals( 0, result[0].size() );
result = decLine.getCoordinatesBetween(10.0, 20.0);
assertEquals(1, result.length); result = decLine.getCoordinatesBetween( 10.0, 20.0 );
assertEquals(0, result[0].size()); assertEquals( 1, result.length );
} assertEquals( 0, result[0].size() );
}
@Test
public void test_measure_overlap_monotone_increasing() throws MGeometryException { @Test
CoordinateSequence[] result; public void test_measure_overlap_monotone_increasing() throws MGeometryException {
result = incrLine.getCoordinatesBetween(-0.5, 5); CoordinateSequence[] result;
assertEquals(1, result.length); result = incrLine.getCoordinatesBetween( -0.5, 5 );
Coordinate[] crds = result[0].toCoordinateArray(); assertEquals( 1, result.length );
assertEquals(5, crds.length); Coordinate[] crds = result[0].toCoordinateArray();
assertEquals(MCoordinate.create2dWithMeasure(0.0, 0.0, 0.0), crds[0]); assertEquals( 5, crds.length );
assertEquals(MCoordinate.create2dWithMeasure(4.0, 0.0, 4.0), crds[crds.length - 1]); assertEquals( MCoordinate.create2dWithMeasure( 0.0, 0.0, 0.0 ), crds[0] );
assertEquals( MCoordinate.create2dWithMeasure( 4.0, 0.0, 4.0 ), crds[crds.length - 1] );
result = incrLine.getCoordinatesBetween(0.5, 5);
assertEquals(1, result.length); result = incrLine.getCoordinatesBetween( 0.5, 5 );
crds = result[0].toCoordinateArray(); assertEquals( 1, result.length );
assertEquals(5, crds.length); crds = result[0].toCoordinateArray();
assertEquals(MCoordinate.create2dWithMeasure(0.5, 0.0, 0.5), crds[0]); assertEquals( 5, crds.length );
assertEquals(MCoordinate.create2dWithMeasure(4.0, 0.0, 4.0), crds[crds.length - 1]); assertEquals( MCoordinate.create2dWithMeasure( 0.5, 0.0, 0.5 ), crds[0] );
assertEquals( MCoordinate.create2dWithMeasure( 4.0, 0.0, 4.0 ), crds[crds.length - 1] );
result = incrLine.getCoordinatesBetween(-1.0, 2.5);
assertEquals(1, result.length); result = incrLine.getCoordinatesBetween( -1.0, 2.5 );
crds = result[0].toCoordinateArray(); assertEquals( 1, result.length );
assertEquals(4, crds.length); crds = result[0].toCoordinateArray();
assertEquals(MCoordinate.create2dWithMeasure(0.0, 0.0, 0.0), crds[0]); assertEquals( 4, crds.length );
assertEquals(MCoordinate.create2dWithMeasure(2.5, 0.0, 2.5), crds[crds.length - 1]); assertEquals( MCoordinate.create2dWithMeasure( 0.0, 0.0, 0.0 ), crds[0] );
assertEquals( MCoordinate.create2dWithMeasure( 2.5, 0.0, 2.5 ), crds[crds.length - 1] );
result = incrLine.getCoordinatesBetween(4.0, 5.5);
assertEquals(1, result.length); result = incrLine.getCoordinatesBetween( 4.0, 5.5 );
crds = result[0].toCoordinateArray(); assertEquals( 1, result.length );
assertEquals(1, crds.length); crds = result[0].toCoordinateArray();
assertEquals( 1, crds.length );
}
}
@Test
public void test_measure_overlap_monotone_decreasing() throws MGeometryException { @Test
CoordinateSequence[] result; public void test_measure_overlap_monotone_decreasing() throws MGeometryException {
result = decLine.getCoordinatesBetween(-0.5, 5); CoordinateSequence[] result;
assertEquals(1, result.length); result = decLine.getCoordinatesBetween( -0.5, 5 );
Coordinate[] crds = result[0].toCoordinateArray(); assertEquals( 1, result.length );
assertEquals(5, crds.length); Coordinate[] crds = result[0].toCoordinateArray();
assertEquals(MCoordinate.create2dWithMeasure(4.0, 0.0, 4.0), crds[0]); assertEquals( 5, crds.length );
assertEquals(MCoordinate.create2dWithMeasure(0.0, 0.0, 0.0), crds[crds.length - 1]); assertEquals( MCoordinate.create2dWithMeasure( 4.0, 0.0, 4.0 ), crds[0] );
assertEquals( MCoordinate.create2dWithMeasure( 0.0, 0.0, 0.0 ), crds[crds.length - 1] );
result = decLine.getCoordinatesBetween(0.5, 5);
assertEquals(1, result.length); result = decLine.getCoordinatesBetween( 0.5, 5 );
crds = result[0].toCoordinateArray(); assertEquals( 1, result.length );
assertEquals(5, crds.length); crds = result[0].toCoordinateArray();
assertEquals(MCoordinate.create2dWithMeasure(4.0, 0.0, 4.0), crds[0]); assertEquals( 5, crds.length );
assertEquals(MCoordinate.create2dWithMeasure(0.5, 0.0, 0.5), crds[crds.length - 1]); assertEquals( MCoordinate.create2dWithMeasure( 4.0, 0.0, 4.0 ), crds[0] );
assertEquals( MCoordinate.create2dWithMeasure( 0.5, 0.0, 0.5 ), crds[crds.length - 1] );
result = decLine.getCoordinatesBetween(-1.0, 2.5);
assertEquals(1, result.length); result = decLine.getCoordinatesBetween( -1.0, 2.5 );
crds = result[0].toCoordinateArray(); assertEquals( 1, result.length );
assertEquals(4, crds.length); crds = result[0].toCoordinateArray();
assertEquals(MCoordinate.create2dWithMeasure(2.5, 0.0, 2.5), crds[0]); assertEquals( 4, crds.length );
assertEquals(MCoordinate.create2dWithMeasure(0.0, 0.0, 0.0), crds[crds.length - 1]); assertEquals( MCoordinate.create2dWithMeasure( 2.5, 0.0, 2.5 ), crds[0] );
} assertEquals( MCoordinate.create2dWithMeasure( 0.0, 0.0, 0.0 ), crds[crds.length - 1] );
}
@Test
public void test_measure_inverse_monotone_increasing() throws MGeometryException { @Test
CoordinateSequence[] result; public void test_measure_inverse_monotone_increasing() throws MGeometryException {
result = incrLine.getCoordinatesBetween(3.5, 0.5); CoordinateSequence[] result;
assertEquals(1, result.length); result = incrLine.getCoordinatesBetween( 3.5, 0.5 );
Coordinate[] crds = result[0].toCoordinateArray(); assertEquals( 1, result.length );
assertEquals(5, crds.length); Coordinate[] crds = result[0].toCoordinateArray();
assertEquals(MCoordinate.create2dWithMeasure(0.5, 0.0, 0.5), crds[0]); assertEquals( 5, crds.length );
assertEquals(MCoordinate.create2dWithMeasure(3.5, 0.0, 3.5), crds[crds.length - 1]); assertEquals( MCoordinate.create2dWithMeasure( 0.5, 0.0, 0.5 ), crds[0] );
} assertEquals( MCoordinate.create2dWithMeasure( 3.5, 0.0, 3.5 ), crds[crds.length - 1] );
}
@Test
public void test_measure_inverse_monotone_decreasing() throws MGeometryException { @Test
CoordinateSequence[] result; public void test_measure_inverse_monotone_decreasing() throws MGeometryException {
result = decLine.getCoordinatesBetween(3.5, 0.5); CoordinateSequence[] result;
assertEquals(1, result.length); result = decLine.getCoordinatesBetween( 3.5, 0.5 );
Coordinate[] crds = result[0].toCoordinateArray(); assertEquals( 1, result.length );
assertEquals(5, crds.length); Coordinate[] crds = result[0].toCoordinateArray();
assertEquals(MCoordinate.create2dWithMeasure(3.5, 0.0, 3.5), crds[0]); assertEquals( 5, crds.length );
assertEquals(MCoordinate.create2dWithMeasure(0.5, 0.0, 0.5), crds[crds.length - 1]); assertEquals( MCoordinate.create2dWithMeasure( 3.5, 0.0, 3.5 ), crds[0] );
} assertEquals( MCoordinate.create2dWithMeasure( 0.5, 0.0, 0.5 ), crds[crds.length - 1] );
}
@Test
public void test_fail_on_non_monotone() throws MGeometryException { @Test
try { public void test_fail_on_non_monotone() throws MGeometryException {
nonMonotoneLine.getCoordinatesBetween(0.5, 10.0); try {
fail("Needs to throw an IllegalArgumentException on non-monotone linestrings."); nonMonotoneLine.getCoordinatesBetween( 0.5, 10.0 );
} catch (MGeometryException e) { fail( "Needs to throw an IllegalArgumentException on non-monotone linestrings." );
assertEquals(e.getType(), MGeometryException.OPERATION_REQUIRES_MONOTONE); }
} catch ( MGeometryException e ) {
} assertEquals( e.getType(), MGeometryException.OPERATION_REQUIRES_MONOTONE );
}
}
} }